[Kaleidoscope] Start C++11'ifying the kaleidoscope tutorials.
[oota-llvm.git] / examples / Kaleidoscope / Chapter8 / toy.cpp
1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/ADT/Triple.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/DIBuilder.h"
8 #include "llvm/IR/DataLayout.h"
9 #include "llvm/IR/DerivedTypes.h"
10 #include "llvm/IR/IRBuilder.h"
11 #include "llvm/IR/LLVMContext.h"
12 #include "llvm/IR/LegacyPassManager.h"
13 #include "llvm/IR/Module.h"
14 #include "llvm/IR/Verifier.h"
15 #include "llvm/Support/Host.h"
16 #include "llvm/Support/TargetSelect.h"
17 #include "llvm/Transforms/Scalar.h"
18 #include <cctype>
19 #include <cstdio>
20 #include <iostream>
21 #include <map>
22 #include <string>
23 #include <vector>
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 // Lexer
28 //===----------------------------------------------------------------------===//
29
30 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
31 // of these for known things.
32 enum Token {
33   tok_eof = -1,
34
35   // commands
36   tok_def = -2,
37   tok_extern = -3,
38
39   // primary
40   tok_identifier = -4,
41   tok_number = -5,
42
43   // control
44   tok_if = -6,
45   tok_then = -7,
46   tok_else = -8,
47   tok_for = -9,
48   tok_in = -10,
49
50   // operators
51   tok_binary = -11,
52   tok_unary = -12,
53
54   // var definition
55   tok_var = -13
56 };
57
58 std::string getTokName(int Tok) {
59   switch (Tok) {
60   case tok_eof:
61     return "eof";
62   case tok_def:
63     return "def";
64   case tok_extern:
65     return "extern";
66   case tok_identifier:
67     return "identifier";
68   case tok_number:
69     return "number";
70   case tok_if:
71     return "if";
72   case tok_then:
73     return "then";
74   case tok_else:
75     return "else";
76   case tok_for:
77     return "for";
78   case tok_in:
79     return "in";
80   case tok_binary:
81     return "binary";
82   case tok_unary:
83     return "unary";
84   case tok_var:
85     return "var";
86   }
87   return std::string(1, (char)Tok);
88 }
89
90 namespace {
91 class PrototypeAST;
92 class ExprAST;
93 }
94 static IRBuilder<> Builder(getGlobalContext());
95 struct DebugInfo {
96   DICompileUnit *TheCU;
97   DIType *DblTy;
98   std::vector<DIScope *> LexicalBlocks;
99   std::map<const PrototypeAST *, DIScope *> FnScopeMap;
100
101   void emitLocation(ExprAST *AST);
102   DIType *getDoubleTy();
103 } KSDbgInfo;
104
105 static std::string IdentifierStr; // Filled in if tok_identifier
106 static double NumVal;             // Filled in if tok_number
107 struct SourceLocation {
108   int Line;
109   int Col;
110 };
111 static SourceLocation CurLoc;
112 static SourceLocation LexLoc = { 1, 0 };
113
114 static int advance() {
115   int LastChar = getchar();
116
117   if (LastChar == '\n' || LastChar == '\r') {
118     LexLoc.Line++;
119     LexLoc.Col = 0;
120   } else
121     LexLoc.Col++;
122   return LastChar;
123 }
124
125 /// gettok - Return the next token from standard input.
126 static int gettok() {
127   static int LastChar = ' ';
128
129   // Skip any whitespace.
130   while (isspace(LastChar))
131     LastChar = advance();
132
133   CurLoc = LexLoc;
134
135   if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
136     IdentifierStr = LastChar;
137     while (isalnum((LastChar = advance())))
138       IdentifierStr += LastChar;
139
140     if (IdentifierStr == "def")
141       return tok_def;
142     if (IdentifierStr == "extern")
143       return tok_extern;
144     if (IdentifierStr == "if")
145       return tok_if;
146     if (IdentifierStr == "then")
147       return tok_then;
148     if (IdentifierStr == "else")
149       return tok_else;
150     if (IdentifierStr == "for")
151       return tok_for;
152     if (IdentifierStr == "in")
153       return tok_in;
154     if (IdentifierStr == "binary")
155       return tok_binary;
156     if (IdentifierStr == "unary")
157       return tok_unary;
158     if (IdentifierStr == "var")
159       return tok_var;
160     return tok_identifier;
161   }
162
163   if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
164     std::string NumStr;
165     do {
166       NumStr += LastChar;
167       LastChar = advance();
168     } while (isdigit(LastChar) || LastChar == '.');
169
170     NumVal = strtod(NumStr.c_str(), 0);
171     return tok_number;
172   }
173
174   if (LastChar == '#') {
175     // Comment until end of line.
176     do
177       LastChar = advance();
178     while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
179
180     if (LastChar != EOF)
181       return gettok();
182   }
183
184   // Check for end of file.  Don't eat the EOF.
185   if (LastChar == EOF)
186     return tok_eof;
187
188   // Otherwise, just return the character as its ascii value.
189   int ThisChar = LastChar;
190   LastChar = advance();
191   return ThisChar;
192 }
193
194 //===----------------------------------------------------------------------===//
195 // Abstract Syntax Tree (aka Parse Tree)
196 //===----------------------------------------------------------------------===//
197 namespace {
198
199 std::ostream &indent(std::ostream &O, int size) {
200   return O << std::string(size, ' ');
201 }
202
203 /// ExprAST - Base class for all expression nodes.
204 class ExprAST {
205   SourceLocation Loc;
206 public:
207   int getLine() const { return Loc.Line; }
208   int getCol() const { return Loc.Col; }
209   ExprAST(SourceLocation Loc = CurLoc) : Loc(Loc) {}
210   virtual std::ostream &dump(std::ostream &out, int ind) {
211     return out << ':' << getLine() << ':' << getCol() << '\n';
212   }
213   virtual ~ExprAST() {}
214   virtual Value *Codegen() = 0;
215 };
216
217 /// NumberExprAST - Expression class for numeric literals like "1.0".
218 class NumberExprAST : public ExprAST {
219   double Val;
220 public:
221   NumberExprAST(double Val) : Val(Val) {}
222   std::ostream &dump(std::ostream &out, int ind) override {
223     return ExprAST::dump(out << Val, ind);
224   }
225   Value *Codegen() override;
226 };
227
228 /// VariableExprAST - Expression class for referencing a variable, like "a".
229 class VariableExprAST : public ExprAST {
230   std::string Name;
231 public:
232   VariableExprAST(SourceLocation Loc, const std::string &Name)
233       : ExprAST(Loc), Name(Name) {}
234   const std::string &getName() const { return Name; }
235   std::ostream &dump(std::ostream &out, int ind) override {
236     return ExprAST::dump(out << Name, ind);
237   }
238   Value *Codegen() override;
239 };
240
241 /// UnaryExprAST - Expression class for a unary operator.
242 class UnaryExprAST : public ExprAST {
243   char Opcode;
244   std::unique_ptr<ExprAST> Operand;
245 public:
246   UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
247       : Opcode(Opcode), Operand(std::move(Operand)) {}
248   std::ostream &dump(std::ostream &out, int ind) override {
249     ExprAST::dump(out << "unary" << Opcode, ind);
250     Operand->dump(out, ind + 1);
251     return out;
252   }
253   Value *Codegen() override;
254 };
255
256 /// BinaryExprAST - Expression class for a binary operator.
257 class BinaryExprAST : public ExprAST {
258   char Op;
259   std::unique_ptr<ExprAST> LHS, RHS;
260 public:
261   BinaryExprAST(SourceLocation Loc, char Op, std::unique_ptr<ExprAST> LHS,
262                 std::unique_ptr<ExprAST> RHS)
263       : ExprAST(Loc), Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
264   std::ostream &dump(std::ostream &out, int ind) override {
265     ExprAST::dump(out << "binary" << Op, ind);
266     LHS->dump(indent(out, ind) << "LHS:", ind + 1);
267     RHS->dump(indent(out, ind) << "RHS:", ind + 1);
268     return out;
269   }
270   Value *Codegen() override;
271 };
272
273 /// CallExprAST - Expression class for function calls.
274 class CallExprAST : public ExprAST {
275   std::string Callee;
276   std::vector<std::unique_ptr<ExprAST>> Args;
277 public:
278   CallExprAST(SourceLocation Loc, const std::string &Callee,
279               std::vector<std::unique_ptr<ExprAST>> Args)
280       : ExprAST(Loc), Callee(Callee), Args(std::move(Args)) {}
281   std::ostream &dump(std::ostream &out, int ind) override {
282     ExprAST::dump(out << "call " << Callee, ind);
283     for (const auto &Arg : Args)
284       Arg->dump(indent(out, ind + 1), ind + 1);
285     return out;
286   }
287   Value *Codegen() override;
288 };
289
290 /// IfExprAST - Expression class for if/then/else.
291 class IfExprAST : public ExprAST {
292   std::unique_ptr<ExprAST> Cond, Then, Else;
293 public:
294   IfExprAST(SourceLocation Loc, std::unique_ptr<ExprAST> Cond,
295             std::unique_ptr<ExprAST> Then, std::unique_ptr<ExprAST> Else)
296     : ExprAST(Loc), Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
297   std::ostream &dump(std::ostream &out, int ind) override {
298     ExprAST::dump(out << "if", ind);
299     Cond->dump(indent(out, ind) << "Cond:", ind + 1);
300     Then->dump(indent(out, ind) << "Then:", ind + 1);
301     Else->dump(indent(out, ind) << "Else:", ind + 1);
302     return out;
303   }
304   Value *Codegen() override;
305 };
306
307 /// ForExprAST - Expression class for for/in.
308 class ForExprAST : public ExprAST {
309   std::string VarName;
310   std::unique_ptr<ExprAST> Start, End, Step, Body;
311 public:
312   ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
313              std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
314              std::unique_ptr<ExprAST> Body)
315       : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
316         Step(std::move(Step)), Body(std::move(Body)) {}
317   std::ostream &dump(std::ostream &out, int ind) override {
318     ExprAST::dump(out << "for", ind);
319     Start->dump(indent(out, ind) << "Cond:", ind + 1);
320     End->dump(indent(out, ind) << "End:", ind + 1);
321     Step->dump(indent(out, ind) << "Step:", ind + 1);
322     Body->dump(indent(out, ind) << "Body:", ind + 1);
323     return out;
324   }
325   Value *Codegen() override;
326 };
327
328 /// VarExprAST - Expression class for var/in
329 class VarExprAST : public ExprAST {
330   std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
331   std::unique_ptr<ExprAST> Body;
332 public:
333   VarExprAST(std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames,
334              std::unique_ptr<ExprAST> Body)
335       : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
336   std::ostream &dump(std::ostream &out, int ind) override {
337     ExprAST::dump(out << "var", ind);
338     for (const auto &NamedVar : VarNames)
339       NamedVar.second->dump(indent(out, ind) << NamedVar.first << ':', ind + 1);
340     Body->dump(indent(out, ind) << "Body:", ind + 1);
341     return out;
342   }
343   Value *Codegen() override;
344 };
345
346 /// PrototypeAST - This class represents the "prototype" for a function,
347 /// which captures its argument names as well as if it is an operator.
348 class PrototypeAST {
349   std::string Name;
350   std::vector<std::string> Args;
351   bool IsOperator;
352   unsigned Precedence; // Precedence if a binary op.
353   int Line;
354 public:
355   PrototypeAST(SourceLocation Loc, const std::string &Name,
356                std::vector<std::string> Args, bool IsOperator = false,
357                unsigned Prec = 0)
358     : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
359       Precedence(Prec), Line(Loc.Line) {}
360
361   bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
362   bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
363
364   char getOperatorName() const {
365     assert(isUnaryOp() || isBinaryOp());
366     return Name[Name.size() - 1];
367   }
368
369   unsigned getBinaryPrecedence() const { return Precedence; }
370
371   Function *Codegen();
372
373   void CreateArgumentAllocas(Function *F);
374   const std::vector<std::string> &getArgs() const { return Args; }
375 };
376
377 /// FunctionAST - This class represents a function definition itself.
378 class FunctionAST {
379   std::unique_ptr<PrototypeAST> Proto;
380   std::unique_ptr<ExprAST> Body;
381 public:
382   FunctionAST(std::unique_ptr<PrototypeAST> Proto,
383               std::unique_ptr<ExprAST> Body)
384       : Proto(std::move(Proto)), Body(std::move(Body)) {}
385
386   std::ostream &dump(std::ostream &out, int ind) {
387     indent(out, ind) << "FunctionAST\n";
388     ++ind;
389     indent(out, ind) << "Body:";
390     return Body ? Body->dump(out, ind) : out << "null\n";
391   }
392
393   Function *Codegen();
394 };
395 } // end anonymous namespace
396
397 //===----------------------------------------------------------------------===//
398 // Parser
399 //===----------------------------------------------------------------------===//
400
401 /// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
402 /// token the parser is looking at.  getNextToken reads another token from the
403 /// lexer and updates CurTok with its results.
404 static int CurTok;
405 static int getNextToken() { return CurTok = gettok(); }
406
407 /// BinopPrecedence - This holds the precedence for each binary operator that is
408 /// defined.
409 static std::map<char, int> BinopPrecedence;
410
411 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
412 static int GetTokPrecedence() {
413   if (!isascii(CurTok))
414     return -1;
415
416   // Make sure it's a declared binop.
417   int TokPrec = BinopPrecedence[CurTok];
418   if (TokPrec <= 0)
419     return -1;
420   return TokPrec;
421 }
422
423 /// Error* - These are little helper functions for error handling.
424 std::unique_ptr<ExprAST> Error(const char *Str) {
425   fprintf(stderr, "Error: %s\n", Str);
426   return nullptr;
427 }
428 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
429   Error(Str);
430   return nullptr;
431 }
432 std::unique_ptr<FunctionAST> ErrorF(const char *Str) {
433   Error(Str);
434   return nullptr;
435 }
436
437 static std::unique_ptr<ExprAST> ParseExpression();
438
439 /// identifierexpr
440 ///   ::= identifier
441 ///   ::= identifier '(' expression* ')'
442   static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
443   std::string IdName = IdentifierStr;
444
445   SourceLocation LitLoc = CurLoc;
446
447   getNextToken(); // eat identifier.
448
449   if (CurTok != '(') // Simple variable ref.
450     return llvm::make_unique<VariableExprAST>(LitLoc, IdName);
451
452   // Call.
453   getNextToken(); // eat (
454   std::vector<std::unique_ptr<ExprAST>> Args;
455   if (CurTok != ')') {
456     while (1) {
457       auto Arg = ParseExpression();
458       if (!Arg)
459         return nullptr;
460       Args.push_back(std::move(Arg));
461
462       if (CurTok == ')')
463         break;
464
465       if (CurTok != ',')
466         return Error("Expected ')' or ',' in argument list");
467       getNextToken();
468     }
469   }
470
471   // Eat the ')'.
472   getNextToken();
473
474   return llvm::make_unique<CallExprAST>(LitLoc, IdName, std::move(Args));
475 }
476
477 /// numberexpr ::= number
478 static std::unique_ptr<ExprAST> ParseNumberExpr() {
479   auto Result = llvm::make_unique<NumberExprAST>(NumVal);
480   getNextToken(); // consume the number
481   return std::move(Result);
482 }
483
484 /// parenexpr ::= '(' expression ')'
485 static std::unique_ptr<ExprAST> ParseParenExpr() {
486   getNextToken(); // eat (.
487   auto V = ParseExpression();
488   if (!V)
489     return nullptr;
490
491   if (CurTok != ')')
492     return Error("expected ')'");
493   getNextToken(); // eat ).
494   return V;
495 }
496
497 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
498 static std::unique_ptr<ExprAST> ParseIfExpr() {
499   SourceLocation IfLoc = CurLoc;
500
501   getNextToken(); // eat the if.
502
503   // condition.
504   auto Cond = ParseExpression();
505   if (!Cond)
506     return nullptr;
507
508   if (CurTok != tok_then)
509     return Error("expected then");
510   getNextToken(); // eat the then
511
512   auto Then = ParseExpression();
513   if (!Then)
514     return nullptr;
515
516   if (CurTok != tok_else)
517     return Error("expected else");
518
519   getNextToken();
520
521   auto Else = ParseExpression();
522   if (!Else)
523     return nullptr;
524
525   return llvm::make_unique<IfExprAST>(IfLoc, std::move(Cond), std::move(Then),
526                                       std::move(Else));
527 }
528
529 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
530 static std::unique_ptr<ExprAST> ParseForExpr() {
531   getNextToken(); // eat the for.
532
533   if (CurTok != tok_identifier)
534     return Error("expected identifier after for");
535
536   std::string IdName = IdentifierStr;
537   getNextToken(); // eat identifier.
538
539   if (CurTok != '=')
540     return Error("expected '=' after for");
541   getNextToken(); // eat '='.
542
543   auto Start = ParseExpression();
544   if (!Start)
545     return nullptr;
546   if (CurTok != ',')
547     return Error("expected ',' after for start value");
548   getNextToken();
549
550   auto End = ParseExpression();
551   if (!End)
552     return nullptr;
553
554   // The step value is optional.
555   std::unique_ptr<ExprAST> Step;
556   if (CurTok == ',') {
557     getNextToken();
558     Step = ParseExpression();
559     if (!Step)
560       return nullptr;
561   }
562
563   if (CurTok != tok_in)
564     return Error("expected 'in' after for");
565   getNextToken(); // eat 'in'.
566
567   auto Body = ParseExpression();
568   if (!Body)
569     return nullptr;
570
571   return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
572                                        std::move(Step), std::move(Body));
573 }
574
575 /// varexpr ::= 'var' identifier ('=' expression)?
576 //                    (',' identifier ('=' expression)?)* 'in' expression
577 static std::unique_ptr<ExprAST> ParseVarExpr() {
578   getNextToken(); // eat the var.
579
580   std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
581
582   // At least one variable name is required.
583   if (CurTok != tok_identifier)
584     return Error("expected identifier after var");
585
586   while (1) {
587     std::string Name = IdentifierStr;
588     getNextToken(); // eat identifier.
589
590     // Read the optional initializer.
591     std::unique_ptr<ExprAST> Init = nullptr;
592     if (CurTok == '=') {
593       getNextToken(); // eat the '='.
594
595       Init = ParseExpression();
596       if (!Init)
597         return nullptr;
598     }
599
600     VarNames.push_back(std::make_pair(Name, std::move(Init)));
601
602     // End of var list, exit loop.
603     if (CurTok != ',')
604       break;
605     getNextToken(); // eat the ','.
606
607     if (CurTok != tok_identifier)
608       return Error("expected identifier list after var");
609   }
610
611   // At this point, we have to have 'in'.
612   if (CurTok != tok_in)
613     return Error("expected 'in' keyword after 'var'");
614   getNextToken(); // eat 'in'.
615
616   auto Body = ParseExpression();
617   if (!Body)
618     return nullptr;
619
620   return llvm::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
621 }
622
623 /// primary
624 ///   ::= identifierexpr
625 ///   ::= numberexpr
626 ///   ::= parenexpr
627 ///   ::= ifexpr
628 ///   ::= forexpr
629 ///   ::= varexpr
630 static std::unique_ptr<ExprAST> ParsePrimary() {
631   switch (CurTok) {
632   default:
633     return Error("unknown token when expecting an expression");
634   case tok_identifier:
635     return ParseIdentifierExpr();
636   case tok_number:
637     return ParseNumberExpr();
638   case '(':
639     return ParseParenExpr();
640   case tok_if:
641     return ParseIfExpr();
642   case tok_for:
643     return ParseForExpr();
644   case tok_var:
645     return ParseVarExpr();
646   }
647 }
648
649 /// unary
650 ///   ::= primary
651 ///   ::= '!' unary
652 static std::unique_ptr<ExprAST> ParseUnary() {
653   // If the current token is not an operator, it must be a primary expr.
654   if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
655     return ParsePrimary();
656
657   // If this is a unary operator, read it.
658   int Opc = CurTok;
659   getNextToken();
660   if (auto Operand = ParseUnary())
661     return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
662   return nullptr;
663 }
664
665 /// binoprhs
666 ///   ::= ('+' unary)*
667 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec, std::unique_ptr<ExprAST> LHS) {
668   // If this is a binop, find its precedence.
669   while (1) {
670     int TokPrec = GetTokPrecedence();
671
672     // If this is a binop that binds at least as tightly as the current binop,
673     // consume it, otherwise we are done.
674     if (TokPrec < ExprPrec)
675       return LHS;
676
677     // Okay, we know this is a binop.
678     int BinOp = CurTok;
679     SourceLocation BinLoc = CurLoc;
680     getNextToken(); // eat binop
681
682     // Parse the unary expression after the binary operator.
683     auto RHS = ParseUnary();
684     if (!RHS)
685       return nullptr;
686
687     // If BinOp binds less tightly with RHS than the operator after RHS, let
688     // the pending operator take RHS as its LHS.
689     int NextPrec = GetTokPrecedence();
690     if (TokPrec < NextPrec) {
691       RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
692       if (!RHS)
693         return nullptr;
694     }
695
696     // Merge LHS/RHS.
697     LHS = llvm::make_unique<BinaryExprAST>(BinLoc, BinOp, std::move(LHS),
698                                            std::move(RHS));
699   }
700 }
701
702 /// expression
703 ///   ::= unary binoprhs
704 ///
705 static std::unique_ptr<ExprAST> ParseExpression() {
706   auto LHS = ParseUnary();
707   if (!LHS)
708     return nullptr;
709
710   return ParseBinOpRHS(0, std::move(LHS));
711 }
712
713 /// prototype
714 ///   ::= id '(' id* ')'
715 ///   ::= binary LETTER number? (id, id)
716 ///   ::= unary LETTER (id)
717 static std::unique_ptr<PrototypeAST> ParsePrototype() {
718   std::string FnName;
719
720   SourceLocation FnLoc = CurLoc;
721
722   unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
723   unsigned BinaryPrecedence = 30;
724
725   switch (CurTok) {
726   default:
727     return ErrorP("Expected function name in prototype");
728   case tok_identifier:
729     FnName = IdentifierStr;
730     Kind = 0;
731     getNextToken();
732     break;
733   case tok_unary:
734     getNextToken();
735     if (!isascii(CurTok))
736       return ErrorP("Expected unary operator");
737     FnName = "unary";
738     FnName += (char)CurTok;
739     Kind = 1;
740     getNextToken();
741     break;
742   case tok_binary:
743     getNextToken();
744     if (!isascii(CurTok))
745       return ErrorP("Expected binary operator");
746     FnName = "binary";
747     FnName += (char)CurTok;
748     Kind = 2;
749     getNextToken();
750
751     // Read the precedence if present.
752     if (CurTok == tok_number) {
753       if (NumVal < 1 || NumVal > 100)
754         return ErrorP("Invalid precedecnce: must be 1..100");
755       BinaryPrecedence = (unsigned)NumVal;
756       getNextToken();
757     }
758     break;
759   }
760
761   if (CurTok != '(')
762     return ErrorP("Expected '(' in prototype");
763
764   std::vector<std::string> ArgNames;
765   while (getNextToken() == tok_identifier)
766     ArgNames.push_back(IdentifierStr);
767   if (CurTok != ')')
768     return ErrorP("Expected ')' in prototype");
769
770   // success.
771   getNextToken(); // eat ')'.
772
773   // Verify right number of names for operator.
774   if (Kind && ArgNames.size() != Kind)
775     return ErrorP("Invalid number of operands for operator");
776
777   return llvm::make_unique<PrototypeAST>(FnLoc, FnName, ArgNames, Kind != 0,
778                                          BinaryPrecedence);
779 }
780
781 /// definition ::= 'def' prototype expression
782 static std::unique_ptr<FunctionAST> ParseDefinition() {
783   getNextToken(); // eat def.
784   auto Proto = ParsePrototype();
785   if (!Proto)
786     return nullptr;
787
788   if (auto E = ParseExpression())
789     return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
790   return nullptr;
791 }
792
793 /// toplevelexpr ::= expression
794 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
795   SourceLocation FnLoc = CurLoc;
796   if (auto E = ParseExpression()) {
797     // Make an anonymous proto.
798     auto Proto =
799       llvm::make_unique<PrototypeAST>(FnLoc, "main", std::vector<std::string>());
800     return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
801   }
802   return nullptr;
803 }
804
805 /// external ::= 'extern' prototype
806 static std::unique_ptr<PrototypeAST> ParseExtern() {
807   getNextToken(); // eat extern.
808   return ParsePrototype();
809 }
810
811 //===----------------------------------------------------------------------===//
812 // Debug Info Support
813 //===----------------------------------------------------------------------===//
814
815 static DIBuilder *DBuilder;
816
817 DIType *DebugInfo::getDoubleTy() {
818   if (DblTy)
819     return DblTy;
820
821   DblTy = DBuilder->createBasicType("double", 64, 64, dwarf::DW_ATE_float);
822   return DblTy;
823 }
824
825 void DebugInfo::emitLocation(ExprAST *AST) {
826   if (!AST)
827     return Builder.SetCurrentDebugLocation(DebugLoc());
828   DIScope *Scope;
829   if (LexicalBlocks.empty())
830     Scope = TheCU;
831   else
832     Scope = LexicalBlocks.back();
833   Builder.SetCurrentDebugLocation(
834       DebugLoc::get(AST->getLine(), AST->getCol(), Scope));
835 }
836
837 static DISubroutineType *CreateFunctionType(unsigned NumArgs, DIFile *Unit) {
838   SmallVector<Metadata *, 8> EltTys;
839   DIType *DblTy = KSDbgInfo.getDoubleTy();
840
841   // Add the result type.
842   EltTys.push_back(DblTy);
843
844   for (unsigned i = 0, e = NumArgs; i != e; ++i)
845     EltTys.push_back(DblTy);
846
847   return DBuilder->createSubroutineType(Unit,
848                                         DBuilder->getOrCreateTypeArray(EltTys));
849 }
850
851 //===----------------------------------------------------------------------===//
852 // Code Generation
853 //===----------------------------------------------------------------------===//
854
855 static Module *TheModule;
856 static std::map<std::string, AllocaInst *> NamedValues;
857 static legacy::FunctionPassManager *TheFPM;
858
859 Value *ErrorV(const char *Str) {
860   Error(Str);
861   return nullptr;
862 }
863
864 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
865 /// the function.  This is used for mutable variables etc.
866 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
867                                           const std::string &VarName) {
868   IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
869                    TheFunction->getEntryBlock().begin());
870   return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
871                            VarName.c_str());
872 }
873
874 Value *NumberExprAST::Codegen() {
875   KSDbgInfo.emitLocation(this);
876   return ConstantFP::get(getGlobalContext(), APFloat(Val));
877 }
878
879 Value *VariableExprAST::Codegen() {
880   // Look this variable up in the function.
881   Value *V = NamedValues[Name];
882   if (!V)
883     return ErrorV("Unknown variable name");
884
885   KSDbgInfo.emitLocation(this);
886   // Load the value.
887   return Builder.CreateLoad(V, Name.c_str());
888 }
889
890 Value *UnaryExprAST::Codegen() {
891   Value *OperandV = Operand->Codegen();
892   if (!OperandV)
893     return nullptr;
894
895   Function *F = TheModule->getFunction(std::string("unary") + Opcode);
896   if (!F)
897     return ErrorV("Unknown unary operator");
898
899   KSDbgInfo.emitLocation(this);
900   return Builder.CreateCall(F, OperandV, "unop");
901 }
902
903 Value *BinaryExprAST::Codegen() {
904   KSDbgInfo.emitLocation(this);
905
906   // Special case '=' because we don't want to emit the LHS as an expression.
907   if (Op == '=') {
908     // Assignment requires the LHS to be an identifier.
909     // This assume we're building without RTTI because LLVM builds that way by
910     // default.  If you build LLVM with RTTI this can be changed to a
911     // dynamic_cast for automatic error checking.
912     VariableExprAST *LHSE = static_cast<VariableExprAST*>(LHS.get());
913     if (!LHSE)
914       return ErrorV("destination of '=' must be a variable");
915     // Codegen the RHS.
916     Value *Val = RHS->Codegen();
917     if (!Val)
918       return nullptr;
919
920     // Look up the name.
921     Value *Variable = NamedValues[LHSE->getName()];
922     if (!Variable)
923       return ErrorV("Unknown variable name");
924
925     Builder.CreateStore(Val, Variable);
926     return Val;
927   }
928
929   Value *L = LHS->Codegen();
930   Value *R = RHS->Codegen();
931   if (!L || !R)
932     return nullptr;
933
934   switch (Op) {
935   case '+':
936     return Builder.CreateFAdd(L, R, "addtmp");
937   case '-':
938     return Builder.CreateFSub(L, R, "subtmp");
939   case '*':
940     return Builder.CreateFMul(L, R, "multmp");
941   case '<':
942     L = Builder.CreateFCmpULT(L, R, "cmptmp");
943     // Convert bool 0/1 to double 0.0 or 1.0
944     return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
945                                 "booltmp");
946   default:
947     break;
948   }
949
950   // If it wasn't a builtin binary operator, it must be a user defined one. Emit
951   // a call to it.
952   Function *F = TheModule->getFunction(std::string("binary") + Op);
953   assert(F && "binary operator not found!");
954
955   Value *Ops[] = { L, R };
956   return Builder.CreateCall(F, Ops, "binop");
957 }
958
959 Value *CallExprAST::Codegen() {
960   KSDbgInfo.emitLocation(this);
961
962   // Look up the name in the global module table.
963   Function *CalleeF = TheModule->getFunction(Callee);
964   if (!CalleeF)
965     return ErrorV("Unknown function referenced");
966
967   // If argument mismatch error.
968   if (CalleeF->arg_size() != Args.size())
969     return ErrorV("Incorrect # arguments passed");
970
971   std::vector<Value *> ArgsV;
972   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
973     ArgsV.push_back(Args[i]->Codegen());
974     if (!ArgsV.back())
975       return nullptr;
976   }
977
978   return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
979 }
980
981 Value *IfExprAST::Codegen() {
982   KSDbgInfo.emitLocation(this);
983
984   Value *CondV = Cond->Codegen();
985   if (!CondV)
986     return nullptr;
987
988   // Convert condition to a bool by comparing equal to 0.0.
989   CondV = Builder.CreateFCmpONE(
990       CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
991
992   Function *TheFunction = Builder.GetInsertBlock()->getParent();
993
994   // Create blocks for the then and else cases.  Insert the 'then' block at the
995   // end of the function.
996   BasicBlock *ThenBB =
997       BasicBlock::Create(getGlobalContext(), "then", TheFunction);
998   BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
999   BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
1000
1001   Builder.CreateCondBr(CondV, ThenBB, ElseBB);
1002
1003   // Emit then value.
1004   Builder.SetInsertPoint(ThenBB);
1005
1006   Value *ThenV = Then->Codegen();
1007   if (!ThenV)
1008     return nullptr;
1009
1010   Builder.CreateBr(MergeBB);
1011   // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
1012   ThenBB = Builder.GetInsertBlock();
1013
1014   // Emit else block.
1015   TheFunction->getBasicBlockList().push_back(ElseBB);
1016   Builder.SetInsertPoint(ElseBB);
1017
1018   Value *ElseV = Else->Codegen();
1019   if (!ElseV)
1020     return nullptr;
1021
1022   Builder.CreateBr(MergeBB);
1023   // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
1024   ElseBB = Builder.GetInsertBlock();
1025
1026   // Emit merge block.
1027   TheFunction->getBasicBlockList().push_back(MergeBB);
1028   Builder.SetInsertPoint(MergeBB);
1029   PHINode *PN =
1030       Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
1031
1032   PN->addIncoming(ThenV, ThenBB);
1033   PN->addIncoming(ElseV, ElseBB);
1034   return PN;
1035 }
1036
1037 Value *ForExprAST::Codegen() {
1038   // Output this as:
1039   //   var = alloca double
1040   //   ...
1041   //   start = startexpr
1042   //   store start -> var
1043   //   goto loop
1044   // loop:
1045   //   ...
1046   //   bodyexpr
1047   //   ...
1048   // loopend:
1049   //   step = stepexpr
1050   //   endcond = endexpr
1051   //
1052   //   curvar = load var
1053   //   nextvar = curvar + step
1054   //   store nextvar -> var
1055   //   br endcond, loop, endloop
1056   // outloop:
1057
1058   Function *TheFunction = Builder.GetInsertBlock()->getParent();
1059
1060   // Create an alloca for the variable in the entry block.
1061   AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1062
1063   KSDbgInfo.emitLocation(this);
1064
1065   // Emit the start code first, without 'variable' in scope.
1066   Value *StartVal = Start->Codegen();
1067   if (!StartVal)
1068     return nullptr;
1069
1070   // Store the value into the alloca.
1071   Builder.CreateStore(StartVal, Alloca);
1072
1073   // Make the new basic block for the loop header, inserting after current
1074   // block.
1075   BasicBlock *LoopBB =
1076       BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
1077
1078   // Insert an explicit fall through from the current block to the LoopBB.
1079   Builder.CreateBr(LoopBB);
1080
1081   // Start insertion in LoopBB.
1082   Builder.SetInsertPoint(LoopBB);
1083
1084   // Within the loop, the variable is defined equal to the PHI node.  If it
1085   // shadows an existing variable, we have to restore it, so save it now.
1086   AllocaInst *OldVal = NamedValues[VarName];
1087   NamedValues[VarName] = Alloca;
1088
1089   // Emit the body of the loop.  This, like any other expr, can change the
1090   // current BB.  Note that we ignore the value computed by the body, but don't
1091   // allow an error.
1092   if (!Body->Codegen())
1093     return nullptr;
1094
1095   // Emit the step value.
1096   Value *StepVal;
1097   if (Step) {
1098     StepVal = Step->Codegen();
1099     if (!StepVal)
1100       return nullptr;
1101   } else {
1102     // If not specified, use 1.0.
1103     StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
1104   }
1105
1106   // Compute the end condition.
1107   Value *EndCond = End->Codegen();
1108   if (!EndCond)
1109     return EndCond;
1110
1111   // Reload, increment, and restore the alloca.  This handles the case where
1112   // the body of the loop mutates the variable.
1113   Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
1114   Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
1115   Builder.CreateStore(NextVar, Alloca);
1116
1117   // Convert condition to a bool by comparing equal to 0.0.
1118   EndCond = Builder.CreateFCmpONE(
1119       EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
1120
1121   // Create the "after loop" block and insert it.
1122   BasicBlock *AfterBB =
1123       BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
1124
1125   // Insert the conditional branch into the end of LoopEndBB.
1126   Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
1127
1128   // Any new code will be inserted in AfterBB.
1129   Builder.SetInsertPoint(AfterBB);
1130
1131   // Restore the unshadowed variable.
1132   if (OldVal)
1133     NamedValues[VarName] = OldVal;
1134   else
1135     NamedValues.erase(VarName);
1136
1137   // for expr always returns 0.0.
1138   return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
1139 }
1140
1141 Value *VarExprAST::Codegen() {
1142   std::vector<AllocaInst *> OldBindings;
1143
1144   Function *TheFunction = Builder.GetInsertBlock()->getParent();
1145
1146   // Register all variables and emit their initializer.
1147   for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
1148     const std::string &VarName = VarNames[i].first;
1149     ExprAST *Init = VarNames[i].second.get();
1150
1151     // Emit the initializer before adding the variable to scope, this prevents
1152     // the initializer from referencing the variable itself, and permits stuff
1153     // like this:
1154     //  var a = 1 in
1155     //    var a = a in ...   # refers to outer 'a'.
1156     Value *InitVal;
1157     if (Init) {
1158       InitVal = Init->Codegen();
1159       if (!InitVal)
1160         return nullptr;
1161     } else { // If not specified, use 0.0.
1162       InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
1163     }
1164
1165     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1166     Builder.CreateStore(InitVal, Alloca);
1167
1168     // Remember the old variable binding so that we can restore the binding when
1169     // we unrecurse.
1170     OldBindings.push_back(NamedValues[VarName]);
1171
1172     // Remember this binding.
1173     NamedValues[VarName] = Alloca;
1174   }
1175
1176   KSDbgInfo.emitLocation(this);
1177
1178   // Codegen the body, now that all vars are in scope.
1179   Value *BodyVal = Body->Codegen();
1180   if (!BodyVal)
1181     return nullptr;
1182
1183   // Pop all our variables from scope.
1184   for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1185     NamedValues[VarNames[i].first] = OldBindings[i];
1186
1187   // Return the body computation.
1188   return BodyVal;
1189 }
1190
1191 Function *PrototypeAST::Codegen() {
1192   // Make the function type:  double(double,double) etc.
1193   std::vector<Type *> Doubles(Args.size(),
1194                               Type::getDoubleTy(getGlobalContext()));
1195   FunctionType *FT =
1196       FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
1197
1198   Function *F =
1199       Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
1200
1201   // If F conflicted, there was already something named 'Name'.  If it has a
1202   // body, don't allow redefinition or reextern.
1203   if (F->getName() != Name) {
1204     // Delete the one we just made and get the existing one.
1205     F->eraseFromParent();
1206     F = TheModule->getFunction(Name);
1207
1208     // If F already has a body, reject this.
1209     if (!F->empty()) {
1210       ErrorF("redefinition of function");
1211       return nullptr;
1212     }
1213
1214     // If F took a different number of args, reject.
1215     if (F->arg_size() != Args.size()) {
1216       ErrorF("redefinition of function with different # args");
1217       return nullptr;
1218     }
1219   }
1220
1221   // Set names for all arguments.
1222   unsigned Idx = 0;
1223   for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1224        ++AI, ++Idx)
1225     AI->setName(Args[Idx]);
1226
1227   // Create a subprogram DIE for this function.
1228   DIFile *Unit = DBuilder->createFile(KSDbgInfo.TheCU->getFilename(),
1229                                       KSDbgInfo.TheCU->getDirectory());
1230   DIScope *FContext = Unit;
1231   unsigned LineNo = Line;
1232   unsigned ScopeLine = Line;
1233   DISubprogram *SP = DBuilder->createFunction(
1234       FContext, Name, StringRef(), Unit, LineNo,
1235       CreateFunctionType(Args.size(), Unit), false /* internal linkage */,
1236       true /* definition */, ScopeLine, DINode::FlagPrototyped, false, F);
1237
1238   KSDbgInfo.FnScopeMap[this] = SP;
1239   return F;
1240 }
1241
1242 /// CreateArgumentAllocas - Create an alloca for each argument and register the
1243 /// argument in the symbol table so that references to it will succeed.
1244 void PrototypeAST::CreateArgumentAllocas(Function *F) {
1245   Function::arg_iterator AI = F->arg_begin();
1246   for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1247     // Create an alloca for this variable.
1248     AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1249
1250     // Create a debug descriptor for the variable.
1251     DIScope *Scope = KSDbgInfo.LexicalBlocks.back();
1252     DIFile *Unit = DBuilder->createFile(KSDbgInfo.TheCU->getFilename(),
1253                                         KSDbgInfo.TheCU->getDirectory());
1254     DILocalVariable *D = DBuilder->createParameterVariable(
1255         Scope, Args[Idx], Idx + 1, Unit, Line, KSDbgInfo.getDoubleTy(), true);
1256
1257     DBuilder->insertDeclare(Alloca, D, DBuilder->createExpression(),
1258                             DebugLoc::get(Line, 0, Scope),
1259                             Builder.GetInsertBlock());
1260
1261     // Store the initial value into the alloca.
1262     Builder.CreateStore(AI, Alloca);
1263
1264     // Add arguments to variable symbol table.
1265     NamedValues[Args[Idx]] = Alloca;
1266   }
1267 }
1268
1269 Function *FunctionAST::Codegen() {
1270   NamedValues.clear();
1271
1272   Function *TheFunction = Proto->Codegen();
1273   if (!TheFunction)
1274     return nullptr;
1275
1276   // Push the current scope.
1277   KSDbgInfo.LexicalBlocks.push_back(KSDbgInfo.FnScopeMap[Proto.get()]);
1278
1279   // Unset the location for the prologue emission (leading instructions with no
1280   // location in a function are considered part of the prologue and the debugger
1281   // will run past them when breaking on a function)
1282   KSDbgInfo.emitLocation(nullptr);
1283
1284   // If this is an operator, install it.
1285   if (Proto->isBinaryOp())
1286     BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
1287
1288   // Create a new basic block to start insertion into.
1289   BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1290   Builder.SetInsertPoint(BB);
1291
1292   // Add all arguments to the symbol table and create their allocas.
1293   Proto->CreateArgumentAllocas(TheFunction);
1294
1295   KSDbgInfo.emitLocation(Body.get());
1296
1297   if (Value *RetVal = Body->Codegen()) {
1298     // Finish off the function.
1299     Builder.CreateRet(RetVal);
1300
1301     // Pop off the lexical block for the function.
1302     KSDbgInfo.LexicalBlocks.pop_back();
1303
1304     // Validate the generated code, checking for consistency.
1305     verifyFunction(*TheFunction);
1306
1307     // Optimize the function.
1308     TheFPM->run(*TheFunction);
1309
1310     return TheFunction;
1311   }
1312
1313   // Error reading body, remove function.
1314   TheFunction->eraseFromParent();
1315
1316   if (Proto->isBinaryOp())
1317     BinopPrecedence.erase(Proto->getOperatorName());
1318
1319   // Pop off the lexical block for the function since we added it
1320   // unconditionally.
1321   KSDbgInfo.LexicalBlocks.pop_back();
1322
1323   return nullptr;
1324 }
1325
1326 //===----------------------------------------------------------------------===//
1327 // Top-Level parsing and JIT Driver
1328 //===----------------------------------------------------------------------===//
1329
1330 static ExecutionEngine *TheExecutionEngine;
1331
1332 static void HandleDefinition() {
1333   if (auto FnAST = ParseDefinition()) {
1334     if (!FnAST->Codegen()) {
1335       fprintf(stderr, "Error reading function definition:");
1336     }
1337   } else {
1338     // Skip token for error recovery.
1339     getNextToken();
1340   }
1341 }
1342
1343 static void HandleExtern() {
1344   if (auto ProtoAST = ParseExtern()) {
1345     if (!ProtoAST->Codegen()) {
1346       fprintf(stderr, "Error reading extern");
1347     }
1348   } else {
1349     // Skip token for error recovery.
1350     getNextToken();
1351   }
1352 }
1353
1354 static void HandleTopLevelExpression() {
1355   // Evaluate a top-level expression into an anonymous function.
1356   if (auto FnAST = ParseTopLevelExpr()) {
1357     if (!FnAST->Codegen()) {
1358       fprintf(stderr, "Error generating code for top level expr");
1359     }
1360   } else {
1361     // Skip token for error recovery.
1362     getNextToken();
1363   }
1364 }
1365
1366 /// top ::= definition | external | expression | ';'
1367 static void MainLoop() {
1368   while (1) {
1369     switch (CurTok) {
1370     case tok_eof:
1371       return;
1372     case ';':
1373       getNextToken();
1374       break; // ignore top-level semicolons.
1375     case tok_def:
1376       HandleDefinition();
1377       break;
1378     case tok_extern:
1379       HandleExtern();
1380       break;
1381     default:
1382       HandleTopLevelExpression();
1383       break;
1384     }
1385   }
1386 }
1387
1388 //===----------------------------------------------------------------------===//
1389 // "Library" functions that can be "extern'd" from user code.
1390 //===----------------------------------------------------------------------===//
1391
1392 /// putchard - putchar that takes a double and returns 0.
1393 extern "C" double putchard(double X) {
1394   putchar((char)X);
1395   return 0;
1396 }
1397
1398 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1399 extern "C" double printd(double X) {
1400   printf("%f\n", X);
1401   return 0;
1402 }
1403
1404 //===----------------------------------------------------------------------===//
1405 // Main driver code.
1406 //===----------------------------------------------------------------------===//
1407
1408 int main() {
1409   InitializeNativeTarget();
1410   InitializeNativeTargetAsmPrinter();
1411   InitializeNativeTargetAsmParser();
1412   LLVMContext &Context = getGlobalContext();
1413
1414   // Install standard binary operators.
1415   // 1 is lowest precedence.
1416   BinopPrecedence['='] = 2;
1417   BinopPrecedence['<'] = 10;
1418   BinopPrecedence['+'] = 20;
1419   BinopPrecedence['-'] = 20;
1420   BinopPrecedence['*'] = 40; // highest.
1421
1422   // Prime the first token.
1423   getNextToken();
1424
1425   // Make the module, which holds all the code.
1426   std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1427   TheModule = Owner.get();
1428
1429   // Add the current debug info version into the module.
1430   TheModule->addModuleFlag(Module::Warning, "Debug Info Version",
1431                            DEBUG_METADATA_VERSION);
1432
1433   // Darwin only supports dwarf2.
1434   if (Triple(sys::getProcessTriple()).isOSDarwin())
1435     TheModule->addModuleFlag(llvm::Module::Warning, "Dwarf Version", 2);
1436
1437   // Construct the DIBuilder, we do this here because we need the module.
1438   DBuilder = new DIBuilder(*TheModule);
1439
1440   // Create the compile unit for the module.
1441   // Currently down as "fib.ks" as a filename since we're redirecting stdin
1442   // but we'd like actual source locations.
1443   KSDbgInfo.TheCU = DBuilder->createCompileUnit(
1444       dwarf::DW_LANG_C, "fib.ks", ".", "Kaleidoscope Compiler", 0, "", 0);
1445
1446   // Create the JIT.  This takes ownership of the module.
1447   std::string ErrStr;
1448   TheExecutionEngine =
1449       EngineBuilder(std::move(Owner))
1450           .setErrorStr(&ErrStr)
1451           .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
1452           .create();
1453   if (!TheExecutionEngine) {
1454     fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1455     exit(1);
1456   }
1457
1458   legacy::FunctionPassManager OurFPM(TheModule);
1459
1460   // Set up the optimizer pipeline.  Start with registering info about how the
1461   // target lays out data structures.
1462   TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
1463 #if 0
1464   // Provide basic AliasAnalysis support for GVN.
1465   OurFPM.add(createBasicAliasAnalysisPass());
1466   // Promote allocas to registers.
1467   OurFPM.add(createPromoteMemoryToRegisterPass());
1468   // Do simple "peephole" optimizations and bit-twiddling optzns.
1469   OurFPM.add(createInstructionCombiningPass());
1470   // Reassociate expressions.
1471   OurFPM.add(createReassociatePass());
1472   // Eliminate Common SubExpressions.
1473   OurFPM.add(createGVNPass());
1474   // Simplify the control flow graph (deleting unreachable blocks, etc).
1475   OurFPM.add(createCFGSimplificationPass());
1476   #endif
1477   OurFPM.doInitialization();
1478
1479   // Set the global so the code gen can use this.
1480   TheFPM = &OurFPM;
1481
1482   // Run the main "interpreter loop" now.
1483   MainLoop();
1484
1485   TheFPM = 0;
1486
1487   // Finalize the debug info.
1488   DBuilder->finalize();
1489
1490   // Print out all of the generated code.
1491   TheModule->dump();
1492
1493   return 0;
1494 }