SlideShare a Scribd company logo
let swift(16)
Internals
LLVM, Type system, Swift Foundation
OSXDEV.orgj
Agenda
Swift Compiler
Swift Type System
Swift Type Internals
Swift Foundation
Summary
let swift(16)
Swift Compiler
LLVM, Clang, Swiftc
Swift internals
A LoNG Time AGo,
in a galaxy
far, far away...
LLVM
Low-Level Virtual Machine
An Infrastructure for Multi-stage Optimization
− by Chris Arthur Lattner @2002
Design and Implementation of a compiler infrastructure
− support a unique multi-stage optimization system
− support inter-procedural and profile-driven optimizations
LLVM virtual instruction (IR)
− with high-level type information
Sponsored by APPLE
Chris Lattner
The Father of LLVM
LLVM Compiler
GCC#4.2#
프론트엔드#
C"
Tree*SSA#
최적화기#
코드 생성기#C++"
Objec)ve+C"
실행파일"
GCC"4.2"
GCC#4.2#
프론트엔드#
C"
LLVM#
최적화기#
LLVM#
코드 생성기#
C++"
Objec)ve+C"
실행파일"
LLVM+GCC"4.2"
Clang#
프론트엔드#
C"
LLVM#
최적화기#
LLVM#
코드 생성기#
C++"
Objec)ve+C"
실행파일"
LLVM"
Swift internals
Swift Compiler
yp RVHES
− 9 RHMF DL MSH M RHR
− % < OD GD D
p
− d S MREN L % -: % DMD H
> : c
k ib p ib y AHM
.swift 기계코드
let swift(16)
Swift Type System
Duck Type vs. HM Type Inference
Objective-C Type System
Static Type + Duck Type System
− C-style static type
− Smalltalk-style duck type
Duck Type History
− a message to comp.lang.python Newsgroup (2000)
Don't check whether it IS-a duck: check whether it QUACKS-like-a
duck, WALKS-like-a duck, etc, etc, depending on exactly what subset
of duck-like behaviour you need to play your language-games with.
“
”
Swift Type System
Bi-directional type inference
Constraint-based type checker
− Based classical Hindley-Milner type system
− Include polymorphic types & function overloading
− Step : Generate ➔ Solve ➔ Solution Application
func foo(x: Double) -> Int { … }

var doubleValue : Double = 3.141592

var unknown = foo(doubleValue)

func bar<T>(x: T) -> T { return x }

var floatValue: Float = -bar(1.414)
“The Principal Type-Scheme of an Object in
Combinatory Logic” Hindley, J. Roger (1969)
− Describe what types an expression can have
− Present an algorithm actually computing a type.
Deductive System
First implemented as part of the system of ML.
Hindley-Milner Type System
A, A ➔ B
B
(rule)
Hindley-Milner Type System
Expression
e = x
| e1 e2
| 𝞴x . e
| let x=e1 in e2
Types
mono 𝞃 = 𝝰
| D𝞃…𝞃
poly 𝞂 = 𝞃
| ∀𝝰.𝞂
variable
application
abstraction
variable
application
quantifier
Syntax
Context 𝛤 = 𝛜
| 𝛤, x : 𝝰
Typing = 𝛤 ⊢e : 𝞂
Hindley-Milner Algorithm W
[Var]
[App]
[Abs]
[Let]
Type Checker - Constraints
0PT HS x
TAS OD r
NMUD RHNM r q DPT HS RTAS OD
NMRS T SHNM s r q
DLAD c% h
NMEN L M D p
GD DC RS R q
-OO H A D ETM SHNM d
UD N C AHMCHMF y
RR
NMITMSHNM /HRITM SHNM a i p i
Constraint Solving
Take a given set of constraints
Determine the most specific type binding for each of the type
variables
The Design of the solver
− Simplification : Relational, Member constraints
− Strategies : solver scope, overload selection
− Comparing solutions : choose solution with smaller scores
“more specific” type
the super-type of overload binds
Swift internals
let swift(16)
Swift Type Internals
class, enumeration, struct, protocol
Native class type
class NativePen {
let id = 512
var sequence = 1024
}
// class.NativePen.__deallocating_deinit
@_TFC5class9NativePenD : $@convention(method) (@owned NativePen) -> () {
%0 : $NativePen, let, name "self", argno 1
%3 = class.NativePen.deinit(%0)
%4 = unchecked_ref_cast(%3) // $Builtin.NativeObject to $NativePen
dealloc_ref(%4)
}
// class.NativePen.deinit
@_TFC5class9NativePend : $@convention(method) (@guaranteed NativePen) -> @owned
Builtin.NativeObject {
%0 : $NativePen, let, name "self", argno 1
%2 = unchecked_ref_cast(%0) // $NativePen to $Builtin.NativeObject
return %2 // $Builtin.NativeObject
}
deinit
Native class type
// class.NativePen.init () -> class.NativePen
@_TFC5class9NativePencfT_S0_ : $@convention(method) (@owned NativePen) -> @owned
NativePen {
%0 : $NativePen, let, name "self"
%2 = mark_uninitialized([rootself], %0)
%4 = metatype(Int.Type)
%5 = integer_literal($Builtin.Int2048, 512)
%6 = Swift.Int.init(%5, %4)
%7 = ref_element_addr(%2 : $NativePen, #NativePen.id)
assign(%6 to %7)
%10 = metatype(Int.Type)
%11 = integer_literal($Builtin.Int2048, 1024)
%12 = Swift.Int.init(%11, %10)
%13 = ref_element_addr(%2 : $NativePen, #NativePen.sequence)
assign (%12 to %13)
return %2 // $NativePen
}
// class.NativePen.__allocating_init () -> class.NativePen
@_TFC5class9NativePenCfT_S0_ : $@convention(thin) (@thick NativePen.Type) -> @owned
NativePen {
%1 = alloc_ref($NativePen)
%3 = class.NativePen.init(%1)
return %3 : $NativePen
}
init
enumeration type
_ p r q
− _l u q p
RG A D O NSN N
0PT S A D O NSN N
public protocol Hashable : Equatable {
var hashValue: Int { get }
}
public protocol Equatable {
@warn_unused_result
func == (lhs: Self, rhs: Self) -> Bool
}
enum type example
enum PenModels {
case BallPen
case NamePen
}
// enum.PenModels.hashValue.getter : Swift.Int
@_TFO4enum9PenModelsg9hashValueSi : $@convention(method) (PenModels) -> Int {
%2 = alloc_box($Int, var, name "index")
%3 = mark_uninitialized([var] %2#1 : $*Int)
switch_enum %0 : $PenModels,
case #PenModels.BallPen!enumelt: bb1,
case #PenModels.NamePen!enumelt: bb2
bb1:
%6 = metatype($@thin Int.Type)
%7 = integer_literal($Builtin.Int2048, 0)
%8 = Swift.Int.init(%7, %6) // (Builtin.Int2048, @thin Int.Type) -> Int
assign(%8 to %3)
br bb3
bb2:
%12 = metatype($@thin Int.Type)
%13 = integer_literal($Builtin.Int2048, 1)
%14 = Swift.Int.init(%13, %12) // (Builtin.Int2048, @thin Int.Type) -> Int
assign(%14 to %3)
br bb3
bb3:
%17 = load(%3 : $*Int)
%19 = Swift.Int.hashValue.getter(%17) // $@convention(method) (Int) -> Int
strong_release(%2#0) // $@box Int
return %19
}
getter
enum type example
// protocol witness for static Swift.Equatable.== infix (A, A) -> Swift.Bool
@_TTWO4enum9PenModelss9EquatableS_ZFS1_oi2eefTxx_Sb :
$@convention(witness_method) (@in PenModels, @in PenModels, @thick
PenModels.Type) -> Bool {
%3 = load(%0 : $*PenModels)
%4 = load(%1 : $*PenModels)
%6 = enum.== infix(%3, %4)
return %6 // $Bool
}
// protocol witness for Swift.Hashable.hashValue.getter : Swift.Int
@_TTWO4enum9PenModelss8HashableS_FS1_g9hashValueSi :
$@convention(witness_method) (@in_guaranteed PenModels) -> Int {
%1 = alloc_stack($PenModels)
copy_addr(%0 to [initialization] %1 : $*PenModels)
%3 = load(%1 : $*PenModels)
%5 = enum.PenModels.hashValue.getter(%3)
dealloc_stack(%1 : $*PenModels)
return %5 // $Int
}
sil_witness_table PenModels: Equatable module enum {
method #Equatable."=="!1:
@_TTWO4enum9PenModelss9EquatableS_ZFS1_oi2eefTxx_Sb
}
sil_witness_table PenModels: Hashable module enum {
base_protocol Equatable: PenModels: Equatable module enum
method #Hashable.hashValue!getter.1:
@_TTWO4enum9PenModelss8HashableS_FS1_g9hashValueSi
}
Protocol Witness Table
struct type
i wp p
− MS - % DS% /H SHNM t )(
f
i HED D c
− r
n g b r
− DS HM D D RD
struct type - let example
struct Car {
let model = "apple"
}
// struct.Car.init () -> struct.Car
@_TFV6struct3CarCfT_S0_ : $@convention(thin) (@thin Car.Type) -> @owned Car {
%1 = alloc_box($Car, var, name "self", argno 1)
%2 = mark_uninitialized([rootself] %1#1 : $*Car)
%4 = metatype($@thin String.Type)
%5 = string_literal(utf8 "apple")
%6 = integer_literal($Builtin.Word, 5)
%7 = integer_literal($Builtin.Int1, -1)
%8 = Swift.String.init(%5, %6, %7, %4)
%9 = struct_element_addr(%2 : $*Car, #Car.model)
assign(%8 to %9 : $*String)
%11 = load(%2 : $*Car)
retain_value(%11 : $Car)
strong_release(%1#0 : $@box Car)
return %11
}
// struct.Car.model.getter : Swift.String
@_TFV6struct3Carg5modelSS : $@convention(method) (@guaranteed Car) -> @owned String {
%2 = struct_extract(%0 : $Car, #Car.model)
retain_value(%2 : $String)
return %2
}
struct type - var example
struct Car {
var driver = "tim"
}
// struct.Car.init (driver : Swift.String) -> struct.Car
@_TFV6struct3CarCfT6driverSS_S0_ : $@convention(thin) (@owned String, @thin Car.Type)
-> @owned Car {
%2 = struct.$Car(%0 : $String)
return %2
}
// struct.Car.init () -> struct.Car
@_TFV6struct3CarCfT_S0_ : $@convention(thin) (@thin Car.Type) -> @owned Car {
%1 = alloc_box($Car, var, name "self", argno 1)
%2 = mark_uninitialized([rootself] %1#1 : $*Car)
%4 = metatype($@thin String.Type)
%5 = string_literal(utf8 "tim")
%6 = integer_literal($Builtin.Word, 3)
%7 = integer_literal($Builtin.Int1, -1)
%8 = Swift.String.init(%5, %6, %7, %4)
%9 = struct_element_addr(%2 : $*Car, #Car.driver)
assign(%8 to %9 : $*String)
%11 = load(%2 : $*Car)
retain_value(%11 : $Car)
strong_release(%1#0 : $@box Car)
return %11
}
init
struct type - var example
// struct.Car.driver.getter : Swift.String
@_TFV6struct3Carg6driverSS : $@convention(method) (@guaranteed Car) -> @owned String {
%2 = struct_extract(%0 : $Car, #Car.driver)
retain_value(%2 : $String)
return %2
}
// struct.Car.driver.setter : Swift.String
@_TFV6struct3Cars6driverSS : $@convention(method) (@owned String, @inout Car) -> () {
%3 = alloc_box($Car, var, name "self", argno 2)
copy_addr(%1 to [initialization] %3#1 : $*Car)
retain_value(%0 : $String)
%6 = struct_element_addr(%3#1 : $*Car, #Car.driver)
assign(%0 to %6 : $*String)
copy_addr(%3#1 to %1 : $*Car)
strong_release(%3#0 : $@box Car)
release_value(%0 : $String)
%11 = tuple ()
return %11
}
// struct.Car.driver.materializeForSet : Swift.String
@_TFV6struct3Carm6driverSS : $@convention(method) (Builtin.RawPointer, @inout
Builtin.UnsafeValueBuffer, @inout Car) -> (Builtin.RawPointer, Optional<@convention(thin)
(Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Car, @thick Car.Type) -> ()>) {
%3 = struct_element_addr(%2 : $*Car, #Car.driver)
%4 = address_to_pointer(%3 : $*String to $Builtin.RawPointer)
%5 = enum $Optional<@convention(thin) (Builtin.RawPointer, inout
Builtin.UnsafeValueBuffer, inout Car, @thick Car.Type) -> ()>, #Optional.None!enumelt
%6 = tuple (%4 : $Builtin.RawPointer, %5 : $Optional<@convention(thin)
(Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Car, @thick Car.Type) -> ()>)
return %6 : $(Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout
Builtin.UnsafeValueBuffer, inout Car, @thick Car.Type) -> ()>)
}
getter/setter
let swift(16)
Swift 3 Foundation
Foundation SDK
source : WWDC 2016. Session207. Whats new in foundation for swift
파일 구분 관련 타입들 설명
AffineTransform OTA H RS T S -EEHMD< MREN L -EEHMD< MREN L v p f
CharacterSet
HMSD M EHM RR
VHES G SD DS
G SD DS d TS A D G SD DS p n
Data HMSD M EHM RR VHES / S / S TS A D/ S p n
Date OTA H RS T S / SD <HLD MSD U SHLD m b p
DateComponents OTA H RS T S / SD NLONMDMSR / SD NLONMDMSR p m
DateInterval OTA H RS T S / SD MSD U / SD MSD U p m i o
Decimal D SDMRHNM /D HL
t % e % /D HL TLAD
a p
FileManager OTA H RR H D M FD H D M FD
IndexPath OTA H RS T S MCD 9 SG MCD 9 SG v p o f
IndexSet OTA H RS T S MCD DS MCD DS v p o f
Measurement
OTA H RS T S D RT DLDMS+ MHS< OD
MHS,
D RT DLDMS v p o f
Notification OTA H RS T S NSHEH SHNM NSHEH SHNM v p o f
NSError D SDMRHNM 0 N 0 N 9 NSN N 0 N o u
URL OTA H RS T S : : p f
URLComponents OTA H RS T S : NLONMDMSR : NLONMDMSR p f
URLRequest OTA H RS T S : :DPTDRS TS A D : :DPTDRS p f
Summary
Swift Compiler
− LLVM + Chris Lattner, Talyer swift
Type System
− HM Type System + W Algorithm
Type Internals
− class, enumeration, struct, protocol Types
Swift Foundation
− IndexPath, IndexSet, Measurement, Notification
References
llvm.org
swift.org
https://github.com/apple/swift-evolution
https://github.com/apple/swift/tree/swift-3.0-preview-2-branch
https://en.wikipedia.org/wiki/Duck_typing
https://en.wikipedia.org/wiki/
Hindley%E2%80%93Milner_type_system
http://akgupta.ca/blog/2013/05/14/so-you-still-dont-understand-
hindley-milner/
https://developer.apple.com/videos/wwdc2016/
let swift(16)

More Related Content

PDF
LetSwift RxSwift 시작하기
PDF
Swift 함수 커링 사용하기
PDF
RxSwift 활용하기 - Let'Swift 2017
PDF
Letswift Swift 3.0
PPTX
Type Driven Development with TypeScript
PPTX
JavaScript Basics and Trends
PDF
Functional Algebra: Monoids Applied
PDF
Being functional in PHP (DPC 2016)
LetSwift RxSwift 시작하기
Swift 함수 커링 사용하기
RxSwift 활용하기 - Let'Swift 2017
Letswift Swift 3.0
Type Driven Development with TypeScript
JavaScript Basics and Trends
Functional Algebra: Monoids Applied
Being functional in PHP (DPC 2016)

What's hot (20)

PPT
JavaScript Tutorial
PPTX
Hardened JavaScript
PDF
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
PDF
ES6 - Next Generation Javascript
PDF
Swift 2
PDF
Funcitonal Swift Conference: The Functional Way
PDF
Java Cheat Sheet
PDF
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
PDF
Developer Experience i TypeScript. Najbardziej ikoniczne duo
PDF
Anonymous functions in JavaScript
PPTX
Category theory, Monads, and Duality in the world of (BIG) Data
PDF
ECMAScript 6
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
PDF
响应式编程及框架
PDF
JavaScript 101 - Class 1
PDF
Explaining ES6: JavaScript History and What is to Come
PPTX
5 Tips for Better JavaScript
KEY
Why Learn Python?
PDF
Nikita Popov "What’s new in PHP 8.0?"
PDF
Proxies are Awesome!
JavaScript Tutorial
Hardened JavaScript
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
ES6 - Next Generation Javascript
Swift 2
Funcitonal Swift Conference: The Functional Way
Java Cheat Sheet
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Anonymous functions in JavaScript
Category theory, Monads, and Duality in the world of (BIG) Data
ECMAScript 6
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
响应式编程及框架
JavaScript 101 - Class 1
Explaining ES6: JavaScript History and What is to Come
5 Tips for Better JavaScript
Why Learn Python?
Nikita Popov "What’s new in PHP 8.0?"
Proxies are Awesome!
Ad

Viewers also liked (9)

PDF
Let'Swift 17 키노트
PDF
프알못의 Realm 사용기
PDF
Swift package manager
PDF
Swift and Xcode8
PDF
Do swift: Swift 무작정 해보기
PDF
안드로이드 개발자를 위한 스위프트
PDF
Swift server-side-let swift2016
PDF
Protocol Oriented Programming in Swift
PDF
스위프트 성능 이해하기
Let'Swift 17 키노트
프알못의 Realm 사용기
Swift package manager
Swift and Xcode8
Do swift: Swift 무작정 해보기
안드로이드 개발자를 위한 스위프트
Swift server-side-let swift2016
Protocol Oriented Programming in Swift
스위프트 성능 이해하기
Ad

Similar to Swift internals (20)

PDF
The Swift Compiler and Standard Library
PDF
dotSwift 2016 : Beyond Crusty - Real-World Protocols
PDF
Swift core
PPTX
Protocol-Oriented Programming in Swift
PDF
Swift Programming
PDF
Swift Introduction
PDF
掀起 Swift 的面紗
PDF
Protocol-Oriented Programming in Swift
PDF
SIL for the first time
PDF
Introduction to Swift
PDF
SIL for First Time Learners
PDF
Cocoaheads Meetup / Alex Zimin / Swift magic
PDF
Александр Зимин (Alexander Zimin) — Магия Swift
PDF
Swift Type System
PDF
From android/java to swift (3)
PDF
Swift, swiftly
PDF
Quick swift tour
PDF
Denis Lebedev, Swift
PDF
Generics programming in Swift
PDF
Denis Lebedev. Non functional swift.
The Swift Compiler and Standard Library
dotSwift 2016 : Beyond Crusty - Real-World Protocols
Swift core
Protocol-Oriented Programming in Swift
Swift Programming
Swift Introduction
掀起 Swift 的面紗
Protocol-Oriented Programming in Swift
SIL for the first time
Introduction to Swift
SIL for First Time Learners
Cocoaheads Meetup / Alex Zimin / Swift magic
Александр Зимин (Alexander Zimin) — Магия Swift
Swift Type System
From android/java to swift (3)
Swift, swiftly
Quick swift tour
Denis Lebedev, Swift
Generics programming in Swift
Denis Lebedev. Non functional swift.

More from Jung Kim (14)

PDF
Let'Swift 2019 키노트
PDF
Letswift19-clean-architecture
PDF
Letswift18 워크숍#1 스위프트 클린코드와 코드리뷰
PDF
Letswift18 키노트
PDF
개발자를 위한 넓고 얕은 지식
PDF
스위프트를 여행하는 히치하이커를 위한 스타일 안내
PDF
Swift와 Objective-C를 함께 쓰는 방법
PDF
마스터즈 오픈세미나 - 소프트웨어가좋아요
PDF
소프트웨어로 미래를 준비하는 사람들
PDF
Developerway-2016-camp
PDF
Swift2 smalltalk osxdev
PDF
모바일 트렌드와 iOS
PDF
개발자로 살아가는 길, 그리고 NEXT
PDF
차세대컴파일러, VM의미래: 애플 오픈소스 LLVM
Let'Swift 2019 키노트
Letswift19-clean-architecture
Letswift18 워크숍#1 스위프트 클린코드와 코드리뷰
Letswift18 키노트
개발자를 위한 넓고 얕은 지식
스위프트를 여행하는 히치하이커를 위한 스타일 안내
Swift와 Objective-C를 함께 쓰는 방법
마스터즈 오픈세미나 - 소프트웨어가좋아요
소프트웨어로 미래를 준비하는 사람들
Developerway-2016-camp
Swift2 smalltalk osxdev
모바일 트렌드와 iOS
개발자로 살아가는 길, 그리고 NEXT
차세대컴파일러, VM의미래: 애플 오픈소스 LLVM

Recently uploaded (20)

PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
CCleaner Pro 6.38.11537 Crack Final Latest Version 2025
PDF
medical staffing services at VALiNTRY
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Tally Prime Crack Download New Version 5.1 [2025] (License Key Free
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
Transform Your Business with a Software ERP System
DOCX
Greta — No-Code AI for Building Full-Stack Web & Mobile Apps
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PPTX
Why Generative AI is the Future of Content, Code & Creativity?
PPTX
Advanced SystemCare Ultimate Crack + Portable (2025)
PPTX
Reimagine Home Health with the Power of Agentic AI​
PPTX
Monitoring Stack: Grafana, Loki & Promtail
PDF
AutoCAD Professional Crack 2025 With License Key
PDF
Designing Intelligence for the Shop Floor.pdf
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Design an Analysis of Algorithms II-SECS-1021-03
wealthsignaloriginal-com-DS-text-... (1).pdf
CCleaner Pro 6.38.11537 Crack Final Latest Version 2025
medical staffing services at VALiNTRY
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Tally Prime Crack Download New Version 5.1 [2025] (License Key Free
Design an Analysis of Algorithms I-SECS-1021-03
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
How to Choose the Right IT Partner for Your Business in Malaysia
Transform Your Business with a Software ERP System
Greta — No-Code AI for Building Full-Stack Web & Mobile Apps
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Why Generative AI is the Future of Content, Code & Creativity?
Advanced SystemCare Ultimate Crack + Portable (2025)
Reimagine Home Health with the Power of Agentic AI​
Monitoring Stack: Grafana, Loki & Promtail
AutoCAD Professional Crack 2025 With License Key
Designing Intelligence for the Shop Floor.pdf
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Design an Analysis of Algorithms II-SECS-1021-03

Swift internals

  • 1. let swift(16) Internals LLVM, Type system, Swift Foundation OSXDEV.orgj
  • 2. Agenda Swift Compiler Swift Type System Swift Type Internals Swift Foundation Summary
  • 5. A LoNG Time AGo, in a galaxy far, far away...
  • 6. LLVM Low-Level Virtual Machine An Infrastructure for Multi-stage Optimization − by Chris Arthur Lattner @2002 Design and Implementation of a compiler infrastructure − support a unique multi-stage optimization system − support inter-procedural and profile-driven optimizations LLVM virtual instruction (IR) − with high-level type information Sponsored by APPLE
  • 8. LLVM Compiler GCC#4.2# 프론트엔드# C" Tree*SSA# 최적화기# 코드 생성기#C++" Objec)ve+C" 실행파일" GCC"4.2" GCC#4.2# 프론트엔드# C" LLVM# 최적화기# LLVM# 코드 생성기# C++" Objec)ve+C" 실행파일" LLVM+GCC"4.2" Clang# 프론트엔드# C" LLVM# 최적화기# LLVM# 코드 생성기# C++" Objec)ve+C" 실행파일" LLVM"
  • 10. Swift Compiler yp RVHES − 9 RHMF DL MSH M RHR − % < OD GD D p − d S MREN L % -: % DMD H > : c k ib p ib y AHM .swift 기계코드
  • 11. let swift(16) Swift Type System Duck Type vs. HM Type Inference
  • 12. Objective-C Type System Static Type + Duck Type System − C-style static type − Smalltalk-style duck type Duck Type History − a message to comp.lang.python Newsgroup (2000) Don't check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need to play your language-games with. “ ”
  • 13. Swift Type System Bi-directional type inference Constraint-based type checker − Based classical Hindley-Milner type system − Include polymorphic types & function overloading − Step : Generate ➔ Solve ➔ Solution Application func foo(x: Double) -> Int { … } var doubleValue : Double = 3.141592 var unknown = foo(doubleValue) func bar<T>(x: T) -> T { return x } var floatValue: Float = -bar(1.414)
  • 14. “The Principal Type-Scheme of an Object in Combinatory Logic” Hindley, J. Roger (1969) − Describe what types an expression can have − Present an algorithm actually computing a type. Deductive System First implemented as part of the system of ML. Hindley-Milner Type System A, A ➔ B B (rule)
  • 15. Hindley-Milner Type System Expression e = x | e1 e2 | 𝞴x . e | let x=e1 in e2 Types mono 𝞃 = 𝝰 | D𝞃…𝞃 poly 𝞂 = 𝞃 | ∀𝝰.𝞂 variable application abstraction variable application quantifier Syntax Context 𝛤 = 𝛜 | 𝛤, x : 𝝰 Typing = 𝛤 ⊢e : 𝞂
  • 17. Type Checker - Constraints 0PT HS x TAS OD r NMUD RHNM r q DPT HS RTAS OD NMRS T SHNM s r q DLAD c% h NMEN L M D p GD DC RS R q -OO H A D ETM SHNM d UD N C AHMCHMF y RR NMITMSHNM /HRITM SHNM a i p i
  • 18. Constraint Solving Take a given set of constraints Determine the most specific type binding for each of the type variables The Design of the solver − Simplification : Relational, Member constraints − Strategies : solver scope, overload selection − Comparing solutions : choose solution with smaller scores “more specific” type the super-type of overload binds
  • 20. let swift(16) Swift Type Internals class, enumeration, struct, protocol
  • 21. Native class type class NativePen { let id = 512 var sequence = 1024 } // class.NativePen.__deallocating_deinit @_TFC5class9NativePenD : $@convention(method) (@owned NativePen) -> () { %0 : $NativePen, let, name "self", argno 1 %3 = class.NativePen.deinit(%0) %4 = unchecked_ref_cast(%3) // $Builtin.NativeObject to $NativePen dealloc_ref(%4) } // class.NativePen.deinit @_TFC5class9NativePend : $@convention(method) (@guaranteed NativePen) -> @owned Builtin.NativeObject { %0 : $NativePen, let, name "self", argno 1 %2 = unchecked_ref_cast(%0) // $NativePen to $Builtin.NativeObject return %2 // $Builtin.NativeObject } deinit
  • 22. Native class type // class.NativePen.init () -> class.NativePen @_TFC5class9NativePencfT_S0_ : $@convention(method) (@owned NativePen) -> @owned NativePen { %0 : $NativePen, let, name "self" %2 = mark_uninitialized([rootself], %0) %4 = metatype(Int.Type) %5 = integer_literal($Builtin.Int2048, 512) %6 = Swift.Int.init(%5, %4) %7 = ref_element_addr(%2 : $NativePen, #NativePen.id) assign(%6 to %7) %10 = metatype(Int.Type) %11 = integer_literal($Builtin.Int2048, 1024) %12 = Swift.Int.init(%11, %10) %13 = ref_element_addr(%2 : $NativePen, #NativePen.sequence) assign (%12 to %13) return %2 // $NativePen } // class.NativePen.__allocating_init () -> class.NativePen @_TFC5class9NativePenCfT_S0_ : $@convention(thin) (@thick NativePen.Type) -> @owned NativePen { %1 = alloc_ref($NativePen) %3 = class.NativePen.init(%1) return %3 : $NativePen } init
  • 23. enumeration type _ p r q − _l u q p RG A D O NSN N 0PT S A D O NSN N public protocol Hashable : Equatable { var hashValue: Int { get } } public protocol Equatable { @warn_unused_result func == (lhs: Self, rhs: Self) -> Bool }
  • 24. enum type example enum PenModels { case BallPen case NamePen } // enum.PenModels.hashValue.getter : Swift.Int @_TFO4enum9PenModelsg9hashValueSi : $@convention(method) (PenModels) -> Int { %2 = alloc_box($Int, var, name "index") %3 = mark_uninitialized([var] %2#1 : $*Int) switch_enum %0 : $PenModels, case #PenModels.BallPen!enumelt: bb1, case #PenModels.NamePen!enumelt: bb2 bb1: %6 = metatype($@thin Int.Type) %7 = integer_literal($Builtin.Int2048, 0) %8 = Swift.Int.init(%7, %6) // (Builtin.Int2048, @thin Int.Type) -> Int assign(%8 to %3) br bb3 bb2: %12 = metatype($@thin Int.Type) %13 = integer_literal($Builtin.Int2048, 1) %14 = Swift.Int.init(%13, %12) // (Builtin.Int2048, @thin Int.Type) -> Int assign(%14 to %3) br bb3 bb3: %17 = load(%3 : $*Int) %19 = Swift.Int.hashValue.getter(%17) // $@convention(method) (Int) -> Int strong_release(%2#0) // $@box Int return %19 } getter
  • 25. enum type example // protocol witness for static Swift.Equatable.== infix (A, A) -> Swift.Bool @_TTWO4enum9PenModelss9EquatableS_ZFS1_oi2eefTxx_Sb : $@convention(witness_method) (@in PenModels, @in PenModels, @thick PenModels.Type) -> Bool { %3 = load(%0 : $*PenModels) %4 = load(%1 : $*PenModels) %6 = enum.== infix(%3, %4) return %6 // $Bool } // protocol witness for Swift.Hashable.hashValue.getter : Swift.Int @_TTWO4enum9PenModelss8HashableS_FS1_g9hashValueSi : $@convention(witness_method) (@in_guaranteed PenModels) -> Int { %1 = alloc_stack($PenModels) copy_addr(%0 to [initialization] %1 : $*PenModels) %3 = load(%1 : $*PenModels) %5 = enum.PenModels.hashValue.getter(%3) dealloc_stack(%1 : $*PenModels) return %5 // $Int } sil_witness_table PenModels: Equatable module enum { method #Equatable."=="!1: @_TTWO4enum9PenModelss9EquatableS_ZFS1_oi2eefTxx_Sb } sil_witness_table PenModels: Hashable module enum { base_protocol Equatable: PenModels: Equatable module enum method #Hashable.hashValue!getter.1: @_TTWO4enum9PenModelss8HashableS_FS1_g9hashValueSi } Protocol Witness Table
  • 26. struct type i wp p − MS - % DS% /H SHNM t )( f i HED D c − r n g b r − DS HM D D RD
  • 27. struct type - let example struct Car { let model = "apple" } // struct.Car.init () -> struct.Car @_TFV6struct3CarCfT_S0_ : $@convention(thin) (@thin Car.Type) -> @owned Car { %1 = alloc_box($Car, var, name "self", argno 1) %2 = mark_uninitialized([rootself] %1#1 : $*Car) %4 = metatype($@thin String.Type) %5 = string_literal(utf8 "apple") %6 = integer_literal($Builtin.Word, 5) %7 = integer_literal($Builtin.Int1, -1) %8 = Swift.String.init(%5, %6, %7, %4) %9 = struct_element_addr(%2 : $*Car, #Car.model) assign(%8 to %9 : $*String) %11 = load(%2 : $*Car) retain_value(%11 : $Car) strong_release(%1#0 : $@box Car) return %11 } // struct.Car.model.getter : Swift.String @_TFV6struct3Carg5modelSS : $@convention(method) (@guaranteed Car) -> @owned String { %2 = struct_extract(%0 : $Car, #Car.model) retain_value(%2 : $String) return %2 }
  • 28. struct type - var example struct Car { var driver = "tim" } // struct.Car.init (driver : Swift.String) -> struct.Car @_TFV6struct3CarCfT6driverSS_S0_ : $@convention(thin) (@owned String, @thin Car.Type) -> @owned Car { %2 = struct.$Car(%0 : $String) return %2 } // struct.Car.init () -> struct.Car @_TFV6struct3CarCfT_S0_ : $@convention(thin) (@thin Car.Type) -> @owned Car { %1 = alloc_box($Car, var, name "self", argno 1) %2 = mark_uninitialized([rootself] %1#1 : $*Car) %4 = metatype($@thin String.Type) %5 = string_literal(utf8 "tim") %6 = integer_literal($Builtin.Word, 3) %7 = integer_literal($Builtin.Int1, -1) %8 = Swift.String.init(%5, %6, %7, %4) %9 = struct_element_addr(%2 : $*Car, #Car.driver) assign(%8 to %9 : $*String) %11 = load(%2 : $*Car) retain_value(%11 : $Car) strong_release(%1#0 : $@box Car) return %11 } init
  • 29. struct type - var example // struct.Car.driver.getter : Swift.String @_TFV6struct3Carg6driverSS : $@convention(method) (@guaranteed Car) -> @owned String { %2 = struct_extract(%0 : $Car, #Car.driver) retain_value(%2 : $String) return %2 } // struct.Car.driver.setter : Swift.String @_TFV6struct3Cars6driverSS : $@convention(method) (@owned String, @inout Car) -> () { %3 = alloc_box($Car, var, name "self", argno 2) copy_addr(%1 to [initialization] %3#1 : $*Car) retain_value(%0 : $String) %6 = struct_element_addr(%3#1 : $*Car, #Car.driver) assign(%0 to %6 : $*String) copy_addr(%3#1 to %1 : $*Car) strong_release(%3#0 : $@box Car) release_value(%0 : $String) %11 = tuple () return %11 } // struct.Car.driver.materializeForSet : Swift.String @_TFV6struct3Carm6driverSS : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Car) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Car, @thick Car.Type) -> ()>) { %3 = struct_element_addr(%2 : $*Car, #Car.driver) %4 = address_to_pointer(%3 : $*String to $Builtin.RawPointer) %5 = enum $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Car, @thick Car.Type) -> ()>, #Optional.None!enumelt %6 = tuple (%4 : $Builtin.RawPointer, %5 : $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Car, @thick Car.Type) -> ()>) return %6 : $(Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Car, @thick Car.Type) -> ()>) } getter/setter
  • 30. let swift(16) Swift 3 Foundation
  • 31. Foundation SDK source : WWDC 2016. Session207. Whats new in foundation for swift
  • 32. 파일 구분 관련 타입들 설명 AffineTransform OTA H RS T S -EEHMD< MREN L -EEHMD< MREN L v p f CharacterSet HMSD M EHM RR VHES G SD DS G SD DS d TS A D G SD DS p n Data HMSD M EHM RR VHES / S / S TS A D/ S p n Date OTA H RS T S / SD <HLD MSD U SHLD m b p DateComponents OTA H RS T S / SD NLONMDMSR / SD NLONMDMSR p m DateInterval OTA H RS T S / SD MSD U / SD MSD U p m i o Decimal D SDMRHNM /D HL t % e % /D HL TLAD a p FileManager OTA H RR H D M FD H D M FD IndexPath OTA H RS T S MCD 9 SG MCD 9 SG v p o f IndexSet OTA H RS T S MCD DS MCD DS v p o f Measurement OTA H RS T S D RT DLDMS+ MHS< OD MHS, D RT DLDMS v p o f Notification OTA H RS T S NSHEH SHNM NSHEH SHNM v p o f NSError D SDMRHNM 0 N 0 N 9 NSN N 0 N o u URL OTA H RS T S : : p f URLComponents OTA H RS T S : NLONMDMSR : NLONMDMSR p f URLRequest OTA H RS T S : :DPTDRS TS A D : :DPTDRS p f
  • 33. Summary Swift Compiler − LLVM + Chris Lattner, Talyer swift Type System − HM Type System + W Algorithm Type Internals − class, enumeration, struct, protocol Types Swift Foundation − IndexPath, IndexSet, Measurement, Notification