llvm.org GIT mirror llvm / b0acadc
[Kaleidoscope][BuildingAJIT] Add code for chapter 4. This chapter will cover lazy compilation directly from ASTs using the Compile Callbacks and Indirect Stubs APIs. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@271054 91177308-0d34-0410-b5e6-96231b3b80d8 Lang Hames 3 years ago
4 changed file(s) with 1479 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 add_subdirectory(Chapter1)
11 add_subdirectory(Chapter2)
22 add_subdirectory(Chapter3)
3 add_subdirectory(Chapter4)
34
0 set(LLVM_LINK_COMPONENTS
1 Analysis
2 Core
3 ExecutionEngine
4 InstCombine
5 Object
6 OrcJIT
7 RuntimeDyld
8 ScalarOpts
9 Support
10 TransformUtils
11 native
12 )
13
14 add_kaleidoscope_chapter(BuildingAJIT-Ch4
15 toy.cpp
16 )
17
18 export_executable_symbols(BuildingAJIT-Ch4)
0 //===----- KaleidoscopeJIT.h - A simple JIT for Kaleidoscope ----*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Contains a simple JIT definition for use in the kaleidoscope tutorials.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_EXECUTIONENGINE_ORC_KALEIDOSCOPEJIT_H
14 #define LLVM_EXECUTIONENGINE_ORC_KALEIDOSCOPEJIT_H
15
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ExecutionEngine/ExecutionEngine.h"
18 #include "llvm/ExecutionEngine/RuntimeDyld.h"
19 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
20 #include "llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h"
21 #include "llvm/ExecutionEngine/Orc/CompileUtils.h"
22 #include "llvm/ExecutionEngine/Orc/JITSymbol.h"
23 #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
24 #include "llvm/ExecutionEngine/Orc/IRTransformLayer.h"
25 #include "llvm/ExecutionEngine/Orc/LambdaResolver.h"
26 #include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/Mangler.h"
29 #include "llvm/Support/DynamicLibrary.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include
33 #include
34 #include
35 #include
36
37 class PrototypeAST;
38 class ExprAST;
39
40 /// FunctionAST - This class represents a function definition itself.
41 class FunctionAST {
42 std::unique_ptr Proto;
43 std::unique_ptr Body;
44
45 public:
46 FunctionAST(std::unique_ptr Proto,
47 std::unique_ptr Body)
48 : Proto(std::move(Proto)), Body(std::move(Body)) {}
49 const PrototypeAST& getProto() const;
50 const std::string& getName() const;
51 llvm::Function *codegen();
52 };
53
54 /// This will compile FnAST to IR, rename the function to add the given
55 /// suffix (needed to prevent a name-clash with the function's stub),
56 /// and then take ownership of the module that the function was compiled
57 /// into.
58 std::unique_ptr
59 irgenAndTakeOwnership(FunctionAST &FnAST, const std::string &Suffix);
60
61 namespace llvm {
62 namespace orc {
63
64 class KaleidoscopeJIT {
65 private:
66 std::unique_ptr TM;
67 const DataLayout DL;
68 std::unique_ptr CompileCallbackMgr;
69 std::unique_ptr IndirectStubsMgr;
70 ObjectLinkingLayer<> ObjectLayer;
71 IRCompileLayer CompileLayer;
72
73 typedef std::function(std::unique_ptr)>
74 OptimizeFunction;
75
76 IRTransformLayer OptimizeLayer;
77
78 public:
79 typedef decltype(OptimizeLayer)::ModuleSetHandleT ModuleHandle;
80
81 KaleidoscopeJIT()
82 : TM(EngineBuilder().selectTarget()),
83 DL(TM->createDataLayout()),
84 CompileCallbackMgr(
85 orc::createLocalCompileCallbackManager(TM->getTargetTriple(), 0)),
86 CompileLayer(ObjectLayer, SimpleCompiler(*TM)),
87 OptimizeLayer(CompileLayer,
88 [this](std::unique_ptr M) {
89 return optimizeModule(std::move(M));
90 }) {
91 auto IndirectStubsMgrBuilder =
92 orc::createLocalIndirectStubsManagerBuilder(TM->getTargetTriple());
93 IndirectStubsMgr = IndirectStubsMgrBuilder();
94 llvm::sys::DynamicLibrary::LoadLibraryPermanently(nullptr);
95 }
96
97 TargetMachine &getTargetMachine() { return *TM; }
98
99 ModuleHandle addModule(std::unique_ptr M) {
100
101 // Build our symbol resolver:
102 // Lambda 1: Look back into the JIT itself to find symbols that are part of
103 // the same "logical dylib".
104 // Lambda 2: Search for external symbols in the host process.
105 auto Resolver = createLambdaResolver(
106 [&](const std::string &Name) {
107 if (auto Sym = IndirectStubsMgr->findStub(Name, false))
108 return RuntimeDyld::SymbolInfo(Sym.getAddress(), Sym.getFlags());
109 if (auto Sym = OptimizeLayer.findSymbol(Name, false))
110 return RuntimeDyld::SymbolInfo(Sym.getAddress(), Sym.getFlags());
111 return RuntimeDyld::SymbolInfo(nullptr);
112 },
113 [](const std::string &Name) {
114 if (auto SymAddr =
115 RTDyldMemoryManager::getSymbolAddressInProcess(Name))
116 return RuntimeDyld::SymbolInfo(SymAddr, JITSymbolFlags::Exported);
117 return RuntimeDyld::SymbolInfo(nullptr);
118 });
119
120 // Build a singlton module set to hold our module.
121 std::vector> Ms;
122 Ms.push_back(std::move(M));
123
124 // Add the set to the JIT with the resolver we created above and a newly
125 // created SectionMemoryManager.
126 return OptimizeLayer.addModuleSet(std::move(Ms),
127 make_unique(),
128 std::move(Resolver));
129 }
130
131 Error addFunctionAST(std::unique_ptr FnAST) {
132 // Create a CompileCallback - this is the re-entry point into the compiler
133 // for functions that haven't been compiled yet.
134 auto CCInfo = CompileCallbackMgr->getCompileCallback();
135
136 // Create an indirect stub. This serves as the functions "canonical
137 // definition" - an unchanging (constant address) entry point to the
138 // function implementation.
139 // Initially we point the stub's function-pointer at the compile callback
140 // that we just created. In the compile action for the callback (see below)
141 // we will update the stub's function pointer to point at the function
142 // implementation that we just implemented.
143 if (auto Err = IndirectStubsMgr->createStub(mangle(FnAST->getName()),
144 CCInfo.getAddress(),
145 JITSymbolFlags::Exported))
146 return Err;
147
148 // Move ownership of FnAST to a shared pointer - C++11 lambdas don't support
149 // capture-by-move, which is be required for unique_ptr.
150 auto SharedFnAST = std::shared_ptr(std::move(FnAST));
151
152 // Set the action to compile our AST. This lambda will be run if/when
153 // execution hits the compile callback (via the stub).
154 //
155 // The steps to compile are:
156 // (1) IRGen the function.
157 // (2) Add the IR module to the JIT to make it executable like any other
158 // module.
159 // (3) Use findSymbol to get the address of the compiled function.
160 // (4) Update the stub pointer to point at the implementation so that
161 /// subsequent calls go directly to it and bypass the compiler.
162 // (5) Return the address of the implementation: this lambda will actually
163 // be run inside an attempted call to the function, and we need to
164 // continue on to the implementation to complete the attempted call.
165 // The JIT runtime (the resolver block) will use the return address of
166 // this function as the address to continue at once it has reset the
167 // CPU state to what it was immediately before the call.
168 CCInfo.setCompileAction(
169 [this, SharedFnAST]() {
170 auto M = irgenAndTakeOwnership(*SharedFnAST, "$impl");
171 addModule(std::move(M));
172 auto Sym = findSymbol(SharedFnAST->getName() + "$impl");
173 assert(Sym && "Couldn't find compiled function?");
174 TargetAddress SymAddr = Sym.getAddress();
175 if (auto Err =
176 IndirectStubsMgr->updatePointer(mangle(SharedFnAST->getName()),
177 SymAddr)) {
178 logAllUnhandledErrors(std::move(Err), errs(),
179 "Error updating function pointer: ");
180 exit(1);
181 }
182
183 return SymAddr;
184 });
185
186 return Error::success();
187 }
188
189 JITSymbol findSymbol(const std::string Name) {
190 return OptimizeLayer.findSymbol(mangle(Name), true);
191 }
192
193 void removeModule(ModuleHandle H) {
194 OptimizeLayer.removeModuleSet(H);
195 }
196
197 private:
198
199 std::string mangle(const std::string &Name) {
200 std::string MangledName;
201 raw_string_ostream MangledNameStream(MangledName);
202 Mangler::getNameWithPrefix(MangledNameStream, Name, DL);
203 return MangledNameStream.str();
204 }
205
206 std::unique_ptr optimizeModule(std::unique_ptr M) {
207 // Create a function pass manager.
208 auto FPM = llvm::make_unique(M.get());
209
210 // Add some optimizations.
211 FPM->add(createInstructionCombiningPass());
212 FPM->add(createReassociatePass());
213 FPM->add(createGVNPass());
214 FPM->add(createCFGSimplificationPass());
215 FPM->doInitialization();
216
217 // Run the optimizations over all functions in the module being added to
218 // the JIT.
219 for (auto &F : *M)
220 FPM->run(F);
221
222 return M;
223 }
224
225 };
226
227 } // end namespace orc
228 } // end namespace llvm
229
230 #endif // LLVM_EXECUTIONENGINE_ORC_KALEIDOSCOPEJIT_H
0 #include "llvm/ADT/APFloat.h"
1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/IR/BasicBlock.h"
3 #include "llvm/IR/Constants.h"
4 #include "llvm/IR/DerivedTypes.h"
5 #include "llvm/IR/Function.h"
6 #include "llvm/IR/Instructions.h"
7 #include "llvm/IR/IRBuilder.h"
8 #include "llvm/IR/LLVMContext.h"
9 #include "llvm/IR/LegacyPassManager.h"
10 #include "llvm/IR/Module.h"
11 #include "llvm/IR/Type.h"
12 #include "llvm/IR/Verifier.h"
13 #include "llvm/Support/Error.h"
14 #include "llvm/Support/TargetSelect.h"
15 #include "llvm/Target/TargetMachine.h"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Transforms/Scalar/GVN.h"
18 #include "KaleidoscopeJIT.h"
19 #include
20 #include
21 #include
22 #include
23 #include
24 #include
25 #include
26 #include
27 #include
28 #include
29
30 using namespace llvm;
31 using namespace llvm::orc;
32
33 //===----------------------------------------------------------------------===//
34 // Lexer
35 //===----------------------------------------------------------------------===//
36
37 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
38 // of these for known things.
39 enum Token {
40 tok_eof = -1,
41
42 // commands
43 tok_def = -2,
44 tok_extern = -3,
45
46 // primary
47 tok_identifier = -4,
48 tok_number = -5,
49
50 // control
51 tok_if = -6,
52 tok_then = -7,
53 tok_else = -8,
54 tok_for = -9,
55 tok_in = -10,
56
57 // operators
58 tok_binary = -11,
59 tok_unary = -12,
60
61 // var definition
62 tok_var = -13
63 };
64
65 static std::string IdentifierStr; // Filled in if tok_identifier
66 static double NumVal; // Filled in if tok_number
67
68 /// gettok - Return the next token from standard input.
69 static int gettok() {
70 static int LastChar = ' ';
71
72 // Skip any whitespace.
73 while (isspace(LastChar))
74 LastChar = getchar();
75
76 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
77 IdentifierStr = LastChar;
78 while (isalnum((LastChar = getchar())))
79 IdentifierStr += LastChar;
80
81 if (IdentifierStr == "def")
82 return tok_def;
83 if (IdentifierStr == "extern")
84 return tok_extern;
85 if (IdentifierStr == "if")
86 return tok_if;
87 if (IdentifierStr == "then")
88 return tok_then;
89 if (IdentifierStr == "else")
90 return tok_else;
91 if (IdentifierStr == "for")
92 return tok_for;
93 if (IdentifierStr == "in")
94 return tok_in;
95 if (IdentifierStr == "binary")
96 return tok_binary;
97 if (IdentifierStr == "unary")
98 return tok_unary;
99 if (IdentifierStr == "var")
100 return tok_var;
101 return tok_identifier;
102 }
103
104 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
105 std::string NumStr;
106 do {
107 NumStr += LastChar;
108 LastChar = getchar();
109 } while (isdigit(LastChar) || LastChar == '.');
110
111 NumVal = strtod(NumStr.c_str(), nullptr);
112 return tok_number;
113 }
114
115 if (LastChar == '#') {
116 // Comment until end of line.
117 do
118 LastChar = getchar();
119 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
120
121 if (LastChar != EOF)
122 return gettok();
123 }
124
125 // Check for end of file. Don't eat the EOF.
126 if (LastChar == EOF)
127 return tok_eof;
128
129 // Otherwise, just return the character as its ascii value.
130 int ThisChar = LastChar;
131 LastChar = getchar();
132 return ThisChar;
133 }
134
135 //===----------------------------------------------------------------------===//
136 // Abstract Syntax Tree (aka Parse Tree)
137 //===----------------------------------------------------------------------===//
138
139 /// ExprAST - Base class for all expression nodes.
140 class ExprAST {
141 public:
142 virtual ~ExprAST() {}
143 virtual Value *codegen() = 0;
144 };
145
146 /// NumberExprAST - Expression class for numeric literals like "1.0".
147 class NumberExprAST : public ExprAST {
148 double Val;
149
150 public:
151 NumberExprAST(double Val) : Val(Val) {}
152 Value *codegen() override;
153 };
154
155 /// VariableExprAST - Expression class for referencing a variable, like "a".
156 class VariableExprAST : public ExprAST {
157 std::string Name;
158
159 public:
160 VariableExprAST(const std::string &Name) : Name(Name) {}
161 const std::string &getName() const { return Name; }
162 Value *codegen() override;
163 };
164
165 /// UnaryExprAST - Expression class for a unary operator.
166 class UnaryExprAST : public ExprAST {
167 char Opcode;
168 std::unique_ptr Operand;
169
170 public:
171 UnaryExprAST(char Opcode, std::unique_ptr Operand)
172 : Opcode(Opcode), Operand(std::move(Operand)) {}
173 Value *codegen() override;
174 };
175
176 /// BinaryExprAST - Expression class for a binary operator.
177 class BinaryExprAST : public ExprAST {
178 char Op;
179 std::unique_ptr LHS, RHS;
180
181 public:
182 BinaryExprAST(char Op, std::unique_ptr LHS,
183 std::unique_ptr RHS)
184 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
185 Value *codegen() override;
186 };
187
188 /// CallExprAST - Expression class for function calls.
189 class CallExprAST : public ExprAST {
190 std::string Callee;
191 std::vector> Args;
192
193 public:
194 CallExprAST(const std::string &Callee,
195 std::vector> Args)
196 : Callee(Callee), Args(std::move(Args)) {}
197 Value *codegen() override;
198 };
199
200 /// IfExprAST - Expression class for if/then/else.
201 class IfExprAST : public ExprAST {
202 std::unique_ptr Cond, Then, Else;
203
204 public:
205 IfExprAST(std::unique_ptr Cond, std::unique_ptr Then,
206 std::unique_ptr Else)
207 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
208 Value *codegen() override;
209 };
210
211 /// ForExprAST - Expression class for for/in.
212 class ForExprAST : public ExprAST {
213 std::string VarName;
214 std::unique_ptr Start, End, Step, Body;
215
216 public:
217 ForExprAST(const std::string &VarName, std::unique_ptr Start,
218 std::unique_ptr End, std::unique_ptr Step,
219 std::unique_ptr Body)
220 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
221 Step(std::move(Step)), Body(std::move(Body)) {}
222 Value *codegen() override;
223 };
224
225 /// VarExprAST - Expression class for var/in
226 class VarExprAST : public ExprAST {
227 std::vector>> VarNames;
228 std::unique_ptr Body;
229
230 public:
231 VarExprAST(
232 std::vector>> VarNames,
233 std::unique_ptr Body)
234 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
235 Value *codegen() override;
236 };
237
238 /// PrototypeAST - This class represents the "prototype" for a function,
239 /// which captures its name, and its argument names (thus implicitly the number
240 /// of arguments the function takes), as well as if it is an operator.
241 class PrototypeAST {
242 std::string Name;
243 std::vector Args;
244 bool IsOperator;
245 unsigned Precedence; // Precedence if a binary op.
246
247 public:
248 PrototypeAST(const std::string &Name, std::vector Args,
249 bool IsOperator = false, unsigned Prec = 0)
250 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
251 Precedence(Prec) {}
252 Function *codegen();
253 const std::string &getName() const { return Name; }
254
255 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
256 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
257
258 char getOperatorName() const {
259 assert(isUnaryOp() || isBinaryOp());
260 return Name[Name.size() - 1];
261 }
262
263 unsigned getBinaryPrecedence() const { return Precedence; }
264 };
265
266 //===----------------------------------------------------------------------===//
267 // Parser
268 //===----------------------------------------------------------------------===//
269
270 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
271 /// token the parser is looking at. getNextToken reads another token from the
272 /// lexer and updates CurTok with its results.
273 static int CurTok;
274 static int getNextToken() { return CurTok = gettok(); }
275
276 /// BinopPrecedence - This holds the precedence for each binary operator that is
277 /// defined.
278 static std::map BinopPrecedence;
279
280 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
281 static int GetTokPrecedence() {
282 if (!isascii(CurTok))
283 return -1;
284
285 // Make sure it's a declared binop.
286 int TokPrec = BinopPrecedence[CurTok];
287 if (TokPrec <= 0)
288 return -1;
289 return TokPrec;
290 }
291
292 /// LogError* - These are little helper functions for error handling.
293 std::unique_ptr LogError(const char *Str) {
294 fprintf(stderr, "Error: %s\n", Str);
295 return nullptr;
296 }
297
298 std::unique_ptr LogErrorP(const char *Str) {
299 LogError(Str);
300 return nullptr;
301 }
302
303 static std::unique_ptr ParseExpression();
304
305 /// numberexpr ::= number
306 static std::unique_ptr ParseNumberExpr() {
307 auto Result = llvm::make_unique(NumVal);
308 getNextToken(); // consume the number
309 return std::move(Result);
310 }
311
312 /// parenexpr ::= '(' expression ')'
313 static std::unique_ptr ParseParenExpr() {
314 getNextToken(); // eat (.
315 auto V = ParseExpression();
316 if (!V)
317 return nullptr;
318
319 if (CurTok != ')')
320 return LogError("expected ')'");
321 getNextToken(); // eat ).
322 return V;
323 }
324
325 /// identifierexpr
326 /// ::= identifier
327 /// ::= identifier '(' expression* ')'
328 static std::unique_ptr ParseIdentifierExpr() {
329 std::string IdName = IdentifierStr;
330
331 getNextToken(); // eat identifier.
332
333 if (CurTok != '(') // Simple variable ref.
334 return llvm::make_unique(IdName);
335
336 // Call.
337 getNextToken(); // eat (
338 std::vector> Args;
339 if (CurTok != ')') {
340 while (true) {
341 if (auto Arg = ParseExpression())
342 Args.push_back(std::move(Arg));
343 else
344 return nullptr;
345
346 if (CurTok == ')')
347 break;
348
349 if (CurTok != ',')
350 return LogError("Expected ')' or ',' in argument list");
351 getNextToken();
352 }
353 }
354
355 // Eat the ')'.
356 getNextToken();
357
358 return llvm::make_unique(IdName, std::move(Args));
359 }
360
361 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
362 static std::unique_ptr ParseIfExpr() {
363 getNextToken(); // eat the if.
364
365 // condition.
366 auto Cond = ParseExpression();
367 if (!Cond)
368 return nullptr;
369
370 if (CurTok != tok_then)
371 return LogError("expected then");
372 getNextToken(); // eat the then
373
374 auto Then = ParseExpression();
375 if (!Then)
376 return nullptr;
377
378 if (CurTok != tok_else)
379 return LogError("expected else");
380
381 getNextToken();
382
383 auto Else = ParseExpression();
384 if (!Else)
385 return nullptr;
386
387 return llvm::make_unique(std::move(Cond), std::move(Then),
388 std::move(Else));
389 }
390
391 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
392 static std::unique_ptr ParseForExpr() {
393 getNextToken(); // eat the for.
394
395 if (CurTok != tok_identifier)
396 return LogError("expected identifier after for");
397
398 std::string IdName = IdentifierStr;
399 getNextToken(); // eat identifier.
400
401 if (CurTok != '=')
402 return LogError("expected '=' after for");
403 getNextToken(); // eat '='.
404
405 auto Start = ParseExpression();
406 if (!Start)
407 return nullptr;
408 if (CurTok != ',')
409 return LogError("expected ',' after for start value");
410 getNextToken();
411
412 auto End = ParseExpression();
413 if (!End)
414 return nullptr;
415
416 // The step value is optional.
417 std::unique_ptr Step;
418 if (CurTok == ',') {
419 getNextToken();
420 Step = ParseExpression();
421 if (!Step)
422 return nullptr;
423 }
424
425 if (CurTok != tok_in)
426 return LogError("expected 'in' after for");
427 getNextToken(); // eat 'in'.
428
429 auto Body = ParseExpression();
430 if (!Body)
431 return nullptr;
432
433 return llvm::make_unique(IdName, std::move(Start), std::move(End),
434 std::move(Step), std::move(Body));
435 }
436
437 /// varexpr ::= 'var' identifier ('=' expression)?
438 // (',' identifier ('=' expression)?)* 'in' expression
439 static std::unique_ptr ParseVarExpr() {
440 getNextToken(); // eat the var.
441
442 std::vector>> VarNames;
443
444 // At least one variable name is required.
445 if (CurTok != tok_identifier)
446 return LogError("expected identifier after var");
447
448 while (true) {
449 std::string Name = IdentifierStr;
450 getNextToken(); // eat identifier.
451
452 // Read the optional initializer.
453 std::unique_ptr Init = nullptr;
454 if (CurTok == '=') {
455 getNextToken(); // eat the '='.
456
457 Init = ParseExpression();
458 if (!Init)
459 return nullptr;
460 }
461
462 VarNames.push_back(std::make_pair(Name, std::move(Init)));
463
464 // End of var list, exit loop.
465 if (CurTok != ',')
466 break;
467 getNextToken(); // eat the ','.
468
469 if (CurTok != tok_identifier)
470 return LogError("expected identifier list after var");
471 }
472
473 // At this point, we have to have 'in'.
474 if (CurTok != tok_in)
475 return LogError("expected 'in' keyword after 'var'");
476 getNextToken(); // eat 'in'.
477
478 auto Body = ParseExpression();
479 if (!Body)
480 return nullptr;
481
482 return llvm::make_unique(std::move(VarNames), std::move(Body));
483 }
484
485 /// primary
486 /// ::= identifierexpr
487 /// ::= numberexpr
488 /// ::= parenexpr
489 /// ::= ifexpr
490 /// ::= forexpr
491 /// ::= varexpr
492 static std::unique_ptr ParsePrimary() {
493 switch (CurTok) {
494 default:
495 return LogError("unknown token when expecting an expression");
496 case tok_identifier:
497 return ParseIdentifierExpr();
498 case tok_number:
499 return ParseNumberExpr();
500 case '(':
501 return ParseParenExpr();
502 case tok_if:
503 return ParseIfExpr();
504 case tok_for:
505 return ParseForExpr();
506 case tok_var:
507 return ParseVarExpr();
508 }
509 }
510
511 /// unary
512 /// ::= primary
513 /// ::= '!' unary
514 static std::unique_ptr ParseUnary() {
515 // If the current token is not an operator, it must be a primary expr.
516 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
517 return ParsePrimary();
518
519 // If this is a unary operator, read it.
520 int Opc = CurTok;
521 getNextToken();
522 if (auto Operand = ParseUnary())
523 return llvm::make_unique(Opc, std::move(Operand));
524 return nullptr;
525 }
526
527 /// binoprhs
528 /// ::= ('+' unary)*
529 static std::unique_ptr ParseBinOpRHS(int ExprPrec,
530 std::unique_ptr LHS) {
531 // If this is a binop, find its precedence.
532 while (true) {
533 int TokPrec = GetTokPrecedence();
534
535 // If this is a binop that binds at least as tightly as the current binop,
536 // consume it, otherwise we are done.
537 if (TokPrec < ExprPrec)
538 return LHS;
539
540 // Okay, we know this is a binop.
541 int BinOp = CurTok;
542 getNextToken(); // eat binop
543
544 // Parse the unary expression after the binary operator.
545 auto RHS = ParseUnary();
546 if (!RHS)
547 return nullptr;
548
549 // If BinOp binds less tightly with RHS than the operator after RHS, let
550 // the pending operator take RHS as its LHS.
551 int NextPrec = GetTokPrecedence();
552 if (TokPrec < NextPrec) {
553 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
554 if (!RHS)
555 return nullptr;
556 }
557
558 // Merge LHS/RHS.
559 LHS =
560 llvm::make_unique(BinOp, std::move(LHS), std::move(RHS));
561 }
562 }
563
564 /// expression
565 /// ::= unary binoprhs
566 ///
567 static std::unique_ptr ParseExpression() {
568 auto LHS = ParseUnary();
569 if (!LHS)
570 return nullptr;
571
572 return ParseBinOpRHS(0, std::move(LHS));
573 }
574
575 /// prototype
576 /// ::= id '(' id* ')'
577 /// ::= binary LETTER number? (id, id)
578 /// ::= unary LETTER (id)
579 static std::unique_ptr ParsePrototype() {
580 std::string FnName;
581
582 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
583 unsigned BinaryPrecedence = 30;
584
585 switch (CurTok) {
586 default:
587 return LogErrorP("Expected function name in prototype");
588 case tok_identifier:
589 FnName = IdentifierStr;
590 Kind = 0;
591 getNextToken();
592 break;
593 case tok_unary:
594 getNextToken();
595 if (!isascii(CurTok))
596 return LogErrorP("Expected unary operator");
597 FnName = "unary";
598 FnName += (char)CurTok;
599 Kind = 1;
600 getNextToken();
601 break;
602 case tok_binary:
603 getNextToken();
604 if (!isascii(CurTok))
605 return LogErrorP("Expected binary operator");
606 FnName = "binary";
607 FnName += (char)CurTok;
608 Kind = 2;
609 getNextToken();
610
611 // Read the precedence if present.
612 if (CurTok == tok_number) {
613 if (NumVal < 1 || NumVal > 100)
614 return LogErrorP("Invalid precedecnce: must be 1..100");
615 BinaryPrecedence = (unsigned)NumVal;
616 getNextToken();
617 }
618 break;
619 }
620
621 if (CurTok != '(')
622 return LogErrorP("Expected '(' in prototype");
623
624 std::vector ArgNames;
625 while (getNextToken() == tok_identifier)
626 ArgNames.push_back(IdentifierStr);
627 if (CurTok != ')')
628 return LogErrorP("Expected ')' in prototype");
629
630 // success.
631 getNextToken(); // eat ')'.
632
633 // Verify right number of names for operator.
634 if (Kind && ArgNames.size() != Kind)
635 return LogErrorP("Invalid number of operands for operator");
636
637 return llvm::make_unique(FnName, ArgNames, Kind != 0,
638 BinaryPrecedence);
639 }
640
641 /// definition ::= 'def' prototype expression
642 static std::unique_ptr ParseDefinition() {
643 getNextToken(); // eat def.
644 auto Proto = ParsePrototype();
645 if (!Proto)
646 return nullptr;
647
648 if (auto E = ParseExpression())
649 return llvm::make_unique(std::move(Proto), std::move(E));
650 return nullptr;
651 }
652
653 /// toplevelexpr ::= expression
654 static std::unique_ptr ParseTopLevelExpr() {
655 if (auto E = ParseExpression()) {
656 // Make an anonymous proto.
657 auto Proto = llvm::make_unique("__anon_expr",
658 std::vector());
659 return llvm::make_unique(std::move(Proto), std::move(E));
660 }
661 return nullptr;
662 }
663
664 /// external ::= 'extern' prototype
665 static std::unique_ptr ParseExtern() {
666 getNextToken(); // eat extern.
667 return ParsePrototype();
668 }
669
670 //===----------------------------------------------------------------------===//
671 // Code Generation
672 //===----------------------------------------------------------------------===//
673
674 static LLVMContext TheContext;
675 static IRBuilder<> Builder(TheContext);
676 static std::unique_ptr TheModule;
677 static std::map NamedValues;
678 static std::unique_ptr TheJIT;
679 static std::map> FunctionProtos;
680 static ExitOnError ExitOnErr;
681
682 Value *LogErrorV(const char *Str) {
683 LogError(Str);
684 return nullptr;
685 }
686
687 Function *getFunction(std::string Name) {
688 // First, see if the function has already been added to the current module.
689 if (auto *F = TheModule->getFunction(Name))
690 return F;
691
692 // If not, check whether we can codegen the declaration from some existing
693 // prototype.
694 auto FI = FunctionProtos.find(Name);
695 if (FI != FunctionProtos.end())
696 return FI->second->codegen();
697
698 // If no existing prototype exists, return null.
699 return nullptr;
700 }
701
702 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
703 /// the function. This is used for mutable variables etc.
704 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
705 const std::string &VarName) {
706 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
707 TheFunction->getEntryBlock().begin());
708 return TmpB.CreateAlloca(Type::getDoubleTy(TheContext), nullptr, VarName);
709 }
710
711 Value *NumberExprAST::codegen() {
712 return ConstantFP::get(TheContext, APFloat(Val));
713 }
714
715 Value *VariableExprAST::codegen() {
716 // Look this variable up in the function.
717 Value *V = NamedValues[Name];
718 if (!V)
719 return LogErrorV("Unknown variable name");
720
721 // Load the value.
722 return Builder.CreateLoad(V, Name.c_str());
723 }
724
725 Value *UnaryExprAST::codegen() {
726 Value *OperandV = Operand->codegen();
727 if (!OperandV)
728 return nullptr;
729
730 Function *F = getFunction(std::string("unary") + Opcode);
731 if (!F)
732 return LogErrorV("Unknown unary operator");
733
734 return Builder.CreateCall(F, OperandV, "unop");
735 }
736
737 Value *BinaryExprAST::codegen() {
738 // Special case '=' because we don't want to emit the LHS as an expression.
739 if (Op == '=') {
740 // Assignment requires the LHS to be an identifier.
741 // This assume we're building without RTTI because LLVM builds that way by
742 // default. If you build LLVM with RTTI this can be changed to a
743 // dynamic_cast for automatic error checking.
744 VariableExprAST *LHSE = static_cast(LHS.get());
745 if (!LHSE)
746 return LogErrorV("destination of '=' must be a variable");
747 // Codegen the RHS.
748 Value *Val = RHS->codegen();
749 if (!Val)
750 return nullptr;
751
752 // Look up the name.
753 Value *Variable = NamedValues[LHSE->getName()];
754 if (!Variable)
755 return LogErrorV("Unknown variable name");
756
757 Builder.CreateStore(Val, Variable);
758 return Val;
759 }
760
761 Value *L = LHS->codegen();
762 Value *R = RHS->codegen();
763 if (!L || !R)
764 return nullptr;
765
766 switch (Op) {
767 case '+':
768 return Builder.CreateFAdd(L, R, "addtmp");
769 case '-':
770 return Builder.CreateFSub(L, R, "subtmp");
771 case '*':
772 return Builder.CreateFMul(L, R, "multmp");
773 case '<':
774 L = Builder.CreateFCmpULT(L, R, "cmptmp");
775 // Convert bool 0/1 to double 0.0 or 1.0
776 return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext), "booltmp");
777 default:
778 break;
779 }
780
781 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
782 // a call to it.
783 Function *F = getFunction(std::string("binary") + Op);
784 assert(F && "binary operator not found!");
785
786 Value *Ops[] = {L, R};
787 return Builder.CreateCall(F, Ops, "binop");
788 }
789
790 Value *CallExprAST::codegen() {
791 // Look up the name in the global module table.
792 Function *CalleeF = getFunction(Callee);
793 if (!CalleeF)
794 return LogErrorV("Unknown function referenced");
795
796 // If argument mismatch error.
797 if (CalleeF->arg_size() != Args.size())
798 return LogErrorV("Incorrect # arguments passed");
799
800 std::vector ArgsV;
801 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
802 ArgsV.push_back(Args[i]->codegen());
803 if (!ArgsV.back())
804 return nullptr;
805 }
806
807 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
808 }
809
810 Value *IfExprAST::codegen() {
811 Value *CondV = Cond->codegen();
812 if (!CondV)
813 return nullptr;
814
815 // Convert condition to a bool by comparing equal to 0.0.
816 CondV = Builder.CreateFCmpONE(
817 CondV, ConstantFP::get(TheContext, APFloat(0.0)), "ifcond");
818
819 Function *TheFunction = Builder.GetInsertBlock()->getParent();
820
821 // Create blocks for the then and else cases. Insert the 'then' block at the
822 // end of the function.
823 BasicBlock *ThenBB = BasicBlock::Create(TheContext, "then", TheFunction);
824 BasicBlock *ElseBB = BasicBlock::Create(TheContext, "else");
825 BasicBlock *MergeBB = BasicBlock::Create(TheContext, "ifcont");
826
827 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
828
829 // Emit then value.
830 Builder.SetInsertPoint(ThenBB);
831
832 Value *ThenV = Then->codegen();
833 if (!ThenV)
834 return nullptr;
835
836 Builder.CreateBr(MergeBB);
837 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
838 ThenBB = Builder.GetInsertBlock();
839
840 // Emit else block.
841 TheFunction->getBasicBlockList().push_back(ElseBB);
842 Builder.SetInsertPoint(ElseBB);
843
844 Value *ElseV = Else->codegen();
845 if (!ElseV)
846 return nullptr;
847
848 Builder.CreateBr(MergeBB);
849 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
850 ElseBB = Builder.GetInsertBlock();
851
852 // Emit merge block.
853 TheFunction->getBasicBlockList().push_back(MergeBB);
854 Builder.SetInsertPoint(MergeBB);
855 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(TheContext), 2, "iftmp");
856
857 PN->addIncoming(ThenV, ThenBB);
858 PN->addIncoming(ElseV, ElseBB);
859 return PN;
860 }
861
862 // Output for-loop as:
863 // var = alloca double
864 // ...
865 // start = startexpr
866 // store start -> var
867 // goto loop
868 // loop:
869 // ...
870 // bodyexpr
871 // ...
872 // loopend:
873 // step = stepexpr
874 // endcond = endexpr
875 //
876 // curvar = load var
877 // nextvar = curvar + step
878 // store nextvar -> var
879 // br endcond, loop, endloop
880 // outloop:
881 Value *ForExprAST::codegen() {
882 Function *TheFunction = Builder.GetInsertBlock()->getParent();
883
884 // Create an alloca for the variable in the entry block.
885 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
886
887 // Emit the start code first, without 'variable' in scope.
888 Value *StartVal = Start->codegen();
889 if (!StartVal)
890 return nullptr;
891
892 // Store the value into the alloca.
893 Builder.CreateStore(StartVal, Alloca);
894
895 // Make the new basic block for the loop header, inserting after current
896 // block.
897 BasicBlock *LoopBB = BasicBlock::Create(TheContext, "loop", TheFunction);
898
899 // Insert an explicit fall through from the current block to the LoopBB.
900 Builder.CreateBr(LoopBB);
901
902 // Start insertion in LoopBB.
903 Builder.SetInsertPoint(LoopBB);
904
905 // Within the loop, the variable is defined equal to the PHI node. If it
906 // shadows an existing variable, we have to restore it, so save it now.
907 AllocaInst *OldVal = NamedValues[VarName];
908 NamedValues[VarName] = Alloca;
909
910 // Emit the body of the loop. This, like any other expr, can change the
911 // current BB. Note that we ignore the value computed by the body, but don't
912 // allow an error.
913 if (!Body->codegen())
914 return nullptr;
915
916 // Emit the step value.
917 Value *StepVal = nullptr;
918 if (Step) {
919 StepVal = Step->codegen();
920 if (!StepVal)
921 return nullptr;
922 } else {
923 // If not specified, use 1.0.
924 StepVal = ConstantFP::get(TheContext, APFloat(1.0));
925 }
926
927 // Compute the end condition.
928 Value *EndCond = End->codegen();
929 if (!EndCond)
930 return nullptr;
931
932 // Reload, increment, and restore the alloca. This handles the case where
933 // the body of the loop mutates the variable.
934 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
935 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
936 Builder.CreateStore(NextVar, Alloca);
937
938 // Convert condition to a bool by comparing equal to 0.0.
939 EndCond = Builder.CreateFCmpONE(
940 EndCond, ConstantFP::get(TheContext, APFloat(0.0)), "loopcond");
941
942 // Create the "after loop" block and insert it.
943 BasicBlock *AfterBB =
944 BasicBlock::Create(TheContext, "afterloop", TheFunction);
945
946 // Insert the conditional branch into the end of LoopEndBB.
947 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
948
949 // Any new code will be inserted in AfterBB.
950 Builder.SetInsertPoint(AfterBB);
951
952 // Restore the unshadowed variable.
953 if (OldVal)
954 NamedValues[VarName] = OldVal;
955 else
956 NamedValues.erase(VarName);
957
958 // for expr always returns 0.0.
959 return Constant::getNullValue(Type::getDoubleTy(TheContext));
960 }
961
962 Value *VarExprAST::codegen() {
963 std::vector OldBindings;
964
965 Function *TheFunction = Builder.GetInsertBlock()->getParent();
966
967 // Register all variables and emit their initializer.
968 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
969 const std::string &VarName = VarNames[i].first;
970 ExprAST *Init = VarNames[i].second.get();
971
972 // Emit the initializer before adding the variable to scope, this prevents
973 // the initializer from referencing the variable itself, and permits stuff
974 // like this:
975 // var a = 1 in
976 // var a = a in ... # refers to outer 'a'.
977 Value *InitVal;
978 if (Init) {
979 InitVal = Init->codegen();
980 if (!InitVal)
981 return nullptr;
982 } else { // If not specified, use 0.0.
983 InitVal = ConstantFP::get(TheContext, APFloat(0.0));
984 }
985
986 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
987 Builder.CreateStore(InitVal, Alloca);
988
989 // Remember the old variable binding so that we can restore the binding when
990 // we unrecurse.
991 OldBindings.push_back(NamedValues[VarName]);
992
993 // Remember this binding.
994 NamedValues[VarName] = Alloca;
995 }
996
997 // Codegen the body, now that all vars are in scope.
998 Value *BodyVal = Body->codegen();
999 if (!BodyVal)
1000 return nullptr;
1001
1002 // Pop all our variables from scope.
1003 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1004 NamedValues[VarNames[i].first] = OldBindings[i];
1005
1006 // Return the body computation.
1007 return BodyVal;
1008 }
1009
1010 Function *PrototypeAST::codegen() {
1011 // Make the function type: double(double,double) etc.
1012 std::vector Doubles(Args.size(), Type::getDoubleTy(TheContext));
1013 FunctionType *FT =
1014 FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);
1015
1016 Function *F =
1017 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
1018
1019 // Set names for all arguments.
1020 unsigned Idx = 0;
1021 for (auto &Arg : F->args())
1022 Arg.setName(Args[Idx++]);
1023
1024 return F;
1025 }
1026
1027 const PrototypeAST& FunctionAST::getProto() const {
1028 return *Proto;
1029 }
1030
1031 const std::string& FunctionAST::getName() const {
1032 return Proto->getName();
1033 }
1034
1035 Function *FunctionAST::codegen() {
1036 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
1037 // reference to it for use below.
1038 auto &P = *Proto;
1039 Function *TheFunction = getFunction(P.getName());
1040 if (!TheFunction)
1041 return nullptr;
1042
1043 // If this is an operator, install it.
1044 if (P.isBinaryOp())
1045 BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
1046
1047 // Create a new basic block to start insertion into.
1048 BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
1049 Builder.SetInsertPoint(BB);
1050
1051 // Record the function arguments in the NamedValues map.
1052 NamedValues.clear();
1053 for (auto &Arg : TheFunction->args()) {
1054 // Create an alloca for this variable.
1055 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName());
1056
1057 // Store the initial value into the alloca.
1058 Builder.CreateStore(&Arg, Alloca);
1059
1060 // Add arguments to variable symbol table.
1061 NamedValues[Arg.getName()] = Alloca;
1062 }
1063
1064 if (Value *RetVal = Body->codegen()) {
1065 // Finish off the function.
1066 Builder.CreateRet(RetVal);
1067
1068 // Validate the generated code, checking for consistency.
1069 verifyFunction(*TheFunction);
1070
1071 return TheFunction;
1072 }
1073
1074 // Error reading body, remove function.
1075 TheFunction->eraseFromParent();
1076
1077 if (P.isBinaryOp())
1078 BinopPrecedence.erase(Proto->getOperatorName());
1079 return nullptr;
1080 }
1081
1082 //===----------------------------------------------------------------------===//
1083 // Top-Level parsing and JIT Driver
1084 //===----------------------------------------------------------------------===//
1085
1086 static void InitializeModule() {
1087 // Open a new module.
1088 TheModule = llvm::make_unique("my cool jit", TheContext);
1089 TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
1090 }
1091
1092 std::unique_ptr
1093 irgenAndTakeOwnership(FunctionAST &FnAST, const std::string &Suffix) {
1094 if (auto *F = FnAST.codegen()) {
1095 F->setName(F->getName() + Suffix);
1096 auto M = std::move(TheModule);
1097 // Start a new module.
1098 InitializeModule();
1099 return M;
1100 } else
1101 report_fatal_error("Couldn't compile lazily JIT'd function");
1102 }
1103
1104 static void HandleDefinition() {
1105 if (auto FnAST = ParseDefinition()) {
1106 FunctionProtos[FnAST->getProto().getName()] =
1107 llvm::make_unique(FnAST->getProto());
1108 ExitOnErr(TheJIT->addFunctionAST(std::move(FnAST)));
1109 } else {
1110 // Skip token for error recovery.
1111 getNextToken();
1112 }
1113 }
1114
1115 static void HandleExtern() {
1116 if (auto ProtoAST = ParseExtern()) {
1117 if (auto *FnIR = ProtoAST->codegen()) {
1118 fprintf(stderr, "Read extern: ");
1119 FnIR->dump();
1120 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
1121 }
1122 } else {
1123 // Skip token for error recovery.
1124 getNextToken();
1125 }
1126 }
1127
1128 static void HandleTopLevelExpression() {
1129 // Evaluate a top-level expression into an anonymous function.
1130 if (auto FnAST = ParseTopLevelExpr()) {
1131 FunctionProtos[FnAST->getName()] =
1132 llvm::make_unique(FnAST->getProto());
1133 if (FnAST->codegen()) {
1134 // JIT the module containing the anonymous expression, keeping a handle so
1135 // we can free it later.
1136 auto H = TheJIT->addModule(std::move(TheModule));
1137 InitializeModule();
1138
1139 // Search the JIT for the __anon_expr symbol.
1140 auto ExprSymbol = TheJIT->findSymbol("__anon_expr");
1141 assert(ExprSymbol && "Function not found");
1142
1143 // Get the symbol's address and cast it to the right type (takes no
1144 // arguments, returns a double) so we can call it as a native function.
1145 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
1146 fprintf(stderr, "Evaluated to %f\n", FP());
1147
1148 // Delete the anonymous expression module from the JIT.
1149 TheJIT->removeModule(H);
1150 }
1151 } else {
1152 // Skip token for error recovery.
1153 getNextToken();
1154 }
1155 }
1156
1157 /// top ::= definition | external | expression | ';'
1158 static void MainLoop() {
1159 while (true) {
1160 fprintf(stderr, "ready> ");
1161 switch (CurTok) {
1162 case tok_eof:
1163 return;
1164 case ';': // ignore top-level semicolons.
1165 getNextToken();
1166 break;
1167 case tok_def:
1168 HandleDefinition();
1169 break;
1170 case tok_extern:
1171 HandleExtern();
1172 break;
1173 default:
1174 HandleTopLevelExpression();
1175 break;
1176 }
1177 }
1178 }
1179
1180 //===----------------------------------------------------------------------===//
1181 // "Library" functions that can be "extern'd" from user code.
1182 //===----------------------------------------------------------------------===//
1183
1184 /// putchard - putchar that takes a double and returns 0.
1185 extern "C" double putchard(double X) {
1186 fputc((char)X, stderr);
1187 return 0;
1188 }
1189
1190 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1191 extern "C" double printd(double X) {
1192 fprintf(stderr, "%f\n", X);
1193 return 0;
1194 }
1195
1196 //===----------------------------------------------------------------------===//
1197 // Main driver code.
1198 //===----------------------------------------------------------------------===//
1199
1200 int main() {
1201 InitializeNativeTarget();
1202 InitializeNativeTargetAsmPrinter();
1203 InitializeNativeTargetAsmParser();
1204
1205 ExitOnErr.setBanner("Kaleidoscope: ");
1206
1207 // Install standard binary operators.
1208 // 1 is lowest precedence.
1209 BinopPrecedence['='] = 2;
1210 BinopPrecedence['<'] = 10;
1211 BinopPrecedence['+'] = 20;
1212 BinopPrecedence['-'] = 20;
1213 BinopPrecedence['*'] = 40; // highest.
1214
1215 // Prime the first token.
1216 fprintf(stderr, "ready> ");
1217 getNextToken();
1218
1219 TheJIT = llvm::make_unique();
1220
1221 InitializeModule();
1222
1223 // Run the main "interpreter loop" now.
1224 MainLoop();
1225
1226 return 0;
1227 }