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