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