教你使用swift寫編譯器玩具(4)

前言

本章對應官方教程第4章,本章介紹如何為中間代碼(LLVM IR)添加優(yōu)化以及添加JIT編譯器支持。

教程如下:

教你使用swift寫編譯器玩具(0)

教你使用swift寫編譯器玩具(1)

教你使用swift寫編譯器玩具(2)

教你使用swift寫編譯器玩具(3)

教你使用swift寫編譯器玩具(4)

教你使用swift寫編譯器玩具(5)

教你使用swift寫編譯器玩具(6)

教你使用swift寫編譯器玩具(7)

教你使用swift寫編譯器玩具(8)

倉庫在這

開始

中間代碼優(yōu)化

我們都知道在編譯的過程中有著中間代碼優(yōu)化這一步。我們想要中間代碼能夠去除無用以及重復計算的內(nèi)容,所以這個時候我們需要使用中間代碼優(yōu)化器。

舉一個例子,在沒有優(yōu)化之前,我們輸入def test(x) (1+2+x)*(x+(1+2));獲得的結(jié)果如下所示。

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
}

我們可以看出來其實addadd1是相同的值,完全沒有必要算兩次。所以經(jīng)過優(yōu)化之后長下面這樣

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被優(yōu)化成了一個。

那么我們該如何添加優(yōu)化呢?LLVM為我們提供了PassManager。但是有趣的是在LLVMSwift中,PassManagerdeprecated了。所以我們只需要使用更簡單的PassPipeliner即可。

有多簡單呢?簡單到只需要添加兩行代碼。

let passPipeliner = PassPipeliner(module: theModule)

    func lexerWithDefinition(_ lexer: Lexer) {
        if let p = parseDefinition() {
            if let f = p.codeGen() {
                //在這里調(diào)用execute()方法
                    passPipeliner.execute()
                print("Read function definition:")
                f.dump()
            }
        } else {
            lexer.nextToken()
        }
    }

添加JIT支持

使用LLVMSwift中的JIT也十分簡單。我們只需要在合適的地方調(diào)用即可。

首先我們定義全局變量JIT,并在main中初始化它。

var theJIT: JIT!
let targetMachine = try! TargetMachine()
theJIT = JIT(machine: targetMachine)

接著我們在lexerWithDefinition中把Module中的IR添加到JIT中。

            ...
                        f.dump()
            _ = try! theJIT.addLazilyCompiledIR(theModule) { (_) -> JIT.TargetAddress in
                return JIT.TargetAddress()
            }

lexerWithTopLevelExpression中把繼續(xù)把Module中的IR添加到JIT中。

                ...
                                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中添加的默認函數(shù)名"__anon_expr"嗎?在lexerWithTopLevelExpression新增代碼的意思就是把頂級表達式包在一個名為"__anon_expr"且返回值為空的函數(shù)中進行調(diào)用。

但是目前我們還只能調(diào)用一次函數(shù),調(diào)用第二次函數(shù)時我們就找不到這個函數(shù)了。所以這個時候我們需要有一個全局的表用來記錄。

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()
    }
}

接著我們需要為CallExprASTFunctionAST替換獲取函數(shù)名的方式。

//CallExprAST
let calleeF = getFunction(named: callee!)
//FunctionAST
functionProtos[proto!.name!] = proto
let theFunction = getFunction(named: proto!.name!)
guard theFunction != nil else {
    return nil
}

這樣我們總是可以在當前Module中獲得先前定義過的函數(shù)進行調(diào)用。

最后我們還需要更新一下lexerWithDefinition方法和lexerWithExtern方法。

//lexerWithDefinition
...
f.dump()
_ = try! theJIT.addLazilyCompiledIR(theModule) { (_) -> JIT.TargetAddress in
        return JIT.TargetAddress()
}
initModule()

//lexerWithExtern
...
f.dump()
functionProtos[p.name!] = p

func initModule() {
    theModule = Module(name: "main")
    theModule.dataLayout = targetMachine.dataLayout
}

測試

直接輸入表達式。

1+20;//輸入
Read top-level expression:

define i64 @__anon_expr() {
entry:
  ret i64 21
}
Evaluated to 21.//輸出

函數(shù)調(diào)用。

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.//輸出
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容