blob: 6c2087927565ad3f8c8a2f927c8f0e699b2e7176 [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"
Chandler Carruthec5872b2016-03-11 12:10:15 +000010#include "llvm/Transforms/Scalar/GVN.h"
Will Dietz981af002013-10-12 00:55:57 +000011#include <cctype>
Nick Lewycky109af622009-04-12 20:47:23 +000012#include <cstdio>
Nick Lewycky109af622009-04-12 20:47:23 +000013#include <map>
Chandler Carruth605e30e2012-12-04 10:16:57 +000014#include <string>
Nick Lewycky109af622009-04-12 20:47:23 +000015#include <vector>
Lang Hames2d789c32015-08-26 03:07:41 +000016#include "../include/KaleidoscopeJIT.h"
17
Nick Lewycky109af622009-04-12 20:47:23 +000018using namespace llvm;
Lang Hames2d789c32015-08-26 03:07:41 +000019using namespace llvm::orc;
Nick Lewycky109af622009-04-12 20:47:23 +000020
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.
27enum Token {
28 tok_eof = -1,
29
30 // commands
Eric Christopherc0239362014-12-08 18:12:28 +000031 tok_def = -2,
32 tok_extern = -3,
Nick Lewycky109af622009-04-12 20:47:23 +000033
34 // primary
Eric Christopherc0239362014-12-08 18:12:28 +000035 tok_identifier = -4,
36 tok_number = -5,
37
Nick Lewycky109af622009-04-12 20:47:23 +000038 // control
Eric Christopherc0239362014-12-08 18:12:28 +000039 tok_if = -6,
40 tok_then = -7,
41 tok_else = -8,
42 tok_for = -9,
43 tok_in = -10,
44
Nick Lewycky109af622009-04-12 20:47:23 +000045 // operators
Eric Christopherc0239362014-12-08 18:12:28 +000046 tok_binary = -11,
47 tok_unary = -12,
48
Nick Lewycky109af622009-04-12 20:47:23 +000049 // var definition
50 tok_var = -13
51};
52
Eric Christopherc0239362014-12-08 18:12:28 +000053static std::string IdentifierStr; // Filled in if tok_identifier
54static double NumVal; // Filled in if tok_number
Nick Lewycky109af622009-04-12 20:47:23 +000055
56/// gettok - Return the next token from standard input.
57static 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
Eric Christopherc0239362014-12-08 18:12:28 +000069 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;
Nick Lewycky109af622009-04-12 20:47:23 +000089 return tok_identifier;
90 }
91
Eric Christopherc0239362014-12-08 18:12:28 +000092 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
Nick Lewycky109af622009-04-12 20:47:23 +000093 std::string NumStr;
94 do {
95 NumStr += LastChar;
96 LastChar = getchar();
97 } while (isdigit(LastChar) || LastChar == '.');
98
Hans Wennborgcc9deb42015-09-29 18:02:48 +000099 NumVal = strtod(NumStr.c_str(), nullptr);
Nick Lewycky109af622009-04-12 20:47:23 +0000100 return tok_number;
101 }
102
103 if (LastChar == '#') {
104 // Comment until end of line.
Eric Christopherc0239362014-12-08 18:12:28 +0000105 do
106 LastChar = getchar();
Nick Lewycky109af622009-04-12 20:47:23 +0000107 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
Eric Christopherc0239362014-12-08 18:12:28 +0000108
Nick Lewycky109af622009-04-12 20:47:23 +0000109 if (LastChar != EOF)
110 return gettok();
111 }
Eric Christopherc0239362014-12-08 18:12:28 +0000112
Nick Lewycky109af622009-04-12 20:47:23 +0000113 // 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//===----------------------------------------------------------------------===//
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000126namespace {
Nick Lewycky109af622009-04-12 20:47:23 +0000127/// ExprAST - Base class for all expression nodes.
128class ExprAST {
129public:
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000130 virtual ~ExprAST() {}
Lang Hames2d789c32015-08-26 03:07:41 +0000131 virtual Value *codegen() = 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000132};
133
134/// NumberExprAST - Expression class for numeric literals like "1.0".
135class NumberExprAST : public ExprAST {
136 double Val;
Lang Hames59b0da82015-08-19 18:15:58 +0000137
Nick Lewycky109af622009-04-12 20:47:23 +0000138public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000139 NumberExprAST(double Val) : Val(Val) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000140 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000141};
142
143/// VariableExprAST - Expression class for referencing a variable, like "a".
144class VariableExprAST : public ExprAST {
145 std::string Name;
Lang Hames59b0da82015-08-19 18:15:58 +0000146
Nick Lewycky109af622009-04-12 20:47:23 +0000147public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000148 VariableExprAST(const std::string &Name) : Name(Name) {}
Nick Lewycky109af622009-04-12 20:47:23 +0000149 const std::string &getName() const { return Name; }
Lang Hames2d789c32015-08-26 03:07:41 +0000150 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000151};
152
153/// UnaryExprAST - Expression class for a unary operator.
154class UnaryExprAST : public ExprAST {
155 char Opcode;
Lang Hames09bf4c12015-08-18 18:11:06 +0000156 std::unique_ptr<ExprAST> Operand;
Lang Hames59b0da82015-08-19 18:15:58 +0000157
Nick Lewycky109af622009-04-12 20:47:23 +0000158public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000159 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
160 : Opcode(Opcode), Operand(std::move(Operand)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000161 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000162};
163
164/// BinaryExprAST - Expression class for a binary operator.
165class BinaryExprAST : public ExprAST {
166 char Op;
Lang Hames09bf4c12015-08-18 18:11:06 +0000167 std::unique_ptr<ExprAST> LHS, RHS;
Lang Hames59b0da82015-08-19 18:15:58 +0000168
Nick Lewycky109af622009-04-12 20:47:23 +0000169public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000170 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)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000173 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000174};
175
176/// CallExprAST - Expression class for function calls.
177class CallExprAST : public ExprAST {
178 std::string Callee;
Lang Hames09bf4c12015-08-18 18:11:06 +0000179 std::vector<std::unique_ptr<ExprAST>> Args;
Lang Hames59b0da82015-08-19 18:15:58 +0000180
Nick Lewycky109af622009-04-12 20:47:23 +0000181public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000182 CallExprAST(const std::string &Callee,
183 std::vector<std::unique_ptr<ExprAST>> Args)
184 : Callee(Callee), Args(std::move(Args)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000185 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000186};
187
188/// IfExprAST - Expression class for if/then/else.
189class IfExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000190 std::unique_ptr<ExprAST> Cond, Then, Else;
Lang Hames59b0da82015-08-19 18:15:58 +0000191
Nick Lewycky109af622009-04-12 20:47:23 +0000192public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000193 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)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000196 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000197};
198
199/// ForExprAST - Expression class for for/in.
200class ForExprAST : public ExprAST {
201 std::string VarName;
Lang Hames09bf4c12015-08-18 18:11:06 +0000202 std::unique_ptr<ExprAST> Start, End, Step, Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000203
Nick Lewycky109af622009-04-12 20:47:23 +0000204public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000205 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)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000210 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000211};
212
213/// VarExprAST - Expression class for var/in
214class VarExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000215 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
216 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000217
Nick Lewycky109af622009-04-12 20:47:23 +0000218public:
Lang Hames59b0da82015-08-19 18:15:58 +0000219 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)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000223 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000224};
225
226/// PrototypeAST - This class represents the "prototype" for a function,
Lang Hames59b0da82015-08-19 18:15:58 +0000227/// 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.
Nick Lewycky109af622009-04-12 20:47:23 +0000229class PrototypeAST {
230 std::string Name;
231 std::vector<std::string> Args;
Lang Hames09bf4c12015-08-18 18:11:06 +0000232 bool IsOperator;
Eric Christopherc0239362014-12-08 18:12:28 +0000233 unsigned Precedence; // Precedence if a binary op.
Lang Hames59b0da82015-08-19 18:15:58 +0000234
Nick Lewycky109af622009-04-12 20:47:23 +0000235public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000236 PrototypeAST(const std::string &Name, std::vector<std::string> Args,
237 bool IsOperator = false, unsigned Prec = 0)
Lang Hames59b0da82015-08-19 18:15:58 +0000238 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
239 Precedence(Prec) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000240 Function *codegen();
241 const std::string &getName() const { return Name; }
Eric Christopherc0239362014-12-08 18:12:28 +0000242
Lang Hames09bf4c12015-08-18 18:11:06 +0000243 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
244 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
Eric Christopherc0239362014-12-08 18:12:28 +0000245
Nick Lewycky109af622009-04-12 20:47:23 +0000246 char getOperatorName() const {
247 assert(isUnaryOp() || isBinaryOp());
Eric Christopherc0239362014-12-08 18:12:28 +0000248 return Name[Name.size() - 1];
Nick Lewycky109af622009-04-12 20:47:23 +0000249 }
Eric Christopherc0239362014-12-08 18:12:28 +0000250
Nick Lewycky109af622009-04-12 20:47:23 +0000251 unsigned getBinaryPrecedence() const { return Precedence; }
Nick Lewycky109af622009-04-12 20:47:23 +0000252};
253
254/// FunctionAST - This class represents a function definition itself.
255class FunctionAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000256 std::unique_ptr<PrototypeAST> Proto;
257 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000258
Nick Lewycky109af622009-04-12 20:47:23 +0000259public:
Lang Hames59b0da82015-08-19 18:15:58 +0000260 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
261 std::unique_ptr<ExprAST> Body)
Lang Hames09bf4c12015-08-18 18:11:06 +0000262 : Proto(std::move(Proto)), Body(std::move(Body)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000263 Function *codegen();
Nick Lewycky109af622009-04-12 20:47:23 +0000264};
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000265} // end anonymous namespace
Nick Lewycky109af622009-04-12 20:47:23 +0000266
267//===----------------------------------------------------------------------===//
268// Parser
269//===----------------------------------------------------------------------===//
270
271/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000272/// token the parser is looking at. getNextToken reads another token from the
Nick Lewycky109af622009-04-12 20:47:23 +0000273/// lexer and updates CurTok with its results.
274static int CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000275static int getNextToken() { return CurTok = gettok(); }
Nick Lewycky109af622009-04-12 20:47:23 +0000276
277/// BinopPrecedence - This holds the precedence for each binary operator that is
278/// defined.
279static std::map<char, int> BinopPrecedence;
280
281/// GetTokPrecedence - Get the precedence of the pending binary operator token.
282static int GetTokPrecedence() {
283 if (!isascii(CurTok))
284 return -1;
Eric Christopherc0239362014-12-08 18:12:28 +0000285
Nick Lewycky109af622009-04-12 20:47:23 +0000286 // Make sure it's a declared binop.
287 int TokPrec = BinopPrecedence[CurTok];
Eric Christopherc0239362014-12-08 18:12:28 +0000288 if (TokPrec <= 0)
289 return -1;
Nick Lewycky109af622009-04-12 20:47:23 +0000290 return TokPrec;
291}
292
293/// Error* - These are little helper functions for error handling.
Lang Hames09bf4c12015-08-18 18:11:06 +0000294std::unique_ptr<ExprAST> Error(const char *Str) {
Eric Christopherc0239362014-12-08 18:12:28 +0000295 fprintf(stderr, "Error: %s\n", Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000296 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000297}
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000298
Lang Hames09bf4c12015-08-18 18:11:06 +0000299std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
Eric Christopherc0239362014-12-08 18:12:28 +0000300 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000301 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000302}
Nick Lewycky109af622009-04-12 20:47:23 +0000303
Lang Hames09bf4c12015-08-18 18:11:06 +0000304static std::unique_ptr<ExprAST> ParseExpression();
Nick Lewycky109af622009-04-12 20:47:23 +0000305
Lang Hames59b0da82015-08-19 18:15:58 +0000306/// numberexpr ::= number
307static std::unique_ptr<ExprAST> ParseNumberExpr() {
308 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
309 getNextToken(); // consume the number
310 return std::move(Result);
311}
312
313/// parenexpr ::= '(' expression ')'
314static std::unique_ptr<ExprAST> ParseParenExpr() {
315 getNextToken(); // eat (.
316 auto V = ParseExpression();
317 if (!V)
318 return nullptr;
319
320 if (CurTok != ')')
321 return Error("expected ')'");
322 getNextToken(); // eat ).
323 return V;
324}
325
Nick Lewycky109af622009-04-12 20:47:23 +0000326/// identifierexpr
327/// ::= identifier
328/// ::= identifier '(' expression* ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000329static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
Nick Lewycky109af622009-04-12 20:47:23 +0000330 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000331
332 getNextToken(); // eat identifier.
333
Nick Lewycky109af622009-04-12 20:47:23 +0000334 if (CurTok != '(') // Simple variable ref.
Lang Hames09bf4c12015-08-18 18:11:06 +0000335 return llvm::make_unique<VariableExprAST>(IdName);
Eric Christopherc0239362014-12-08 18:12:28 +0000336
Nick Lewycky109af622009-04-12 20:47:23 +0000337 // Call.
Eric Christopherc0239362014-12-08 18:12:28 +0000338 getNextToken(); // eat (
Lang Hames09bf4c12015-08-18 18:11:06 +0000339 std::vector<std::unique_ptr<ExprAST>> Args;
Nick Lewycky109af622009-04-12 20:47:23 +0000340 if (CurTok != ')') {
341 while (1) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000342 if (auto Arg = ParseExpression())
343 Args.push_back(std::move(Arg));
344 else
345 return nullptr;
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000346
Eric Christopherc0239362014-12-08 18:12:28 +0000347 if (CurTok == ')')
348 break;
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000349
Nick Lewycky109af622009-04-12 20:47:23 +0000350 if (CurTok != ',')
351 return Error("Expected ')' or ',' in argument list");
352 getNextToken();
353 }
354 }
355
356 // Eat the ')'.
357 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000358
Lang Hames09bf4c12015-08-18 18:11:06 +0000359 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
Nick Lewycky109af622009-04-12 20:47:23 +0000360}
361
Nick Lewycky109af622009-04-12 20:47:23 +0000362/// ifexpr ::= 'if' expression 'then' expression 'else' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000363static std::unique_ptr<ExprAST> ParseIfExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000364 getNextToken(); // eat the if.
365
Nick Lewycky109af622009-04-12 20:47:23 +0000366 // condition.
Lang Hames09bf4c12015-08-18 18:11:06 +0000367 auto Cond = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000368 if (!Cond)
Lang Hames09bf4c12015-08-18 18:11:06 +0000369 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000370
Nick Lewycky109af622009-04-12 20:47:23 +0000371 if (CurTok != tok_then)
372 return Error("expected then");
Eric Christopherc0239362014-12-08 18:12:28 +0000373 getNextToken(); // eat the then
374
Lang Hames09bf4c12015-08-18 18:11:06 +0000375 auto Then = ParseExpression();
376 if (!Then)
377 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000378
Nick Lewycky109af622009-04-12 20:47:23 +0000379 if (CurTok != tok_else)
380 return Error("expected else");
Eric Christopherc0239362014-12-08 18:12:28 +0000381
Nick Lewycky109af622009-04-12 20:47:23 +0000382 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000383
Lang Hames09bf4c12015-08-18 18:11:06 +0000384 auto Else = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000385 if (!Else)
Lang Hames09bf4c12015-08-18 18:11:06 +0000386 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000387
Lang Hames09bf4c12015-08-18 18:11:06 +0000388 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
389 std::move(Else));
Nick Lewycky109af622009-04-12 20:47:23 +0000390}
391
392/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000393static std::unique_ptr<ExprAST> ParseForExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000394 getNextToken(); // eat the for.
Nick Lewycky109af622009-04-12 20:47:23 +0000395
396 if (CurTok != tok_identifier)
397 return Error("expected identifier after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000398
Nick Lewycky109af622009-04-12 20:47:23 +0000399 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000400 getNextToken(); // eat identifier.
401
Nick Lewycky109af622009-04-12 20:47:23 +0000402 if (CurTok != '=')
403 return Error("expected '=' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000404 getNextToken(); // eat '='.
405
Lang Hames09bf4c12015-08-18 18:11:06 +0000406 auto Start = ParseExpression();
407 if (!Start)
408 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000409 if (CurTok != ',')
410 return Error("expected ',' after for start value");
411 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000412
Lang Hames09bf4c12015-08-18 18:11:06 +0000413 auto End = ParseExpression();
414 if (!End)
415 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000416
Nick Lewycky109af622009-04-12 20:47:23 +0000417 // The step value is optional.
Lang Hames09bf4c12015-08-18 18:11:06 +0000418 std::unique_ptr<ExprAST> Step;
Nick Lewycky109af622009-04-12 20:47:23 +0000419 if (CurTok == ',') {
420 getNextToken();
421 Step = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000422 if (!Step)
423 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000424 }
Eric Christopherc0239362014-12-08 18:12:28 +0000425
Nick Lewycky109af622009-04-12 20:47:23 +0000426 if (CurTok != tok_in)
427 return Error("expected 'in' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000428 getNextToken(); // eat 'in'.
429
Lang Hames09bf4c12015-08-18 18:11:06 +0000430 auto Body = ParseExpression();
431 if (!Body)
432 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000433
Lang Hames09bf4c12015-08-18 18:11:06 +0000434 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
435 std::move(Step), std::move(Body));
Nick Lewycky109af622009-04-12 20:47:23 +0000436}
437
Eric Christopherc0239362014-12-08 18:12:28 +0000438/// varexpr ::= 'var' identifier ('=' expression)?
Nick Lewycky109af622009-04-12 20:47:23 +0000439// (',' identifier ('=' expression)?)* 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000440static std::unique_ptr<ExprAST> ParseVarExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000441 getNextToken(); // eat the var.
Nick Lewycky109af622009-04-12 20:47:23 +0000442
Lang Hames09bf4c12015-08-18 18:11:06 +0000443 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
Nick Lewycky109af622009-04-12 20:47:23 +0000444
445 // At least one variable name is required.
446 if (CurTok != tok_identifier)
447 return Error("expected identifier after var");
Eric Christopherc0239362014-12-08 18:12:28 +0000448
Nick Lewycky109af622009-04-12 20:47:23 +0000449 while (1) {
450 std::string Name = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000451 getNextToken(); // eat identifier.
Nick Lewycky109af622009-04-12 20:47:23 +0000452
453 // Read the optional initializer.
Lang Hames09bf4c12015-08-18 18:11:06 +0000454 std::unique_ptr<ExprAST> Init = nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000455 if (CurTok == '=') {
456 getNextToken(); // eat the '='.
Eric Christopherc0239362014-12-08 18:12:28 +0000457
Nick Lewycky109af622009-04-12 20:47:23 +0000458 Init = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000459 if (!Init)
460 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000461 }
Eric Christopherc0239362014-12-08 18:12:28 +0000462
Lang Hames09bf4c12015-08-18 18:11:06 +0000463 VarNames.push_back(std::make_pair(Name, std::move(Init)));
Eric Christopherc0239362014-12-08 18:12:28 +0000464
Nick Lewycky109af622009-04-12 20:47:23 +0000465 // End of var list, exit loop.
Eric Christopherc0239362014-12-08 18:12:28 +0000466 if (CurTok != ',')
467 break;
Nick Lewycky109af622009-04-12 20:47:23 +0000468 getNextToken(); // eat the ','.
Eric Christopherc0239362014-12-08 18:12:28 +0000469
Nick Lewycky109af622009-04-12 20:47:23 +0000470 if (CurTok != tok_identifier)
471 return Error("expected identifier list after var");
472 }
Eric Christopherc0239362014-12-08 18:12:28 +0000473
Nick Lewycky109af622009-04-12 20:47:23 +0000474 // At this point, we have to have 'in'.
475 if (CurTok != tok_in)
476 return Error("expected 'in' keyword after 'var'");
Eric Christopherc0239362014-12-08 18:12:28 +0000477 getNextToken(); // eat 'in'.
478
Lang Hames09bf4c12015-08-18 18:11:06 +0000479 auto Body = ParseExpression();
480 if (!Body)
481 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000482
Lang Hames09bf4c12015-08-18 18:11:06 +0000483 return llvm::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
Nick Lewycky109af622009-04-12 20:47:23 +0000484}
485
Nick Lewycky109af622009-04-12 20:47:23 +0000486/// primary
487/// ::= identifierexpr
488/// ::= numberexpr
489/// ::= parenexpr
490/// ::= ifexpr
491/// ::= forexpr
492/// ::= varexpr
Lang Hames09bf4c12015-08-18 18:11:06 +0000493static std::unique_ptr<ExprAST> ParsePrimary() {
Nick Lewycky109af622009-04-12 20:47:23 +0000494 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +0000495 default:
496 return Error("unknown token when expecting an expression");
497 case tok_identifier:
498 return ParseIdentifierExpr();
499 case tok_number:
500 return ParseNumberExpr();
501 case '(':
502 return ParseParenExpr();
503 case tok_if:
504 return ParseIfExpr();
505 case tok_for:
506 return ParseForExpr();
507 case tok_var:
508 return ParseVarExpr();
Nick Lewycky109af622009-04-12 20:47:23 +0000509 }
510}
511
512/// unary
513/// ::= primary
514/// ::= '!' unary
Lang Hames09bf4c12015-08-18 18:11:06 +0000515static std::unique_ptr<ExprAST> ParseUnary() {
Nick Lewycky109af622009-04-12 20:47:23 +0000516 // If the current token is not an operator, it must be a primary expr.
517 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
518 return ParsePrimary();
Eric Christopherc0239362014-12-08 18:12:28 +0000519
Nick Lewycky109af622009-04-12 20:47:23 +0000520 // If this is a unary operator, read it.
521 int Opc = CurTok;
522 getNextToken();
Lang Hames09bf4c12015-08-18 18:11:06 +0000523 if (auto Operand = ParseUnary())
524 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
525 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000526}
527
528/// binoprhs
529/// ::= ('+' unary)*
Lang Hames59b0da82015-08-19 18:15:58 +0000530static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
531 std::unique_ptr<ExprAST> LHS) {
Nick Lewycky109af622009-04-12 20:47:23 +0000532 // If this is a binop, find its precedence.
533 while (1) {
534 int TokPrec = GetTokPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +0000535
Nick Lewycky109af622009-04-12 20:47:23 +0000536 // If this is a binop that binds at least as tightly as the current binop,
537 // consume it, otherwise we are done.
538 if (TokPrec < ExprPrec)
539 return LHS;
Eric Christopherc0239362014-12-08 18:12:28 +0000540
Nick Lewycky109af622009-04-12 20:47:23 +0000541 // Okay, we know this is a binop.
542 int BinOp = CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000543 getNextToken(); // eat binop
544
Nick Lewycky109af622009-04-12 20:47:23 +0000545 // Parse the unary expression after the binary operator.
Lang Hames09bf4c12015-08-18 18:11:06 +0000546 auto RHS = ParseUnary();
Eric Christopherc0239362014-12-08 18:12:28 +0000547 if (!RHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000548 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000549
Nick Lewycky109af622009-04-12 20:47:23 +0000550 // If BinOp binds less tightly with RHS than the operator after RHS, let
551 // the pending operator take RHS as its LHS.
552 int NextPrec = GetTokPrecedence();
553 if (TokPrec < NextPrec) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000554 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
555 if (!RHS)
556 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000557 }
Eric Christopherc0239362014-12-08 18:12:28 +0000558
Nick Lewycky109af622009-04-12 20:47:23 +0000559 // Merge LHS/RHS.
Lang Hames59b0da82015-08-19 18:15:58 +0000560 LHS =
561 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
Nick Lewycky109af622009-04-12 20:47:23 +0000562 }
563}
564
565/// expression
566/// ::= unary binoprhs
567///
Lang Hames09bf4c12015-08-18 18:11:06 +0000568static std::unique_ptr<ExprAST> ParseExpression() {
569 auto LHS = ParseUnary();
Eric Christopherc0239362014-12-08 18:12:28 +0000570 if (!LHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000571 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000572
Lang Hames09bf4c12015-08-18 18:11:06 +0000573 return ParseBinOpRHS(0, std::move(LHS));
Nick Lewycky109af622009-04-12 20:47:23 +0000574}
575
576/// prototype
577/// ::= id '(' id* ')'
578/// ::= binary LETTER number? (id, id)
579/// ::= unary LETTER (id)
Lang Hames09bf4c12015-08-18 18:11:06 +0000580static std::unique_ptr<PrototypeAST> ParsePrototype() {
Nick Lewycky109af622009-04-12 20:47:23 +0000581 std::string FnName;
Eric Christopherc0239362014-12-08 18:12:28 +0000582
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000583 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
Nick Lewycky109af622009-04-12 20:47:23 +0000584 unsigned BinaryPrecedence = 30;
Eric Christopherc0239362014-12-08 18:12:28 +0000585
Nick Lewycky109af622009-04-12 20:47:23 +0000586 switch (CurTok) {
587 default:
588 return ErrorP("Expected function name in prototype");
589 case tok_identifier:
590 FnName = IdentifierStr;
591 Kind = 0;
592 getNextToken();
593 break;
594 case tok_unary:
595 getNextToken();
596 if (!isascii(CurTok))
597 return ErrorP("Expected unary operator");
598 FnName = "unary";
599 FnName += (char)CurTok;
600 Kind = 1;
601 getNextToken();
602 break;
603 case tok_binary:
604 getNextToken();
605 if (!isascii(CurTok))
606 return ErrorP("Expected binary operator");
607 FnName = "binary";
608 FnName += (char)CurTok;
609 Kind = 2;
610 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000611
Nick Lewycky109af622009-04-12 20:47:23 +0000612 // Read the precedence if present.
613 if (CurTok == tok_number) {
614 if (NumVal < 1 || NumVal > 100)
615 return ErrorP("Invalid precedecnce: must be 1..100");
616 BinaryPrecedence = (unsigned)NumVal;
617 getNextToken();
618 }
619 break;
620 }
Eric Christopherc0239362014-12-08 18:12:28 +0000621
Nick Lewycky109af622009-04-12 20:47:23 +0000622 if (CurTok != '(')
623 return ErrorP("Expected '(' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000624
Nick Lewycky109af622009-04-12 20:47:23 +0000625 std::vector<std::string> ArgNames;
626 while (getNextToken() == tok_identifier)
627 ArgNames.push_back(IdentifierStr);
628 if (CurTok != ')')
629 return ErrorP("Expected ')' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000630
Nick Lewycky109af622009-04-12 20:47:23 +0000631 // success.
Eric Christopherc0239362014-12-08 18:12:28 +0000632 getNextToken(); // eat ')'.
633
Nick Lewycky109af622009-04-12 20:47:23 +0000634 // Verify right number of names for operator.
635 if (Kind && ArgNames.size() != Kind)
636 return ErrorP("Invalid number of operands for operator");
Eric Christopherc0239362014-12-08 18:12:28 +0000637
Lang Hames09bf4c12015-08-18 18:11:06 +0000638 return llvm::make_unique<PrototypeAST>(FnName, ArgNames, Kind != 0,
639 BinaryPrecedence);
Nick Lewycky109af622009-04-12 20:47:23 +0000640}
641
642/// definition ::= 'def' prototype expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000643static std::unique_ptr<FunctionAST> ParseDefinition() {
Eric Christopherc0239362014-12-08 18:12:28 +0000644 getNextToken(); // eat def.
Lang Hames09bf4c12015-08-18 18:11:06 +0000645 auto Proto = ParsePrototype();
646 if (!Proto)
647 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000648
Lang Hames09bf4c12015-08-18 18:11:06 +0000649 if (auto E = ParseExpression())
650 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
651 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000652}
653
654/// toplevelexpr ::= expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000655static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
656 if (auto E = ParseExpression()) {
Nick Lewycky109af622009-04-12 20:47:23 +0000657 // Make an anonymous proto.
Lang Hames2d789c32015-08-26 03:07:41 +0000658 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
659 std::vector<std::string>());
Lang Hames09bf4c12015-08-18 18:11:06 +0000660 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
Nick Lewycky109af622009-04-12 20:47:23 +0000661 }
Lang Hames09bf4c12015-08-18 18:11:06 +0000662 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000663}
664
665/// external ::= 'extern' prototype
Lang Hames09bf4c12015-08-18 18:11:06 +0000666static std::unique_ptr<PrototypeAST> ParseExtern() {
Eric Christopherc0239362014-12-08 18:12:28 +0000667 getNextToken(); // eat extern.
Nick Lewycky109af622009-04-12 20:47:23 +0000668 return ParsePrototype();
669}
670
671//===----------------------------------------------------------------------===//
672// Code Generation
673//===----------------------------------------------------------------------===//
674
Lang Hames2d789c32015-08-26 03:07:41 +0000675static std::unique_ptr<Module> TheModule;
Owen Andersona7714592009-07-08 20:50:47 +0000676static IRBuilder<> Builder(getGlobalContext());
Eric Christopherc0239362014-12-08 18:12:28 +0000677static std::map<std::string, AllocaInst *> NamedValues;
Lang Hames2d789c32015-08-26 03:07:41 +0000678static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
679static std::unique_ptr<KaleidoscopeJIT> TheJIT;
680static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
Nick Lewycky109af622009-04-12 20:47:23 +0000681
Eric Christopherc0239362014-12-08 18:12:28 +0000682Value *ErrorV(const char *Str) {
683 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000684 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000685}
Nick Lewycky109af622009-04-12 20:47:23 +0000686
Lang Hames2d789c32015-08-26 03:07:41 +0000687Function *getFunction(std::string Name) {
688 // First, see if the function has already been added to the current module.
689 if (auto *F = TheModule->getFunction(Name))
690 return F;
691
692 // If not, check whether we can codegen the declaration from some existing
693 // prototype.
694 auto FI = FunctionProtos.find(Name);
695 if (FI != FunctionProtos.end())
696 return FI->second->codegen();
697
698 // If no existing prototype exists, return null.
699 return nullptr;
700}
701
Nick Lewycky109af622009-04-12 20:47:23 +0000702/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
703/// the function. This is used for mutable variables etc.
704static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
705 const std::string &VarName) {
706 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
Eric Christopherc0239362014-12-08 18:12:28 +0000707 TheFunction->getEntryBlock().begin());
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000708 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), nullptr,
Owen Anderson55f1c092009-08-13 21:58:54 +0000709 VarName.c_str());
Nick Lewycky109af622009-04-12 20:47:23 +0000710}
711
Lang Hames2d789c32015-08-26 03:07:41 +0000712Value *NumberExprAST::codegen() {
Owen Anderson69c464d2009-07-27 20:59:43 +0000713 return ConstantFP::get(getGlobalContext(), APFloat(Val));
Nick Lewycky109af622009-04-12 20:47:23 +0000714}
715
Lang Hames2d789c32015-08-26 03:07:41 +0000716Value *VariableExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000717 // Look this variable up in the function.
718 Value *V = NamedValues[Name];
Lang Hames09bf4c12015-08-18 18:11:06 +0000719 if (!V)
Eric Christopherc0239362014-12-08 18:12:28 +0000720 return ErrorV("Unknown variable name");
Nick Lewycky109af622009-04-12 20:47:23 +0000721
722 // Load the value.
723 return Builder.CreateLoad(V, Name.c_str());
724}
725
Lang Hames2d789c32015-08-26 03:07:41 +0000726Value *UnaryExprAST::codegen() {
727 Value *OperandV = Operand->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000728 if (!OperandV)
729 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000730
Lang Hames2d789c32015-08-26 03:07:41 +0000731 Function *F = getFunction(std::string("unary") + Opcode);
Lang Hames09bf4c12015-08-18 18:11:06 +0000732 if (!F)
Nick Lewycky109af622009-04-12 20:47:23 +0000733 return ErrorV("Unknown unary operator");
Eric Christopherc0239362014-12-08 18:12:28 +0000734
Nick Lewycky109af622009-04-12 20:47:23 +0000735 return Builder.CreateCall(F, OperandV, "unop");
736}
737
Lang Hames2d789c32015-08-26 03:07:41 +0000738Value *BinaryExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000739 // Special case '=' because we don't want to emit the LHS as an expression.
740 if (Op == '=') {
741 // Assignment requires the LHS to be an identifier.
Lang Hamese7c28bc2015-04-22 20:41:34 +0000742 // This assume we're building without RTTI because LLVM builds that way by
743 // default. If you build LLVM with RTTI this can be changed to a
744 // dynamic_cast for automatic error checking.
Lang Hames59b0da82015-08-19 18:15:58 +0000745 VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS.get());
Nick Lewycky109af622009-04-12 20:47:23 +0000746 if (!LHSE)
747 return ErrorV("destination of '=' must be a variable");
748 // Codegen the RHS.
Lang Hames2d789c32015-08-26 03:07:41 +0000749 Value *Val = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000750 if (!Val)
751 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000752
753 // Look up the name.
754 Value *Variable = NamedValues[LHSE->getName()];
Lang Hames09bf4c12015-08-18 18:11:06 +0000755 if (!Variable)
Eric Christopherc0239362014-12-08 18:12:28 +0000756 return ErrorV("Unknown variable name");
Nick Lewycky109af622009-04-12 20:47:23 +0000757
758 Builder.CreateStore(Val, Variable);
759 return Val;
760 }
Eric Christopherc0239362014-12-08 18:12:28 +0000761
Lang Hames2d789c32015-08-26 03:07:41 +0000762 Value *L = LHS->codegen();
763 Value *R = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000764 if (!L || !R)
765 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000766
Nick Lewycky109af622009-04-12 20:47:23 +0000767 switch (Op) {
Eric Christopherc0239362014-12-08 18:12:28 +0000768 case '+':
769 return Builder.CreateFAdd(L, R, "addtmp");
770 case '-':
771 return Builder.CreateFSub(L, R, "subtmp");
772 case '*':
773 return Builder.CreateFMul(L, R, "multmp");
Nick Lewycky109af622009-04-12 20:47:23 +0000774 case '<':
775 L = Builder.CreateFCmpULT(L, R, "cmptmp");
776 // Convert bool 0/1 to double 0.0 or 1.0
Owen Anderson55f1c092009-08-13 21:58:54 +0000777 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
778 "booltmp");
Eric Christopherc0239362014-12-08 18:12:28 +0000779 default:
780 break;
Nick Lewycky109af622009-04-12 20:47:23 +0000781 }
Eric Christopherc0239362014-12-08 18:12:28 +0000782
Nick Lewycky109af622009-04-12 20:47:23 +0000783 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
784 // a call to it.
Lang Hames2d789c32015-08-26 03:07:41 +0000785 Function *F = getFunction(std::string("binary") + Op);
Nick Lewycky109af622009-04-12 20:47:23 +0000786 assert(F && "binary operator not found!");
Eric Christopherc0239362014-12-08 18:12:28 +0000787
Lang Hames59b0da82015-08-19 18:15:58 +0000788 Value *Ops[] = {L, R};
Francois Pichetc5d10502011-07-15 10:59:52 +0000789 return Builder.CreateCall(F, Ops, "binop");
Nick Lewycky109af622009-04-12 20:47:23 +0000790}
791
Lang Hames2d789c32015-08-26 03:07:41 +0000792Value *CallExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000793 // Look up the name in the global module table.
Lang Hames2d789c32015-08-26 03:07:41 +0000794 Function *CalleeF = getFunction(Callee);
Lang Hames09bf4c12015-08-18 18:11:06 +0000795 if (!CalleeF)
Nick Lewycky109af622009-04-12 20:47:23 +0000796 return ErrorV("Unknown function referenced");
Eric Christopherc0239362014-12-08 18:12:28 +0000797
Nick Lewycky109af622009-04-12 20:47:23 +0000798 // If argument mismatch error.
799 if (CalleeF->arg_size() != Args.size())
800 return ErrorV("Incorrect # arguments passed");
801
Eric Christopherc0239362014-12-08 18:12:28 +0000802 std::vector<Value *> ArgsV;
Nick Lewycky109af622009-04-12 20:47:23 +0000803 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Lang Hames2d789c32015-08-26 03:07:41 +0000804 ArgsV.push_back(Args[i]->codegen());
Lang Hames09bf4c12015-08-18 18:11:06 +0000805 if (!ArgsV.back())
806 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000807 }
Eric Christopherc0239362014-12-08 18:12:28 +0000808
Francois Pichetc5d10502011-07-15 10:59:52 +0000809 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
Nick Lewycky109af622009-04-12 20:47:23 +0000810}
811
Lang Hames2d789c32015-08-26 03:07:41 +0000812Value *IfExprAST::codegen() {
813 Value *CondV = Cond->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000814 if (!CondV)
815 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000816
Nick Lewycky109af622009-04-12 20:47:23 +0000817 // Convert condition to a bool by comparing equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000818 CondV = Builder.CreateFCmpONE(
819 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
820
Nick Lewycky109af622009-04-12 20:47:23 +0000821 Function *TheFunction = Builder.GetInsertBlock()->getParent();
Eric Christopherc0239362014-12-08 18:12:28 +0000822
Nick Lewycky109af622009-04-12 20:47:23 +0000823 // Create blocks for the then and else cases. Insert the 'then' block at the
824 // end of the function.
Eric Christopherc0239362014-12-08 18:12:28 +0000825 BasicBlock *ThenBB =
826 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
Owen Anderson55f1c092009-08-13 21:58:54 +0000827 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
828 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
Eric Christopherc0239362014-12-08 18:12:28 +0000829
Nick Lewycky109af622009-04-12 20:47:23 +0000830 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000831
Nick Lewycky109af622009-04-12 20:47:23 +0000832 // Emit then value.
833 Builder.SetInsertPoint(ThenBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000834
Lang Hames2d789c32015-08-26 03:07:41 +0000835 Value *ThenV = Then->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000836 if (!ThenV)
837 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000838
Nick Lewycky109af622009-04-12 20:47:23 +0000839 Builder.CreateBr(MergeBB);
840 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
841 ThenBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000842
Nick Lewycky109af622009-04-12 20:47:23 +0000843 // Emit else block.
844 TheFunction->getBasicBlockList().push_back(ElseBB);
845 Builder.SetInsertPoint(ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000846
Lang Hames2d789c32015-08-26 03:07:41 +0000847 Value *ElseV = Else->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000848 if (!ElseV)
849 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000850
Nick Lewycky109af622009-04-12 20:47:23 +0000851 Builder.CreateBr(MergeBB);
852 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
853 ElseBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000854
Nick Lewycky109af622009-04-12 20:47:23 +0000855 // Emit merge block.
856 TheFunction->getBasicBlockList().push_back(MergeBB);
857 Builder.SetInsertPoint(MergeBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000858 PHINode *PN =
859 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
860
Nick Lewycky109af622009-04-12 20:47:23 +0000861 PN->addIncoming(ThenV, ThenBB);
862 PN->addIncoming(ElseV, ElseBB);
863 return PN;
864}
865
Lang Hames59b0da82015-08-19 18:15:58 +0000866// Output for-loop as:
867// var = alloca double
868// ...
869// start = startexpr
870// store start -> var
871// goto loop
872// loop:
873// ...
874// bodyexpr
875// ...
876// loopend:
877// step = stepexpr
878// endcond = endexpr
879//
880// curvar = load var
881// nextvar = curvar + step
882// store nextvar -> var
883// br endcond, loop, endloop
884// outloop:
Lang Hames2d789c32015-08-26 03:07:41 +0000885Value *ForExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000886 Function *TheFunction = Builder.GetInsertBlock()->getParent();
887
888 // Create an alloca for the variable in the entry block.
889 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
Eric Christopherc0239362014-12-08 18:12:28 +0000890
Nick Lewycky109af622009-04-12 20:47:23 +0000891 // Emit the start code first, without 'variable' in scope.
Lang Hames2d789c32015-08-26 03:07:41 +0000892 Value *StartVal = Start->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000893 if (!StartVal)
894 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000895
Nick Lewycky109af622009-04-12 20:47:23 +0000896 // Store the value into the alloca.
897 Builder.CreateStore(StartVal, Alloca);
Eric Christopherc0239362014-12-08 18:12:28 +0000898
Nick Lewycky109af622009-04-12 20:47:23 +0000899 // Make the new basic block for the loop header, inserting after current
900 // block.
Eric Christopherc0239362014-12-08 18:12:28 +0000901 BasicBlock *LoopBB =
902 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
903
Nick Lewycky109af622009-04-12 20:47:23 +0000904 // Insert an explicit fall through from the current block to the LoopBB.
905 Builder.CreateBr(LoopBB);
906
907 // Start insertion in LoopBB.
908 Builder.SetInsertPoint(LoopBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000909
Nick Lewycky109af622009-04-12 20:47:23 +0000910 // Within the loop, the variable is defined equal to the PHI node. If it
911 // shadows an existing variable, we have to restore it, so save it now.
912 AllocaInst *OldVal = NamedValues[VarName];
913 NamedValues[VarName] = Alloca;
Eric Christopherc0239362014-12-08 18:12:28 +0000914
Nick Lewycky109af622009-04-12 20:47:23 +0000915 // Emit the body of the loop. This, like any other expr, can change the
916 // current BB. Note that we ignore the value computed by the body, but don't
917 // allow an error.
Lang Hames2d789c32015-08-26 03:07:41 +0000918 if (!Body->codegen())
Lang Hames09bf4c12015-08-18 18:11:06 +0000919 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000920
Nick Lewycky109af622009-04-12 20:47:23 +0000921 // Emit the step value.
Lang Hames59b0da82015-08-19 18:15:58 +0000922 Value *StepVal = nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000923 if (Step) {
Lang Hames2d789c32015-08-26 03:07:41 +0000924 StepVal = Step->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000925 if (!StepVal)
926 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000927 } else {
928 // If not specified, use 1.0.
Owen Anderson69c464d2009-07-27 20:59:43 +0000929 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
Nick Lewycky109af622009-04-12 20:47:23 +0000930 }
Eric Christopherc0239362014-12-08 18:12:28 +0000931
Nick Lewycky109af622009-04-12 20:47:23 +0000932 // Compute the end condition.
Lang Hames2d789c32015-08-26 03:07:41 +0000933 Value *EndCond = End->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000934 if (!EndCond)
Lang Hames59b0da82015-08-19 18:15:58 +0000935 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000936
Nick Lewycky109af622009-04-12 20:47:23 +0000937 // Reload, increment, and restore the alloca. This handles the case where
938 // the body of the loop mutates the variable.
939 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
Chris Lattner26d79502010-06-21 22:51:14 +0000940 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
Nick Lewycky109af622009-04-12 20:47:23 +0000941 Builder.CreateStore(NextVar, Alloca);
Eric Christopherc0239362014-12-08 18:12:28 +0000942
Nick Lewycky109af622009-04-12 20:47:23 +0000943 // Convert condition to a bool by comparing equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000944 EndCond = Builder.CreateFCmpONE(
945 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
946
Nick Lewycky109af622009-04-12 20:47:23 +0000947 // Create the "after loop" block and insert it.
Eric Christopherc0239362014-12-08 18:12:28 +0000948 BasicBlock *AfterBB =
949 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
950
Nick Lewycky109af622009-04-12 20:47:23 +0000951 // Insert the conditional branch into the end of LoopEndBB.
952 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000953
Nick Lewycky109af622009-04-12 20:47:23 +0000954 // Any new code will be inserted in AfterBB.
955 Builder.SetInsertPoint(AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000956
Nick Lewycky109af622009-04-12 20:47:23 +0000957 // Restore the unshadowed variable.
958 if (OldVal)
959 NamedValues[VarName] = OldVal;
960 else
961 NamedValues.erase(VarName);
962
Nick Lewycky109af622009-04-12 20:47:23 +0000963 // for expr always returns 0.0.
Owen Anderson55f1c092009-08-13 21:58:54 +0000964 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
Nick Lewycky109af622009-04-12 20:47:23 +0000965}
966
Lang Hames2d789c32015-08-26 03:07:41 +0000967Value *VarExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000968 std::vector<AllocaInst *> OldBindings;
Eric Christopherc0239362014-12-08 18:12:28 +0000969
Nick Lewycky109af622009-04-12 20:47:23 +0000970 Function *TheFunction = Builder.GetInsertBlock()->getParent();
971
972 // Register all variables and emit their initializer.
973 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
974 const std::string &VarName = VarNames[i].first;
Lang Hames09bf4c12015-08-18 18:11:06 +0000975 ExprAST *Init = VarNames[i].second.get();
Eric Christopherc0239362014-12-08 18:12:28 +0000976
Nick Lewycky109af622009-04-12 20:47:23 +0000977 // Emit the initializer before adding the variable to scope, this prevents
978 // the initializer from referencing the variable itself, and permits stuff
979 // like this:
980 // var a = 1 in
981 // var a = a in ... # refers to outer 'a'.
982 Value *InitVal;
983 if (Init) {
Lang Hames2d789c32015-08-26 03:07:41 +0000984 InitVal = Init->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000985 if (!InitVal)
986 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000987 } else { // If not specified, use 0.0.
Owen Anderson69c464d2009-07-27 20:59:43 +0000988 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
Nick Lewycky109af622009-04-12 20:47:23 +0000989 }
Eric Christopherc0239362014-12-08 18:12:28 +0000990
Nick Lewycky109af622009-04-12 20:47:23 +0000991 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
992 Builder.CreateStore(InitVal, Alloca);
993
994 // Remember the old variable binding so that we can restore the binding when
995 // we unrecurse.
996 OldBindings.push_back(NamedValues[VarName]);
Eric Christopherc0239362014-12-08 18:12:28 +0000997
Nick Lewycky109af622009-04-12 20:47:23 +0000998 // Remember this binding.
999 NamedValues[VarName] = Alloca;
1000 }
Eric Christopherc0239362014-12-08 18:12:28 +00001001
Nick Lewycky109af622009-04-12 20:47:23 +00001002 // Codegen the body, now that all vars are in scope.
Lang Hames2d789c32015-08-26 03:07:41 +00001003 Value *BodyVal = Body->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001004 if (!BodyVal)
1005 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +00001006
Nick Lewycky109af622009-04-12 20:47:23 +00001007 // Pop all our variables from scope.
1008 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1009 NamedValues[VarNames[i].first] = OldBindings[i];
1010
1011 // Return the body computation.
1012 return BodyVal;
1013}
1014
Lang Hames2d789c32015-08-26 03:07:41 +00001015Function *PrototypeAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +00001016 // Make the function type: double(double,double) etc.
Eric Christopherc0239362014-12-08 18:12:28 +00001017 std::vector<Type *> Doubles(Args.size(),
1018 Type::getDoubleTy(getGlobalContext()));
1019 FunctionType *FT =
1020 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
1021
1022 Function *F =
Lang Hames2d789c32015-08-26 03:07:41 +00001023 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
Eric Christopherc0239362014-12-08 18:12:28 +00001024
Nick Lewycky109af622009-04-12 20:47:23 +00001025 // Set names for all arguments.
1026 unsigned Idx = 0;
Lang Hames2d789c32015-08-26 03:07:41 +00001027 for (auto &Arg : F->args())
1028 Arg.setName(Args[Idx++]);
Eric Christopherc0239362014-12-08 18:12:28 +00001029
Nick Lewycky109af622009-04-12 20:47:23 +00001030 return F;
1031}
1032
Lang Hames2d789c32015-08-26 03:07:41 +00001033Function *FunctionAST::codegen() {
1034 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
1035 // reference to it for use below.
1036 auto &P = *Proto;
1037 FunctionProtos[Proto->getName()] = std::move(Proto);
1038 Function *TheFunction = getFunction(P.getName());
Lang Hames09bf4c12015-08-18 18:11:06 +00001039 if (!TheFunction)
1040 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +00001041
Nick Lewycky109af622009-04-12 20:47:23 +00001042 // If this is an operator, install it.
Lang Hames2d789c32015-08-26 03:07:41 +00001043 if (P.isBinaryOp())
1044 BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +00001045
Nick Lewycky109af622009-04-12 20:47:23 +00001046 // Create a new basic block to start insertion into.
Owen Anderson55f1c092009-08-13 21:58:54 +00001047 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
Nick Lewycky109af622009-04-12 20:47:23 +00001048 Builder.SetInsertPoint(BB);
Eric Christopherc0239362014-12-08 18:12:28 +00001049
Lang Hames2d789c32015-08-26 03:07:41 +00001050 // Record the function arguments in the NamedValues map.
1051 NamedValues.clear();
1052 for (auto &Arg : TheFunction->args()) {
1053 // Create an alloca for this variable.
1054 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName());
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001055
Lang Hames2d789c32015-08-26 03:07:41 +00001056 // Store the initial value into the alloca.
1057 Builder.CreateStore(&Arg, Alloca);
1058
1059 // Add arguments to variable symbol table.
1060 NamedValues[Arg.getName()] = Alloca;
1061 }
1062
1063 if (Value *RetVal = Body->codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001064 // Finish off the function.
1065 Builder.CreateRet(RetVal);
1066
1067 // Validate the generated code, checking for consistency.
1068 verifyFunction(*TheFunction);
1069
Lang Hames2d789c32015-08-26 03:07:41 +00001070 // Run the optimizer on the function.
Nick Lewycky109af622009-04-12 20:47:23 +00001071 TheFPM->run(*TheFunction);
Eric Christopherc0239362014-12-08 18:12:28 +00001072
Nick Lewycky109af622009-04-12 20:47:23 +00001073 return TheFunction;
1074 }
Eric Christopherc0239362014-12-08 18:12:28 +00001075
Nick Lewycky109af622009-04-12 20:47:23 +00001076 // Error reading body, remove function.
1077 TheFunction->eraseFromParent();
1078
Lang Hames2d789c32015-08-26 03:07:41 +00001079 if (P.isBinaryOp())
Nick Lewycky109af622009-04-12 20:47:23 +00001080 BinopPrecedence.erase(Proto->getOperatorName());
Lang Hames09bf4c12015-08-18 18:11:06 +00001081 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +00001082}
1083
1084//===----------------------------------------------------------------------===//
1085// Top-Level parsing and JIT Driver
1086//===----------------------------------------------------------------------===//
1087
Lang Hames2d789c32015-08-26 03:07:41 +00001088static void InitializeModuleAndPassManager() {
1089 // Open a new module.
1090 TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
1091 TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
1092
1093 // Create a new pass manager attached to it.
1094 TheFPM = llvm::make_unique<legacy::FunctionPassManager>(TheModule.get());
1095
Lang Hames2d789c32015-08-26 03:07:41 +00001096 // Do simple "peephole" optimizations and bit-twiddling optzns.
1097 TheFPM->add(createInstructionCombiningPass());
1098 // Reassociate expressions.
1099 TheFPM->add(createReassociatePass());
1100 // Eliminate Common SubExpressions.
1101 TheFPM->add(createGVNPass());
1102 // Simplify the control flow graph (deleting unreachable blocks, etc).
1103 TheFPM->add(createCFGSimplificationPass());
1104
1105 TheFPM->doInitialization();
1106}
Nick Lewycky109af622009-04-12 20:47:23 +00001107
1108static void HandleDefinition() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001109 if (auto FnAST = ParseDefinition()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001110 if (auto *FnIR = FnAST->codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001111 fprintf(stderr, "Read function definition:");
Lang Hames09bf4c12015-08-18 18:11:06 +00001112 FnIR->dump();
Lang Hames2d789c32015-08-26 03:07:41 +00001113 TheJIT->addModule(std::move(TheModule));
1114 InitializeModuleAndPassManager();
Nick Lewycky109af622009-04-12 20:47:23 +00001115 }
1116 } else {
1117 // Skip token for error recovery.
1118 getNextToken();
1119 }
1120}
1121
1122static void HandleExtern() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001123 if (auto ProtoAST = ParseExtern()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001124 if (auto *FnIR = ProtoAST->codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001125 fprintf(stderr, "Read extern: ");
Lang Hames09bf4c12015-08-18 18:11:06 +00001126 FnIR->dump();
Lang Hames2d789c32015-08-26 03:07:41 +00001127 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
Nick Lewycky109af622009-04-12 20:47:23 +00001128 }
1129 } else {
1130 // Skip token for error recovery.
1131 getNextToken();
1132 }
1133}
1134
1135static void HandleTopLevelExpression() {
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001136 // Evaluate a top-level expression into an anonymous function.
Lang Hames09bf4c12015-08-18 18:11:06 +00001137 if (auto FnAST = ParseTopLevelExpr()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001138 if (FnAST->codegen()) {
Eric Christopherc0239362014-12-08 18:12:28 +00001139
Lang Hames2d789c32015-08-26 03:07:41 +00001140 // JIT the module containing the anonymous expression, keeping a handle so
1141 // we can free it later.
1142 auto H = TheJIT->addModule(std::move(TheModule));
1143 InitializeModuleAndPassManager();
1144
1145 // Search the JIT for the __anon_expr symbol.
1146 auto ExprSymbol = TheJIT->findSymbol("__anon_expr");
1147 assert(ExprSymbol && "Function not found");
1148
1149 // Get the symbol's address and cast it to the right type (takes no
1150 // arguments, returns a double) so we can call it as a native function.
1151 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
Nick Lewycky109af622009-04-12 20:47:23 +00001152 fprintf(stderr, "Evaluated to %f\n", FP());
Lang Hames2d789c32015-08-26 03:07:41 +00001153
1154 // Delete the anonymous expression module from the JIT.
1155 TheJIT->removeModule(H);
Nick Lewycky109af622009-04-12 20:47:23 +00001156 }
1157 } else {
1158 // Skip token for error recovery.
1159 getNextToken();
1160 }
1161}
1162
1163/// top ::= definition | external | expression | ';'
1164static void MainLoop() {
1165 while (1) {
1166 fprintf(stderr, "ready> ");
1167 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +00001168 case tok_eof:
1169 return;
Lang Hames59b0da82015-08-19 18:15:58 +00001170 case ';': // ignore top-level semicolons.
Eric Christopherc0239362014-12-08 18:12:28 +00001171 getNextToken();
Lang Hames59b0da82015-08-19 18:15:58 +00001172 break;
Eric Christopherc0239362014-12-08 18:12:28 +00001173 case tok_def:
1174 HandleDefinition();
1175 break;
1176 case tok_extern:
1177 HandleExtern();
1178 break;
1179 default:
1180 HandleTopLevelExpression();
1181 break;
Nick Lewycky109af622009-04-12 20:47:23 +00001182 }
1183 }
1184}
1185
Nick Lewycky109af622009-04-12 20:47:23 +00001186//===----------------------------------------------------------------------===//
1187// "Library" functions that can be "extern'd" from user code.
1188//===----------------------------------------------------------------------===//
1189
1190/// putchard - putchar that takes a double and returns 0.
NAKAMURA Takumiac9d3732015-08-28 03:34:33 +00001191extern "C" double putchard(double X) {
Lang Hamesd76e0672015-08-27 20:31:44 +00001192 fputc((char)X, stderr);
Nick Lewycky109af622009-04-12 20:47:23 +00001193 return 0;
1194}
1195
1196/// printd - printf that takes a double prints it as "%f\n", returning 0.
NAKAMURA Takumiac9d3732015-08-28 03:34:33 +00001197extern "C" double printd(double X) {
Lang Hamesd76e0672015-08-27 20:31:44 +00001198 fprintf(stderr, "%f\n", X);
Nick Lewycky109af622009-04-12 20:47:23 +00001199 return 0;
1200}
1201
1202//===----------------------------------------------------------------------===//
1203// Main driver code.
1204//===----------------------------------------------------------------------===//
1205
1206int main() {
Chris Lattnerd24df242009-06-17 16:48:44 +00001207 InitializeNativeTarget();
Eric Christopher1b74b652014-12-08 18:00:38 +00001208 InitializeNativeTargetAsmPrinter();
1209 InitializeNativeTargetAsmParser();
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001210
Nick Lewycky109af622009-04-12 20:47:23 +00001211 // Install standard binary operators.
1212 // 1 is lowest precedence.
1213 BinopPrecedence['='] = 2;
1214 BinopPrecedence['<'] = 10;
1215 BinopPrecedence['+'] = 20;
1216 BinopPrecedence['-'] = 20;
Eric Christopherc0239362014-12-08 18:12:28 +00001217 BinopPrecedence['*'] = 40; // highest.
Nick Lewycky109af622009-04-12 20:47:23 +00001218
1219 // Prime the first token.
1220 fprintf(stderr, "ready> ");
1221 getNextToken();
1222
Lang Hames2d789c32015-08-26 03:07:41 +00001223 TheJIT = llvm::make_unique<KaleidoscopeJIT>();
Nick Lewycky109af622009-04-12 20:47:23 +00001224
Lang Hames2d789c32015-08-26 03:07:41 +00001225 InitializeModuleAndPassManager();
Reid Klecknerab770042009-08-26 20:58:25 +00001226
1227 // Run the main "interpreter loop" now.
1228 MainLoop();
1229
Nick Lewycky109af622009-04-12 20:47:23 +00001230 return 0;
1231}