llvm.org GIT mirror llvm / afae23b
[Kaleidoscope] Start C++11'ifying the kaleidoscope tutorials. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@245322 91177308-0d34-0410-b5e6-96231b3b80d8 Lang Hames 4 years ago
15 changed file(s) with 1104 addition(s) and 1049 deletion(s). Raw diff Collapse all Expand all
2424 about teaching compiler techniques and LLVM specifically, *not* about
2525 teaching modern and sane software engineering principles. In practice,
2626 this means that we'll take a number of shortcuts to simplify the
27 exposition. For example, the code leaks memory, uses global variables
27 exposition. For example, the code uses global variables
2828 all over the place, doesn't use nice design patterns like
2929 `visitors `_, etc... but
3030 it is very simple. If you dig in and use the code as a basis for future
4444 class NumberExprAST : public ExprAST {
4545 double Val;
4646 public:
47 NumberExprAST(double val) : Val(val) {}
47 NumberExprAST(double Val) : Val(Val) {}
4848 };
4949
5050 The code above shows the definition of the base ExprAST class and one
6565 class VariableExprAST : public ExprAST {
6666 std::string Name;
6767 public:
68 VariableExprAST(const std::string &name) : Name(name) {}
68 VariableExprAST(const std::string &Name) : Name(Name) {}
6969 };
7070
7171 /// BinaryExprAST - Expression class for a binary operator.
7272 class BinaryExprAST : public ExprAST {
7373 char Op;
74 ExprAST *LHS, *RHS;
74 std::unique_ptr LHS, RHS;
7575 public:
76 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
77 : Op(op), LHS(lhs), RHS(rhs) {}
76 BinaryExprAST(char op, std::unique_ptr LHS,
77 std::unique_ptr RHS)
78 : Op(op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
7879 };
7980
8081 /// CallExprAST - Expression class for function calls.
8283 std::string Callee;
8384 std::vector Args;
8485 public:
85 CallExprAST(const std::string &callee, std::vector &args)
86 : Callee(callee), Args(args) {}
86 CallExprAST(const std::string &Callee,
87 std::vector> Args)
88 : Callee(Callee), Args(std::move(Args)) {}
8789 };
8890
8991 This is all (intentionally) rather straight-forward: variables capture
109111 std::string Name;
110112 std::vector Args;
111113 public:
112 PrototypeAST(const std::string &name, const std::vector &args)
113 : Name(name), Args(args) {}
114 PrototypeAST(const std::string &name, std::vector Args)
115 : Name(name), Args(std::move(Args)) {}
114116 };
115117
116118 /// FunctionAST - This class represents a function definition itself.
117119 class FunctionAST {
118 PrototypeAST *Proto;
119 ExprAST *Body;
120 std::unique_ptr Proto;
121 std::unique_ptr Body;
120122 public:
121 FunctionAST(PrototypeAST *proto, ExprAST *body)
122 : Proto(proto), Body(body) {}
123 FunctionAST(std::unique_ptr Proto,
124 std::unique_ptr Body)
125 : Proto(std::move(Proto)), Body(std::move(Body)) {}
123126 };
124127
125128 In Kaleidoscope, functions are typed with just a count of their
141144
142145 .. code-block:: c++
143146
144 ExprAST *X = new VariableExprAST("x");
145 ExprAST *Y = new VariableExprAST("y");
146 ExprAST *Result = new BinaryExprAST('+', X, Y);
147 auto LHS = llvm::make_unique("x");
148 auto RHS = llvm::make_unique("y");
149 auto Result = std::make_unique('+', std::move(LHS),
150 std::move(RHS));
147151
148152 In order to do this, we'll start by defining some basic helper routines:
149153
189193 .. code-block:: c++
190194
191195 /// numberexpr ::= number
192 static ExprAST *ParseNumberExpr() {
193 ExprAST *Result = new NumberExprAST(NumVal);
196 static std::unique_ptr ParseNumberExpr() {
197 auto Result = llvm::make_unique(NumVal);
194198 getNextToken(); // consume the number
195 return Result;
199 return std::move(Result);
196200 }
197201
198202 This routine is very simple: it expects to be called when the current
210214 .. code-block:: c++
211215
212216 /// parenexpr ::= '(' expression ')'
213 static ExprAST *ParseParenExpr() {
217 static std::unique_ptr ParseParenExpr() {
214218 getNextToken(); // eat (.
215 ExprAST *V = ParseExpression();
216 if (!V) return 0;
219 auto V = ParseExpression();
220 if (!V) return nullptr;
217221
218222 if (CurTok != ')')
219223 return Error("expected ')'");
249253 /// identifierexpr
250254 /// ::= identifier
251255 /// ::= identifier '(' expression* ')'
252 static ExprAST *ParseIdentifierExpr() {
256 static std::unique_ptr ParseIdentifierExpr() {
253257 std::string IdName = IdentifierStr;
254258
255259 getNextToken(); // eat identifier.
256260
257261 if (CurTok != '(') // Simple variable ref.
258 return new VariableExprAST(IdName);
262 return llvm::make_unique(IdName);
259263
260264 // Call.
261265 getNextToken(); // eat (
262 std::vector<ExprAST*> Args;
266 std::vector<std::unique_ptr> Args;
263267 if (CurTok != ')') {
264268 while (1) {
265 ExprAST *Arg = ParseExpression();
266 if (!Arg) return 0;
267 Args.push_back(Arg);
269 auto Arg = ParseExpression();
270 if (!Arg) return nullptr;
271 Args.push_back(std::move(Arg));
268272
269273 if (CurTok == ')') break;
270274
277281 // Eat the ')'.
278282 getNextToken();
279283
280 return new CallExprAST(IdName, Args);
284 return llvm::make_unique(IdName, std::move(Args));
281285 }
282286
283287 This routine follows the same style as the other routines. (It expects
302306 /// ::= identifierexpr
303307 /// ::= numberexpr
304308 /// ::= parenexpr
305 static ExprAST *ParsePrimary() {
309 static std::unique_ptr ParsePrimary() {
306310 switch (CurTok) {
307311 default: return Error("unknown token when expecting an expression");
308312 case tok_identifier: return ParseIdentifierExpr();
389393 /// expression
390394 /// ::= primary binoprhs
391395 ///
392 static ExprAST *ParseExpression() {
393 ExprAST *LHS = ParsePrimary();
394 if (!LHS) return 0;
395
396 return ParseBinOpRHS(0, LHS);
396 static std::unique_ptr ParseExpression() {
397 auto LHS = ParsePrimary();
398 if (!LHS) return nullptr;
399
400 return ParseBinOpRHS(0, std::move(LHS));
397401 }
398402
399403 ``ParseBinOpRHS`` is the function that parses the sequence of pairs for
415419
416420 /// binoprhs
417421 /// ::= ('+' primary)*
418 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
422 static std::unique_ptr ParseBinOpRHS(int ExprPrec,
423 std::unique_ptr LHS) {
419424 // If this is a binop, find its precedence.
420425 while (1) {
421426 int TokPrec = GetTokPrecedence();
439444 getNextToken(); // eat binop
440445
441446 // Parse the primary expression after the binary operator.
442 ExprAST *RHS = ParsePrimary();
443 if (!RHS) return 0;
447 auto RHS = ParsePrimary();
448 if (!RHS) return nullptr;
444449
445450 As such, this code eats (and remembers) the binary operator and then
446451 parses the primary expression that follows. This builds up the whole
473478 }
474479
475480 // Merge LHS/RHS.
476 LHS = new BinaryExprAST(BinOp, LHS, RHS);
481 LHS = llvm::make_unique(BinOp, std::move(LHS),
482 std::move(RHS));
477483 } // loop around to the top of the while loop.
478484 }
479485
497503 // the pending operator take RHS as its LHS.
498504 int NextPrec = GetTokPrecedence();
499505 if (TokPrec < NextPrec) {
500 RHS = ParseBinOpRHS(TokPrec+1, RHS);
506 RHS = ParseBinOpRHS(TokPrec+1, std::move(RHS));
501507 if (RHS == 0) return 0;
502508 }
503509 // Merge LHS/RHS.
504 LHS = new BinaryExprAST(BinOp, LHS, RHS);
510 LHS = llvm::make_unique(BinOp, std::move(LHS),
511 std::move(RHS));
505512 } // loop around to the top of the while loop.
506513 }
507514
540547
541548 /// prototype
542549 /// ::= id '(' id* ')'
543 static PrototypeAST *ParsePrototype() {
550 static std::unique_ptr ParsePrototype() {
544551 if (CurTok != tok_identifier)
545552 return ErrorP("Expected function name in prototype");
546553
560567 // success.
561568 getNextToken(); // eat ')'.
562569
563 return new PrototypeAST(FnName, ArgNames);
570 return llvm::make_unique(FnName, std::move(ArgNames));
564571 }
565572
566573 Given this, a function definition is very simple, just a prototype plus
569576 .. code-block:: c++
570577
571578 /// definition ::= 'def' prototype expression
572 static FunctionAST *ParseDefinition() {
579 static std::unique_ptr ParseDefinition() {
573580 getNextToken(); // eat def.
574 PrototypeAST *Proto = ParsePrototype();
575 if (Proto == 0) return 0;
576
577 if (ExprAST *E = ParseExpression())
578 return new FunctionAST(Proto, E);
579 return 0;
581 auto Proto = ParsePrototype();
582 if (!Proto) return nullptr;
583
584 if (auto E = ParseExpression())
585 return llvm::make_unique(std::move(Proto), std::move(E));
586 return nullptr;
580587 }
581588
582589 In addition, we support 'extern' to declare functions like 'sin' and
586593 .. code-block:: c++
587594
588595 /// external ::= 'extern' prototype
589 static PrototypeAST *ParseExtern() {
596 static std::unique_ptr ParseExtern() {
590597 getNextToken(); // eat extern.
591598 return ParsePrototype();
592599 }
598605 .. code-block:: c++
599606
600607 /// toplevelexpr ::= expression
601 static FunctionAST *ParseTopLevelExpr() {
602 if (ExprAST *E = ParseExpression()) {
608 static std::unique_ptr ParseTopLevelExpr() {
609 if (auto E = ParseExpression()) {
603610 // Make an anonymous proto.
604 PrototypeAST *Proto = new PrototypeAST("", std::vector());
605 return new FunctionAST(Proto, E);
611 auto Proto = llvm::make_unique("", std::vector());
612 return llvm::make_unique(std::move(Proto), std::move(E));
606613 }
607 return 0;
614 return nullptr;
608615 }
609616
610617 Now that we have all the pieces, let's build a little driver that will
4141 class NumberExprAST : public ExprAST {
4242 double Val;
4343 public:
44 NumberExprAST(double val) : Val(val) {}
44 NumberExprAST(double Val) : Val(Val) {}
4545 virtual Value *Codegen();
4646 };
4747 ...
259259
260260 static void HandleTopLevelExpression() {
261261 // Evaluate a top-level expression into an anonymous function.
262 if (FunctionAST *F = ParseTopLevelExpr()) {
263 if (Function *LF = F->Codegen()) {
264 LF->dump(); // Dump the function for exposition purposes.
262 if (auto FnAST = ParseTopLevelExpr()) {
263 if (auto *FnIR = FnAST->Codegen()) {
264 FnIR->dump(); // Dump the function for exposition purposes.
265265
266266 // JIT the function, returning a function pointer.
267 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
267 void *FPtr = TheExecutionEngine->getPointerToFunction(FnIR);
268268
269269 // Cast it to the right type (takes no arguments, returns a double) so we
270270 // can call it as a native function.
8989
9090 /// IfExprAST - Expression class for if/then/else.
9191 class IfExprAST : public ExprAST {
92 ExprAST *Cond, *Then, *Else;
92 std::unique Cond, Then, Else;
9393 public:
94 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
95 : Cond(cond), Then(then), Else(_else) {}
94 IfExprAST(std::unique_ptr Cond, std::unique_ptr Then,
95 std::unique_ptr Else)
96 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
9697 virtual Value *Codegen();
9798 };
9899
108109 .. code-block:: c++
109110
110111 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
111 static ExprAST *ParseIfExpr() {
112 static std::unique_ptr ParseIfExpr() {
112113 getNextToken(); // eat the if.
113114
114115 // condition.
115 ExprAST *Cond = ParseExpression();
116 if (!Cond) return 0;
116 auto Cond = ParseExpression();
117 if (!Cond) return nullptr;
117118
118119 if (CurTok != tok_then)
119120 return Error("expected then");
120121 getNextToken(); // eat the then
121122
122 ExprAST *Then = ParseExpression();
123 if (Then == 0) return 0;
123 auto Then = ParseExpression();
124 if (Then) return nullptr;
124125
125126 if (CurTok != tok_else)
126127 return Error("expected else");
127128
128129 getNextToken();
129130
130 ExprAST *Else = ParseExpression();
131 if (!Else) return 0;
132
133 return new IfExprAST(Cond, Then, Else);
131 auto Else = ParseExpression();
132 if (!Else) return nullptr;
133
134 return llvm::make_unique(std::move(Cond), std::move(Then),
135 std::move(Else));
134136 }
135137
136138 Next we hook it up as a primary expression:
137139
138140 .. code-block:: c++
139141
140 static ExprAST *ParsePrimary() {
142 static std::unique_ptr ParsePrimary() {
141143 switch (CurTok) {
142144 default: return Error("unknown token when expecting an expression");
143145 case tok_identifier: return ParseIdentifierExpr();
268270
269271 Value *IfExprAST::Codegen() {
270272 Value *CondV = Cond->Codegen();
271 if (CondV == 0) return 0;
273 if (!CondV) return nullptr;
272274
273275 // Convert condition to a bool by comparing equal to 0.0.
274276 CondV = Builder.CreateFCmpONE(CondV,
463465 /// ForExprAST - Expression class for for/in.
464466 class ForExprAST : public ExprAST {
465467 std::string VarName;
466 ExprAST *Start, *End, *Step, *Body;
468 std::unique_ptr Start, End, Step, Body;
467469 public:
468 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
469 ExprAST *step, ExprAST *body)
470 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
470 ForExprAST(const std::string &VarName, std::unique_ptr Start,
471 std::unique_ptr End, std::unique_ptr Step,
472 std::unique_ptr Body)
473 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
474 Step(std::move(Step)), Body(std::move(Body)) {}
471475 virtual Value *Codegen();
472476 };
473477
482486 .. code-block:: c++
483487
484488 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
485 static ExprAST *ParseForExpr() {
489 static std::unique_ptr ParseForExpr() {
486490 getNextToken(); // eat the for.
487491
488492 if (CurTok != tok_identifier)
496500 getNextToken(); // eat '='.
497501
498502
499 ExprAST *Start = ParseExpression();
500 if (Start == 0) return 0;
503 auto Start = ParseExpression();
504 if (!Start) return nullptr;
501505 if (CurTok != ',')
502506 return Error("expected ',' after for start value");
503507 getNextToken();
504508
505 ExprAST *End = ParseExpression();
506 if (End == 0) return 0;
509 auto End = ParseExpression();
510 if (!End) return nullptr;
507511
508512 // The step value is optional.
509 ExprAST *Step = 0;
513 std::unique_ptr Step;
510514 if (CurTok == ',') {
511515 getNextToken();
512516 Step = ParseExpression();
513 if (Step == 0) return 0;
517 if (!Step) return nullptr;
514518 }
515519
516520 if (CurTok != tok_in)
517521 return Error("expected 'in' after for");
518522 getNextToken(); // eat 'in'.
519523
520 ExprAST *Body = ParseExpression();
521 if (Body == 0) return 0;
522
523 return new ForExprAST(IdName, Start, End, Step, Body);
524 auto Body = ParseExpression();
525 if (!Body) return nullptr;
526
527 return llvm::make_unique(IdName, std::move(Start),
528 std::move(End), std::move(Step),
529 std::move(Body));
524530 }
525531
526532 LLVM IR for the 'for' Loop
128128 class PrototypeAST {
129129 std::string Name;
130130 std::vector Args;
131 bool isOperator;
131 bool IsOperator;
132132 unsigned Precedence; // Precedence if a binary op.
133133 public:
134 PrototypeAST(const std::string &name, const std::vector &args,
135 bool isoperator = false, unsigned prec = 0)
136 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
137
138 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
139 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
134 PrototypeAST(const std::string &name, std::vector Args,
135 bool IsOperator = false, unsigned Prec = 0)
136 : Name(name), Args(std::move(Args)), IsOperator(IsOperator),
137 Precedence(Prec) {}
138
139 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
140 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
140141
141142 char getOperatorName() const {
142143 assert(isUnaryOp() || isBinaryOp());
160161 /// prototype
161162 /// ::= id '(' id* ')'
162163 /// ::= binary LETTER number? (id, id)
163 static PrototypeAST *ParsePrototype() {
164 static std::unique_ptr ParsePrototype() {
164165 std::string FnName;
165166
166167 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
209210 if (Kind && ArgNames.size() != Kind)
210211 return ErrorP("Invalid number of operands for operator");
211212
212 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
213 return llvm::make_unique(FnName, std::move(ArgNames),
214 Kind != 0, BinaryPrecedence);
213215 }
214216
215217 This is all fairly straightforward parsing code, and we have already
304306 /// UnaryExprAST - Expression class for a unary operator.
305307 class UnaryExprAST : public ExprAST {
306308 char Opcode;
307 ExprAST *Operand;
309 std::unique_ptr Operand;
308310 public:
309 UnaryExprAST(char opcode, ExprAST *operand)
310 : Opcode(opcode), Operand(operand) {}
311 UnaryExprAST(char Opcode, std::unique_ptr Operand)
312 : Opcode(Opcode), Operand(std::move(Operand)) {}
311313 virtual Value *Codegen();
312314 };
313315
321323 /// unary
322324 /// ::= primary
323325 /// ::= '!' unary
324 static ExprAST *ParseUnary() {
326 static std::unique_ptr ParseUnary() {
325327 // If the current token is not an operator, it must be a primary expr.
326328 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
327329 return ParsePrimary();
329331 // If this is a unary operator, read it.
330332 int Opc = CurTok;
331333 getNextToken();
332 if (ExprAST *Operand = ParseUnary())
333 return new UnaryExprAST(Opc, Operand);
334 return 0;
334 if (auto Operand = ParseUnary())
335 return llvm::unique_ptr(Opc, std::move(Operand));
336 return nullptr;
335337 }
336338
337339 The grammar we add is pretty straightforward here. If we see a unary
349351
350352 /// binoprhs
351353 /// ::= ('+' unary)*
352 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
354 static std::unique_ptr ParseBinOpRHS(int ExprPrec,
355 std::unique_ptr LHS) {
353356 ...
354357 // Parse the unary expression after the binary operator.
355 ExprAST *RHS = ParseUnary();
356 if (!RHS) return 0;
358 auto RHS = ParseUnary();
359 if (!RHS) return nullptr;
357360 ...
358361 }
359362 /// expression
360363 /// ::= unary binoprhs
361364 ///
362 static ExprAST *ParseExpression() {
363 ExprAST *LHS = ParseUnary();
364 if (!LHS) return 0;
365
366 return ParseBinOpRHS(0, LHS);
365 static std::unique_ptr ParseExpression() {
366 auto LHS = ParseUnary();
367 if (!LHS) return nullptr;
368
369 return ParseBinOpRHS(0, std::move(LHS));
367370 }
368371
369372 With these two simple changes, we are now able to parse unary operators
377380 /// ::= id '(' id* ')'
378381 /// ::= binary LETTER number? (id, id)
379382 /// ::= unary LETTER (id)
380 static PrototypeAST *ParsePrototype() {
383 static std::unique_ptr ParsePrototype() {
381384 std::string FnName;
382385
383386 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
572572 // Special case '=' because we don't want to emit the LHS as an expression.
573573 if (Op == '=') {
574574 // Assignment requires the LHS to be an identifier.
575 VariableExprAST *LHSE = dynamic_cast(LHS);
575 VariableExprAST *LHSE = dynamic_cast(LHS.get());
576576 if (!LHSE)
577577 return ErrorV("destination of '=' must be a variable");
578578
662662
663663 /// VarExprAST - Expression class for var/in
664664 class VarExprAST : public ExprAST {
665 std::vector > VarNames;
666 ExprAST *Body;
665 std::vector>> VarNames;
666 std::unique_ptr Body;
667667 public:
668 VarExprAST(const std::vector > &varnames,
669 ExprAST *body)
670 : VarNames(varnames), Body(body) {}
668 VarExprAST(std::vector>> VarNames,
669 std::unique_ptr body)
670 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
671671
672672 virtual Value *Codegen();
673673 };
689689 /// ::= ifexpr
690690 /// ::= forexpr
691691 /// ::= varexpr
692 static ExprAST *ParsePrimary() {
692 static std::unique_ptr ParsePrimary() {
693693 switch (CurTok) {
694694 default: return Error("unknown token when expecting an expression");
695695 case tok_identifier: return ParseIdentifierExpr();
707707
708708 /// varexpr ::= 'var' identifier ('=' expression)?
709709 // (',' identifier ('=' expression)?)* 'in' expression
710 static ExprAST *ParseVarExpr() {
710 static std::unique_ptr ParseVarExpr() {
711711 getNextToken(); // eat the var.
712712
713 std::vectorExprAST*> > VarNames;
713 std::vectorstd::unique_ptr>> VarNames;
714714
715715 // At least one variable name is required.
716716 if (CurTok != tok_identifier)
726726 getNextToken(); // eat identifier.
727727
728728 // Read the optional initializer.
729 ExprAST *Init = 0;
729 std::unique_ptr Init;
730730 if (CurTok == '=') {
731731 getNextToken(); // eat the '='.
732732
733733 Init = ParseExpression();
734 if (Init == 0) return 0;
734 if (!Init) return nullptr;
735735 }
736736
737 VarNames.push_back(std::make_pair(Name, Init));
737 VarNames.push_back(std::make_pair(Name, std::move(Init)));
738738
739739 // End of var list, exit loop.
740740 if (CurTok != ',') break;
754754 return Error("expected 'in' keyword after 'var'");
755755 getNextToken(); // eat 'in'.
756756
757 ExprAST *Body = ParseExpression();
758 if (Body == 0) return 0;
759
760 return new VarExprAST(VarNames, Body);
757 auto Body = ParseExpression();
758 if (!Body) return nullptr;
759
760 return llvm::make_unique(std::move(VarNames),
761 std::move(Body));
761762 }
762763
763764 Now that we can parse and represent the code, we need to support
773774 // Register all variables and emit their initializer.
774775 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
775776 const std::string &VarName = VarNames[i].first;
776 ExprAST *Init = VarNames[i].second;
777 ExprAST *Init = VarNames[i].second.get();
777778
778779 Basically it loops over all the variables, installing them one at a
779780 time. For each variable we put into the symbol table, we remember the
7474
7575 .. code-block:: udiff
7676
77 - PrototypeAST *Proto = new PrototypeAST("", std::vector());
78 + PrototypeAST *Proto = new PrototypeAST("main", std::vector());
77 - auto Proto = llvm::make_unique("", std::vector());
78 + auto Proto = llvm::make_unique("main", std::vector());
7979
8080 just with the simple change of giving it a name.
8181
107107 @@ -1108,17 +1108,8 @@ static void HandleExtern() {
108108 static void HandleTopLevelExpression() {
109109 // Evaluate a top-level expression into an anonymous function.
110 if (FunctionAST *F = ParseTopLevelExpr()) {
111 - if (Function *LF = F->Codegen()) {
110 if (auto FnAST = ParseTopLevelExpr()) {
111 - if (auto *FnIR = FnAST->Codegen()) {
112112 - // We're just doing this to make sure it executes.
113113 - TheExecutionEngine->finalizeObject();
114114 - // JIT the function, returning a function pointer.
115 - void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
115 - void *FPtr = TheExecutionEngine->getPointerToFunction(FnIR);
116116 -
117117 - // Cast it to the right type (takes no arguments, returns a double) so we
118118 - // can call it as a native function.
317317
318318 .. code-block:: c++
319319
320 LHS = new BinaryExprAST(BinLoc, BinOp, LHS, RHS);
320 LHS = llvm::make_unique(BinLoc, BinOp, std::move(LHS),
321 std::move(RHS));
321322
322323 giving us locations for each of our expressions and variables.
323324
0 #include "llvm/ADT/STLExtras.h"
1 #include
12 #include
2 #include
33 #include
44 #include
55 #include
8484 /// NumberExprAST - Expression class for numeric literals like "1.0".
8585 class NumberExprAST : public ExprAST {
8686 public:
87 NumberExprAST(double val) {}
87 NumberExprAST(double Val) {}
8888 };
8989
9090 /// VariableExprAST - Expression class for referencing a variable, like "a".
9191 class VariableExprAST : public ExprAST {
9292 std::string Name;
9393 public:
94 VariableExprAST(const std::string &name) : Name(name) {}
94 VariableExprAST(const std::string &Name) : Name(Name) {}
9595 };
9696
9797 /// BinaryExprAST - Expression class for a binary operator.
9898 class BinaryExprAST : public ExprAST {
9999 public:
100 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs) {}
100 BinaryExprAST(char Op, std::unique_ptr LHS,
101 std::unique_ptr RHS) {}
101102 };
102103
103104 /// CallExprAST - Expression class for function calls.
104105 class CallExprAST : public ExprAST {
105106 std::string Callee;
106 std::vector Args;
107 public:
108 CallExprAST(const std::string &callee, std::vector &args)
109 : Callee(callee), Args(args) {}
107 std::vector> Args;
108 public:
109 CallExprAST(const std::string &Callee,
110 std::vector> Args)
111 : Callee(Callee), Args(std::move(Args)) {}
110112 };
111113
112114 /// PrototypeAST - This class represents the "prototype" for a function,
116118 std::string Name;
117119 std::vector Args;
118120 public:
119 PrototypeAST(const std::string &name, const std::vector &args)
120 : Name(name), Args(args) {}
121 PrototypeAST(const std::string &Name, std::vector Args)
122 : Name(Name), Args(std::move(Args)) {}
121123
122124 };
123125
124126 /// FunctionAST - This class represents a function definition itself.
125127 class FunctionAST {
126128 public:
127 FunctionAST(PrototypeAST *proto, ExprAST *body) {}
129 FunctionAST(std::unique_ptr Proto,
130 std::unique_ptr Body) {}
128131 };
129132 } // end anonymous namespace
130133
156159 }
157160
158161 /// Error* - These are little helper functions for error handling.
159 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
160 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
161
162 static ExprAST *ParseExpression();
162 std::unique_ptr Error(const char *Str) {
163 fprintf(stderr, "Error: %s\n", Str);
164 return nullptr;
165 }
166 std::unique_ptr ErrorP(const char *Str) {
167 Error(Str);
168 return nullptr;
169 }
170
171 static std::unique_ptr ParseExpression();
163172
164173 /// identifierexpr
165174 /// ::= identifier
166175 /// ::= identifier '(' expression* ')'
167 static ExprAST *ParseIdentifierExpr() {
176 static std::unique_ptr ParseIdentifierExpr() {
168177 std::string IdName = IdentifierStr;
169178
170179 getNextToken(); // eat identifier.
171180
172181 if (CurTok != '(') // Simple variable ref.
173 return new VariableExprAST(IdName);
182 return llvm::make_unique(IdName);
174183
175184 // Call.
176185 getNextToken(); // eat (
177 std::vector<ExprAST*> Args;
186 std::vector<std::unique_ptr> Args;
178187 if (CurTok != ')') {
179188 while (1) {
180 ExprAST *Arg = ParseExpression();
181 if (!Arg) return 0;
182 Args.push_back(Arg);
189 if (auto Arg = ParseExpression())
190 Args.push_back(std::move(Arg));
191 else
192 return nullptr;
183193
184194 if (CurTok == ')') break;
185195
192202 // Eat the ')'.
193203 getNextToken();
194204
195 return new CallExprAST(IdName, Args);
205 return llvm::make_unique(IdName, std::move(Args));
196206 }
197207
198208 /// numberexpr ::= number
199 static ExprAST *ParseNumberExpr() {
200 ExprAST *Result = new NumberExprAST(NumVal);
209 static std::unique_ptr ParseNumberExpr() {
210 auto Result = llvm::make_unique(NumVal);
201211 getNextToken(); // consume the number
202 return Result;
212 return std::move(Result);
203213 }
204214
205215 /// parenexpr ::= '(' expression ')'
206 static ExprAST *ParseParenExpr() {
216 static std::unique_ptr ParseParenExpr() {
207217 getNextToken(); // eat (.
208 ExprAST *V = ParseExpression();
209 if (!V) return 0;
218 auto V = ParseExpression();
219 if (!V)
220 return nullptr;
210221
211222 if (CurTok != ')')
212223 return Error("expected ')'");
218229 /// ::= identifierexpr
219230 /// ::= numberexpr
220231 /// ::= parenexpr
221 static ExprAST *ParsePrimary() {
232 static std::unique_ptr ParsePrimary() {
222233 switch (CurTok) {
223234 default: return Error("unknown token when expecting an expression");
224235 case tok_identifier: return ParseIdentifierExpr();
229240
230241 /// binoprhs
231242 /// ::= ('+' primary)*
232 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
243 static std::unique_ptr ParseBinOpRHS(int ExprPrec,
244 std::unique_ptr LHS) {
233245 // If this is a binop, find its precedence.
234246 while (1) {
235247 int TokPrec = GetTokPrecedence();
244256 getNextToken(); // eat binop
245257
246258 // Parse the primary expression after the binary operator.
247 ExprAST *RHS = ParsePrimary();
248 if (!RHS) return 0;
259 auto RHS = ParsePrimary();
260 if (!RHS) return nullptr;
249261
250262 // If BinOp binds less tightly with RHS than the operator after RHS, let
251263 // the pending operator take RHS as its LHS.
252264 int NextPrec = GetTokPrecedence();
253265 if (TokPrec < NextPrec) {
254 RHS = ParseBinOpRHS(TokPrec+1, RHS);
255 if (RHS == 0) return 0;
266 RHS = ParseBinOpRHS(TokPrec+1, std::move(RHS));
267 if (!RHS) return nullptr;
256268 }
257269
258270 // Merge LHS/RHS.
259 LHS = new BinaryExprAST(BinOp, LHS, RHS);
271 LHS = llvm::make_unique(BinOp, std::move(LHS),
272 std::move(RHS));
260273 }
261274 }
262275
263276 /// expression
264277 /// ::= primary binoprhs
265278 ///
266 static ExprAST *ParseExpression() {
267 ExprAST *LHS = ParsePrimary();
268 if (!LHS) return 0;
269
270 return ParseBinOpRHS(0, LHS);
279 static std::unique_ptr ParseExpression() {
280 auto LHS = ParsePrimary();
281 if (!LHS) return nullptr;
282
283 return ParseBinOpRHS(0, std::move(LHS));
271284 }
272285
273286 /// prototype
274287 /// ::= id '(' id* ')'
275 static PrototypeAST *ParsePrototype() {
288 static std::unique_ptr ParsePrototype() {
276289 if (CurTok != tok_identifier)
277290 return ErrorP("Expected function name in prototype");
278291
291304 // success.
292305 getNextToken(); // eat ')'.
293306
294 return new PrototypeAST(FnName, ArgNames);
307 return llvm::make_unique(std::move(FnName),
308 std::move(ArgNames));
295309 }
296310
297311 /// definition ::= 'def' prototype expression
298 static FunctionAST *ParseDefinition() {
312 static std::unique_ptr ParseDefinition() {
299313 getNextToken(); // eat def.
300 PrototypeAST *Proto = ParsePrototype();
301 if (Proto == 0) return 0;
302
303 if (ExprAST *E = ParseExpression())
304 return new FunctionAST(Proto, E);
305 return 0;
314 auto Proto = ParsePrototype();
315 if (!Proto) return nullptr;
316
317 if (auto E = ParseExpression())
318 return llvm::make_unique(std::move(Proto), std::move(E));
319 return nullptr;
306320 }
307321
308322 /// toplevelexpr ::= expression
309 static FunctionAST *ParseTopLevelExpr() {
310 if (ExprAST *E = ParseExpression()) {
323 static std::unique_ptr ParseTopLevelExpr() {
324 if (auto E = ParseExpression()) {
311325 // Make an anonymous proto.
312 PrototypeAST *Proto = new PrototypeAST("", std::vector());
313 return new FunctionAST(Proto, E);
314 }
315 return 0;
326 auto Proto = llvm::make_unique("",
327 std::vector());
328 return llvm::make_unique(std::move(Proto), std::move(E));
329 }
330 return nullptr;
316331 }
317332
318333 /// external ::= 'extern' prototype
319 static PrototypeAST *ParseExtern() {
334 static std::unique_ptr ParseExtern() {
320335 getNextToken(); // eat extern.
321336 return ParsePrototype();
322337 }
0 #include "llvm/ADT/STLExtras.h"
1 #include "llvm/IR/Verifier.h"
12 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/IRBuilder.h"
9192 class NumberExprAST : public ExprAST {
9293 double Val;
9394 public:
94 NumberExprAST(double val) : Val(val) {}
95 NumberExprAST(double Val) : Val(Val) {}
9596 Value *Codegen() override;
9697 };
9798
99100 class VariableExprAST : public ExprAST {
100101 std::string Name;
101102 public:
102 VariableExprAST(const std::string &name) : Name(name) {}
103 VariableExprAST(const std::string &Name) : Name(Name) {}
103104 Value *Codegen() override;
104105 };
105106
106107 /// BinaryExprAST - Expression class for a binary operator.
107108 class BinaryExprAST : public ExprAST {
108109 char Op;
109 ExprAST *LHS, *RHS;
110 public:
111 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
112 : Op(op), LHS(lhs), RHS(rhs) {}
110 std::unique_ptr LHS, RHS;
111 public:
112 BinaryExprAST(char Op, std::unique_ptr LHS,
113 std::unique_ptr RHS)
114 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
113115 Value *Codegen() override;
114116 };
115117
116118 /// CallExprAST - Expression class for function calls.
117119 class CallExprAST : public ExprAST {
118120 std::string Callee;
119 std::vector Args;
120 public:
121 CallExprAST(const std::string &callee, std::vector &args)
122 : Callee(callee), Args(args) {}
121 std::vector> Args;
122 public:
123 CallExprAST(const std::string &Callee,
124 std::vector> Args)
125 : Callee(Callee), Args(std::move(Args)) {}
123126 Value *Codegen() override;
124127 };
125128
130133 std::string Name;
131134 std::vector Args;
132135 public:
133 PrototypeAST(const std::string &name, const std::vector &args)
134 : Name(name), Args(args) {}
136 PrototypeAST(const std::string &Name, std::vector Args)
137 : Name(Name), Args(std::move(Args)) {}
135138
136139 Function *Codegen();
137140 };
138141
139142 /// FunctionAST - This class represents a function definition itself.
140143 class FunctionAST {
141 PrototypeAST *Proto;
142 ExprAST *Body;
143 public:
144 FunctionAST(PrototypeAST *proto, ExprAST *body)
145 : Proto(proto), Body(body) {}
144 std::unique_ptr Proto;
145 std::unique_ptr Body;
146 public:
147 FunctionAST(std::unique_ptr Proto,
148 std::unique_ptr Body)
149 : Proto(std::move(Proto)), Body(std::move(Body)) {}
146150
147151 Function *Codegen();
148152 };
176180 }
177181
178182 /// Error* - These are little helper functions for error handling.
179 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
180 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
181 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
182
183 static ExprAST *ParseExpression();
183 std::unique_ptr Error(const char *Str) {
184 fprintf(stderr, "Error: %s\n", Str);
185 return nullptr;
186 }
187 std::unique_ptr ErrorP(const char *Str) {
188 Error(Str);
189 return nullptr;
190 }
191 std::unique_ptr ErrorF(const char *Str) {
192 Error(Str);
193 return nullptr;
194 }
195
196 static std::unique_ptr ParseExpression();
184197
185198 /// identifierexpr
186199 /// ::= identifier
187200 /// ::= identifier '(' expression* ')'
188 static ExprAST *ParseIdentifierExpr() {
201 static std::unique_ptr ParseIdentifierExpr() {
189202 std::string IdName = IdentifierStr;
190203
191204 getNextToken(); // eat identifier.
192205
193206 if (CurTok != '(') // Simple variable ref.
194 return new VariableExprAST(IdName);
207 return llvm::make_unique(IdName);
195208
196209 // Call.
197210 getNextToken(); // eat (
198 std::vector<ExprAST*> Args;
211 std::vector<std::unique_ptr> Args;
199212 if (CurTok != ')') {
200213 while (1) {
201 ExprAST *Arg = ParseExpression();
202 if (!Arg) return 0;
203 Args.push_back(Arg);
214 if (auto Arg = ParseExpression())
215 Args.push_back(std::move(Arg));
216 else
217 return nullptr;
204218
205219 if (CurTok == ')') break;
206220
213227 // Eat the ')'.
214228 getNextToken();
215229
216 return new CallExprAST(IdName, Args);
230 return llvm::make_unique(IdName, std::move(Args));
217231 }
218232
219233 /// numberexpr ::= number
220 static ExprAST *ParseNumberExpr() {
221 ExprAST *Result = new NumberExprAST(NumVal);
234 static std::unique_ptr ParseNumberExpr() {
235 auto Result = llvm::make_unique(NumVal);
222236 getNextToken(); // consume the number
223 return Result;
237 return std::move(Result);
224238 }
225239
226240 /// parenexpr ::= '(' expression ')'
227 static ExprAST *ParseParenExpr() {
241 static std::unique_ptr ParseParenExpr() {
228242 getNextToken(); // eat (.
229 ExprAST *V = ParseExpression();
230 if (!V) return 0;
243 auto V = ParseExpression();
244 if (!V)
245 return nullptr;
231246
232247 if (CurTok != ')')
233248 return Error("expected ')'");
239254 /// ::= identifierexpr
240255 /// ::= numberexpr
241256 /// ::= parenexpr
242 static ExprAST *ParsePrimary() {
257 static std::unique_ptr ParsePrimary() {
243258 switch (CurTok) {
244259 default: return Error("unknown token when expecting an expression");
245260 case tok_identifier: return ParseIdentifierExpr();
250265
251266 /// binoprhs
252267 /// ::= ('+' primary)*
253 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
268 static std::unique_ptr ParseBinOpRHS(int ExprPrec,
269 std::unique_ptr LHS) {
254270 // If this is a binop, find its precedence.
255271 while (1) {
256272 int TokPrec = GetTokPrecedence();
265281 getNextToken(); // eat binop
266282
267283 // Parse the primary expression after the binary operator.
268 ExprAST *RHS = ParsePrimary();
269 if (!RHS) return 0;
284 auto RHS = ParsePrimary();
285 if (!RHS) return nullptr;
270286
271287 // If BinOp binds less tightly with RHS than the operator after RHS, let
272288 // the pending operator take RHS as its LHS.
273289 int NextPrec = GetTokPrecedence();
274290 if (TokPrec < NextPrec) {
275 RHS = ParseBinOpRHS(TokPrec+1, RHS);
276 if (RHS == 0) return 0;
291 RHS = ParseBinOpRHS(TokPrec+1, std::move(RHS));
292 if (!RHS) return nullptr;
277293 }
278294
279295 // Merge LHS/RHS.
280 LHS = new BinaryExprAST(BinOp, LHS, RHS);
296 LHS = llvm::make_unique(BinOp, std::move(LHS),
297 std::move(RHS));
281298 }
282299 }
283300
284301 /// expression
285302 /// ::= primary binoprhs
286303 ///
287 static ExprAST *ParseExpression() {
288 ExprAST *LHS = ParsePrimary();
289 if (!LHS) return 0;
290
291 return ParseBinOpRHS(0, LHS);
304 static std::unique_ptr ParseExpression() {
305 auto LHS = ParsePrimary();
306 if (!LHS) return nullptr;
307
308 return ParseBinOpRHS(0, std::move(LHS));
292309 }
293310
294311 /// prototype
295312 /// ::= id '(' id* ')'
296 static PrototypeAST *ParsePrototype() {
313 static std::unique_ptr ParsePrototype() {
297314 if (CurTok != tok_identifier)
298315 return ErrorP("Expected function name in prototype");
299316
312329 // success.
313330 getNextToken(); // eat ')'.
314331
315 return new PrototypeAST(FnName, ArgNames);
332 return llvm::make_unique(std::move(FnName),
333 std::move(ArgNames));
316334 }
317335
318336 /// definition ::= 'def' prototype expression
319 static FunctionAST *ParseDefinition() {
337 static std::unique_ptr ParseDefinition() {
320338 getNextToken(); // eat def.
321 PrototypeAST *Proto = ParsePrototype();
322 if (Proto == 0) return 0;
323
324 if (ExprAST *E = ParseExpression())
325 return new FunctionAST(Proto, E);
326 return 0;
339 auto Proto = ParsePrototype();
340 if (!Proto) return nullptr;
341
342 if (auto E = ParseExpression())
343 return llvm::make_unique(std::move(Proto), std::move(E));
344 return nullptr;
327345 }
328346
329347 /// toplevelexpr ::= expression
330 static FunctionAST *ParseTopLevelExpr() {
331 if (ExprAST *E = ParseExpression()) {
348 static std::unique_ptr ParseTopLevelExpr() {
349 if (auto E = ParseExpression()) {
332350 // Make an anonymous proto.
333 PrototypeAST *Proto = new PrototypeAST("", std::vector());
334 return new FunctionAST(Proto, E);
335 }
336 return 0;
351 auto Proto = llvm::make_unique("",
352 std::vector());
353 return llvm::make_unique(std::move(Proto), std::move(E));
354 }
355 return nullptr;
337356 }
338357
339358 /// external ::= 'extern' prototype
340 static PrototypeAST *ParseExtern() {
359 static std::unique_ptr ParseExtern() {
341360 getNextToken(); // eat extern.
342361 return ParsePrototype();
343362 }
350369 static IRBuilder<> Builder(getGlobalContext());
351370 static std::map NamedValues;
352371
353 Value *ErrorV(const char *Str) { Error(Str); return 0; }
372 Value *ErrorV(const char *Str) { Error(Str); return nullptr; }
354373
355374 Value *NumberExprAST::Codegen() {
356375 return ConstantFP::get(getGlobalContext(), APFloat(Val));
365384 Value *BinaryExprAST::Codegen() {
366385 Value *L = LHS->Codegen();
367386 Value *R = RHS->Codegen();
368 if (L == 0 || R == 0) return 0;
387 if (!L || !R) return nullptr;
369388
370389 switch (Op) {
371390 case '+': return Builder.CreateFAdd(L, R, "addtmp");
383402 Value *CallExprAST::Codegen() {
384403 // Look up the name in the global module table.
385404 Function *CalleeF = TheModule->getFunction(Callee);
386 if (CalleeF == 0)
405 if (!CalleeF)
387406 return ErrorV("Unknown function referenced");
388407
389408 // If argument mismatch error.
393412 std::vector ArgsV;
394413 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
395414 ArgsV.push_back(Args[i]->Codegen());
396 if (ArgsV.back() == 0) return 0;
415 if (!ArgsV.back()) return nullptr;
397416 }
398417
399418 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
406425 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
407426 Doubles, false);
408427
409 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
428 Function *F = Function::Create(FT, Function::ExternalLinkage, Name,
429 TheModule);
410430
411431 // If F conflicted, there was already something named 'Name'. If it has a
412432 // body, don't allow redefinition or reextern.
418438 // If F already has a body, reject this.
419439 if (!F->empty()) {
420440 ErrorF("redefinition of function");
421 return 0;
441 return nullptr;
422442 }
423443
424444 // If F took a different number of args, reject.
425445 if (F->arg_size() != Args.size()) {
426446 ErrorF("redefinition of function with different # args");
427 return 0;
447 return nullptr;
428448 }
429449 }
430450
445465 NamedValues.clear();
446466
447467 Function *TheFunction = Proto->Codegen();
448 if (TheFunction == 0)
449 return 0;
468 if (!TheFunction)
469 return nullptr;
450470
451471 // Create a new basic block to start insertion into.
452472 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
464484
465485 // Error reading body, remove function.
466486 TheFunction->eraseFromParent();
467 return 0;
487 return nullptr;
468488 }
469489
470490 //===----------------------------------------------------------------------===//
472492 //===----------------------------------------------------------------------===//
473493
474494 static void HandleDefinition() {
475 if (FunctionAST *F = ParseDefinition()) {
476 if (Function *LF = F->Codegen()) {
495 if (auto FnAST = ParseDefinition()) {
496 if (auto *FnIR = FnAST->Codegen()) {
477497 fprintf(stderr, "Read function definition:");
478 LF->dump();
498 FnIR->dump();
479499 }
480500 } else {
481501 // Skip token for error recovery.
484504 }
485505
486506 static void HandleExtern() {
487 if (PrototypeAST *P = ParseExtern()) {
488 if (Function *F = P->Codegen()) {
507 if (auto ProtoAST = ParseExtern()) {
508 if (auto *FnIR = ProtoAST->Codegen()) {
489509 fprintf(stderr, "Read extern: ");
490 F->dump();
510 FnIR->dump();
491511 }
492512 } else {
493513 // Skip token for error recovery.
497517
498518 static void HandleTopLevelExpression() {
499519 // Evaluate a top-level expression into an anonymous function.
500 if (FunctionAST *F = ParseTopLevelExpr()) {
501 if (Function *LF = F->Codegen()) {
520 if (auto FnAST = ParseTopLevelExpr()) {
521 if (auto *FnIR = FnAST->Codegen()) {
502522 fprintf(stderr, "Read top-level expression:");
503 LF->dump();
523 FnIR->dump();
504524 }
505525 } else {
506526 // Skip token for error recovery.
552572 getNextToken();
553573
554574 // Make the module, which holds all the code.
555 TheModule = new Module("my cool jit", Context);
575 std::unique_ptr Owner = llvm::make_unique("my cool jit", Context);
576 TheModule = Owner.get();
556577
557578 // Run the main "interpreter loop" now.
558579 MainLoop();
0 #include "llvm/ADT/STLExtras.h"
1 #include "llvm/Analysis/BasicAliasAnalysis.h"
12 #include "llvm/Analysis/Passes.h"
23 #include "llvm/ExecutionEngine/ExecutionEngine.h"
104105 /// NumberExprAST - Expression class for numeric literals like "1.0".
105106 class NumberExprAST : public ExprAST {
106107 double Val;
107
108108 public:
109 NumberExprAST(double val) : Val(val) {}
109 NumberExprAST(double Val) : Val(Val) {}
110110 Value *Codegen() override;
111111 };
112112
113113 /// VariableExprAST - Expression class for referencing a variable, like "a".
114114 class VariableExprAST : public ExprAST {
115115 std::string Name;
116
117116 public:
118 VariableExprAST(const std::string &name) : Name(name) {}
117 VariableExprAST(const std::string &Name) : Name(Name) {}
119118 Value *Codegen() override;
120119 };
121120
122121 /// BinaryExprAST - Expression class for a binary operator.
123122 class BinaryExprAST : public ExprAST {
124123 char Op;
125 ExprAST *LHS, *RHS;
126
124 std::unique_ptr LHS, RHS;
127125 public:
128 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
129 : Op(op), LHS(lhs), RHS(rhs) {}
126 BinaryExprAST(char Op, std::unique_ptr LHS,
127 std::unique_ptr RHS)
128 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
130129 Value *Codegen() override;
131130 };
132131
133132 /// CallExprAST - Expression class for function calls.
134133 class CallExprAST : public ExprAST {
135134 std::string Callee;
136 std::vector Args;
137
135 std::vector> Args;
138136 public:
139 CallExprAST(const std::string &callee, std::vector &args)
140 : Callee(callee), Args(args) {}
137 CallExprAST(const std::string &Callee,
138 std::vector> Args)
139 : Callee(Callee), Args(std::move(Args)) {}
141140 Value *Codegen() override;
142141 };
143142
147146 class PrototypeAST {
148147 std::string Name;
149148 std::vector Args;
150
151149 public:
152 PrototypeAST(const std::string &name, const std::vector &args)
153 : Name(name), Args(args) {}
154
150 PrototypeAST(const std::string &name, std::vector Args)
151 : Name(name), Args(std::move(Args)) {}
155152 Function *Codegen();
156153 };
157154
158155 /// FunctionAST - This class represents a function definition itself.
159156 class FunctionAST {
160 PrototypeAST *Proto;
161 ExprAST *Body;
162
157 std::unique_ptr Proto;
158 std::unique_ptr Body;
163159 public:
164 FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
165
160 FunctionAST(std::unique_ptr Proto,
161 std::unique_ptr Body)
162 : Proto(std::move(Proto)), Body(std::move(Body)) {}
166163 Function *Codegen();
167164 };
168165 } // end anonymous namespace
194191 }
195192
196193 /// Error* - These are little helper functions for error handling.
197 ExprAST *Error(const char *Str) {
194 std::unique_ptr Error(const char *Str) {
198195 fprintf(stderr, "Error: %s\n", Str);
199 return 0;
200 }
201 PrototypeAST *ErrorP(const char *Str) {
196 return nullptr;
197 }
198 std::unique_ptr ErrorP(const char *Str) {
202199 Error(Str);
203 return 0;
204 }
205 FunctionAST *ErrorF(const char *Str) {
200 return nullptr;
201 }
202 std::unique_ptr ErrorF(const char *Str) {
206203 Error(Str);
207 return 0;
208 }
209
210 static ExprAST *ParseExpression();
204 return nullptr;
205 }
206
207 static std::unique_ptr ParseExpression();
211208
212209 /// identifierexpr
213210 /// ::= identifier
214211 /// ::= identifier '(' expression* ')'
215 static ExprAST *ParseIdentifierExpr() {
212 static std::unique_ptr ParseIdentifierExpr() {
216213 std::string IdName = IdentifierStr;
217214
218215 getNextToken(); // eat identifier.
219216
220217 if (CurTok != '(') // Simple variable ref.
221 return new VariableExprAST(IdName);
218 return llvm::make_unique(IdName);
222219
223220 // Call.
224221 getNextToken(); // eat (
225 std::vector<ExprAST *> Args;
222 std::vector<std::unique_ptr> Args;
226223 if (CurTok != ')') {
227224 while (1) {
228 ExprAST *Arg = ParseExpression();
229 if (!Arg)
230 return 0;
231 Args.push_back(Arg);
225 if (auto Arg = ParseExpression())
226 Args.push_back(std::move(Arg));
227 else
228 return nullptr;
232229
233230 if (CurTok == ')')
234231 break;
242239 // Eat the ')'.
243240 getNextToken();
244241
245 return new CallExprAST(IdName, Args);
242 return llvm::make_unique(IdName, std::move(Args));
246243 }
247244
248245 /// numberexpr ::= number
249 static ExprAST *ParseNumberExpr() {
250 ExprAST *Result = new NumberExprAST(NumVal);
246 static std::unique_ptr ParseNumberExpr() {
247 auto Result = llvm::make_unique(NumVal);
251248 getNextToken(); // consume the number
252 return Result;
249 return std::move(Result);
253250 }
254251
255252 /// parenexpr ::= '(' expression ')'
256 static ExprAST *ParseParenExpr() {
253 static std::unique_ptr ParseParenExpr() {
257254 getNextToken(); // eat (.
258 ExprAST *V = ParseExpression();
255 auto V = ParseExpression();
259256 if (!V)
260 return 0;
257 return nullptr;
261258
262259 if (CurTok != ')')
263260 return Error("expected ')'");
269266 /// ::= identifierexpr
270267 /// ::= numberexpr
271268 /// ::= parenexpr
272 static ExprAST *ParsePrimary() {
269 static std::unique_ptr ParsePrimary() {
273270 switch (CurTok) {
274271 default:
275272 return Error("unknown token when expecting an expression");
284281
285282 /// binoprhs
286283 /// ::= ('+' primary)*
287 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
284 static std::unique_ptr ParseBinOpRHS(int ExprPrec,
285 std::unique_ptr LHS) {
288286 // If this is a binop, find its precedence.
289287 while (1) {
290288 int TokPrec = GetTokPrecedence();
299297 getNextToken(); // eat binop
300298
301299 // Parse the primary expression after the binary operator.
302 ExprAST *RHS = ParsePrimary();
300 auto RHS = ParsePrimary();
303301 if (!RHS)
304 return 0;
302 return nullptr;
305303
306304 // If BinOp binds less tightly with RHS than the operator after RHS, let
307305 // the pending operator take RHS as its LHS.
308306 int NextPrec = GetTokPrecedence();
309307 if (TokPrec < NextPrec) {
310 RHS = ParseBinOpRHS(TokPrec + 1, RHS);
311 if (RHS == 0)
312 return 0;
308 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
309 if (!RHS)
310 return nullptr;
313311 }
314312
315313 // Merge LHS/RHS.
316 LHS = new BinaryExprAST(BinOp, LHS, RHS);
314 LHS = llvm::make_unique(BinOp, std::move(LHS),
315 std::move(RHS));
317316 }
318317 }
319318
320319 /// expression
321320 /// ::= primary binoprhs
322321 ///
323 static ExprAST *ParseExpression() {
324 ExprAST *LHS = ParsePrimary();
322 static std::unique_ptr ParseExpression() {
323 auto LHS = ParsePrimary();
325324 if (!LHS)
326 return 0;
327
328 return ParseBinOpRHS(0, LHS);
325 return nullptr;
326
327 return ParseBinOpRHS(0, std::move(LHS));
329328 }
330329
331330 /// prototype
332331 /// ::= id '(' id* ')'
333 static PrototypeAST *ParsePrototype() {
332 static std::unique_ptr ParsePrototype() {
334333 if (CurTok != tok_identifier)
335334 return ErrorP("Expected function name in prototype");
336335
349348 // success.
350349 getNextToken(); // eat ')'.
351350
352 return new PrototypeAST(FnName, ArgNames);
351 return llvm::make_unique(FnName, std::move(ArgNames));
353352 }
354353
355354 /// definition ::= 'def' prototype expression
356 static FunctionAST *ParseDefinition() {
355 static std::unique_ptr ParseDefinition() {
357356 getNextToken(); // eat def.
358 PrototypeAST *Proto = ParsePrototype();
359 if (Proto == 0)
360 return 0;
361
362 if (ExprAST *E = ParseExpression())
363 return new FunctionAST(Proto, E);
364 return 0;
357 auto Proto = ParsePrototype();
358 if (!Proto)
359 return nullptr;
360
361 if (auto E = ParseExpression())
362 return llvm::make_unique(std::move(Proto), std::move(E));
363 return nullptr;
365364 }
366365
367366 /// toplevelexpr ::= expression
368 static FunctionAST *ParseTopLevelExpr() {
369 if (ExprAST *E = ParseExpression()) {
367 static std::unique_ptr ParseTopLevelExpr() {
368 if (auto E = ParseExpression()) {
370369 // Make an anonymous proto.
371 PrototypeAST *Proto = new PrototypeAST("", std::vector());
372 return new FunctionAST(Proto, E);
373 }
374 return 0;
370 auto Proto = llvm::make_unique("",
371 std::vector());
372 return llvm::make_unique(std::move(Proto), std::move(E));
373 }
374 return nullptr;
375375 }
376376
377377 /// external ::= 'extern' prototype
378 static PrototypeAST *ParseExtern() {
378 static std::unique_ptr ParseExtern() {
379379 getNextToken(); // eat extern.
380380 return ParsePrototype();
381381 }
504504 Function *PF = OpenModule->getFunction(FnName);
505505 if (PF && !PF->empty()) {
506506 ErrorF("redefinition of function across modules");
507 return 0;
507 return nullptr;
508508 }
509509
510510 // If we don't have a prototype yet, create one.
625625
626626 Value *ErrorV(const char *Str) {
627627 Error(Str);
628 return 0;
628 return nullptr;
629629 }
630630
631631 Value *NumberExprAST::Codegen() {
641641 Value *BinaryExprAST::Codegen() {
642642 Value *L = LHS->Codegen();
643643 Value *R = RHS->Codegen();
644 if (L == 0 || R == 0)
645 return 0;
644 if (!L || !R)
645 return nullptr;
646646
647647 switch (Op) {
648648 case '+':
664664 Value *CallExprAST::Codegen() {
665665 // Look up the name in the global module table.
666666 Function *CalleeF = JITHelper->getFunction(Callee);
667 if (CalleeF == 0)
667 if (!CalleeF)
668668 return ErrorV("Unknown function referenced");
669669
670670 // If argument mismatch error.
674674 std::vector ArgsV;
675675 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
676676 ArgsV.push_back(Args[i]->Codegen());
677 if (ArgsV.back() == 0)
678 return 0;
677 if (!ArgsV.back())
678 return nullptr;
679679 }
680680
681681 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
703703 // If F already has a body, reject this.
704704 if (!F->empty()) {
705705 ErrorF("redefinition of function");
706 return 0;
706 return nullptr;
707707 }
708708
709709 // If F took a different number of args, reject.
710710 if (F->arg_size() != Args.size()) {
711711 ErrorF("redefinition of function with different # args");
712 return 0;
712 return nullptr;
713713 }
714714 }
715715
730730 NamedValues.clear();
731731
732732 Function *TheFunction = Proto->Codegen();
733 if (TheFunction == 0)
734 return 0;
733 if (!TheFunction)
734 return nullptr;
735735
736736 // Create a new basic block to start insertion into.
737737 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
749749
750750 // Error reading body, remove function.
751751 TheFunction->eraseFromParent();
752 return 0;
752 return nullptr;
753753 }
754754
755755 //===----------------------------------------------------------------------===//
757757 //===----------------------------------------------------------------------===//
758758
759759 static void HandleDefinition() {
760 if (FunctionAST *F = ParseDefinition()) {
761 if (Function *LF = F->Codegen()) {
760 if (auto FnAST = ParseDefinition()) {
761 if (auto *FnIR = FnAST->Codegen()) {
762762 fprintf(stderr, "Read function definition:");
763 LF->dump();
763 FnIR->dump();
764764 }
765765 } else {
766766 // Skip token for error recovery.
769769 }
770770
771771 static void HandleExtern() {
772 if (PrototypeAST *P = ParseExtern()) {
773 if (Function *F = P->Codegen()) {
772 if (auto ProtoAST = ParseExtern()) {
773 if (auto *FnIR = ProtoAST->Codegen()) {
774774 fprintf(stderr, "Read extern: ");
775 F->dump();
775 FnIR->dump();
776776 }
777777 } else {
778778 // Skip token for error recovery.
782782
783783 static void HandleTopLevelExpression() {
784784 // Evaluate a top-level expression into an anonymous function.
785 if (FunctionAST *F = ParseTopLevelExpr()) {
786 if (Function *LF = F->Codegen()) {
785 if (auto FnAST = ParseTopLevelExpr()) {
786 if (auto *FnIR = FnAST->Codegen()) {
787787 // JIT the function, returning a function pointer.
788 void *FPtr = JITHelper->getPointerToFunction(LF);
788 void *FPtr = JITHelper->getPointerToFunction(FnIR);
789789
790790 // Cast it to the right type (takes no arguments, returns a double) so we
791791 // can call it as a native function.
122122 /// NumberExprAST - Expression class for numeric literals like "1.0".
123123 class NumberExprAST : public ExprAST {
124124 double Val;
125
126125 public:
127 NumberExprAST(double val) : Val(val) {}
126 NumberExprAST(double Val) : Val(Val) {}
128127 Value *Codegen() override;
129128 };
130129
131130 /// VariableExprAST - Expression class for referencing a variable, like "a".
132131 class VariableExprAST : public ExprAST {
133132 std::string Name;
134
135133 public:
136 VariableExprAST(const std::string &name) : Name(name) {}
134 VariableExprAST(const std::string &Name) : Name(Name) {}
137135 Value *Codegen() override;
138136 };
139137
140138 /// BinaryExprAST - Expression class for a binary operator.
141139 class BinaryExprAST : public ExprAST {
142140 char Op;
143 ExprAST *LHS, *RHS;
144
141 std::unique_ptr LHS, RHS;
145142 public:
146 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
147 : Op(op), LHS(lhs), RHS(rhs) {}
143 BinaryExprAST(char Op, std::unique_ptr LHS,
144 std::unique_ptr RHS)
145 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
148146 Value *Codegen() override;
149147 };
150148
151149 /// CallExprAST - Expression class for function calls.
152150 class CallExprAST : public ExprAST {
153151 std::string Callee;
154 std::vector Args;
155
152 std::vector> Args;
156153 public:
157 CallExprAST(const std::string &callee, std::vector &args)
158 : Callee(callee), Args(args) {}
154 CallExprAST(const std::string &Callee,
155 std::vector> Args)
156 : Callee(Callee), Args(std::move(Args)) {}
159157 Value *Codegen() override;
160158 };
161159
162160 /// IfExprAST - Expression class for if/then/else.
163161 class IfExprAST : public ExprAST {
164 ExprAST *Cond, *Then, *Else;
165
162 std::unique_ptr Cond, Then, Else;
166163 public:
167 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
168 : Cond(cond), Then(then), Else(_else) {}
164 IfExprAST(std::unique_ptr Cond, std::unique_ptr Then,
165 std::unique_ptr Else)
166 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
169167 Value *Codegen() override;
170168 };
171169
172170 /// ForExprAST - Expression class for for/in.
173171 class ForExprAST : public ExprAST {
174172 std::string VarName;
175 ExprAST *Start, *End, *Step, *Body;
176
173 std::unique_ptr Start, End, Step, Body;
177174 public:
178 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
179 ExprAST *step, ExprAST *body)
180 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
175 ForExprAST(const std::string &VarName, std::unique_ptr Start,
176 std::unique_ptr End, std::unique_ptr Step,
177 std::unique_ptr Body)
178 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
179 Step(std::move(Step)), Body(std::move(Body)) {}
181180 Value *Codegen() override;
182181 };
183182
187186 class PrototypeAST {
188187 std::string Name;
189188 std::vector Args;
190
191189 public:
192 PrototypeAST(const std::string &name, const std::vector &args)
193 : Name(name), Args(args) {}
194
190 PrototypeAST(const std::string &name, std::vector Args)
191 : Name(name), Args(std::move(Args)) {}
195192 Function *Codegen();
196193 };
197194
198195 /// FunctionAST - This class represents a function definition itself.
199196 class FunctionAST {
200 PrototypeAST *Proto;
201 ExprAST *Body;
202
197 std::unique_ptr Proto;
198 std::unique_ptr Body;
203199 public:
204 FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
205
200 FunctionAST(std::unique_ptr Proto,
201 std::unique_ptr Body)
202 : Proto(std::move(Proto)), Body(std::move(Body)) {}
206203 Function *Codegen();
207204 };
208205 } // end anonymous namespace
234231 }
235232
236233 /// Error* - These are little helper functions for error handling.
237 ExprAST *Error(const char *Str) {
234 std::unique_ptr Error(const char *Str) {
238235 fprintf(stderr, "Error: %s\n", Str);
239 return 0;
240 }
241 PrototypeAST *ErrorP(const char *Str) {
236 return nullptr;
237 }
238 std::unique_ptr ErrorP(const char *Str) {
242239 Error(Str);
243 return 0;
244 }
245 FunctionAST *ErrorF(const char *Str) {
240 return nullptr;
241 }
242 std::unique_ptr ErrorF(const char *Str) {
246243 Error(Str);
247 return 0;
248 }
249
250 static ExprAST *ParseExpression();
244 return nullptr;
245 }
246
247 static std::unique_ptr ParseExpression();
251248
252249 /// identifierexpr
253250 /// ::= identifier
254251 /// ::= identifier '(' expression* ')'
255 static ExprAST *ParseIdentifierExpr() {
252 static std::unique_ptr ParseIdentifierExpr() {
256253 std::string IdName = IdentifierStr;
257254
258255 getNextToken(); // eat identifier.
259256
260257 if (CurTok != '(') // Simple variable ref.
261 return new VariableExprAST(IdName);
258 return llvm::make_unique(IdName);
262259
263260 // Call.
264261 getNextToken(); // eat (
265 std::vector<ExprAST *> Args;
262 std::vector<std::unique_ptr> Args;
266263 if (CurTok != ')') {
267264 while (1) {
268 ExprAST *Arg = ParseExpression();
269 if (!Arg)
270 return 0;
271 Args.push_back(Arg);
265 if (auto Arg = ParseExpression())
266 Args.push_back(std::move(Arg));
267 else
268 return nullptr;
272269
273270 if (CurTok == ')')
274271 break;
282279 // Eat the ')'.
283280 getNextToken();
284281
285 return new CallExprAST(IdName, Args);
282 return llvm::make_unique(IdName, std::move(Args));
286283 }
287284
288285 /// numberexpr ::= number
289 static ExprAST *ParseNumberExpr() {
290 ExprAST *Result = new NumberExprAST(NumVal);
286 static std::unique_ptr ParseNumberExpr() {
287 auto Result = llvm::make_unique(NumVal);
291288 getNextToken(); // consume the number
292 return Result;
289 return std::move(Result);
293290 }
294291
295292 /// parenexpr ::= '(' expression ')'
296 static ExprAST *ParseParenExpr() {
293 static std::unique_ptr ParseParenExpr() {
297294 getNextToken(); // eat (.
298 ExprAST *V = ParseExpression();
295 auto V = ParseExpression();
299296 if (!V)
300 return 0;
297 return nullptr;
301298
302299 if (CurTok != ')')
303300 return Error("expected ')'");
306303 }
307304
308305 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
309 static ExprAST *ParseIfExpr() {
306 static std::unique_ptr ParseIfExpr() {
310307 getNextToken(); // eat the if.
311308
312309 // condition.
313 ExprAST *Cond = ParseExpression();
310 auto Cond = ParseExpression();
314311 if (!Cond)
315 return 0;
312 return nullptr;
316313
317314 if (CurTok != tok_then)
318315 return Error("expected then");
319316 getNextToken(); // eat the then
320317
321 ExprAST *Then = ParseExpression();
322 if (Then == 0)
323 return 0;
318 auto Then = ParseExpression();
319 if (!Then)
320 return nullptr;
324321
325322 if (CurTok != tok_else)
326323 return Error("expected else");
327324
328325 getNextToken();
329326
330 ExprAST *Else = ParseExpression();
327 auto Else = ParseExpression();
331328 if (!Else)
332 return 0;
333
334 return new IfExprAST(Cond, Then, Else);
329 return nullptr;
330
331 return llvm::make_unique(std::move(Cond), std::move(Then),
332 std::move(Else));
335333 }
336334
337335 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
338 static ExprAST *ParseForExpr() {
336 static std::unique_ptr ParseForExpr() {
339337 getNextToken(); // eat the for.
340338
341339 if (CurTok != tok_identifier)
348346 return Error("expected '=' after for");
349347 getNextToken(); // eat '='.
350348
351 ExprAST *Start = ParseExpression();
352 if (Start == 0)
353 return 0;
349 auto Start = ParseExpression();
350 if (!Start)
351 return nullptr;
354352 if (CurTok != ',')
355353 return Error("expected ',' after for start value");
356354 getNextToken();
357355
358 ExprAST *End = ParseExpression();
359 if (End == 0)
360 return 0;
356 auto End = ParseExpression();
357 if (!End)
358 return nullptr;
361359
362360 // The step value is optional.
363 ExprAST *Step = 0;
361 std::unique_ptr Step;
364362 if (CurTok == ',') {
365363 getNextToken();
366364 Step = ParseExpression();
367 if (Step == 0)
368 return 0;
365 if (!Step)
366 return nullptr;
369367 }
370368
371369 if (CurTok != tok_in)
372370 return Error("expected 'in' after for");
373371 getNextToken(); // eat 'in'.
374372
375 ExprAST *Body = ParseExpression();
376 if (Body == 0)
377 return 0;
378
379 return new ForExprAST(IdName, Start, End, Step, Body);
373 auto Body = ParseExpression();
374 if (!Body)
375 return nullptr;
376
377 return llvm::make_unique(IdName, std::move(Start), std::move(End),
378 std::move(Step), std::move(Body));
380379 }
381380
382381 /// primary
385384 /// ::= parenexpr
386385 /// ::= ifexpr
387386 /// ::= forexpr
388 static ExprAST *ParsePrimary() {
387 static std::unique_ptr ParsePrimary() {
389388 switch (CurTok) {
390389 default:
391390 return Error("unknown token when expecting an expression");
404403
405404 /// binoprhs
406405 /// ::= ('+' primary)*
407 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
406 static std::unique_ptr ParseBinOpRHS(int ExprPrec,
407 std::unique_ptr LHS) {
408408 // If this is a binop, find its precedence.
409409 while (1) {
410410 int TokPrec = GetTokPrecedence();
419419 getNextToken(); // eat binop
420420
421421 // Parse the primary expression after the binary operator.
422 ExprAST *RHS = ParsePrimary();
422 auto RHS = ParsePrimary();
423423 if (!RHS)
424 return 0;
424 return nullptr;
425425
426426 // If BinOp binds less tightly with RHS than the operator after RHS, let
427427 // the pending operator take RHS as its LHS.
428428 int NextPrec = GetTokPrecedence();
429429 if (TokPrec < NextPrec) {
430 RHS = ParseBinOpRHS(TokPrec + 1, RHS);
431 if (RHS == 0)
432 return 0;
430 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
431 if (!RHS)
432 return nullptr;
433433 }
434434
435435 // Merge LHS/RHS.
436 LHS = new BinaryExprAST(BinOp, LHS, RHS);
436 LHS = llvm::make_unique(BinOp, std::move(LHS),
437 std::move(RHS));
437438 }
438439 }
439440
440441 /// expression
441442 /// ::= primary binoprhs
442443 ///
443 static ExprAST *ParseExpression() {
444 ExprAST *LHS = ParsePrimary();
444 static std::unique_ptr ParseExpression() {
445 auto LHS = ParsePrimary();
445446 if (!LHS)
446 return 0;
447
448 return ParseBinOpRHS(0, LHS);
447 return nullptr;
448
449 return ParseBinOpRHS(0, std::move(LHS));
449450 }
450451
451452 /// prototype
452453 /// ::= id '(' id* ')'
453 static PrototypeAST *ParsePrototype() {
454 static std::unique_ptr ParsePrototype() {
454455 if (CurTok != tok_identifier)
455456 return ErrorP("Expected function name in prototype");
456457
469470 // success.
470471 getNextToken(); // eat ')'.
471472
472 return new PrototypeAST(FnName, ArgNames);
473 return llvm::make_unique(FnName, std::move(ArgNames));
473474 }
474475
475476 /// definition ::= 'def' prototype expression
476 static FunctionAST *ParseDefinition() {
477 static std::unique_ptr ParseDefinition() {
477478 getNextToken(); // eat def.
478 PrototypeAST *Proto = ParsePrototype();
479 if (Proto == 0)
480 return 0;
481
482 if (ExprAST *E = ParseExpression())
483 return new FunctionAST(Proto, E);
484 return 0;
479 auto Proto = ParsePrototype();
480 if (!Proto)
481 return nullptr;
482
483 if (auto E = ParseExpression())
484 return llvm::make_unique(std::move(Proto), std::move(E));
485 return nullptr;
485486 }
486487
487488 /// toplevelexpr ::= expression
488 static FunctionAST *ParseTopLevelExpr() {
489 if (ExprAST *E = ParseExpression()) {
489 static std::unique_ptr ParseTopLevelExpr() {
490 if (auto E = ParseExpression()) {
490491 // Make an anonymous proto.
491 PrototypeAST *Proto = new PrototypeAST("", std::vector());
492 return new FunctionAST(Proto, E);
493 }
494 return 0;
492 auto Proto = llvm::make_unique("",
493 std::vector());
494 return llvm::make_unique(std::move(Proto), std::move(E));
495 }
496 return nullptr;
495497 }
496498
497499 /// external ::= 'extern' prototype
498 static PrototypeAST *ParseExtern() {
500 static std::unique_ptr ParseExtern() {
499501 getNextToken(); // eat extern.
500502 return ParsePrototype();
501503 }
511513
512514 Value *ErrorV(const char *Str) {
513515 Error(Str);
514 return 0;
516 return nullptr;
515517 }
516518
517519 Value *NumberExprAST::Codegen() {
527529 Value *BinaryExprAST::Codegen() {
528530 Value *L = LHS->Codegen();
529531 Value *R = RHS->Codegen();
530 if (L == 0 || R == 0)
531 return 0;
532 if (!L || !R)
533 return nullptr;
532534
533535 switch (Op) {
534536 case '+':
550552 Value *CallExprAST::Codegen() {
551553 // Look up the name in the global module table.
552554 Function *CalleeF = TheModule->getFunction(Callee);
553 if (CalleeF == 0)
555 if (!CalleeF)
554556 return ErrorV("Unknown function referenced");
555557
556558 // If argument mismatch error.
560562 std::vector ArgsV;
561563 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
562564 ArgsV.push_back(Args[i]->Codegen());
563 if (ArgsV.back() == 0)
564 return 0;
565 if (!ArgsV.back())
566 return nullptr;
565567 }
566568
567569 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
569571
570572 Value *IfExprAST::Codegen() {
571573 Value *CondV = Cond->Codegen();
572 if (CondV == 0)
573 return 0;
574 if (!CondV)
575 return nullptr;
574576
575577 // Convert condition to a bool by comparing equal to 0.0.
576578 CondV = Builder.CreateFCmpONE(
591593 Builder.SetInsertPoint(ThenBB);
592594
593595 Value *ThenV = Then->Codegen();
594 if (ThenV == 0)
595 return 0;
596 if (!ThenV)
597 return nullptr;
596598
597599 Builder.CreateBr(MergeBB);
598600 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
603605 Builder.SetInsertPoint(ElseBB);
604606
605607 Value *ElseV = Else->Codegen();
606 if (ElseV == 0)
607 return 0;
608 if (!ElseV)
609 return nullptr;
608610
609611 Builder.CreateBr(MergeBB);
610612 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
640642
641643 // Emit the start code first, without 'variable' in scope.
642644 Value *StartVal = Start->Codegen();
643 if (StartVal == 0)
644 return 0;
645 if (!StartVal)
646 return nullptr;
645647
646648 // Make the new basic block for the loop header, inserting after current
647649 // block.
669671 // Emit the body of the loop. This, like any other expr, can change the
670672 // current BB. Note that we ignore the value computed by the body, but don't
671673 // allow an error.
672 if (Body->Codegen() == 0)
673 return 0;
674 if (!Body->Codegen())
675 return nullptr;
674676
675677 // Emit the step value.
676678 Value *StepVal;
677679 if (Step) {
678680 StepVal = Step->Codegen();
679 if (StepVal == 0)
680 return 0;
681 if (!StepVal)
682 return nullptr;
681683 } else {
682684 // If not specified, use 1.0.
683685 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
687689
688690 // Compute the end condition.
689691 Value *EndCond = End->Codegen();
690 if (EndCond == 0)
692 if (!EndCond)
691693 return EndCond;
692694
693695 // Convert condition to a bool by comparing equal to 0.0.
738740 // If F already has a body, reject this.
739741 if (!F->empty()) {
740742 ErrorF("redefinition of function");
741 return 0;
743 return nullptr;
742744 }
743745
744746 // If F took a different number of args, reject.
745747 if (F->arg_size() != Args.size()) {
746748 ErrorF("redefinition of function with different # args");
747 return 0;
749 return nullptr;
748750 }
749751 }
750752
765767 NamedValues.clear();
766768
767769 Function *TheFunction = Proto->Codegen();
768 if (TheFunction == 0)
769 return 0;
770 if (!TheFunction)
771 return nullptr;
770772
771773 // Create a new basic block to start insertion into.
772774 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
787789
788790 // Error reading body, remove function.
789791 TheFunction->eraseFromParent();
790 return 0;
792 return nullptr;
791793 }
792794
793795 //===----------------------------------------------------------------------===//
797799 static ExecutionEngine *TheExecutionEngine;
798800
799801 static void HandleDefinition() {
800 if (FunctionAST *F = ParseDefinition()) {
801 if (Function *LF = F->Codegen()) {
802 if (auto FnAST = ParseDefinition()) {
803 if (auto *FnIR = FnAST->Codegen()) {
802804 fprintf(stderr, "Read function definition:");
803 LF->dump();
805 FnIR->dump();
804806 }
805807 } else {
806808 // Skip token for error recovery.
809811 }
810812
811813 static void HandleExtern() {
812 if (PrototypeAST *P = ParseExtern()) {
813 if (Function *F = P->Codegen()) {
814 if (auto ProtoAST = ParseExtern()) {
815 if (auto *FnIR = ProtoAST->Codegen()) {
814816 fprintf(stderr, "Read extern: ");
815 F->dump();
817 FnIR->dump();
816818 }
817819 } else {
818820 // Skip token for error recovery.
822824
823825 static void HandleTopLevelExpression() {
824826 // Evaluate a top-level expression into an anonymous function.
825 if (FunctionAST *F = ParseTopLevelExpr()) {
826 if (Function *LF = F->Codegen()) {
827 if (auto FnAST = ParseTopLevelExpr()) {
828 if (auto *FnIR = FnAST->Codegen()) {
827829 TheExecutionEngine->finalizeObject();
828830 // JIT the function, returning a function pointer.
829 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
831 void *FPtr = TheExecutionEngine->getPointerToFunction(FnIR);
830832
831833 // Cast it to the right type (takes no arguments, returns a double) so we
832834 // can call it as a native function.
130130 /// NumberExprAST - Expression class for numeric literals like "1.0".
131131 class NumberExprAST : public ExprAST {
132132 double Val;
133
134133 public:
135 NumberExprAST(double val) : Val(val) {}
134 NumberExprAST(double Val) : Val(Val) {}
136135 Value *Codegen() override;
137136 };
138137
139138 /// VariableExprAST - Expression class for referencing a variable, like "a".
140139 class VariableExprAST : public ExprAST {
141140 std::string Name;
142
143141 public:
144 VariableExprAST(const std::string &name) : Name(name) {}
142 VariableExprAST(const std::string &Name) : Name(Name) {}
145143 Value *Codegen() override;
146144 };
147145
148146 /// UnaryExprAST - Expression class for a unary operator.
149147 class UnaryExprAST : public ExprAST {
150148 char Opcode;
151 ExprAST *Operand;
149 std::unique_ptr Operand;
152150
153151 public:
154 UnaryExprAST(char opcode, ExprAST *operand)
155 : Opcode(opcode), Operand(operand) {}
152 UnaryExprAST(char Opcode, std::unique_ptr Operand)
153 : Opcode(Opcode), Operand(std::move(Operand)) {}
156154 Value *Codegen() override;
157155 };
158156
159157 /// BinaryExprAST - Expression class for a binary operator.
160158 class BinaryExprAST : public ExprAST {
161159 char Op;
162 ExprAST *LHS, *RHS;
163
160 std::unique_ptr LHS, RHS;
164161 public:
165 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
166 : Op(op), LHS(lhs), RHS(rhs) {}
162 BinaryExprAST(char Op, std::unique_ptr LHS,
163 std::unique_ptr RHS)
164 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
167165 Value *Codegen() override;
168166 };
169167
170168 /// CallExprAST - Expression class for function calls.
171169 class CallExprAST : public ExprAST {
172170 std::string Callee;
173 std::vector Args;
174
171 std::vector> Args;
175172 public:
176 CallExprAST(const std::string &callee, std::vector &args)
177 : Callee(callee), Args(args) {}
173 CallExprAST(const std::string &Callee,
174 std::vector> Args)
175 : Callee(Callee), Args(std::move(Args)) {}
178176 Value *Codegen() override;
179177 };
180178
181179 /// IfExprAST - Expression class for if/then/else.
182180 class IfExprAST : public ExprAST {
183 ExprAST *Cond, *Then, *Else;
184
181 std::unique_ptr Cond, Then, Else;
185182 public:
186 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
187 : Cond(cond), Then(then), Else(_else) {}
183 IfExprAST(std::unique_ptr Cond, std::unique_ptr Then,
184 std::unique_ptr Else)
185 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
188186 Value *Codegen() override;
189187 };
190188
191189 /// ForExprAST - Expression class for for/in.
192190 class ForExprAST : public ExprAST {
193191 std::string VarName;
194 ExprAST *Start, *End, *Step, *Body;
195
192 std::unique_ptr Start, End, Step, Body;
196193 public:
197 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
198 ExprAST *step, ExprAST *body)
199 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
194 ForExprAST(const std::string &VarName, std::unique_ptr Start,
195 std::unique_ptr End, std::unique_ptr Step,
196 std::unique_ptr Body)
197 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
198 Step(std::move(Step)), Body(std::move(Body)) {}
200199 Value *Codegen() override;
201200 };
202201
206205 class PrototypeAST {
207206 std::string Name;
208207 std::vector Args;
209 bool isOperator;
208 bool IsOperator;
210209 unsigned Precedence; // Precedence if a binary op.
211210 public:
212 PrototypeAST(const std::string &name, const std::vector &args,
213 bool isoperator = false, unsigned prec = 0)
214 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
215
216 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
217 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
211 PrototypeAST(const std::string &Name, std::vector Args,
212 bool IsOperator = false, unsigned Prec = 0)
213 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
214 Precedence(Prec) {}
215
216 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
217 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
218218
219219 char getOperatorName() const {
220220 assert(isUnaryOp() || isBinaryOp());
228228
229229 /// FunctionAST - This class represents a function definition itself.
230230 class FunctionAST {
231 PrototypeAST *Proto;
232 ExprAST *Body;
233
231 std::unique_ptr Proto;
232 std::unique_ptr Body;
234233 public:
235 FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
236
234 FunctionAST(std::unique_ptr Proto, std::unique_ptr Body)
235 : Proto(std::move(Proto)), Body(std::move(Body)) {}
237236 Function *Codegen();
238237 };
239238 } // end anonymous namespace
265264 }
266265
267266 /// Error* - These are little helper functions for error handling.
268 ExprAST *Error(const char *Str) {
267 std::unique_ptr Error(const char *Str) {
269268 fprintf(stderr, "Error: %s\n", Str);
270 return 0;
271 }
272 PrototypeAST *ErrorP(const char *Str) {
269 return nullptr;
270 }
271 std::unique_ptr ErrorP(const char *Str) {
273272 Error(Str);
274 return 0;
275 }
276 FunctionAST *ErrorF(const char *Str) {
273 return nullptr;
274 }
275 std::unique_ptr ErrorF(const char *Str) {
277276 Error(Str);
278 return 0;
279 }
280
281 static ExprAST *ParseExpression();
277 return nullptr;
278 }
279
280 static std::unique_ptr ParseExpression();
282281
283282 /// identifierexpr
284283 /// ::= identifier
285284 /// ::= identifier '(' expression* ')'
286 static ExprAST *ParseIdentifierExpr() {
285 static std::unique_ptr ParseIdentifierExpr() {
287286 std::string IdName = IdentifierStr;
288287
289288 getNextToken(); // eat identifier.
290289
291290 if (CurTok != '(') // Simple variable ref.
292 return new VariableExprAST(IdName);
291 return llvm::make_unique(IdName);
293292
294293 // Call.
295294 getNextToken(); // eat (
296 std::vector<ExprAST *> Args;
295 std::vector<std::unique_ptr> Args;
297296 if (CurTok != ')') {
298297 while (1) {
299 ExprAST *Arg = ParseExpression();
300 if (!Arg)
301 return 0;
302 Args.push_back(Arg);
298 if (auto Arg = ParseExpression())
299 Args.push_back(std::move(Arg));
300 else
301 return nullptr;
303302
304303 if (CurTok == ')')
305304 break;
313312 // Eat the ')'.
314313 getNextToken();
315314
316 return new CallExprAST(IdName, Args);
315 return llvm::make_unique(IdName, std::move(Args));
317316 }
318317
319318 /// numberexpr ::= number
320 static ExprAST *ParseNumberExpr() {
321 ExprAST *Result = new NumberExprAST(NumVal);
319 static std::unique_ptr ParseNumberExpr() {
320 auto Result = llvm::make_unique(NumVal);
322321 getNextToken(); // consume the number
323 return Result;
322 return std::move(Result);
324323 }
325324
326325 /// parenexpr ::= '(' expression ')'
327 static ExprAST *ParseParenExpr() {
326 static std::unique_ptr ParseParenExpr() {
328327 getNextToken(); // eat (.
329 ExprAST *V = ParseExpression();
328 auto V = ParseExpression();
330329 if (!V)
331 return 0;
330 return nullptr;
332331
333332 if (CurTok != ')')
334333 return Error("expected ')'");
337336 }
338337
339338 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
340 static ExprAST *ParseIfExpr() {
339 static std::unique_ptr ParseIfExpr() {
341340 getNextToken(); // eat the if.
342341
343342 // condition.
344 ExprAST *Cond = ParseExpression();
343 auto Cond = ParseExpression();
345344 if (!Cond)
346 return 0;
345 return nullptr;
347346
348347 if (CurTok != tok_then)
349348 return Error("expected then");
350349 getNextToken(); // eat the then
351350
352 ExprAST *Then = ParseExpression();
353 if (Then == 0)
354 return 0;
351 auto Then = ParseExpression();
352 if (!Then)
353 return nullptr;
355354
356355 if (CurTok != tok_else)
357356 return Error("expected else");
358357
359358 getNextToken();
360359
361 ExprAST *Else = ParseExpression();
360 auto Else = ParseExpression();
362361 if (!Else)
363 return 0;
364
365 return new IfExprAST(Cond, Then, Else);
362 return nullptr;
363
364 return llvm::make_unique(std::move(Cond), std::move(Then),
365 std::move(Else));
366366 }
367367
368368 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
369 static ExprAST *ParseForExpr() {
369 static std::unique_ptr ParseForExpr() {
370370 getNextToken(); // eat the for.
371371
372372 if (CurTok != tok_identifier)
379379 return Error("expected '=' after for");
380380 getNextToken(); // eat '='.
381381
382 ExprAST *Start = ParseExpression();
383 if (Start == 0)
384 return 0;
382 auto Start = ParseExpression();
383 if (!Start)
384 return nullptr;
385385 if (CurTok != ',')
386386 return Error("expected ',' after for start value");
387387 getNextToken();
388388
389 ExprAST *End = ParseExpression();
390 if (End == 0)
391 return 0;
389 auto End = ParseExpression();
390 if (!End)
391 return nullptr;
392392
393393 // The step value is optional.
394 ExprAST *Step = 0;
394 std::unique_ptr Step;
395395 if (CurTok == ',') {
396396 getNextToken();
397397 Step = ParseExpression();
398 if (Step == 0)
399 return 0;
398 if (!Step)
399 return nullptr;
400400 }
401401
402402 if (CurTok != tok_in)
403403 return Error("expected 'in' after for");
404404 getNextToken(); // eat 'in'.
405405
406 ExprAST *Body = ParseExpression();
407 if (Body == 0)
408 return 0;
409
410 return new ForExprAST(IdName, Start, End, Step, Body);
406 auto Body = ParseExpression();
407 if (!Body)
408 return nullptr;
409
410 return llvm::make_unique(IdName, std::move(Start), std::move(End),
411 std::move(Step), std::move(Body));
411412 }
412413
413414 /// primary
416417 /// ::= parenexpr
417418 /// ::= ifexpr
418419 /// ::= forexpr
419 static ExprAST *ParsePrimary() {
420 static std::unique_ptr ParsePrimary() {
420421 switch (CurTok) {
421422 default:
422423 return Error("unknown token when expecting an expression");
436437 /// unary
437438 /// ::= primary
438439 /// ::= '!' unary
439 static ExprAST *ParseUnary() {
440 static std::unique_ptr ParseUnary() {
440441 // If the current token is not an operator, it must be a primary expr.
441442 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
442443 return ParsePrimary();
444445 // If this is a unary operator, read it.
445446 int Opc = CurTok;
446447 getNextToken();
447 if (ExprAST *Operand = ParseUnary())
448 return new UnaryExprAST(Opc, Operand);
449 return 0;
448 if (auto Operand = ParseUnary())
449 return llvm::make_unique(Opc, std::move(Operand));
450 return nullptr;
450451 }
451452
452453 /// binoprhs
453454 /// ::= ('+' unary)*
454 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
455 static std::unique_ptr ParseBinOpRHS(int ExprPrec, std::unique_ptr LHS) {
455456 // If this is a binop, find its precedence.
456457 while (1) {
457458 int TokPrec = GetTokPrecedence();
466467 getNextToken(); // eat binop
467468
468469 // Parse the unary expression after the binary operator.
469 ExprAST *RHS = ParseUnary();
470 auto RHS = ParseUnary();
470471 if (!RHS)
471 return 0;
472 return nullptr;
472473
473474 // If BinOp binds less tightly with RHS than the operator after RHS, let
474475 // the pending operator take RHS as its LHS.
475476 int NextPrec = GetTokPrecedence();
476477 if (TokPrec < NextPrec) {
477 RHS = ParseBinOpRHS(TokPrec + 1, RHS);
478 if (RHS == 0)
479 return 0;
478 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
479 if (!RHS)
480 return nullptr;
480481 }
481482
482483 // Merge LHS/RHS.
483 LHS = new BinaryExprAST(BinOp, LHS, RHS);
484 LHS = llvm::make_unique(BinOp, std::move(LHS), std::move(RHS));
484485 }
485486 }
486487
487488 /// expression
488489 /// ::= unary binoprhs
489490 ///
490 static ExprAST *ParseExpression() {
491 ExprAST *LHS = ParseUnary();
491 static std::unique_ptr ParseExpression() {
492 auto LHS = ParseUnary();
492493 if (!LHS)
493 return 0;
494
495 return ParseBinOpRHS(0, LHS);
494 return nullptr;
495
496 return ParseBinOpRHS(0, std::move(LHS));
496497 }
497498
498499 /// prototype
499500 /// ::= id '(' id* ')'
500501 /// ::= binary LETTER number? (id, id)
501502 /// ::= unary LETTER (id)
502 static PrototypeAST *ParsePrototype() {
503 static std::unique_ptr ParsePrototype() {
503504 std::string FnName;
504505
505506 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
557558 if (Kind && ArgNames.size() != Kind)
558559 return ErrorP("Invalid number of operands for operator");
559560
560 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
561 return llvm::make_unique(FnName, ArgNames, Kind != 0,
562 BinaryPrecedence);
561563 }
562564
563565 /// definition ::= 'def' prototype expression
564 static FunctionAST *ParseDefinition() {
566 static std::unique_ptr ParseDefinition() {
565567 getNextToken(); // eat def.
566 PrototypeAST *Proto = ParsePrototype();
567 if (Proto == 0)
568 return 0;
569
570 if (ExprAST *E = ParseExpression())
571 return new FunctionAST(Proto, E);
572 return 0;
568 auto Proto = ParsePrototype();
569 if (!Proto)
570 return nullptr;
571
572 if (auto E = ParseExpression())
573 return llvm::make_unique(std::move(Proto), std::move(E));
574 return nullptr;
573575 }
574576
575577 /// toplevelexpr ::= expression
576 static FunctionAST *ParseTopLevelExpr() {
577 if (ExprAST *E = ParseExpression()) {
578 static std::unique_ptr ParseTopLevelExpr() {
579 if (auto E = ParseExpression()) {
578580 // Make an anonymous proto.
579 PrototypeAST *Proto = new PrototypeAST("", std::vector());
580 return new FunctionAST(Proto, E);
581 }
582 return 0;
581 auto Proto = llvm::make_unique("", std::vector());
582 return llvm::make_unique(std::move(Proto), std::move(E));
583 }
584 return nullptr;
583585 }
584586
585587 /// external ::= 'extern' prototype
586 static PrototypeAST *ParseExtern() {
588 static std::unique_ptr ParseExtern() {
587589 getNextToken(); // eat extern.
588590 return ParsePrototype();
589591 }
599601
600602 Value *ErrorV(const char *Str) {
601603 Error(Str);
602 return 0;
604 return nullptr;
603605 }
604606
605607 Value *NumberExprAST::Codegen() {
614616
615617 Value *UnaryExprAST::Codegen() {
616618 Value *OperandV = Operand->Codegen();
617 if (OperandV == 0)
618 return 0;
619 if (!OperandV)
620 return nullptr;
619621
620622 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
621 if (F == 0)
623 if (!F)
622624 return ErrorV("Unknown unary operator");
623625
624626 return Builder.CreateCall(F, OperandV, "unop");
627629 Value *BinaryExprAST::Codegen() {
628630 Value *L = LHS->Codegen();
629631 Value *R = RHS->Codegen();
630 if (L == 0 || R == 0)
631 return 0;
632 if (!L || !R)
633 return nullptr;
632634
633635 switch (Op) {
634636 case '+':
658660 Value *CallExprAST::Codegen() {
659661 // Look up the name in the global module table.
660662 Function *CalleeF = TheModule->getFunction(Callee);
661 if (CalleeF == 0)
663 if (!CalleeF)
662664 return ErrorV("Unknown function referenced");
663665
664666 // If argument mismatch error.
668670 std::vector ArgsV;
669671 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
670672 ArgsV.push_back(Args[i]->Codegen());
671 if (ArgsV.back() == 0)
672 return 0;
673 if (!ArgsV.back())
674 return nullptr;
673675 }
674676
675677 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
677679
678680 Value *IfExprAST::Codegen() {
679681 Value *CondV = Cond->Codegen();
680 if (CondV == 0)
681 return 0;
682 if (!CondV)
683 return nullptr;
682684
683685 // Convert condition to a bool by comparing equal to 0.0.
684686 CondV = Builder.CreateFCmpONE(
699701 Builder.SetInsertPoint(ThenBB);
700702
701703 Value *ThenV = Then->Codegen();
702 if (ThenV == 0)
703 return 0;
704 if (!ThenV)
705 return nullptr;
704706
705707 Builder.CreateBr(MergeBB);
706708 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
711713 Builder.SetInsertPoint(ElseBB);
712714
713715 Value *ElseV = Else->Codegen();
714 if (ElseV == 0)
715 return 0;
716 if (!ElseV)
717 return nullptr;
716718
717719 Builder.CreateBr(MergeBB);
718720 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
748750
749751 // Emit the start code first, without 'variable' in scope.
750752 Value *StartVal = Start->Codegen();
751 if (StartVal == 0)
752 return 0;
753 if (!StartVal)
754 return nullptr;
753755
754756 // Make the new basic block for the loop header, inserting after current
755757 // block.
777779 // Emit the body of the loop. This, like any other expr, can change the
778780 // current BB. Note that we ignore the value computed by the body, but don't
779781 // allow an error.
780 if (Body->Codegen() == 0)
781 return 0;
782 if (!Body->Codegen())
783 return nullptr;
782784
783785 // Emit the step value.
784786 Value *StepVal;
785787 if (Step) {
786788 StepVal = Step->Codegen();
787 if (StepVal == 0)
788 return 0;
789 if (!StepVal)
790 return nullptr;
789791 } else {
790792 // If not specified, use 1.0.
791793 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
795797
796798 // Compute the end condition.
797799 Value *EndCond = End->Codegen();
798 if (EndCond == 0)
800 if (!EndCond)
799801 return EndCond;
800802
801803 // Convert condition to a bool by comparing equal to 0.0.
846848 // If F already has a body, reject this.
847849 if (!F->empty()) {
848850 ErrorF("redefinition of function");
849 return 0;
851 return nullptr;
850852 }
851853
852854 // If F took a different number of args, reject.
853855 if (F->arg_size() != Args.size()) {
854856 ErrorF("redefinition of function with different # args");
855 return 0;
857 return nullptr;
856858 }
857859 }
858860
873875 NamedValues.clear();
874876
875877 Function *TheFunction = Proto->Codegen();
876 if (TheFunction == 0)
877 return 0;
878 if (!TheFunction)
879 return nullptr;
878880
879881 // If this is an operator, install it.
880882 if (Proto->isBinaryOp())
902904
903905 if (Proto->isBinaryOp())
904906 BinopPrecedence.erase(Proto->getOperatorName());
905 return 0;
907 return nullptr;
906908 }
907909
908910 //===----------------------------------------------------------------------===//
912914 static ExecutionEngine *TheExecutionEngine;
913915
914916 static void HandleDefinition() {
915 if (FunctionAST *F = ParseDefinition()) {
916 if (Function *LF = F->Codegen()) {
917 if (auto FnAST = ParseDefinition()) {
918 if (auto *FnIR = FnAST->Codegen()) {
917919 fprintf(stderr, "Read function definition:");
918 LF->dump();
920 FnIR->dump();
919921 }
920922 } else {
921923 // Skip token for error recovery.
924926 }
925927
926928 static void HandleExtern() {
927 if (PrototypeAST *P = ParseExtern()) {
928 if (Function *F = P->Codegen()) {
929 if (auto ProtoAST = ParseExtern()) {
930 if (auto *FnIR = ProtoAST->Codegen()) {
929931 fprintf(stderr, "Read extern: ");
930 F->dump();
932 FnIR->dump();
931933 }
932934 } else {
933935 // Skip token for error recovery.
937939
938940 static void HandleTopLevelExpression() {
939941 // Evaluate a top-level expression into an anonymous function.
940 if (FunctionAST *F = ParseTopLevelExpr()) {
941 if (Function *LF = F->Codegen()) {
942 if (auto FnAST = ParseTopLevelExpr()) {
943 if (auto *FnIR = FnAST->Codegen()) {
942944 TheExecutionEngine->finalizeObject();
943945 // JIT the function, returning a function pointer.
944 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
946 void *FPtr = TheExecutionEngine->getPointerToFunction(FnIR);
945947
946948 // Cast it to the right type (takes no arguments, returns a double) so we
947949 // can call it as a native function.
135135 /// NumberExprAST - Expression class for numeric literals like "1.0".
136136 class NumberExprAST : public ExprAST {
137137 double Val;
138
139138 public:
140 NumberExprAST(double val) : Val(val) {}
139 NumberExprAST(double Val) : Val(Val) {}
141140 Value *Codegen() override;
142141 };
143142
144143 /// VariableExprAST - Expression class for referencing a variable, like "a".
145144 class VariableExprAST : public ExprAST {
146145 std::string Name;
147
148146 public:
149 VariableExprAST(const std::string &name) : Name(name) {}
147 VariableExprAST(const std::string &Name) : Name(Name) {}
150148 const std::string &getName() const { return Name; }
151149 Value *Codegen() override;
152150 };
154152 /// UnaryExprAST - Expression class for a unary operator.
155153 class UnaryExprAST : public ExprAST {
156154 char Opcode;
157 ExprAST *Operand;
158
155 std::unique_ptr Operand;
159156 public:
160 UnaryExprAST(char opcode, ExprAST *operand)
161 : Opcode(opcode), Operand(operand) {}
157 UnaryExprAST(char Opcode, std::unique_ptr Operand)
158 : Opcode(Opcode), Operand(std::move(Operand)) {}
162159 Value *Codegen() override;
163160 };
164161
165162 /// BinaryExprAST - Expression class for a binary operator.
166163 class BinaryExprAST : public ExprAST {
167164 char Op;
168 ExprAST *LHS, *RHS;
169
165 std::unique_ptr LHS, RHS;
170166 public:
171 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
172 : Op(op), LHS(lhs), RHS(rhs) {}
167 BinaryExprAST(char Op, std::unique_ptr LHS,
168 std::unique_ptr RHS)
169 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
173170 Value *Codegen() override;
174171 };
175172
176173 /// CallExprAST - Expression class for function calls.
177174 class CallExprAST : public ExprAST {
178175 std::string Callee;
179 std::vector Args;
180
176 std::vector> Args;
181177 public:
182 CallExprAST(const std::string &callee, std::vector &args)
183 : Callee(callee), Args(args) {}
178 CallExprAST(const std::string &Callee,
179 std::vector> Args)
180 : Callee(Callee), Args(std::move(Args)) {}
184181 Value *Codegen() override;
185182 };
186183
187184 /// IfExprAST - Expression class for if/then/else.
188185 class IfExprAST : public ExprAST {
189 ExprAST *Cond, *Then, *Else;
190
186 std::unique_ptr Cond, Then, Else;
191187 public:
192 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
193 : Cond(cond), Then(then), Else(_else) {}
188 IfExprAST(std::unique_ptr Cond, std::unique_ptr Then,
189 std::unique_ptr Else)
190 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
194191 Value *Codegen() override;
195192 };
196193
197194 /// ForExprAST - Expression class for for/in.
198195 class ForExprAST : public ExprAST {
199196 std::string VarName;
200 ExprAST *Start, *End, *Step, *Body;
201
197 std::unique_ptr Start, End, Step, Body;
202198 public:
203 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
204 ExprAST *step, ExprAST *body)
205 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
199 ForExprAST(const std::string &VarName, std::unique_ptr Start,
200 std::unique_ptr End, std::unique_ptr Step,
201 std::unique_ptr Body)
202 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
203 Step(std::move(Step)), Body(std::move(Body)) {}
206204 Value *Codegen() override;
207205 };
208206
209207 /// VarExprAST - Expression class for var/in
210208 class VarExprAST : public ExprAST {
211 std::vector > VarNames;
212 ExprAST *Body;
213
209 std::vector>> VarNames;
210 std::unique_ptr Body;
214211 public:
215 VarExprAST(const std::vector > &varnames,
216 ExprAST *body)
217 : VarNames(varnames), Body(body) {}
218
212 VarExprAST(std::vector>> VarNames,
213 std::unique_ptr Body)
214 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
219215 Value *Codegen() override;
220216 };
221217
224220 class PrototypeAST {
225221 std::string Name;
226222 std::vector Args;
227 bool isOperator;
223 bool IsOperator;
228224 unsigned Precedence; // Precedence if a binary op.
229225 public:
230 PrototypeAST(const std::string &name, const std::vector &args,
231 bool isoperator = false, unsigned prec = 0)
232 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
233
234 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
235 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
226 PrototypeAST(const std::string &Name, std::vector Args,
227 bool IsOperator = false, unsigned Prec = 0)
228 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
229 Precedence(Prec) {}
230
231 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
232 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
236233
237234 char getOperatorName() const {
238235 assert(isUnaryOp() || isBinaryOp());
248245
249246 /// FunctionAST - This class represents a function definition itself.
250247 class FunctionAST {
251 PrototypeAST *Proto;
252 ExprAST *Body;
253
248 std::unique_ptr Proto;
249 std::unique_ptr Body;
254250 public:
255 FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
256
251 FunctionAST(std::unique_ptr Proto, std::unique_ptr Body)
252 : Proto(std::move(Proto)), Body(std::move(Body)) {}
257253 Function *Codegen();
258254 };
259255 } // end anonymous namespace
285281 }
286282
287283 /// Error* - These are little helper functions for error handling.
288 ExprAST *Error(const char *Str) {
284 std::unique_ptr Error(const char *Str) {
289285 fprintf(stderr, "Error: %s\n", Str);
290 return 0;
291 }
292 PrototypeAST *ErrorP(const char *Str) {
286 return nullptr;
287 }
288 std::unique_ptr ErrorP(const char *Str) {
293289 Error(Str);
294 return 0;
295 }
296 FunctionAST *ErrorF(const char *Str) {
290 return nullptr;
291 }
292 std::unique_ptr ErrorF(const char *Str) {
297293 Error(Str);
298 return 0;
299 }
300
301 static ExprAST *ParseExpression();
294 return nullptr;
295 }
296
297 static std::unique_ptr ParseExpression();
302298
303299 /// identifierexpr
304300 /// ::= identifier
305301 /// ::= identifier '(' expression* ')'
306 static ExprAST *ParseIdentifierExpr() {
302 static std::unique_ptr ParseIdentifierExpr() {
307303 std::string IdName = IdentifierStr;
308304
309305 getNextToken(); // eat identifier.
310306
311307 if (CurTok != '(') // Simple variable ref.
312 return new VariableExprAST(IdName);
308 return llvm::make_unique(IdName);
313309
314310 // Call.
315311 getNextToken(); // eat (
316 std::vector<ExprAST *> Args;
312 std::vector<std::unique_ptr> Args;
317313 if (CurTok != ')') {
318314 while (1) {
319 ExprAST *Arg = ParseExpression();
320 if (!Arg)
321 return 0;
322 Args.push_back(Arg);
315 if (auto Arg = ParseExpression())
316 Args.push_back(std::move(Arg));
317 else
318 return nullptr;
323319
324320 if (CurTok == ')')
325321 break;
333329 // Eat the ')'.
334330 getNextToken();
335331
336 return new CallExprAST(IdName, Args);
332 return llvm::make_unique(IdName, std::move(Args));
337333 }
338334
339335 /// numberexpr ::= number
340 static ExprAST *ParseNumberExpr() {
341 ExprAST *Result = new NumberExprAST(NumVal);
336 static std::unique_ptr ParseNumberExpr() {
337 auto Result = llvm::make_unique(NumVal);