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