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