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