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