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