Kaleidoscope: Prune __attribute__((used)). Some compilers wouldn't accept one.
[oota-llvm.git] / examples / Kaleidoscope / Chapter7 / 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   // control
39   tok_if = -6,
40   tok_then = -7,
41   tok_else = -8,
42   tok_for = -9,
43   tok_in = -10,
44
45   // operators
46   tok_binary = -11,
47   tok_unary = -12,
48
49   // var definition
50   tok_var = -13
51 };
52
53 static std::string IdentifierStr; // Filled in if tok_identifier
54 static double NumVal;             // Filled in if tok_number
55
56 /// gettok - Return the next token from standard input.
57 static int gettok() {
58   static int LastChar = ' ';
59
60   // Skip any whitespace.
61   while (isspace(LastChar))
62     LastChar = getchar();
63
64   if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
65     IdentifierStr = LastChar;
66     while (isalnum((LastChar = getchar())))
67       IdentifierStr += LastChar;
68
69     if (IdentifierStr == "def")
70       return tok_def;
71     if (IdentifierStr == "extern")
72       return tok_extern;
73     if (IdentifierStr == "if")
74       return tok_if;
75     if (IdentifierStr == "then")
76       return tok_then;
77     if (IdentifierStr == "else")
78       return tok_else;
79     if (IdentifierStr == "for")
80       return tok_for;
81     if (IdentifierStr == "in")
82       return tok_in;
83     if (IdentifierStr == "binary")
84       return tok_binary;
85     if (IdentifierStr == "unary")
86       return tok_unary;
87     if (IdentifierStr == "var")
88       return tok_var;
89     return tok_identifier;
90   }
91
92   if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
93     std::string NumStr;
94     do {
95       NumStr += LastChar;
96       LastChar = getchar();
97     } while (isdigit(LastChar) || LastChar == '.');
98
99     NumVal = strtod(NumStr.c_str(), 0);
100     return tok_number;
101   }
102
103   if (LastChar == '#') {
104     // Comment until end of line.
105     do
106       LastChar = getchar();
107     while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
108
109     if (LastChar != EOF)
110       return gettok();
111   }
112
113   // Check for end of file.  Don't eat the EOF.
114   if (LastChar == EOF)
115     return tok_eof;
116
117   // Otherwise, just return the character as its ascii value.
118   int ThisChar = LastChar;
119   LastChar = getchar();
120   return ThisChar;
121 }
122
123 //===----------------------------------------------------------------------===//
124 // Abstract Syntax Tree (aka Parse Tree)
125 //===----------------------------------------------------------------------===//
126 namespace {
127 /// ExprAST - Base class for all expression nodes.
128 class ExprAST {
129 public:
130   virtual ~ExprAST() {}
131   virtual Value *codegen() = 0;
132 };
133
134 /// NumberExprAST - Expression class for numeric literals like "1.0".
135 class NumberExprAST : public ExprAST {
136   double Val;
137
138 public:
139   NumberExprAST(double Val) : Val(Val) {}
140   Value *codegen() override;
141 };
142
143 /// VariableExprAST - Expression class for referencing a variable, like "a".
144 class VariableExprAST : public ExprAST {
145   std::string Name;
146
147 public:
148   VariableExprAST(const std::string &Name) : Name(Name) {}
149   const std::string &getName() const { return Name; }
150   Value *codegen() override;
151 };
152
153 /// UnaryExprAST - Expression class for a unary operator.
154 class UnaryExprAST : public ExprAST {
155   char Opcode;
156   std::unique_ptr<ExprAST> Operand;
157
158 public:
159   UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
160       : Opcode(Opcode), Operand(std::move(Operand)) {}
161   Value *codegen() override;
162 };
163
164 /// BinaryExprAST - Expression class for a binary operator.
165 class BinaryExprAST : public ExprAST {
166   char Op;
167   std::unique_ptr<ExprAST> LHS, RHS;
168
169 public:
170   BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
171                 std::unique_ptr<ExprAST> RHS)
172       : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
173   Value *codegen() override;
174 };
175
176 /// CallExprAST - Expression class for function calls.
177 class CallExprAST : public ExprAST {
178   std::string Callee;
179   std::vector<std::unique_ptr<ExprAST>> Args;
180
181 public:
182   CallExprAST(const std::string &Callee,
183               std::vector<std::unique_ptr<ExprAST>> Args)
184       : Callee(Callee), Args(std::move(Args)) {}
185   Value *codegen() override;
186 };
187
188 /// IfExprAST - Expression class for if/then/else.
189 class IfExprAST : public ExprAST {
190   std::unique_ptr<ExprAST> Cond, Then, Else;
191
192 public:
193   IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
194             std::unique_ptr<ExprAST> Else)
195       : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
196   Value *codegen() override;
197 };
198
199 /// ForExprAST - Expression class for for/in.
200 class ForExprAST : public ExprAST {
201   std::string VarName;
202   std::unique_ptr<ExprAST> Start, End, Step, Body;
203
204 public:
205   ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
206              std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
207              std::unique_ptr<ExprAST> Body)
208       : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
209         Step(std::move(Step)), Body(std::move(Body)) {}
210   Value *codegen() override;
211 };
212
213 /// VarExprAST - Expression class for var/in
214 class VarExprAST : public ExprAST {
215   std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
216   std::unique_ptr<ExprAST> Body;
217
218 public:
219   VarExprAST(
220       std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames,
221       std::unique_ptr<ExprAST> Body)
222       : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
223   Value *codegen() override;
224 };
225
226 /// PrototypeAST - This class represents the "prototype" for a function,
227 /// which captures its name, and its argument names (thus implicitly the number
228 /// of arguments the function takes), as well as if it is an operator.
229 class PrototypeAST {
230   std::string Name;
231   std::vector<std::string> Args;
232   bool IsOperator;
233   unsigned Precedence; // Precedence if a binary op.
234
235 public:
236   PrototypeAST(const std::string &Name, std::vector<std::string> Args,
237                bool IsOperator = false, unsigned Prec = 0)
238       : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
239         Precedence(Prec) {}
240   Function *codegen();
241   const std::string &getName() const { return Name; }
242
243   bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
244   bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
245
246   char getOperatorName() const {
247     assert(isUnaryOp() || isBinaryOp());
248     return Name[Name.size() - 1];
249   }
250
251   unsigned getBinaryPrecedence() const { return Precedence; }
252 };
253
254 /// FunctionAST - This class represents a function definition itself.
255 class FunctionAST {
256   std::unique_ptr<PrototypeAST> Proto;
257   std::unique_ptr<ExprAST> Body;
258
259 public:
260   FunctionAST(std::unique_ptr<PrototypeAST> Proto,
261               std::unique_ptr<ExprAST> Body)
262       : Proto(std::move(Proto)), Body(std::move(Body)) {}
263   Function *codegen();
264 };
265 } // end anonymous namespace
266
267 //===----------------------------------------------------------------------===//
268 // Parser
269 //===----------------------------------------------------------------------===//
270
271 /// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
272 /// token the parser is looking at.  getNextToken reads another token from the
273 /// lexer and updates CurTok with its results.
274 static int CurTok;
275 static int getNextToken() { return CurTok = gettok(); }
276
277 /// BinopPrecedence - This holds the precedence for each binary operator that is
278 /// defined.
279 static std::map<char, int> BinopPrecedence;
280
281 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
282 static int GetTokPrecedence() {
283   if (!isascii(CurTok))
284     return -1;
285
286   // Make sure it's a declared binop.
287   int TokPrec = BinopPrecedence[CurTok];
288   if (TokPrec <= 0)
289     return -1;
290   return TokPrec;
291 }
292
293 /// Error* - These are little helper functions for error handling.
294 std::unique_ptr<ExprAST> Error(const char *Str) {
295   fprintf(stderr, "Error: %s\n", Str);
296   return nullptr;
297 }
298 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
299   Error(Str);
300   return nullptr;
301 }
302
303 static std::unique_ptr<ExprAST> ParseExpression();
304
305 /// numberexpr ::= number
306 static std::unique_ptr<ExprAST> ParseNumberExpr() {
307   auto Result = llvm::make_unique<NumberExprAST>(NumVal);
308   getNextToken(); // consume the number
309   return std::move(Result);
310 }
311
312 /// parenexpr ::= '(' expression ')'
313 static std::unique_ptr<ExprAST> ParseParenExpr() {
314   getNextToken(); // eat (.
315   auto V = ParseExpression();
316   if (!V)
317     return nullptr;
318
319   if (CurTok != ')')
320     return Error("expected ')'");
321   getNextToken(); // eat ).
322   return V;
323 }
324
325 /// identifierexpr
326 ///   ::= identifier
327 ///   ::= identifier '(' expression* ')'
328 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
329   std::string IdName = IdentifierStr;
330
331   getNextToken(); // eat identifier.
332
333   if (CurTok != '(') // Simple variable ref.
334     return llvm::make_unique<VariableExprAST>(IdName);
335
336   // Call.
337   getNextToken(); // eat (
338   std::vector<std::unique_ptr<ExprAST>> Args;
339   if (CurTok != ')') {
340     while (1) {
341       if (auto Arg = ParseExpression())
342         Args.push_back(std::move(Arg));
343       else
344         return nullptr;
345
346       if (CurTok == ')')
347         break;
348
349       if (CurTok != ',')
350         return Error("Expected ')' or ',' in argument list");
351       getNextToken();
352     }
353   }
354
355   // Eat the ')'.
356   getNextToken();
357
358   return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
359 }
360
361 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
362 static std::unique_ptr<ExprAST> ParseIfExpr() {
363   getNextToken(); // eat the if.
364
365   // condition.
366   auto Cond = ParseExpression();
367   if (!Cond)
368     return nullptr;
369
370   if (CurTok != tok_then)
371     return Error("expected then");
372   getNextToken(); // eat the then
373
374   auto Then = ParseExpression();
375   if (!Then)
376     return nullptr;
377
378   if (CurTok != tok_else)
379     return Error("expected else");
380
381   getNextToken();
382
383   auto Else = ParseExpression();
384   if (!Else)
385     return nullptr;
386
387   return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
388                                       std::move(Else));
389 }
390
391 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
392 static std::unique_ptr<ExprAST> ParseForExpr() {
393   getNextToken(); // eat the for.
394
395   if (CurTok != tok_identifier)
396     return Error("expected identifier after for");
397
398   std::string IdName = IdentifierStr;
399   getNextToken(); // eat identifier.
400
401   if (CurTok != '=')
402     return Error("expected '=' after for");
403   getNextToken(); // eat '='.
404
405   auto Start = ParseExpression();
406   if (!Start)
407     return nullptr;
408   if (CurTok != ',')
409     return Error("expected ',' after for start value");
410   getNextToken();
411
412   auto End = ParseExpression();
413   if (!End)
414     return nullptr;
415
416   // The step value is optional.
417   std::unique_ptr<ExprAST> Step;
418   if (CurTok == ',') {
419     getNextToken();
420     Step = ParseExpression();
421     if (!Step)
422       return nullptr;
423   }
424
425   if (CurTok != tok_in)
426     return Error("expected 'in' after for");
427   getNextToken(); // eat 'in'.
428
429   auto Body = ParseExpression();
430   if (!Body)
431     return nullptr;
432
433   return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
434                                        std::move(Step), std::move(Body));
435 }
436
437 /// varexpr ::= 'var' identifier ('=' expression)?
438 //                    (',' identifier ('=' expression)?)* 'in' expression
439 static std::unique_ptr<ExprAST> ParseVarExpr() {
440   getNextToken(); // eat the var.
441
442   std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
443
444   // At least one variable name is required.
445   if (CurTok != tok_identifier)
446     return Error("expected identifier after var");
447
448   while (1) {
449     std::string Name = IdentifierStr;
450     getNextToken(); // eat identifier.
451
452     // Read the optional initializer.
453     std::unique_ptr<ExprAST> Init = nullptr;
454     if (CurTok == '=') {
455       getNextToken(); // eat the '='.
456
457       Init = ParseExpression();
458       if (!Init)
459         return nullptr;
460     }
461
462     VarNames.push_back(std::make_pair(Name, std::move(Init)));
463
464     // End of var list, exit loop.
465     if (CurTok != ',')
466       break;
467     getNextToken(); // eat the ','.
468
469     if (CurTok != tok_identifier)
470       return Error("expected identifier list after var");
471   }
472
473   // At this point, we have to have 'in'.
474   if (CurTok != tok_in)
475     return Error("expected 'in' keyword after 'var'");
476   getNextToken(); // eat 'in'.
477
478   auto Body = ParseExpression();
479   if (!Body)
480     return nullptr;
481
482   return llvm::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
483 }
484
485 /// primary
486 ///   ::= identifierexpr
487 ///   ::= numberexpr
488 ///   ::= parenexpr
489 ///   ::= ifexpr
490 ///   ::= forexpr
491 ///   ::= varexpr
492 static std::unique_ptr<ExprAST> ParsePrimary() {
493   switch (CurTok) {
494   default:
495     return Error("unknown token when expecting an expression");
496   case tok_identifier:
497     return ParseIdentifierExpr();
498   case tok_number:
499     return ParseNumberExpr();
500   case '(':
501     return ParseParenExpr();
502   case tok_if:
503     return ParseIfExpr();
504   case tok_for:
505     return ParseForExpr();
506   case tok_var:
507     return ParseVarExpr();
508   }
509 }
510
511 /// unary
512 ///   ::= primary
513 ///   ::= '!' unary
514 static std::unique_ptr<ExprAST> ParseUnary() {
515   // If the current token is not an operator, it must be a primary expr.
516   if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
517     return ParsePrimary();
518
519   // If this is a unary operator, read it.
520   int Opc = CurTok;
521   getNextToken();
522   if (auto Operand = ParseUnary())
523     return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
524   return nullptr;
525 }
526
527 /// binoprhs
528 ///   ::= ('+' unary)*
529 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
530                                               std::unique_ptr<ExprAST> LHS) {
531   // If this is a binop, find its precedence.
532   while (1) {
533     int TokPrec = GetTokPrecedence();
534
535     // If this is a binop that binds at least as tightly as the current binop,
536     // consume it, otherwise we are done.
537     if (TokPrec < ExprPrec)
538       return LHS;
539
540     // Okay, we know this is a binop.
541     int BinOp = CurTok;
542     getNextToken(); // eat binop
543
544     // Parse the unary expression after the binary operator.
545     auto RHS = ParseUnary();
546     if (!RHS)
547       return nullptr;
548
549     // If BinOp binds less tightly with RHS than the operator after RHS, let
550     // the pending operator take RHS as its LHS.
551     int NextPrec = GetTokPrecedence();
552     if (TokPrec < NextPrec) {
553       RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
554       if (!RHS)
555         return nullptr;
556     }
557
558     // Merge LHS/RHS.
559     LHS =
560         llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
561   }
562 }
563
564 /// expression
565 ///   ::= unary binoprhs
566 ///
567 static std::unique_ptr<ExprAST> ParseExpression() {
568   auto LHS = ParseUnary();
569   if (!LHS)
570     return nullptr;
571
572   return ParseBinOpRHS(0, std::move(LHS));
573 }
574
575 /// prototype
576 ///   ::= id '(' id* ')'
577 ///   ::= binary LETTER number? (id, id)
578 ///   ::= unary LETTER (id)
579 static std::unique_ptr<PrototypeAST> ParsePrototype() {
580   std::string FnName;
581
582   unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
583   unsigned BinaryPrecedence = 30;
584
585   switch (CurTok) {
586   default:
587     return ErrorP("Expected function name in prototype");
588   case tok_identifier:
589     FnName = IdentifierStr;
590     Kind = 0;
591     getNextToken();
592     break;
593   case tok_unary:
594     getNextToken();
595     if (!isascii(CurTok))
596       return ErrorP("Expected unary operator");
597     FnName = "unary";
598     FnName += (char)CurTok;
599     Kind = 1;
600     getNextToken();
601     break;
602   case tok_binary:
603     getNextToken();
604     if (!isascii(CurTok))
605       return ErrorP("Expected binary operator");
606     FnName = "binary";
607     FnName += (char)CurTok;
608     Kind = 2;
609     getNextToken();
610
611     // Read the precedence if present.
612     if (CurTok == tok_number) {
613       if (NumVal < 1 || NumVal > 100)
614         return ErrorP("Invalid precedecnce: must be 1..100");
615       BinaryPrecedence = (unsigned)NumVal;
616       getNextToken();
617     }
618     break;
619   }
620
621   if (CurTok != '(')
622     return ErrorP("Expected '(' in prototype");
623
624   std::vector<std::string> ArgNames;
625   while (getNextToken() == tok_identifier)
626     ArgNames.push_back(IdentifierStr);
627   if (CurTok != ')')
628     return ErrorP("Expected ')' in prototype");
629
630   // success.
631   getNextToken(); // eat ')'.
632
633   // Verify right number of names for operator.
634   if (Kind && ArgNames.size() != Kind)
635     return ErrorP("Invalid number of operands for operator");
636
637   return llvm::make_unique<PrototypeAST>(FnName, ArgNames, Kind != 0,
638                                          BinaryPrecedence);
639 }
640
641 /// definition ::= 'def' prototype expression
642 static std::unique_ptr<FunctionAST> ParseDefinition() {
643   getNextToken(); // eat def.
644   auto Proto = ParsePrototype();
645   if (!Proto)
646     return nullptr;
647
648   if (auto E = ParseExpression())
649     return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
650   return nullptr;
651 }
652
653 /// toplevelexpr ::= expression
654 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
655   if (auto E = ParseExpression()) {
656     // Make an anonymous proto.
657     auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
658                                                  std::vector<std::string>());
659     return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
660   }
661   return nullptr;
662 }
663
664 /// external ::= 'extern' prototype
665 static std::unique_ptr<PrototypeAST> ParseExtern() {
666   getNextToken(); // eat extern.
667   return ParsePrototype();
668 }
669
670 //===----------------------------------------------------------------------===//
671 // Code Generation
672 //===----------------------------------------------------------------------===//
673
674 static std::unique_ptr<Module> TheModule;
675 static IRBuilder<> Builder(getGlobalContext());
676 static std::map<std::string, AllocaInst *> NamedValues;
677 static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
678 static std::unique_ptr<KaleidoscopeJIT> TheJIT;
679 static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
680
681 Value *ErrorV(const char *Str) {
682   Error(Str);
683   return nullptr;
684 }
685
686 Function *getFunction(std::string Name) {
687   // First, see if the function has already been added to the current module.
688   if (auto *F = TheModule->getFunction(Name))
689     return F;
690
691   // If not, check whether we can codegen the declaration from some existing
692   // prototype.
693   auto FI = FunctionProtos.find(Name);
694   if (FI != FunctionProtos.end())
695     return FI->second->codegen();
696
697   // If no existing prototype exists, return null.
698   return nullptr;
699 }
700
701 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
702 /// the function.  This is used for mutable variables etc.
703 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
704                                           const std::string &VarName) {
705   IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
706                    TheFunction->getEntryBlock().begin());
707   return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
708                            VarName.c_str());
709 }
710
711 Value *NumberExprAST::codegen() {
712   return ConstantFP::get(getGlobalContext(), APFloat(Val));
713 }
714
715 Value *VariableExprAST::codegen() {
716   // Look this variable up in the function.
717   Value *V = NamedValues[Name];
718   if (!V)
719     return ErrorV("Unknown variable name");
720
721   // Load the value.
722   return Builder.CreateLoad(V, Name.c_str());
723 }
724
725 Value *UnaryExprAST::codegen() {
726   Value *OperandV = Operand->codegen();
727   if (!OperandV)
728     return nullptr;
729
730   Function *F = getFunction(std::string("unary") + Opcode);
731   if (!F)
732     return ErrorV("Unknown unary operator");
733
734   return Builder.CreateCall(F, OperandV, "unop");
735 }
736
737 Value *BinaryExprAST::codegen() {
738   // Special case '=' because we don't want to emit the LHS as an expression.
739   if (Op == '=') {
740     // Assignment requires the LHS to be an identifier.
741     // This assume we're building without RTTI because LLVM builds that way by
742     // default.  If you build LLVM with RTTI this can be changed to a
743     // dynamic_cast for automatic error checking.
744     VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS.get());
745     if (!LHSE)
746       return ErrorV("destination of '=' must be a variable");
747     // Codegen the RHS.
748     Value *Val = RHS->codegen();
749     if (!Val)
750       return nullptr;
751
752     // Look up the name.
753     Value *Variable = NamedValues[LHSE->getName()];
754     if (!Variable)
755       return ErrorV("Unknown variable name");
756
757     Builder.CreateStore(Val, Variable);
758     return Val;
759   }
760
761   Value *L = LHS->codegen();
762   Value *R = RHS->codegen();
763   if (!L || !R)
764     return nullptr;
765
766   switch (Op) {
767   case '+':
768     return Builder.CreateFAdd(L, R, "addtmp");
769   case '-':
770     return Builder.CreateFSub(L, R, "subtmp");
771   case '*':
772     return Builder.CreateFMul(L, R, "multmp");
773   case '<':
774     L = Builder.CreateFCmpULT(L, R, "cmptmp");
775     // Convert bool 0/1 to double 0.0 or 1.0
776     return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
777                                 "booltmp");
778   default:
779     break;
780   }
781
782   // If it wasn't a builtin binary operator, it must be a user defined one. Emit
783   // a call to it.
784   Function *F = getFunction(std::string("binary") + Op);
785   assert(F && "binary operator not found!");
786
787   Value *Ops[] = {L, R};
788   return Builder.CreateCall(F, Ops, "binop");
789 }
790
791 Value *CallExprAST::codegen() {
792   // Look up the name in the global module table.
793   Function *CalleeF = getFunction(Callee);
794   if (!CalleeF)
795     return ErrorV("Unknown function referenced");
796
797   // If argument mismatch error.
798   if (CalleeF->arg_size() != Args.size())
799     return ErrorV("Incorrect # arguments passed");
800
801   std::vector<Value *> ArgsV;
802   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
803     ArgsV.push_back(Args[i]->codegen());
804     if (!ArgsV.back())
805       return nullptr;
806   }
807
808   return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
809 }
810
811 Value *IfExprAST::codegen() {
812   Value *CondV = Cond->codegen();
813   if (!CondV)
814     return nullptr;
815
816   // Convert condition to a bool by comparing equal to 0.0.
817   CondV = Builder.CreateFCmpONE(
818       CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
819
820   Function *TheFunction = Builder.GetInsertBlock()->getParent();
821
822   // Create blocks for the then and else cases.  Insert the 'then' block at the
823   // end of the function.
824   BasicBlock *ThenBB =
825       BasicBlock::Create(getGlobalContext(), "then", TheFunction);
826   BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
827   BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
828
829   Builder.CreateCondBr(CondV, ThenBB, ElseBB);
830
831   // Emit then value.
832   Builder.SetInsertPoint(ThenBB);
833
834   Value *ThenV = Then->codegen();
835   if (!ThenV)
836     return nullptr;
837
838   Builder.CreateBr(MergeBB);
839   // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
840   ThenBB = Builder.GetInsertBlock();
841
842   // Emit else block.
843   TheFunction->getBasicBlockList().push_back(ElseBB);
844   Builder.SetInsertPoint(ElseBB);
845
846   Value *ElseV = Else->codegen();
847   if (!ElseV)
848     return nullptr;
849
850   Builder.CreateBr(MergeBB);
851   // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
852   ElseBB = Builder.GetInsertBlock();
853
854   // Emit merge block.
855   TheFunction->getBasicBlockList().push_back(MergeBB);
856   Builder.SetInsertPoint(MergeBB);
857   PHINode *PN =
858       Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
859
860   PN->addIncoming(ThenV, ThenBB);
861   PN->addIncoming(ElseV, ElseBB);
862   return PN;
863 }
864
865 // Output for-loop as:
866 //   var = alloca double
867 //   ...
868 //   start = startexpr
869 //   store start -> var
870 //   goto loop
871 // loop:
872 //   ...
873 //   bodyexpr
874 //   ...
875 // loopend:
876 //   step = stepexpr
877 //   endcond = endexpr
878 //
879 //   curvar = load var
880 //   nextvar = curvar + step
881 //   store nextvar -> var
882 //   br endcond, loop, endloop
883 // outloop:
884 Value *ForExprAST::codegen() {
885   Function *TheFunction = Builder.GetInsertBlock()->getParent();
886
887   // Create an alloca for the variable in the entry block.
888   AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
889
890   // Emit the start code first, without 'variable' in scope.
891   Value *StartVal = Start->codegen();
892   if (!StartVal)
893     return nullptr;
894
895   // Store the value into the alloca.
896   Builder.CreateStore(StartVal, Alloca);
897
898   // Make the new basic block for the loop header, inserting after current
899   // block.
900   BasicBlock *LoopBB =
901       BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
902
903   // Insert an explicit fall through from the current block to the LoopBB.
904   Builder.CreateBr(LoopBB);
905
906   // Start insertion in LoopBB.
907   Builder.SetInsertPoint(LoopBB);
908
909   // Within the loop, the variable is defined equal to the PHI node.  If it
910   // shadows an existing variable, we have to restore it, so save it now.
911   AllocaInst *OldVal = NamedValues[VarName];
912   NamedValues[VarName] = Alloca;
913
914   // Emit the body of the loop.  This, like any other expr, can change the
915   // current BB.  Note that we ignore the value computed by the body, but don't
916   // allow an error.
917   if (!Body->codegen())
918     return nullptr;
919
920   // Emit the step value.
921   Value *StepVal = nullptr;
922   if (Step) {
923     StepVal = Step->codegen();
924     if (!StepVal)
925       return nullptr;
926   } else {
927     // If not specified, use 1.0.
928     StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
929   }
930
931   // Compute the end condition.
932   Value *EndCond = End->codegen();
933   if (!EndCond)
934     return nullptr;
935
936   // Reload, increment, and restore the alloca.  This handles the case where
937   // the body of the loop mutates the variable.
938   Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
939   Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
940   Builder.CreateStore(NextVar, Alloca);
941
942   // Convert condition to a bool by comparing equal to 0.0.
943   EndCond = Builder.CreateFCmpONE(
944       EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
945
946   // Create the "after loop" block and insert it.
947   BasicBlock *AfterBB =
948       BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
949
950   // Insert the conditional branch into the end of LoopEndBB.
951   Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
952
953   // Any new code will be inserted in AfterBB.
954   Builder.SetInsertPoint(AfterBB);
955
956   // Restore the unshadowed variable.
957   if (OldVal)
958     NamedValues[VarName] = OldVal;
959   else
960     NamedValues.erase(VarName);
961
962   // for expr always returns 0.0.
963   return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
964 }
965
966 Value *VarExprAST::codegen() {
967   std::vector<AllocaInst *> OldBindings;
968
969   Function *TheFunction = Builder.GetInsertBlock()->getParent();
970
971   // Register all variables and emit their initializer.
972   for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
973     const std::string &VarName = VarNames[i].first;
974     ExprAST *Init = VarNames[i].second.get();
975
976     // Emit the initializer before adding the variable to scope, this prevents
977     // the initializer from referencing the variable itself, and permits stuff
978     // like this:
979     //  var a = 1 in
980     //    var a = a in ...   # refers to outer 'a'.
981     Value *InitVal;
982     if (Init) {
983       InitVal = Init->codegen();
984       if (!InitVal)
985         return nullptr;
986     } else { // If not specified, use 0.0.
987       InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
988     }
989
990     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
991     Builder.CreateStore(InitVal, Alloca);
992
993     // Remember the old variable binding so that we can restore the binding when
994     // we unrecurse.
995     OldBindings.push_back(NamedValues[VarName]);
996
997     // Remember this binding.
998     NamedValues[VarName] = Alloca;
999   }
1000
1001   // Codegen the body, now that all vars are in scope.
1002   Value *BodyVal = Body->codegen();
1003   if (!BodyVal)
1004     return nullptr;
1005
1006   // Pop all our variables from scope.
1007   for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1008     NamedValues[VarNames[i].first] = OldBindings[i];
1009
1010   // Return the body computation.
1011   return BodyVal;
1012 }
1013
1014 Function *PrototypeAST::codegen() {
1015   // Make the function type:  double(double,double) etc.
1016   std::vector<Type *> Doubles(Args.size(),
1017                               Type::getDoubleTy(getGlobalContext()));
1018   FunctionType *FT =
1019       FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
1020
1021   Function *F =
1022       Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
1023
1024   // Set names for all arguments.
1025   unsigned Idx = 0;
1026   for (auto &Arg : F->args())
1027     Arg.setName(Args[Idx++]);
1028
1029   return F;
1030 }
1031
1032 Function *FunctionAST::codegen() {
1033   // Transfer ownership of the prototype to the FunctionProtos map, but keep a
1034   // reference to it for use below.
1035   auto &P = *Proto;
1036   FunctionProtos[Proto->getName()] = std::move(Proto);
1037   Function *TheFunction = getFunction(P.getName());
1038   if (!TheFunction)
1039     return nullptr;
1040
1041   // If this is an operator, install it.
1042   if (P.isBinaryOp())
1043     BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
1044
1045   // Create a new basic block to start insertion into.
1046   BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1047   Builder.SetInsertPoint(BB);
1048
1049   // Record the function arguments in the NamedValues map.
1050   NamedValues.clear();
1051   for (auto &Arg : TheFunction->args()) {
1052     // Create an alloca for this variable.
1053     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName());
1054
1055     // Store the initial value into the alloca.
1056     Builder.CreateStore(&Arg, Alloca);
1057
1058     // Add arguments to variable symbol table.
1059     NamedValues[Arg.getName()] = Alloca;
1060   }
1061
1062   if (Value *RetVal = Body->codegen()) {
1063     // Finish off the function.
1064     Builder.CreateRet(RetVal);
1065
1066     // Validate the generated code, checking for consistency.
1067     verifyFunction(*TheFunction);
1068
1069     // Run the optimizer on the function.
1070     TheFPM->run(*TheFunction);
1071
1072     return TheFunction;
1073   }
1074
1075   // Error reading body, remove function.
1076   TheFunction->eraseFromParent();
1077
1078   if (P.isBinaryOp())
1079     BinopPrecedence.erase(Proto->getOperatorName());
1080   return nullptr;
1081 }
1082
1083 //===----------------------------------------------------------------------===//
1084 // Top-Level parsing and JIT Driver
1085 //===----------------------------------------------------------------------===//
1086
1087 static void InitializeModuleAndPassManager() {
1088   // Open a new module.
1089   TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
1090   TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
1091
1092   // Create a new pass manager attached to it.
1093   TheFPM = llvm::make_unique<legacy::FunctionPassManager>(TheModule.get());
1094
1095   // Provide basic AliasAnalysis support for GVN.
1096   TheFPM->add(createBasicAliasAnalysisPass());
1097   // Do simple "peephole" optimizations and bit-twiddling optzns.
1098   TheFPM->add(createInstructionCombiningPass());
1099   // Reassociate expressions.
1100   TheFPM->add(createReassociatePass());
1101   // Eliminate Common SubExpressions.
1102   TheFPM->add(createGVNPass());
1103   // Simplify the control flow graph (deleting unreachable blocks, etc).
1104   TheFPM->add(createCFGSimplificationPass());
1105
1106   TheFPM->doInitialization();
1107 }
1108
1109 static void HandleDefinition() {
1110   if (auto FnAST = ParseDefinition()) {
1111     if (auto *FnIR = FnAST->codegen()) {
1112       fprintf(stderr, "Read function definition:");
1113       FnIR->dump();
1114       TheJIT->addModule(std::move(TheModule));
1115       InitializeModuleAndPassManager();
1116     }
1117   } else {
1118     // Skip token for error recovery.
1119     getNextToken();
1120   }
1121 }
1122
1123 static void HandleExtern() {
1124   if (auto ProtoAST = ParseExtern()) {
1125     if (auto *FnIR = ProtoAST->codegen()) {
1126       fprintf(stderr, "Read extern: ");
1127       FnIR->dump();
1128       FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
1129     }
1130   } else {
1131     // Skip token for error recovery.
1132     getNextToken();
1133   }
1134 }
1135
1136 static void HandleTopLevelExpression() {
1137   // Evaluate a top-level expression into an anonymous function.
1138   if (auto FnAST = ParseTopLevelExpr()) {
1139     if (FnAST->codegen()) {
1140
1141       // JIT the module containing the anonymous expression, keeping a handle so
1142       // we can free it later.
1143       auto H = TheJIT->addModule(std::move(TheModule));
1144       InitializeModuleAndPassManager();
1145
1146       // Search the JIT for the __anon_expr symbol.
1147       auto ExprSymbol = TheJIT->findSymbol("__anon_expr");
1148       assert(ExprSymbol && "Function not found");
1149
1150       // Get the symbol's address and cast it to the right type (takes no
1151       // arguments, returns a double) so we can call it as a native function.
1152       double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
1153       fprintf(stderr, "Evaluated to %f\n", FP());
1154
1155       // Delete the anonymous expression module from the JIT.
1156       TheJIT->removeModule(H);
1157     }
1158   } else {
1159     // Skip token for error recovery.
1160     getNextToken();
1161   }
1162 }
1163
1164 /// top ::= definition | external | expression | ';'
1165 static void MainLoop() {
1166   while (1) {
1167     fprintf(stderr, "ready> ");
1168     switch (CurTok) {
1169     case tok_eof:
1170       return;
1171     case ';': // ignore top-level semicolons.
1172       getNextToken();
1173       break;
1174     case tok_def:
1175       HandleDefinition();
1176       break;
1177     case tok_extern:
1178       HandleExtern();
1179       break;
1180     default:
1181       HandleTopLevelExpression();
1182       break;
1183     }
1184   }
1185 }
1186
1187 //===----------------------------------------------------------------------===//
1188 // "Library" functions that can be "extern'd" from user code.
1189 //===----------------------------------------------------------------------===//
1190
1191 /// putchard - putchar that takes a double and returns 0.
1192 extern "C" double putchard(double X) {
1193   fputc((char)X, stderr);
1194   return 0;
1195 }
1196
1197 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1198 extern "C" double printd(double X) {
1199   fprintf(stderr, "%f\n", X);
1200   return 0;
1201 }
1202
1203 //===----------------------------------------------------------------------===//
1204 // Main driver code.
1205 //===----------------------------------------------------------------------===//
1206
1207 int main() {
1208   InitializeNativeTarget();
1209   InitializeNativeTargetAsmPrinter();
1210   InitializeNativeTargetAsmParser();
1211
1212   // Install standard binary operators.
1213   // 1 is lowest precedence.
1214   BinopPrecedence['='] = 2;
1215   BinopPrecedence['<'] = 10;
1216   BinopPrecedence['+'] = 20;
1217   BinopPrecedence['-'] = 20;
1218   BinopPrecedence['*'] = 40; // highest.
1219
1220   // Prime the first token.
1221   fprintf(stderr, "ready> ");
1222   getNextToken();
1223
1224   TheJIT = llvm::make_unique<KaleidoscopeJIT>();
1225
1226   InitializeModuleAndPassManager();
1227
1228   // Run the main "interpreter loop" now.
1229   MainLoop();
1230
1231   return 0;
1232 }