llvm.org GIT mirror llvm / 44364a3
[Kaleidoscope] Clang-format the Kaleidoscope tutorials. Also reduces changes between tutorial chapters. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@245472 91177308-0d34-0410-b5e6-96231b3b80d8 Lang Hames 4 years ago
17 changed file(s) with 860 addition(s) and 614 deletion(s). Raw diff Collapse all Expand all
168168 tok_eof = -1,
169169
170170 // commands
171 tok_def = -2, tok_extern = -3,
171 tok_def = -2,
172 tok_extern = -3,
172173
173174 // primary
174 tok_identifier = -4, tok_number = -5,
175 tok_identifier = -4,
176 tok_number = -5,
175177 };
176178
177 static std::string IdentifierStr; // Filled in if tok_identifier
178 static double NumVal; // Filled in if tok_number
179 static std::string IdentifierStr; // Filled in if tok_identifier
180 static double NumVal; // Filled in if tok_number
179181
180182 Each token returned by our lexer will either be one of the Token enum
181183 values or it will be an 'unknown' character like '+', which is returned
216218 while (isalnum((LastChar = getchar())))
217219 IdentifierStr += LastChar;
218220
219 if (IdentifierStr == "def") return tok_def;
220 if (IdentifierStr == "extern") return tok_extern;
221 if (IdentifierStr == "def")
222 return tok_def;
223 if (IdentifierStr == "extern")
224 return tok_extern;
221225 return tok_identifier;
222226 }
223227
249253
250254 if (LastChar == '#') {
251255 // Comment until end of line.
252 do LastChar = getchar();
256 do
257 LastChar = getchar();
253258 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
254259
255260 if (LastChar != EOF)
4343 /// NumberExprAST - Expression class for numeric literals like "1.0".
4444 class NumberExprAST : public ExprAST {
4545 double Val;
46
4647 public:
4748 NumberExprAST(double Val) : Val(Val) {}
4849 };
6465 /// VariableExprAST - Expression class for referencing a variable, like "a".
6566 class VariableExprAST : public ExprAST {
6667 std::string Name;
68
6769 public:
6870 VariableExprAST(const std::string &Name) : Name(Name) {}
6971 };
7274 class BinaryExprAST : public ExprAST {
7375 char Op;
7476 std::unique_ptr LHS, RHS;
77
7578 public:
7679 BinaryExprAST(char op, std::unique_ptr LHS,
7780 std::unique_ptr RHS)
8285 class CallExprAST : public ExprAST {
8386 std::string Callee;
8487 std::vector Args;
88
8589 public:
8690 CallExprAST(const std::string &Callee,
8791 std::vector> Args)
110114 class PrototypeAST {
111115 std::string Name;
112116 std::vector Args;
117
113118 public:
114119 PrototypeAST(const std::string &name, std::vector Args)
115120 : Name(name), Args(std::move(Args)) {}
119124 class FunctionAST {
120125 std::unique_ptr Proto;
121126 std::unique_ptr Body;
127
122128 public:
123129 FunctionAST(std::unique_ptr Proto,
124130 std::unique_ptr Body)
170176
171177
172178 /// Error* - These are little helper functions for error handling.
173 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
174 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
175 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
179 std::unique_ptr Error(const char *Str) {
180 fprintf(stderr, "Error: %s\n", Str);
181 return nullptr;
182 }
183 std::unique_ptr ErrorP(const char *Str) {
184 Error(Str);
185 return nullptr;
186 }
176187
177188 The ``Error`` routines are simple helper routines that our parser will
178189 use to handle errors. The error recovery in our parser will not be the
215226
216227 /// parenexpr ::= '(' expression ')'
217228 static std::unique_ptr ParseParenExpr() {
218 getNextToken(); // eat (.
229 getNextToken(); // eat (.
219230 auto V = ParseExpression();
220 if (!V) return nullptr;
231 if (!V)
232 return nullptr;
221233
222234 if (CurTok != ')')
223235 return Error("expected ')'");
224 getNextToken(); // eat ).
236 getNextToken(); // eat ).
225237 return V;
226238 }
227239
266278 std::vector> Args;
267279 if (CurTok != ')') {
268280 while (1) {
269 auto Arg = ParseExpression();
270 if (!Arg) return nullptr;
271 Args.push_back(std::move(Arg));
272
273 if (CurTok == ')') break;
281 if (auto Arg = ParseExpression())
282 Args.push_back(std::move(Arg));
283 else
284 return nullptr;
285
286 if (CurTok == ')')
287 break;
274288
275289 if (CurTok != ',')
276290 return Error("Expected ')' or ',' in argument list");
308322 /// ::= parenexpr
309323 static std::unique_ptr ParsePrimary() {
310324 switch (CurTok) {
311 default: return Error("unknown token when expecting an expression");
312 case tok_identifier: return ParseIdentifierExpr();
313 case tok_number: return ParseNumberExpr();
314 case '(': return ParseParenExpr();
325 default:
326 return Error("unknown token when expecting an expression");
327 case tok_identifier:
328 return ParseIdentifierExpr();
329 case tok_number:
330 return ParseNumberExpr();
331 case '(':
332 return ParseParenExpr();
315333 }
316334 }
317335
395413 ///
396414 static std::unique_ptr ParseExpression() {
397415 auto LHS = ParsePrimary();
398 if (!LHS) return nullptr;
416 if (!LHS)
417 return nullptr;
399418
400419 return ParseBinOpRHS(0, std::move(LHS));
401420 }
445464
446465 // Parse the primary expression after the binary operator.
447466 auto RHS = ParsePrimary();
448 if (!RHS) return nullptr;
467 if (!RHS)
468 return nullptr;
449469
450470 As such, this code eats (and remembers) the binary operator and then
451471 parses the primary expression that follows. This builds up the whole
504524 int NextPrec = GetTokPrecedence();
505525 if (TokPrec < NextPrec) {
506526 RHS = ParseBinOpRHS(TokPrec+1, std::move(RHS));
507 if (RHS == 0) return 0;
527 if (!RHS)
528 return nullptr;
508529 }
509530 // Merge LHS/RHS.
510531 LHS = llvm::make_unique(BinOp, std::move(LHS),
632653 while (1) {
633654 fprintf(stderr, "ready> ");
634655 switch (CurTok) {
635 case tok_eof: return;
636 case ';': getNextToken(); break; // ignore top-level semicolons.
637 case tok_def: HandleDefinition(); break;
638 case tok_extern: HandleExtern(); break;
639 default: HandleTopLevelExpression(); break;
656 case tok_eof:
657 return;
658 case ';': // ignore top-level semicolons.
659 getNextToken();
660 break;
661 case tok_def:
662 HandleDefinition();
663 break;
664 case tok_extern:
665 HandleExtern();
666 break;
667 default:
668 HandleTopLevelExpression();
669 break;
640670 }
641671 }
642672 }
4040 /// NumberExprAST - Expression class for numeric literals like "1.0".
4141 class NumberExprAST : public ExprAST {
4242 double Val;
43
4344 public:
4445 NumberExprAST(double Val) : Val(Val) {}
4546 virtual Value *Codegen();
7172
7273 .. code-block:: c++
7374
74 Value *ErrorV(const char *Str) { Error(Str); return 0; }
75 Value *ErrorV(const char *Str) {
76 Error(Str);
77 return nullptr;
78 }
7579
7680 static Module *TheModule;
7781 static IRBuilder<> Builder(getGlobalContext());
144148 Value *BinaryExprAST::Codegen() {
145149 Value *L = LHS->Codegen();
146150 Value *R = RHS->Codegen();
147 if (L == 0 || R == 0) return 0;
151 if (!L || !R)
152 return nullptr;
148153
149154 switch (Op) {
150 case '+': return Builder.CreateFAdd(L, R, "addtmp");
151 case '-': return Builder.CreateFSub(L, R, "subtmp");
152 case '*': return Builder.CreateFMul(L, R, "multmp");
155 case '+':
156 return Builder.CreateFAdd(L, R, "addtmp");
157 case '-':
158 return Builder.CreateFSub(L, R, "subtmp");
159 case '*':
160 return Builder.CreateFMul(L, R, "multmp");
153161 case '<':
154162 L = Builder.CreateFCmpULT(L, R, "cmptmp");
155163 // Convert bool 0/1 to double 0.0 or 1.0
156164 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
157165 "booltmp");
158 default: return ErrorV("invalid binary operator");
166 default:
167 return ErrorV("invalid binary operator");
159168 }
160169 }
161170
200209 Value *CallExprAST::Codegen() {
201210 // Look up the name in the global module table.
202211 Function *CalleeF = TheModule->getFunction(Callee);
203 if (CalleeF == 0)
212 if (!CalleeF)
204213 return ErrorV("Unknown function referenced");
205214
206215 // If argument mismatch error.
207216 if (CalleeF->arg_size() != Args.size())
208217 return ErrorV("Incorrect # arguments passed");
209218
210 std::vector*> ArgsV;
219 std::vector *> ArgsV;
211220 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
212221 ArgsV.push_back(Args[i]->Codegen());
213 if (ArgsV.back() == 0) return 0;
222 if (!ArgsV.back())
223 return nullptr;
214224 }
215225
216226 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
252262 // Make the function type: double(double,double) etc.
253263 std::vector Doubles(Args.size(),
254264 Type::getDoubleTy(getGlobalContext()));
255 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
256 Doubles, false);
257
258 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
265 FunctionType *FT =
266 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
267
268 Function *F =
269 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
259270
260271 This code packs a lot of power into a few lines. Note first that this
261272 function returns a "Function\*" instead of a "Value\*". Because a
320331 // If F already has a body, reject this.
321332 if (!F->empty()) {
322333 ErrorF("redefinition of function");
323 return 0;
334 return nullptr;
324335 }
325336
326337 // If F took a different number of args, reject.
327338 if (F->arg_size() != Args.size()) {
328339 ErrorF("redefinition of function with different # args");
329 return 0;
340 return nullptr;
330341 }
331342 }
332343
350361 // Add arguments to variable symbol table.
351362 NamedValues[Args[Idx]] = AI;
352363 }
364
353365 return F;
354366 }
355367
367379 NamedValues.clear();
368380
369381 Function *TheFunction = Proto->Codegen();
370 if (TheFunction == 0)
371 return 0;
382 if (!TheFunction)
383 return nullptr;
372384
373385 Code generation for function definitions starts out simply enough: we
374386 just codegen the prototype (Proto) and verify that it is ok. We then
422434
423435 // Error reading body, remove function.
424436 TheFunction->eraseFromParent();
425 return 0;
437 return nullptr;
426438 }
427439
428440 The only piece left here is handling of the error case. For simplicity,
399399 .. code-block:: c++
400400
401401 /// putchard - putchar that takes a double and returns 0.
402 extern "C"
403 double putchard(double X) {
402 extern "C" double putchard(double X) {
404403 putchar((char)X);
405404 return 0;
406405 }
6565 .. code-block:: c++
6666
6767 // control
68 tok_if = -6, tok_then = -7, tok_else = -8,
68 tok_if = -6,
69 tok_then = -7,
70 tok_else = -8,
6971
7072 Once we have that, we recognize the new keywords in the lexer. This is
7173 pretty simple stuff:
7375 .. code-block:: c++
7476
7577 ...
76 if (IdentifierStr == "def") return tok_def;
77 if (IdentifierStr == "extern") return tok_extern;
78 if (IdentifierStr == "if") return tok_if;
79 if (IdentifierStr == "then") return tok_then;
80 if (IdentifierStr == "else") return tok_else;
78 if (IdentifierStr == "def")
79 return tok_def;
80 if (IdentifierStr == "extern")
81 return tok_extern;
82 if (IdentifierStr == "if")
83 return tok_if;
84 if (IdentifierStr == "then")
85 return tok_then;
86 if (IdentifierStr == "else")
87 return tok_else;
8188 return tok_identifier;
8289
8390 AST Extensions for If/Then/Else
9097 /// IfExprAST - Expression class for if/then/else.
9198 class IfExprAST : public ExprAST {
9299 std::unique Cond, Then, Else;
100
93101 public:
94102 IfExprAST(std::unique_ptr Cond, std::unique_ptr Then,
95103 std::unique_ptr Else)
114122
115123 // condition.
116124 auto Cond = ParseExpression();
117 if (!Cond) return nullptr;
125 if (!Cond)
126 return nullptr;
118127
119128 if (CurTok != tok_then)
120129 return Error("expected then");
121130 getNextToken(); // eat the then
122131
123132 auto Then = ParseExpression();
124 if (Then) return nullptr;
133 if (!Then)
134 return nullptr;
125135
126136 if (CurTok != tok_else)
127137 return Error("expected else");
129139 getNextToken();
130140
131141 auto Else = ParseExpression();
132 if (!Else) return nullptr;
142 if (!Else)
143 return nullptr;
133144
134145 return llvm::make_unique(std::move(Cond), std::move(Then),
135146 std::move(Else));
141152
142153 static std::unique_ptr ParsePrimary() {
143154 switch (CurTok) {
144 default: return Error("unknown token when expecting an expression");
145 case tok_identifier: return ParseIdentifierExpr();
146 case tok_number: return ParseNumberExpr();
147 case '(': return ParseParenExpr();
148 case tok_if: return ParseIfExpr();
155 default:
156 return Error("unknown token when expecting an expression");
157 case tok_identifier:
158 return ParseIdentifierExpr();
159 case tok_number:
160 return ParseNumberExpr();
161 case '(':
162 return ParseParenExpr();
163 case tok_if:
164 return ParseIfExpr();
149165 }
150166 }
151167
270286
271287 Value *IfExprAST::Codegen() {
272288 Value *CondV = Cond->Codegen();
273 if (!CondV) return nullptr;
289 if (!CondV)
290 return nullptr;
274291
275292 // Convert condition to a bool by comparing equal to 0.0.
276 CondV = Builder.CreateFCmpONE(CondV,
277 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
278 "ifcond");
293 CondV = Builder.CreateFCmpONE(
294 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
279295
280296 This code is straightforward and similar to what we saw before. We emit
281297 the expression for the condition, then compare that value to zero to get
287303
288304 // Create blocks for the then and else cases. Insert the 'then' block at the
289305 // end of the function.
290 BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
306 BasicBlock *ThenBB =
307 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
291308 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
292309 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
293310
320337 Builder.SetInsertPoint(ThenBB);
321338
322339 Value *ThenV = Then->Codegen();
323 if (ThenV == 0) return 0;
340 if (!ThenV)
341 return nullptr;
324342
325343 Builder.CreateBr(MergeBB);
326344 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
361379 Builder.SetInsertPoint(ElseBB);
362380
363381 Value *ElseV = Else->Codegen();
364 if (ElseV == 0) return 0;
382 if (!ElseV)
383 return nullptr;
365384
366385 Builder.CreateBr(MergeBB);
367386 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
379398 // Emit merge block.
380399 TheFunction->getBasicBlockList().push_back(MergeBB);
381400 Builder.SetInsertPoint(MergeBB);
382 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
383 "iftmp");
401 PHINode *PN =
402 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
384403
385404 PN->addIncoming(ThenV, ThenBB);
386405 PN->addIncoming(ElseV, ElseBB);
445464 tok_for = -9, tok_in = -10
446465
447466 ... in gettok ...
448 if (IdentifierStr == "def") return tok_def;
449 if (IdentifierStr == "extern") return tok_extern;
450 if (IdentifierStr == "if") return tok_if;
451 if (IdentifierStr == "then") return tok_then;
452 if (IdentifierStr == "else") return tok_else;
453 if (IdentifierStr == "for") return tok_for;
454 if (IdentifierStr == "in") return tok_in;
467 if (IdentifierStr == "def")
468 return tok_def;
469 if (IdentifierStr == "extern")
470 return tok_extern;
471 if (IdentifierStr == "if")
472 return tok_if;
473 if (IdentifierStr == "then")
474 return tok_then;
475 if (IdentifierStr == "else")
476 return tok_else;
477 if (IdentifierStr == "for")
478 return tok_for;
479 if (IdentifierStr == "in")
480 return tok_in;
455481 return tok_identifier;
456482
457483 AST Extensions for the 'for' Loop
466492 class ForExprAST : public ExprAST {
467493 std::string VarName;
468494 std::unique_ptr Start, End, Step, Body;
495
469496 public:
470497 ForExprAST(const std::string &VarName, std::unique_ptr Start,
471498 std::unique_ptr End, std::unique_ptr Step,
501528
502529
503530 auto Start = ParseExpression();
504 if (!Start) return nullptr;
531 if (!Start)
532 return nullptr;
505533 if (CurTok != ',')
506534 return Error("expected ',' after for start value");
507535 getNextToken();
508536
509537 auto End = ParseExpression();
510 if (!End) return nullptr;
538 if (!End)
539 return nullptr;
511540
512541 // The step value is optional.
513542 std::unique_ptr Step;
514543 if (CurTok == ',') {
515544 getNextToken();
516545 Step = ParseExpression();
517 if (!Step) return nullptr;
546 if (!Step)
547 return nullptr;
518548 }
519549
520550 if (CurTok != tok_in)
522552 getNextToken(); // eat 'in'.
523553
524554 auto Body = ParseExpression();
525 if (!Body) return nullptr;
555 if (!Body)
556 return nullptr;
526557
527558 return llvm::make_unique(IdName, std::move(Start),
528559 std::move(End), std::move(Step),
592623 // block.
593624 Function *TheFunction = Builder.GetInsertBlock()->getParent();
594625 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
595 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
626 BasicBlock *LoopBB =
627 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
596628
597629 // Insert an explicit fall through from the current block to the LoopBB.
598630 Builder.CreateBr(LoopBB);
609641 Builder.SetInsertPoint(LoopBB);
610642
611643 // Start the PHI node with an entry for Start.
612 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str());
644 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
645 2, VarName.c_str());
613646 Variable->addIncoming(StartVal, PreheaderBB);
614647
615648 Now that the "preheader" for the loop is set up, we switch to emitting
629662 // Emit the body of the loop. This, like any other expr, can change the
630663 // current BB. Note that we ignore the value computed by the body, but don't
631664 // allow an error.
632 if (Body->Codegen() == 0)
633 return 0;
665 if (!Body->Codegen())
666 return nullptr;
634667
635668 Now the code starts to get more interesting. Our 'for' loop introduces a
636669 new variable to the symbol table. This means that our symbol table can
652685 .. code-block:: c++
653686
654687 // Emit the step value.
655 Value *StepVal;
688 Value *StepVal = nullptr;
656689 if (Step) {
657690 StepVal = Step->Codegen();
658 if (StepVal == 0) return 0;
691 if (!StepVal)
692 return nullptr;
659693 } else {
660694 // If not specified, use 1.0.
661695 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
672706
673707 // Compute the end condition.
674708 Value *EndCond = End->Codegen();
675 if (EndCond == 0) return EndCond;
709 if (!EndCond)
710 return nullptr;
676711
677712 // Convert condition to a bool by comparing equal to 0.0.
678 EndCond = Builder.CreateFCmpONE(EndCond,
679 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
680 "loopcond");
713 EndCond = Builder.CreateFCmpONE(
714 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
681715
682716 Finally, we evaluate the exit value of the loop, to determine whether
683717 the loop should exit. This mirrors the condition evaluation for the
687721
688722 // Create the "after loop" block and insert it.
689723 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
690 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
724 BasicBlock *AfterBB =
725 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
691726
692727 // Insert the conditional branch into the end of LoopEndBB.
693728 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
9595 enum Token {
9696 ...
9797 // operators
98 tok_binary = -11, tok_unary = -12
98 tok_binary = -11,
99 tok_unary = -12
99100 };
100101 ...
101102 static int gettok() {
102103 ...
103 if (IdentifierStr == "for") return tok_for;
104 if (IdentifierStr == "in") return tok_in;
105 if (IdentifierStr == "binary") return tok_binary;
106 if (IdentifierStr == "unary") return tok_unary;
104 if (IdentifierStr == "for")
105 return tok_for;
106 if (IdentifierStr == "in")
107 return tok_in;
108 if (IdentifierStr == "binary")
109 return tok_binary;
110 if (IdentifierStr == "unary")
111 return tok_unary;
107112 return tok_identifier;
108113
109114 This just adds lexer support for the unary and binary keywords, like we
130135 std::vector Args;
131136 bool IsOperator;
132137 unsigned Precedence; // Precedence if a binary op.
138
133139 public:
134140 PrototypeAST(const std::string &name, std::vector Args,
135141 bool IsOperator = false, unsigned Prec = 0)
210216 if (Kind && ArgNames.size() != Kind)
211217 return ErrorP("Invalid number of operands for operator");
212218
213 return llvm::make_unique(FnName, std::move(ArgNames),
214 Kind != 0, BinaryPrecedence);
219 return llvm::make_unique(FnName, std::move(ArgNames), Kind != 0,
220 BinaryPrecedence);
215221 }
216222
217223 This is all fairly straightforward parsing code, and we have already
231237 Value *BinaryExprAST::Codegen() {
232238 Value *L = LHS->Codegen();
233239 Value *R = RHS->Codegen();
234 if (L == 0 || R == 0) return 0;
240 if (!L || !R)
241 return nullptr;
235242
236243 switch (Op) {
237 case '+': return Builder.CreateFAdd(L, R, "addtmp");
238 case '-': return Builder.CreateFSub(L, R, "subtmp");
239 case '*': return Builder.CreateFMul(L, R, "multmp");
244 case '+':
245 return Builder.CreateFAdd(L, R, "addtmp");
246 case '-':
247 return Builder.CreateFSub(L, R, "subtmp");
248 case '*':
249 return Builder.CreateFMul(L, R, "multmp");
240250 case '<':
241251 L = Builder.CreateFCmpULT(L, R, "cmptmp");
242252 // Convert bool 0/1 to double 0.0 or 1.0
243253 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
244254 "booltmp");
245 default: break;
255 default:
256 break;
246257 }
247258
248259 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
249260 // a call to it.
250 Function *F = TheModule->getFunction(std::string("binary")+Op);
261 Function *F = TheModule->getFunction(std::string("binary") + Op);
251262 assert(F && "binary operator not found!");
252263
253264 Value *Ops[2] = { L, R };
268279 NamedValues.clear();
269280
270281 Function *TheFunction = Proto->Codegen();
271 if (TheFunction == 0)
272 return 0;
282 if (!TheFunction)
283 return nullptr;
273284
274285 // If this is an operator, install it.
275286 if (Proto->isBinaryOp())
307318 class UnaryExprAST : public ExprAST {
308319 char Opcode;
309320 std::unique_ptr Operand;
321
310322 public:
311323 UnaryExprAST(char Opcode, std::unique_ptr Operand)
312324 : Opcode(Opcode), Operand(std::move(Operand)) {}
356368 ...
357369 // Parse the unary expression after the binary operator.
358370 auto RHS = ParseUnary();
359 if (!RHS) return nullptr;
371 if (!RHS)
372 return nullptr;
360373 ...
361374 }
362375 /// expression
364377 ///
365378 static std::unique_ptr ParseExpression() {
366379 auto LHS = ParseUnary();
367 if (!LHS) return nullptr;
380 if (!LHS)
381 return nullptr;
368382
369383 return ParseBinOpRHS(0, std::move(LHS));
370384 }
415429
416430 Value *UnaryExprAST::Codegen() {
417431 Value *OperandV = Operand->Codegen();
418 if (OperandV == 0) return 0;
432 if (!OperandV)
433 return nullptr;
419434
420435 Function *F = TheModule->getFunction(std::string("unary")+Opcode);
421 if (F == 0)
436 if (!F)
422437 return ErrorV("Unknown unary operator");
423438
424439 return Builder.CreateCall(F, OperandV, "unop");
357357 Value *VariableExprAST::Codegen() {
358358 // Look this variable up in the function.
359359 Value *V = NamedValues[Name];
360 if (V == 0) return ErrorV("Unknown variable name");
360 if (!V)
361 return ErrorV("Unknown variable name");
361362
362363 // Load the value.
363364 return Builder.CreateLoad(V, Name.c_str());
377378
378379 // Emit the start code first, without 'variable' in scope.
379380 Value *StartVal = Start->Codegen();
380 if (StartVal == 0) return 0;
381 if (!StartVal)
382 return nullptr;
381383
382384 // Store the value into the alloca.
383385 Builder.CreateStore(StartVal, Alloca);
385387
386388 // Compute the end condition.
387389 Value *EndCond = End->Codegen();
388 if (EndCond == 0) return EndCond;
390 if (!EndCond)
391 return nullptr;
389392
390393 // Reload, increment, and restore the alloca. This handles the case where
391394 // the body of the loop mutates the variable.
587590
588591 // Codegen the RHS.
589592 Value *Val = RHS->Codegen();
590 if (Val == 0) return 0;
593 if (!Val)
594 return nullptr;
591595
592596 // Look up the name.
593597 Value *Variable = NamedValues[LHSE->getName()];
594 if (Variable == 0) return ErrorV("Unknown variable name");
598 if (!Variable)
599 return ErrorV("Unknown variable name");
595600
596601 Builder.CreateStore(Val, Variable);
597602 return Val;
648653 ...
649654 static int gettok() {
650655 ...
651 if (IdentifierStr == "in") return tok_in;
652 if (IdentifierStr == "binary") return tok_binary;
653 if (IdentifierStr == "unary") return tok_unary;
654 if (IdentifierStr == "var") return tok_var;
656 if (IdentifierStr == "in")
657 return tok_in;
658 if (IdentifierStr == "binary")
659 return tok_binary;
660 if (IdentifierStr == "unary")
661 return tok_unary;
662 if (IdentifierStr == "var")
663 return tok_var;
655664 return tok_identifier;
656665 ...
657666
664673 class VarExprAST : public ExprAST {
665674 std::vector>> VarNames;
666675 std::unique_ptr Body;
676
667677 public:
668678 VarExprAST(std::vector>> VarNames,
669679 std::unique_ptr body)
691701 /// ::= varexpr
692702 static std::unique_ptr ParsePrimary() {
693703 switch (CurTok) {
694 default: return Error("unknown token when expecting an expression");
695 case tok_identifier: return ParseIdentifierExpr();
696 case tok_number: return ParseNumberExpr();
697 case '(': return ParseParenExpr();
698 case tok_if: return ParseIfExpr();
699 case tok_for: return ParseForExpr();
700 case tok_var: return ParseVarExpr();
704 default:
705 return Error("unknown token when expecting an expression");
706 case tok_identifier:
707 return ParseIdentifierExpr();
708 case tok_number:
709 return ParseNumberExpr();
710 case '(':
711 return ParseParenExpr();
712 case tok_if:
713 return ParseIfExpr();
714 case tok_for:
715 return ParseForExpr();
716 case tok_var:
717 return ParseVarExpr();
701718 }
702719 }
703720
755772 getNextToken(); // eat 'in'.
756773
757774 auto Body = ParseExpression();
758 if (!Body) return nullptr;
775 if (!Body)
776 return nullptr;
759777
760778 return llvm::make_unique(std::move(VarNames),
761779 std::move(Body));
790808 Value *InitVal;
791809 if (Init) {
792810 InitVal = Init->Codegen();
793 if (InitVal == 0) return 0;
811 if (!InitVal)
812 return nullptr;
794813 } else { // If not specified, use 0.0.
795814 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
796815 }
815834
816835 // Codegen the body, now that all vars are in scope.
817836 Value *BodyVal = Body->Codegen();
818 if (BodyVal == 0) return 0;
837 if (!BodyVal)
838 return nullptr;
819839
820840 Finally, before returning, we restore the previous variable bindings:
821841
306306 SourceLocation Loc;
307307
308308 public:
309 ExprAST(SourceLocation Loc = CurLoc) : Loc(Loc) {}
310 virtual ~ExprAST() {}
311 virtual Value* Codegen() = 0;
309312 int getLine() const { return Loc.Line; }
310313 int getCol() const { return Loc.Col; }
311 ExprAST(SourceLocation Loc = CurLoc) : Loc(Loc) {}
312 virtual std::ostream &dump(std::ostream &out, int ind) {
314 virtual raw_ostream &dump(raw_ostream &out, int ind) {
313315 return out << ':' << getLine() << ':' << getCol() << '\n';
314316 }
315317
398400 DILocalVariable D = DBuilder->createParameterVariable(
399401 Scope, Args[Idx], Idx + 1, Unit, Line, KSDbgInfo.getDoubleTy(), true);
400402
401 Instruction *Call = DBuilder->insertDeclare(
402 Alloca, D, DBuilder->createExpression(), Builder.GetInsertBlock());
403 Call->setDebugLoc(DebugLoc::get(Line, 0, Scope));
403 DBuilder->insertDeclare(Alloca, D, DBuilder->createExpression(),
404 DebugLoc::get(Line, 0, Scope),
405 Builder.GetInsertBlock());
404406
405407 Here we're doing a few things. First, we're grabbing our current scope
406408 for the variable so we can say what range of code our variable is valid
408410 the name, source location, type, and since it's an argument, the argument
409411 index. Third, we create an ``lvm.dbg.declare`` call to indicate at the IR
410412 level that we've got a variable in an alloca (and it gives a starting
411 location for the variable). Lastly, we set a source location for the
413 location for the variable), and setting a source location for the
412414 beginning of the scope on the declare.
413415
414416 One interesting thing to note at this point is that various debuggers have
0 set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-private-field")
1
2 add_kaleidoscope_chapter(Kaleidoscope-Ch2
13 toy.cpp
24 )
99 TOOLNAME = Kaleidoscope-Ch2
1010 EXAMPLE_TOOL = 1
1111
12 LLVM_CXXFLAGS := -Wno-unused-private-field
13
1214 include $(LEVEL)/Makefile.common
1414 tok_eof = -1,
1515
1616 // commands
17 tok_def = -2, tok_extern = -3,
17 tok_def = -2,
18 tok_extern = -3,
1819
1920 // primary
20 tok_identifier = -4, tok_number = -5
21 };
22
23 static std::string IdentifierStr; // Filled in if tok_identifier
24 static double NumVal; // Filled in if tok_number
21 tok_identifier = -4,
22 tok_number = -5
23 };
24
25 static std::string IdentifierStr; // Filled in if tok_identifier
26 static double NumVal; // Filled in if tok_number
2527
2628 /// gettok - Return the next token from standard input.
2729 static int gettok() {
3638 while (isalnum((LastChar = getchar())))
3739 IdentifierStr += LastChar;
3840
39 if (IdentifierStr == "def") return tok_def;
40 if (IdentifierStr == "extern") return tok_extern;
41 if (IdentifierStr == "def")
42 return tok_def;
43 if (IdentifierStr == "extern")
44 return tok_extern;
4145 return tok_identifier;
4246 }
4347
44 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
48 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
4549 std::string NumStr;
4650 do {
4751 NumStr += LastChar;
5458
5559 if (LastChar == '#') {
5660 // Comment until end of line.
57 do LastChar = getchar();
61 do
62 LastChar = getchar();
5863 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
59
64
6065 if (LastChar != EOF)
6166 return gettok();
6267 }
63
68
6469 // Check for end of file. Don't eat the EOF.
6570 if (LastChar == EOF)
6671 return tok_eof;
8388
8489 /// NumberExprAST - Expression class for numeric literals like "1.0".
8590 class NumberExprAST : public ExprAST {
86 public:
87 NumberExprAST(double Val) {}
91 double Val;
92
93 public:
94 NumberExprAST(double Val) : Val(Val) {}
8895 };
8996
9097 /// VariableExprAST - Expression class for referencing a variable, like "a".
9198 class VariableExprAST : public ExprAST {
9299 std::string Name;
100
93101 public:
94102 VariableExprAST(const std::string &Name) : Name(Name) {}
95103 };
96104
97105 /// BinaryExprAST - Expression class for a binary operator.
98106 class BinaryExprAST : public ExprAST {
107 char Op;
108 std::unique_ptr LHS, RHS;
109
99110 public:
100111 BinaryExprAST(char Op, std::unique_ptr LHS,
101 std::unique_ptr RHS) {}
112 std::unique_ptr RHS)
113 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
102114 };
103115
104116 /// CallExprAST - Expression class for function calls.
105117 class CallExprAST : public ExprAST {
106118 std::string Callee;
107119 std::vector> Args;
120
108121 public:
109122 CallExprAST(const std::string &Callee,
110123 std::vector> Args)
111 : Callee(Callee), Args(std::move(Args)) {}
124 : Callee(Callee), Args(std::move(Args)) {}
112125 };
113126
114127 /// PrototypeAST - This class represents the "prototype" for a function,
117130 class PrototypeAST {
118131 std::string Name;
119132 std::vector Args;
133
120134 public:
121135 PrototypeAST(const std::string &Name, std::vector Args)
122 : Name(Name), Args(std::move(Args)) {}
123
136 : Name(Name), Args(std::move(Args)) {}
124137 };
125138
126139 /// FunctionAST - This class represents a function definition itself.
127140 class FunctionAST {
141 std::unique_ptr Proto;
142 std::unique_ptr Body;
143
128144 public:
129145 FunctionAST(std::unique_ptr Proto,
130 std::unique_ptr Body) {}
146 std::unique_ptr Body)
147 : Proto(std::move(Proto)), Body(std::move(Body)) {}
131148 };
132149 } // end anonymous namespace
133150
139156 /// token the parser is looking at. getNextToken reads another token from the
140157 /// lexer and updates CurTok with its results.
141158 static int CurTok;
142 static int getNextToken() {
143 return CurTok = gettok();
144 }
159 static int getNextToken() { return CurTok = gettok(); }
145160
146161 /// BinopPrecedence - This holds the precedence for each binary operator that is
147162 /// defined.
151166 static int GetTokPrecedence() {
152167 if (!isascii(CurTok))
153168 return -1;
154
169
155170 // Make sure it's a declared binop.
156171 int TokPrec = BinopPrecedence[CurTok];
157 if (TokPrec <= 0) return -1;
172 if (TokPrec <= 0)
173 return -1;
158174 return TokPrec;
159175 }
160176
169185 }
170186
171187 static std::unique_ptr ParseExpression();
188
189 /// numberexpr ::= number
190 static std::unique_ptr ParseNumberExpr() {
191 auto Result = llvm::make_unique(NumVal);
192 getNextToken(); // consume the number
193 return std::move(Result);
194 }
195
196 /// parenexpr ::= '(' expression ')'
197 static std::unique_ptr ParseParenExpr() {
198 getNextToken(); // eat (.
199 auto V = ParseExpression();
200 if (!V)
201 return nullptr;
202
203 if (CurTok != ')')
204 return Error("expected ')'");
205 getNextToken(); // eat ).
206 return V;
207 }
172208
173209 /// identifierexpr
174210 /// ::= identifier
175211 /// ::= identifier '(' expression* ')'
176212 static std::unique_ptr ParseIdentifierExpr() {
177213 std::string IdName = IdentifierStr;
178
179 getNextToken(); // eat identifier.
180
214
215 getNextToken(); // eat identifier.
216
181217 if (CurTok != '(') // Simple variable ref.
182218 return llvm::make_unique(IdName);
183
219
184220 // Call.
185 getNextToken(); // eat (
221 getNextToken(); // eat (
186222 std::vector> Args;
187223 if (CurTok != ')') {
188224 while (1) {
191227 else
192228 return nullptr;
193229
194 if (CurTok == ')') break;
230 if (CurTok == ')')
231 break;
195232
196233 if (CurTok != ',')
197234 return Error("Expected ')' or ',' in argument list");
201238
202239 // Eat the ')'.
203240 getNextToken();
204
241
205242 return llvm::make_unique(IdName, std::move(Args));
206 }
207
208 /// numberexpr ::= number
209 static std::unique_ptr ParseNumberExpr() {
210 auto Result = llvm::make_unique(NumVal);
211 getNextToken(); // consume the number
212 return std::move(Result);
213 }
214
215 /// parenexpr ::= '(' expression ')'
216 static std::unique_ptr ParseParenExpr() {
217 getNextToken(); // eat (.
218 auto V = ParseExpression();
219 if (!V)
220 return nullptr;
221
222 if (CurTok != ')')
223 return Error("expected ')'");
224 getNextToken(); // eat ).
225 return V;
226243 }
227244
228245 /// primary
231248 /// ::= parenexpr
232249 static std::unique_ptr ParsePrimary() {
233250 switch (CurTok) {
234 default: return Error("unknown token when expecting an expression");
235 case tok_identifier: return ParseIdentifierExpr();
236 case tok_number: return ParseNumberExpr();
237 case '(': return ParseParenExpr();
251 default:
252 return Error("unknown token when expecting an expression");
253 case tok_identifier:
254 return ParseIdentifierExpr();
255 case tok_number:
256 return ParseNumberExpr();
257 case '(':
258 return ParseParenExpr();
238259 }
239260 }
240261
245266 // If this is a binop, find its precedence.
246267 while (1) {
247268 int TokPrec = GetTokPrecedence();
248
269
249270 // If this is a binop that binds at least as tightly as the current binop,
250271 // consume it, otherwise we are done.
251272 if (TokPrec < ExprPrec)
252273 return LHS;
253
274
254275 // Okay, we know this is a binop.
255276 int BinOp = CurTok;
256 getNextToken(); // eat binop
257
277 getNextToken(); // eat binop
278
258279 // Parse the primary expression after the binary operator.
259280 auto RHS = ParsePrimary();
260 if (!RHS) return nullptr;
261
281 if (!RHS)
282 return nullptr;
283
262284 // If BinOp binds less tightly with RHS than the operator after RHS, let
263285 // the pending operator take RHS as its LHS.
264286 int NextPrec = GetTokPrecedence();
265287 if (TokPrec < NextPrec) {
266 RHS = ParseBinOpRHS(TokPrec+1, std::move(RHS));
267 if (!RHS) return nullptr;
288 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
289 if (!RHS)
290 return nullptr;
268291 }
269
292
270293 // Merge LHS/RHS.
271 LHS = llvm::make_unique(BinOp, std::move(LHS),
272 std::move(RHS));
294 LHS =
295 llvm::make_unique(BinOp, std::move(LHS), std::move(RHS));
273296 }
274297 }
275298
278301 ///
279302 static std::unique_ptr ParseExpression() {
280303 auto LHS = ParsePrimary();
281 if (!LHS) return nullptr;
282
304 if (!LHS)
305 return nullptr;
306
283307 return ParseBinOpRHS(0, std::move(LHS));
284308 }
285309
291315
292316 std::string FnName = IdentifierStr;
293317 getNextToken();
294
318
295319 if (CurTok != '(')
296320 return ErrorP("Expected '(' in prototype");
297
321
298322 std::vector ArgNames;
299323 while (getNextToken() == tok_identifier)
300324 ArgNames.push_back(IdentifierStr);
301325 if (CurTok != ')')
302326 return ErrorP("Expected ')' in prototype");
303
327
304328 // success.
305 getNextToken(); // eat ')'.
306
307 return llvm::make_unique(std::move(FnName),
308 std::move(ArgNames));
329 getNextToken(); // eat ')'.
330
331 return llvm::make_unique(FnName, std::move(ArgNames));
309332 }
310333
311334 /// definition ::= 'def' prototype expression
312335 static std::unique_ptr ParseDefinition() {
313 getNextToken(); // eat def.
336 getNextToken(); // eat def.
314337 auto Proto = ParsePrototype();
315 if (!Proto) return nullptr;
338 if (!Proto)
339 return nullptr;
316340
317341 if (auto E = ParseExpression())
318342 return llvm::make_unique(std::move(Proto), std::move(E));
323347 static std::unique_ptr ParseTopLevelExpr() {
324348 if (auto E = ParseExpression()) {
325349 // Make an anonymous proto.
326 auto Proto = llvm::make_unique("",
327 std::vector());
350 auto Proto =
351 llvm::make_unique("", std::vector());
328352 return llvm::make_unique(std::move(Proto), std::move(E));
329353 }
330354 return nullptr;
332356
333357 /// external ::= 'extern' prototype
334358 static std::unique_ptr ParseExtern() {
335 getNextToken(); // eat extern.
359 getNextToken(); // eat extern.
336360 return ParsePrototype();
337361 }
338362
373397 while (1) {
374398 fprintf(stderr, "ready> ");
375399 switch (CurTok) {
376 case tok_eof: return;
377 case ';': getNextToken(); break; // ignore top-level semicolons.
378 case tok_def: HandleDefinition(); break;
379 case tok_extern: HandleExtern(); break;
380 default: HandleTopLevelExpression(); break;
400 case tok_eof:
401 return;
402 case ';': // ignore top-level semicolons.
403 getNextToken();
404 break;
405 case tok_def:
406 HandleDefinition();
407 break;
408 case tok_extern:
409 HandleExtern();
410 break;
411 default:
412 HandleTopLevelExpression();
413 break;
381414 }
382415 }
383416 }
392425 BinopPrecedence['<'] = 10;
393426 BinopPrecedence['+'] = 20;
394427 BinopPrecedence['-'] = 20;
395 BinopPrecedence['*'] = 40; // highest.
428 BinopPrecedence['*'] = 40; // highest.
396429
397430 // Prime the first token.
398431 fprintf(stderr, "ready> ");
2020 tok_eof = -1,
2121
2222 // commands
23 tok_def = -2, tok_extern = -3,
23 tok_def = -2,
24 tok_extern = -3,
2425
2526 // primary
26 tok_identifier = -4, tok_number = -5
27 };
28
29 static std::string IdentifierStr; // Filled in if tok_identifier
30 static double NumVal; // Filled in if tok_number
27 tok_identifier = -4,
28 tok_number = -5
29 };
30
31 static std::string IdentifierStr; // Filled in if tok_identifier
32 static double NumVal; // Filled in if tok_number
3133
3234 /// gettok - Return the next token from standard input.
3335 static int gettok() {
4244 while (isalnum((LastChar = getchar())))
4345 IdentifierStr += LastChar;
4446
45 if (IdentifierStr == "def") return tok_def;
46 if (IdentifierStr == "extern") return tok_extern;
47 if (IdentifierStr == "def")
48 return tok_def;
49 if (IdentifierStr == "extern")
50 return tok_extern;
4751 return tok_identifier;
4852 }
4953
50 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
54 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
5155 std::string NumStr;
5256 do {
5357 NumStr += LastChar;
6064
6165 if (LastChar == '#') {
6266 // Comment until end of line.
63 do LastChar = getchar();
67 do
68 LastChar = getchar();
6469 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
65
70
6671 if (LastChar != EOF)
6772 return gettok();
6873 }
69
74
7075 // Check for end of file. Don't eat the EOF.
7176 if (LastChar == EOF)
7277 return tok_eof;
9196 /// NumberExprAST - Expression class for numeric literals like "1.0".
9297 class NumberExprAST : public ExprAST {
9398 double Val;
99
94100 public:
95101 NumberExprAST(double Val) : Val(Val) {}
96102 Value *Codegen() override;
99105 /// VariableExprAST - Expression class for referencing a variable, like "a".
100106 class VariableExprAST : public ExprAST {
101107 std::string Name;
108
102109 public:
103110 VariableExprAST(const std::string &Name) : Name(Name) {}
104111 Value *Codegen() override;
108115 class BinaryExprAST : public ExprAST {
109116 char Op;
110117 std::unique_ptr LHS, RHS;
118
111119 public:
112120 BinaryExprAST(char Op, std::unique_ptr LHS,
113121 std::unique_ptr RHS)
114 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
122 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
115123 Value *Codegen() override;
116124 };
117125
119127 class CallExprAST : public ExprAST {
120128 std::string Callee;
121129 std::vector> Args;
130
122131 public:
123132 CallExprAST(const std::string &Callee,
124133 std::vector> Args)
125 : Callee(Callee), Args(std::move(Args)) {}
134 : Callee(Callee), Args(std::move(Args)) {}
126135 Value *Codegen() override;
127136 };
128137
132141 class PrototypeAST {
133142 std::string Name;
134143 std::vector Args;
144
135145 public:
136146 PrototypeAST(const std::string &Name, std::vector Args)
137 : Name(Name), Args(std::move(Args)) {}
138
147 : Name(Name), Args(std::move(Args)) {}
139148 Function *Codegen();
140149 };
141150
143152 class FunctionAST {
144153 std::unique_ptr Proto;
145154 std::unique_ptr Body;
155
146156 public:
147157 FunctionAST(std::unique_ptr Proto,
148158 std::unique_ptr Body)
149 : Proto(std::move(Proto)), Body(std::move(Body)) {}
150
159 : Proto(std::move(Proto)), Body(std::move(Body)) {}
151160 Function *Codegen();
152161 };
153162 } // end anonymous namespace
160169 /// token the parser is looking at. getNextToken reads another token from the
161170 /// lexer and updates CurTok with its results.
162171 static int CurTok;
163 static int getNextToken() {
164 return CurTok = gettok();
165 }
172 static int getNextToken() { return CurTok = gettok(); }
166173
167174 /// BinopPrecedence - This holds the precedence for each binary operator that is
168175 /// defined.
172179 static int GetTokPrecedence() {
173180 if (!isascii(CurTok))
174181 return -1;
175
182
176183 // Make sure it's a declared binop.
177184 int TokPrec = BinopPrecedence[CurTok];
178 if (TokPrec <= 0) return -1;
185 if (TokPrec <= 0)
186 return -1;
179187 return TokPrec;
180188 }
181189
194202 }
195203
196204 static std::unique_ptr ParseExpression();
205
206 /// numberexpr ::= number
207 static std::unique_ptr ParseNumberExpr() {
208 auto Result = llvm::make_unique(NumVal);
209 getNextToken(); // consume the number
210 return std::move(Result);
211 }
212
213 /// parenexpr ::= '(' expression ')'
214 static std::unique_ptr ParseParenExpr() {
215 getNextToken(); // eat (.
216 auto V = ParseExpression();
217 if (!V)
218 return nullptr;
219
220 if (CurTok != ')')
221 return Error("expected ')'");
222 getNextToken(); // eat ).
223 return V;
224 }
197225
198226 /// identifierexpr
199227 /// ::= identifier
200228 /// ::= identifier '(' expression* ')'
201229 static std::unique_ptr ParseIdentifierExpr() {
202230 std::string IdName = IdentifierStr;
203
204 getNextToken(); // eat identifier.
205
231
232 getNextToken(); // eat identifier.
233
206234 if (CurTok != '(') // Simple variable ref.
207235 return llvm::make_unique(IdName);
208
236
209237 // Call.
210 getNextToken(); // eat (
238 getNextToken(); // eat (
211239 std::vector> Args;
212240 if (CurTok != ')') {
213241 while (1) {
216244 else
217245 return nullptr;
218246
219 if (CurTok == ')') break;
247 if (CurTok == ')')
248 break;
220249
221250 if (CurTok != ',')
222251 return Error("Expected ')' or ',' in argument list");
226255
227256 // Eat the ')'.
228257 getNextToken();
229
258
230259 return llvm::make_unique(IdName, std::move(Args));
231 }
232
233 /// numberexpr ::= number
234 static std::unique_ptr ParseNumberExpr() {
235 auto Result = llvm::make_unique(NumVal);
236 getNextToken(); // consume the number
237 return std::move(Result);
238 }
239
240 /// parenexpr ::= '(' expression ')'
241 static std::unique_ptr ParseParenExpr() {
242 getNextToken(); // eat (.
243 auto V = ParseExpression();
244 if (!V)
245 return nullptr;
246
247 if (CurTok != ')')
248 return Error("expected ')'");
249 getNextToken(); // eat ).
250 return V;
251260 }
252261
253262 /// primary
256265 /// ::= parenexpr
257266 static std::unique_ptr ParsePrimary() {
258267 switch (CurTok) {
259 default: return Error("unknown token when expecting an expression");
260 case tok_identifier: return ParseIdentifierExpr();
261 case tok_number: return ParseNumberExpr();
262 case '(': return ParseParenExpr();
268 default:
269 return Error("unknown token when expecting an expression");
270 case tok_identifier:
271 return ParseIdentifierExpr();
272 case tok_number:
273 return ParseNumberExpr();
274 case '(':
275 return ParseParenExpr();
263276 }
264277 }
265278
270283 // If this is a binop, find its precedence.
271284 while (1) {
272285 int TokPrec = GetTokPrecedence();
273
286
274287 // If this is a binop that binds at least as tightly as the current binop,
275288 // consume it, otherwise we are done.
276289 if (TokPrec < ExprPrec)
277290 return LHS;
278
291
279292 // Okay, we know this is a binop.
280293 int BinOp = CurTok;
281 getNextToken(); // eat binop
282
294 getNextToken(); // eat binop
295
283296 // Parse the primary expression after the binary operator.
284297 auto RHS = ParsePrimary();
285 if (!RHS) return nullptr;
286
298 if (!RHS)
299 return nullptr;
300
287301 // If BinOp binds less tightly with RHS than the operator after RHS, let
288302 // the pending operator take RHS as its LHS.
289303 int NextPrec = GetTokPrecedence();
290304 if (TokPrec < NextPrec) {
291 RHS = ParseBinOpRHS(TokPrec+1, std::move(RHS));
292 if (!RHS) return nullptr;
293 }
294
305 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
306 if (!RHS)
307 return nullptr;
308 }
309
295310 // Merge LHS/RHS.
296 LHS = llvm::make_unique(BinOp, std::move(LHS),
297 std::move(RHS));
311 LHS =
312 llvm::make_unique(BinOp, std::move(LHS), std::move(RHS));
298313 }
299314 }
300315
303318 ///
304319 static std::unique_ptr ParseExpression() {
305320 auto LHS = ParsePrimary();
306 if (!LHS) return nullptr;
307
321 if (!LHS)
322 return nullptr;
323
308324 return ParseBinOpRHS(0, std::move(LHS));
309325 }
310326
316332
317333 std::string FnName = IdentifierStr;
318334 getNextToken();
319
335
320336 if (CurTok != '(')
321337 return ErrorP("Expected '(' in prototype");
322
338
323339 std::vector ArgNames;
324340 while (getNextToken() == tok_identifier)
325341 ArgNames.push_back(IdentifierStr);
326342 if (CurTok != ')')
327343 return ErrorP("Expected ')' in prototype");
328
344
329345 // success.
330 getNextToken(); // eat ')'.
331
332 return llvm::make_unique(std::move(FnName),
333 std::move(ArgNames));
346 getNextToken(); // eat ')'.
347
348 return llvm::make_unique(FnName, std::move(ArgNames));
334349 }
335350
336351 /// definition ::= 'def' prototype expression
337352 static std::unique_ptr ParseDefinition() {
338 getNextToken(); // eat def.
353 getNextToken(); // eat def.
339354 auto Proto = ParsePrototype();
340 if (!Proto) return nullptr;
355 if (!Proto)
356 return nullptr;
341357
342358 if (auto E = ParseExpression())
343359 return llvm::make_unique(std::move(Proto), std::move(E));
348364 static std::unique_ptr ParseTopLevelExpr() {
349365 if (auto E = ParseExpression()) {
350366 // Make an anonymous proto.
351 auto Proto = llvm::make_unique("",
352 std::vector());
367 auto Proto =
368 llvm::make_unique("", std::vector());
353369 return llvm::make_unique(std::move(Proto), std::move(E));
354370 }
355371 return nullptr;
357373
358374 /// external ::= 'extern' prototype
359375 static std::unique_ptr ParseExtern() {
360 getNextToken(); // eat extern.
376 getNextToken(); // eat extern.
361377 return ParsePrototype();
362378 }
363379
364380 //===----------------------------------------------------------------------===//
365381 // Code Generation
366382 //===----------------------------------------------------------------------===//
383
384 Value *ErrorV(const char *Str) {
385 Error(Str);
386 return nullptr;
387 }
367388
368389 static Module *TheModule;
369390 static IRBuilder<> Builder(getGlobalContext());
370 static std::map NamedValues;
371
372 Value *ErrorV(const char *Str) { Error(Str); return nullptr; }
391 static std::map NamedValues;
373392
374393 Value *NumberExprAST::Codegen() {
375394 return ConstantFP::get(getGlobalContext(), APFloat(Val));
384403 Value *BinaryExprAST::Codegen() {
385404 Value *L = LHS->Codegen();
386405 Value *R = RHS->Codegen();
387 if (!L || !R) return nullptr;
388
406 if (!L || !R)
407 return nullptr;
408
389409 switch (Op) {
390 case '+': return Builder.CreateFAdd(L, R, "addtmp");
391 case '-': return Builder.CreateFSub(L, R, "subtmp");
392 case '*': return Builder.CreateFMul(L, R, "multmp");
410 case '+':
411 return Builder.CreateFAdd(L, R, "addtmp");
412 case '-':
413 return Builder.CreateFSub(L, R, "subtmp");
414 case '*':
415 return Builder.CreateFMul(L, R, "multmp");
393416 case '<':
394417 L = Builder.CreateFCmpULT(L, R, "cmptmp");
395418 // Convert bool 0/1 to double 0.0 or 1.0
396419 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
397420 "booltmp");
398 default: return ErrorV("invalid binary operator");
421 default:
422 return ErrorV("invalid binary operator");
399423 }
400424 }
401425
404428 Function *CalleeF = TheModule->getFunction(Callee);
405429 if (!CalleeF)
406430 return ErrorV("Unknown function referenced");
407
431
408432 // If argument mismatch error.
409433 if (CalleeF->arg_size() != Args.size())
410434 return ErrorV("Incorrect # arguments passed");
411435
412 std::vector*> ArgsV;
436 std::vector *> ArgsV;
413437 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
414438 ArgsV.push_back(Args[i]->Codegen());
415 if (!ArgsV.back()) return nullptr;
416 }
417
439 if (!ArgsV.back())
440 return nullptr;
441 }
442
418443 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
419444 }
420445
421446 Function *PrototypeAST::Codegen() {
422447 // Make the function type: double(double,double) etc.
423 std::vector Doubles(Args.size(),
424 Type::getDoubleTy(getGlobalContext()));
425 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
426 Doubles, false);
427
428 Function *F = Function::Create(FT, Function::ExternalLinkage, Name,
429 TheModule);
430
448 std::vector Doubles(Args.size(),
449 Type::getDoubleTy(getGlobalContext()));
450 FunctionType *FT =
451 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
452
453 Function *F =
454 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
455
431456 // If F conflicted, there was already something named 'Name'. If it has a
432457 // body, don't allow redefinition or reextern.
433458 if (F->getName() != Name) {
434459 // Delete the one we just made and get the existing one.
435460 F->eraseFromParent();
436461 F = TheModule->getFunction(Name);
437
462
438463 // If F already has a body, reject this.
439464 if (!F->empty()) {
440465 ErrorF("redefinition of function");
441466 return nullptr;
442467 }
443
468
444469 // If F took a different number of args, reject.
445470 if (F->arg_size() != Args.size()) {
446471 ErrorF("redefinition of function with different # args");
447472 return nullptr;
448473 }
449474 }
450
475
451476 // Set names for all arguments.
452477 unsigned Idx = 0;
453478 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
454479 ++AI, ++Idx) {
455480 AI->setName(Args[Idx]);
456
481
457482 // Add arguments to variable symbol table.
458483 NamedValues[Args[Idx]] = AI;
459484 }
460
485
461486 return F;
462487 }
463488
464489 Function *FunctionAST::Codegen() {
465490 NamedValues.clear();
466
491
467492 Function *TheFunction = Proto->Codegen();
468493 if (!TheFunction)
469494 return nullptr;
470
495
471496 // Create a new basic block to start insertion into.
472497 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
473498 Builder.SetInsertPoint(BB);
474
499
475500 if (Value *RetVal = Body->Codegen()) {
476501 // Finish off the function.
477502 Builder.CreateRet(RetVal);
481506
482507 return TheFunction;
483508 }
484
509
485510 // Error reading body, remove function.
486511 TheFunction->eraseFromParent();
487512 return nullptr;
533558 while (1) {
534559 fprintf(stderr, "ready> ");
535560 switch (CurTok) {
536 case tok_eof: return;
537 case ';': getNextToken(); break; // ignore top-level semicolons.
538 case tok_def: HandleDefinition(); break;
539 case tok_extern: HandleExtern(); break;
540 default: HandleTopLevelExpression(); break;
541 }
542 }
543 }
544
545 //===----------------------------------------------------------------------===//
546 // "Library" functions that can be "extern'd" from user code.
547 //===----------------------------------------------------------------------===//
548
549 /// putchard - putchar that takes a double and returns 0.
550 extern "C"
551 double putchard(double X) {
552 putchar((char)X);
553 return 0;
561 case tok_eof:
562 return;
563 case ';': // ignore top-level semicolons.
564 getNextToken();
565 break;
566 case tok_def:
567 HandleDefinition();
568 break;
569 case tok_extern:
570 HandleExtern();
571 break;
572 default:
573 HandleTopLevelExpression();
574 break;
575 }
576 }
554577 }
555578
556579 //===----------------------------------------------------------------------===//
565588 BinopPrecedence['<'] = 10;
566589 BinopPrecedence['+'] = 20;
567590 BinopPrecedence['-'] = 20;
568 BinopPrecedence['*'] = 40; // highest.
591 BinopPrecedence['*'] = 40; // highest.
569592
570593 // Prime the first token.
571594 fprintf(stderr, "ready> ");
572595 getNextToken();
573596
574597 // Make the module, which holds all the code.
575 std::unique_ptr Owner = llvm::make_unique("my cool jit", Context);
598 std::unique_ptr Owner =
599 llvm::make_unique("my cool jit", Context);
576600 TheModule = Owner.get();
577601
578602 // Run the main "interpreter loop" now.
105105 /// NumberExprAST - Expression class for numeric literals like "1.0".
106106 class NumberExprAST : public ExprAST {
107107 double Val;
108
108109 public:
109110 NumberExprAST(double Val) : Val(Val) {}
110111 Value *Codegen() override;
113114 /// VariableExprAST - Expression class for referencing a variable, like "a".
114115 class VariableExprAST : public ExprAST {
115116 std::string Name;
117
116118 public:
117119 VariableExprAST(const std::string &Name) : Name(Name) {}
118120 Value *Codegen() override;
122124 class BinaryExprAST : public ExprAST {
123125 char Op;
124126 std::unique_ptr LHS, RHS;
127
125128 public:
126129 BinaryExprAST(char Op, std::unique_ptr LHS,
127130 std::unique_ptr RHS)
133136 class CallExprAST : public ExprAST {
134137 std::string Callee;
135138 std::vector> Args;
139
136140 public:
137141 CallExprAST(const std::string &Callee,
138142 std::vector> Args)
146150 class PrototypeAST {
147151 std::string Name;
148152 std::vector Args;
153
149154 public:
150 PrototypeAST(const std::string &name, std::vector Args)
151 : Name(name), Args(std::move(Args)) {}
155 PrototypeAST(const std::string &Name, std::vector Args)
156 : Name(Name), Args(std::move(Args)) {}
152157 Function *Codegen();
153158 };
154159
156161 class FunctionAST {
157162 std::unique_ptr Proto;
158163 std::unique_ptr Body;
164
159165 public:
160166 FunctionAST(std::unique_ptr Proto,
161167 std::unique_ptr Body)
162 : Proto(std::move(Proto)), Body(std::move(Body)) {}
168 : Proto(std::move(Proto)), Body(std::move(Body)) {}
163169 Function *Codegen();
164170 };
165171 } // end anonymous namespace
205211 }
206212
207213 static std::unique_ptr ParseExpression();
214
215 /// numberexpr ::= number
216 static std::unique_ptr ParseNumberExpr() {
217 auto Result = llvm::make_unique(NumVal);
218 getNextToken(); // consume the number
219 return std::move(Result);
220 }
221
222 /// parenexpr ::= '(' expression ')'
223 static std::unique_ptr ParseParenExpr() {
224 getNextToken(); // eat (.
225 auto V = ParseExpression();
226 if (!V)
227 return nullptr;
228
229 if (CurTok != ')')
230 return Error("expected ')'");
231 getNextToken(); // eat ).
232 return V;
233 }
208234
209235 /// identifierexpr
210236 /// ::= identifier
240266 getNextToken();
241267
242268 return llvm::make_unique(IdName, std::move(Args));
243 }
244
245 /// numberexpr ::= number
246 static std::unique_ptr ParseNumberExpr() {
247 auto Result = llvm::make_unique(NumVal);
248 getNextToken(); // consume the number
249 return std::move(Result);
250 }
251
252 /// parenexpr ::= '(' expression ')'
253 static std::unique_ptr ParseParenExpr() {
254 getNextToken(); // eat (.
255 auto V = ParseExpression();
256 if (!V)
257 return nullptr;
258
259 if (CurTok != ')')
260 return Error("expected ')'");
261 getNextToken(); // eat ).
262 return V;
263269 }
264270
265271 /// primary
311317 }
312318
313319 // Merge LHS/RHS.
314 LHS = llvm::make_unique(BinOp, std::move(LHS),
315 std::move(RHS));
320 LHS =
321 llvm::make_unique(BinOp, std::move(LHS), std::move(RHS));
316322 }
317323 }
318324
367373 static std::unique_ptr ParseTopLevelExpr() {
368374 if (auto E = ParseExpression()) {
369375 // Make an anonymous proto.
370 auto Proto = llvm::make_unique("",
371 std::vector());
376 auto Proto =
377 llvm::make_unique("", std::vector());
372378 return llvm::make_unique(std::move(Proto), std::move(E));
373379 }
374380 return nullptr;
805811 switch (CurTok) {
806812 case tok_eof:
807813 return;
808 case ';':
814 case ';': // ignore top-level semicolons.
809815 getNextToken();
810 break; // ignore top-level semicolons.
816 break;
811817 case tok_def:
812818 HandleDefinition();
813819 break;
831837 return 0;
832838 }
833839
840 /// printd - printf that takes a double prints it as "%f\n", returning 0.
841 extern "C" double printd(double X) {
842 printf("%f\n", X);
843 return 0;
844 }
845
834846 //===----------------------------------------------------------------------===//
835847 // Main driver code.
836848 //===----------------------------------------------------------------------===//
122122 /// NumberExprAST - Expression class for numeric literals like "1.0".
123123 class NumberExprAST : public ExprAST {
124124 double Val;
125
125126 public:
126127 NumberExprAST(double Val) : Val(Val) {}
127128 Value *Codegen() override;
130131 /// VariableExprAST - Expression class for referencing a variable, like "a".
131132 class VariableExprAST : public ExprAST {
132133 std::string Name;
134
133135 public:
134136 VariableExprAST(const std::string &Name) : Name(Name) {}
135137 Value *Codegen() override;
139141 class BinaryExprAST : public ExprAST {
140142 char Op;
141143 std::unique_ptr LHS, RHS;
144
142145 public:
143146 BinaryExprAST(char Op, std::unique_ptr LHS,
144147 std::unique_ptr RHS)
150153 class CallExprAST : public ExprAST {
151154 std::string Callee;
152155 std::vector> Args;
156
153157 public:
154158 CallExprAST(const std::string &Callee,
155159 std::vector> Args)
160164 /// IfExprAST - Expression class for if/then/else.
161165 class IfExprAST : public ExprAST {
162166 std::unique_ptr Cond, Then, Else;
167
163168 public:
164169 IfExprAST(std::unique_ptr Cond, std::unique_ptr Then,
165170 std::unique_ptr Else)
171176 class ForExprAST : public ExprAST {
172177 std::string VarName;
173178 std::unique_ptr Start, End, Step, Body;
179
174180 public:
175181 ForExprAST(const std::string &VarName, std::unique_ptr Start,
176182 std::unique_ptr End, std::unique_ptr Step,
186192 class PrototypeAST {
187193 std::string Name;
188194 std::vector Args;
195
189196 public:
190 PrototypeAST(const std::string &name, std::vector Args)
191 : Name(name), Args(std::move(Args)) {}
197 PrototypeAST(const std::string &Name, std::vector Args)
198 : Name(Name), Args(std::move(Args)) {}
192199 Function *Codegen();
193200 };
194201
196203 class FunctionAST {
197204 std::unique_ptr Proto;
198205 std::unique_ptr Body;
206
199207 public:
200208 FunctionAST(std::unique_ptr Proto,
201209 std::unique_ptr Body)
202 : Proto(std::move(Proto)), Body(std::move(Body)) {}
210 : Proto(std::move(Proto)), Body(std::move(Body)) {}
203211 Function *Codegen();
204212 };
205213 } // end anonymous namespace
245253 }
246254
247255 static std::unique_ptr ParseExpression();
256
257 /// numberexpr ::= number
258 static std::unique_ptr ParseNumberExpr() {
259 auto Result = llvm::make_unique(NumVal);
260 getNextToken(); // consume the number
261 return std::move(Result);
262 }
263
264 /// parenexpr ::= '(' expression ')'
265 static std::unique_ptr ParseParenExpr() {
266 getNextToken(); // eat (.
267 auto V = ParseExpression();
268 if (!V)
269 return nullptr;
270
271 if (CurTok != ')')
272 return Error("expected ')'");
273 getNextToken(); // eat ).
274 return V;
275 }
248276
249277 /// identifierexpr
250278 /// ::= identifier
280308 getNextToken();
281309
282310 return llvm::make_unique(IdName, std::move(Args));
283 }
284
285 /// numberexpr ::= number
286 static std::unique_ptr ParseNumberExpr() {
287 auto Result = llvm::make_unique(NumVal);
288 getNextToken(); // consume the number
289 return std::move(Result);
290 }
291
292 /// parenexpr ::= '(' expression ')'
293 static std::unique_ptr ParseParenExpr() {
294 getNextToken(); // eat (.
295 auto V = ParseExpression();
296 if (!V)
297 return nullptr;
298
299 if (CurTok != ')')
300 return Error("expected ')'");
301 getNextToken(); // eat ).
302 return V;
303311 }
304312
305313 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
433441 }
434442
435443 // Merge LHS/RHS.
436 LHS = llvm::make_unique(BinOp, std::move(LHS),
437 std::move(RHS));
444 LHS =
445 llvm::make_unique(BinOp, std::move(LHS), std::move(RHS));
438446 }
439447 }
440448
489497 static std::unique_ptr ParseTopLevelExpr() {
490498 if (auto E = ParseExpression()) {
491499 // Make an anonymous proto.
492 auto Proto = llvm::make_unique("",
493 std::vector());
500 auto Proto =
501 llvm::make_unique("", std::vector());
494502 return llvm::make_unique(std::move(Proto), std::move(E));
495503 }
496504 return nullptr;
623631 return PN;
624632 }
625633
634 // Output for-loop as:
635 // ...
636 // start = startexpr
637 // goto loop
638 // loop:
639 // variable = phi [start, loopheader], [nextvariable, loopend]
640 // ...
641 // bodyexpr
642 // ...
643 // loopend:
644 // step = stepexpr
645 // nextvariable = variable + step
646 // endcond = endexpr
647 // br endcond, loop, endloop
648 // outloop:
626649 Value *ForExprAST::Codegen() {
627 // Output this as:
628 // ...
629 // start = startexpr
630 // goto loop
631 // loop:
632 // variable = phi [start, loopheader], [nextvariable, loopend]
633 // ...
634 // bodyexpr
635 // ...
636 // loopend:
637 // step = stepexpr
638 // nextvariable = variable + step
639 // endcond = endexpr
640 // br endcond, loop, endloop
641 // outloop:
642
643650 // Emit the start code first, without 'variable' in scope.
644651 Value *StartVal = Start->Codegen();
645652 if (!StartVal)
675682 return nullptr;
676683
677684 // Emit the step value.
678 Value *StepVal;
685 Value *StepVal = nullptr;
679686 if (Step) {
680687 StepVal = Step->Codegen();
681688 if (!StepVal)
690697 // Compute the end condition.
691698 Value *EndCond = End->Codegen();
692699 if (!EndCond)
693 return EndCond;
700 return nullptr;
694701
695702 // Convert condition to a bool by comparing equal to 0.0.
696703 EndCond = Builder.CreateFCmpONE(
848855 switch (CurTok) {
849856 case tok_eof:
850857 return;
851 case ';':
858 case ';': // ignore top-level semicolons.
852859 getNextToken();
853 break; // ignore top-level semicolons.
860 break;
854861 case tok_def:
855862 HandleDefinition();
856863 break;
871878 /// putchard - putchar that takes a double and returns 0.
872879 extern "C" double putchard(double X) {
873880 putchar((char)X);
881 return 0;
882 }
883
884 /// printd - printf that takes a double prints it as "%f\n", returning 0.
885 extern "C" double printd(double X) {
886 printf("%f\n", X);
874887 return 0;
875888 }
876889
130130 /// NumberExprAST - Expression class for numeric literals like "1.0".
131131 class NumberExprAST : public ExprAST {
132132 double Val;
133
133134 public:
134135 NumberExprAST(double Val) : Val(Val) {}
135136 Value *Codegen() override;
138139 /// VariableExprAST - Expression class for referencing a variable, like "a".
139140 class VariableExprAST : public ExprAST {
140141 std::string Name;
142
141143 public:
142144 VariableExprAST(const std::string &Name) : Name(Name) {}
143145 Value *Codegen() override;
158160 class BinaryExprAST : public ExprAST {
159161 char Op;
160162 std::unique_ptr LHS, RHS;
163
161164 public:
162165 BinaryExprAST(char Op, std::unique_ptr LHS,
163166 std::unique_ptr RHS)
169172 class CallExprAST : public ExprAST {
170173 std::string Callee;
171174 std::vector> Args;
175
172176 public:
173177 CallExprAST(const std::string &Callee,
174178 std::vector> Args)
179183 /// IfExprAST - Expression class for if/then/else.
180184 class IfExprAST : public ExprAST {
181185 std::unique_ptr Cond, Then, Else;
186
182187 public:
183188 IfExprAST(std::unique_ptr Cond, std::unique_ptr Then,
184189 std::unique_ptr Else)
190195 class ForExprAST : public ExprAST {
191196 std::string VarName;
192197 std::unique_ptr Start, End, Step, Body;
198
193199 public:
194200 ForExprAST(const std::string &VarName, std::unique_ptr Start,
195201 std::unique_ptr End, std::unique_ptr Step,
196202 std::unique_ptr Body)
197 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
198 Step(std::move(Step)), Body(std::move(Body)) {}
203 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
204 Step(std::move(Step)), Body(std::move(Body)) {}
199205 Value *Codegen() override;
200206 };
201207
207213 std::vector Args;
208214 bool IsOperator;
209215 unsigned Precedence; // Precedence if a binary op.
216
210217 public:
211218 PrototypeAST(const std::string &Name, std::vector Args,
212219 bool IsOperator = false, unsigned Prec = 0)
213 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
214 Precedence(Prec) {}
220 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
221 Precedence(Prec) {}
215222
216223 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
217224 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
230237 class FunctionAST {
231238 std::unique_ptr Proto;
232239 std::unique_ptr Body;
240
233241 public:
234 FunctionAST(std::unique_ptr Proto, std::unique_ptr Body)
242 FunctionAST(std::unique_ptr Proto,
243 std::unique_ptr Body)
235244 : Proto(std::move(Proto)), Body(std::move(Body)) {}
236245 Function *Codegen();
237246 };
278287 }
279288
280289 static std::unique_ptr ParseExpression();
290
291 /// numberexpr ::= number
292 static std::unique_ptr ParseNumberExpr() {
293 auto Result = llvm::make_unique(NumVal);
294 getNextToken(); // consume the number
295 return std::move(Result);
296 }
297
298 /// parenexpr ::= '(' expression ')'
299 static std::unique_ptr ParseParenExpr() {
300 getNextToken(); // eat (.
301 auto V = ParseExpression();
302 if (!V)
303 return nullptr;
304
305 if (CurTok != ')')
306 return Error("expected ')'");
307 getNextToken(); // eat ).
308 return V;
309 }
281310
282311 /// identifierexpr
283312 /// ::= identifier
313342 getNextToken();
314343
315344 return llvm::make_unique(IdName, std::move(Args));
316 }
317
318 /// numberexpr ::= number
319 static std::unique_ptr ParseNumberExpr() {
320 auto Result = llvm::make_unique(NumVal);
321 getNextToken(); // consume the number
322 return std::move(Result);
323 }
324
325 /// parenexpr ::= '(' expression ')'
326 static std::unique_ptr ParseParenExpr() {
327 getNextToken(); // eat (.
328 auto V = ParseExpression();
329 if (!V)
330 return nullptr;
331
332 if (CurTok != ')')
333 return Error("expected ')'");
334 getNextToken(); // eat ).
335 return V;
336345 }
337346
338347 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
452461
453462 /// binoprhs
454463 /// ::= ('+' unary)*
455 static std::unique_ptr ParseBinOpRHS(int ExprPrec, std::unique_ptr LHS) {
464 static std::unique_ptr ParseBinOpRHS(int ExprPrec,
465 std::unique_ptr LHS) {
456466 // If this is a binop, find its precedence.
457467 while (1) {
458468 int TokPrec = GetTokPrecedence();
481491 }
482492
483493 // Merge LHS/RHS.
484 LHS = llvm::make_unique(BinOp, std::move(LHS), std::move(RHS));
494 LHS =
495 llvm::make_unique(BinOp, std::move(LHS), std::move(RHS));
485496 }
486497 }
487498
578589 static std::unique_ptr ParseTopLevelExpr() {
579590 if (auto E = ParseExpression()) {
580591 // Make an anonymous proto.
581 auto Proto = llvm::make_unique("", std::vector());
592 auto Proto =
593 llvm::make_unique("", std::vector());
582594 return llvm::make_unique(std::move(Proto), std::move(E));
583595 }
584596 return nullptr;
611623 Value *VariableExprAST::Codegen() {
612624 // Look this variable up in the function.
613625 Value *V = NamedValues[Name];
614 return V ? V : ErrorV("Unknown variable name");
626 if (!V)
627 return ErrorV("Unknown variable name");
628
629 return V;
615630 }
616631
617632 Value *UnaryExprAST::Codegen() {
653668 Function *F = TheModule->getFunction(std::string("binary") + Op);
654669 assert(F && "binary operator not found!");
655670
656 Value *Ops[] = { L, R };
671 Value *Ops[] = {L, R};
657672 return Builder.CreateCall(F, Ops, "binop");
658673 }
659674
731746 return PN;
732747 }
733748
749 // Output for-loop as:
750 // ...
751 // start = startexpr
752 // goto loop
753 // loop:
754 // variable = phi [start, loopheader], [nextvariable, loopend]
755 // ...
756 // bodyexpr
757 // ...
758 // loopend:
759 // step = stepexpr
760 // nextvariable = variable + step
761 // endcond = endexpr
762 // br endcond, loop, endloop
763 // outloop:
734764 Value *ForExprAST::Codegen() {
735 // Output this as:
736 // ...
737 // start = startexpr
738 // goto loop
739 // loop:
740 // variable = phi [start, loopheader], [nextvariable, loopend]
741 // ...
742 // bodyexpr
743 // ...
744 // loopend:
745 // step = stepexpr
746 // nextvariable = variable + step
747 // endcond = endexpr
748 // br endcond, loop, endloop
749 // outloop:
750
751765 // Emit the start code first, without 'variable' in scope.
752766 Value *StartVal = Start->Codegen();
753767 if (!StartVal)
783797 return nullptr;
784798
785799 // Emit the step value.
786 Value *StepVal;
800 Value *StepVal = nullptr;
787801 if (Step) {
788802 StepVal = Step->Codegen();
789803 if (!StepVal)
798812 // Compute the end condition.
799813 Value *EndCond = End->Codegen();
800814 if (!EndCond)
801 return EndCond;
815 return nullptr;
802816
803817 // Convert condition to a bool by comparing equal to 0.0.
804818 EndCond = Builder.CreateFCmpONE(
963977 switch (CurTok) {
964978 case tok_eof:
965979 return;
966 case ';':
980 case ';': // ignore top-level semicolons.
967981 getNextToken();
968 break; // ignore top-level semicolons.
982 break;
969983 case tok_def:
970984 HandleDefinition();
971985 break;
135135 /// NumberExprAST - Expression class for numeric literals like "1.0".
136136 class NumberExprAST : public ExprAST {
137137 double Val;
138
138139 public:
139140 NumberExprAST(double Val) : Val(Val) {}
140141 Value *Codegen() override;
143144 /// VariableExprAST - Expression class for referencing a variable, like "a".
144145 class VariableExprAST : public ExprAST {
145146 std::string Name;
147
146148 public:
147149 VariableExprAST(const std::string &Name) : Name(Name) {}
148150 const std::string &getName() const { return Name; }
153155 class UnaryExprAST : public ExprAST {
154156 char Opcode;
155157 std::unique_ptr Operand;
158
156159 public:
157160 UnaryExprAST(char Opcode, std::unique_ptr Operand)
158161 : Opcode(Opcode), Operand(std::move(Operand)) {}
163166 class BinaryExprAST : public ExprAST {
164167 char Op;
165168 std::unique_ptr LHS, RHS;
169
166170 public:
167171 BinaryExprAST(char Op, std::unique_ptr LHS,
168172 std::unique_ptr RHS)
174178 class CallExprAST : public ExprAST {
175179 std::string Callee;
176180 std::vector> Args;
181
177182 public:
178183 CallExprAST(const std::string &Callee,
179184 std::vector> Args)
184189 /// IfExprAST - Expression class for if/then/else.
185190 class IfExprAST : public ExprAST {
186191 std::unique_ptr Cond, Then, Else;
192
187193 public:
188194 IfExprAST(std::unique_ptr Cond, std::unique_ptr Then,
189195 std::unique_ptr Else)
195201 class ForExprAST : public ExprAST {
196202 std::string VarName;
197203 std::unique_ptr Start, End, Step, Body;
204
198205 public:
199206 ForExprAST(const std::string &VarName, std::unique_ptr Start,
200207 std::unique_ptr End, std::unique_ptr Step,
208215 class VarExprAST : public ExprAST {
209216 std::vector>> VarNames;
210217 std::unique_ptr Body;
218
211219 public:
212 VarExprAST(std::vector>> VarNames,
213 std::unique_ptr Body)
214 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
220 VarExprAST(
221 std::vector>> VarNames,
222 std::unique_ptr Body)
223 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
215224 Value *Codegen() override;
216225 };
217226
218227 /// PrototypeAST - This class represents the "prototype" for a function,
219 /// which captures its argument names as well as if it is an operator.
228 /// which captures its name, and its argument names (thus implicitly the number
229 /// of arguments the function takes), as well as if it is an operator.
220230 class PrototypeAST {
221231 std::string Name;
222232 std::vector Args;
223233 bool IsOperator;
224234 unsigned Precedence; // Precedence if a binary op.
235
225236 public:
226237 PrototypeAST(const std::string &Name, std::vector Args,
227238 bool IsOperator = false, unsigned Prec = 0)
228 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
229 Precedence(Prec) {}
239 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
240 Precedence(Prec) {}
230241
231242 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
232243 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
247258 class FunctionAST {
248259 std::unique_ptr Proto;
249260 std::unique_ptr Body;
261
250262 public:
251 FunctionAST(std::unique_ptr Proto, std::unique_ptr Body)
263 FunctionAST(std::unique_ptr Proto,
264 std::unique_ptr Body)
252265 : Proto(std::move(Proto)), Body(std::move(Body)) {}
253266 Function *Codegen();
254267 };
295308 }
296309
297310 static std::unique_ptr ParseExpression();
311
312 /// numberexpr ::= number
313 static std::unique_ptr ParseNumberExpr() {
314 auto Result = llvm::make_unique(NumVal);
315 getNextToken(); // consume the number
316 return std::move(Result);
317 }
318
319 /// parenexpr ::= '(' expression ')'
320 static std::unique_ptr ParseParenExpr() {
321 getNextToken(); // eat (.
322 auto V = ParseExpression();
323 if (!V)
324 return nullptr;
325
326 if (CurTok != ')')
327 return Error("expected ')'");
328 getNextToken(); // eat ).
329 return V;
330 }
298331
299332 /// identifierexpr
300333 /// ::= identifier
330363 getNextToken();
331364
332365 return llvm::make_unique(IdName, std::move(Args));
333 }
334
335 /// numberexpr ::= number
336 static std::unique_ptr ParseNumberExpr() {
337 auto Result = llvm::make_unique(NumVal);
338 getNextToken(); // consume the number
339 return std::move(Result);
340 }
341
342 /// parenexpr ::= '(' expression ')'
343 static std::unique_ptr ParseParenExpr() {
344 getNextToken(); // eat (.
345 auto V = ParseExpression();
346 if (!V)
347 return nullptr;
348
349 if (CurTok != ')')
350 return Error("expected ')'");
351 getNextToken(); // eat ).
352 return V;
353366 }
354367
355368 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
520533
521534 /// binoprhs
522535 /// ::= ('+' unary)*
523 static std::unique_ptr ParseBinOpRHS(int ExprPrec, std::unique_ptr LHS) {
536 static std::unique_ptr ParseBinOpRHS(int ExprPrec,
537 std::unique_ptr LHS) {
524538 // If this is a binop, find its precedence.
525539 while (1) {
526540 int TokPrec = GetTokPrecedence();
549563 }
550564
551565 // Merge LHS/RHS.
552 LHS = llvm::make_unique(BinOp, std::move(LHS), std::move(RHS));
566 LHS =
567 llvm::make_unique(BinOp, std::move(LHS), std::move(RHS));
553568 }
554569 }
555570
646661 static std::unique_ptr ParseTopLevelExpr() {
647662 if (auto E = ParseExpression()) {
648663 // Make an anonymous proto.
649 auto Proto = llvm::make_unique("", std::vector());
664 auto Proto =
665 llvm::make_unique("", std::vector());
650666 return llvm::make_unique(std::move(Proto), std::move(E));
651667 }
652668 return nullptr;
715731 // This assume we're building without RTTI because LLVM builds that way by
716732 // default. If you build LLVM with RTTI this can be changed to a
717733 // dynamic_cast for automatic error checking.
718 VariableExprAST *LHSE = static_cast*>(LHS.get());
734 VariableExprAST *LHSE = static_cast *>(LHS.get());
719735 if (!LHSE)
720736 return ErrorV("destination of '=' must be a variable");
721737 // Codegen the RHS.
758774 Function *F = TheModule->getFunction(std::string("binary") + Op);
759775 assert(F && "binary operator not found!");
760776
761 Value *Ops[] = { L, R };
777 Value *Ops[] = {L, R};
762778 return Builder.CreateCall(F, Ops, "binop");
763779 }
764780
836852 return PN;
837853 }
838854
855 // Output for-loop as:
856 // var = alloca double
857 // ...
858 // start = startexpr
859 // store start -> var
860 // goto loop
861 // loop:
862 // ...
863 // bodyexpr
864 // ...
865 // loopend:
866 // step = stepexpr
867 // endcond = endexpr
868 //
869 // curvar = load var
870 // nextvar = curvar + step
871 // store nextvar -> var
872 // br endcond, loop, endloop
873 // outloop:
839874 Value *ForExprAST::Codegen() {
840 // Output this as:
841 // var = alloca double
842 // ...
843 // start = startexpr
844 // store start -> var
845 // goto loop
846 // loop:
847 // ...
848 // bodyexpr
849 // ...
850 // loopend:
851 // step = stepexpr
852 // endcond = endexpr
853 //
854 // curvar = load var
855 // nextvar = curvar + step
856 // store nextvar -> var
857 // br endcond, loop, endloop
858 // outloop:
859
860875 Function *TheFunction = Builder.GetInsertBlock()->getParent();
861876
862877 // Create an alloca for the variable in the entry block.
893908 return nullptr;
894909
895910 // Emit the step value.
896 Value *StepVal;
911 Value *StepVal = nullptr;
897912 if (Step) {
898913 StepVal = Step->Codegen();
899914 if (!StepVal)
906921 // Compute the end condition.
907922 Value *EndCond = End->Codegen();
908923 if (!EndCond)
909 return EndCond;
924 return nullptr;
910925
911926 // Reload, increment, and restore the alloca. This handles the case where
912927 // the body of the loop mutates the variable.
11361151 switch (CurTok) {
11371152 case tok_eof:
11381153 return;
1139 case ';':
1154 case ';': // ignore top-level semicolons.
11401155 getNextToken();
1141 break; // ignore top-level semicolons.
1156 break;
11421157 case tok_def:
11431158 HandleDefinition();
11441159 break;
1616 #include "llvm/Transforms/Scalar.h"
1717 #include
1818 #include
19 #include
2019 #include
2120 #include
2221 #include
108107 int Col;
109108 };
110109 static SourceLocation CurLoc;
111 static SourceLocation LexLoc = { 1, 0 };
110 static SourceLocation LexLoc = {1, 0};
112111
113112 static int advance() {
114113 int LastChar = getchar();
195194 //===----------------------------------------------------------------------===//
196195 namespace {
197196
198 std::ostream &indent(std::ostream &O, int size) {
197 raw_ostream &indent(raw_ostream &O, int size) {
199198 return O << std::string(size, ' ');
200199 }
201200
202201 /// ExprAST - Base class for all expression nodes.
203202 class ExprAST {
204203 SourceLocation Loc;
204
205205 public:
206 ExprAST(SourceLocation Loc = CurLoc) : Loc(Loc) {}
207 virtual ~ExprAST() {}
208 virtual Value *Codegen() = 0;
206209 int getLine() const { return Loc.Line; }
207210 int getCol() const { return Loc.Col; }
208 ExprAST(SourceLocation Loc = CurLoc) : Loc(Loc) {}
209 virtual std::ostream &dump(std::ostream &out, int ind) {
211 virtual raw_ostream &dump(raw_ostream &out, int ind) {
210212 return out << ':' << getLine() << ':' << getCol() << '\n';
211213 }
212 virtual ~ExprAST() {}
213 virtual Value *Codegen() = 0;
214214 };
215215
216216 /// NumberExprAST - Expression class for numeric literals like "1.0".
217217 class NumberExprAST : public ExprAST {
218218 double Val;
219
219220 public:
220221 NumberExprAST(double Val) : Val(Val) {}
221 std::ostream &dump(std::ostream &out, int ind) override {
222 raw_ostream &dump(raw_ostream &out, int ind) override {
222223 return ExprAST::dump(out << Val, ind);
223224 }
224225 Value *Codegen() override;
227228 /// VariableExprAST - Expression class for referencing a variable, like "a".
228229 class VariableExprAST : public ExprAST {
229230 std::string Name;
231
230232 public:
231233 VariableExprAST(SourceLocation Loc, const std::string &Name)
232234 : ExprAST(Loc), Name(Name) {}
233235 const std::string &getName() const { return Name; }
234 std::ostream &dump(std::ostream &out, int ind) override {
236 raw_ostream &dump(raw_ostream &out, int ind) override {
235237 return ExprAST::dump(out << Name, ind);
236238 }
237239 Value *Codegen() override;
241243 class UnaryExprAST : public ExprAST {
242244 char Opcode;
243245 std::unique_ptr Operand;
246
244247 public:
245248 UnaryExprAST(char Opcode, std::unique_ptr Operand)
246249 : Opcode(Opcode), Operand(std::move(Operand)) {}
247 std::ostream &dump(std::ostream &out, int ind) override {
250 raw_ostream &dump(raw_ostream &out, int ind) override {
248251 ExprAST::dump(out << "unary" << Opcode, ind);
249252 Operand->dump(out, ind + 1);
250253 return out;
256259 class BinaryExprAST : public ExprAST {
257260 char Op;
258261 std::unique_ptr LHS, RHS;
262
259263 public:
260264 BinaryExprAST(SourceLocation Loc, char Op, std::unique_ptr LHS,
261265 std::unique_ptr RHS)
262266 : ExprAST(Loc), Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
263 std::ostream &dump(std::ostream &out, int ind) override {
267 raw_ostream &dump(raw_ostream &out, int ind) override {
264268 ExprAST::dump(out << "binary" << Op, ind);
265269 LHS->dump(indent(out, ind) << "LHS:", ind + 1);
266270 RHS->dump(indent(out, ind) << "RHS:", ind + 1);
273277 class CallExprAST : public ExprAST {
274278 std::string Callee;
275279 std::vector> Args;
280
276281 public:
277282 CallExprAST(SourceLocation Loc, const std::string &Callee,
278283 std::vector> Args)
279284 : ExprAST(Loc), Callee(Callee), Args(std::move(Args)) {}
280 std::ostream &dump(std::ostream &out, int ind) override {
285 raw_ostream &dump(raw_ostream &out, int ind) override {
281286 ExprAST::dump(out << "call " << Callee, ind);
282287 for (const auto &Arg : Args)
283288 Arg->dump(indent(out, ind + 1), ind + 1);
289294 /// IfExprAST - Expression class for if/then/else.
290295 class IfExprAST : public ExprAST {
291296 std::unique_ptr Cond, Then, Else;
297
292298 public:
293299 IfExprAST(SourceLocation Loc, std::unique_ptr Cond,
294300 std::unique_ptr Then, std::unique_ptr Else)
295 : ExprAST(Loc), Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
296 std::ostream &dump(std::ostream &out, int ind) override {
301 : ExprAST(Loc), Cond(std::move(Cond)), Then(std::move(Then)),
302 Else(std::move(Else)) {}
303 raw_ostream &dump(raw_ostream &out, int ind) override {
297304 ExprAST::dump(out << "if", ind);
298305 Cond->dump(indent(out, ind) << "Cond:", ind + 1);
299306 Then->dump(indent(out, ind) << "Then:", ind + 1);
307314 class ForExprAST : public ExprAST {
308315 std::string VarName;
309316 std::unique_ptr Start, End, Step, Body;
317
310318 public:
311319 ForExprAST(const std::string &VarName, std::unique_ptr Start,
312320 std::unique_ptr End, std::unique_ptr Step,
313321 std::unique_ptr Body)
314322 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
315323 Step(std::move(Step)), Body(std::move(Body)) {}
316 std::ostream &dump(std::ostream &out, int ind) override {
324 raw_ostream &dump(raw_ostream &out, int ind) override {
317325 ExprAST::dump(out << "for", ind);
318326 Start->dump(indent(out, ind) << "Cond:", ind + 1);
319327 End->dump(indent(out, ind) << "End:", ind + 1);
328336 class VarExprAST : public ExprAST {
329337 std::vector>> VarNames;
330338 std::unique_ptr Body;
339
331340 public:
332 VarExprAST(std::vector>> VarNames,
333 std::unique_ptr Body)
341 VarExprAST(
342 std::vector>> VarNames,
343 std::unique_ptr Body)
334344 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
335 std::ostream &dump(std::ostream &out, int ind) override {
345 raw_ostream &dump(raw_ostream &out, int ind) override {
336346 ExprAST::dump(out << "var", ind);
337347 for (const auto &NamedVar : VarNames)
338348 NamedVar.second->dump(indent(out, ind) << NamedVar.first << ':', ind + 1);
343353 };
344354
345355 /// PrototypeAST - This class represents the "prototype" for a function,
346 /// which captures its argument names as well as if it is an operator.
356 /// which captures its name, and its argument names (thus implicitly the number
357 /// of arguments the function takes), as well as if it is an operator.
347358 class PrototypeAST {
348359 std::string Name;
349360 std::vector Args;
350361 bool IsOperator;
351362 unsigned Precedence; // Precedence if a binary op.
352363 int Line;
364
353365 public:
354366 PrototypeAST(SourceLocation Loc, const std::string &Name,
355367 std::vector Args, bool IsOperator = false,
356368 unsigned Prec = 0)
357 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
358 Precedence(Prec), Line(Loc.Line) {}
369 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
370 Precedence(Prec), Line(Loc.Line) {}
359371
360372 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
361373 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
377389 class FunctionAST {
378390 std::unique_ptr Proto;
379391 std::unique_ptr Body;
392
380393 public:
381394 FunctionAST(std::unique_ptr Proto,
382395 std::unique_ptr Body)
383396 : Proto(std::move(Proto)), Body(std::move(Body)) {}
384397
385 std::ostream &dump(std::ostream &out, int ind) {
398 raw_ostream &dump(raw_ostream &out, int ind) {
386399 indent(out, ind) << "FunctionAST\n";
387400 ++ind;
388401 indent(out, ind) << "Body:";
435448
436449 static std::unique_ptr ParseExpression();
437450
451 /// numberexpr ::= number
452 static std::unique_ptr ParseNumberExpr() {
453 auto Result = llvm::make_unique(NumVal);
454 getNextToken(); // consume the number
455 return std::move(Result);
456 }
457
458 /// parenexpr ::= '(' expression ')'
459 static std::unique_ptr ParseParenExpr() {
460 getNextToken(); // eat (.
461 auto V = ParseExpression();
462 if (!V)
463 return nullptr;
464
465 if (CurTok != ')')
466 return Error("expected ')'");
467 getNextToken(); // eat ).
468 return V;
469 }
470
438471 /// identifierexpr
439472 /// ::= identifier
440473 /// ::= identifier '(' expression* ')'
441 static std::unique_ptr ParseIdentifierExpr() {
474 static std::unique_ptr ParseIdentifierExpr() {
442475 std::string IdName = IdentifierStr;
443476
444477 SourceLocation LitLoc = CurLoc;
453486 std::vector> Args;
454487 if (CurTok != ')') {
455488 while (1) {
456 auto Arg = ParseExpression();
457 if (!Arg)
489 if (auto Arg = ParseExpression())
490 Args.push_back(std::move(Arg));
491 else
458492 return nullptr;
459 Args.push_back(std::move(Arg));
460493
461494 if (CurTok == ')')
462495 break;
471504 getNextToken();
472505
473506 return llvm::make_unique(LitLoc, IdName, std::move(Args));
474 }
475
476 /// numberexpr ::= number
477 static std::unique_ptr ParseNumberExpr() {
478 auto Result = llvm::make_unique(NumVal);
479 getNextToken(); // consume the number
480 return std::move(Result);
481 }
482
483 /// parenexpr ::= '(' expression ')'
484 static std::unique_ptr ParseParenExpr() {
485 getNextToken(); // eat (.
486 auto V = ParseExpression();
487 if (!V)
488 return nullptr;
489
490 if (CurTok != ')')
491 return Error("expected ')'");
492 getNextToken(); // eat ).
493 return V;
494507 }
495508
496509 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
663676
664677 /// binoprhs
665678 /// ::= ('+' unary)*
666 static std::unique_ptr ParseBinOpRHS(int ExprPrec, std::unique_ptr LHS) {
679 static std::unique_ptr ParseBinOpRHS(int ExprPrec,
680 std::unique_ptr LHS) {
667681 // If this is a binop, find its precedence.
668682 while (1) {
669683 int TokPrec = GetTokPrecedence();
794808 SourceLocation FnLoc = CurLoc;
795809 if (auto E = ParseExpression()) {
796810 // Make an anonymous proto.
797 auto Proto =
798 llvm::make_unique(FnLoc, "main", std::vector());
811 auto Proto = llvm::make_unique(FnLoc, "main",
812 std::vector());
799813 return llvm::make_unique(std::move(Proto), std::move(E));
800814 }
801815 return nullptr;
908922 // This assume we're building without RTTI because LLVM builds that way by
909923 // default. If you build LLVM with RTTI this can be changed to a
910924 // dynamic_cast for automatic error checking.
911 VariableExprAST *LHSE = static_cast*>(LHS.get());
925 VariableExprAST *LHSE = static_cast *>(LHS.get());
912926 if (!LHSE)
913927 return ErrorV("destination of '=' must be a variable");
914928 // Codegen the RHS.
951965 Function *F = TheModule->getFunction(std::string("binary") + Op);
952966 assert(F && "binary operator not found!");
953967
954 Value *Ops[] = { L, R };
968 Value *Ops[] = {L, R};
955969 return Builder.CreateCall(F, Ops, "binop");
956970 }
957971
10331047 return PN;
10341048 }
10351049
1050 // Output for-loop as:
1051 // var = alloca double
1052 // ...
1053 // start = startexpr
1054 // store start -> var
1055 // goto loop
1056 // loop:
1057 // ...
1058 // bodyexpr
1059 // ...
1060 // loopend:
1061 // step = stepexpr
1062 // endcond = endexpr
1063 //
1064 // curvar = load var
1065 // nextvar = curvar + step
1066 // store nextvar -> var
1067 // br endcond, loop, endloop
1068 // outloop:
10361069 Value *ForExprAST::Codegen() {
1037 // Output this as:
1038 // var = alloca double
1039 // ...
1040 // start = startexpr
1041 // store start -> var
1042 // goto loop
1043 // loop:
1044 // ...
1045 // bodyexpr
1046 // ...
1047 // loopend:
1048 // step = stepexpr
1049 // endcond = endexpr
1050 //
1051 // curvar = load var
1052 // nextvar = curvar + step
1053 // store nextvar -> var
1054 // br endcond, loop, endloop
1055 // outloop:
1056
10571070 Function *TheFunction = Builder.GetInsertBlock()->getParent();
10581071
10591072 // Create an alloca for the variable in the entry block.
10921105 return nullptr;
10931106
10941107 // Emit the step value.
1095 Value *StepVal;
1108 Value *StepVal = nullptr;
10961109 if (Step) {
10971110 StepVal = Step->Codegen();
10981111 if (!StepVal)
11051118 // Compute the end condition.
11061119 Value *EndCond = End->Codegen();
11071120 if (!EndCond)
1108 return EndCond;
1121 return nullptr;
11091122
11101123 // Reload, increment, and restore the alloca. This handles the case where
11111124 // the body of the loop mutates the variable.
13681381 switch (CurTok) {
13691382 case tok_eof:
13701383 return;
1371 case ';':
1384 case ';': // ignore top-level semicolons.
13721385 getNextToken();
1373 break; // ignore top-level semicolons.
1386 break;
13741387 case tok_def:
13751388 HandleDefinition();
13761389 break;
14721485 OurFPM.add(createGVNPass());
14731486 // Simplify the control flow graph (deleting unreachable blocks, etc).
14741487 OurFPM.add(createCFGSimplificationPass());
1475 #endif
1488 #endif
14761489 OurFPM.doInitialization();
14771490
14781491 // Set the global so the code gen can use this.