blob: cf3fbdf15da7baf10f53d94ea490a89cd5f2e01a [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>
Nick Lewycky109af622009-04-12 20:47:23 +000011#include <cstdio>
Nick Lewycky109af622009-04-12 20:47:23 +000012#include <map>
Chandler Carruth605e30e2012-12-04 10:16:57 +000013#include <string>
Nick Lewycky109af622009-04-12 20:47:23 +000014#include <vector>
Lang Hames2d789c32015-08-26 03:07:41 +000015#include "../include/KaleidoscopeJIT.h"
16
Nick Lewycky109af622009-04-12 20:47:23 +000017using namespace llvm;
Lang Hames2d789c32015-08-26 03:07:41 +000018using namespace llvm::orc;
Nick Lewycky109af622009-04-12 20:47:23 +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,
Nick Lewycky109af622009-04-12 20:47:23 +000032
33 // primary
Eric Christopherc0239362014-12-08 18:12:28 +000034 tok_identifier = -4,
35 tok_number = -5,
36
Nick Lewycky109af622009-04-12 20:47:23 +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,
43
Nick Lewycky109af622009-04-12 20:47:23 +000044 // operators
Eric Christopherc0239362014-12-08 18:12:28 +000045 tok_binary = -11,
46 tok_unary = -12,
47
Nick Lewycky109af622009-04-12 20:47:23 +000048 // var definition
49 tok_var = -13
50};
51
Eric Christopherc0239362014-12-08 18:12:28 +000052static std::string IdentifierStr; // Filled in if tok_identifier
53static double NumVal; // Filled in if tok_number
Nick Lewycky109af622009-04-12 20:47:23 +000054
55/// gettok - Return the next token from standard input.
56static int gettok() {
57 static int LastChar = ' ';
58
59 // Skip any whitespace.
60 while (isspace(LastChar))
61 LastChar = getchar();
62
63 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
64 IdentifierStr = LastChar;
65 while (isalnum((LastChar = getchar())))
66 IdentifierStr += LastChar;
67
Eric Christopherc0239362014-12-08 18:12:28 +000068 if (IdentifierStr == "def")
69 return tok_def;
70 if (IdentifierStr == "extern")
71 return tok_extern;
72 if (IdentifierStr == "if")
73 return tok_if;
74 if (IdentifierStr == "then")
75 return tok_then;
76 if (IdentifierStr == "else")
77 return tok_else;
78 if (IdentifierStr == "for")
79 return tok_for;
80 if (IdentifierStr == "in")
81 return tok_in;
82 if (IdentifierStr == "binary")
83 return tok_binary;
84 if (IdentifierStr == "unary")
85 return tok_unary;
86 if (IdentifierStr == "var")
87 return tok_var;
Nick Lewycky109af622009-04-12 20:47:23 +000088 return tok_identifier;
89 }
90
Eric Christopherc0239362014-12-08 18:12:28 +000091 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
Nick Lewycky109af622009-04-12 20:47:23 +000092 std::string NumStr;
93 do {
94 NumStr += LastChar;
95 LastChar = getchar();
96 } while (isdigit(LastChar) || LastChar == '.');
97
98 NumVal = strtod(NumStr.c_str(), 0);
99 return tok_number;
100 }
101
102 if (LastChar == '#') {
103 // Comment until end of line.
Eric Christopherc0239362014-12-08 18:12:28 +0000104 do
105 LastChar = getchar();
Nick Lewycky109af622009-04-12 20:47:23 +0000106 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
Eric Christopherc0239362014-12-08 18:12:28 +0000107
Nick Lewycky109af622009-04-12 20:47:23 +0000108 if (LastChar != EOF)
109 return gettok();
110 }
Eric Christopherc0239362014-12-08 18:12:28 +0000111
Nick Lewycky109af622009-04-12 20:47:23 +0000112 // Check for end of file. Don't eat the EOF.
113 if (LastChar == EOF)
114 return tok_eof;
115
116 // Otherwise, just return the character as its ascii value.
117 int ThisChar = LastChar;
118 LastChar = getchar();
119 return ThisChar;
120}
121
122//===----------------------------------------------------------------------===//
123// Abstract Syntax Tree (aka Parse Tree)
124//===----------------------------------------------------------------------===//
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000125namespace {
Nick Lewycky109af622009-04-12 20:47:23 +0000126/// ExprAST - Base class for all expression nodes.
127class ExprAST {
128public:
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000129 virtual ~ExprAST() {}
Lang Hames2d789c32015-08-26 03:07:41 +0000130 virtual Value *codegen() = 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000131};
132
133/// NumberExprAST - Expression class for numeric literals like "1.0".
134class NumberExprAST : public ExprAST {
135 double Val;
Lang Hames59b0da82015-08-19 18:15:58 +0000136
Nick Lewycky109af622009-04-12 20:47:23 +0000137public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000138 NumberExprAST(double Val) : Val(Val) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000139 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000140};
141
142/// VariableExprAST - Expression class for referencing a variable, like "a".
143class VariableExprAST : public ExprAST {
144 std::string Name;
Lang Hames59b0da82015-08-19 18:15:58 +0000145
Nick Lewycky109af622009-04-12 20:47:23 +0000146public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000147 VariableExprAST(const std::string &Name) : Name(Name) {}
Nick Lewycky109af622009-04-12 20:47:23 +0000148 const std::string &getName() const { return Name; }
Lang Hames2d789c32015-08-26 03:07:41 +0000149 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000150};
151
152/// UnaryExprAST - Expression class for a unary operator.
153class UnaryExprAST : public ExprAST {
154 char Opcode;
Lang Hames09bf4c12015-08-18 18:11:06 +0000155 std::unique_ptr<ExprAST> Operand;
Lang Hames59b0da82015-08-19 18:15:58 +0000156
Nick Lewycky109af622009-04-12 20:47:23 +0000157public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000158 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
159 : Opcode(Opcode), Operand(std::move(Operand)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000160 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000161};
162
163/// BinaryExprAST - Expression class for a binary operator.
164class BinaryExprAST : public ExprAST {
165 char Op;
Lang Hames09bf4c12015-08-18 18:11:06 +0000166 std::unique_ptr<ExprAST> LHS, RHS;
Lang Hames59b0da82015-08-19 18:15:58 +0000167
Nick Lewycky109af622009-04-12 20:47:23 +0000168public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000169 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
170 std::unique_ptr<ExprAST> RHS)
171 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000172 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000173};
174
175/// CallExprAST - Expression class for function calls.
176class CallExprAST : public ExprAST {
177 std::string Callee;
Lang Hames09bf4c12015-08-18 18:11:06 +0000178 std::vector<std::unique_ptr<ExprAST>> Args;
Lang Hames59b0da82015-08-19 18:15:58 +0000179
Nick Lewycky109af622009-04-12 20:47:23 +0000180public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000181 CallExprAST(const std::string &Callee,
182 std::vector<std::unique_ptr<ExprAST>> Args)
183 : Callee(Callee), Args(std::move(Args)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000184 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000185};
186
187/// IfExprAST - Expression class for if/then/else.
188class IfExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000189 std::unique_ptr<ExprAST> Cond, Then, Else;
Lang Hames59b0da82015-08-19 18:15:58 +0000190
Nick Lewycky109af622009-04-12 20:47:23 +0000191public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000192 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
193 std::unique_ptr<ExprAST> Else)
194 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000195 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000196};
197
198/// ForExprAST - Expression class for for/in.
199class ForExprAST : public ExprAST {
200 std::string VarName;
Lang Hames09bf4c12015-08-18 18:11:06 +0000201 std::unique_ptr<ExprAST> Start, End, Step, Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000202
Nick Lewycky109af622009-04-12 20:47:23 +0000203public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000204 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
205 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
206 std::unique_ptr<ExprAST> Body)
207 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
208 Step(std::move(Step)), Body(std::move(Body)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000209 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000210};
211
212/// VarExprAST - Expression class for var/in
213class VarExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000214 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
215 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000216
Nick Lewycky109af622009-04-12 20:47:23 +0000217public:
Lang Hames59b0da82015-08-19 18:15:58 +0000218 VarExprAST(
219 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames,
220 std::unique_ptr<ExprAST> Body)
221 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000222 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000223};
224
225/// PrototypeAST - This class represents the "prototype" for a function,
Lang Hames59b0da82015-08-19 18:15:58 +0000226/// which captures its name, and its argument names (thus implicitly the number
227/// of arguments the function takes), as well as if it is an operator.
Nick Lewycky109af622009-04-12 20:47:23 +0000228class PrototypeAST {
229 std::string Name;
230 std::vector<std::string> Args;
Lang Hames09bf4c12015-08-18 18:11:06 +0000231 bool IsOperator;
Eric Christopherc0239362014-12-08 18:12:28 +0000232 unsigned Precedence; // Precedence if a binary op.
Lang Hames59b0da82015-08-19 18:15:58 +0000233
Nick Lewycky109af622009-04-12 20:47:23 +0000234public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000235 PrototypeAST(const std::string &Name, std::vector<std::string> Args,
236 bool IsOperator = false, unsigned Prec = 0)
Lang Hames59b0da82015-08-19 18:15:58 +0000237 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
238 Precedence(Prec) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000239 Function *codegen();
240 const std::string &getName() const { return Name; }
Eric Christopherc0239362014-12-08 18:12:28 +0000241
Lang Hames09bf4c12015-08-18 18:11:06 +0000242 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
243 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
Eric Christopherc0239362014-12-08 18:12:28 +0000244
Nick Lewycky109af622009-04-12 20:47:23 +0000245 char getOperatorName() const {
246 assert(isUnaryOp() || isBinaryOp());
Eric Christopherc0239362014-12-08 18:12:28 +0000247 return Name[Name.size() - 1];
Nick Lewycky109af622009-04-12 20:47:23 +0000248 }
Eric Christopherc0239362014-12-08 18:12:28 +0000249
Nick Lewycky109af622009-04-12 20:47:23 +0000250 unsigned getBinaryPrecedence() const { return Precedence; }
Nick Lewycky109af622009-04-12 20:47:23 +0000251};
252
253/// FunctionAST - This class represents a function definition itself.
254class FunctionAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000255 std::unique_ptr<PrototypeAST> Proto;
256 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000257
Nick Lewycky109af622009-04-12 20:47:23 +0000258public:
Lang Hames59b0da82015-08-19 18:15:58 +0000259 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
260 std::unique_ptr<ExprAST> Body)
Lang Hames09bf4c12015-08-18 18:11:06 +0000261 : Proto(std::move(Proto)), Body(std::move(Body)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000262 Function *codegen();
Nick Lewycky109af622009-04-12 20:47:23 +0000263};
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000264} // end anonymous namespace
Nick Lewycky109af622009-04-12 20:47:23 +0000265
266//===----------------------------------------------------------------------===//
267// Parser
268//===----------------------------------------------------------------------===//
269
270/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000271/// token the parser is looking at. getNextToken reads another token from the
Nick Lewycky109af622009-04-12 20:47:23 +0000272/// lexer and updates CurTok with its results.
273static int CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000274static int getNextToken() { return CurTok = gettok(); }
Nick Lewycky109af622009-04-12 20:47:23 +0000275
276/// BinopPrecedence - This holds the precedence for each binary operator that is
277/// defined.
278static std::map<char, int> BinopPrecedence;
279
280/// GetTokPrecedence - Get the precedence of the pending binary operator token.
281static int GetTokPrecedence() {
282 if (!isascii(CurTok))
283 return -1;
Eric Christopherc0239362014-12-08 18:12:28 +0000284
Nick Lewycky109af622009-04-12 20:47:23 +0000285 // Make sure it's a declared binop.
286 int TokPrec = BinopPrecedence[CurTok];
Eric Christopherc0239362014-12-08 18:12:28 +0000287 if (TokPrec <= 0)
288 return -1;
Nick Lewycky109af622009-04-12 20:47:23 +0000289 return TokPrec;
290}
291
292/// Error* - These are little helper functions for error handling.
Lang Hames09bf4c12015-08-18 18:11:06 +0000293std::unique_ptr<ExprAST> Error(const char *Str) {
Eric Christopherc0239362014-12-08 18:12:28 +0000294 fprintf(stderr, "Error: %s\n", Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000295 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000296}
Lang Hames09bf4c12015-08-18 18:11:06 +0000297std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
Eric Christopherc0239362014-12-08 18:12:28 +0000298 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000299 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000300}
Nick Lewycky109af622009-04-12 20:47:23 +0000301
Lang Hames09bf4c12015-08-18 18:11:06 +0000302static std::unique_ptr<ExprAST> ParseExpression();
Nick Lewycky109af622009-04-12 20:47:23 +0000303
Lang Hames59b0da82015-08-19 18:15:58 +0000304/// numberexpr ::= number
305static std::unique_ptr<ExprAST> ParseNumberExpr() {
306 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
307 getNextToken(); // consume the number
308 return std::move(Result);
309}
310
311/// parenexpr ::= '(' expression ')'
312static std::unique_ptr<ExprAST> ParseParenExpr() {
313 getNextToken(); // eat (.
314 auto V = ParseExpression();
315 if (!V)
316 return nullptr;
317
318 if (CurTok != ')')
319 return Error("expected ')'");
320 getNextToken(); // eat ).
321 return V;
322}
323
Nick Lewycky109af622009-04-12 20:47:23 +0000324/// identifierexpr
325/// ::= identifier
326/// ::= identifier '(' expression* ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000327static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
Nick Lewycky109af622009-04-12 20:47:23 +0000328 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000329
330 getNextToken(); // eat identifier.
331
Nick Lewycky109af622009-04-12 20:47:23 +0000332 if (CurTok != '(') // Simple variable ref.
Lang Hames09bf4c12015-08-18 18:11:06 +0000333 return llvm::make_unique<VariableExprAST>(IdName);
Eric Christopherc0239362014-12-08 18:12:28 +0000334
Nick Lewycky109af622009-04-12 20:47:23 +0000335 // Call.
Eric Christopherc0239362014-12-08 18:12:28 +0000336 getNextToken(); // eat (
Lang Hames09bf4c12015-08-18 18:11:06 +0000337 std::vector<std::unique_ptr<ExprAST>> Args;
Nick Lewycky109af622009-04-12 20:47:23 +0000338 if (CurTok != ')') {
339 while (1) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000340 if (auto Arg = ParseExpression())
341 Args.push_back(std::move(Arg));
342 else
343 return nullptr;
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000344
Eric Christopherc0239362014-12-08 18:12:28 +0000345 if (CurTok == ')')
346 break;
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000347
Nick Lewycky109af622009-04-12 20:47:23 +0000348 if (CurTok != ',')
349 return Error("Expected ')' or ',' in argument list");
350 getNextToken();
351 }
352 }
353
354 // Eat the ')'.
355 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000356
Lang Hames09bf4c12015-08-18 18:11:06 +0000357 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
Nick Lewycky109af622009-04-12 20:47:23 +0000358}
359
Nick Lewycky109af622009-04-12 20:47:23 +0000360/// ifexpr ::= 'if' expression 'then' expression 'else' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000361static std::unique_ptr<ExprAST> ParseIfExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000362 getNextToken(); // eat the if.
363
Nick Lewycky109af622009-04-12 20:47:23 +0000364 // condition.
Lang Hames09bf4c12015-08-18 18:11:06 +0000365 auto Cond = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000366 if (!Cond)
Lang Hames09bf4c12015-08-18 18:11:06 +0000367 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000368
Nick Lewycky109af622009-04-12 20:47:23 +0000369 if (CurTok != tok_then)
370 return Error("expected then");
Eric Christopherc0239362014-12-08 18:12:28 +0000371 getNextToken(); // eat the then
372
Lang Hames09bf4c12015-08-18 18:11:06 +0000373 auto Then = ParseExpression();
374 if (!Then)
375 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000376
Nick Lewycky109af622009-04-12 20:47:23 +0000377 if (CurTok != tok_else)
378 return Error("expected else");
Eric Christopherc0239362014-12-08 18:12:28 +0000379
Nick Lewycky109af622009-04-12 20:47:23 +0000380 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000381
Lang Hames09bf4c12015-08-18 18:11:06 +0000382 auto Else = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000383 if (!Else)
Lang Hames09bf4c12015-08-18 18:11:06 +0000384 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000385
Lang Hames09bf4c12015-08-18 18:11:06 +0000386 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
387 std::move(Else));
Nick Lewycky109af622009-04-12 20:47:23 +0000388}
389
390/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000391static std::unique_ptr<ExprAST> ParseForExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000392 getNextToken(); // eat the for.
Nick Lewycky109af622009-04-12 20:47:23 +0000393
394 if (CurTok != tok_identifier)
395 return Error("expected identifier after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000396
Nick Lewycky109af622009-04-12 20:47:23 +0000397 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000398 getNextToken(); // eat identifier.
399
Nick Lewycky109af622009-04-12 20:47:23 +0000400 if (CurTok != '=')
401 return Error("expected '=' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000402 getNextToken(); // eat '='.
403
Lang Hames09bf4c12015-08-18 18:11:06 +0000404 auto Start = ParseExpression();
405 if (!Start)
406 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000407 if (CurTok != ',')
408 return Error("expected ',' after for start value");
409 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000410
Lang Hames09bf4c12015-08-18 18:11:06 +0000411 auto End = ParseExpression();
412 if (!End)
413 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000414
Nick Lewycky109af622009-04-12 20:47:23 +0000415 // The step value is optional.
Lang Hames09bf4c12015-08-18 18:11:06 +0000416 std::unique_ptr<ExprAST> Step;
Nick Lewycky109af622009-04-12 20:47:23 +0000417 if (CurTok == ',') {
418 getNextToken();
419 Step = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000420 if (!Step)
421 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000422 }
Eric Christopherc0239362014-12-08 18:12:28 +0000423
Nick Lewycky109af622009-04-12 20:47:23 +0000424 if (CurTok != tok_in)
425 return Error("expected 'in' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000426 getNextToken(); // eat 'in'.
427
Lang Hames09bf4c12015-08-18 18:11:06 +0000428 auto Body = ParseExpression();
429 if (!Body)
430 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000431
Lang Hames09bf4c12015-08-18 18:11:06 +0000432 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
433 std::move(Step), std::move(Body));
Nick Lewycky109af622009-04-12 20:47:23 +0000434}
435
Eric Christopherc0239362014-12-08 18:12:28 +0000436/// varexpr ::= 'var' identifier ('=' expression)?
Nick Lewycky109af622009-04-12 20:47:23 +0000437// (',' identifier ('=' expression)?)* 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000438static std::unique_ptr<ExprAST> ParseVarExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000439 getNextToken(); // eat the var.
Nick Lewycky109af622009-04-12 20:47:23 +0000440
Lang Hames09bf4c12015-08-18 18:11:06 +0000441 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
Nick Lewycky109af622009-04-12 20:47:23 +0000442
443 // At least one variable name is required.
444 if (CurTok != tok_identifier)
445 return Error("expected identifier after var");
Eric Christopherc0239362014-12-08 18:12:28 +0000446
Nick Lewycky109af622009-04-12 20:47:23 +0000447 while (1) {
448 std::string Name = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000449 getNextToken(); // eat identifier.
Nick Lewycky109af622009-04-12 20:47:23 +0000450
451 // Read the optional initializer.
Lang Hames09bf4c12015-08-18 18:11:06 +0000452 std::unique_ptr<ExprAST> Init = nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000453 if (CurTok == '=') {
454 getNextToken(); // eat the '='.
Eric Christopherc0239362014-12-08 18:12:28 +0000455
Nick Lewycky109af622009-04-12 20:47:23 +0000456 Init = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000457 if (!Init)
458 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000459 }
Eric Christopherc0239362014-12-08 18:12:28 +0000460
Lang Hames09bf4c12015-08-18 18:11:06 +0000461 VarNames.push_back(std::make_pair(Name, std::move(Init)));
Eric Christopherc0239362014-12-08 18:12:28 +0000462
Nick Lewycky109af622009-04-12 20:47:23 +0000463 // End of var list, exit loop.
Eric Christopherc0239362014-12-08 18:12:28 +0000464 if (CurTok != ',')
465 break;
Nick Lewycky109af622009-04-12 20:47:23 +0000466 getNextToken(); // eat the ','.
Eric Christopherc0239362014-12-08 18:12:28 +0000467
Nick Lewycky109af622009-04-12 20:47:23 +0000468 if (CurTok != tok_identifier)
469 return Error("expected identifier list after var");
470 }
Eric Christopherc0239362014-12-08 18:12:28 +0000471
Nick Lewycky109af622009-04-12 20:47:23 +0000472 // At this point, we have to have 'in'.
473 if (CurTok != tok_in)
474 return Error("expected 'in' keyword after 'var'");
Eric Christopherc0239362014-12-08 18:12:28 +0000475 getNextToken(); // eat 'in'.
476
Lang Hames09bf4c12015-08-18 18:11:06 +0000477 auto Body = ParseExpression();
478 if (!Body)
479 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000480
Lang Hames09bf4c12015-08-18 18:11:06 +0000481 return llvm::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
Nick Lewycky109af622009-04-12 20:47:23 +0000482}
483
Nick Lewycky109af622009-04-12 20:47:23 +0000484/// primary
485/// ::= identifierexpr
486/// ::= numberexpr
487/// ::= parenexpr
488/// ::= ifexpr
489/// ::= forexpr
490/// ::= varexpr
Lang Hames09bf4c12015-08-18 18:11:06 +0000491static std::unique_ptr<ExprAST> ParsePrimary() {
Nick Lewycky109af622009-04-12 20:47:23 +0000492 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +0000493 default:
494 return Error("unknown token when expecting an expression");
495 case tok_identifier:
496 return ParseIdentifierExpr();
497 case tok_number:
498 return ParseNumberExpr();
499 case '(':
500 return ParseParenExpr();
501 case tok_if:
502 return ParseIfExpr();
503 case tok_for:
504 return ParseForExpr();
505 case tok_var:
506 return ParseVarExpr();
Nick Lewycky109af622009-04-12 20:47:23 +0000507 }
508}
509
510/// unary
511/// ::= primary
512/// ::= '!' unary
Lang Hames09bf4c12015-08-18 18:11:06 +0000513static std::unique_ptr<ExprAST> ParseUnary() {
Nick Lewycky109af622009-04-12 20:47:23 +0000514 // If the current token is not an operator, it must be a primary expr.
515 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
516 return ParsePrimary();
Eric Christopherc0239362014-12-08 18:12:28 +0000517
Nick Lewycky109af622009-04-12 20:47:23 +0000518 // If this is a unary operator, read it.
519 int Opc = CurTok;
520 getNextToken();
Lang Hames09bf4c12015-08-18 18:11:06 +0000521 if (auto Operand = ParseUnary())
522 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
523 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000524}
525
526/// binoprhs
527/// ::= ('+' unary)*
Lang Hames59b0da82015-08-19 18:15:58 +0000528static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
529 std::unique_ptr<ExprAST> LHS) {
Nick Lewycky109af622009-04-12 20:47:23 +0000530 // If this is a binop, find its precedence.
531 while (1) {
532 int TokPrec = GetTokPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +0000533
Nick Lewycky109af622009-04-12 20:47:23 +0000534 // If this is a binop that binds at least as tightly as the current binop,
535 // consume it, otherwise we are done.
536 if (TokPrec < ExprPrec)
537 return LHS;
Eric Christopherc0239362014-12-08 18:12:28 +0000538
Nick Lewycky109af622009-04-12 20:47:23 +0000539 // Okay, we know this is a binop.
540 int BinOp = CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000541 getNextToken(); // eat binop
542
Nick Lewycky109af622009-04-12 20:47:23 +0000543 // Parse the unary expression after the binary operator.
Lang Hames09bf4c12015-08-18 18:11:06 +0000544 auto RHS = ParseUnary();
Eric Christopherc0239362014-12-08 18:12:28 +0000545 if (!RHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000546 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000547
Nick Lewycky109af622009-04-12 20:47:23 +0000548 // If BinOp binds less tightly with RHS than the operator after RHS, let
549 // the pending operator take RHS as its LHS.
550 int NextPrec = GetTokPrecedence();
551 if (TokPrec < NextPrec) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000552 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
553 if (!RHS)
554 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000555 }
Eric Christopherc0239362014-12-08 18:12:28 +0000556
Nick Lewycky109af622009-04-12 20:47:23 +0000557 // Merge LHS/RHS.
Lang Hames59b0da82015-08-19 18:15:58 +0000558 LHS =
559 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
Nick Lewycky109af622009-04-12 20:47:23 +0000560 }
561}
562
563/// expression
564/// ::= unary binoprhs
565///
Lang Hames09bf4c12015-08-18 18:11:06 +0000566static std::unique_ptr<ExprAST> ParseExpression() {
567 auto LHS = ParseUnary();
Eric Christopherc0239362014-12-08 18:12:28 +0000568 if (!LHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000569 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000570
Lang Hames09bf4c12015-08-18 18:11:06 +0000571 return ParseBinOpRHS(0, std::move(LHS));
Nick Lewycky109af622009-04-12 20:47:23 +0000572}
573
574/// prototype
575/// ::= id '(' id* ')'
576/// ::= binary LETTER number? (id, id)
577/// ::= unary LETTER (id)
Lang Hames09bf4c12015-08-18 18:11:06 +0000578static std::unique_ptr<PrototypeAST> ParsePrototype() {
Nick Lewycky109af622009-04-12 20:47:23 +0000579 std::string FnName;
Eric Christopherc0239362014-12-08 18:12:28 +0000580
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000581 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
Nick Lewycky109af622009-04-12 20:47:23 +0000582 unsigned BinaryPrecedence = 30;
Eric Christopherc0239362014-12-08 18:12:28 +0000583
Nick Lewycky109af622009-04-12 20:47:23 +0000584 switch (CurTok) {
585 default:
586 return ErrorP("Expected function name in prototype");
587 case tok_identifier:
588 FnName = IdentifierStr;
589 Kind = 0;
590 getNextToken();
591 break;
592 case tok_unary:
593 getNextToken();
594 if (!isascii(CurTok))
595 return ErrorP("Expected unary operator");
596 FnName = "unary";
597 FnName += (char)CurTok;
598 Kind = 1;
599 getNextToken();
600 break;
601 case tok_binary:
602 getNextToken();
603 if (!isascii(CurTok))
604 return ErrorP("Expected binary operator");
605 FnName = "binary";
606 FnName += (char)CurTok;
607 Kind = 2;
608 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000609
Nick Lewycky109af622009-04-12 20:47:23 +0000610 // Read the precedence if present.
611 if (CurTok == tok_number) {
612 if (NumVal < 1 || NumVal > 100)
613 return ErrorP("Invalid precedecnce: must be 1..100");
614 BinaryPrecedence = (unsigned)NumVal;
615 getNextToken();
616 }
617 break;
618 }
Eric Christopherc0239362014-12-08 18:12:28 +0000619
Nick Lewycky109af622009-04-12 20:47:23 +0000620 if (CurTok != '(')
621 return ErrorP("Expected '(' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000622
Nick Lewycky109af622009-04-12 20:47:23 +0000623 std::vector<std::string> ArgNames;
624 while (getNextToken() == tok_identifier)
625 ArgNames.push_back(IdentifierStr);
626 if (CurTok != ')')
627 return ErrorP("Expected ')' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000628
Nick Lewycky109af622009-04-12 20:47:23 +0000629 // success.
Eric Christopherc0239362014-12-08 18:12:28 +0000630 getNextToken(); // eat ')'.
631
Nick Lewycky109af622009-04-12 20:47:23 +0000632 // Verify right number of names for operator.
633 if (Kind && ArgNames.size() != Kind)
634 return ErrorP("Invalid number of operands for operator");
Eric Christopherc0239362014-12-08 18:12:28 +0000635
Lang Hames09bf4c12015-08-18 18:11:06 +0000636 return llvm::make_unique<PrototypeAST>(FnName, ArgNames, Kind != 0,
637 BinaryPrecedence);
Nick Lewycky109af622009-04-12 20:47:23 +0000638}
639
640/// definition ::= 'def' prototype expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000641static std::unique_ptr<FunctionAST> ParseDefinition() {
Eric Christopherc0239362014-12-08 18:12:28 +0000642 getNextToken(); // eat def.
Lang Hames09bf4c12015-08-18 18:11:06 +0000643 auto Proto = ParsePrototype();
644 if (!Proto)
645 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000646
Lang Hames09bf4c12015-08-18 18:11:06 +0000647 if (auto E = ParseExpression())
648 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
649 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000650}
651
652/// toplevelexpr ::= expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000653static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
654 if (auto E = ParseExpression()) {
Nick Lewycky109af622009-04-12 20:47:23 +0000655 // Make an anonymous proto.
Lang Hames2d789c32015-08-26 03:07:41 +0000656 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
657 std::vector<std::string>());
Lang Hames09bf4c12015-08-18 18:11:06 +0000658 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
Nick Lewycky109af622009-04-12 20:47:23 +0000659 }
Lang Hames09bf4c12015-08-18 18:11:06 +0000660 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000661}
662
663/// external ::= 'extern' prototype
Lang Hames09bf4c12015-08-18 18:11:06 +0000664static std::unique_ptr<PrototypeAST> ParseExtern() {
Eric Christopherc0239362014-12-08 18:12:28 +0000665 getNextToken(); // eat extern.
Nick Lewycky109af622009-04-12 20:47:23 +0000666 return ParsePrototype();
667}
668
669//===----------------------------------------------------------------------===//
670// Code Generation
671//===----------------------------------------------------------------------===//
672
Lang Hames2d789c32015-08-26 03:07:41 +0000673static std::unique_ptr<Module> TheModule;
Owen Andersona7714592009-07-08 20:50:47 +0000674static IRBuilder<> Builder(getGlobalContext());
Eric Christopherc0239362014-12-08 18:12:28 +0000675static std::map<std::string, AllocaInst *> NamedValues;
Lang Hames2d789c32015-08-26 03:07:41 +0000676static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
677static std::unique_ptr<KaleidoscopeJIT> TheJIT;
678static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
Nick Lewycky109af622009-04-12 20:47:23 +0000679
Eric Christopherc0239362014-12-08 18:12:28 +0000680Value *ErrorV(const char *Str) {
681 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000682 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000683}
Nick Lewycky109af622009-04-12 20:47:23 +0000684
Lang Hames2d789c32015-08-26 03:07:41 +0000685Function *getFunction(std::string Name) {
686 // First, see if the function has already been added to the current module.
687 if (auto *F = TheModule->getFunction(Name))
688 return F;
689
690 // If not, check whether we can codegen the declaration from some existing
691 // prototype.
692 auto FI = FunctionProtos.find(Name);
693 if (FI != FunctionProtos.end())
694 return FI->second->codegen();
695
696 // If no existing prototype exists, return null.
697 return nullptr;
698}
699
Nick Lewycky109af622009-04-12 20:47:23 +0000700/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
701/// the function. This is used for mutable variables etc.
702static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
703 const std::string &VarName) {
704 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
Eric Christopherc0239362014-12-08 18:12:28 +0000705 TheFunction->getEntryBlock().begin());
Owen Anderson55f1c092009-08-13 21:58:54 +0000706 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
707 VarName.c_str());
Nick Lewycky109af622009-04-12 20:47:23 +0000708}
709
Lang Hames2d789c32015-08-26 03:07:41 +0000710Value *NumberExprAST::codegen() {
Owen Anderson69c464d2009-07-27 20:59:43 +0000711 return ConstantFP::get(getGlobalContext(), APFloat(Val));
Nick Lewycky109af622009-04-12 20:47:23 +0000712}
713
Lang Hames2d789c32015-08-26 03:07:41 +0000714Value *VariableExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000715 // Look this variable up in the function.
716 Value *V = NamedValues[Name];
Lang Hames09bf4c12015-08-18 18:11:06 +0000717 if (!V)
Eric Christopherc0239362014-12-08 18:12:28 +0000718 return ErrorV("Unknown variable name");
Nick Lewycky109af622009-04-12 20:47:23 +0000719
720 // Load the value.
721 return Builder.CreateLoad(V, Name.c_str());
722}
723
Lang Hames2d789c32015-08-26 03:07:41 +0000724Value *UnaryExprAST::codegen() {
725 Value *OperandV = Operand->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000726 if (!OperandV)
727 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000728
Lang Hames2d789c32015-08-26 03:07:41 +0000729 Function *F = getFunction(std::string("unary") + Opcode);
Lang Hames09bf4c12015-08-18 18:11:06 +0000730 if (!F)
Nick Lewycky109af622009-04-12 20:47:23 +0000731 return ErrorV("Unknown unary operator");
Eric Christopherc0239362014-12-08 18:12:28 +0000732
Nick Lewycky109af622009-04-12 20:47:23 +0000733 return Builder.CreateCall(F, OperandV, "unop");
734}
735
Lang Hames2d789c32015-08-26 03:07:41 +0000736Value *BinaryExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000737 // Special case '=' because we don't want to emit the LHS as an expression.
738 if (Op == '=') {
739 // Assignment requires the LHS to be an identifier.
Lang Hamese7c28bc2015-04-22 20:41:34 +0000740 // This assume we're building without RTTI because LLVM builds that way by
741 // default. If you build LLVM with RTTI this can be changed to a
742 // dynamic_cast for automatic error checking.
Lang Hames59b0da82015-08-19 18:15:58 +0000743 VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS.get());
Nick Lewycky109af622009-04-12 20:47:23 +0000744 if (!LHSE)
745 return ErrorV("destination of '=' must be a variable");
746 // Codegen the RHS.
Lang Hames2d789c32015-08-26 03:07:41 +0000747 Value *Val = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000748 if (!Val)
749 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000750
751 // Look up the name.
752 Value *Variable = NamedValues[LHSE->getName()];
Lang Hames09bf4c12015-08-18 18:11:06 +0000753 if (!Variable)
Eric Christopherc0239362014-12-08 18:12:28 +0000754 return ErrorV("Unknown variable name");
Nick Lewycky109af622009-04-12 20:47:23 +0000755
756 Builder.CreateStore(Val, Variable);
757 return Val;
758 }
Eric Christopherc0239362014-12-08 18:12:28 +0000759
Lang Hames2d789c32015-08-26 03:07:41 +0000760 Value *L = LHS->codegen();
761 Value *R = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000762 if (!L || !R)
763 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000764
Nick Lewycky109af622009-04-12 20:47:23 +0000765 switch (Op) {
Eric Christopherc0239362014-12-08 18:12:28 +0000766 case '+':
767 return Builder.CreateFAdd(L, R, "addtmp");
768 case '-':
769 return Builder.CreateFSub(L, R, "subtmp");
770 case '*':
771 return Builder.CreateFMul(L, R, "multmp");
Nick Lewycky109af622009-04-12 20:47:23 +0000772 case '<':
773 L = Builder.CreateFCmpULT(L, R, "cmptmp");
774 // Convert bool 0/1 to double 0.0 or 1.0
Owen Anderson55f1c092009-08-13 21:58:54 +0000775 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
776 "booltmp");
Eric Christopherc0239362014-12-08 18:12:28 +0000777 default:
778 break;
Nick Lewycky109af622009-04-12 20:47:23 +0000779 }
Eric Christopherc0239362014-12-08 18:12:28 +0000780
Nick Lewycky109af622009-04-12 20:47:23 +0000781 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
782 // a call to it.
Lang Hames2d789c32015-08-26 03:07:41 +0000783 Function *F = getFunction(std::string("binary") + Op);
Nick Lewycky109af622009-04-12 20:47:23 +0000784 assert(F && "binary operator not found!");
Eric Christopherc0239362014-12-08 18:12:28 +0000785
Lang Hames59b0da82015-08-19 18:15:58 +0000786 Value *Ops[] = {L, R};
Francois Pichetc5d10502011-07-15 10:59:52 +0000787 return Builder.CreateCall(F, Ops, "binop");
Nick Lewycky109af622009-04-12 20:47:23 +0000788}
789
Lang Hames2d789c32015-08-26 03:07:41 +0000790Value *CallExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000791 // Look up the name in the global module table.
Lang Hames2d789c32015-08-26 03:07:41 +0000792 Function *CalleeF = getFunction(Callee);
Lang Hames09bf4c12015-08-18 18:11:06 +0000793 if (!CalleeF)
Nick Lewycky109af622009-04-12 20:47:23 +0000794 return ErrorV("Unknown function referenced");
Eric Christopherc0239362014-12-08 18:12:28 +0000795
Nick Lewycky109af622009-04-12 20:47:23 +0000796 // If argument mismatch error.
797 if (CalleeF->arg_size() != Args.size())
798 return ErrorV("Incorrect # arguments passed");
799
Eric Christopherc0239362014-12-08 18:12:28 +0000800 std::vector<Value *> ArgsV;
Nick Lewycky109af622009-04-12 20:47:23 +0000801 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Lang Hames2d789c32015-08-26 03:07:41 +0000802 ArgsV.push_back(Args[i]->codegen());
Lang Hames09bf4c12015-08-18 18:11:06 +0000803 if (!ArgsV.back())
804 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000805 }
Eric Christopherc0239362014-12-08 18:12:28 +0000806
Francois Pichetc5d10502011-07-15 10:59:52 +0000807 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
Nick Lewycky109af622009-04-12 20:47:23 +0000808}
809
Lang Hames2d789c32015-08-26 03:07:41 +0000810Value *IfExprAST::codegen() {
811 Value *CondV = Cond->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000812 if (!CondV)
813 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000814
Nick Lewycky109af622009-04-12 20:47:23 +0000815 // Convert condition to a bool by comparing equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000816 CondV = Builder.CreateFCmpONE(
817 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
818
Nick Lewycky109af622009-04-12 20:47:23 +0000819 Function *TheFunction = Builder.GetInsertBlock()->getParent();
Eric Christopherc0239362014-12-08 18:12:28 +0000820
Nick Lewycky109af622009-04-12 20:47:23 +0000821 // Create blocks for the then and else cases. Insert the 'then' block at the
822 // end of the function.
Eric Christopherc0239362014-12-08 18:12:28 +0000823 BasicBlock *ThenBB =
824 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
Owen Anderson55f1c092009-08-13 21:58:54 +0000825 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
826 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
Eric Christopherc0239362014-12-08 18:12:28 +0000827
Nick Lewycky109af622009-04-12 20:47:23 +0000828 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000829
Nick Lewycky109af622009-04-12 20:47:23 +0000830 // Emit then value.
831 Builder.SetInsertPoint(ThenBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000832
Lang Hames2d789c32015-08-26 03:07:41 +0000833 Value *ThenV = Then->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000834 if (!ThenV)
835 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000836
Nick Lewycky109af622009-04-12 20:47:23 +0000837 Builder.CreateBr(MergeBB);
838 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
839 ThenBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000840
Nick Lewycky109af622009-04-12 20:47:23 +0000841 // Emit else block.
842 TheFunction->getBasicBlockList().push_back(ElseBB);
843 Builder.SetInsertPoint(ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000844
Lang Hames2d789c32015-08-26 03:07:41 +0000845 Value *ElseV = Else->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000846 if (!ElseV)
847 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000848
Nick Lewycky109af622009-04-12 20:47:23 +0000849 Builder.CreateBr(MergeBB);
850 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
851 ElseBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000852
Nick Lewycky109af622009-04-12 20:47:23 +0000853 // Emit merge block.
854 TheFunction->getBasicBlockList().push_back(MergeBB);
855 Builder.SetInsertPoint(MergeBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000856 PHINode *PN =
857 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
858
Nick Lewycky109af622009-04-12 20:47:23 +0000859 PN->addIncoming(ThenV, ThenBB);
860 PN->addIncoming(ElseV, ElseBB);
861 return PN;
862}
863
Lang Hames59b0da82015-08-19 18:15:58 +0000864// Output for-loop as:
865// var = alloca double
866// ...
867// start = startexpr
868// store start -> var
869// goto loop
870// loop:
871// ...
872// bodyexpr
873// ...
874// loopend:
875// step = stepexpr
876// endcond = endexpr
877//
878// curvar = load var
879// nextvar = curvar + step
880// store nextvar -> var
881// br endcond, loop, endloop
882// outloop:
Lang Hames2d789c32015-08-26 03:07:41 +0000883Value *ForExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000884 Function *TheFunction = Builder.GetInsertBlock()->getParent();
885
886 // Create an alloca for the variable in the entry block.
887 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
Eric Christopherc0239362014-12-08 18:12:28 +0000888
Nick Lewycky109af622009-04-12 20:47:23 +0000889 // Emit the start code first, without 'variable' in scope.
Lang Hames2d789c32015-08-26 03:07:41 +0000890 Value *StartVal = Start->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000891 if (!StartVal)
892 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000893
Nick Lewycky109af622009-04-12 20:47:23 +0000894 // Store the value into the alloca.
895 Builder.CreateStore(StartVal, Alloca);
Eric Christopherc0239362014-12-08 18:12:28 +0000896
Nick Lewycky109af622009-04-12 20:47:23 +0000897 // Make the new basic block for the loop header, inserting after current
898 // block.
Eric Christopherc0239362014-12-08 18:12:28 +0000899 BasicBlock *LoopBB =
900 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
901
Nick Lewycky109af622009-04-12 20:47:23 +0000902 // Insert an explicit fall through from the current block to the LoopBB.
903 Builder.CreateBr(LoopBB);
904
905 // Start insertion in LoopBB.
906 Builder.SetInsertPoint(LoopBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000907
Nick Lewycky109af622009-04-12 20:47:23 +0000908 // Within the loop, the variable is defined equal to the PHI node. If it
909 // shadows an existing variable, we have to restore it, so save it now.
910 AllocaInst *OldVal = NamedValues[VarName];
911 NamedValues[VarName] = Alloca;
Eric Christopherc0239362014-12-08 18:12:28 +0000912
Nick Lewycky109af622009-04-12 20:47:23 +0000913 // Emit the body of the loop. This, like any other expr, can change the
914 // current BB. Note that we ignore the value computed by the body, but don't
915 // allow an error.
Lang Hames2d789c32015-08-26 03:07:41 +0000916 if (!Body->codegen())
Lang Hames09bf4c12015-08-18 18:11:06 +0000917 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000918
Nick Lewycky109af622009-04-12 20:47:23 +0000919 // Emit the step value.
Lang Hames59b0da82015-08-19 18:15:58 +0000920 Value *StepVal = nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000921 if (Step) {
Lang Hames2d789c32015-08-26 03:07:41 +0000922 StepVal = Step->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000923 if (!StepVal)
924 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000925 } else {
926 // If not specified, use 1.0.
Owen Anderson69c464d2009-07-27 20:59:43 +0000927 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
Nick Lewycky109af622009-04-12 20:47:23 +0000928 }
Eric Christopherc0239362014-12-08 18:12:28 +0000929
Nick Lewycky109af622009-04-12 20:47:23 +0000930 // Compute the end condition.
Lang Hames2d789c32015-08-26 03:07:41 +0000931 Value *EndCond = End->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000932 if (!EndCond)
Lang Hames59b0da82015-08-19 18:15:58 +0000933 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000934
Nick Lewycky109af622009-04-12 20:47:23 +0000935 // Reload, increment, and restore the alloca. This handles the case where
936 // the body of the loop mutates the variable.
937 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
Chris Lattner26d79502010-06-21 22:51:14 +0000938 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
Nick Lewycky109af622009-04-12 20:47:23 +0000939 Builder.CreateStore(NextVar, Alloca);
Eric Christopherc0239362014-12-08 18:12:28 +0000940
Nick Lewycky109af622009-04-12 20:47:23 +0000941 // Convert condition to a bool by comparing equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000942 EndCond = Builder.CreateFCmpONE(
943 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
944
Nick Lewycky109af622009-04-12 20:47:23 +0000945 // Create the "after loop" block and insert it.
Eric Christopherc0239362014-12-08 18:12:28 +0000946 BasicBlock *AfterBB =
947 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
948
Nick Lewycky109af622009-04-12 20:47:23 +0000949 // Insert the conditional branch into the end of LoopEndBB.
950 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000951
Nick Lewycky109af622009-04-12 20:47:23 +0000952 // Any new code will be inserted in AfterBB.
953 Builder.SetInsertPoint(AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000954
Nick Lewycky109af622009-04-12 20:47:23 +0000955 // Restore the unshadowed variable.
956 if (OldVal)
957 NamedValues[VarName] = OldVal;
958 else
959 NamedValues.erase(VarName);
960
Nick Lewycky109af622009-04-12 20:47:23 +0000961 // for expr always returns 0.0.
Owen Anderson55f1c092009-08-13 21:58:54 +0000962 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
Nick Lewycky109af622009-04-12 20:47:23 +0000963}
964
Lang Hames2d789c32015-08-26 03:07:41 +0000965Value *VarExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000966 std::vector<AllocaInst *> OldBindings;
Eric Christopherc0239362014-12-08 18:12:28 +0000967
Nick Lewycky109af622009-04-12 20:47:23 +0000968 Function *TheFunction = Builder.GetInsertBlock()->getParent();
969
970 // Register all variables and emit their initializer.
971 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
972 const std::string &VarName = VarNames[i].first;
Lang Hames09bf4c12015-08-18 18:11:06 +0000973 ExprAST *Init = VarNames[i].second.get();
Eric Christopherc0239362014-12-08 18:12:28 +0000974
Nick Lewycky109af622009-04-12 20:47:23 +0000975 // Emit the initializer before adding the variable to scope, this prevents
976 // the initializer from referencing the variable itself, and permits stuff
977 // like this:
978 // var a = 1 in
979 // var a = a in ... # refers to outer 'a'.
980 Value *InitVal;
981 if (Init) {
Lang Hames2d789c32015-08-26 03:07:41 +0000982 InitVal = Init->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000983 if (!InitVal)
984 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000985 } else { // If not specified, use 0.0.
Owen Anderson69c464d2009-07-27 20:59:43 +0000986 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
Nick Lewycky109af622009-04-12 20:47:23 +0000987 }
Eric Christopherc0239362014-12-08 18:12:28 +0000988
Nick Lewycky109af622009-04-12 20:47:23 +0000989 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
990 Builder.CreateStore(InitVal, Alloca);
991
992 // Remember the old variable binding so that we can restore the binding when
993 // we unrecurse.
994 OldBindings.push_back(NamedValues[VarName]);
Eric Christopherc0239362014-12-08 18:12:28 +0000995
Nick Lewycky109af622009-04-12 20:47:23 +0000996 // Remember this binding.
997 NamedValues[VarName] = Alloca;
998 }
Eric Christopherc0239362014-12-08 18:12:28 +0000999
Nick Lewycky109af622009-04-12 20:47:23 +00001000 // Codegen the body, now that all vars are in scope.
Lang Hames2d789c32015-08-26 03:07:41 +00001001 Value *BodyVal = Body->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001002 if (!BodyVal)
1003 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +00001004
Nick Lewycky109af622009-04-12 20:47:23 +00001005 // Pop all our variables from scope.
1006 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1007 NamedValues[VarNames[i].first] = OldBindings[i];
1008
1009 // Return the body computation.
1010 return BodyVal;
1011}
1012
Lang Hames2d789c32015-08-26 03:07:41 +00001013Function *PrototypeAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +00001014 // Make the function type: double(double,double) etc.
Eric Christopherc0239362014-12-08 18:12:28 +00001015 std::vector<Type *> Doubles(Args.size(),
1016 Type::getDoubleTy(getGlobalContext()));
1017 FunctionType *FT =
1018 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
1019
1020 Function *F =
Lang Hames2d789c32015-08-26 03:07:41 +00001021 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
Eric Christopherc0239362014-12-08 18:12:28 +00001022
Nick Lewycky109af622009-04-12 20:47:23 +00001023 // Set names for all arguments.
1024 unsigned Idx = 0;
Lang Hames2d789c32015-08-26 03:07:41 +00001025 for (auto &Arg : F->args())
1026 Arg.setName(Args[Idx++]);
Eric Christopherc0239362014-12-08 18:12:28 +00001027
Nick Lewycky109af622009-04-12 20:47:23 +00001028 return F;
1029}
1030
Lang Hames2d789c32015-08-26 03:07:41 +00001031Function *FunctionAST::codegen() {
1032 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
1033 // reference to it for use below.
1034 auto &P = *Proto;
1035 FunctionProtos[Proto->getName()] = std::move(Proto);
1036 Function *TheFunction = getFunction(P.getName());
Lang Hames09bf4c12015-08-18 18:11:06 +00001037 if (!TheFunction)
1038 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +00001039
Nick Lewycky109af622009-04-12 20:47:23 +00001040 // If this is an operator, install it.
Lang Hames2d789c32015-08-26 03:07:41 +00001041 if (P.isBinaryOp())
1042 BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +00001043
Nick Lewycky109af622009-04-12 20:47:23 +00001044 // Create a new basic block to start insertion into.
Owen Anderson55f1c092009-08-13 21:58:54 +00001045 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
Nick Lewycky109af622009-04-12 20:47:23 +00001046 Builder.SetInsertPoint(BB);
Eric Christopherc0239362014-12-08 18:12:28 +00001047
Lang Hames2d789c32015-08-26 03:07:41 +00001048 // Record the function arguments in the NamedValues map.
1049 NamedValues.clear();
1050 for (auto &Arg : TheFunction->args()) {
1051 // Create an alloca for this variable.
1052 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName());
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001053
Lang Hames2d789c32015-08-26 03:07:41 +00001054 // Store the initial value into the alloca.
1055 Builder.CreateStore(&Arg, Alloca);
1056
1057 // Add arguments to variable symbol table.
1058 NamedValues[Arg.getName()] = Alloca;
1059 }
1060
1061 if (Value *RetVal = Body->codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001062 // Finish off the function.
1063 Builder.CreateRet(RetVal);
1064
1065 // Validate the generated code, checking for consistency.
1066 verifyFunction(*TheFunction);
1067
Lang Hames2d789c32015-08-26 03:07:41 +00001068 // Run the optimizer on the function.
Nick Lewycky109af622009-04-12 20:47:23 +00001069 TheFPM->run(*TheFunction);
Eric Christopherc0239362014-12-08 18:12:28 +00001070
Nick Lewycky109af622009-04-12 20:47:23 +00001071 return TheFunction;
1072 }
Eric Christopherc0239362014-12-08 18:12:28 +00001073
Nick Lewycky109af622009-04-12 20:47:23 +00001074 // Error reading body, remove function.
1075 TheFunction->eraseFromParent();
1076
Lang Hames2d789c32015-08-26 03:07:41 +00001077 if (P.isBinaryOp())
Nick Lewycky109af622009-04-12 20:47:23 +00001078 BinopPrecedence.erase(Proto->getOperatorName());
Lang Hames09bf4c12015-08-18 18:11:06 +00001079 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +00001080}
1081
1082//===----------------------------------------------------------------------===//
1083// Top-Level parsing and JIT Driver
1084//===----------------------------------------------------------------------===//
1085
Lang Hames2d789c32015-08-26 03:07:41 +00001086static void InitializeModuleAndPassManager() {
1087 // Open a new module.
1088 TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
1089 TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
1090
1091 // Create a new pass manager attached to it.
1092 TheFPM = llvm::make_unique<legacy::FunctionPassManager>(TheModule.get());
1093
Lang Hames2d789c32015-08-26 03:07:41 +00001094 // Do simple "peephole" optimizations and bit-twiddling optzns.
1095 TheFPM->add(createInstructionCombiningPass());
1096 // Reassociate expressions.
1097 TheFPM->add(createReassociatePass());
1098 // Eliminate Common SubExpressions.
1099 TheFPM->add(createGVNPass());
1100 // Simplify the control flow graph (deleting unreachable blocks, etc).
1101 TheFPM->add(createCFGSimplificationPass());
1102
1103 TheFPM->doInitialization();
1104}
Nick Lewycky109af622009-04-12 20:47:23 +00001105
1106static void HandleDefinition() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001107 if (auto FnAST = ParseDefinition()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001108 if (auto *FnIR = FnAST->codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001109 fprintf(stderr, "Read function definition:");
Lang Hames09bf4c12015-08-18 18:11:06 +00001110 FnIR->dump();
Lang Hames2d789c32015-08-26 03:07:41 +00001111 TheJIT->addModule(std::move(TheModule));
1112 InitializeModuleAndPassManager();
Nick Lewycky109af622009-04-12 20:47:23 +00001113 }
1114 } else {
1115 // Skip token for error recovery.
1116 getNextToken();
1117 }
1118}
1119
1120static void HandleExtern() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001121 if (auto ProtoAST = ParseExtern()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001122 if (auto *FnIR = ProtoAST->codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001123 fprintf(stderr, "Read extern: ");
Lang Hames09bf4c12015-08-18 18:11:06 +00001124 FnIR->dump();
Lang Hames2d789c32015-08-26 03:07:41 +00001125 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
Nick Lewycky109af622009-04-12 20:47:23 +00001126 }
1127 } else {
1128 // Skip token for error recovery.
1129 getNextToken();
1130 }
1131}
1132
1133static void HandleTopLevelExpression() {
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001134 // Evaluate a top-level expression into an anonymous function.
Lang Hames09bf4c12015-08-18 18:11:06 +00001135 if (auto FnAST = ParseTopLevelExpr()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001136 if (FnAST->codegen()) {
Eric Christopherc0239362014-12-08 18:12:28 +00001137
Lang Hames2d789c32015-08-26 03:07:41 +00001138 // JIT the module containing the anonymous expression, keeping a handle so
1139 // we can free it later.
1140 auto H = TheJIT->addModule(std::move(TheModule));
1141 InitializeModuleAndPassManager();
1142
1143 // Search the JIT for the __anon_expr symbol.
1144 auto ExprSymbol = TheJIT->findSymbol("__anon_expr");
1145 assert(ExprSymbol && "Function not found");
1146
1147 // Get the symbol's address and cast it to the right type (takes no
1148 // arguments, returns a double) so we can call it as a native function.
1149 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
Nick Lewycky109af622009-04-12 20:47:23 +00001150 fprintf(stderr, "Evaluated to %f\n", FP());
Lang Hames2d789c32015-08-26 03:07:41 +00001151
1152 // Delete the anonymous expression module from the JIT.
1153 TheJIT->removeModule(H);
Nick Lewycky109af622009-04-12 20:47:23 +00001154 }
1155 } else {
1156 // Skip token for error recovery.
1157 getNextToken();
1158 }
1159}
1160
1161/// top ::= definition | external | expression | ';'
1162static void MainLoop() {
1163 while (1) {
1164 fprintf(stderr, "ready> ");
1165 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +00001166 case tok_eof:
1167 return;
Lang Hames59b0da82015-08-19 18:15:58 +00001168 case ';': // ignore top-level semicolons.
Eric Christopherc0239362014-12-08 18:12:28 +00001169 getNextToken();
Lang Hames59b0da82015-08-19 18:15:58 +00001170 break;
Eric Christopherc0239362014-12-08 18:12:28 +00001171 case tok_def:
1172 HandleDefinition();
1173 break;
1174 case tok_extern:
1175 HandleExtern();
1176 break;
1177 default:
1178 HandleTopLevelExpression();
1179 break;
Nick Lewycky109af622009-04-12 20:47:23 +00001180 }
1181 }
1182}
1183
Nick Lewycky109af622009-04-12 20:47:23 +00001184//===----------------------------------------------------------------------===//
1185// "Library" functions that can be "extern'd" from user code.
1186//===----------------------------------------------------------------------===//
1187
1188/// putchard - putchar that takes a double and returns 0.
NAKAMURA Takumiac9d3732015-08-28 03:34:33 +00001189extern "C" double putchard(double X) {
Lang Hamesd76e0672015-08-27 20:31:44 +00001190 fputc((char)X, stderr);
Nick Lewycky109af622009-04-12 20:47:23 +00001191 return 0;
1192}
1193
1194/// printd - printf that takes a double prints it as "%f\n", returning 0.
NAKAMURA Takumiac9d3732015-08-28 03:34:33 +00001195extern "C" double printd(double X) {
Lang Hamesd76e0672015-08-27 20:31:44 +00001196 fprintf(stderr, "%f\n", X);
Nick Lewycky109af622009-04-12 20:47:23 +00001197 return 0;
1198}
1199
1200//===----------------------------------------------------------------------===//
1201// Main driver code.
1202//===----------------------------------------------------------------------===//
1203
1204int main() {
Chris Lattnerd24df242009-06-17 16:48:44 +00001205 InitializeNativeTarget();
Eric Christopher1b74b652014-12-08 18:00:38 +00001206 InitializeNativeTargetAsmPrinter();
1207 InitializeNativeTargetAsmParser();
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001208
Nick Lewycky109af622009-04-12 20:47:23 +00001209 // Install standard binary operators.
1210 // 1 is lowest precedence.
1211 BinopPrecedence['='] = 2;
1212 BinopPrecedence['<'] = 10;
1213 BinopPrecedence['+'] = 20;
1214 BinopPrecedence['-'] = 20;
Eric Christopherc0239362014-12-08 18:12:28 +00001215 BinopPrecedence['*'] = 40; // highest.
Nick Lewycky109af622009-04-12 20:47:23 +00001216
1217 // Prime the first token.
1218 fprintf(stderr, "ready> ");
1219 getNextToken();
1220
Lang Hames2d789c32015-08-26 03:07:41 +00001221 TheJIT = llvm::make_unique<KaleidoscopeJIT>();
Nick Lewycky109af622009-04-12 20:47:23 +00001222
Lang Hames2d789c32015-08-26 03:07:41 +00001223 InitializeModuleAndPassManager();
Reid Klecknerab770042009-08-26 20:58:25 +00001224
1225 // Run the main "interpreter loop" now.
1226 MainLoop();
1227
Nick Lewycky109af622009-04-12 20:47:23 +00001228 return 0;
1229}