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