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