[weak vtables] Remove a bunch of weak vtables
[oota-llvm.git] / examples / Kaleidoscope / Chapter4 / toy.cpp
1 #include "llvm/Analysis/Passes.h"
2 #include "llvm/Analysis/Verifier.h"
3 #include "llvm/ExecutionEngine/ExecutionEngine.h"
4 #include "llvm/ExecutionEngine/JIT.h"
5 #include "llvm/IR/DataLayout.h"
6 #include "llvm/IR/DerivedTypes.h"
7 #include "llvm/IR/IRBuilder.h"
8 #include "llvm/IR/LLVMContext.h"
9 #include "llvm/IR/Module.h"
10 #include "llvm/PassManager.h"
11 #include "llvm/Support/TargetSelect.h"
12 #include "llvm/Transforms/Scalar.h"
13 #include <cctype>
14 #include <cstdio>
15 #include <map>
16 #include <string>
17 #include <vector>
18 using namespace llvm;
19
20 //===----------------------------------------------------------------------===//
21 // Lexer
22 //===----------------------------------------------------------------------===//
23
24 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
25 // of these for known things.
26 enum Token {
27   tok_eof = -1,
28
29   // commands
30   tok_def = -2, tok_extern = -3,
31
32   // primary
33   tok_identifier = -4, tok_number = -5
34 };
35
36 static std::string IdentifierStr;  // Filled in if tok_identifier
37 static double NumVal;              // Filled in if tok_number
38
39 /// gettok - Return the next token from standard input.
40 static int gettok() {
41   static int LastChar = ' ';
42
43   // Skip any whitespace.
44   while (isspace(LastChar))
45     LastChar = getchar();
46
47   if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
48     IdentifierStr = LastChar;
49     while (isalnum((LastChar = getchar())))
50       IdentifierStr += LastChar;
51
52     if (IdentifierStr == "def") return tok_def;
53     if (IdentifierStr == "extern") return tok_extern;
54     return tok_identifier;
55   }
56
57   if (isdigit(LastChar) || LastChar == '.') {   // Number: [0-9.]+
58     std::string NumStr;
59     do {
60       NumStr += LastChar;
61       LastChar = getchar();
62     } while (isdigit(LastChar) || LastChar == '.');
63
64     NumVal = strtod(NumStr.c_str(), 0);
65     return tok_number;
66   }
67
68   if (LastChar == '#') {
69     // Comment until end of line.
70     do LastChar = getchar();
71     while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
72     
73     if (LastChar != EOF)
74       return gettok();
75   }
76   
77   // Check for end of file.  Don't eat the EOF.
78   if (LastChar == EOF)
79     return tok_eof;
80
81   // Otherwise, just return the character as its ascii value.
82   int ThisChar = LastChar;
83   LastChar = getchar();
84   return ThisChar;
85 }
86
87 //===----------------------------------------------------------------------===//
88 // Abstract Syntax Tree (aka Parse Tree)
89 //===----------------------------------------------------------------------===//
90
91 /// ExprAST - Base class for all expression nodes.
92 class ExprAST {
93 public:
94   virtual ~ExprAST();
95   virtual Value *Codegen() = 0;
96 };
97
98 // Provide out-of-line definition to prevent weak vtable.
99 ExprAST::~ExprAST() {}
100
101 /// NumberExprAST - Expression class for numeric literals like "1.0".
102 class NumberExprAST : public ExprAST {
103   double Val;
104 public:
105   NumberExprAST(double val) : Val(val) {}
106   virtual Value *Codegen();
107 };
108
109 /// VariableExprAST - Expression class for referencing a variable, like "a".
110 class VariableExprAST : public ExprAST {
111   std::string Name;
112 public:
113   VariableExprAST(const std::string &name) : Name(name) {}
114   virtual Value *Codegen();
115 };
116
117 /// BinaryExprAST - Expression class for a binary operator.
118 class BinaryExprAST : public ExprAST {
119   char Op;
120   ExprAST *LHS, *RHS;
121 public:
122   BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs) 
123     : Op(op), LHS(lhs), RHS(rhs) {}
124   virtual Value *Codegen();
125 };
126
127 /// CallExprAST - Expression class for function calls.
128 class CallExprAST : public ExprAST {
129   std::string Callee;
130   std::vector<ExprAST*> Args;
131 public:
132   CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
133     : Callee(callee), Args(args) {}
134   virtual Value *Codegen();
135 };
136
137 /// PrototypeAST - This class represents the "prototype" for a function,
138 /// which captures its name, and its argument names (thus implicitly the number
139 /// of arguments the function takes).
140 class PrototypeAST {
141   std::string Name;
142   std::vector<std::string> Args;
143 public:
144   PrototypeAST(const std::string &name, const std::vector<std::string> &args)
145     : Name(name), Args(args) {}
146   
147   Function *Codegen();
148 };
149
150 /// FunctionAST - This class represents a function definition itself.
151 class FunctionAST {
152   PrototypeAST *Proto;
153   ExprAST *Body;
154 public:
155   FunctionAST(PrototypeAST *proto, ExprAST *body)
156     : Proto(proto), Body(body) {}
157   
158   Function *Codegen();
159 };
160
161 //===----------------------------------------------------------------------===//
162 // Parser
163 //===----------------------------------------------------------------------===//
164
165 /// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
166 /// token the parser is looking at.  getNextToken reads another token from the
167 /// lexer and updates CurTok with its results.
168 static int CurTok;
169 static int getNextToken() {
170   return CurTok = gettok();
171 }
172
173 /// BinopPrecedence - This holds the precedence for each binary operator that is
174 /// defined.
175 static std::map<char, int> BinopPrecedence;
176
177 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
178 static int GetTokPrecedence() {
179   if (!isascii(CurTok))
180     return -1;
181   
182   // Make sure it's a declared binop.
183   int TokPrec = BinopPrecedence[CurTok];
184   if (TokPrec <= 0) return -1;
185   return TokPrec;
186 }
187
188 /// Error* - These are little helper functions for error handling.
189 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
190 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
191 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
192
193 static ExprAST *ParseExpression();
194
195 /// identifierexpr
196 ///   ::= identifier
197 ///   ::= identifier '(' expression* ')'
198 static ExprAST *ParseIdentifierExpr() {
199   std::string IdName = IdentifierStr;
200   
201   getNextToken();  // eat identifier.
202   
203   if (CurTok != '(') // Simple variable ref.
204     return new VariableExprAST(IdName);
205   
206   // Call.
207   getNextToken();  // eat (
208   std::vector<ExprAST*> Args;
209   if (CurTok != ')') {
210     while (1) {
211       ExprAST *Arg = ParseExpression();
212       if (!Arg) return 0;
213       Args.push_back(Arg);
214
215       if (CurTok == ')') break;
216
217       if (CurTok != ',')
218         return Error("Expected ')' or ',' in argument list");
219       getNextToken();
220     }
221   }
222
223   // Eat the ')'.
224   getNextToken();
225   
226   return new CallExprAST(IdName, Args);
227 }
228
229 /// numberexpr ::= number
230 static ExprAST *ParseNumberExpr() {
231   ExprAST *Result = new NumberExprAST(NumVal);
232   getNextToken(); // consume the number
233   return Result;
234 }
235
236 /// parenexpr ::= '(' expression ')'
237 static ExprAST *ParseParenExpr() {
238   getNextToken();  // eat (.
239   ExprAST *V = ParseExpression();
240   if (!V) return 0;
241   
242   if (CurTok != ')')
243     return Error("expected ')'");
244   getNextToken();  // eat ).
245   return V;
246 }
247
248 /// primary
249 ///   ::= identifierexpr
250 ///   ::= numberexpr
251 ///   ::= parenexpr
252 static ExprAST *ParsePrimary() {
253   switch (CurTok) {
254   default: return Error("unknown token when expecting an expression");
255   case tok_identifier: return ParseIdentifierExpr();
256   case tok_number:     return ParseNumberExpr();
257   case '(':            return ParseParenExpr();
258   }
259 }
260
261 /// binoprhs
262 ///   ::= ('+' primary)*
263 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
264   // If this is a binop, find its precedence.
265   while (1) {
266     int TokPrec = GetTokPrecedence();
267     
268     // If this is a binop that binds at least as tightly as the current binop,
269     // consume it, otherwise we are done.
270     if (TokPrec < ExprPrec)
271       return LHS;
272     
273     // Okay, we know this is a binop.
274     int BinOp = CurTok;
275     getNextToken();  // eat binop
276     
277     // Parse the primary expression after the binary operator.
278     ExprAST *RHS = ParsePrimary();
279     if (!RHS) return 0;
280     
281     // If BinOp binds less tightly with RHS than the operator after RHS, let
282     // the pending operator take RHS as its LHS.
283     int NextPrec = GetTokPrecedence();
284     if (TokPrec < NextPrec) {
285       RHS = ParseBinOpRHS(TokPrec+1, RHS);
286       if (RHS == 0) return 0;
287     }
288     
289     // Merge LHS/RHS.
290     LHS = new BinaryExprAST(BinOp, LHS, RHS);
291   }
292 }
293
294 /// expression
295 ///   ::= primary binoprhs
296 ///
297 static ExprAST *ParseExpression() {
298   ExprAST *LHS = ParsePrimary();
299   if (!LHS) return 0;
300   
301   return ParseBinOpRHS(0, LHS);
302 }
303
304 /// prototype
305 ///   ::= id '(' id* ')'
306 static PrototypeAST *ParsePrototype() {
307   if (CurTok != tok_identifier)
308     return ErrorP("Expected function name in prototype");
309
310   std::string FnName = IdentifierStr;
311   getNextToken();
312   
313   if (CurTok != '(')
314     return ErrorP("Expected '(' in prototype");
315   
316   std::vector<std::string> ArgNames;
317   while (getNextToken() == tok_identifier)
318     ArgNames.push_back(IdentifierStr);
319   if (CurTok != ')')
320     return ErrorP("Expected ')' in prototype");
321   
322   // success.
323   getNextToken();  // eat ')'.
324   
325   return new PrototypeAST(FnName, ArgNames);
326 }
327
328 /// definition ::= 'def' prototype expression
329 static FunctionAST *ParseDefinition() {
330   getNextToken();  // eat def.
331   PrototypeAST *Proto = ParsePrototype();
332   if (Proto == 0) return 0;
333
334   if (ExprAST *E = ParseExpression())
335     return new FunctionAST(Proto, E);
336   return 0;
337 }
338
339 /// toplevelexpr ::= expression
340 static FunctionAST *ParseTopLevelExpr() {
341   if (ExprAST *E = ParseExpression()) {
342     // Make an anonymous proto.
343     PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
344     return new FunctionAST(Proto, E);
345   }
346   return 0;
347 }
348
349 /// external ::= 'extern' prototype
350 static PrototypeAST *ParseExtern() {
351   getNextToken();  // eat extern.
352   return ParsePrototype();
353 }
354
355 //===----------------------------------------------------------------------===//
356 // Code Generation
357 //===----------------------------------------------------------------------===//
358
359 static Module *TheModule;
360 static IRBuilder<> Builder(getGlobalContext());
361 static std::map<std::string, Value*> NamedValues;
362 static FunctionPassManager *TheFPM;
363
364 Value *ErrorV(const char *Str) { Error(Str); return 0; }
365
366 Value *NumberExprAST::Codegen() {
367   return ConstantFP::get(getGlobalContext(), APFloat(Val));
368 }
369
370 Value *VariableExprAST::Codegen() {
371   // Look this variable up in the function.
372   Value *V = NamedValues[Name];
373   return V ? V : ErrorV("Unknown variable name");
374 }
375
376 Value *BinaryExprAST::Codegen() {
377   Value *L = LHS->Codegen();
378   Value *R = RHS->Codegen();
379   if (L == 0 || R == 0) return 0;
380   
381   switch (Op) {
382   case '+': return Builder.CreateFAdd(L, R, "addtmp");
383   case '-': return Builder.CreateFSub(L, R, "subtmp");
384   case '*': return Builder.CreateFMul(L, R, "multmp");
385   case '<':
386     L = Builder.CreateFCmpULT(L, R, "cmptmp");
387     // Convert bool 0/1 to double 0.0 or 1.0
388     return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
389                                 "booltmp");
390   default: return ErrorV("invalid binary operator");
391   }
392 }
393
394 Value *CallExprAST::Codegen() {
395   // Look up the name in the global module table.
396   Function *CalleeF = TheModule->getFunction(Callee);
397   if (CalleeF == 0)
398     return ErrorV("Unknown function referenced");
399   
400   // If argument mismatch error.
401   if (CalleeF->arg_size() != Args.size())
402     return ErrorV("Incorrect # arguments passed");
403
404   std::vector<Value*> ArgsV;
405   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
406     ArgsV.push_back(Args[i]->Codegen());
407     if (ArgsV.back() == 0) return 0;
408   }
409   
410   return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
411 }
412
413 Function *PrototypeAST::Codegen() {
414   // Make the function type:  double(double,double) etc.
415   std::vector<Type*> Doubles(Args.size(),
416                              Type::getDoubleTy(getGlobalContext()));
417   FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
418                                        Doubles, false);
419   
420   Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
421   
422   // If F conflicted, there was already something named 'Name'.  If it has a
423   // body, don't allow redefinition or reextern.
424   if (F->getName() != Name) {
425     // Delete the one we just made and get the existing one.
426     F->eraseFromParent();
427     F = TheModule->getFunction(Name);
428     
429     // If F already has a body, reject this.
430     if (!F->empty()) {
431       ErrorF("redefinition of function");
432       return 0;
433     }
434     
435     // If F took a different number of args, reject.
436     if (F->arg_size() != Args.size()) {
437       ErrorF("redefinition of function with different # args");
438       return 0;
439     }
440   }
441   
442   // Set names for all arguments.
443   unsigned Idx = 0;
444   for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
445        ++AI, ++Idx) {
446     AI->setName(Args[Idx]);
447     
448     // Add arguments to variable symbol table.
449     NamedValues[Args[Idx]] = AI;
450   }
451   
452   return F;
453 }
454
455 Function *FunctionAST::Codegen() {
456   NamedValues.clear();
457   
458   Function *TheFunction = Proto->Codegen();
459   if (TheFunction == 0)
460     return 0;
461   
462   // Create a new basic block to start insertion into.
463   BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
464   Builder.SetInsertPoint(BB);
465   
466   if (Value *RetVal = Body->Codegen()) {
467     // Finish off the function.
468     Builder.CreateRet(RetVal);
469
470     // Validate the generated code, checking for consistency.
471     verifyFunction(*TheFunction);
472
473     // Optimize the function.
474     TheFPM->run(*TheFunction);
475     
476     return TheFunction;
477   }
478   
479   // Error reading body, remove function.
480   TheFunction->eraseFromParent();
481   return 0;
482 }
483
484 //===----------------------------------------------------------------------===//
485 // Top-Level parsing and JIT Driver
486 //===----------------------------------------------------------------------===//
487
488 static ExecutionEngine *TheExecutionEngine;
489
490 static void HandleDefinition() {
491   if (FunctionAST *F = ParseDefinition()) {
492     if (Function *LF = F->Codegen()) {
493       fprintf(stderr, "Read function definition:");
494       LF->dump();
495     }
496   } else {
497     // Skip token for error recovery.
498     getNextToken();
499   }
500 }
501
502 static void HandleExtern() {
503   if (PrototypeAST *P = ParseExtern()) {
504     if (Function *F = P->Codegen()) {
505       fprintf(stderr, "Read extern: ");
506       F->dump();
507     }
508   } else {
509     // Skip token for error recovery.
510     getNextToken();
511   }
512 }
513
514 static void HandleTopLevelExpression() {
515   // Evaluate a top-level expression into an anonymous function.
516   if (FunctionAST *F = ParseTopLevelExpr()) {
517     if (Function *LF = F->Codegen()) {
518       // JIT the function, returning a function pointer.
519       void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
520       
521       // Cast it to the right type (takes no arguments, returns a double) so we
522       // can call it as a native function.
523       double (*FP)() = (double (*)())(intptr_t)FPtr;
524       fprintf(stderr, "Evaluated to %f\n", FP());
525     }
526   } else {
527     // Skip token for error recovery.
528     getNextToken();
529   }
530 }
531
532 /// top ::= definition | external | expression | ';'
533 static void MainLoop() {
534   while (1) {
535     fprintf(stderr, "ready> ");
536     switch (CurTok) {
537     case tok_eof:    return;
538     case ';':        getNextToken(); break;  // ignore top-level semicolons.
539     case tok_def:    HandleDefinition(); break;
540     case tok_extern: HandleExtern(); break;
541     default:         HandleTopLevelExpression(); break;
542     }
543   }
544 }
545
546 //===----------------------------------------------------------------------===//
547 // "Library" functions that can be "extern'd" from user code.
548 //===----------------------------------------------------------------------===//
549
550 /// putchard - putchar that takes a double and returns 0.
551 extern "C" 
552 double putchard(double X) {
553   putchar((char)X);
554   return 0;
555 }
556
557 //===----------------------------------------------------------------------===//
558 // Main driver code.
559 //===----------------------------------------------------------------------===//
560
561 int main() {
562   InitializeNativeTarget();
563   LLVMContext &Context = getGlobalContext();
564
565   // Install standard binary operators.
566   // 1 is lowest precedence.
567   BinopPrecedence['<'] = 10;
568   BinopPrecedence['+'] = 20;
569   BinopPrecedence['-'] = 20;
570   BinopPrecedence['*'] = 40;  // highest.
571
572   // Prime the first token.
573   fprintf(stderr, "ready> ");
574   getNextToken();
575
576   // Make the module, which holds all the code.
577   TheModule = new Module("my cool jit", Context);
578
579   // Create the JIT.  This takes ownership of the module.
580   std::string ErrStr;
581   TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
582   if (!TheExecutionEngine) {
583     fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
584     exit(1);
585   }
586
587   FunctionPassManager OurFPM(TheModule);
588
589   // Set up the optimizer pipeline.  Start with registering info about how the
590   // target lays out data structures.
591   OurFPM.add(new DataLayout(*TheExecutionEngine->getDataLayout()));
592   // Provide basic AliasAnalysis support for GVN.
593   OurFPM.add(createBasicAliasAnalysisPass());
594   // Do simple "peephole" optimizations and bit-twiddling optzns.
595   OurFPM.add(createInstructionCombiningPass());
596   // Reassociate expressions.
597   OurFPM.add(createReassociatePass());
598   // Eliminate Common SubExpressions.
599   OurFPM.add(createGVNPass());
600   // Simplify the control flow graph (deleting unreachable blocks, etc).
601   OurFPM.add(createCFGSimplificationPass());
602
603   OurFPM.doInitialization();
604
605   // Set the global so the code gen can use this.
606   TheFPM = &OurFPM;
607
608   // Run the main "interpreter loop" now.
609   MainLoop();
610
611   TheFPM = 0;
612
613   // Print out all of the generated code.
614   TheModule->dump();
615
616   return 0;
617 }