blob: d61d880e5403b529cc62ff5c4d4a5106caf18ed5 [file] [log] [blame]
NAKAMURA Takumi85c9bac2015-03-02 01:04:34 +00001#include "llvm/ADT/STLExtras.h"
Chandler Carruth17e0bc32015-08-06 07:33:15 +00002#include "llvm/Analysis/BasicAliasAnalysis.h"
Chandler Carruth605e30e2012-12-04 10:16:57 +00003#include "llvm/Analysis/Passes.h"
Chandler Carruth005f27a2013-01-02 11:56:33 +00004#include "llvm/IR/IRBuilder.h"
5#include "llvm/IR/LLVMContext.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +00006#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth005f27a2013-01-02 11:56:33 +00007#include "llvm/IR/Module.h"
Chandler Carruth20d4e6b2014-01-13 09:58:03 +00008#include "llvm/IR/Verifier.h"
Evan Cheng2bb40352011-08-24 18:08:43 +00009#include "llvm/Support/TargetSelect.h"
Chandler Carruth605e30e2012-12-04 10:16:57 +000010#include "llvm/Transforms/Scalar.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
99 NumVal = strtod(NumStr.c_str(), 0);
100 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}
Lang Hames09bf4c12015-08-18 18:11:06 +0000298std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
Eric Christopherc0239362014-12-08 18:12:28 +0000299 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000300 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000301}
Nick Lewycky109af622009-04-12 20:47:23 +0000302
Lang Hames09bf4c12015-08-18 18:11:06 +0000303static std::unique_ptr<ExprAST> ParseExpression();
Nick Lewycky109af622009-04-12 20:47:23 +0000304
Lang Hames59b0da82015-08-19 18:15:58 +0000305/// numberexpr ::= number
306static std::unique_ptr<ExprAST> ParseNumberExpr() {
307 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
308 getNextToken(); // consume the number
309 return std::move(Result);
310}
311
312/// parenexpr ::= '(' expression ')'
313static std::unique_ptr<ExprAST> ParseParenExpr() {
314 getNextToken(); // eat (.
315 auto V = ParseExpression();
316 if (!V)
317 return nullptr;
318
319 if (CurTok != ')')
320 return Error("expected ')'");
321 getNextToken(); // eat ).
322 return V;
323}
324
Nick Lewycky109af622009-04-12 20:47:23 +0000325/// identifierexpr
326/// ::= identifier
327/// ::= identifier '(' expression* ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000328static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
Nick Lewycky109af622009-04-12 20:47:23 +0000329 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000330
331 getNextToken(); // eat identifier.
332
Nick Lewycky109af622009-04-12 20:47:23 +0000333 if (CurTok != '(') // Simple variable ref.
Lang Hames09bf4c12015-08-18 18:11:06 +0000334 return llvm::make_unique<VariableExprAST>(IdName);
Eric Christopherc0239362014-12-08 18:12:28 +0000335
Nick Lewycky109af622009-04-12 20:47:23 +0000336 // Call.
Eric Christopherc0239362014-12-08 18:12:28 +0000337 getNextToken(); // eat (
Lang Hames09bf4c12015-08-18 18:11:06 +0000338 std::vector<std::unique_ptr<ExprAST>> Args;
Nick Lewycky109af622009-04-12 20:47:23 +0000339 if (CurTok != ')') {
340 while (1) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000341 if (auto Arg = ParseExpression())
342 Args.push_back(std::move(Arg));
343 else
344 return nullptr;
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000345
Eric Christopherc0239362014-12-08 18:12:28 +0000346 if (CurTok == ')')
347 break;
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000348
Nick Lewycky109af622009-04-12 20:47:23 +0000349 if (CurTok != ',')
350 return Error("Expected ')' or ',' in argument list");
351 getNextToken();
352 }
353 }
354
355 // Eat the ')'.
356 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000357
Lang Hames09bf4c12015-08-18 18:11:06 +0000358 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
Nick Lewycky109af622009-04-12 20:47:23 +0000359}
360
Nick Lewycky109af622009-04-12 20:47:23 +0000361/// ifexpr ::= 'if' expression 'then' expression 'else' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000362static std::unique_ptr<ExprAST> ParseIfExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000363 getNextToken(); // eat the if.
364
Nick Lewycky109af622009-04-12 20:47:23 +0000365 // condition.
Lang Hames09bf4c12015-08-18 18:11:06 +0000366 auto Cond = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000367 if (!Cond)
Lang Hames09bf4c12015-08-18 18:11:06 +0000368 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000369
Nick Lewycky109af622009-04-12 20:47:23 +0000370 if (CurTok != tok_then)
371 return Error("expected then");
Eric Christopherc0239362014-12-08 18:12:28 +0000372 getNextToken(); // eat the then
373
Lang Hames09bf4c12015-08-18 18:11:06 +0000374 auto Then = ParseExpression();
375 if (!Then)
376 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000377
Nick Lewycky109af622009-04-12 20:47:23 +0000378 if (CurTok != tok_else)
379 return Error("expected else");
Eric Christopherc0239362014-12-08 18:12:28 +0000380
Nick Lewycky109af622009-04-12 20:47:23 +0000381 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000382
Lang Hames09bf4c12015-08-18 18:11:06 +0000383 auto Else = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000384 if (!Else)
Lang Hames09bf4c12015-08-18 18:11:06 +0000385 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000386
Lang Hames09bf4c12015-08-18 18:11:06 +0000387 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
388 std::move(Else));
Nick Lewycky109af622009-04-12 20:47:23 +0000389}
390
391/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000392static std::unique_ptr<ExprAST> ParseForExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000393 getNextToken(); // eat the for.
Nick Lewycky109af622009-04-12 20:47:23 +0000394
395 if (CurTok != tok_identifier)
396 return Error("expected identifier after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000397
Nick Lewycky109af622009-04-12 20:47:23 +0000398 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000399 getNextToken(); // eat identifier.
400
Nick Lewycky109af622009-04-12 20:47:23 +0000401 if (CurTok != '=')
402 return Error("expected '=' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000403 getNextToken(); // eat '='.
404
Lang Hames09bf4c12015-08-18 18:11:06 +0000405 auto Start = ParseExpression();
406 if (!Start)
407 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000408 if (CurTok != ',')
409 return Error("expected ',' after for start value");
410 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000411
Lang Hames09bf4c12015-08-18 18:11:06 +0000412 auto End = ParseExpression();
413 if (!End)
414 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000415
Nick Lewycky109af622009-04-12 20:47:23 +0000416 // The step value is optional.
Lang Hames09bf4c12015-08-18 18:11:06 +0000417 std::unique_ptr<ExprAST> Step;
Nick Lewycky109af622009-04-12 20:47:23 +0000418 if (CurTok == ',') {
419 getNextToken();
420 Step = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000421 if (!Step)
422 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000423 }
Eric Christopherc0239362014-12-08 18:12:28 +0000424
Nick Lewycky109af622009-04-12 20:47:23 +0000425 if (CurTok != tok_in)
426 return Error("expected 'in' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000427 getNextToken(); // eat 'in'.
428
Lang Hames09bf4c12015-08-18 18:11:06 +0000429 auto Body = ParseExpression();
430 if (!Body)
431 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000432
Lang Hames09bf4c12015-08-18 18:11:06 +0000433 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
434 std::move(Step), std::move(Body));
Nick Lewycky109af622009-04-12 20:47:23 +0000435}
436
Eric Christopherc0239362014-12-08 18:12:28 +0000437/// varexpr ::= 'var' identifier ('=' expression)?
Nick Lewycky109af622009-04-12 20:47:23 +0000438// (',' identifier ('=' expression)?)* 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000439static std::unique_ptr<ExprAST> ParseVarExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000440 getNextToken(); // eat the var.
Nick Lewycky109af622009-04-12 20:47:23 +0000441
Lang Hames09bf4c12015-08-18 18:11:06 +0000442 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
Nick Lewycky109af622009-04-12 20:47:23 +0000443
444 // At least one variable name is required.
445 if (CurTok != tok_identifier)
446 return Error("expected identifier after var");
Eric Christopherc0239362014-12-08 18:12:28 +0000447
Nick Lewycky109af622009-04-12 20:47:23 +0000448 while (1) {
449 std::string Name = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000450 getNextToken(); // eat identifier.
Nick Lewycky109af622009-04-12 20:47:23 +0000451
452 // Read the optional initializer.
Lang Hames09bf4c12015-08-18 18:11:06 +0000453 std::unique_ptr<ExprAST> Init = nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000454 if (CurTok == '=') {
455 getNextToken(); // eat the '='.
Eric Christopherc0239362014-12-08 18:12:28 +0000456
Nick Lewycky109af622009-04-12 20:47:23 +0000457 Init = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000458 if (!Init)
459 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000460 }
Eric Christopherc0239362014-12-08 18:12:28 +0000461
Lang Hames09bf4c12015-08-18 18:11:06 +0000462 VarNames.push_back(std::make_pair(Name, std::move(Init)));
Eric Christopherc0239362014-12-08 18:12:28 +0000463
Nick Lewycky109af622009-04-12 20:47:23 +0000464 // End of var list, exit loop.
Eric Christopherc0239362014-12-08 18:12:28 +0000465 if (CurTok != ',')
466 break;
Nick Lewycky109af622009-04-12 20:47:23 +0000467 getNextToken(); // eat the ','.
Eric Christopherc0239362014-12-08 18:12:28 +0000468
Nick Lewycky109af622009-04-12 20:47:23 +0000469 if (CurTok != tok_identifier)
470 return Error("expected identifier list after var");
471 }
Eric Christopherc0239362014-12-08 18:12:28 +0000472
Nick Lewycky109af622009-04-12 20:47:23 +0000473 // At this point, we have to have 'in'.
474 if (CurTok != tok_in)
475 return Error("expected 'in' keyword after 'var'");
Eric Christopherc0239362014-12-08 18:12:28 +0000476 getNextToken(); // eat 'in'.
477
Lang Hames09bf4c12015-08-18 18:11:06 +0000478 auto Body = ParseExpression();
479 if (!Body)
480 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000481
Lang Hames09bf4c12015-08-18 18:11:06 +0000482 return llvm::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
Nick Lewycky109af622009-04-12 20:47:23 +0000483}
484
Nick Lewycky109af622009-04-12 20:47:23 +0000485/// primary
486/// ::= identifierexpr
487/// ::= numberexpr
488/// ::= parenexpr
489/// ::= ifexpr
490/// ::= forexpr
491/// ::= varexpr
Lang Hames09bf4c12015-08-18 18:11:06 +0000492static std::unique_ptr<ExprAST> ParsePrimary() {
Nick Lewycky109af622009-04-12 20:47:23 +0000493 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +0000494 default:
495 return Error("unknown token when expecting an expression");
496 case tok_identifier:
497 return ParseIdentifierExpr();
498 case tok_number:
499 return ParseNumberExpr();
500 case '(':
501 return ParseParenExpr();
502 case tok_if:
503 return ParseIfExpr();
504 case tok_for:
505 return ParseForExpr();
506 case tok_var:
507 return ParseVarExpr();
Nick Lewycky109af622009-04-12 20:47:23 +0000508 }
509}
510
511/// unary
512/// ::= primary
513/// ::= '!' unary
Lang Hames09bf4c12015-08-18 18:11:06 +0000514static std::unique_ptr<ExprAST> ParseUnary() {
Nick Lewycky109af622009-04-12 20:47:23 +0000515 // If the current token is not an operator, it must be a primary expr.
516 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
517 return ParsePrimary();
Eric Christopherc0239362014-12-08 18:12:28 +0000518
Nick Lewycky109af622009-04-12 20:47:23 +0000519 // If this is a unary operator, read it.
520 int Opc = CurTok;
521 getNextToken();
Lang Hames09bf4c12015-08-18 18:11:06 +0000522 if (auto Operand = ParseUnary())
523 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
524 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000525}
526
527/// binoprhs
528/// ::= ('+' unary)*
Lang Hames59b0da82015-08-19 18:15:58 +0000529static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
530 std::unique_ptr<ExprAST> LHS) {
Nick Lewycky109af622009-04-12 20:47:23 +0000531 // If this is a binop, find its precedence.
532 while (1) {
533 int TokPrec = GetTokPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +0000534
Nick Lewycky109af622009-04-12 20:47:23 +0000535 // If this is a binop that binds at least as tightly as the current binop,
536 // consume it, otherwise we are done.
537 if (TokPrec < ExprPrec)
538 return LHS;
Eric Christopherc0239362014-12-08 18:12:28 +0000539
Nick Lewycky109af622009-04-12 20:47:23 +0000540 // Okay, we know this is a binop.
541 int BinOp = CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000542 getNextToken(); // eat binop
543
Nick Lewycky109af622009-04-12 20:47:23 +0000544 // Parse the unary expression after the binary operator.
Lang Hames09bf4c12015-08-18 18:11:06 +0000545 auto RHS = ParseUnary();
Eric Christopherc0239362014-12-08 18:12:28 +0000546 if (!RHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000547 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000548
Nick Lewycky109af622009-04-12 20:47:23 +0000549 // If BinOp binds less tightly with RHS than the operator after RHS, let
550 // the pending operator take RHS as its LHS.
551 int NextPrec = GetTokPrecedence();
552 if (TokPrec < NextPrec) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000553 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
554 if (!RHS)
555 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000556 }
Eric Christopherc0239362014-12-08 18:12:28 +0000557
Nick Lewycky109af622009-04-12 20:47:23 +0000558 // Merge LHS/RHS.
Lang Hames59b0da82015-08-19 18:15:58 +0000559 LHS =
560 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
Nick Lewycky109af622009-04-12 20:47:23 +0000561 }
562}
563
564/// expression
565/// ::= unary binoprhs
566///
Lang Hames09bf4c12015-08-18 18:11:06 +0000567static std::unique_ptr<ExprAST> ParseExpression() {
568 auto LHS = ParseUnary();
Eric Christopherc0239362014-12-08 18:12:28 +0000569 if (!LHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000570 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000571
Lang Hames09bf4c12015-08-18 18:11:06 +0000572 return ParseBinOpRHS(0, std::move(LHS));
Nick Lewycky109af622009-04-12 20:47:23 +0000573}
574
575/// prototype
576/// ::= id '(' id* ')'
577/// ::= binary LETTER number? (id, id)
578/// ::= unary LETTER (id)
Lang Hames09bf4c12015-08-18 18:11:06 +0000579static std::unique_ptr<PrototypeAST> ParsePrototype() {
Nick Lewycky109af622009-04-12 20:47:23 +0000580 std::string FnName;
Eric Christopherc0239362014-12-08 18:12:28 +0000581
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000582 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
Nick Lewycky109af622009-04-12 20:47:23 +0000583 unsigned BinaryPrecedence = 30;
Eric Christopherc0239362014-12-08 18:12:28 +0000584
Nick Lewycky109af622009-04-12 20:47:23 +0000585 switch (CurTok) {
586 default:
587 return ErrorP("Expected function name in prototype");
588 case tok_identifier:
589 FnName = IdentifierStr;
590 Kind = 0;
591 getNextToken();
592 break;
593 case tok_unary:
594 getNextToken();
595 if (!isascii(CurTok))
596 return ErrorP("Expected unary operator");
597 FnName = "unary";
598 FnName += (char)CurTok;
599 Kind = 1;
600 getNextToken();
601 break;
602 case tok_binary:
603 getNextToken();
604 if (!isascii(CurTok))
605 return ErrorP("Expected binary operator");
606 FnName = "binary";
607 FnName += (char)CurTok;
608 Kind = 2;
609 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000610
Nick Lewycky109af622009-04-12 20:47:23 +0000611 // Read the precedence if present.
612 if (CurTok == tok_number) {
613 if (NumVal < 1 || NumVal > 100)
614 return ErrorP("Invalid precedecnce: must be 1..100");
615 BinaryPrecedence = (unsigned)NumVal;
616 getNextToken();
617 }
618 break;
619 }
Eric Christopherc0239362014-12-08 18:12:28 +0000620
Nick Lewycky109af622009-04-12 20:47:23 +0000621 if (CurTok != '(')
622 return ErrorP("Expected '(' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000623
Nick Lewycky109af622009-04-12 20:47:23 +0000624 std::vector<std::string> ArgNames;
625 while (getNextToken() == tok_identifier)
626 ArgNames.push_back(IdentifierStr);
627 if (CurTok != ')')
628 return ErrorP("Expected ')' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000629
Nick Lewycky109af622009-04-12 20:47:23 +0000630 // success.
Eric Christopherc0239362014-12-08 18:12:28 +0000631 getNextToken(); // eat ')'.
632
Nick Lewycky109af622009-04-12 20:47:23 +0000633 // Verify right number of names for operator.
634 if (Kind && ArgNames.size() != Kind)
635 return ErrorP("Invalid number of operands for operator");
Eric Christopherc0239362014-12-08 18:12:28 +0000636
Lang Hames09bf4c12015-08-18 18:11:06 +0000637 return llvm::make_unique<PrototypeAST>(FnName, ArgNames, Kind != 0,
638 BinaryPrecedence);
Nick Lewycky109af622009-04-12 20:47:23 +0000639}
640
641/// definition ::= 'def' prototype expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000642static std::unique_ptr<FunctionAST> ParseDefinition() {
Eric Christopherc0239362014-12-08 18:12:28 +0000643 getNextToken(); // eat def.
Lang Hames09bf4c12015-08-18 18:11:06 +0000644 auto Proto = ParsePrototype();
645 if (!Proto)
646 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000647
Lang Hames09bf4c12015-08-18 18:11:06 +0000648 if (auto E = ParseExpression())
649 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
650 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000651}
652
653/// toplevelexpr ::= expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000654static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
655 if (auto E = ParseExpression()) {
Nick Lewycky109af622009-04-12 20:47:23 +0000656 // Make an anonymous proto.
Lang Hames2d789c32015-08-26 03:07:41 +0000657 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
658 std::vector<std::string>());
Lang Hames09bf4c12015-08-18 18:11:06 +0000659 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
Nick Lewycky109af622009-04-12 20:47:23 +0000660 }
Lang Hames09bf4c12015-08-18 18:11:06 +0000661 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000662}
663
664/// external ::= 'extern' prototype
Lang Hames09bf4c12015-08-18 18:11:06 +0000665static std::unique_ptr<PrototypeAST> ParseExtern() {
Eric Christopherc0239362014-12-08 18:12:28 +0000666 getNextToken(); // eat extern.
Nick Lewycky109af622009-04-12 20:47:23 +0000667 return ParsePrototype();
668}
669
670//===----------------------------------------------------------------------===//
671// Code Generation
672//===----------------------------------------------------------------------===//
673
Lang Hames2d789c32015-08-26 03:07:41 +0000674static std::unique_ptr<Module> TheModule;
Owen Andersona7714592009-07-08 20:50:47 +0000675static IRBuilder<> Builder(getGlobalContext());
Eric Christopherc0239362014-12-08 18:12:28 +0000676static std::map<std::string, AllocaInst *> NamedValues;
Lang Hames2d789c32015-08-26 03:07:41 +0000677static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
678static std::unique_ptr<KaleidoscopeJIT> TheJIT;
679static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
Nick Lewycky109af622009-04-12 20:47:23 +0000680
Eric Christopherc0239362014-12-08 18:12:28 +0000681Value *ErrorV(const char *Str) {
682 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000683 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000684}
Nick Lewycky109af622009-04-12 20:47:23 +0000685
Lang Hames2d789c32015-08-26 03:07:41 +0000686Function *getFunction(std::string Name) {
687 // First, see if the function has already been added to the current module.
688 if (auto *F = TheModule->getFunction(Name))
689 return F;
690
691 // If not, check whether we can codegen the declaration from some existing
692 // prototype.
693 auto FI = FunctionProtos.find(Name);
694 if (FI != FunctionProtos.end())
695 return FI->second->codegen();
696
697 // If no existing prototype exists, return null.
698 return nullptr;
699}
700
Nick Lewycky109af622009-04-12 20:47:23 +0000701/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
702/// the function. This is used for mutable variables etc.
703static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
704 const std::string &VarName) {
705 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
Eric Christopherc0239362014-12-08 18:12:28 +0000706 TheFunction->getEntryBlock().begin());
Owen Anderson55f1c092009-08-13 21:58:54 +0000707 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
708 VarName.c_str());
Nick Lewycky109af622009-04-12 20:47:23 +0000709}
710
Lang Hames2d789c32015-08-26 03:07:41 +0000711Value *NumberExprAST::codegen() {
Owen Anderson69c464d2009-07-27 20:59:43 +0000712 return ConstantFP::get(getGlobalContext(), APFloat(Val));
Nick Lewycky109af622009-04-12 20:47:23 +0000713}
714
Lang Hames2d789c32015-08-26 03:07:41 +0000715Value *VariableExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000716 // Look this variable up in the function.
717 Value *V = NamedValues[Name];
Lang Hames09bf4c12015-08-18 18:11:06 +0000718 if (!V)
Eric Christopherc0239362014-12-08 18:12:28 +0000719 return ErrorV("Unknown variable name");
Nick Lewycky109af622009-04-12 20:47:23 +0000720
721 // Load the value.
722 return Builder.CreateLoad(V, Name.c_str());
723}
724
Lang Hames2d789c32015-08-26 03:07:41 +0000725Value *UnaryExprAST::codegen() {
726 Value *OperandV = Operand->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000727 if (!OperandV)
728 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000729
Lang Hames2d789c32015-08-26 03:07:41 +0000730 Function *F = getFunction(std::string("unary") + Opcode);
Lang Hames09bf4c12015-08-18 18:11:06 +0000731 if (!F)
Nick Lewycky109af622009-04-12 20:47:23 +0000732 return ErrorV("Unknown unary operator");
Eric Christopherc0239362014-12-08 18:12:28 +0000733
Nick Lewycky109af622009-04-12 20:47:23 +0000734 return Builder.CreateCall(F, OperandV, "unop");
735}
736
Lang Hames2d789c32015-08-26 03:07:41 +0000737Value *BinaryExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000738 // Special case '=' because we don't want to emit the LHS as an expression.
739 if (Op == '=') {
740 // Assignment requires the LHS to be an identifier.
Lang Hamese7c28bc2015-04-22 20:41:34 +0000741 // This assume we're building without RTTI because LLVM builds that way by
742 // default. If you build LLVM with RTTI this can be changed to a
743 // dynamic_cast for automatic error checking.
Lang Hames59b0da82015-08-19 18:15:58 +0000744 VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS.get());
Nick Lewycky109af622009-04-12 20:47:23 +0000745 if (!LHSE)
746 return ErrorV("destination of '=' must be a variable");
747 // Codegen the RHS.
Lang Hames2d789c32015-08-26 03:07:41 +0000748 Value *Val = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000749 if (!Val)
750 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000751
752 // Look up the name.
753 Value *Variable = NamedValues[LHSE->getName()];
Lang Hames09bf4c12015-08-18 18:11:06 +0000754 if (!Variable)
Eric Christopherc0239362014-12-08 18:12:28 +0000755 return ErrorV("Unknown variable name");
Nick Lewycky109af622009-04-12 20:47:23 +0000756
757 Builder.CreateStore(Val, Variable);
758 return Val;
759 }
Eric Christopherc0239362014-12-08 18:12:28 +0000760
Lang Hames2d789c32015-08-26 03:07:41 +0000761 Value *L = LHS->codegen();
762 Value *R = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000763 if (!L || !R)
764 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000765
Nick Lewycky109af622009-04-12 20:47:23 +0000766 switch (Op) {
Eric Christopherc0239362014-12-08 18:12:28 +0000767 case '+':
768 return Builder.CreateFAdd(L, R, "addtmp");
769 case '-':
770 return Builder.CreateFSub(L, R, "subtmp");
771 case '*':
772 return Builder.CreateFMul(L, R, "multmp");
Nick Lewycky109af622009-04-12 20:47:23 +0000773 case '<':
774 L = Builder.CreateFCmpULT(L, R, "cmptmp");
775 // Convert bool 0/1 to double 0.0 or 1.0
Owen Anderson55f1c092009-08-13 21:58:54 +0000776 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
777 "booltmp");
Eric Christopherc0239362014-12-08 18:12:28 +0000778 default:
779 break;
Nick Lewycky109af622009-04-12 20:47:23 +0000780 }
Eric Christopherc0239362014-12-08 18:12:28 +0000781
Nick Lewycky109af622009-04-12 20:47:23 +0000782 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
783 // a call to it.
Lang Hames2d789c32015-08-26 03:07:41 +0000784 Function *F = getFunction(std::string("binary") + Op);
Nick Lewycky109af622009-04-12 20:47:23 +0000785 assert(F && "binary operator not found!");
Eric Christopherc0239362014-12-08 18:12:28 +0000786
Lang Hames59b0da82015-08-19 18:15:58 +0000787 Value *Ops[] = {L, R};
Francois Pichetc5d10502011-07-15 10:59:52 +0000788 return Builder.CreateCall(F, Ops, "binop");
Nick Lewycky109af622009-04-12 20:47:23 +0000789}
790
Lang Hames2d789c32015-08-26 03:07:41 +0000791Value *CallExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000792 // Look up the name in the global module table.
Lang Hames2d789c32015-08-26 03:07:41 +0000793 Function *CalleeF = getFunction(Callee);
Lang Hames09bf4c12015-08-18 18:11:06 +0000794 if (!CalleeF)
Nick Lewycky109af622009-04-12 20:47:23 +0000795 return ErrorV("Unknown function referenced");
Eric Christopherc0239362014-12-08 18:12:28 +0000796
Nick Lewycky109af622009-04-12 20:47:23 +0000797 // If argument mismatch error.
798 if (CalleeF->arg_size() != Args.size())
799 return ErrorV("Incorrect # arguments passed");
800
Eric Christopherc0239362014-12-08 18:12:28 +0000801 std::vector<Value *> ArgsV;
Nick Lewycky109af622009-04-12 20:47:23 +0000802 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Lang Hames2d789c32015-08-26 03:07:41 +0000803 ArgsV.push_back(Args[i]->codegen());
Lang Hames09bf4c12015-08-18 18:11:06 +0000804 if (!ArgsV.back())
805 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000806 }
Eric Christopherc0239362014-12-08 18:12:28 +0000807
Francois Pichetc5d10502011-07-15 10:59:52 +0000808 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
Nick Lewycky109af622009-04-12 20:47:23 +0000809}
810
Lang Hames2d789c32015-08-26 03:07:41 +0000811Value *IfExprAST::codegen() {
812 Value *CondV = Cond->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000813 if (!CondV)
814 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000815
Nick Lewycky109af622009-04-12 20:47:23 +0000816 // Convert condition to a bool by comparing equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000817 CondV = Builder.CreateFCmpONE(
818 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
819
Nick Lewycky109af622009-04-12 20:47:23 +0000820 Function *TheFunction = Builder.GetInsertBlock()->getParent();
Eric Christopherc0239362014-12-08 18:12:28 +0000821
Nick Lewycky109af622009-04-12 20:47:23 +0000822 // Create blocks for the then and else cases. Insert the 'then' block at the
823 // end of the function.
Eric Christopherc0239362014-12-08 18:12:28 +0000824 BasicBlock *ThenBB =
825 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
Owen Anderson55f1c092009-08-13 21:58:54 +0000826 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
827 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
Eric Christopherc0239362014-12-08 18:12:28 +0000828
Nick Lewycky109af622009-04-12 20:47:23 +0000829 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000830
Nick Lewycky109af622009-04-12 20:47:23 +0000831 // Emit then value.
832 Builder.SetInsertPoint(ThenBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000833
Lang Hames2d789c32015-08-26 03:07:41 +0000834 Value *ThenV = Then->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000835 if (!ThenV)
836 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000837
Nick Lewycky109af622009-04-12 20:47:23 +0000838 Builder.CreateBr(MergeBB);
839 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
840 ThenBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000841
Nick Lewycky109af622009-04-12 20:47:23 +0000842 // Emit else block.
843 TheFunction->getBasicBlockList().push_back(ElseBB);
844 Builder.SetInsertPoint(ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000845
Lang Hames2d789c32015-08-26 03:07:41 +0000846 Value *ElseV = Else->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000847 if (!ElseV)
848 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000849
Nick Lewycky109af622009-04-12 20:47:23 +0000850 Builder.CreateBr(MergeBB);
851 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
852 ElseBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000853
Nick Lewycky109af622009-04-12 20:47:23 +0000854 // Emit merge block.
855 TheFunction->getBasicBlockList().push_back(MergeBB);
856 Builder.SetInsertPoint(MergeBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000857 PHINode *PN =
858 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
859
Nick Lewycky109af622009-04-12 20:47:23 +0000860 PN->addIncoming(ThenV, ThenBB);
861 PN->addIncoming(ElseV, ElseBB);
862 return PN;
863}
864
Lang Hames59b0da82015-08-19 18:15:58 +0000865// Output for-loop as:
866// var = alloca double
867// ...
868// start = startexpr
869// store start -> var
870// goto loop
871// loop:
872// ...
873// bodyexpr
874// ...
875// loopend:
876// step = stepexpr
877// endcond = endexpr
878//
879// curvar = load var
880// nextvar = curvar + step
881// store nextvar -> var
882// br endcond, loop, endloop
883// outloop:
Lang Hames2d789c32015-08-26 03:07:41 +0000884Value *ForExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000885 Function *TheFunction = Builder.GetInsertBlock()->getParent();
886
887 // Create an alloca for the variable in the entry block.
888 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
Eric Christopherc0239362014-12-08 18:12:28 +0000889
Nick Lewycky109af622009-04-12 20:47:23 +0000890 // Emit the start code first, without 'variable' in scope.
Lang Hames2d789c32015-08-26 03:07:41 +0000891 Value *StartVal = Start->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000892 if (!StartVal)
893 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000894
Nick Lewycky109af622009-04-12 20:47:23 +0000895 // Store the value into the alloca.
896 Builder.CreateStore(StartVal, Alloca);
Eric Christopherc0239362014-12-08 18:12:28 +0000897
Nick Lewycky109af622009-04-12 20:47:23 +0000898 // Make the new basic block for the loop header, inserting after current
899 // block.
Eric Christopherc0239362014-12-08 18:12:28 +0000900 BasicBlock *LoopBB =
901 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
902
Nick Lewycky109af622009-04-12 20:47:23 +0000903 // Insert an explicit fall through from the current block to the LoopBB.
904 Builder.CreateBr(LoopBB);
905
906 // Start insertion in LoopBB.
907 Builder.SetInsertPoint(LoopBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000908
Nick Lewycky109af622009-04-12 20:47:23 +0000909 // Within the loop, the variable is defined equal to the PHI node. If it
910 // shadows an existing variable, we have to restore it, so save it now.
911 AllocaInst *OldVal = NamedValues[VarName];
912 NamedValues[VarName] = Alloca;
Eric Christopherc0239362014-12-08 18:12:28 +0000913
Nick Lewycky109af622009-04-12 20:47:23 +0000914 // Emit the body of the loop. This, like any other expr, can change the
915 // current BB. Note that we ignore the value computed by the body, but don't
916 // allow an error.
Lang Hames2d789c32015-08-26 03:07:41 +0000917 if (!Body->codegen())
Lang Hames09bf4c12015-08-18 18:11:06 +0000918 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000919
Nick Lewycky109af622009-04-12 20:47:23 +0000920 // Emit the step value.
Lang Hames59b0da82015-08-19 18:15:58 +0000921 Value *StepVal = nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000922 if (Step) {
Lang Hames2d789c32015-08-26 03:07:41 +0000923 StepVal = Step->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000924 if (!StepVal)
925 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000926 } else {
927 // If not specified, use 1.0.
Owen Anderson69c464d2009-07-27 20:59:43 +0000928 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
Nick Lewycky109af622009-04-12 20:47:23 +0000929 }
Eric Christopherc0239362014-12-08 18:12:28 +0000930
Nick Lewycky109af622009-04-12 20:47:23 +0000931 // Compute the end condition.
Lang Hames2d789c32015-08-26 03:07:41 +0000932 Value *EndCond = End->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000933 if (!EndCond)
Lang Hames59b0da82015-08-19 18:15:58 +0000934 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000935
Nick Lewycky109af622009-04-12 20:47:23 +0000936 // Reload, increment, and restore the alloca. This handles the case where
937 // the body of the loop mutates the variable.
938 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
Chris Lattner26d79502010-06-21 22:51:14 +0000939 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
Nick Lewycky109af622009-04-12 20:47:23 +0000940 Builder.CreateStore(NextVar, Alloca);
Eric Christopherc0239362014-12-08 18:12:28 +0000941
Nick Lewycky109af622009-04-12 20:47:23 +0000942 // Convert condition to a bool by comparing equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000943 EndCond = Builder.CreateFCmpONE(
944 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
945
Nick Lewycky109af622009-04-12 20:47:23 +0000946 // Create the "after loop" block and insert it.
Eric Christopherc0239362014-12-08 18:12:28 +0000947 BasicBlock *AfterBB =
948 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
949
Nick Lewycky109af622009-04-12 20:47:23 +0000950 // Insert the conditional branch into the end of LoopEndBB.
951 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000952
Nick Lewycky109af622009-04-12 20:47:23 +0000953 // Any new code will be inserted in AfterBB.
954 Builder.SetInsertPoint(AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000955
Nick Lewycky109af622009-04-12 20:47:23 +0000956 // Restore the unshadowed variable.
957 if (OldVal)
958 NamedValues[VarName] = OldVal;
959 else
960 NamedValues.erase(VarName);
961
Nick Lewycky109af622009-04-12 20:47:23 +0000962 // for expr always returns 0.0.
Owen Anderson55f1c092009-08-13 21:58:54 +0000963 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
Nick Lewycky109af622009-04-12 20:47:23 +0000964}
965
Lang Hames2d789c32015-08-26 03:07:41 +0000966Value *VarExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000967 std::vector<AllocaInst *> OldBindings;
Eric Christopherc0239362014-12-08 18:12:28 +0000968
Nick Lewycky109af622009-04-12 20:47:23 +0000969 Function *TheFunction = Builder.GetInsertBlock()->getParent();
970
971 // Register all variables and emit their initializer.
972 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
973 const std::string &VarName = VarNames[i].first;
Lang Hames09bf4c12015-08-18 18:11:06 +0000974 ExprAST *Init = VarNames[i].second.get();
Eric Christopherc0239362014-12-08 18:12:28 +0000975
Nick Lewycky109af622009-04-12 20:47:23 +0000976 // Emit the initializer before adding the variable to scope, this prevents
977 // the initializer from referencing the variable itself, and permits stuff
978 // like this:
979 // var a = 1 in
980 // var a = a in ... # refers to outer 'a'.
981 Value *InitVal;
982 if (Init) {
Lang Hames2d789c32015-08-26 03:07:41 +0000983 InitVal = Init->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000984 if (!InitVal)
985 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000986 } else { // If not specified, use 0.0.
Owen Anderson69c464d2009-07-27 20:59:43 +0000987 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
Nick Lewycky109af622009-04-12 20:47:23 +0000988 }
Eric Christopherc0239362014-12-08 18:12:28 +0000989
Nick Lewycky109af622009-04-12 20:47:23 +0000990 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
991 Builder.CreateStore(InitVal, Alloca);
992
993 // Remember the old variable binding so that we can restore the binding when
994 // we unrecurse.
995 OldBindings.push_back(NamedValues[VarName]);
Eric Christopherc0239362014-12-08 18:12:28 +0000996
Nick Lewycky109af622009-04-12 20:47:23 +0000997 // Remember this binding.
998 NamedValues[VarName] = Alloca;
999 }
Eric Christopherc0239362014-12-08 18:12:28 +00001000
Nick Lewycky109af622009-04-12 20:47:23 +00001001 // Codegen the body, now that all vars are in scope.
Lang Hames2d789c32015-08-26 03:07:41 +00001002 Value *BodyVal = Body->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001003 if (!BodyVal)
1004 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +00001005
Nick Lewycky109af622009-04-12 20:47:23 +00001006 // Pop all our variables from scope.
1007 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1008 NamedValues[VarNames[i].first] = OldBindings[i];
1009
1010 // Return the body computation.
1011 return BodyVal;
1012}
1013
Lang Hames2d789c32015-08-26 03:07:41 +00001014Function *PrototypeAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +00001015 // Make the function type: double(double,double) etc.
Eric Christopherc0239362014-12-08 18:12:28 +00001016 std::vector<Type *> Doubles(Args.size(),
1017 Type::getDoubleTy(getGlobalContext()));
1018 FunctionType *FT =
1019 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
1020
1021 Function *F =
Lang Hames2d789c32015-08-26 03:07:41 +00001022 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
Eric Christopherc0239362014-12-08 18:12:28 +00001023
Nick Lewycky109af622009-04-12 20:47:23 +00001024 // Set names for all arguments.
1025 unsigned Idx = 0;
Lang Hames2d789c32015-08-26 03:07:41 +00001026 for (auto &Arg : F->args())
1027 Arg.setName(Args[Idx++]);
Eric Christopherc0239362014-12-08 18:12:28 +00001028
Nick Lewycky109af622009-04-12 20:47:23 +00001029 return F;
1030}
1031
Lang Hames2d789c32015-08-26 03:07:41 +00001032Function *FunctionAST::codegen() {
1033 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
1034 // reference to it for use below.
1035 auto &P = *Proto;
1036 FunctionProtos[Proto->getName()] = std::move(Proto);
1037 Function *TheFunction = getFunction(P.getName());
Lang Hames09bf4c12015-08-18 18:11:06 +00001038 if (!TheFunction)
1039 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +00001040
Nick Lewycky109af622009-04-12 20:47:23 +00001041 // If this is an operator, install it.
Lang Hames2d789c32015-08-26 03:07:41 +00001042 if (P.isBinaryOp())
1043 BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +00001044
Nick Lewycky109af622009-04-12 20:47:23 +00001045 // Create a new basic block to start insertion into.
Owen Anderson55f1c092009-08-13 21:58:54 +00001046 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
Nick Lewycky109af622009-04-12 20:47:23 +00001047 Builder.SetInsertPoint(BB);
Eric Christopherc0239362014-12-08 18:12:28 +00001048
Lang Hames2d789c32015-08-26 03:07:41 +00001049 // Record the function arguments in the NamedValues map.
1050 NamedValues.clear();
1051 for (auto &Arg : TheFunction->args()) {
1052 // Create an alloca for this variable.
1053 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName());
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001054
Lang Hames2d789c32015-08-26 03:07:41 +00001055 // Store the initial value into the alloca.
1056 Builder.CreateStore(&Arg, Alloca);
1057
1058 // Add arguments to variable symbol table.
1059 NamedValues[Arg.getName()] = Alloca;
1060 }
1061
1062 if (Value *RetVal = Body->codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001063 // Finish off the function.
1064 Builder.CreateRet(RetVal);
1065
1066 // Validate the generated code, checking for consistency.
1067 verifyFunction(*TheFunction);
1068
Lang Hames2d789c32015-08-26 03:07:41 +00001069 // Run the optimizer on the function.
Nick Lewycky109af622009-04-12 20:47:23 +00001070 TheFPM->run(*TheFunction);
Eric Christopherc0239362014-12-08 18:12:28 +00001071
Nick Lewycky109af622009-04-12 20:47:23 +00001072 return TheFunction;
1073 }
Eric Christopherc0239362014-12-08 18:12:28 +00001074
Nick Lewycky109af622009-04-12 20:47:23 +00001075 // Error reading body, remove function.
1076 TheFunction->eraseFromParent();
1077
Lang Hames2d789c32015-08-26 03:07:41 +00001078 if (P.isBinaryOp())
Nick Lewycky109af622009-04-12 20:47:23 +00001079 BinopPrecedence.erase(Proto->getOperatorName());
Lang Hames09bf4c12015-08-18 18:11:06 +00001080 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +00001081}
1082
1083//===----------------------------------------------------------------------===//
1084// Top-Level parsing and JIT Driver
1085//===----------------------------------------------------------------------===//
1086
Lang Hames2d789c32015-08-26 03:07:41 +00001087static void InitializeModuleAndPassManager() {
1088 // Open a new module.
1089 TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
1090 TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
1091
1092 // Create a new pass manager attached to it.
1093 TheFPM = llvm::make_unique<legacy::FunctionPassManager>(TheModule.get());
1094
1095 // Provide basic AliasAnalysis support for GVN.
1096 TheFPM->add(createBasicAliasAnalysisPass());
1097 // Do simple "peephole" optimizations and bit-twiddling optzns.
1098 TheFPM->add(createInstructionCombiningPass());
1099 // Reassociate expressions.
1100 TheFPM->add(createReassociatePass());
1101 // Eliminate Common SubExpressions.
1102 TheFPM->add(createGVNPass());
1103 // Simplify the control flow graph (deleting unreachable blocks, etc).
1104 TheFPM->add(createCFGSimplificationPass());
1105
1106 TheFPM->doInitialization();
1107}
Nick Lewycky109af622009-04-12 20:47:23 +00001108
1109static void HandleDefinition() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001110 if (auto FnAST = ParseDefinition()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001111 if (auto *FnIR = FnAST->codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001112 fprintf(stderr, "Read function definition:");
Lang Hames09bf4c12015-08-18 18:11:06 +00001113 FnIR->dump();
Lang Hames2d789c32015-08-26 03:07:41 +00001114 TheJIT->addModule(std::move(TheModule));
1115 InitializeModuleAndPassManager();
Nick Lewycky109af622009-04-12 20:47:23 +00001116 }
1117 } else {
1118 // Skip token for error recovery.
1119 getNextToken();
1120 }
1121}
1122
1123static void HandleExtern() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001124 if (auto ProtoAST = ParseExtern()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001125 if (auto *FnIR = ProtoAST->codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001126 fprintf(stderr, "Read extern: ");
Lang Hames09bf4c12015-08-18 18:11:06 +00001127 FnIR->dump();
Lang Hames2d789c32015-08-26 03:07:41 +00001128 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
Nick Lewycky109af622009-04-12 20:47:23 +00001129 }
1130 } else {
1131 // Skip token for error recovery.
1132 getNextToken();
1133 }
1134}
1135
1136static void HandleTopLevelExpression() {
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001137 // Evaluate a top-level expression into an anonymous function.
Lang Hames09bf4c12015-08-18 18:11:06 +00001138 if (auto FnAST = ParseTopLevelExpr()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001139 if (FnAST->codegen()) {
Eric Christopherc0239362014-12-08 18:12:28 +00001140
Lang Hames2d789c32015-08-26 03:07:41 +00001141 // JIT the module containing the anonymous expression, keeping a handle so
1142 // we can free it later.
1143 auto H = TheJIT->addModule(std::move(TheModule));
1144 InitializeModuleAndPassManager();
1145
1146 // Search the JIT for the __anon_expr symbol.
1147 auto ExprSymbol = TheJIT->findSymbol("__anon_expr");
1148 assert(ExprSymbol && "Function not found");
1149
1150 // Get the symbol's address and cast it to the right type (takes no
1151 // arguments, returns a double) so we can call it as a native function.
1152 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
Nick Lewycky109af622009-04-12 20:47:23 +00001153 fprintf(stderr, "Evaluated to %f\n", FP());
Lang Hames2d789c32015-08-26 03:07:41 +00001154
1155 // Delete the anonymous expression module from the JIT.
1156 TheJIT->removeModule(H);
Nick Lewycky109af622009-04-12 20:47:23 +00001157 }
1158 } else {
1159 // Skip token for error recovery.
1160 getNextToken();
1161 }
1162}
1163
1164/// top ::= definition | external | expression | ';'
1165static void MainLoop() {
1166 while (1) {
1167 fprintf(stderr, "ready> ");
1168 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +00001169 case tok_eof:
1170 return;
Lang Hames59b0da82015-08-19 18:15:58 +00001171 case ';': // ignore top-level semicolons.
Eric Christopherc0239362014-12-08 18:12:28 +00001172 getNextToken();
Lang Hames59b0da82015-08-19 18:15:58 +00001173 break;
Eric Christopherc0239362014-12-08 18:12:28 +00001174 case tok_def:
1175 HandleDefinition();
1176 break;
1177 case tok_extern:
1178 HandleExtern();
1179 break;
1180 default:
1181 HandleTopLevelExpression();
1182 break;
Nick Lewycky109af622009-04-12 20:47:23 +00001183 }
1184 }
1185}
1186
Nick Lewycky109af622009-04-12 20:47:23 +00001187//===----------------------------------------------------------------------===//
1188// "Library" functions that can be "extern'd" from user code.
1189//===----------------------------------------------------------------------===//
1190
1191/// putchard - putchar that takes a double and returns 0.
Lang Hamesd76e0672015-08-27 20:31:44 +00001192__attribute__((used)) extern "C" double putchard(double X) {
1193 fputc((char)X, stderr);
Nick Lewycky109af622009-04-12 20:47:23 +00001194 return 0;
1195}
1196
1197/// printd - printf that takes a double prints it as "%f\n", returning 0.
Lang Hamesd76e0672015-08-27 20:31:44 +00001198__attribute__((used)) extern "C" double printd(double X) {
1199 fprintf(stderr, "%f\n", X);
Nick Lewycky109af622009-04-12 20:47:23 +00001200 return 0;
1201}
1202
1203//===----------------------------------------------------------------------===//
1204// Main driver code.
1205//===----------------------------------------------------------------------===//
1206
1207int main() {
Chris Lattnerd24df242009-06-17 16:48:44 +00001208 InitializeNativeTarget();
Eric Christopher1b74b652014-12-08 18:00:38 +00001209 InitializeNativeTargetAsmPrinter();
1210 InitializeNativeTargetAsmParser();
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001211
Nick Lewycky109af622009-04-12 20:47:23 +00001212 // Install standard binary operators.
1213 // 1 is lowest precedence.
1214 BinopPrecedence['='] = 2;
1215 BinopPrecedence['<'] = 10;
1216 BinopPrecedence['+'] = 20;
1217 BinopPrecedence['-'] = 20;
Eric Christopherc0239362014-12-08 18:12:28 +00001218 BinopPrecedence['*'] = 40; // highest.
Nick Lewycky109af622009-04-12 20:47:23 +00001219
1220 // Prime the first token.
1221 fprintf(stderr, "ready> ");
1222 getNextToken();
1223
Lang Hames2d789c32015-08-26 03:07:41 +00001224 TheJIT = llvm::make_unique<KaleidoscopeJIT>();
Nick Lewycky109af622009-04-12 20:47:23 +00001225
Lang Hames2d789c32015-08-26 03:07:41 +00001226 InitializeModuleAndPassManager();
Reid Klecknerab770042009-08-26 20:58:25 +00001227
1228 // Run the main "interpreter loop" now.
1229 MainLoop();
1230
Nick Lewycky109af622009-04-12 20:47:23 +00001231 return 0;
1232}