Swift编译器架构

Swift编译流程图

Swift编译器架构_第1张图片

  1. Swift Code : 开发者自己编写的代码
  2. Swift AST : 根据swiftc生成语法树
  3. Raw Swift IL : Swift特有的中间代码
  4. Canonical Swift IL : 更加简洁的中间代码版本
  5. LLVM IR : 编译器前端处理完后转交给LLVM生成后端中间代码
  6. Assembly : 后端对代码进行优化转变成汇编代码
  7. Executable : 汇编代码转换成可执行的二进制代码

swiftc介绍

swiftc存放在Xcode内部

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

swiftc基本操作

  • 生成语法树: swiftc -dump-ast main.swift
    Swift编译器架构_第2张图片
  • 生成最简洁的SIL代码: swiftc -emit-sil main.swift
    Swift编译器架构_第3张图片
  • 生成LLVM IR代码: swiftc -emit-ir main.swift -o mail.ll
  • 生成汇编代码: swiftc -emit-assembly main.swift -o main.s

官方介绍

  • Parsing: The parser is a simple, recursive-descent parser (implemented in lib/Parse) with an integrated, hand-coded lexer. The parser is responsible for generating an Abstract Syntax Tree (AST) without any semantic or type information, and emit warnings or errors for grammatical problems with the input source.

  • Semantic analysis: Semantic analysis (implemented in lib/Sema) is responsible for taking the parsed AST and transforming it into a well-formed, fully-type-checked form of the AST, emitting warnings or errors for semantic problems in the source code. Semantic analysis includes type inference and, on success, indicates that it is safe to generate code from the resulting, type-checked AST.

  • Clang importer: The Clang importer (implemented in lib/ClangImporter) imports Clang modules and maps the C or Objective-C APIs they export into their corresponding Swift APIs. The resulting imported ASTs can be referred to by semantic analysis.

  • SIL generation: The Swift Intermediate Language (SIL) is a high-level, Swift-specific intermediate language suitable for further analysis and optimization of Swift code. The SIL generation phase (implemented in lib/SILGen) lowers the type-checked AST into so-called “raw” SIL. The design of SIL is described in docs/SIL.rst.

  • SIL guaranteed transformations: The SIL guaranteed transformations (implemented in lib/SILOptimizer/Mandatory) perform additional dataflow diagnostics that affect the correctness of a program (such as a use of uninitialized variables). The end result of these transformations is “canonical” SIL.

  • SIL Optimizations: The SIL optimizations (implemented in lib/Analysis, lib/ARC, lib/LoopTransforms, and lib/Transforms) perform additional high-level, Swift-specific optimizations to the program, including (for example) Automatic Reference Counting optimizations, devirtualization, and generic specialization.

  • LLVM IR Generation: IR generation (implemented in lib/IRGen) lowers SIL to LLVM IR, at which point LLVM can continue to optimize it and generate machine code.

参考: https://swift.org/swift-compiler/#compiler-architecture

你可能感兴趣的:(Swift,iOS,swift,ios)