Kaleidoscope:JIT 与优化器支持
Kaleidoscope:JIT 与优化器支持
本章为 Kaleidoscope 加入 LLVM optimization passes 和 JIT compiler,使用户输入的函数能够被优化并立即执行。
TL;DR
IRBuilder能做局部 constant folding,但无法发现跨表达式的公共子表达式。- LLVM 通过可组合的 optimization passes 处理更复杂的 IR 优化;本章使用
InstCombinePass、ReassociatePass、GVNPass和SimplifyCFGPass。 - JIT 将每个已完成的 LLVM module 添加到
KaleidoscopeJIT,通过 symbol lookup 找到机器码并直接调用。 - 每个 function 放入独立 module 后,可以支持 REPL 中的重新定义;
FunctionProtos负责在新 module 中重新生成已有 declarations。 - 从 LLVM 9 起,独立 modules 中不允许重复 symbols;教程中的旧式重新定义示例需要跳过。
目录
| 章节 | 说明 |
|---|---|
| 本章简介 | 优化与 JIT 的目标 |
| 简单的 Constant Folding | IRBuilder 的局部优化能力 |
| LLVM Optimization Passes | pass manager 与函数优化 |
| 添加 JIT Compiler | 将 LLVM IR 编译并执行 |
| 完整代码清单 | 带 JIT 和 optimizer 的完整示例 |
本章简介
欢迎来到“使用 LLVM 实现一门语言”教程的第 4 章。第 1~3 章描述了如何实现一门简单语言,并加入 LLVM IR 生成能力。本章介绍两种新技术:为 language 加入 optimizer support,以及加入 JIT compiler support。这些 additions 会展示如何为 Kaleidoscope language 生成漂亮且高效的 code。
简单的 Constant Folding
第 3 章的示例优雅且容易扩展,但生成的 code 并不理想。不过,IRBuilder 在编译简单 code 时确实会提供明显的 optimization:
ready> def test(x) 1+2+x;
Read function definition:
define double @test(double %x) {
entry:
%addtmp = fadd double 3.000000e+00, %x
ret double %addtmp
}
这段 code 并不是对 parsing 得到的 AST 的字面转录。字面转录应当是:
ready> def test(x) 1+2+x;
Read function definition:
define double @test(double %x) {
entry:
%addtmp = fadd double 2.000000e+00, 1.000000e+00
%addtmp1 = fadd double %addtmp, %x
ret double %addtmp1
}
上面展示的 constant folding 是一种非常常见、也非常重要的 optimization;重要到许多 language implementors 都会在 AST representation 中实现 constant folding support。
使用 LLVM 时,不需要把这项 support 加到 AST 中。由于所有用于构建 LLVM IR 的 calls 都会经过 LLVM IR builder,因此 builder 自身会在被调用时检查是否存在 constant folding opportunity。如果存在,它就直接执行 constant fold,返回 constant,而不是创建 instruction。
这很简单 :)。实践中,我们建议在生成 code 时始终使用 IRBuilder。它没有“syntactic overhead”(不需要在 compiler 各处加入 constant checks),并且在某些情况下可以显著减少生成的 LLVM IR 数量,尤其是带有 macro preprocessor 或大量 constants 的 language。
另一方面,IRBuilder 的能力受限于它是在构建 code 的过程中 inline 完成 analysis。如果使用稍微复杂一些的示例:
ready> def test(x) (1+2+x)*(x+(1+2));
ready> Read function definition:
define double @test(double %x) {
entry:
%addtmp = fadd double 3.000000e+00, %x
%addtmp1 = fadd double %x, 3.000000e+00
%multmp = fmul double %addtmp, %addtmp1
ret double %multmp
}
这里,乘法的 LHS 和 RHS 是同一个 value。我们很希望生成的 code 是 tmp = x+3; result = tmp*tmp;,而不是计算两次 x+3。
遗憾的是,任何局部 analysis 都无法发现并修复这个问题。它需要两种 transformations:reassociation of expressions(让两个加法在 lexical 上变得相同),以及 Common Subexpression Elimination(CSE,删除重复的 add instruction)。幸运的是,LLVM 以 passes 的形式提供了大量 optimizations。
LLVM Optimization Passes
LLVM 提供了许多 optimization passes,它们执行不同类型的工作,也有不同的 tradeoffs。与其他系统不同,LLVM 不坚持“对所有 languages 和所有场景都适用同一套 optimizations”这种错误观念。LLVM 允许 compiler implementor 完全决定使用哪些 optimizations、采用什么顺序,以及在什么场景使用。
例如,LLVM 支持“whole module” passes:它们会尽可能查看大范围的 code(通常是整个 file;如果在 link time 运行,范围可能是整个 program 的很大一部分)。LLVM 也支持并包含 “per-function” passes:它们一次只处理一个 function,而不查看其他 functions。更多关于 passes 及其运行方式的信息,请参阅 How to Write a Pass 和 List of LLVM Passes。
当前 Kaleidoscope 是在用户输入 function 时,一个接一个地即时生成 functions。我们不追求这种场景下最极致的 optimization experience,但也希望在可能时捕获那些简单、快速的优化。因此,我们会在用户输入 function 时运行几个 per-function optimizations。如果想实现一个 “static Kaleidoscope compiler”,只需保留当前的 code,并把 optimizer 的运行推迟到整个 file 都解析完之后。
除了 function passes 和 module passes 的区别,passes 还可以分为 transform passes 与 analysis passes。Transform passes 会修改 IR;analysis passes 会计算其他 passes 可以使用的信息。要添加一个 transform pass,必须预先注册它所依赖的所有 analysis passes。
要启用 per-function optimizations,需要设置一个 FunctionPassManager,用于保存并组织希望运行的 LLVM optimizations。完成之后,就可以添加一组要运行的 optimizations。每个需要优化的 module 都需要一个新的 FunctionPassManager,因此我们会修改上一章中创建的 InitializeModule() function:
void InitializeModuleAndManagers(void) {
// Open a new context and module.
TheContext = std::make_unique<LLVMContext>();
TheModule = std::make_unique<Module>("KaleidoscopeJIT", *TheContext);
TheModule->setDataLayout(TheJIT->getDataLayout());
// Create a new builder for the module.
Builder = std::make_unique<IRBuilder<>>(*TheContext);
// Create new pass and analysis managers.
TheFPM = std::make_unique<FunctionPassManager>();
TheLAM = std::make_unique<LoopAnalysisManager>();
TheFAM = std::make_unique<FunctionAnalysisManager>();
TheCGAM = std::make_unique<CGSCCAnalysisManager>();
TheMAM = std::make_unique<ModuleAnalysisManager>();
ThePIC = std::make_unique<PassInstrumentationCallbacks>();
TheSI = std::make_unique<StandardInstrumentations>(*TheContext,
/*DebugLogging*/ true);
TheSI->registerCallbacks(*ThePIC, TheMAM.get());
...
除了初始化 global module TheModule 和 FunctionPassManager 外,代码还包含 TheModule->setDataLayout(TheJIT->getDataLayout());。本章后面会讨论它。
初始化 global module TheModule 和 FunctionPassManager 后,还需要初始化 framework 的其他部分。四个 AnalysisManager 允许我们添加覆盖 IR hierarchy 四个层级的 analysis passes。PassInstrumentationCallbacks 和 StandardInstrumentations 是 pass instrumentation framework 所必需的;这个 framework 允许 developers 定制 passes 之间发生的事情。
manager 设置好后,使用一系列 addPass calls 添加 LLVM transform passes:
// Add transform passes.
// Do simple "peephole" optimizations and bit-twiddling optzns.
TheFPM->addPass(InstCombinePass());
// Reassociate expressions.
TheFPM->addPass(ReassociatePass());
// Eliminate Common SubExpressions.
TheFPM->addPass(GVNPass());
// Simplify the control flow graph (deleting unreachable blocks, etc).
TheFPM->addPass(SimplifyCFGPass());
这里选择了四个 optimization passes。它们是一组相当标准的 “cleanup” optimizations,适用于广泛的 code。这里不深入介绍各个 pass 的具体工作,但它们确实是一个很好的起点 :)。
接下来,注册 transform passes 使用的 analysis passes:
// Register analysis passes used in these transform passes.
PassBuilder PB;
PB.registerModuleAnalyses(*TheMAM);
PB.registerFunctionAnalyses(*TheFAM);
PB.crossRegisterProxies(*TheLAM, *TheFAM, *TheCGAM, *TheMAM);
}
设置好 PassManager 后,需要实际使用它。做法是在新创建的 function 构造完成后(FunctionAST::codegen() 中),但在它返回给 client 之前运行 optimizer:
if (Value *RetVal = Body->codegen()) {
// Finish off the function.
Builder.CreateRet(RetVal);
// Validate the generated code, checking for consistency.
verifyFunction(*TheFunction);
// Optimize the function.
TheFPM->run(*TheFunction, *TheFAM);
return TheFunction;
}
如你所见,这非常直接。FunctionPassManager 会原地优化并更新 LLVM Function*,希望能改善它的 body。加入这段代码后,再次运行上面的测试:
ready> def test(x) (1+2+x)*(x+(1+2));
ready> Read function definition:
define double @test(double %x) {
entry:
%addtmp = fadd double %x, 3.000000e+00
%multmp = fmul double %addtmp, %addtmp
ret double %multmp
}
正如预期,现在得到了漂亮的 optimized code,每次执行这个 function 时都省去了一条 floating point add instruction。
LLVM 提供了大量可在特定场景使用的 optimizations。关于不同 passes 的 documentation 目前并不完整。另一个寻找思路的好来源,是查看 Clang 为了开始工作而运行的 passes。opt tool 允许你在 command line 中实验 passes,从而观察它们是否产生了作用。
现在 front-end 已经可以生成合理的 code,接下来讨论如何执行它!
添加 JIT Compiler
LLVM IR 中的 code 可以应用许多不同的 tools。例如,可以对它运行 optimizations,可以将它以 text 或 binary form dump 出来,可以把 code 编译为某个 target 的 assembly file(.s),也可以 JIT compile 它。LLVM IR representation 的优点在于,它是 compiler 不同部分之间的 “common currency”。
本节为 interpreter 加入 JIT compiler support。Kaleidoscope 的基本目标是:用户仍然像现在一样输入 function bodies,但刚输入 top-level expressions 就立即对它们求值。例如,输入 1 + 2; 后应该计算并打印 3;如果定义了一个 function,则应该可以在 command line 中调用它。
为此,首先需要准备 environment,使其能够为当前 native target 创建 code,然后声明并初始化 JIT。做法是调用一些 InitializeNativeTarget* functions,在 main 中添加 global variable TheJIT 并初始化它:
static std::unique_ptr<KaleidoscopeJIT> TheJIT;
...
int main() {
InitializeNativeTarget();
InitializeNativeTargetAsmPrinter();
InitializeNativeTargetAsmParser();
// Install standard binary operators.
// 1 is lowest precedence.
BinopPrecedence['<'] = 10;
BinopPrecedence['+'] = 20;
BinopPrecedence['-'] = 20;
BinopPrecedence['*'] = 40; // highest.
// Prime the first token.
fprintf(stderr, "ready> ");
getNextToken();
TheJIT = std::make_unique<KaleidoscopeJIT>();
// Run the main "interpreter loop" now.
MainLoop();
return 0;
}
还需要为 JIT 设置 data layout。现在 TheJIT 已经存在,可以在 InitializeModuleAndManagers 中添加 setDataLayout call:
void InitializeModuleAndManagers(void) {
// Open a new context and module.
TheContext = std::make_unique<LLVMContext>();
TheModule = std::make_unique<Module>("KaleidoscopeJIT", *TheContext);
TheModule->setDataLayout(TheJIT->getDataLayout());
...
}
KaleidoscopeJIT class 是专门为本教程构建的简单 JIT,位于 LLVM source code 的 llvm-src/examples/Kaleidoscope/include/KaleidoscopeJIT.h。后续章节会查看它的工作方式,并为它加入新 features;现在先把它当作已知组件。它的 API 很简单:addModule 将一个 LLVM IR module 加入 JIT,使 module 中的 functions 可供执行(其 memory 由 ResourceTracker 管理);lookup 则允许查找 compiled code 的 pointers。
利用这个简单 API,可以把解析 top-level expressions 的 code 改成:
static ExitOnError ExitOnErr;
...
static void HandleTopLevelExpression() {
// Evaluate a top-level expression into an anonymous function.
if (auto FnAST = ParseTopLevelExpr()) {
if (FnAST->codegen()) {
// Create a ResourceTracker to track JIT'd memory allocated to our
// anonymous expression -- that way we can free it after executing.
auto RT = TheJIT->getMainJITDylib().createResourceTracker();
auto TSM = ThreadSafeModule(std::move(TheModule), std::move(TheContext));
ExitOnErr(TheJIT->addModule(std::move(TSM), RT));
InitializeModuleAndManagers();
// Search the JIT for the __anon_expr symbol.
auto ExprSymbol = ExitOnErr(TheJIT->lookup("__anon_expr"));
// Get the symbol's address and cast it to the right type (takes no
// arguments, returns a double) so we can call it as a native function.
double (*FP)() = ExprSymbol.toPtr<double (*)()>();
fprintf(stderr, "Evaluated to %f\n", FP());
// Delete the anonymous expression module from the JIT.
ExitOnErr(RT->remove());
}
如果 parsing 和 codegen 成功,下一步就是把包含 top-level expression 的 module 加到 JIT。我们调用 addModule;它会触发 module 中所有 functions 的 code generation,并接收一个 ResourceTracker,之后可以用它从 JIT 删除 module。module 加入 JIT 后就不能再修改,因此还要调用 InitializeModuleAndManagers() 打开一个新 module,保存后续 code。
module 加入 JIT 后,需要取得最终生成的 code 的 pointer。做法是调用 JIT 的 lookup method,并传入 top-level expression function 的 name:__anon_expr。
接下来获取 __anon_expr function 的 in-memory address。parser 会把 top-level expressions 编译成一个 self-contained LLVM function,它不接收 arguments,并返回计算出的 double。由于 LLVM JIT compiler 匹配 native platform ABI,因此可以直接把返回的 pointer cast 成对应类型的 function pointer 并调用。这意味着 JIT compiled code 与静态链接到 application 中的 native machine code 没有区别。
最后,由于当前不支持重新计算 top-level expressions,执行完成后会从 JIT 删除 module,以释放关联的 memory。不过,刚才通过 InitializeModuleAndManagers 创建的 module 仍然保持打开,等待添加新的 code。
只做这两处修改,就来看看 Kaleidoscope 现在的表现:
ready> 4+5;
Read top-level expression:
define double @0() {
entry:
ret double 9.000000e+00
}
Evaluated to 9.000000
这基本已经可以工作了。function dump 展示了我们为每个 top-level expression 合成的“无参数、始终返回 double 的 function”。这是非常基础的功能,但还能做更多吗?
ready> def testfunc(x y) x + y*2;
Read function definition:
define double @testfunc(double %x, double %y) {
entry:
%multmp = fmul double %y, 2.000000e+00
%addtmp = fadd double %multmp, %x
ret double %addtmp
}
ready> testfunc(4, 10);
Read top-level expression:
define double @1() {
entry:
%calltmp = call double @testfunc(double 4.000000e+00, double 1.000000e+01)
ret double %calltmp
}
Evaluated to 24.000000
ready> testfunc(5, 10);
ready> LLVM ERROR: Program used external function 'testfunc' which could not be resolved!
function definitions 和 calls 也能工作,但最后一行出了严重问题。call 看起来是有效的,发生了什么?正如你可能从 API 中猜到的,Module 是 JIT 的 allocation unit,而 testfunc 属于同时包含 anonymous expression 的那个 module。当我们从 JIT 删除该 module 以释放 anonymous expression 的 memory 时,也连同 testfunc 的 definition 一起删除了。于是第二次调用 testfunc 时,JIT 已经找不到它。
最简单的修复方式,是让 anonymous expression 位于与其他 function definitions 不同的 module 中。只要每个被调用的 function 都有 prototype,并且在调用前已经加入 JIT,JIT 就可以跨 module 解析 function calls。将 anonymous expression 放在单独 module 中,就可以删除它而不影响其余 functions。
实际上,我们会更进一步,让每个 function 都位于自己的 module 中。这样可以利用 KaleidoscopeJIT 的一个有用属性,让 environment 更像 REPL:同一个 function 可以多次加入 JIT(不同于一个 module,在 module 中每个 function 必须有唯一 definition)。使用 KaleidoscopeJIT 查找 symbol 时,总会返回最新的 definition:
ready> def foo(x) x + 1;
Read function definition:
define double @foo(double %x) {
entry:
%addtmp = fadd double %x, 1.000000e+00
ret double %addtmp
}
ready> foo(2);
Evaluated to 3.000000
ready> def foo(x) x + 2;
define double @foo(double %x) {
entry:
%addtmp = fadd double %x, 2.000000e+00
ret double %addtmp
}
ready> foo(2);
Evaluated to 4.000000
为了让每个 function 位于自己的 module 中,需要能够在每个新 module 中重新生成之前的 function declarations:
static std::unique_ptr<KaleidoscopeJIT> TheJIT;
...
Function *getFunction(std::string Name) {
// First, see if the function has already been added to the current module.
if (auto *F = TheModule->getFunction(Name))
return F;
// If not, check whether we can codegen the declaration from some existing
// prototype.
auto FI = FunctionProtos.find(Name);
if (FI != FunctionProtos.end())
return FI->second->codegen();
// If no existing prototype exists, return null.
return nullptr;
}
...
Value *CallExprAST::codegen() {
// Look up the name in the global module table.
Function *CalleeF = getFunction(Callee);
...
Function *FunctionAST::codegen() {
// Transfer ownership of the prototype to the FunctionProtos map, but keep a
// reference to it for use below.
auto &P = *Proto;
FunctionProtos[Proto->getName()] = std::move(Proto);
Function *TheFunction = getFunction(P.getName());
if (!TheFunction)
return nullptr;
为此,先添加一个新的 global FunctionProtos,保存每个 function 最近的 prototype;再添加 convenience method getFunction(),替代对 TheModule->getFunction() 的调用。
这个 convenience method 会先在 TheModule 中搜索已有的 function declaration;如果找不到,就根据 FunctionProtos 生成一个新 declaration。在 CallExprAST::codegen() 中只需替换原来的 TheModule->getFunction() call。在 FunctionAST::codegen() 中,先更新 FunctionProtos map,再调用 getFunction()。这样,对于此前声明过的任意 function,总能在当前 module 中获得对应 declaration。
还需要更新 HandleDefinition 和 HandleExtern:
static void HandleDefinition() {
if (auto FnAST = ParseDefinition()) {
if (auto *FnIR = FnAST->codegen()) {
fprintf(stderr, "Read function definition:");
FnIR->print(errs());
fprintf(stderr, "\n");
ExitOnErr(TheJIT->addModule(
ThreadSafeModule(std::move(TheModule), std::move(TheContext))));
InitializeModuleAndManagers();
}
} else {
// Skip token for error recovery.
getNextToken();
}
}
static void HandleExtern() {
if (auto ProtoAST = ParseExtern()) {
if (auto *FnIR = ProtoAST->codegen()) {
fprintf(stderr, "Read extern: ");
FnIR->print(errs());
fprintf(stderr, "\n");
FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
}
} else {
// Skip token for error recovery.
getNextToken();
}
}
在 HandleDefinition 中,添加两行,将新定义的 function 转移到 JIT 并打开一个新 module。在 HandleExtern 中,只需添加一行,将 prototype 加入 FunctionProtos。
警告
LLVM 9 起,不允许在独立 modules 中重复 symbols。因此不能像上面的旧示例那样在 Kaleidoscope 中重新定义 function,请跳过这部分。
原因是更新后的 OrcV2 JIT APIs 正在尽可能贴近 static linker 和 dynamic linker 的规则,其中包括拒绝 duplicate symbols。要求 symbol names 唯一,可以使用这些唯一的 names 作为 tracking keys,从而支持 symbols 的 concurrent compilation。
完成修改后,再试一次 REPL(这次删除了 anonymous functions 的 dump,相信你已经理解它了):
ready> def foo(x) x + 1;
ready> foo(2);
Evaluated to 3.000000
ready> def foo(x) x + 2;
ready> foo(2);
Evaluated to 4.000000
它可以工作了!
即使只有这些简单的 code,我们也得到了令人惊讶的能力。看这个:
ready> extern sin(x);
Read extern:
declare double @sin(double)
ready> extern cos(x);
Read extern:
declare double @cos(double)
ready> sin(1.0);
Read top-level expression:
define double @2() {
entry:
ret double 0x3FEAED548F090CEE
}
Evaluated to 0.841471
ready> def foo(x) sin(x)*sin(x) + cos(x)*cos(x);
Read function definition:
define double @foo(double %x) {
entry:
%calltmp = call double @sin(double %x)
%multmp = fmul double %calltmp, %calltmp
%calltmp2 = call double @cos(double %x)
%multmp4 = fmul double %calltmp2, %calltmp2
%addtmp = fadd double %multmp, %multmp4
ret double %addtmp
}
ready> foo(4.0);
Read top-level expression:
define double @3() {
entry:
%calltmp = call double @foo(double 4.000000e+00)
ret double %calltmp
}
Evaluated to 1.000000
JIT 是如何知道 sin 和 cos 的?答案出人意料地简单:KaleidoscopeJIT 有一条直接的 symbol resolution rule,用来查找当前 module 中不可用的 symbols。它首先从最近加入的 module 开始,到最早加入的 module 为止,搜索已经加入 JIT 的所有 modules,寻找最新的 definition。如果 JIT 内部找不到 definition,就退回到 Kaleidoscope process 自身上调用 dlsym("sin")。
由于 sin 定义在 JIT 的 address space 中,它只需修补 module 中的 calls,让它们直接调用 libm 中的 sin 版本。但在某些情况下,这还会更进一步:因为 sin 和 cos 是标准数学 functions 的 names,所以当以 sin(1.0) 这样的 constant 调用它们时,constant folder 会直接将 function calls 求值为正确结果。
之后我们会看到,调整这条 symbol resolution rule,可以实现从安全性(限制 JIT code 可用的 symbols 集合)到基于 symbol names 的 dynamic code generation,甚至 lazy compilation 等各种有用 features。
symbol resolution rule 的一个直接收益是:现在可以通过任意 C++ code 实现 operations,从而扩展这门 language。例如,加入:
#ifdef _WIN32
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT
#endif
/// putchard - putchar that takes a double and returns 0.
extern "C" DLLEXPORT double putchard(double X) {
fputc((char)X, stderr);
return 0;
}
注意,在 Windows 上必须真正 export 这些 functions,因为 dynamic symbol loader 会使用 GetProcAddress 查找 symbols。
现在,可以使用 extern putchard(x); putchard(120); 这样的 code 向 console 输出一个小写 x(120 是 x 的 ASCII code)。类似的 code 也可以用于实现 file I/O、console input,以及 Kaleidoscope 中的许多其他 capabilities。
至此,Kaleidoscope tutorial 的 JIT 和 optimizer 章节结束。现在,我们可以用 user-driven 的方式,编译一种还不是 Turing-complete 的 programming language,并对它进行优化和 JIT compilation。下一章将继续扩展 language,加入 control flow constructs,并在此过程中处理一些有趣的 LLVM IR 问题。
完整代码清单
下面是加入 LLVM JIT 和 optimizer 后的完整代码。构建示例时使用:
# Compile
clang++ -g toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core orcjit native` -O3 -o toy
# Run
./toy
如果在 Linux 上编译,还要加入 -rdynamic option,确保 external functions 能在 runtime 正确解析。
下面是代码:
#include "../include/KaleidoscopeJIT.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Passes/PassBuilder.h"
#include "llvm/Passes/StandardInstrumentations.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/InstCombine/InstCombine.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Scalar/GVN.h"
#include "llvm/Transforms/Scalar/Reassociate.h"
#include "llvm/Transforms/Scalar/SimplifyCFG.h"
#include <algorithm>
#include <cassert>
#include <cctype>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <memory>
#include <string>
#include <vector>
using namespace llvm;
using namespace llvm::orc;
//===----------------------------------------------------------------------===//
// Lexer
//===----------------------------------------------------------------------===//
enum Token { tok_eof = -1, tok_def = -2, tok_extern = -3,
tok_identifier = -4, tok_number = -5 };
static std::string IdentifierStr;
static double NumVal;
static int gettok() {
static int LastChar = ' ';
while (isspace(LastChar)) LastChar = getchar();
if (isalpha(LastChar)) {
IdentifierStr = LastChar;
while (isalnum((LastChar = getchar()))) IdentifierStr += LastChar;
if (IdentifierStr == "def") return tok_def;
if (IdentifierStr == "extern") return tok_extern;
return tok_identifier;
}
if (isdigit(LastChar) || LastChar == '.') {
std::string NumStr;
do { NumStr += LastChar; LastChar = getchar(); }
while (isdigit(LastChar) || LastChar == '.');
NumVal = strtod(NumStr.c_str(), nullptr);
return tok_number;
}
if (LastChar == '#') {
do LastChar = getchar();
while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
if (LastChar != EOF) return gettok();
}
if (LastChar == EOF) return tok_eof;
int ThisChar = LastChar;
LastChar = getchar();
return ThisChar;
}
//===----------------------------------------------------------------------===//
// Abstract Syntax Tree
//===----------------------------------------------------------------------===//
namespace {
class ExprAST {
public:
virtual ~ExprAST() = default;
virtual Value *codegen() = 0;
};
class NumberExprAST : public ExprAST {
double Val;
public:
NumberExprAST(double Val) : Val(Val) {}
Value *codegen() override;
};
class VariableExprAST : public ExprAST {
std::string Name;
public:
VariableExprAST(const std::string &Name) : Name(Name) {}
Value *codegen() override;
};
class BinaryExprAST : public ExprAST {
char Op; std::unique_ptr<ExprAST> LHS, RHS;
public:
BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
std::unique_ptr<ExprAST> RHS)
: Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
Value *codegen() override;
};
class CallExprAST : public ExprAST {
std::string Callee;
std::vector<std::unique_ptr<ExprAST>> Args;
public:
CallExprAST(const std::string &Callee,
std::vector<std::unique_ptr<ExprAST>> Args)
: Callee(Callee), Args(std::move(Args)) {}
Value *codegen() override;
};
class PrototypeAST {
std::string Name; std::vector<std::string> Args;
public:
PrototypeAST(const std::string &Name, std::vector<std::string> Args)
: Name(Name), Args(std::move(Args)) {}
Function *codegen();
const std::string &getName() const { return Name; }
};
class FunctionAST {
std::unique_ptr<PrototypeAST> Proto; std::unique_ptr<ExprAST> Body;
public:
FunctionAST(std::unique_ptr<PrototypeAST> Proto,
std::unique_ptr<ExprAST> Body)
: Proto(std::move(Proto)), Body(std::move(Body)) {}
Function *codegen();
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// Parser
//===----------------------------------------------------------------------===//
static int CurTok;
static int getNextToken() { return CurTok = gettok(); }
static std::map<char, int> BinopPrecedence;
static int GetTokPrecedence() {
if (!isascii(CurTok)) return -1;
int TokPrec = BinopPrecedence[CurTok];
if (TokPrec <= 0) return -1;
return TokPrec;
}
std::unique_ptr<ExprAST> LogError(const char *Str) {
fprintf(stderr, "Error: %s\n", Str); return nullptr;
}
std::unique_ptr<PrototypeAST> LogErrorP(const char *Str) {
LogError(Str); return nullptr;
}
static std::unique_ptr<ExprAST> ParseExpression();
static std::unique_ptr<ExprAST> ParseNumberExpr() {
auto Result = std::make_unique<NumberExprAST>(NumVal);
getNextToken(); return std::move(Result);
}
static std::unique_ptr<ExprAST> ParseParenExpr() {
getNextToken(); auto V = ParseExpression();
if (!V) return nullptr;
if (CurTok != ')') return LogError("expected ')'");
getNextToken(); return V;
}
static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
std::string IdName = IdentifierStr;
getNextToken();
if (CurTok != '(') return std::make_unique<VariableExprAST>(IdName);
getNextToken(); std::vector<std::unique_ptr<ExprAST>> Args;
if (CurTok != ')') {
while (true) {
if (auto Arg = ParseExpression()) Args.push_back(std::move(Arg));
else return nullptr;
if (CurTok == ')') break;
if (CurTok != ',') return LogError("Expected ')' or ',' in argument list");
getNextToken();
}
}
getNextToken();
return std::make_unique<CallExprAST>(IdName, std::move(Args));
}
static std::unique_ptr<ExprAST> ParsePrimary() {
switch (CurTok) {
default: return LogError("unknown token when expecting an expression");
case tok_identifier: return ParseIdentifierExpr();
case tok_number: return ParseNumberExpr();
case '(': return ParseParenExpr();
}
}
static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
std::unique_ptr<ExprAST> LHS) {
while (true) {
int TokPrec = GetTokPrecedence();
if (TokPrec < ExprPrec) return LHS;
int BinOp = CurTok; getNextToken();
auto RHS = ParsePrimary(); if (!RHS) return nullptr;
int NextPrec = GetTokPrecedence();
if (TokPrec < NextPrec) {
RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
if (!RHS) return nullptr;
}
LHS = std::make_unique<BinaryExprAST>(BinOp, std::move(LHS),
std::move(RHS));
}
}
static std::unique_ptr<ExprAST> ParseExpression() {
auto LHS = ParsePrimary(); if (!LHS) return nullptr;
return ParseBinOpRHS(0, std::move(LHS));
}
static std::unique_ptr<PrototypeAST> ParsePrototype() {
if (CurTok != tok_identifier)
return LogErrorP("Expected function name in prototype");
std::string FnName = IdentifierStr; getNextToken();
if (CurTok != '(') return LogErrorP("Expected '(' in prototype");
std::vector<std::string> ArgNames;
while (getNextToken() == tok_identifier) ArgNames.push_back(IdentifierStr);
if (CurTok != ')') return LogErrorP("Expected ')' in prototype");
getNextToken(); return std::make_unique<PrototypeAST>(FnName,
std::move(ArgNames));
}
static std::unique_ptr<FunctionAST> ParseDefinition() {
getNextToken(); auto Proto = ParsePrototype();
if (!Proto) return nullptr;
if (auto E = ParseExpression())
return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
return nullptr;
}
static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
if (auto E = ParseExpression()) {
auto Proto = std::make_unique<PrototypeAST>("__anon_expr",
std::vector<std::string>());
return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
}
return nullptr;
}
static std::unique_ptr<PrototypeAST> ParseExtern() {
getNextToken(); return ParsePrototype();
}
//===----------------------------------------------------------------------===//
// Code Generation
//===----------------------------------------------------------------------===//
static std::unique_ptr<LLVMContext> TheContext;
static std::unique_ptr<Module> TheModule;
static std::unique_ptr<IRBuilder<>> Builder;
static std::map<std::string, Value *> NamedValues;
static std::unique_ptr<KaleidoscopeJIT> TheJIT;
static std::unique_ptr<FunctionPassManager> TheFPM;
static std::unique_ptr<LoopAnalysisManager> TheLAM;
static std::unique_ptr<FunctionAnalysisManager> TheFAM;
static std::unique_ptr<CGSCCAnalysisManager> TheCGAM;
static std::unique_ptr<ModuleAnalysisManager> TheMAM;
static std::unique_ptr<PassInstrumentationCallbacks> ThePIC;
static std::unique_ptr<StandardInstrumentations> TheSI;
static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
static ExitOnError ExitOnErr;
Value *LogErrorV(const char *Str) { LogError(Str); return nullptr; }
Function *getFunction(std::string Name) {
if (auto *F = TheModule->getFunction(Name)) return F;
auto FI = FunctionProtos.find(Name);
if (FI != FunctionProtos.end()) return FI->second->codegen();
return nullptr;
}
Value *NumberExprAST::codegen() {
return ConstantFP::get(*TheContext, APFloat(Val));
}
Value *VariableExprAST::codegen() {
Value *V = NamedValues[Name];
if (!V) return LogErrorV("Unknown variable name");
return V;
}
Value *BinaryExprAST::codegen() {
Value *L = LHS->codegen(), *R = RHS->codegen();
if (!L || !R) return nullptr;
switch (Op) {
case '+': return Builder->CreateFAdd(L, R, "addtmp");
case '-': return Builder->CreateFSub(L, R, "subtmp");
case '*': return Builder->CreateFMul(L, R, "multmp");
case '<':
L = Builder->CreateFCmpULT(L, R, "cmptmp");
return Builder->CreateUIToFP(L, Type::getDoubleTy(*TheContext), "booltmp");
default: return LogErrorV("invalid binary operator");
}
}
Value *CallExprAST::codegen() {
Function *CalleeF = getFunction(Callee);
if (!CalleeF) return LogErrorV("Unknown function referenced");
if (CalleeF->arg_size() != Args.size())
return LogErrorV("Incorrect # arguments passed");
std::vector<Value *> ArgsV;
for (unsigned i = 0, e = Args.size(); i != e; ++i) {
ArgsV.push_back(Args[i]->codegen());
if (!ArgsV.back()) return nullptr;
}
return Builder->CreateCall(CalleeF, ArgsV, "calltmp");
}
Function *PrototypeAST::codegen() {
std::vector<Type *> Doubles(Args.size(), Type::getDoubleTy(*TheContext));
FunctionType *FT = FunctionType::get(Type::getDoubleTy(*TheContext),
Doubles, false);
Function *F = Function::Create(FT, Function::ExternalLinkage, Name,
TheModule.get());
unsigned Idx = 0;
for (auto &Arg : F->args()) Arg.setName(Args[Idx++]);
return F;
}
Function *FunctionAST::codegen() {
auto &P = *Proto;
FunctionProtos[Proto->getName()] = std::move(Proto);
Function *TheFunction = getFunction(P.getName());
if (!TheFunction) return nullptr;
BasicBlock *BB = BasicBlock::Create(*TheContext, "entry", TheFunction);
Builder->SetInsertPoint(BB);
NamedValues.clear();
for (auto &Arg : TheFunction->args())
NamedValues[std::string(Arg.getName())] = &Arg;
if (Value *RetVal = Body->codegen()) {
Builder->CreateRet(RetVal);
verifyFunction(*TheFunction);
TheFPM->run(*TheFunction, *TheFAM);
return TheFunction;
}
TheFunction->eraseFromParent(); return nullptr;
}
//===----------------------------------------------------------------------===//
// Top-Level parsing and JIT Driver
//===----------------------------------------------------------------------===//
static void InitializeModuleAndManagers() {
TheContext = std::make_unique<LLVMContext>();
TheModule = std::make_unique<Module>("KaleidoscopeJIT", *TheContext);
TheModule->setDataLayout(TheJIT->getDataLayout());
Builder = std::make_unique<IRBuilder<>>(*TheContext);
TheFPM = std::make_unique<FunctionPassManager>();
TheLAM = std::make_unique<LoopAnalysisManager>();
TheFAM = std::make_unique<FunctionAnalysisManager>();
TheCGAM = std::make_unique<CGSCCAnalysisManager>();
TheMAM = std::make_unique<ModuleAnalysisManager>();
ThePIC = std::make_unique<PassInstrumentationCallbacks>();
TheSI = std::make_unique<StandardInstrumentations>(*TheContext,
/*DebugLogging*/ true);
TheSI->registerCallbacks(*ThePIC, TheMAM.get());
TheFPM->addPass(InstCombinePass());
TheFPM->addPass(ReassociatePass());
TheFPM->addPass(GVNPass());
TheFPM->addPass(SimplifyCFGPass());
PassBuilder PB;
PB.registerModuleAnalyses(*TheMAM);
PB.registerFunctionAnalyses(*TheFAM);
PB.crossRegisterProxies(*TheLAM, *TheFAM, *TheCGAM, *TheMAM);
}
static void HandleDefinition() {
if (auto FnAST = ParseDefinition()) {
if (auto *FnIR = FnAST->codegen()) {
fprintf(stderr, "Read function definition:"); FnIR->print(errs());
fprintf(stderr, "\n");
ExitOnErr(TheJIT->addModule(ThreadSafeModule(std::move(TheModule),
std::move(TheContext))));
InitializeModuleAndManagers();
}
} else getNextToken();
}
static void HandleExtern() {
if (auto ProtoAST = ParseExtern()) {
if (auto *FnIR = ProtoAST->codegen()) {
fprintf(stderr, "Read extern: "); FnIR->print(errs());
fprintf(stderr, "\n");
FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
}
} else getNextToken();
}
static void HandleTopLevelExpression() {
if (auto FnAST = ParseTopLevelExpr()) {
if (FnAST->codegen()) {
auto RT = TheJIT->getMainJITDylib().createResourceTracker();
auto TSM = ThreadSafeModule(std::move(TheModule), std::move(TheContext));
ExitOnErr(TheJIT->addModule(std::move(TSM), RT));
InitializeModuleAndManagers();
auto ExprSymbol = ExitOnErr(TheJIT->lookup("__anon_expr"));
double (*FP)() = ExprSymbol.toPtr<double (*)()>();
fprintf(stderr, "Evaluated to %f\n", FP());
ExitOnErr(RT->remove());
}
} else getNextToken();
}
static void MainLoop() {
while (true) {
fprintf(stderr, "ready> ");
switch (CurTok) {
case tok_eof: return;
case ';': getNextToken(); break;
case tok_def: HandleDefinition(); break;
case tok_extern: HandleExtern(); break;
default: HandleTopLevelExpression(); break;
}
}
}
#ifdef _WIN32
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT
#endif
extern "C" DLLEXPORT double putchard(double X) {
fputc((char)X, stderr); return 0;
}
extern "C" DLLEXPORT double printd(double X) {
fprintf(stderr, "%f\n", X); return 0;
}
int main() {
InitializeNativeTarget();
InitializeNativeTargetAsmPrinter();
InitializeNativeTargetAsmParser();
BinopPrecedence['<'] = 10;
BinopPrecedence['+'] = 20;
BinopPrecedence['-'] = 20;
BinopPrecedence['*'] = 40;
fprintf(stderr, "ready> ");
getNextToken();
TheJIT = ExitOnErr(KaleidoscopeJIT::Create());
InitializeModuleAndManagers();
MainLoop();
return 0;
}
下一章
参考资料
版权说明:本文是基于 LLVM 官方教程的个人学习用途中文翻译。原文版权及许可证以 LLVM 项目官方说明为准。
评论 (0)