目录
正在加载目录…
正在阅读专栏 LLVM Kaleidoscope 专栏 第 3 篇 · 共 10 篇 · 30%

Kaleidoscope:从 AST 生成 LLVM IR

发布于 2026-09-16 19:54 · 最后编辑于 2026-09-17 22:07 · 版本 v2 · 字数 7,660 · 预计阅读 16 分钟 👁 13 次阅读

Kaleidoscope:生成 LLVM IR

本章将第 2 章构建的 AST 转换为 LLVM IR,并实现 expression、prototype 和 function 的 code generation。

TL;DR

  • 每个 AST node 通过 codegen() 发出对应的 LLVM IR,并返回一个 Value *。
  • LLVMContext 管理 LLVM 的核心数据,IRBuilder 负责在当前插入点创建 instructions,Module 保存 functions 和 global variables。
  • Kaleidoscope 的所有值都是 double;< 产生 LLVM 的 i1 后,再转换为 0.0 或 1.0。
  • function definition 会创建 basic block、登记参数、生成 body、插入 ret,最后由 verifyFunction 校验。
  • 本章使用的代码要求 LLVM 3.7 或更新版本,并且教程版本应与所使用的 LLVM release 匹配。

目录

章节说明
本章简介将 AST 转为 LLVM IR
Code Generation SetupAST 的 codegen() 与 LLVM 全局对象
Expression Code Generation四类 expression 的 IR 生成
Function Code Generationprototype 和 function body 的 IR 生成
Driver 的修改与结语打印生成的 LLVM IR
完整代码清单带 LLVM code generator 的完整示例

本章简介

欢迎来到“使用 LLVM 实现一门语言”教程的第 3 章。本章展示如何将第 2 章构建的 Abstract Syntax Tree 转换成 LLVM IR。这会让你初步了解 LLVM 的工作方式,同时也会展示 LLVM 的使用有多简单。构建 lexer 和 parser 所需的工作,比生成 LLVM IR code 要多得多 :)。

请注意:本章及后续章节的代码要求 LLVM 3.7 或更新版本。LLVM 3.6 及更早版本无法运行这些代码。另外,你需要使用与 LLVM release 匹配的教程版本:如果使用官方 LLVM release,请使用该 release 附带的 documentation,或者使用 llvm.org releases 页面中的对应版本。

Code Generation Setup

为了生成 LLVM IR,我们先做一些简单的 setup。首先,在每个 AST class 中定义 virtual code generation(codegen)methods:

cpp
/// ExprAST - Base class for all expression nodes.
class ExprAST {
public:
  virtual ~ExprAST() = default;
  virtual Value *codegen() = 0;
};

/// NumberExprAST - Expression class for numeric literals like "1.0".
class NumberExprAST : public ExprAST {
  double Val;

public:
  NumberExprAST(double Val) : Val(Val) {}
  Value *codegen() override;
};
...

codegen() method 的含义是:为该 AST node 以及它所依赖的所有内容发出 IR,并且所有这些调用都会返回一个 LLVM Value object。“Value” 是 LLVM 中用来表示 Static Single Assignment(SSA)register 或 SSA value 的 class。SSA value 最显著的特点是:它的值会随着相关 instruction 的执行而计算出来,只有当该 instruction 再次执行(并且确实再次执行)时,它才会得到一个新值。换句话说,没有办法“修改”一个 SSA value。

更多信息可以自行了解 Static Single Assignment;一旦理解它,这些概念其实非常自然。

注意,除了给 ExprAST class hierarchy 添加 virtual methods,也可以使用 visitor pattern 或其他方式来建模。再次说明,本教程不会过多讨论良好的 software engineering practices:对当前目标而言,添加 virtual method 是最简单的方式。

接下来需要的是一个类似 parser 中使用的 LogError method,用于报告 code generation 过程中发现的 errors(例如使用了未声明的 parameter):

cpp
static std::unique_ptr<LLVMContext> TheContext;
static std::unique_ptr<IRBuilder<>> Builder;
static std::unique_ptr<Module> TheModule;
static std::map<std::string, Value *> NamedValues;

Value *LogErrorV(const char *Str) {
  LogError(Str);
  return nullptr;
}

这些 static variables 会在 code generation 过程中使用。TheContext 是一个 opaque object,拥有许多 LLVM 核心数据结构,例如 type table 和 constant value table。我们不需要详细理解它,只需要创建一个 instance,并将它传给需要它的 APIs。

Builder 是一个 helper object,可以方便地生成 LLVM instructions。IRBuilder class template 的 instances 会跟踪当前插入 instructions 的位置,并提供创建新 instructions 的 methods。

TheModule 是一个包含 functions 和 global variables 的 LLVM construct。从很多方面来看,它就是 LLVM IR 用来容纳 code 的 top-level structure。它负责管理我们生成的全部 IR 的内存,这也是 codegen() method 返回 raw Value* 而不是 unique_ptr<Value> 的原因。

NamedValues map 记录当前 scope 中定义了哪些 values,以及它们对应的 LLVM representation。(换句话说,它是 code 的 symbol table。)在当前版本的 Kaleidoscope 中,唯一可以被引用的内容是 function parameters。因此,在为 function body 生成 code 时,function parameters 会被放入这个 map。

有了这些基础内容,我们就可以开始讨论如何为每种 expression 生成 code。下面的内容假设 Builder 已经被设置为向某个位置生成 code。暂时先假设这一步已经完成,我们直接使用它发出 code。

Expression Code Generation

为 expression nodes 生成 LLVM code 非常直接:四种 expression node 的全部实现加起来还不到 45 行带注释的代码。先处理 numeric literals:

cpp
Value *NumberExprAST::codegen() {
  return ConstantFP::get(*TheContext, APFloat(Val));
}

在 LLVM IR 中,numeric constants 由 ConstantFP class 表示;它在内部使用 APFloat 保存 numeric value(APFloat 能够保存 Arbitrary Precision 的 floating point constants)。这段代码基本上就是创建并返回一个 ConstantFP。注意,在 LLVM IR 中,constants 会被统一去重并共享。因此,API 使用的是 foo::get(…) 这种 idiom,而不是 new foo(..) 或 foo::Create(..)。

cpp
Value *VariableExprAST::codegen() {
  // Look this variable up in the function.
  Value *V = NamedValues[Name];
  if (!V)
    LogErrorV("Unknown variable name");
  return V;
}

使用 LLVM 处理 variable references 也很简单。在 Kaleidoscope 的简单版本中,我们假设 variable 已经在某处发出 code,并且它的 value 可用。实际上,能够出现在 NamedValues map 中的唯一 values 是 function arguments。这段代码只需检查给定 name 是否在 map 中(如果不在,说明引用了 unknown variable),然后返回对应 value。

在后续章节中,我们会将 loop induction variables 和 local variables 加入 symbol table。

cpp
Value *BinaryExprAST::codegen() {
  Value *L = LHS->codegen();
  Value *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");
    // Convert bool 0/1 to double 0.0 or 1.0
    return Builder->CreateUIToFP(L, Type::getDoubleTy(*TheContext),
                                 "booltmp");
  default:
    return LogErrorV("invalid binary operator");
  }
}

Binary operators 开始变得更有意思。基本思路是:递归地为 expression 的 left-hand side 发出 code,然后为 right-hand side 发出 code,最后计算 binary expression 的结果。上面的代码对 opcode 做了一个简单的 switch,以创建正确的 LLVM instruction。

在这个示例中,LLVM builder class 的价值开始显现。IRBuilder 知道应该在哪里插入新创建的 instruction;你只需要指定要创建的 instruction(例如 CreateFAdd)、要使用的 operands(这里是 L 和 R),还可以选择性地为生成的 instruction 提供 name。

LLVM 的一个好处是,name 只是一个 hint。例如,如果上面的代码生成了多个名为 addtmp 的 variables,LLVM 会自动为每一个变量添加递增且唯一的 numeric suffix。instruction 的 local value names 完全是可选的,但它们会让 IR dump 更容易阅读。

LLVM instructions 受到严格规则约束:例如,add instruction 的 Left 和 Right operands 必须拥有相同的 type,add 的 result type 也必须与 operand types 匹配。由于 Kaleidoscope 中的所有 values 都是 doubles,因此 add、sub 和 mul 的代码非常简单。

另一方面,LLVM 规定 fcmp instruction 总是返回 i1 value(一个 one-bit integer)。问题在于,Kaleidoscope 希望得到 0.0 或 1.0 value。为了实现这种语义,我们将 fcmp instruction 与 uitofp instruction 组合起来。这个 instruction 将输入 integer 作为 unsigned value,并把它转换成 floating point value。

相反,如果使用 sitofp instruction,Kaleidoscope 的 < operator 会根据输入 value 返回 0.0 或 -1.0。

cpp
Value *CallExprAST::codegen() {
  // Look up the name in the global module table.
  Function *CalleeF = TheModule->getFunction(Callee);
  if (!CalleeF)
    return LogErrorV("Unknown function referenced");

  // If argument mismatch error.
  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");
}

使用 LLVM 为 function calls 生成 code 也相当直接。上面的代码首先在 LLVM Module 的 symbol table 中查找 function name。还记得吗,LLVM Module 是保存我们要 JIT 的 functions 的 container。让每个 function 使用用户指定的相同 name,就可以使用 LLVM symbol table 为我们解析 function names。

找到要调用的 function 后,我们递归地为每个需要传入的 argument 生成 code,并创建 LLVM call instruction。注意,LLVM 默认使用 native C calling conventions,因此这些 calls 也可以直接调用 sin、cos 等 standard library functions,不需要额外工作。

至此,Kaleidoscope 目前拥有的四种基础 expressions 就处理完了。你可以继续添加更多内容。例如,浏览 LLVM language reference,会发现还有许多其他有趣的 instructions,它们很容易接入当前的基础 framework。

Function Code Generation

为 prototypes 和 functions 生成 code 需要处理一些细节,因此它们的代码没有 expression code generation 那么简洁,但这也让我们可以说明一些重要的内容。先看 prototype 的 code generation:prototype 既用于 function bodies,也用于 external function declarations。代码从这里开始:

cpp
Function *PrototypeAST::codegen() {
  // Make the function type:  double(double,double) etc.
  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());

这几行代码包含了很多能力。首先注意,这个 function 返回 Function* 而不是 Value*。因为“prototype”描述的是 function 的 external interface(而不是 expression 计算出的 value),所以让它返回 codegen 后对应的 LLVM Function 是合理的。

调用 FunctionType::get 会创建给定 Prototype 应使用的 FunctionType。由于 Kaleidoscope 中的所有 function arguments 都是 double 类型,第一行创建了一个包含 “N” 个 LLVM double types 的 vector。然后使用 FunctionType::get 创建一个 function type:它接收 “N” 个 doubles,返回一个 double,并且不是 vararg(false 参数表示这一点)。注意,LLVM 中的 Types 和 Constants 一样也会被去重,因此不能 new 一个 type,而应该使用 get。

上面的最后一行实际创建了与 Prototype 对应的 IR Function。它指定了要使用的 type、linkage 和 name,以及要插入的 module。“external linkage”表示该 function 可以在当前 module 之外定义,或者可以被当前 module 之外的 functions 调用。传入的 Name 就是用户指定的 name;由于指定了 TheModule,这个 name 会注册到 TheModule 的 symbol table 中。

cpp
// Set names for all arguments.
unsigned Idx = 0;
for (auto &Arg : F->args())
  Arg.setName(Args[Idx++]);

return F;

最后,我们根据 Prototype 中给出的 names,为 function 的每个 arguments 设置 name。这一步并非严格必需,但保持 names 一致会让 IR 更易读,并允许后续 code 直接使用 argument names 引用它们,而不必再到 Prototype AST 中查找。

此时,我们已经有了一个没有 body 的 function prototype。这就是 LLVM IR 表示 function declarations 的方式。对于 Kaleidoscope 的 extern statements,这已经足够。但对于 function definitions,我们还需要生成并附加 function body。

cpp
Function *FunctionAST::codegen() {
    // First, check for an existing function from a previous 'extern' declaration.
  Function *TheFunction = TheModule->getFunction(Proto->getName());

  if (!TheFunction)
    TheFunction = Proto->codegen();

  if (!TheFunction)
    return nullptr;

  if (!TheFunction->empty())
    return (Function*)LogErrorV("Function cannot be redefined.");

处理 function definitions 时,我们首先在 TheModule 的 symbol table 中查找 function 的已有版本,以防它已经通过 extern statement 创建。如果 Module::getFunction 返回 null,说明不存在此前的版本,因此我们从 Prototype 生成一个。无论是哪种情况,我们都要确保这个 function 是 empty 的(也就是还没有 body),然后才能继续。

cpp
// Create a new basic block to start insertion into.
BasicBlock *BB = BasicBlock::Create(*TheContext, "entry", TheFunction);
Builder->SetInsertPoint(BB);

// Record the function arguments in the NamedValues map.
NamedValues.clear();
for (auto &Arg : TheFunction->args())
  NamedValues[std::string(Arg.getName())] = &Arg;

现在进入设置 Builder 的阶段。第一行创建一个新的 basic block(名为 entry),并将它插入 TheFunction。第二行告诉 builder:之后创建的新 instructions 应插入这个新 basic block 的末尾。

LLVM 中的 basic blocks 是定义 function Control Flow Graph 的重要组成部分。由于此时还没有 control flow,我们的 functions 目前只包含一个 block。我们会在第 5 章修复这一点 :)。

接下来,把 function arguments 加入 NamedValues map(先清空 map),这样 VariableExprAST nodes 就可以访问它们。

cpp
if (Value *RetVal = Body->codegen()) {
  // Finish off the function.
  Builder->CreateRet(RetVal);

  // Validate the generated code, checking for consistency.
  verifyFunction(*TheFunction);

  return TheFunction;
}

设置好 insertion point 并填充 NamedValues map 后,我们调用 function 的 root expression 的 codegen() method。如果没有发生 error,它会在 entry block 中生成计算该 expression 所需的 code,并返回计算出的 value。没有 error 时,我们再创建一个 LLVM ret instruction,从而完成这个 function。

function 构建完成后,调用 LLVM 提供的 verifyFunction。这个 function 会执行多种 consistency checks,判断 compiler 生成的 code 是否正确。使用它非常重要:它可以捕获许多 bugs。function 完成并通过验证后,我们返回它。

cpp
// Error reading body, remove function.
  TheFunction->eraseFromParent();
  return nullptr;
}

最后只剩 error case。为简单起见,我们直接使用 eraseFromParent method 删除刚才生成的 function。这样,用户就可以重新定义之前错误输入的 function;如果不删除它,它会带着 body 留在 symbol table 中,从而阻止后续的 redefinition。

不过,这段代码有一个 bug:如果 FunctionAST::codegen() 找到了一个已有的 IR Function,它不会将该 function 的 signature 与 definition 自己的 prototype 做校验。这意味着 earlier 的 extern declaration 会优先于 function definition 的 signature,从而可能导致 codegen 失败,例如 function arguments 使用了不同的 names。

有多种方式可以修复这个 bug,看看你能想出哪些方案!下面是一个 testcase:

text
extern foo(a);     # ok, defines foo.
def foo(b) b;      # Error: Unknown variable name. (decl using 'a' takes precedence).

Driver 的修改与结语

目前,向 LLVM 生成 code 的收益还不算多,我们只能查看 pretty IR calls。示例代码在 HandleDefinition、HandleExtern 等 functions 中插入了对 codegen 的调用,然后 dump LLVM IR。这样可以方便地查看简单 functions 对应的 LLVM IR。例如:

text
ready> 4+5;
Read top-level expression:
define double @__anon_expr() {
entry:
  ret double 9.000000e+00
}

注意,parser 会为我们把 top-level expression 转换成 anonymous functions。这在下一章添加 JIT support 时会很有用。还要注意,code 基本是被逐字转录的,除了 IRBuilder 完成的简单 constant folding 外,没有执行任何 optimizations。下一章会显式加入 optimizations。

text
ready> def foo(a b) a*a + 2*a*b + b*b;
Read function definition:
define double @foo(double %a, double %b) {
entry:
  %multmp = fmul double %a, %a
  %multmp1 = fmul double 2.000000e+00, %a
  %multmp2 = fmul double %multmp1, %b
  %addtmp = fadd double %multmp, %multmp2
  %multmp3 = fmul double %b, %b
  %addtmp4 = fadd double %addtmp, %multmp3
  ret double %addtmp4
}

这展示了一些简单的 arithmetic。注意,它与我们用于创建 instructions 的 LLVM builder calls 有着非常明显的相似性。

text
ready> def bar(a) foo(a, 4.0) + bar(31337);
Read function definition:
define double @bar(double %a) {
entry:
  %calltmp = call double @foo(double %a, double 4.000000e+00)
  %calltmp1 = call double @bar(double 3.133700e+04)
  %addtmp = fadd double %calltmp, %calltmp1
  ret double %addtmp
}

这展示了一些 function calls。如果调用它,这个 function 会花很长时间执行。将来我们会加入 conditional control flow,让 recursion 真正有用起来 :)。

text
ready> extern cos(x);
Read extern:
declare double @cos(double)

ready> cos(1.234);
Read top-level expression:
define double @__anon_expr() {
entry:
  %calltmp = call double @cos(double 1.234000e+00)
  ret double %calltmp
}

这展示了一个针对 libm 中 cos function 的 extern,以及对它的调用。

text
ready> ^D
; ModuleID = 'my cool jit'

define double @0() {
entry:
  %addtmp = fadd double 4.000000e+00, 5.000000e+00
  ret double %addtmp
}

define double @foo(double %a, double %b) {
entry:
  %multmp = fmul double %a, %a
  %multmp1 = fmul double 2.000000e+00, %a
  %multmp2 = fmul double %multmp1, %b
  %addtmp = fadd double %multmp, %multmp2
  %multmp3 = fmul double %b, %b
  %addtmp4 = fadd double %addtmp, %multmp3
  ret double %addtmp4
}

define double @bar(double %a) {
entry:
  %calltmp = call double @foo(double %a, double 4.000000e+00)
  %calltmp1 = call double @bar(double 3.133700e+04)
  %addtmp = fadd double %calltmp, %calltmp1
  ret double %addtmp
}

declare double @cos(double)

define double @1() {
entry:
  %calltmp = call double @cos(double 1.234000e+00)
  ret double %calltmp
}

退出当前 demo 时(Linux 上发送 EOF,即 CTRL+D;Windows 上发送 CTRL+Z 后按 Enter),程序会 dump 整个 module 生成的 IR。这里可以看到全貌:所有 functions 以及它们之间的引用关系。

至此,Kaleidoscope tutorial 的第 3 章结束。下一步,我们将介绍如何加入 JIT codegen 和 optimizer support,这样就可以真正运行 code 了!

完整代码清单

下面是本示例的完整代码清单,其中加入了 LLVM code generator。由于使用了 LLVM libraries,因此需要将它们链接进来。我们使用 llvm-config tool 告诉 makefile 或 command line 应该使用哪些 options:

bash
# Compile
clang++ -g -O3 toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core` -o toy
# Run
./toy

下面是代码:

cpp
#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/Type.h"
#include "llvm/IR/Verifier.h"
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <memory>
#include <string>
#include <vector>

using namespace llvm;

//===----------------------------------------------------------------------===//
// Lexer
//===----------------------------------------------------------------------===//

// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
// of these for known things.
enum Token {
  tok_eof = -1,

  // commands
  tok_def = -2,
  tok_extern = -3,

  // primary
  tok_identifier = -4,
  tok_number = -5
};

static std::string IdentifierStr; // Filled in if tok_identifier
static double NumVal;             // Filled in if tok_number

/// gettok - Return the next token from standard input.
static int gettok() {
  static int LastChar = ' ';

  // Skip any whitespace.
  while (isspace(LastChar))
    LastChar = getchar();

  if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
    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 == '.') { // Number: [0-9.]+
    std::string NumStr;
    do {
      NumStr += LastChar;
      LastChar = getchar();
    } while (isdigit(LastChar) || LastChar == '.');

    NumVal = strtod(NumStr.c_str(), nullptr);
    return tok_number;
  }

  if (LastChar == '#') {
    // Comment until end of line.
    do
      LastChar = getchar();
    while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');

    if (LastChar != EOF)
      return gettok();
  }

  // Check for end of file.  Don't eat the EOF.
  if (LastChar == EOF)
    return tok_eof;

  // Otherwise, just return the character as its ascii value.
  int ThisChar = LastChar;
  LastChar = getchar();
  return ThisChar;
}

//===----------------------------------------------------------------------===//
// Abstract Syntax Tree (aka Parse Tree)
//===----------------------------------------------------------------------===//

namespace {

/// ExprAST - Base class for all expression nodes.
class ExprAST {
public:
  virtual ~ExprAST() = default;

  virtual Value *codegen() = 0;
};

/// NumberExprAST - Expression class for numeric literals like "1.0".
class NumberExprAST : public ExprAST {
  double Val;

public:
  NumberExprAST(double Val) : Val(Val) {}

  Value *codegen() override;
};

/// VariableExprAST - Expression class for referencing a variable, like "a".
class VariableExprAST : public ExprAST {
  std::string Name;

public:
  VariableExprAST(const std::string &Name) : Name(Name) {}

  Value *codegen() override;
};

/// BinaryExprAST - Expression class for a binary operator.
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;
};

/// CallExprAST - Expression class for function calls.
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;
};

/// PrototypeAST - This class represents the "prototype" for a function,
/// which captures its name, and its argument names (thus implicitly the number
/// of arguments the function takes).
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; }
};

/// FunctionAST - This class represents a function definition itself.
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
//===----------------------------------------------------------------------===//

/// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
/// token the parser is looking at.  getNextToken reads another token from the
/// lexer and updates CurTok with its results.
static int CurTok;
static int getNextToken() { return CurTok = gettok(); }

/// BinopPrecedence - This holds the precedence for each binary operator that is
/// defined.
static std::map<char, int> BinopPrecedence;

/// GetTokPrecedence - Get the precedence of the pending binary operator token.
static int GetTokPrecedence() {
  if (!isascii(CurTok))
    return -1;

  // Make sure it's a declared binop.
  int TokPrec = BinopPrecedence[CurTok];
  if (TokPrec <= 0)
    return -1;
  return TokPrec;
}

/// LogError* - These are little helper functions for error handling.
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();

/// numberexpr ::= number
static std::unique_ptr<ExprAST> ParseNumberExpr() {
  auto Result = std::make_unique<NumberExprAST>(NumVal);
  getNextToken(); // consume the number
  return std::move(Result);
}

/// parenexpr ::= '(' expression ')'
static std::unique_ptr<ExprAST> ParseParenExpr() {
  getNextToken(); // eat (.
  auto V = ParseExpression();
  if (!V)
    return nullptr;

  if (CurTok != ')')
    return LogError("expected ')'");
  getNextToken(); // eat ).
  return V;
}

/// identifierexpr
///   ::= identifier
///   ::= identifier '(' expression* ')'
static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
  std::string IdName = IdentifierStr;

  getNextToken(); // eat identifier.

  if (CurTok != '(') // Simple variable ref.
    return std::make_unique<VariableExprAST>(IdName);
  // Call.
  getNextToken(); // eat (
  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();
    }
  }

  // Eat the ')'.
  getNextToken();

  return std::make_unique<CallExprAST>(IdName, std::move(Args));
}

/// primary
///   ::= identifierexpr
///   ::= numberexpr
///   ::= parenexpr
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();
  }
}

/// binoprhs
///   ::= ('+' primary)*
static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
                                              std::unique_ptr<ExprAST> LHS) {
  // If this is a binop, find its precedence.
  while (true) {
    int TokPrec = GetTokPrecedence();

    // If this is a binop that binds at least as tightly as the current binop,
    // consume it, otherwise we are done.
    if (TokPrec < ExprPrec)
      return LHS;

    // Okay, we know this is a binop.
    int BinOp = CurTok;
    getNextToken(); // eat binop

    // Parse the primary expression after the binary operator.
    auto RHS = ParsePrimary();
    if (!RHS)
      return nullptr;

    // If BinOp binds less tightly with RHS than the operator after RHS, let
    // the pending operator take RHS as its LHS.
    int NextPrec = GetTokPrecedence();
    if (TokPrec < NextPrec) {
      RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
      if (!RHS)
        return nullptr;
    }

    // Merge LHS/RHS.
    LHS =
        std::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
  }
}

/// expression
///   ::= primary binoprhs
///
static std::unique_ptr<ExprAST> ParseExpression() {
  auto LHS = ParsePrimary();
  if (!LHS)
    return nullptr;

  return ParseBinOpRHS(0, std::move(LHS));
}

/// prototype
///   ::= id '(' id* ')'
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");

  // success.
  getNextToken(); // eat ')'.

  return std::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
}

/// definition ::= 'def' prototype expression
static std::unique_ptr<FunctionAST> ParseDefinition() {
  getNextToken(); // eat def.
  auto Proto = ParsePrototype();
  if (!Proto)
    return nullptr;

  if (auto E = ParseExpression())
    return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
  return nullptr;
}

/// toplevelexpr ::= expression
static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
  if (auto E = ParseExpression()) {
    // Make an anonymous proto.
    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;
}

/// external ::= 'extern' prototype
static std::unique_ptr<PrototypeAST> ParseExtern() {
  getNextToken(); // eat extern.
  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;

Value *LogErrorV(const char *Str) {
  LogError(Str);
  return nullptr;
}

Value *NumberExprAST::codegen() {
  return ConstantFP::get(*TheContext, APFloat(Val));
}

Value *VariableExprAST::codegen() {
  // Look this variable up in the function.
  Value *V = NamedValues[Name];
  if (!V)
    return LogErrorV("Unknown variable name");
  return V;
}

Value *BinaryExprAST::codegen() {
  Value *L = LHS->codegen();
  Value *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");
    // Convert bool 0/1 to double 0.0 or 1.0
    return Builder->CreateUIToFP(L, Type::getDoubleTy(*TheContext), "booltmp");
  default:
    return LogErrorV("invalid binary operator");
  }
}

Value *CallExprAST::codegen() {
  // Look up the name in the global module table.
  Function *CalleeF = TheModule->getFunction(Callee);
  if (!CalleeF)
    return LogErrorV("Unknown function referenced");

  // If argument mismatch error.
  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() {
  // Make the function type:  double(double,double) etc.
  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());

  // Set names for all arguments.
  unsigned Idx = 0;
  for (auto &Arg : F->args())
    Arg.setName(Args[Idx++]);

  return F;
}

Function *FunctionAST::codegen() {
  // First, check for an existing function from a previous 'extern' declaration.
  Function *TheFunction = TheModule->getFunction(Proto->getName());

  if (!TheFunction)
    TheFunction = Proto->codegen();

  if (!TheFunction)
    return nullptr;

  if (!TheFunction->empty())
    return (Function *)LogErrorV("Function cannot be redefined.");

  // Create a new basic block to start insertion into.
  BasicBlock *BB = BasicBlock::Create(*TheContext, "entry", TheFunction);
  Builder->SetInsertPoint(BB);

  // Record the function arguments in the NamedValues map.
  NamedValues.clear();
  for (auto &Arg : TheFunction->args())
    NamedValues[std::string(Arg.getName())] = &Arg;

  if (Value *RetVal = Body->codegen()) {
    // Finish off the function.
    Builder->CreateRet(RetVal);

    // Validate the generated code, checking for consistency.
    verifyFunction(*TheFunction);

    return TheFunction;
  }

  // Error reading body, remove function.
  TheFunction->eraseFromParent();
  return nullptr;
}

//===----------------------------------------------------------------------===//
// Top-Level parsing and JIT Driver
//===----------------------------------------------------------------------===//

static void InitializeModule() {
  // Open a new context and module.
  TheContext = std::make_unique<LLVMContext>();
  TheModule = std::make_unique<Module>("my cool jit", *TheContext);

  // Create a new builder for the module.
  Builder = std::make_unique<IRBuilder<>>(*TheContext);
}

static void HandleDefinition() {
  if (auto FnAST = ParseDefinition()) {
    if (auto *FnIR = FnAST->codegen()) {
      fprintf(stderr, "Read function definition:");
      FnIR->print(errs());
      fprintf(stderr, "\n");
    }
  } 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");
    }
  } else {
    // Skip token for error recovery.
    getNextToken();
  }
}

static void HandleTopLevelExpression() {
  // Evaluate a top-level expression into an anonymous function.
  if (auto FnAST = ParseTopLevelExpr()) {
    if (auto *FnIR = FnAST->codegen()) {
      fprintf(stderr, "Read top-level expression:");
      FnIR->print(errs());
      fprintf(stderr, "\n");

      // Remove the anonymous expression.
      FnIR->eraseFromParent();
    }
  } else {
    // Skip token for error recovery.
    getNextToken();
  }
}

/// top ::= definition | external | expression | ';'
static void MainLoop() {
  while (true) {
    fprintf(stderr, "ready> ");
    switch (CurTok) {
    case tok_eof:
      return;
    case ';': // ignore top-level semicolons.
      getNextToken();
      break;
    case tok_def:
      HandleDefinition();
      break;
    case tok_extern:
      HandleExtern();
      break;
    default:
      HandleTopLevelExpression();
      break;
    }
  }
}

//===----------------------------------------------------------------------===//
// Main driver code.
//===----------------------------------------------------------------------===//

int main() {
  // 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();

  // Make the module, which holds all the code.
  InitializeModule();

  // Run the main "interpreter loop" now.
  MainLoop();

  // Print out all of the generated code.
  TheModule->print(errs(), nullptr);

  return 0;
}

下一章

LLVM Kaleidoscope:JIT 与优化器支持(待整理)

参考资料

版权说明:本文是基于 LLVM 官方教程的个人学习用途中文翻译。原文版权及许可证以 LLVM 项目官方说明为准。

← 返回列表
← 上一篇 Kaleidoscope:Parser 与 AST 下一篇 → Kaleidoscope:JIT 与优化器支持

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论