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