blob: eeca4775eeb11698617b88fa8b2275dee9b1cdb7 [file] [log] [blame]
NAKAMURA Takumi85c9bac2015-03-02 01:04:34 +00001#include "llvm/ADT/STLExtras.h"
Chandler Carruth605e30e2012-12-04 10:16:57 +00002#include "llvm/Analysis/Passes.h"
Chandler Carruth005f27a2013-01-02 11:56:33 +00003#include "llvm/IR/IRBuilder.h"
4#include "llvm/IR/LLVMContext.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +00005#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth005f27a2013-01-02 11:56:33 +00006#include "llvm/IR/Module.h"
Chandler Carruth20d4e6b2014-01-13 09:58:03 +00007#include "llvm/IR/Verifier.h"
Evan Cheng2bb40352011-08-24 18:08:43 +00008#include "llvm/Support/TargetSelect.h"
Chandler Carruth605e30e2012-12-04 10:16:57 +00009#include "llvm/Transforms/Scalar.h"
Will Dietz981af002013-10-12 00:55:57 +000010#include <cctype>
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000011#include <cstdio>
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000012#include <map>
Chandler Carruth605e30e2012-12-04 10:16:57 +000013#include <string>
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000014#include <vector>
Lang Hames2d789c32015-08-26 03:07:41 +000015#include "../include/KaleidoscopeJIT.h"
16
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000017using namespace llvm;
Lang Hames2d789c32015-08-26 03:07:41 +000018using namespace llvm::orc;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000019
20//===----------------------------------------------------------------------===//
21// Lexer
22//===----------------------------------------------------------------------===//
23
24// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
25// of these for known things.
26enum Token {
27 tok_eof = -1,
28
29 // commands
Eric Christopherc0239362014-12-08 18:12:28 +000030 tok_def = -2,
31 tok_extern = -3,
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000032
33 // primary
Eric Christopherc0239362014-12-08 18:12:28 +000034 tok_identifier = -4,
35 tok_number = -5,
36
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000037 // control
Eric Christopherc0239362014-12-08 18:12:28 +000038 tok_if = -6,
39 tok_then = -7,
40 tok_else = -8,
41 tok_for = -9,
42 tok_in = -10
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000043};
44
Eric Christopherc0239362014-12-08 18:12:28 +000045static std::string IdentifierStr; // Filled in if tok_identifier
46static double NumVal; // Filled in if tok_number
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000047
48/// gettok - Return the next token from standard input.
49static int gettok() {
50 static int LastChar = ' ';
51
52 // Skip any whitespace.
53 while (isspace(LastChar))
54 LastChar = getchar();
55
56 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
57 IdentifierStr = LastChar;
58 while (isalnum((LastChar = getchar())))
59 IdentifierStr += LastChar;
60
Eric Christopherc0239362014-12-08 18:12:28 +000061 if (IdentifierStr == "def")
62 return tok_def;
63 if (IdentifierStr == "extern")
64 return tok_extern;
65 if (IdentifierStr == "if")
66 return tok_if;
67 if (IdentifierStr == "then")
68 return tok_then;
69 if (IdentifierStr == "else")
70 return tok_else;
71 if (IdentifierStr == "for")
72 return tok_for;
73 if (IdentifierStr == "in")
74 return tok_in;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000075 return tok_identifier;
76 }
77
Eric Christopherc0239362014-12-08 18:12:28 +000078 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000079 std::string NumStr;
80 do {
81 NumStr += LastChar;
82 LastChar = getchar();
83 } while (isdigit(LastChar) || LastChar == '.');
84
Hans Wennborgcc9deb42015-09-29 18:02:48 +000085 NumVal = strtod(NumStr.c_str(), nullptr);
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000086 return tok_number;
87 }
88
89 if (LastChar == '#') {
90 // Comment until end of line.
Eric Christopherc0239362014-12-08 18:12:28 +000091 do
92 LastChar = getchar();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000093 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
Eric Christopherc0239362014-12-08 18:12:28 +000094
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000095 if (LastChar != EOF)
96 return gettok();
97 }
Eric Christopherc0239362014-12-08 18:12:28 +000098
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000099 // Check for end of file. Don't eat the EOF.
100 if (LastChar == EOF)
101 return tok_eof;
102
103 // Otherwise, just return the character as its ascii value.
104 int ThisChar = LastChar;
105 LastChar = getchar();
106 return ThisChar;
107}
108
109//===----------------------------------------------------------------------===//
110// Abstract Syntax Tree (aka Parse Tree)
111//===----------------------------------------------------------------------===//
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000112namespace {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000113/// ExprAST - Base class for all expression nodes.
114class ExprAST {
115public:
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000116 virtual ~ExprAST() {}
Lang Hames2d789c32015-08-26 03:07:41 +0000117 virtual Value *codegen() = 0;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000118};
119
120/// NumberExprAST - Expression class for numeric literals like "1.0".
121class NumberExprAST : public ExprAST {
122 double Val;
Lang Hames59b0da82015-08-19 18:15:58 +0000123
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000124public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000125 NumberExprAST(double Val) : Val(Val) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000126 Value *codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000127};
128
129/// VariableExprAST - Expression class for referencing a variable, like "a".
130class VariableExprAST : public ExprAST {
131 std::string Name;
Lang Hames59b0da82015-08-19 18:15:58 +0000132
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000133public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000134 VariableExprAST(const std::string &Name) : Name(Name) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000135 Value *codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000136};
137
138/// BinaryExprAST - Expression class for a binary operator.
139class BinaryExprAST : public ExprAST {
140 char Op;
Lang Hames09bf4c12015-08-18 18:11:06 +0000141 std::unique_ptr<ExprAST> LHS, RHS;
Lang Hames59b0da82015-08-19 18:15:58 +0000142
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000143public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000144 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
145 std::unique_ptr<ExprAST> RHS)
146 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000147 Value *codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000148};
149
150/// CallExprAST - Expression class for function calls.
151class CallExprAST : public ExprAST {
152 std::string Callee;
Lang Hames09bf4c12015-08-18 18:11:06 +0000153 std::vector<std::unique_ptr<ExprAST>> Args;
Lang Hames59b0da82015-08-19 18:15:58 +0000154
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000155public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000156 CallExprAST(const std::string &Callee,
157 std::vector<std::unique_ptr<ExprAST>> Args)
158 : Callee(Callee), Args(std::move(Args)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000159 Value *codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000160};
161
162/// IfExprAST - Expression class for if/then/else.
163class IfExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000164 std::unique_ptr<ExprAST> Cond, Then, Else;
Lang Hames59b0da82015-08-19 18:15:58 +0000165
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000166public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000167 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
168 std::unique_ptr<ExprAST> Else)
169 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000170 Value *codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000171};
172
173/// ForExprAST - Expression class for for/in.
174class ForExprAST : public ExprAST {
175 std::string VarName;
Lang Hames09bf4c12015-08-18 18:11:06 +0000176 std::unique_ptr<ExprAST> Start, End, Step, Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000177
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000178public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000179 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
180 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
181 std::unique_ptr<ExprAST> Body)
182 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
183 Step(std::move(Step)), Body(std::move(Body)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000184 Value *codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000185};
186
187/// PrototypeAST - This class represents the "prototype" for a function,
188/// which captures its name, and its argument names (thus implicitly the number
189/// of arguments the function takes).
190class PrototypeAST {
191 std::string Name;
192 std::vector<std::string> Args;
Lang Hames59b0da82015-08-19 18:15:58 +0000193
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000194public:
Lang Hames59b0da82015-08-19 18:15:58 +0000195 PrototypeAST(const std::string &Name, std::vector<std::string> Args)
196 : Name(Name), Args(std::move(Args)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000197 Function *codegen();
198 const std::string &getName() const { return Name; }
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000199};
200
201/// FunctionAST - This class represents a function definition itself.
202class FunctionAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000203 std::unique_ptr<PrototypeAST> Proto;
204 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000205
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000206public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000207 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
208 std::unique_ptr<ExprAST> Body)
Lang Hames59b0da82015-08-19 18:15:58 +0000209 : Proto(std::move(Proto)), Body(std::move(Body)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000210 Function *codegen();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000211};
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000212} // end anonymous namespace
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000213
214//===----------------------------------------------------------------------===//
215// Parser
216//===----------------------------------------------------------------------===//
217
218/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
219/// token the parser is looking at. getNextToken reads another token from the
220/// lexer and updates CurTok with its results.
221static int CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000222static int getNextToken() { return CurTok = gettok(); }
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000223
224/// BinopPrecedence - This holds the precedence for each binary operator that is
225/// defined.
226static std::map<char, int> BinopPrecedence;
227
228/// GetTokPrecedence - Get the precedence of the pending binary operator token.
229static int GetTokPrecedence() {
230 if (!isascii(CurTok))
231 return -1;
Eric Christopherc0239362014-12-08 18:12:28 +0000232
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000233 // Make sure it's a declared binop.
234 int TokPrec = BinopPrecedence[CurTok];
Eric Christopherc0239362014-12-08 18:12:28 +0000235 if (TokPrec <= 0)
236 return -1;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000237 return TokPrec;
238}
239
240/// Error* - These are little helper functions for error handling.
Lang Hames09bf4c12015-08-18 18:11:06 +0000241std::unique_ptr<ExprAST> Error(const char *Str) {
Eric Christopherc0239362014-12-08 18:12:28 +0000242 fprintf(stderr, "Error: %s\n", Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000243 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000244}
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000245
Lang Hames09bf4c12015-08-18 18:11:06 +0000246std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
Eric Christopherc0239362014-12-08 18:12:28 +0000247 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000248 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000249}
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000250
Lang Hames09bf4c12015-08-18 18:11:06 +0000251static std::unique_ptr<ExprAST> ParseExpression();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000252
Lang Hames59b0da82015-08-19 18:15:58 +0000253/// numberexpr ::= number
254static std::unique_ptr<ExprAST> ParseNumberExpr() {
255 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
256 getNextToken(); // consume the number
257 return std::move(Result);
258}
259
260/// parenexpr ::= '(' expression ')'
261static std::unique_ptr<ExprAST> ParseParenExpr() {
262 getNextToken(); // eat (.
263 auto V = ParseExpression();
264 if (!V)
265 return nullptr;
266
267 if (CurTok != ')')
268 return Error("expected ')'");
269 getNextToken(); // eat ).
270 return V;
271}
272
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000273/// identifierexpr
274/// ::= identifier
275/// ::= identifier '(' expression* ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000276static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000277 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000278
279 getNextToken(); // eat identifier.
280
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000281 if (CurTok != '(') // Simple variable ref.
Lang Hames09bf4c12015-08-18 18:11:06 +0000282 return llvm::make_unique<VariableExprAST>(IdName);
Eric Christopherc0239362014-12-08 18:12:28 +0000283
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000284 // Call.
Eric Christopherc0239362014-12-08 18:12:28 +0000285 getNextToken(); // eat (
Lang Hames09bf4c12015-08-18 18:11:06 +0000286 std::vector<std::unique_ptr<ExprAST>> Args;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000287 if (CurTok != ')') {
288 while (1) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000289 if (auto Arg = ParseExpression())
290 Args.push_back(std::move(Arg));
291 else
292 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000293
Eric Christopherc0239362014-12-08 18:12:28 +0000294 if (CurTok == ')')
295 break;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000296
297 if (CurTok != ',')
298 return Error("Expected ')' or ',' in argument list");
299 getNextToken();
300 }
301 }
302
303 // Eat the ')'.
304 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000305
Lang Hames09bf4c12015-08-18 18:11:06 +0000306 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000307}
308
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000309/// ifexpr ::= 'if' expression 'then' expression 'else' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000310static std::unique_ptr<ExprAST> ParseIfExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000311 getNextToken(); // eat the if.
312
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000313 // condition.
Lang Hames09bf4c12015-08-18 18:11:06 +0000314 auto Cond = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000315 if (!Cond)
Lang Hames09bf4c12015-08-18 18:11:06 +0000316 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000317
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000318 if (CurTok != tok_then)
319 return Error("expected then");
Eric Christopherc0239362014-12-08 18:12:28 +0000320 getNextToken(); // eat the then
321
Lang Hames09bf4c12015-08-18 18:11:06 +0000322 auto Then = ParseExpression();
323 if (!Then)
324 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000325
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000326 if (CurTok != tok_else)
327 return Error("expected else");
Eric Christopherc0239362014-12-08 18:12:28 +0000328
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000329 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000330
Lang Hames09bf4c12015-08-18 18:11:06 +0000331 auto Else = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000332 if (!Else)
Lang Hames09bf4c12015-08-18 18:11:06 +0000333 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000334
Lang Hames09bf4c12015-08-18 18:11:06 +0000335 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
336 std::move(Else));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000337}
338
339/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000340static std::unique_ptr<ExprAST> ParseForExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000341 getNextToken(); // eat the for.
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000342
343 if (CurTok != tok_identifier)
344 return Error("expected identifier after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000345
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000346 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000347 getNextToken(); // eat identifier.
348
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000349 if (CurTok != '=')
350 return Error("expected '=' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000351 getNextToken(); // eat '='.
352
Lang Hames09bf4c12015-08-18 18:11:06 +0000353 auto Start = ParseExpression();
354 if (!Start)
355 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000356 if (CurTok != ',')
357 return Error("expected ',' after for start value");
358 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000359
Lang Hames09bf4c12015-08-18 18:11:06 +0000360 auto End = ParseExpression();
361 if (!End)
362 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000363
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000364 // The step value is optional.
Lang Hames09bf4c12015-08-18 18:11:06 +0000365 std::unique_ptr<ExprAST> Step;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000366 if (CurTok == ',') {
367 getNextToken();
368 Step = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000369 if (!Step)
370 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000371 }
Eric Christopherc0239362014-12-08 18:12:28 +0000372
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000373 if (CurTok != tok_in)
374 return Error("expected 'in' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000375 getNextToken(); // eat 'in'.
376
Lang Hames09bf4c12015-08-18 18:11:06 +0000377 auto Body = ParseExpression();
378 if (!Body)
379 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000380
Lang Hames09bf4c12015-08-18 18:11:06 +0000381 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
382 std::move(Step), std::move(Body));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000383}
384
385/// primary
386/// ::= identifierexpr
387/// ::= numberexpr
388/// ::= parenexpr
389/// ::= ifexpr
390/// ::= forexpr
Lang Hames09bf4c12015-08-18 18:11:06 +0000391static std::unique_ptr<ExprAST> ParsePrimary() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000392 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +0000393 default:
394 return Error("unknown token when expecting an expression");
395 case tok_identifier:
396 return ParseIdentifierExpr();
397 case tok_number:
398 return ParseNumberExpr();
399 case '(':
400 return ParseParenExpr();
401 case tok_if:
402 return ParseIfExpr();
403 case tok_for:
404 return ParseForExpr();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000405 }
406}
407
408/// binoprhs
409/// ::= ('+' primary)*
Lang Hames09bf4c12015-08-18 18:11:06 +0000410static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
411 std::unique_ptr<ExprAST> LHS) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000412 // If this is a binop, find its precedence.
413 while (1) {
414 int TokPrec = GetTokPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +0000415
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000416 // If this is a binop that binds at least as tightly as the current binop,
417 // consume it, otherwise we are done.
418 if (TokPrec < ExprPrec)
419 return LHS;
Eric Christopherc0239362014-12-08 18:12:28 +0000420
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000421 // Okay, we know this is a binop.
422 int BinOp = CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000423 getNextToken(); // eat binop
424
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000425 // Parse the primary expression after the binary operator.
Lang Hames09bf4c12015-08-18 18:11:06 +0000426 auto RHS = ParsePrimary();
Eric Christopherc0239362014-12-08 18:12:28 +0000427 if (!RHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000428 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000429
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000430 // If BinOp binds less tightly with RHS than the operator after RHS, let
431 // the pending operator take RHS as its LHS.
432 int NextPrec = GetTokPrecedence();
433 if (TokPrec < NextPrec) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000434 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
435 if (!RHS)
436 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000437 }
Eric Christopherc0239362014-12-08 18:12:28 +0000438
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000439 // Merge LHS/RHS.
Lang Hames59b0da82015-08-19 18:15:58 +0000440 LHS =
441 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000442 }
443}
444
445/// expression
446/// ::= primary binoprhs
447///
Lang Hames09bf4c12015-08-18 18:11:06 +0000448static std::unique_ptr<ExprAST> ParseExpression() {
449 auto LHS = ParsePrimary();
Eric Christopherc0239362014-12-08 18:12:28 +0000450 if (!LHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000451 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000452
Lang Hames09bf4c12015-08-18 18:11:06 +0000453 return ParseBinOpRHS(0, std::move(LHS));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000454}
455
456/// prototype
457/// ::= id '(' id* ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000458static std::unique_ptr<PrototypeAST> ParsePrototype() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000459 if (CurTok != tok_identifier)
460 return ErrorP("Expected function name in prototype");
461
462 std::string FnName = IdentifierStr;
463 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000464
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000465 if (CurTok != '(')
466 return ErrorP("Expected '(' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000467
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000468 std::vector<std::string> ArgNames;
469 while (getNextToken() == tok_identifier)
470 ArgNames.push_back(IdentifierStr);
471 if (CurTok != ')')
472 return ErrorP("Expected ')' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000473
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000474 // success.
Eric Christopherc0239362014-12-08 18:12:28 +0000475 getNextToken(); // eat ')'.
476
Lang Hames09bf4c12015-08-18 18:11:06 +0000477 return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000478}
479
480/// definition ::= 'def' prototype expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000481static std::unique_ptr<FunctionAST> ParseDefinition() {
Eric Christopherc0239362014-12-08 18:12:28 +0000482 getNextToken(); // eat def.
Lang Hames09bf4c12015-08-18 18:11:06 +0000483 auto Proto = ParsePrototype();
484 if (!Proto)
485 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000486
Lang Hames09bf4c12015-08-18 18:11:06 +0000487 if (auto E = ParseExpression())
488 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
489 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000490}
491
492/// toplevelexpr ::= expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000493static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
494 if (auto E = ParseExpression()) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000495 // Make an anonymous proto.
Lang Hames2d789c32015-08-26 03:07:41 +0000496 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
497 std::vector<std::string>());
Lang Hames09bf4c12015-08-18 18:11:06 +0000498 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000499 }
Lang Hames09bf4c12015-08-18 18:11:06 +0000500 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000501}
502
503/// external ::= 'extern' prototype
Lang Hames09bf4c12015-08-18 18:11:06 +0000504static std::unique_ptr<PrototypeAST> ParseExtern() {
Eric Christopherc0239362014-12-08 18:12:28 +0000505 getNextToken(); // eat extern.
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000506 return ParsePrototype();
507}
508
509//===----------------------------------------------------------------------===//
510// Code Generation
511//===----------------------------------------------------------------------===//
512
Lang Hames2d789c32015-08-26 03:07:41 +0000513static std::unique_ptr<Module> TheModule;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000514static IRBuilder<> Builder(getGlobalContext());
Eric Christopherc0239362014-12-08 18:12:28 +0000515static std::map<std::string, Value *> NamedValues;
Lang Hames2d789c32015-08-26 03:07:41 +0000516static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
517static std::unique_ptr<KaleidoscopeJIT> TheJIT;
518static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000519
Eric Christopherc0239362014-12-08 18:12:28 +0000520Value *ErrorV(const char *Str) {
521 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000522 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000523}
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000524
Lang Hames2d789c32015-08-26 03:07:41 +0000525Function *getFunction(std::string Name) {
526 // First, see if the function has already been added to the current module.
527 if (auto *F = TheModule->getFunction(Name))
528 return F;
529
530 // If not, check whether we can codegen the declaration from some existing
531 // prototype.
532 auto FI = FunctionProtos.find(Name);
533 if (FI != FunctionProtos.end())
534 return FI->second->codegen();
535
536 // If no existing prototype exists, return null.
537 return nullptr;
538}
539
540Value *NumberExprAST::codegen() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000541 return ConstantFP::get(getGlobalContext(), APFloat(Val));
542}
543
Lang Hames2d789c32015-08-26 03:07:41 +0000544Value *VariableExprAST::codegen() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000545 // Look this variable up in the function.
546 Value *V = NamedValues[Name];
Lang Hames596aec92015-08-19 18:32:58 +0000547 if (!V)
548 return ErrorV("Unknown variable name");
549 return V;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000550}
551
Lang Hames2d789c32015-08-26 03:07:41 +0000552Value *BinaryExprAST::codegen() {
553 Value *L = LHS->codegen();
554 Value *R = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000555 if (!L || !R)
556 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000557
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000558 switch (Op) {
Eric Christopherc0239362014-12-08 18:12:28 +0000559 case '+':
560 return Builder.CreateFAdd(L, R, "addtmp");
561 case '-':
562 return Builder.CreateFSub(L, R, "subtmp");
563 case '*':
564 return Builder.CreateFMul(L, R, "multmp");
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000565 case '<':
566 L = Builder.CreateFCmpULT(L, R, "cmptmp");
567 // Convert bool 0/1 to double 0.0 or 1.0
568 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
569 "booltmp");
Eric Christopherc0239362014-12-08 18:12:28 +0000570 default:
571 return ErrorV("invalid binary operator");
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000572 }
573}
574
Lang Hames2d789c32015-08-26 03:07:41 +0000575Value *CallExprAST::codegen() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000576 // Look up the name in the global module table.
Lang Hames2d789c32015-08-26 03:07:41 +0000577 Function *CalleeF = getFunction(Callee);
Lang Hames09bf4c12015-08-18 18:11:06 +0000578 if (!CalleeF)
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000579 return ErrorV("Unknown function referenced");
Eric Christopherc0239362014-12-08 18:12:28 +0000580
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000581 // If argument mismatch error.
582 if (CalleeF->arg_size() != Args.size())
583 return ErrorV("Incorrect # arguments passed");
584
Eric Christopherc0239362014-12-08 18:12:28 +0000585 std::vector<Value *> ArgsV;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000586 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Lang Hames2d789c32015-08-26 03:07:41 +0000587 ArgsV.push_back(Args[i]->codegen());
Lang Hames09bf4c12015-08-18 18:11:06 +0000588 if (!ArgsV.back())
589 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000590 }
Eric Christopherc0239362014-12-08 18:12:28 +0000591
Francois Pichetc5d10502011-07-15 10:59:52 +0000592 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000593}
594
Lang Hames2d789c32015-08-26 03:07:41 +0000595Value *IfExprAST::codegen() {
596 Value *CondV = Cond->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000597 if (!CondV)
598 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000599
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000600 // Convert condition to a bool by comparing equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000601 CondV = Builder.CreateFCmpONE(
602 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
603
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000604 Function *TheFunction = Builder.GetInsertBlock()->getParent();
Eric Christopherc0239362014-12-08 18:12:28 +0000605
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000606 // Create blocks for the then and else cases. Insert the 'then' block at the
607 // end of the function.
Eric Christopherc0239362014-12-08 18:12:28 +0000608 BasicBlock *ThenBB =
609 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000610 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
611 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
Eric Christopherc0239362014-12-08 18:12:28 +0000612
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000613 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000614
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000615 // Emit then value.
616 Builder.SetInsertPoint(ThenBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000617
Lang Hames2d789c32015-08-26 03:07:41 +0000618 Value *ThenV = Then->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000619 if (!ThenV)
620 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000621
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000622 Builder.CreateBr(MergeBB);
623 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
624 ThenBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000625
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000626 // Emit else block.
627 TheFunction->getBasicBlockList().push_back(ElseBB);
628 Builder.SetInsertPoint(ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000629
Lang Hames2d789c32015-08-26 03:07:41 +0000630 Value *ElseV = Else->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000631 if (!ElseV)
632 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000633
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000634 Builder.CreateBr(MergeBB);
635 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
636 ElseBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000637
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000638 // Emit merge block.
639 TheFunction->getBasicBlockList().push_back(MergeBB);
640 Builder.SetInsertPoint(MergeBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000641 PHINode *PN =
642 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
643
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000644 PN->addIncoming(ThenV, ThenBB);
645 PN->addIncoming(ElseV, ElseBB);
646 return PN;
647}
648
Lang Hames59b0da82015-08-19 18:15:58 +0000649// Output for-loop as:
650// ...
651// start = startexpr
652// goto loop
653// loop:
654// variable = phi [start, loopheader], [nextvariable, loopend]
655// ...
656// bodyexpr
657// ...
658// loopend:
659// step = stepexpr
660// nextvariable = variable + step
661// endcond = endexpr
662// br endcond, loop, endloop
663// outloop:
Lang Hames2d789c32015-08-26 03:07:41 +0000664Value *ForExprAST::codegen() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000665 // Emit the start code first, without 'variable' in scope.
Lang Hames2d789c32015-08-26 03:07:41 +0000666 Value *StartVal = Start->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000667 if (!StartVal)
668 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000669
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000670 // Make the new basic block for the loop header, inserting after current
671 // block.
672 Function *TheFunction = Builder.GetInsertBlock()->getParent();
673 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000674 BasicBlock *LoopBB =
675 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
676
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000677 // Insert an explicit fall through from the current block to the LoopBB.
678 Builder.CreateBr(LoopBB);
679
680 // Start insertion in LoopBB.
681 Builder.SetInsertPoint(LoopBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000682
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000683 // Start the PHI node with an entry for Start.
Eric Christopherc0239362014-12-08 18:12:28 +0000684 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
685 2, VarName.c_str());
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000686 Variable->addIncoming(StartVal, PreheaderBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000687
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000688 // Within the loop, the variable is defined equal to the PHI node. If it
689 // shadows an existing variable, we have to restore it, so save it now.
690 Value *OldVal = NamedValues[VarName];
691 NamedValues[VarName] = Variable;
Eric Christopherc0239362014-12-08 18:12:28 +0000692
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000693 // Emit the body of the loop. This, like any other expr, can change the
694 // current BB. Note that we ignore the value computed by the body, but don't
695 // allow an error.
Lang Hames2d789c32015-08-26 03:07:41 +0000696 if (!Body->codegen())
Lang Hames09bf4c12015-08-18 18:11:06 +0000697 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000698
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000699 // Emit the step value.
Lang Hames59b0da82015-08-19 18:15:58 +0000700 Value *StepVal = nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000701 if (Step) {
Lang Hames2d789c32015-08-26 03:07:41 +0000702 StepVal = Step->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000703 if (!StepVal)
704 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000705 } else {
706 // If not specified, use 1.0.
707 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
708 }
Eric Christopherc0239362014-12-08 18:12:28 +0000709
Chris Lattner26d79502010-06-21 22:51:14 +0000710 Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000711
712 // Compute the end condition.
Lang Hames2d789c32015-08-26 03:07:41 +0000713 Value *EndCond = End->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000714 if (!EndCond)
Lang Hames59b0da82015-08-19 18:15:58 +0000715 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000716
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000717 // Convert condition to a bool by comparing equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000718 EndCond = Builder.CreateFCmpONE(
719 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
720
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000721 // Create the "after loop" block and insert it.
722 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000723 BasicBlock *AfterBB =
724 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
725
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000726 // Insert the conditional branch into the end of LoopEndBB.
727 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000728
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000729 // Any new code will be inserted in AfterBB.
730 Builder.SetInsertPoint(AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000731
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000732 // Add a new entry to the PHI node for the backedge.
733 Variable->addIncoming(NextVar, LoopEndBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000734
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000735 // Restore the unshadowed variable.
736 if (OldVal)
737 NamedValues[VarName] = OldVal;
738 else
739 NamedValues.erase(VarName);
740
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000741 // for expr always returns 0.0.
742 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
743}
744
Lang Hames2d789c32015-08-26 03:07:41 +0000745Function *PrototypeAST::codegen() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000746 // Make the function type: double(double,double) etc.
Eric Christopherc0239362014-12-08 18:12:28 +0000747 std::vector<Type *> Doubles(Args.size(),
748 Type::getDoubleTy(getGlobalContext()));
749 FunctionType *FT =
750 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
751
752 Function *F =
Lang Hames2d789c32015-08-26 03:07:41 +0000753 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
Eric Christopherc0239362014-12-08 18:12:28 +0000754
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000755 // Set names for all arguments.
756 unsigned Idx = 0;
Lang Hames2d789c32015-08-26 03:07:41 +0000757 for (auto &Arg : F->args())
758 Arg.setName(Args[Idx++]);
Eric Christopherc0239362014-12-08 18:12:28 +0000759
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000760 return F;
761}
762
Lang Hames2d789c32015-08-26 03:07:41 +0000763Function *FunctionAST::codegen() {
764 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
765 // reference to it for use below.
766 auto &P = *Proto;
767 FunctionProtos[Proto->getName()] = std::move(Proto);
768 Function *TheFunction = getFunction(P.getName());
Lang Hames09bf4c12015-08-18 18:11:06 +0000769 if (!TheFunction)
770 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000771
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000772 // Create a new basic block to start insertion into.
773 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
774 Builder.SetInsertPoint(BB);
Eric Christopherc0239362014-12-08 18:12:28 +0000775
Lang Hames2d789c32015-08-26 03:07:41 +0000776 // Record the function arguments in the NamedValues map.
777 NamedValues.clear();
778 for (auto &Arg : TheFunction->args())
779 NamedValues[Arg.getName()] = &Arg;
780
781 if (Value *RetVal = Body->codegen()) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000782 // Finish off the function.
783 Builder.CreateRet(RetVal);
784
785 // Validate the generated code, checking for consistency.
786 verifyFunction(*TheFunction);
787
Lang Hames2d789c32015-08-26 03:07:41 +0000788 // Run the optimizer on the function.
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000789 TheFPM->run(*TheFunction);
Eric Christopherc0239362014-12-08 18:12:28 +0000790
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000791 return TheFunction;
792 }
Eric Christopherc0239362014-12-08 18:12:28 +0000793
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000794 // Error reading body, remove function.
795 TheFunction->eraseFromParent();
Lang Hames09bf4c12015-08-18 18:11:06 +0000796 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000797}
798
799//===----------------------------------------------------------------------===//
800// Top-Level parsing and JIT Driver
801//===----------------------------------------------------------------------===//
802
Lang Hames2d789c32015-08-26 03:07:41 +0000803static void InitializeModuleAndPassManager() {
804 // Open a new module.
805 TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
806 TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
807
808 // Create a new pass manager attached to it.
809 TheFPM = llvm::make_unique<legacy::FunctionPassManager>(TheModule.get());
810
Lang Hames2d789c32015-08-26 03:07:41 +0000811 // Do simple "peephole" optimizations and bit-twiddling optzns.
812 TheFPM->add(createInstructionCombiningPass());
813 // Reassociate expressions.
814 TheFPM->add(createReassociatePass());
815 // Eliminate Common SubExpressions.
816 TheFPM->add(createGVNPass());
817 // Simplify the control flow graph (deleting unreachable blocks, etc).
818 TheFPM->add(createCFGSimplificationPass());
819
820 TheFPM->doInitialization();
821}
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000822
823static void HandleDefinition() {
Lang Hames09bf4c12015-08-18 18:11:06 +0000824 if (auto FnAST = ParseDefinition()) {
Lang Hames2d789c32015-08-26 03:07:41 +0000825 if (auto *FnIR = FnAST->codegen()) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000826 fprintf(stderr, "Read function definition:");
Lang Hames09bf4c12015-08-18 18:11:06 +0000827 FnIR->dump();
Lang Hames2d789c32015-08-26 03:07:41 +0000828 TheJIT->addModule(std::move(TheModule));
829 InitializeModuleAndPassManager();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000830 }
831 } else {
832 // Skip token for error recovery.
833 getNextToken();
834 }
835}
836
837static void HandleExtern() {
Lang Hames09bf4c12015-08-18 18:11:06 +0000838 if (auto ProtoAST = ParseExtern()) {
Lang Hames2d789c32015-08-26 03:07:41 +0000839 if (auto *FnIR = ProtoAST->codegen()) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000840 fprintf(stderr, "Read extern: ");
Lang Hames09bf4c12015-08-18 18:11:06 +0000841 FnIR->dump();
Lang Hames2d789c32015-08-26 03:07:41 +0000842 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000843 }
844 } else {
845 // Skip token for error recovery.
846 getNextToken();
847 }
848}
849
850static void HandleTopLevelExpression() {
851 // Evaluate a top-level expression into an anonymous function.
Lang Hames09bf4c12015-08-18 18:11:06 +0000852 if (auto FnAST = ParseTopLevelExpr()) {
Lang Hames2d789c32015-08-26 03:07:41 +0000853 if (FnAST->codegen()) {
Eric Christopherc0239362014-12-08 18:12:28 +0000854
Lang Hames2d789c32015-08-26 03:07:41 +0000855 // JIT the module containing the anonymous expression, keeping a handle so
856 // we can free it later.
857 auto H = TheJIT->addModule(std::move(TheModule));
858 InitializeModuleAndPassManager();
859
860 // Search the JIT for the __anon_expr symbol.
861 auto ExprSymbol = TheJIT->findSymbol("__anon_expr");
862 assert(ExprSymbol && "Function not found");
863
864 // Get the symbol's address and cast it to the right type (takes no
865 // arguments, returns a double) so we can call it as a native function.
866 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000867 fprintf(stderr, "Evaluated to %f\n", FP());
Lang Hames2d789c32015-08-26 03:07:41 +0000868
869 // Delete the anonymous expression module from the JIT.
870 TheJIT->removeModule(H);
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000871 }
872 } else {
873 // Skip token for error recovery.
874 getNextToken();
875 }
876}
877
878/// top ::= definition | external | expression | ';'
879static void MainLoop() {
880 while (1) {
881 fprintf(stderr, "ready> ");
882 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +0000883 case tok_eof:
884 return;
Lang Hames59b0da82015-08-19 18:15:58 +0000885 case ';': // ignore top-level semicolons.
Eric Christopherc0239362014-12-08 18:12:28 +0000886 getNextToken();
Lang Hames59b0da82015-08-19 18:15:58 +0000887 break;
Eric Christopherc0239362014-12-08 18:12:28 +0000888 case tok_def:
889 HandleDefinition();
890 break;
891 case tok_extern:
892 HandleExtern();
893 break;
894 default:
895 HandleTopLevelExpression();
896 break;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000897 }
898 }
899}
900
901//===----------------------------------------------------------------------===//
902// "Library" functions that can be "extern'd" from user code.
903//===----------------------------------------------------------------------===//
904
905/// putchard - putchar that takes a double and returns 0.
NAKAMURA Takumiac9d3732015-08-28 03:34:33 +0000906extern "C" double putchard(double X) {
Lang Hamesd76e0672015-08-27 20:31:44 +0000907 fputc((char)X, stderr);
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000908 return 0;
909}
910
Lang Hames59b0da82015-08-19 18:15:58 +0000911/// printd - printf that takes a double prints it as "%f\n", returning 0.
NAKAMURA Takumiac9d3732015-08-28 03:34:33 +0000912extern "C" double printd(double X) {
Lang Hamesd76e0672015-08-27 20:31:44 +0000913 fprintf(stderr, "%f\n", X);
Lang Hames59b0da82015-08-19 18:15:58 +0000914 return 0;
915}
916
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000917//===----------------------------------------------------------------------===//
918// Main driver code.
919//===----------------------------------------------------------------------===//
920
921int main() {
922 InitializeNativeTarget();
Eric Christopher1b74b652014-12-08 18:00:38 +0000923 InitializeNativeTargetAsmPrinter();
924 InitializeNativeTargetAsmParser();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000925
926 // Install standard binary operators.
927 // 1 is lowest precedence.
928 BinopPrecedence['<'] = 10;
929 BinopPrecedence['+'] = 20;
930 BinopPrecedence['-'] = 20;
Eric Christopherc0239362014-12-08 18:12:28 +0000931 BinopPrecedence['*'] = 40; // highest.
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000932
933 // Prime the first token.
934 fprintf(stderr, "ready> ");
935 getNextToken();
936
Lang Hames2d789c32015-08-26 03:07:41 +0000937 TheJIT = llvm::make_unique<KaleidoscopeJIT>();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000938
Lang Hames2d789c32015-08-26 03:07:41 +0000939 InitializeModuleAndPassManager();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000940
941 // Run the main "interpreter loop" now.
942 MainLoop();
943
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000944 return 0;
945}