042d974626d2e7d678bccd339a866e9f08df8d43
[oota-llvm.git] / examples / Kaleidoscope / Chapter5 / toy.cpp
1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/Analysis/BasicAliasAnalysis.h"
3 #include "llvm/Analysis/Passes.h"
4 #include "llvm/ExecutionEngine/ExecutionEngine.h"
5 #include "llvm/ExecutionEngine/MCJIT.h"
6 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
7 #include "llvm/IR/DataLayout.h"
8 #include "llvm/IR/DerivedTypes.h"
9 #include "llvm/IR/IRBuilder.h"
10 #include "llvm/IR/LLVMContext.h"
11 #include "llvm/IR/LegacyPassManager.h"
12 #include "llvm/IR/Module.h"
13 #include "llvm/IR/Verifier.h"
14 #include "llvm/Support/TargetSelect.h"
15 #include "llvm/Transforms/Scalar.h"
16 #include <cctype>
17 #include <cstdio>
18 #include <map>
19 #include <string>
20 #include <vector>
21 using namespace llvm;
22
23 //===----------------------------------------------------------------------===//
24 // Lexer
25 //===----------------------------------------------------------------------===//
26
27 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
28 // of these for known things.
29 enum Token {
30   tok_eof = -1,
31
32   // commands
33   tok_def = -2,
34   tok_extern = -3,
35
36   // primary
37   tok_identifier = -4,
38   tok_number = -5,
39
40   // control
41   tok_if = -6,
42   tok_then = -7,
43   tok_else = -8,
44   tok_for = -9,
45   tok_in = -10
46 };
47
48 static std::string IdentifierStr; // Filled in if tok_identifier
49 static double NumVal;             // Filled in if tok_number
50
51 /// gettok - Return the next token from standard input.
52 static int gettok() {
53   static int LastChar = ' ';
54
55   // Skip any whitespace.
56   while (isspace(LastChar))
57     LastChar = getchar();
58
59   if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
60     IdentifierStr = LastChar;
61     while (isalnum((LastChar = getchar())))
62       IdentifierStr += LastChar;
63
64     if (IdentifierStr == "def")
65       return tok_def;
66     if (IdentifierStr == "extern")
67       return tok_extern;
68     if (IdentifierStr == "if")
69       return tok_if;
70     if (IdentifierStr == "then")
71       return tok_then;
72     if (IdentifierStr == "else")
73       return tok_else;
74     if (IdentifierStr == "for")
75       return tok_for;
76     if (IdentifierStr == "in")
77       return tok_in;
78     return tok_identifier;
79   }
80
81   if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
82     std::string NumStr;
83     do {
84       NumStr += LastChar;
85       LastChar = getchar();
86     } while (isdigit(LastChar) || LastChar == '.');
87
88     NumVal = strtod(NumStr.c_str(), 0);
89     return tok_number;
90   }
91
92   if (LastChar == '#') {
93     // Comment until end of line.
94     do
95       LastChar = getchar();
96     while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
97
98     if (LastChar != EOF)
99       return gettok();
100   }
101
102   // Check for end of file.  Don't eat the EOF.
103   if (LastChar == EOF)
104     return tok_eof;
105
106   // Otherwise, just return the character as its ascii value.
107   int ThisChar = LastChar;
108   LastChar = getchar();
109   return ThisChar;
110 }
111
112 //===----------------------------------------------------------------------===//
113 // Abstract Syntax Tree (aka Parse Tree)
114 //===----------------------------------------------------------------------===//
115 namespace {
116 /// ExprAST - Base class for all expression nodes.
117 class ExprAST {
118 public:
119   virtual ~ExprAST() {}
120   virtual Value *Codegen() = 0;
121 };
122
123 /// NumberExprAST - Expression class for numeric literals like "1.0".
124 class NumberExprAST : public ExprAST {
125   double Val;
126 public:
127   NumberExprAST(double Val) : Val(Val) {}
128   Value *Codegen() override;
129 };
130
131 /// VariableExprAST - Expression class for referencing a variable, like "a".
132 class VariableExprAST : public ExprAST {
133   std::string Name;
134 public:
135   VariableExprAST(const std::string &Name) : Name(Name) {}
136   Value *Codegen() override;
137 };
138
139 /// BinaryExprAST - Expression class for a binary operator.
140 class BinaryExprAST : public ExprAST {
141   char Op;
142   std::unique_ptr<ExprAST> LHS, RHS;
143 public:
144   BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
145                 std::unique_ptr<ExprAST> RHS)
146       : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
147   Value *Codegen() override;
148 };
149
150 /// CallExprAST - Expression class for function calls.
151 class CallExprAST : public ExprAST {
152   std::string Callee;
153   std::vector<std::unique_ptr<ExprAST>> Args;
154 public:
155   CallExprAST(const std::string &Callee,
156               std::vector<std::unique_ptr<ExprAST>> Args)
157       : Callee(Callee), Args(std::move(Args)) {}
158   Value *Codegen() override;
159 };
160
161 /// IfExprAST - Expression class for if/then/else.
162 class IfExprAST : public ExprAST {
163   std::unique_ptr<ExprAST> Cond, Then, Else;
164 public:
165   IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
166             std::unique_ptr<ExprAST> Else)
167       : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
168   Value *Codegen() override;
169 };
170
171 /// ForExprAST - Expression class for for/in.
172 class ForExprAST : public ExprAST {
173   std::string VarName;
174   std::unique_ptr<ExprAST> Start, End, Step, Body;
175 public:
176   ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
177              std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
178              std::unique_ptr<ExprAST> Body)
179       : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
180         Step(std::move(Step)), Body(std::move(Body)) {}
181   Value *Codegen() override;
182 };
183
184 /// PrototypeAST - This class represents the "prototype" for a function,
185 /// which captures its name, and its argument names (thus implicitly the number
186 /// of arguments the function takes).
187 class PrototypeAST {
188   std::string Name;
189   std::vector<std::string> Args;
190 public:
191   PrototypeAST(const std::string &name, std::vector<std::string> Args)
192       : Name(name), Args(std::move(Args)) {}
193   Function *Codegen();
194 };
195
196 /// FunctionAST - This class represents a function definition itself.
197 class FunctionAST {
198   std::unique_ptr<PrototypeAST> Proto;
199   std::unique_ptr<ExprAST> Body;
200 public:
201   FunctionAST(std::unique_ptr<PrototypeAST> Proto,
202               std::unique_ptr<ExprAST> Body)
203     : Proto(std::move(Proto)), Body(std::move(Body)) {}
204   Function *Codegen();
205 };
206 } // end anonymous namespace
207
208 //===----------------------------------------------------------------------===//
209 // Parser
210 //===----------------------------------------------------------------------===//
211
212 /// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
213 /// token the parser is looking at.  getNextToken reads another token from the
214 /// lexer and updates CurTok with its results.
215 static int CurTok;
216 static int getNextToken() { return CurTok = gettok(); }
217
218 /// BinopPrecedence - This holds the precedence for each binary operator that is
219 /// defined.
220 static std::map<char, int> BinopPrecedence;
221
222 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
223 static int GetTokPrecedence() {
224   if (!isascii(CurTok))
225     return -1;
226
227   // Make sure it's a declared binop.
228   int TokPrec = BinopPrecedence[CurTok];
229   if (TokPrec <= 0)
230     return -1;
231   return TokPrec;
232 }
233
234 /// Error* - These are little helper functions for error handling.
235 std::unique_ptr<ExprAST> Error(const char *Str) {
236   fprintf(stderr, "Error: %s\n", Str);
237   return nullptr;
238 }
239 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
240   Error(Str);
241   return nullptr;
242 }
243 std::unique_ptr<FunctionAST> ErrorF(const char *Str) {
244   Error(Str);
245   return nullptr;
246 }
247
248 static std::unique_ptr<ExprAST> ParseExpression();
249
250 /// identifierexpr
251 ///   ::= identifier
252 ///   ::= identifier '(' expression* ')'
253 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
254   std::string IdName = IdentifierStr;
255
256   getNextToken(); // eat identifier.
257
258   if (CurTok != '(') // Simple variable ref.
259     return llvm::make_unique<VariableExprAST>(IdName);
260
261   // Call.
262   getNextToken(); // eat (
263   std::vector<std::unique_ptr<ExprAST>> Args;
264   if (CurTok != ')') {
265     while (1) {
266       if (auto Arg = ParseExpression())
267         Args.push_back(std::move(Arg));
268       else
269         return nullptr;
270
271       if (CurTok == ')')
272         break;
273
274       if (CurTok != ',')
275         return Error("Expected ')' or ',' in argument list");
276       getNextToken();
277     }
278   }
279
280   // Eat the ')'.
281   getNextToken();
282
283   return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
284 }
285
286 /// numberexpr ::= number
287 static std::unique_ptr<ExprAST> ParseNumberExpr() {
288   auto Result = llvm::make_unique<NumberExprAST>(NumVal);
289   getNextToken(); // consume the number
290   return std::move(Result);
291 }
292
293 /// parenexpr ::= '(' expression ')'
294 static std::unique_ptr<ExprAST> ParseParenExpr() {
295   getNextToken(); // eat (.
296   auto V = ParseExpression();
297   if (!V)
298     return nullptr;
299
300   if (CurTok != ')')
301     return Error("expected ')'");
302   getNextToken(); // eat ).
303   return V;
304 }
305
306 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
307 static std::unique_ptr<ExprAST> ParseIfExpr() {
308   getNextToken(); // eat the if.
309
310   // condition.
311   auto Cond = ParseExpression();
312   if (!Cond)
313     return nullptr;
314
315   if (CurTok != tok_then)
316     return Error("expected then");
317   getNextToken(); // eat the then
318
319   auto Then = ParseExpression();
320   if (!Then)
321     return nullptr;
322
323   if (CurTok != tok_else)
324     return Error("expected else");
325
326   getNextToken();
327
328   auto Else = ParseExpression();
329   if (!Else)
330     return nullptr;
331
332   return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
333                                       std::move(Else));
334 }
335
336 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
337 static std::unique_ptr<ExprAST> ParseForExpr() {
338   getNextToken(); // eat the for.
339
340   if (CurTok != tok_identifier)
341     return Error("expected identifier after for");
342
343   std::string IdName = IdentifierStr;
344   getNextToken(); // eat identifier.
345
346   if (CurTok != '=')
347     return Error("expected '=' after for");
348   getNextToken(); // eat '='.
349
350   auto Start = ParseExpression();
351   if (!Start)
352     return nullptr;
353   if (CurTok != ',')
354     return Error("expected ',' after for start value");
355   getNextToken();
356
357   auto End = ParseExpression();
358   if (!End)
359     return nullptr;
360
361   // The step value is optional.
362   std::unique_ptr<ExprAST> Step;
363   if (CurTok == ',') {
364     getNextToken();
365     Step = ParseExpression();
366     if (!Step)
367       return nullptr;
368   }
369
370   if (CurTok != tok_in)
371     return Error("expected 'in' after for");
372   getNextToken(); // eat 'in'.
373
374   auto Body = ParseExpression();
375   if (!Body)
376     return nullptr;
377
378   return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
379                                        std::move(Step), std::move(Body));
380 }
381
382 /// primary
383 ///   ::= identifierexpr
384 ///   ::= numberexpr
385 ///   ::= parenexpr
386 ///   ::= ifexpr
387 ///   ::= forexpr
388 static std::unique_ptr<ExprAST> ParsePrimary() {
389   switch (CurTok) {
390   default:
391     return Error("unknown token when expecting an expression");
392   case tok_identifier:
393     return ParseIdentifierExpr();
394   case tok_number:
395     return ParseNumberExpr();
396   case '(':
397     return ParseParenExpr();
398   case tok_if:
399     return ParseIfExpr();
400   case tok_for:
401     return ParseForExpr();
402   }
403 }
404
405 /// binoprhs
406 ///   ::= ('+' primary)*
407 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
408                                               std::unique_ptr<ExprAST> LHS) {
409   // If this is a binop, find its precedence.
410   while (1) {
411     int TokPrec = GetTokPrecedence();
412
413     // If this is a binop that binds at least as tightly as the current binop,
414     // consume it, otherwise we are done.
415     if (TokPrec < ExprPrec)
416       return LHS;
417
418     // Okay, we know this is a binop.
419     int BinOp = CurTok;
420     getNextToken(); // eat binop
421
422     // Parse the primary expression after the binary operator.
423     auto RHS = ParsePrimary();
424     if (!RHS)
425       return nullptr;
426
427     // If BinOp binds less tightly with RHS than the operator after RHS, let
428     // the pending operator take RHS as its LHS.
429     int NextPrec = GetTokPrecedence();
430     if (TokPrec < NextPrec) {
431       RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
432       if (!RHS)
433         return nullptr;
434     }
435
436     // Merge LHS/RHS.
437     LHS = llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS),
438                                            std::move(RHS));
439   }
440 }
441
442 /// expression
443 ///   ::= primary binoprhs
444 ///
445 static std::unique_ptr<ExprAST> ParseExpression() {
446   auto LHS = ParsePrimary();
447   if (!LHS)
448     return nullptr;
449
450   return ParseBinOpRHS(0, std::move(LHS));
451 }
452
453 /// prototype
454 ///   ::= id '(' id* ')'
455 static std::unique_ptr<PrototypeAST> ParsePrototype() {
456   if (CurTok != tok_identifier)
457     return ErrorP("Expected function name in prototype");
458
459   std::string FnName = IdentifierStr;
460   getNextToken();
461
462   if (CurTok != '(')
463     return ErrorP("Expected '(' in prototype");
464
465   std::vector<std::string> ArgNames;
466   while (getNextToken() == tok_identifier)
467     ArgNames.push_back(IdentifierStr);
468   if (CurTok != ')')
469     return ErrorP("Expected ')' in prototype");
470
471   // success.
472   getNextToken(); // eat ')'.
473
474   return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
475 }
476
477 /// definition ::= 'def' prototype expression
478 static std::unique_ptr<FunctionAST> ParseDefinition() {
479   getNextToken(); // eat def.
480   auto Proto = ParsePrototype();
481   if (!Proto)
482     return nullptr;
483
484   if (auto E = ParseExpression())
485     return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
486   return nullptr;
487 }
488
489 /// toplevelexpr ::= expression
490 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
491   if (auto E = ParseExpression()) {
492     // Make an anonymous proto.
493     auto Proto = llvm::make_unique<PrototypeAST>("",
494                                                  std::vector<std::string>());
495     return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
496   }
497   return nullptr;
498 }
499
500 /// external ::= 'extern' prototype
501 static std::unique_ptr<PrototypeAST> ParseExtern() {
502   getNextToken(); // eat extern.
503   return ParsePrototype();
504 }
505
506 //===----------------------------------------------------------------------===//
507 // Code Generation
508 //===----------------------------------------------------------------------===//
509
510 static Module *TheModule;
511 static IRBuilder<> Builder(getGlobalContext());
512 static std::map<std::string, Value *> NamedValues;
513 static legacy::FunctionPassManager *TheFPM;
514
515 Value *ErrorV(const char *Str) {
516   Error(Str);
517   return nullptr;
518 }
519
520 Value *NumberExprAST::Codegen() {
521   return ConstantFP::get(getGlobalContext(), APFloat(Val));
522 }
523
524 Value *VariableExprAST::Codegen() {
525   // Look this variable up in the function.
526   Value *V = NamedValues[Name];
527   return V ? V : ErrorV("Unknown variable name");
528 }
529
530 Value *BinaryExprAST::Codegen() {
531   Value *L = LHS->Codegen();
532   Value *R = RHS->Codegen();
533   if (!L || !R)
534     return nullptr;
535
536   switch (Op) {
537   case '+':
538     return Builder.CreateFAdd(L, R, "addtmp");
539   case '-':
540     return Builder.CreateFSub(L, R, "subtmp");
541   case '*':
542     return Builder.CreateFMul(L, R, "multmp");
543   case '<':
544     L = Builder.CreateFCmpULT(L, R, "cmptmp");
545     // Convert bool 0/1 to double 0.0 or 1.0
546     return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
547                                 "booltmp");
548   default:
549     return ErrorV("invalid binary operator");
550   }
551 }
552
553 Value *CallExprAST::Codegen() {
554   // Look up the name in the global module table.
555   Function *CalleeF = TheModule->getFunction(Callee);
556   if (!CalleeF)
557     return ErrorV("Unknown function referenced");
558
559   // If argument mismatch error.
560   if (CalleeF->arg_size() != Args.size())
561     return ErrorV("Incorrect # arguments passed");
562
563   std::vector<Value *> ArgsV;
564   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
565     ArgsV.push_back(Args[i]->Codegen());
566     if (!ArgsV.back())
567       return nullptr;
568   }
569
570   return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
571 }
572
573 Value *IfExprAST::Codegen() {
574   Value *CondV = Cond->Codegen();
575   if (!CondV)
576     return nullptr;
577
578   // Convert condition to a bool by comparing equal to 0.0.
579   CondV = Builder.CreateFCmpONE(
580       CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
581
582   Function *TheFunction = Builder.GetInsertBlock()->getParent();
583
584   // Create blocks for the then and else cases.  Insert the 'then' block at the
585   // end of the function.
586   BasicBlock *ThenBB =
587       BasicBlock::Create(getGlobalContext(), "then", TheFunction);
588   BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
589   BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
590
591   Builder.CreateCondBr(CondV, ThenBB, ElseBB);
592
593   // Emit then value.
594   Builder.SetInsertPoint(ThenBB);
595
596   Value *ThenV = Then->Codegen();
597   if (!ThenV)
598     return nullptr;
599
600   Builder.CreateBr(MergeBB);
601   // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
602   ThenBB = Builder.GetInsertBlock();
603
604   // Emit else block.
605   TheFunction->getBasicBlockList().push_back(ElseBB);
606   Builder.SetInsertPoint(ElseBB);
607
608   Value *ElseV = Else->Codegen();
609   if (!ElseV)
610     return nullptr;
611
612   Builder.CreateBr(MergeBB);
613   // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
614   ElseBB = Builder.GetInsertBlock();
615
616   // Emit merge block.
617   TheFunction->getBasicBlockList().push_back(MergeBB);
618   Builder.SetInsertPoint(MergeBB);
619   PHINode *PN =
620       Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
621
622   PN->addIncoming(ThenV, ThenBB);
623   PN->addIncoming(ElseV, ElseBB);
624   return PN;
625 }
626
627 Value *ForExprAST::Codegen() {
628   // Output this as:
629   //   ...
630   //   start = startexpr
631   //   goto loop
632   // loop:
633   //   variable = phi [start, loopheader], [nextvariable, loopend]
634   //   ...
635   //   bodyexpr
636   //   ...
637   // loopend:
638   //   step = stepexpr
639   //   nextvariable = variable + step
640   //   endcond = endexpr
641   //   br endcond, loop, endloop
642   // outloop:
643
644   // Emit the start code first, without 'variable' in scope.
645   Value *StartVal = Start->Codegen();
646   if (!StartVal)
647     return nullptr;
648
649   // Make the new basic block for the loop header, inserting after current
650   // block.
651   Function *TheFunction = Builder.GetInsertBlock()->getParent();
652   BasicBlock *PreheaderBB = Builder.GetInsertBlock();
653   BasicBlock *LoopBB =
654       BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
655
656   // Insert an explicit fall through from the current block to the LoopBB.
657   Builder.CreateBr(LoopBB);
658
659   // Start insertion in LoopBB.
660   Builder.SetInsertPoint(LoopBB);
661
662   // Start the PHI node with an entry for Start.
663   PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
664                                         2, VarName.c_str());
665   Variable->addIncoming(StartVal, PreheaderBB);
666
667   // Within the loop, the variable is defined equal to the PHI node.  If it
668   // shadows an existing variable, we have to restore it, so save it now.
669   Value *OldVal = NamedValues[VarName];
670   NamedValues[VarName] = Variable;
671
672   // Emit the body of the loop.  This, like any other expr, can change the
673   // current BB.  Note that we ignore the value computed by the body, but don't
674   // allow an error.
675   if (!Body->Codegen())
676     return nullptr;
677
678   // Emit the step value.
679   Value *StepVal;
680   if (Step) {
681     StepVal = Step->Codegen();
682     if (!StepVal)
683       return nullptr;
684   } else {
685     // If not specified, use 1.0.
686     StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
687   }
688
689   Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
690
691   // Compute the end condition.
692   Value *EndCond = End->Codegen();
693   if (!EndCond)
694     return EndCond;
695
696   // Convert condition to a bool by comparing equal to 0.0.
697   EndCond = Builder.CreateFCmpONE(
698       EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
699
700   // Create the "after loop" block and insert it.
701   BasicBlock *LoopEndBB = Builder.GetInsertBlock();
702   BasicBlock *AfterBB =
703       BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
704
705   // Insert the conditional branch into the end of LoopEndBB.
706   Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
707
708   // Any new code will be inserted in AfterBB.
709   Builder.SetInsertPoint(AfterBB);
710
711   // Add a new entry to the PHI node for the backedge.
712   Variable->addIncoming(NextVar, LoopEndBB);
713
714   // Restore the unshadowed variable.
715   if (OldVal)
716     NamedValues[VarName] = OldVal;
717   else
718     NamedValues.erase(VarName);
719
720   // for expr always returns 0.0.
721   return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
722 }
723
724 Function *PrototypeAST::Codegen() {
725   // Make the function type:  double(double,double) etc.
726   std::vector<Type *> Doubles(Args.size(),
727                               Type::getDoubleTy(getGlobalContext()));
728   FunctionType *FT =
729       FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
730
731   Function *F =
732       Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
733
734   // If F conflicted, there was already something named 'Name'.  If it has a
735   // body, don't allow redefinition or reextern.
736   if (F->getName() != Name) {
737     // Delete the one we just made and get the existing one.
738     F->eraseFromParent();
739     F = TheModule->getFunction(Name);
740
741     // If F already has a body, reject this.
742     if (!F->empty()) {
743       ErrorF("redefinition of function");
744       return nullptr;
745     }
746
747     // If F took a different number of args, reject.
748     if (F->arg_size() != Args.size()) {
749       ErrorF("redefinition of function with different # args");
750       return nullptr;
751     }
752   }
753
754   // Set names for all arguments.
755   unsigned Idx = 0;
756   for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
757        ++AI, ++Idx) {
758     AI->setName(Args[Idx]);
759
760     // Add arguments to variable symbol table.
761     NamedValues[Args[Idx]] = AI;
762   }
763
764   return F;
765 }
766
767 Function *FunctionAST::Codegen() {
768   NamedValues.clear();
769
770   Function *TheFunction = Proto->Codegen();
771   if (!TheFunction)
772     return nullptr;
773
774   // Create a new basic block to start insertion into.
775   BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
776   Builder.SetInsertPoint(BB);
777
778   if (Value *RetVal = Body->Codegen()) {
779     // Finish off the function.
780     Builder.CreateRet(RetVal);
781
782     // Validate the generated code, checking for consistency.
783     verifyFunction(*TheFunction);
784
785     // Optimize the function.
786     TheFPM->run(*TheFunction);
787
788     return TheFunction;
789   }
790
791   // Error reading body, remove function.
792   TheFunction->eraseFromParent();
793   return nullptr;
794 }
795
796 //===----------------------------------------------------------------------===//
797 // Top-Level parsing and JIT Driver
798 //===----------------------------------------------------------------------===//
799
800 static ExecutionEngine *TheExecutionEngine;
801
802 static void HandleDefinition() {
803   if (auto FnAST = ParseDefinition()) {
804     if (auto *FnIR = FnAST->Codegen()) {
805       fprintf(stderr, "Read function definition:");
806       FnIR->dump();
807     }
808   } else {
809     // Skip token for error recovery.
810     getNextToken();
811   }
812 }
813
814 static void HandleExtern() {
815   if (auto ProtoAST = ParseExtern()) {
816     if (auto *FnIR = ProtoAST->Codegen()) {
817       fprintf(stderr, "Read extern: ");
818       FnIR->dump();
819     }
820   } else {
821     // Skip token for error recovery.
822     getNextToken();
823   }
824 }
825
826 static void HandleTopLevelExpression() {
827   // Evaluate a top-level expression into an anonymous function.
828   if (auto FnAST = ParseTopLevelExpr()) {
829     if (auto *FnIR = FnAST->Codegen()) {
830       TheExecutionEngine->finalizeObject();
831       // JIT the function, returning a function pointer.
832       void *FPtr = TheExecutionEngine->getPointerToFunction(FnIR);
833
834       // Cast it to the right type (takes no arguments, returns a double) so we
835       // can call it as a native function.
836       double (*FP)() = (double (*)())(intptr_t)FPtr;
837       fprintf(stderr, "Evaluated to %f\n", FP());
838     }
839   } else {
840     // Skip token for error recovery.
841     getNextToken();
842   }
843 }
844
845 /// top ::= definition | external | expression | ';'
846 static void MainLoop() {
847   while (1) {
848     fprintf(stderr, "ready> ");
849     switch (CurTok) {
850     case tok_eof:
851       return;
852     case ';':
853       getNextToken();
854       break; // ignore top-level semicolons.
855     case tok_def:
856       HandleDefinition();
857       break;
858     case tok_extern:
859       HandleExtern();
860       break;
861     default:
862       HandleTopLevelExpression();
863       break;
864     }
865   }
866 }
867
868 //===----------------------------------------------------------------------===//
869 // "Library" functions that can be "extern'd" from user code.
870 //===----------------------------------------------------------------------===//
871
872 /// putchard - putchar that takes a double and returns 0.
873 extern "C" double putchard(double X) {
874   putchar((char)X);
875   return 0;
876 }
877
878 //===----------------------------------------------------------------------===//
879 // Main driver code.
880 //===----------------------------------------------------------------------===//
881
882 int main() {
883   InitializeNativeTarget();
884   InitializeNativeTargetAsmPrinter();
885   InitializeNativeTargetAsmParser();
886   LLVMContext &Context = getGlobalContext();
887
888   // Install standard binary operators.
889   // 1 is lowest precedence.
890   BinopPrecedence['<'] = 10;
891   BinopPrecedence['+'] = 20;
892   BinopPrecedence['-'] = 20;
893   BinopPrecedence['*'] = 40; // highest.
894
895   // Prime the first token.
896   fprintf(stderr, "ready> ");
897   getNextToken();
898
899   // Make the module, which holds all the code.
900   std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
901   TheModule = Owner.get();
902
903   // Create the JIT.  This takes ownership of the module.
904   std::string ErrStr;
905   TheExecutionEngine =
906       EngineBuilder(std::move(Owner))
907           .setErrorStr(&ErrStr)
908           .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
909           .create();
910   if (!TheExecutionEngine) {
911     fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
912     exit(1);
913   }
914
915   legacy::FunctionPassManager OurFPM(TheModule);
916
917   // Set up the optimizer pipeline.  Start with registering info about how the
918   // target lays out data structures.
919   TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
920   // Provide basic AliasAnalysis support for GVN.
921   OurFPM.add(createBasicAliasAnalysisPass());
922   // Do simple "peephole" optimizations and bit-twiddling optzns.
923   OurFPM.add(createInstructionCombiningPass());
924   // Reassociate expressions.
925   OurFPM.add(createReassociatePass());
926   // Eliminate Common SubExpressions.
927   OurFPM.add(createGVNPass());
928   // Simplify the control flow graph (deleting unreachable blocks, etc).
929   OurFPM.add(createCFGSimplificationPass());
930
931   OurFPM.doInitialization();
932
933   // Set the global so the code gen can use this.
934   TheFPM = &OurFPM;
935
936   // Run the main "interpreter loop" now.
937   MainLoop();
938
939   TheFPM = 0;
940
941   // Print out all of the generated code.
942   TheModule->dump();
943
944   return 0;
945 }