前言
本章对应官方教程第4章,本章介绍如何为中间代码(LLVM IR)添加优化以及添加JIT编译器支持。
教程如下:
教你使用swift写编译器玩具(0)
教你使用swift写编译器玩具(1)
教你使用swift写编译器玩具(2)
教你使用swift写编译器玩具(3)
教你使用swift写编译器玩具(4)
教你使用swift写编译器玩具(5)
教你使用swift写编译器玩具(6)
教你使用swift写编译器玩具(7)
教你使用swift写编译器玩具(8)
仓库在这
开始
中间代码优化
我们都知道在编译的过程中有着中间代码优化这一步。我们想要中间代码能够去除无用以及重复计算的内容,所以这个时候我们需要使用中间代码优化器。
举一个例子,在没有优化之前,我们输入def test(x) (1+2+x)*(x+(1+2));获得的结果如下所示。
1 2 3 4 5 6 7 8 9 10 11
   | def test(x) (1+2+x)*(x+(1+2))
  Read function definition:
  define i64 @test(i64 %x) { entry:   %add = add i64 3, %x   %add1 = add i64 %x, 3   %mul = mul i64 %add, %add1   ret i64 %mul }
 
  | 
 
我们可以看出来其实add和add1是相同的值,完全没有必要算两次。所以经过优化之后长下面这样
1 2 3 4 5 6 7 8 9
   | def test(x) (1+2+x)*(x+(1+2)) Read function definition:
  define i64 @test(i64 %x) { entry:   %add = add i64 3, %x   %mul = mul i64 %add, %add   ret i64 %mul }
 
  | 
 
我们可以看出出来之前的两个add被优化成了一个。
那么我们该如何添加优化呢?LLVM为我们提供了PassManager。但是有趣的是在LLVMSwift中,PassManager被deprecated了。所以我们只需要使用更简单的PassPipeliner即可。
有多简单呢?简单到只需要添加两行代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
   | let passPipeliner = PassPipeliner(module: theModule)
      func lexerWithDefinition(_ lexer: Lexer) {         if let p = parseDefinition() {             if let f = p.codeGen() {               	             		passPipeliner.execute()                 print("Read function definition:")                 f.dump()             }         } else {             lexer.nextToken()         }     }
 
  | 
 
添加JIT支持
使用LLVMSwift中的JIT也十分简单。我们只需要在合适的地方调用即可。
首先我们定义全局变量JIT,并在main中初始化它。
1 2 3
   | var theJIT: JIT! let targetMachine = try! TargetMachine() theJIT = JIT(machine: targetMachine)
 
  | 
 
接着我们在lexerWithDefinition中把Module中的IR添加到JIT中。
1 2 3 4 5
   |       ... f.dump()       _ = try! theJIT.addLazilyCompiledIR(theModule) { (_) -> JIT.TargetAddress in           return JIT.TargetAddress()       }
 
  | 
 
在lexerWithTopLevelExpression中把继续把Module中的IR添加到JIT中。
1 2 3 4 5 6 7 8 9 10
   |         ... let handle = try theJIT.addEagerlyCompiledIR(theModule) { (name) -> JIT.TargetAddress in             return JIT.TargetAddress()         }         let addr = try theJIT.address(of: "__anon_expr")         typealias FnPr = @convention(c) () -> Int         let fn = unsafeBitCast(addr, to: FnPr.self)         print("Evaluated to \(fn()).")         try theJIT.removeModule(handle) initModule()
 
  | 
 
还记得之前parseTopLevelExpr中添加的默认函数名"__anon_expr"吗?在lexerWithTopLevelExpression新增代码的意思就是把顶级表达式包在一个名为"__anon_expr"且返回值为空的函数中进行调用。
但是目前我们还只能调用一次函数,调用第二次函数时我们就找不到这个函数了。所以这个时候我们需要有一个全局的表用来记录。
1 2 3 4 5 6 7 8 9 10 11 12 13
   | var functionProtos: [String: PrototypeAST] = [:]
  func getFunction(named name: String) -> Function? {     if let f = theModule.function(named: name) {         return f     } else {         let fi = functionProtos[name]         guard fi != nil else {             return nil         }         return fi?.codeGen()     } }
 
  | 
 
接着我们需要为CallExprAST和FunctionAST替换获取函数名的方式。
1 2 3 4 5 6 7 8
   |  let calleeF = getFunction(named: callee!)
  functionProtos[proto!.name!] = proto let theFunction = getFunction(named: proto!.name!) guard theFunction != nil else {   	return nil }
 
  | 
 
这样我们总是可以在当前Module中获得先前定义过的函数进行调用。
最后我们还需要更新一下lexerWithDefinition方法和lexerWithExtern方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
   |  ... f.dump() _ = try! theJIT.addLazilyCompiledIR(theModule) { (_) -> JIT.TargetAddress in 		return JIT.TargetAddress() } initModule()
 
  ... f.dump() functionProtos[p.name!] = p
  func initModule() {     theModule = Module(name: "main")     theModule.dataLayout = targetMachine.dataLayout }
 
  | 
 
测试
直接输入表达式。
1 2 3 4 5 6 7 8
   | 1+20 Read top-level expression:
  define i64 @__anon_expr() { entry:   ret i64 21 } Evaluated to 21.//输出
 
  | 
 
函数调用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
   | def testfunc(x y) x + y*2 Read function definition:
  define i64 @testfunc(i64 %x, i64 %y) { entry:   %mul = mul i64 %y, 2   %add = add i64 %x, %mul   ret i64 %add } testfunc(1, 2) Read top-level expression:
  define i64 @__anon_expr() { entry:   %call = call i64 @testfunc(i64 1, i64 2)   ret i64 %call } Evaluated to 5.//输出 testfunc(1, 3) Read top-level expression:
  define i64 @__anon_expr() { entry:   %call = call i64 @testfunc(i64 1, i64 3)   ret i64 %call } Evaluated to 7.//输出
 
  |