blob: e63738f71fef47fab2c3acb67c72e0c97ca80ce4 [file] [log] [blame]
Chandler Carruth605e30e2012-12-04 10:16:57 +00001#include "llvm/Analysis/Passes.h"
Nick Lewycky109af622009-04-12 20:47:23 +00002#include "llvm/ExecutionEngine/ExecutionEngine.h"
Eric Christopher1b74b652014-12-08 18:00:38 +00003#include "llvm/ExecutionEngine/MCJIT.h"
4#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Chandler Carruth005f27a2013-01-02 11:56:33 +00005#include "llvm/IR/DataLayout.h"
6#include "llvm/IR/DerivedTypes.h"
7#include "llvm/IR/IRBuilder.h"
8#include "llvm/IR/LLVMContext.h"
9#include "llvm/IR/Module.h"
Chandler Carruth20d4e6b2014-01-13 09:58:03 +000010#include "llvm/IR/Verifier.h"
Nick Lewycky109af622009-04-12 20:47:23 +000011#include "llvm/PassManager.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000012#include "llvm/Support/TargetSelect.h"
Chandler Carruth605e30e2012-12-04 10:16:57 +000013#include "llvm/Transforms/Scalar.h"
Will Dietz981af002013-10-12 00:55:57 +000014#include <cctype>
Nick Lewycky109af622009-04-12 20:47:23 +000015#include <cstdio>
Nick Lewycky109af622009-04-12 20:47:23 +000016#include <map>
Chandler Carruth605e30e2012-12-04 10:16:57 +000017#include <string>
Nick Lewycky109af622009-04-12 20:47:23 +000018#include <vector>
19using namespace llvm;
20
21//===----------------------------------------------------------------------===//
22// Lexer
23//===----------------------------------------------------------------------===//
24
25// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
26// of these for known things.
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() {}
Nick Lewycky109af622009-04-12 20:47:23 +0000131 virtual Value *Codegen() = 0;
132};
133
134/// NumberExprAST - Expression class for numeric literals like "1.0".
135class NumberExprAST : public ExprAST {
136 double Val;
Eric Christopherc0239362014-12-08 18:12:28 +0000137
Nick Lewycky109af622009-04-12 20:47:23 +0000138public:
139 NumberExprAST(double val) : Val(val) {}
140 virtual Value *Codegen();
141};
142
143/// VariableExprAST - Expression class for referencing a variable, like "a".
144class VariableExprAST : public ExprAST {
145 std::string Name;
Eric Christopherc0239362014-12-08 18:12:28 +0000146
Nick Lewycky109af622009-04-12 20:47:23 +0000147public:
148 VariableExprAST(const std::string &name) : Name(name) {}
149 const std::string &getName() const { return Name; }
150 virtual Value *Codegen();
151};
152
153/// UnaryExprAST - Expression class for a unary operator.
154class UnaryExprAST : public ExprAST {
155 char Opcode;
156 ExprAST *Operand;
Eric Christopherc0239362014-12-08 18:12:28 +0000157
Nick Lewycky109af622009-04-12 20:47:23 +0000158public:
Eric Christopherc0239362014-12-08 18:12:28 +0000159 UnaryExprAST(char opcode, ExprAST *operand)
160 : Opcode(opcode), Operand(operand) {}
Nick Lewycky109af622009-04-12 20:47:23 +0000161 virtual Value *Codegen();
162};
163
164/// BinaryExprAST - Expression class for a binary operator.
165class BinaryExprAST : public ExprAST {
166 char Op;
167 ExprAST *LHS, *RHS;
Eric Christopherc0239362014-12-08 18:12:28 +0000168
Nick Lewycky109af622009-04-12 20:47:23 +0000169public:
Eric Christopherc0239362014-12-08 18:12:28 +0000170 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
171 : Op(op), LHS(lhs), RHS(rhs) {}
Nick Lewycky109af622009-04-12 20:47:23 +0000172 virtual Value *Codegen();
173};
174
175/// CallExprAST - Expression class for function calls.
176class CallExprAST : public ExprAST {
177 std::string Callee;
Eric Christopherc0239362014-12-08 18:12:28 +0000178 std::vector<ExprAST *> Args;
179
Nick Lewycky109af622009-04-12 20:47:23 +0000180public:
Eric Christopherc0239362014-12-08 18:12:28 +0000181 CallExprAST(const std::string &callee, std::vector<ExprAST *> &args)
182 : Callee(callee), Args(args) {}
Nick Lewycky109af622009-04-12 20:47:23 +0000183 virtual Value *Codegen();
184};
185
186/// IfExprAST - Expression class for if/then/else.
187class IfExprAST : public ExprAST {
188 ExprAST *Cond, *Then, *Else;
Eric Christopherc0239362014-12-08 18:12:28 +0000189
Nick Lewycky109af622009-04-12 20:47:23 +0000190public:
191 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
Eric Christopherc0239362014-12-08 18:12:28 +0000192 : Cond(cond), Then(then), Else(_else) {}
Nick Lewycky109af622009-04-12 20:47:23 +0000193 virtual Value *Codegen();
194};
195
196/// ForExprAST - Expression class for for/in.
197class ForExprAST : public ExprAST {
198 std::string VarName;
199 ExprAST *Start, *End, *Step, *Body;
Eric Christopherc0239362014-12-08 18:12:28 +0000200
Nick Lewycky109af622009-04-12 20:47:23 +0000201public:
202 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
203 ExprAST *step, ExprAST *body)
Eric Christopherc0239362014-12-08 18:12:28 +0000204 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
Nick Lewycky109af622009-04-12 20:47:23 +0000205 virtual Value *Codegen();
206};
207
208/// VarExprAST - Expression class for var/in
209class VarExprAST : public ExprAST {
Eric Christopherc0239362014-12-08 18:12:28 +0000210 std::vector<std::pair<std::string, ExprAST *> > VarNames;
Nick Lewycky109af622009-04-12 20:47:23 +0000211 ExprAST *Body;
Eric Christopherc0239362014-12-08 18:12:28 +0000212
Nick Lewycky109af622009-04-12 20:47:23 +0000213public:
Eric Christopherc0239362014-12-08 18:12:28 +0000214 VarExprAST(const std::vector<std::pair<std::string, ExprAST *> > &varnames,
Nick Lewycky109af622009-04-12 20:47:23 +0000215 ExprAST *body)
Eric Christopherc0239362014-12-08 18:12:28 +0000216 : VarNames(varnames), Body(body) {}
217
Nick Lewycky109af622009-04-12 20:47:23 +0000218 virtual Value *Codegen();
219};
220
221/// PrototypeAST - This class represents the "prototype" for a function,
222/// which captures its argument names as well as if it is an operator.
223class PrototypeAST {
224 std::string Name;
225 std::vector<std::string> Args;
226 bool isOperator;
Eric Christopherc0239362014-12-08 18:12:28 +0000227 unsigned Precedence; // Precedence if a binary op.
Nick Lewycky109af622009-04-12 20:47:23 +0000228public:
229 PrototypeAST(const std::string &name, const std::vector<std::string> &args,
230 bool isoperator = false, unsigned prec = 0)
Eric Christopherc0239362014-12-08 18:12:28 +0000231 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
232
Nick Lewycky109af622009-04-12 20:47:23 +0000233 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
234 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
Eric Christopherc0239362014-12-08 18:12:28 +0000235
Nick Lewycky109af622009-04-12 20:47:23 +0000236 char getOperatorName() const {
237 assert(isUnaryOp() || isBinaryOp());
Eric Christopherc0239362014-12-08 18:12:28 +0000238 return Name[Name.size() - 1];
Nick Lewycky109af622009-04-12 20:47:23 +0000239 }
Eric Christopherc0239362014-12-08 18:12:28 +0000240
Nick Lewycky109af622009-04-12 20:47:23 +0000241 unsigned getBinaryPrecedence() const { return Precedence; }
Eric Christopherc0239362014-12-08 18:12:28 +0000242
Nick Lewycky109af622009-04-12 20:47:23 +0000243 Function *Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000244
Nick Lewycky109af622009-04-12 20:47:23 +0000245 void CreateArgumentAllocas(Function *F);
246};
247
248/// FunctionAST - This class represents a function definition itself.
249class FunctionAST {
250 PrototypeAST *Proto;
251 ExprAST *Body;
Eric Christopherc0239362014-12-08 18:12:28 +0000252
Nick Lewycky109af622009-04-12 20:47:23 +0000253public:
Eric Christopherc0239362014-12-08 18:12:28 +0000254 FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
255
Nick Lewycky109af622009-04-12 20:47:23 +0000256 Function *Codegen();
257};
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000258} // end anonymous namespace
Nick Lewycky109af622009-04-12 20:47:23 +0000259
260//===----------------------------------------------------------------------===//
261// Parser
262//===----------------------------------------------------------------------===//
263
264/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000265/// token the parser is looking at. getNextToken reads another token from the
Nick Lewycky109af622009-04-12 20:47:23 +0000266/// lexer and updates CurTok with its results.
267static int CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000268static int getNextToken() { return CurTok = gettok(); }
Nick Lewycky109af622009-04-12 20:47:23 +0000269
270/// BinopPrecedence - This holds the precedence for each binary operator that is
271/// defined.
272static std::map<char, int> BinopPrecedence;
273
274/// GetTokPrecedence - Get the precedence of the pending binary operator token.
275static int GetTokPrecedence() {
276 if (!isascii(CurTok))
277 return -1;
Eric Christopherc0239362014-12-08 18:12:28 +0000278
Nick Lewycky109af622009-04-12 20:47:23 +0000279 // Make sure it's a declared binop.
280 int TokPrec = BinopPrecedence[CurTok];
Eric Christopherc0239362014-12-08 18:12:28 +0000281 if (TokPrec <= 0)
282 return -1;
Nick Lewycky109af622009-04-12 20:47:23 +0000283 return TokPrec;
284}
285
286/// Error* - These are little helper functions for error handling.
Eric Christopherc0239362014-12-08 18:12:28 +0000287ExprAST *Error(const char *Str) {
288 fprintf(stderr, "Error: %s\n", Str);
289 return 0;
290}
291PrototypeAST *ErrorP(const char *Str) {
292 Error(Str);
293 return 0;
294}
295FunctionAST *ErrorF(const char *Str) {
296 Error(Str);
297 return 0;
298}
Nick Lewycky109af622009-04-12 20:47:23 +0000299
300static ExprAST *ParseExpression();
301
302/// identifierexpr
303/// ::= identifier
304/// ::= identifier '(' expression* ')'
305static ExprAST *ParseIdentifierExpr() {
306 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000307
308 getNextToken(); // eat identifier.
309
Nick Lewycky109af622009-04-12 20:47:23 +0000310 if (CurTok != '(') // Simple variable ref.
311 return new VariableExprAST(IdName);
Eric Christopherc0239362014-12-08 18:12:28 +0000312
Nick Lewycky109af622009-04-12 20:47:23 +0000313 // Call.
Eric Christopherc0239362014-12-08 18:12:28 +0000314 getNextToken(); // eat (
315 std::vector<ExprAST *> Args;
Nick Lewycky109af622009-04-12 20:47:23 +0000316 if (CurTok != ')') {
317 while (1) {
318 ExprAST *Arg = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000319 if (!Arg)
320 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000321 Args.push_back(Arg);
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000322
Eric Christopherc0239362014-12-08 18:12:28 +0000323 if (CurTok == ')')
324 break;
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000325
Nick Lewycky109af622009-04-12 20:47:23 +0000326 if (CurTok != ',')
327 return Error("Expected ')' or ',' in argument list");
328 getNextToken();
329 }
330 }
331
332 // Eat the ')'.
333 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000334
Nick Lewycky109af622009-04-12 20:47:23 +0000335 return new CallExprAST(IdName, Args);
336}
337
338/// numberexpr ::= number
339static ExprAST *ParseNumberExpr() {
340 ExprAST *Result = new NumberExprAST(NumVal);
341 getNextToken(); // consume the number
342 return Result;
343}
344
345/// parenexpr ::= '(' expression ')'
346static ExprAST *ParseParenExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000347 getNextToken(); // eat (.
Nick Lewycky109af622009-04-12 20:47:23 +0000348 ExprAST *V = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000349 if (!V)
350 return 0;
351
Nick Lewycky109af622009-04-12 20:47:23 +0000352 if (CurTok != ')')
353 return Error("expected ')'");
Eric Christopherc0239362014-12-08 18:12:28 +0000354 getNextToken(); // eat ).
Nick Lewycky109af622009-04-12 20:47:23 +0000355 return V;
356}
357
358/// ifexpr ::= 'if' expression 'then' expression 'else' expression
359static ExprAST *ParseIfExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000360 getNextToken(); // eat the if.
361
Nick Lewycky109af622009-04-12 20:47:23 +0000362 // condition.
363 ExprAST *Cond = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000364 if (!Cond)
365 return 0;
366
Nick Lewycky109af622009-04-12 20:47:23 +0000367 if (CurTok != tok_then)
368 return Error("expected then");
Eric Christopherc0239362014-12-08 18:12:28 +0000369 getNextToken(); // eat the then
370
Nick Lewycky109af622009-04-12 20:47:23 +0000371 ExprAST *Then = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000372 if (Then == 0)
373 return 0;
374
Nick Lewycky109af622009-04-12 20:47:23 +0000375 if (CurTok != tok_else)
376 return Error("expected else");
Eric Christopherc0239362014-12-08 18:12:28 +0000377
Nick Lewycky109af622009-04-12 20:47:23 +0000378 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000379
Nick Lewycky109af622009-04-12 20:47:23 +0000380 ExprAST *Else = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000381 if (!Else)
382 return 0;
383
Nick Lewycky109af622009-04-12 20:47:23 +0000384 return new IfExprAST(Cond, Then, Else);
385}
386
387/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
388static ExprAST *ParseForExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000389 getNextToken(); // eat the for.
Nick Lewycky109af622009-04-12 20:47:23 +0000390
391 if (CurTok != tok_identifier)
392 return Error("expected identifier after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000393
Nick Lewycky109af622009-04-12 20:47:23 +0000394 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000395 getNextToken(); // eat identifier.
396
Nick Lewycky109af622009-04-12 20:47:23 +0000397 if (CurTok != '=')
398 return Error("expected '=' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000399 getNextToken(); // eat '='.
400
Nick Lewycky109af622009-04-12 20:47:23 +0000401 ExprAST *Start = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000402 if (Start == 0)
403 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000404 if (CurTok != ',')
405 return Error("expected ',' after for start value");
406 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000407
Nick Lewycky109af622009-04-12 20:47:23 +0000408 ExprAST *End = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000409 if (End == 0)
410 return 0;
411
Nick Lewycky109af622009-04-12 20:47:23 +0000412 // The step value is optional.
413 ExprAST *Step = 0;
414 if (CurTok == ',') {
415 getNextToken();
416 Step = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000417 if (Step == 0)
418 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000419 }
Eric Christopherc0239362014-12-08 18:12:28 +0000420
Nick Lewycky109af622009-04-12 20:47:23 +0000421 if (CurTok != tok_in)
422 return Error("expected 'in' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000423 getNextToken(); // eat 'in'.
424
Nick Lewycky109af622009-04-12 20:47:23 +0000425 ExprAST *Body = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000426 if (Body == 0)
427 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000428
429 return new ForExprAST(IdName, Start, End, Step, Body);
430}
431
Eric Christopherc0239362014-12-08 18:12:28 +0000432/// varexpr ::= 'var' identifier ('=' expression)?
Nick Lewycky109af622009-04-12 20:47:23 +0000433// (',' identifier ('=' expression)?)* 'in' expression
434static ExprAST *ParseVarExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000435 getNextToken(); // eat the var.
Nick Lewycky109af622009-04-12 20:47:23 +0000436
Eric Christopherc0239362014-12-08 18:12:28 +0000437 std::vector<std::pair<std::string, ExprAST *> > VarNames;
Nick Lewycky109af622009-04-12 20:47:23 +0000438
439 // At least one variable name is required.
440 if (CurTok != tok_identifier)
441 return Error("expected identifier after var");
Eric Christopherc0239362014-12-08 18:12:28 +0000442
Nick Lewycky109af622009-04-12 20:47:23 +0000443 while (1) {
444 std::string Name = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000445 getNextToken(); // eat identifier.
Nick Lewycky109af622009-04-12 20:47:23 +0000446
447 // Read the optional initializer.
448 ExprAST *Init = 0;
449 if (CurTok == '=') {
450 getNextToken(); // eat the '='.
Eric Christopherc0239362014-12-08 18:12:28 +0000451
Nick Lewycky109af622009-04-12 20:47:23 +0000452 Init = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000453 if (Init == 0)
454 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000455 }
Eric Christopherc0239362014-12-08 18:12:28 +0000456
Nick Lewycky109af622009-04-12 20:47:23 +0000457 VarNames.push_back(std::make_pair(Name, Init));
Eric Christopherc0239362014-12-08 18:12:28 +0000458
Nick Lewycky109af622009-04-12 20:47:23 +0000459 // End of var list, exit loop.
Eric Christopherc0239362014-12-08 18:12:28 +0000460 if (CurTok != ',')
461 break;
Nick Lewycky109af622009-04-12 20:47:23 +0000462 getNextToken(); // eat the ','.
Eric Christopherc0239362014-12-08 18:12:28 +0000463
Nick Lewycky109af622009-04-12 20:47:23 +0000464 if (CurTok != tok_identifier)
465 return Error("expected identifier list after var");
466 }
Eric Christopherc0239362014-12-08 18:12:28 +0000467
Nick Lewycky109af622009-04-12 20:47:23 +0000468 // At this point, we have to have 'in'.
469 if (CurTok != tok_in)
470 return Error("expected 'in' keyword after 'var'");
Eric Christopherc0239362014-12-08 18:12:28 +0000471 getNextToken(); // eat 'in'.
472
Nick Lewycky109af622009-04-12 20:47:23 +0000473 ExprAST *Body = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000474 if (Body == 0)
475 return 0;
476
Nick Lewycky109af622009-04-12 20:47:23 +0000477 return new VarExprAST(VarNames, Body);
478}
479
Nick Lewycky109af622009-04-12 20:47:23 +0000480/// primary
481/// ::= identifierexpr
482/// ::= numberexpr
483/// ::= parenexpr
484/// ::= ifexpr
485/// ::= forexpr
486/// ::= varexpr
487static ExprAST *ParsePrimary() {
488 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +0000489 default:
490 return Error("unknown token when expecting an expression");
491 case tok_identifier:
492 return ParseIdentifierExpr();
493 case tok_number:
494 return ParseNumberExpr();
495 case '(':
496 return ParseParenExpr();
497 case tok_if:
498 return ParseIfExpr();
499 case tok_for:
500 return ParseForExpr();
501 case tok_var:
502 return ParseVarExpr();
Nick Lewycky109af622009-04-12 20:47:23 +0000503 }
504}
505
506/// unary
507/// ::= primary
508/// ::= '!' unary
509static ExprAST *ParseUnary() {
510 // If the current token is not an operator, it must be a primary expr.
511 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
512 return ParsePrimary();
Eric Christopherc0239362014-12-08 18:12:28 +0000513
Nick Lewycky109af622009-04-12 20:47:23 +0000514 // If this is a unary operator, read it.
515 int Opc = CurTok;
516 getNextToken();
517 if (ExprAST *Operand = ParseUnary())
518 return new UnaryExprAST(Opc, Operand);
519 return 0;
520}
521
522/// binoprhs
523/// ::= ('+' unary)*
524static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
525 // If this is a binop, find its precedence.
526 while (1) {
527 int TokPrec = GetTokPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +0000528
Nick Lewycky109af622009-04-12 20:47:23 +0000529 // If this is a binop that binds at least as tightly as the current binop,
530 // consume it, otherwise we are done.
531 if (TokPrec < ExprPrec)
532 return LHS;
Eric Christopherc0239362014-12-08 18:12:28 +0000533
Nick Lewycky109af622009-04-12 20:47:23 +0000534 // Okay, we know this is a binop.
535 int BinOp = CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000536 getNextToken(); // eat binop
537
Nick Lewycky109af622009-04-12 20:47:23 +0000538 // Parse the unary expression after the binary operator.
539 ExprAST *RHS = ParseUnary();
Eric Christopherc0239362014-12-08 18:12:28 +0000540 if (!RHS)
541 return 0;
542
Nick Lewycky109af622009-04-12 20:47:23 +0000543 // If BinOp binds less tightly with RHS than the operator after RHS, let
544 // the pending operator take RHS as its LHS.
545 int NextPrec = GetTokPrecedence();
546 if (TokPrec < NextPrec) {
Eric Christopherc0239362014-12-08 18:12:28 +0000547 RHS = ParseBinOpRHS(TokPrec + 1, RHS);
548 if (RHS == 0)
549 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000550 }
Eric Christopherc0239362014-12-08 18:12:28 +0000551
Nick Lewycky109af622009-04-12 20:47:23 +0000552 // Merge LHS/RHS.
553 LHS = new BinaryExprAST(BinOp, LHS, RHS);
554 }
555}
556
557/// expression
558/// ::= unary binoprhs
559///
560static ExprAST *ParseExpression() {
561 ExprAST *LHS = ParseUnary();
Eric Christopherc0239362014-12-08 18:12:28 +0000562 if (!LHS)
563 return 0;
564
Nick Lewycky109af622009-04-12 20:47:23 +0000565 return ParseBinOpRHS(0, LHS);
566}
567
568/// prototype
569/// ::= id '(' id* ')'
570/// ::= binary LETTER number? (id, id)
571/// ::= unary LETTER (id)
572static PrototypeAST *ParsePrototype() {
573 std::string FnName;
Eric Christopherc0239362014-12-08 18:12:28 +0000574
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000575 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
Nick Lewycky109af622009-04-12 20:47:23 +0000576 unsigned BinaryPrecedence = 30;
Eric Christopherc0239362014-12-08 18:12:28 +0000577
Nick Lewycky109af622009-04-12 20:47:23 +0000578 switch (CurTok) {
579 default:
580 return ErrorP("Expected function name in prototype");
581 case tok_identifier:
582 FnName = IdentifierStr;
583 Kind = 0;
584 getNextToken();
585 break;
586 case tok_unary:
587 getNextToken();
588 if (!isascii(CurTok))
589 return ErrorP("Expected unary operator");
590 FnName = "unary";
591 FnName += (char)CurTok;
592 Kind = 1;
593 getNextToken();
594 break;
595 case tok_binary:
596 getNextToken();
597 if (!isascii(CurTok))
598 return ErrorP("Expected binary operator");
599 FnName = "binary";
600 FnName += (char)CurTok;
601 Kind = 2;
602 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000603
Nick Lewycky109af622009-04-12 20:47:23 +0000604 // Read the precedence if present.
605 if (CurTok == tok_number) {
606 if (NumVal < 1 || NumVal > 100)
607 return ErrorP("Invalid precedecnce: must be 1..100");
608 BinaryPrecedence = (unsigned)NumVal;
609 getNextToken();
610 }
611 break;
612 }
Eric Christopherc0239362014-12-08 18:12:28 +0000613
Nick Lewycky109af622009-04-12 20:47:23 +0000614 if (CurTok != '(')
615 return ErrorP("Expected '(' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000616
Nick Lewycky109af622009-04-12 20:47:23 +0000617 std::vector<std::string> ArgNames;
618 while (getNextToken() == tok_identifier)
619 ArgNames.push_back(IdentifierStr);
620 if (CurTok != ')')
621 return ErrorP("Expected ')' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000622
Nick Lewycky109af622009-04-12 20:47:23 +0000623 // success.
Eric Christopherc0239362014-12-08 18:12:28 +0000624 getNextToken(); // eat ')'.
625
Nick Lewycky109af622009-04-12 20:47:23 +0000626 // Verify right number of names for operator.
627 if (Kind && ArgNames.size() != Kind)
628 return ErrorP("Invalid number of operands for operator");
Eric Christopherc0239362014-12-08 18:12:28 +0000629
Nick Lewycky109af622009-04-12 20:47:23 +0000630 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
631}
632
633/// definition ::= 'def' prototype expression
634static FunctionAST *ParseDefinition() {
Eric Christopherc0239362014-12-08 18:12:28 +0000635 getNextToken(); // eat def.
Nick Lewycky109af622009-04-12 20:47:23 +0000636 PrototypeAST *Proto = ParsePrototype();
Eric Christopherc0239362014-12-08 18:12:28 +0000637 if (Proto == 0)
638 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000639
640 if (ExprAST *E = ParseExpression())
641 return new FunctionAST(Proto, E);
642 return 0;
643}
644
645/// toplevelexpr ::= expression
646static FunctionAST *ParseTopLevelExpr() {
647 if (ExprAST *E = ParseExpression()) {
648 // Make an anonymous proto.
649 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
650 return new FunctionAST(Proto, E);
651 }
652 return 0;
653}
654
655/// external ::= 'extern' prototype
656static PrototypeAST *ParseExtern() {
Eric Christopherc0239362014-12-08 18:12:28 +0000657 getNextToken(); // eat extern.
Nick Lewycky109af622009-04-12 20:47:23 +0000658 return ParsePrototype();
659}
660
661//===----------------------------------------------------------------------===//
662// Code Generation
663//===----------------------------------------------------------------------===//
664
665static Module *TheModule;
Owen Andersona7714592009-07-08 20:50:47 +0000666static IRBuilder<> Builder(getGlobalContext());
Eric Christopherc0239362014-12-08 18:12:28 +0000667static std::map<std::string, AllocaInst *> NamedValues;
Nick Lewycky109af622009-04-12 20:47:23 +0000668static FunctionPassManager *TheFPM;
669
Eric Christopherc0239362014-12-08 18:12:28 +0000670Value *ErrorV(const char *Str) {
671 Error(Str);
672 return 0;
673}
Nick Lewycky109af622009-04-12 20:47:23 +0000674
675/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
676/// the function. This is used for mutable variables etc.
677static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
678 const std::string &VarName) {
679 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
Eric Christopherc0239362014-12-08 18:12:28 +0000680 TheFunction->getEntryBlock().begin());
Owen Anderson55f1c092009-08-13 21:58:54 +0000681 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
682 VarName.c_str());
Nick Lewycky109af622009-04-12 20:47:23 +0000683}
684
Nick Lewycky109af622009-04-12 20:47:23 +0000685Value *NumberExprAST::Codegen() {
Owen Anderson69c464d2009-07-27 20:59:43 +0000686 return ConstantFP::get(getGlobalContext(), APFloat(Val));
Nick Lewycky109af622009-04-12 20:47:23 +0000687}
688
689Value *VariableExprAST::Codegen() {
690 // Look this variable up in the function.
691 Value *V = NamedValues[Name];
Eric Christopherc0239362014-12-08 18:12:28 +0000692 if (V == 0)
693 return ErrorV("Unknown variable name");
Nick Lewycky109af622009-04-12 20:47:23 +0000694
695 // Load the value.
696 return Builder.CreateLoad(V, Name.c_str());
697}
698
699Value *UnaryExprAST::Codegen() {
700 Value *OperandV = Operand->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000701 if (OperandV == 0)
702 return 0;
703
704 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
Nick Lewycky109af622009-04-12 20:47:23 +0000705 if (F == 0)
706 return ErrorV("Unknown unary operator");
Eric Christopherc0239362014-12-08 18:12:28 +0000707
Nick Lewycky109af622009-04-12 20:47:23 +0000708 return Builder.CreateCall(F, OperandV, "unop");
709}
710
Nick Lewycky109af622009-04-12 20:47:23 +0000711Value *BinaryExprAST::Codegen() {
712 // Special case '=' because we don't want to emit the LHS as an expression.
713 if (Op == '=') {
714 // Assignment requires the LHS to be an identifier.
Eric Christopherc0239362014-12-08 18:12:28 +0000715 VariableExprAST *LHSE = dynamic_cast<VariableExprAST *>(LHS);
Nick Lewycky109af622009-04-12 20:47:23 +0000716 if (!LHSE)
717 return ErrorV("destination of '=' must be a variable");
718 // Codegen the RHS.
719 Value *Val = RHS->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000720 if (Val == 0)
721 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000722
723 // Look up the name.
724 Value *Variable = NamedValues[LHSE->getName()];
Eric Christopherc0239362014-12-08 18:12:28 +0000725 if (Variable == 0)
726 return ErrorV("Unknown variable name");
Nick Lewycky109af622009-04-12 20:47:23 +0000727
728 Builder.CreateStore(Val, Variable);
729 return Val;
730 }
Eric Christopherc0239362014-12-08 18:12:28 +0000731
Nick Lewycky109af622009-04-12 20:47:23 +0000732 Value *L = LHS->Codegen();
733 Value *R = RHS->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000734 if (L == 0 || R == 0)
735 return 0;
736
Nick Lewycky109af622009-04-12 20:47:23 +0000737 switch (Op) {
Eric Christopherc0239362014-12-08 18:12:28 +0000738 case '+':
739 return Builder.CreateFAdd(L, R, "addtmp");
740 case '-':
741 return Builder.CreateFSub(L, R, "subtmp");
742 case '*':
743 return Builder.CreateFMul(L, R, "multmp");
Nick Lewycky109af622009-04-12 20:47:23 +0000744 case '<':
745 L = Builder.CreateFCmpULT(L, R, "cmptmp");
746 // Convert bool 0/1 to double 0.0 or 1.0
Owen Anderson55f1c092009-08-13 21:58:54 +0000747 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
748 "booltmp");
Eric Christopherc0239362014-12-08 18:12:28 +0000749 default:
750 break;
Nick Lewycky109af622009-04-12 20:47:23 +0000751 }
Eric Christopherc0239362014-12-08 18:12:28 +0000752
Nick Lewycky109af622009-04-12 20:47:23 +0000753 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
754 // a call to it.
Eric Christopherc0239362014-12-08 18:12:28 +0000755 Function *F = TheModule->getFunction(std::string("binary") + Op);
Nick Lewycky109af622009-04-12 20:47:23 +0000756 assert(F && "binary operator not found!");
Eric Christopherc0239362014-12-08 18:12:28 +0000757
Nick Lewycky109af622009-04-12 20:47:23 +0000758 Value *Ops[] = { L, R };
Francois Pichetc5d10502011-07-15 10:59:52 +0000759 return Builder.CreateCall(F, Ops, "binop");
Nick Lewycky109af622009-04-12 20:47:23 +0000760}
761
762Value *CallExprAST::Codegen() {
763 // Look up the name in the global module table.
764 Function *CalleeF = TheModule->getFunction(Callee);
765 if (CalleeF == 0)
766 return ErrorV("Unknown function referenced");
Eric Christopherc0239362014-12-08 18:12:28 +0000767
Nick Lewycky109af622009-04-12 20:47:23 +0000768 // If argument mismatch error.
769 if (CalleeF->arg_size() != Args.size())
770 return ErrorV("Incorrect # arguments passed");
771
Eric Christopherc0239362014-12-08 18:12:28 +0000772 std::vector<Value *> ArgsV;
Nick Lewycky109af622009-04-12 20:47:23 +0000773 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
774 ArgsV.push_back(Args[i]->Codegen());
Eric Christopherc0239362014-12-08 18:12:28 +0000775 if (ArgsV.back() == 0)
776 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000777 }
Eric Christopherc0239362014-12-08 18:12:28 +0000778
Francois Pichetc5d10502011-07-15 10:59:52 +0000779 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
Nick Lewycky109af622009-04-12 20:47:23 +0000780}
781
782Value *IfExprAST::Codegen() {
783 Value *CondV = Cond->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000784 if (CondV == 0)
785 return 0;
786
Nick Lewycky109af622009-04-12 20:47:23 +0000787 // Convert condition to a bool by comparing equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000788 CondV = Builder.CreateFCmpONE(
789 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
790
Nick Lewycky109af622009-04-12 20:47:23 +0000791 Function *TheFunction = Builder.GetInsertBlock()->getParent();
Eric Christopherc0239362014-12-08 18:12:28 +0000792
Nick Lewycky109af622009-04-12 20:47:23 +0000793 // Create blocks for the then and else cases. Insert the 'then' block at the
794 // end of the function.
Eric Christopherc0239362014-12-08 18:12:28 +0000795 BasicBlock *ThenBB =
796 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
Owen Anderson55f1c092009-08-13 21:58:54 +0000797 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
798 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
Eric Christopherc0239362014-12-08 18:12:28 +0000799
Nick Lewycky109af622009-04-12 20:47:23 +0000800 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000801
Nick Lewycky109af622009-04-12 20:47:23 +0000802 // Emit then value.
803 Builder.SetInsertPoint(ThenBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000804
Nick Lewycky109af622009-04-12 20:47:23 +0000805 Value *ThenV = Then->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000806 if (ThenV == 0)
807 return 0;
808
Nick Lewycky109af622009-04-12 20:47:23 +0000809 Builder.CreateBr(MergeBB);
810 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
811 ThenBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000812
Nick Lewycky109af622009-04-12 20:47:23 +0000813 // Emit else block.
814 TheFunction->getBasicBlockList().push_back(ElseBB);
815 Builder.SetInsertPoint(ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000816
Nick Lewycky109af622009-04-12 20:47:23 +0000817 Value *ElseV = Else->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000818 if (ElseV == 0)
819 return 0;
820
Nick Lewycky109af622009-04-12 20:47:23 +0000821 Builder.CreateBr(MergeBB);
822 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
823 ElseBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000824
Nick Lewycky109af622009-04-12 20:47:23 +0000825 // Emit merge block.
826 TheFunction->getBasicBlockList().push_back(MergeBB);
827 Builder.SetInsertPoint(MergeBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000828 PHINode *PN =
829 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
830
Nick Lewycky109af622009-04-12 20:47:23 +0000831 PN->addIncoming(ThenV, ThenBB);
832 PN->addIncoming(ElseV, ElseBB);
833 return PN;
834}
835
836Value *ForExprAST::Codegen() {
837 // Output this as:
838 // var = alloca double
839 // ...
840 // start = startexpr
841 // store start -> var
842 // goto loop
Eric Christopherc0239362014-12-08 18:12:28 +0000843 // loop:
Nick Lewycky109af622009-04-12 20:47:23 +0000844 // ...
845 // bodyexpr
846 // ...
847 // loopend:
848 // step = stepexpr
849 // endcond = endexpr
850 //
851 // curvar = load var
852 // nextvar = curvar + step
853 // store nextvar -> var
854 // br endcond, loop, endloop
855 // outloop:
Eric Christopherc0239362014-12-08 18:12:28 +0000856
Nick Lewycky109af622009-04-12 20:47:23 +0000857 Function *TheFunction = Builder.GetInsertBlock()->getParent();
858
859 // Create an alloca for the variable in the entry block.
860 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
Eric Christopherc0239362014-12-08 18:12:28 +0000861
Nick Lewycky109af622009-04-12 20:47:23 +0000862 // Emit the start code first, without 'variable' in scope.
863 Value *StartVal = Start->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000864 if (StartVal == 0)
865 return 0;
866
Nick Lewycky109af622009-04-12 20:47:23 +0000867 // Store the value into the alloca.
868 Builder.CreateStore(StartVal, Alloca);
Eric Christopherc0239362014-12-08 18:12:28 +0000869
Nick Lewycky109af622009-04-12 20:47:23 +0000870 // Make the new basic block for the loop header, inserting after current
871 // block.
Eric Christopherc0239362014-12-08 18:12:28 +0000872 BasicBlock *LoopBB =
873 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
874
Nick Lewycky109af622009-04-12 20:47:23 +0000875 // Insert an explicit fall through from the current block to the LoopBB.
876 Builder.CreateBr(LoopBB);
877
878 // Start insertion in LoopBB.
879 Builder.SetInsertPoint(LoopBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000880
Nick Lewycky109af622009-04-12 20:47:23 +0000881 // Within the loop, the variable is defined equal to the PHI node. If it
882 // shadows an existing variable, we have to restore it, so save it now.
883 AllocaInst *OldVal = NamedValues[VarName];
884 NamedValues[VarName] = Alloca;
Eric Christopherc0239362014-12-08 18:12:28 +0000885
Nick Lewycky109af622009-04-12 20:47:23 +0000886 // Emit the body of the loop. This, like any other expr, can change the
887 // current BB. Note that we ignore the value computed by the body, but don't
888 // allow an error.
889 if (Body->Codegen() == 0)
890 return 0;
Eric Christopherc0239362014-12-08 18:12:28 +0000891
Nick Lewycky109af622009-04-12 20:47:23 +0000892 // Emit the step value.
893 Value *StepVal;
894 if (Step) {
895 StepVal = Step->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000896 if (StepVal == 0)
897 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000898 } else {
899 // If not specified, use 1.0.
Owen Anderson69c464d2009-07-27 20:59:43 +0000900 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
Nick Lewycky109af622009-04-12 20:47:23 +0000901 }
Eric Christopherc0239362014-12-08 18:12:28 +0000902
Nick Lewycky109af622009-04-12 20:47:23 +0000903 // Compute the end condition.
904 Value *EndCond = End->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000905 if (EndCond == 0)
906 return EndCond;
907
Nick Lewycky109af622009-04-12 20:47:23 +0000908 // Reload, increment, and restore the alloca. This handles the case where
909 // the body of the loop mutates the variable.
910 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
Chris Lattner26d79502010-06-21 22:51:14 +0000911 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
Nick Lewycky109af622009-04-12 20:47:23 +0000912 Builder.CreateStore(NextVar, Alloca);
Eric Christopherc0239362014-12-08 18:12:28 +0000913
Nick Lewycky109af622009-04-12 20:47:23 +0000914 // Convert condition to a bool by comparing equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000915 EndCond = Builder.CreateFCmpONE(
916 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
917
Nick Lewycky109af622009-04-12 20:47:23 +0000918 // Create the "after loop" block and insert it.
Eric Christopherc0239362014-12-08 18:12:28 +0000919 BasicBlock *AfterBB =
920 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
921
Nick Lewycky109af622009-04-12 20:47:23 +0000922 // Insert the conditional branch into the end of LoopEndBB.
923 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000924
Nick Lewycky109af622009-04-12 20:47:23 +0000925 // Any new code will be inserted in AfterBB.
926 Builder.SetInsertPoint(AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000927
Nick Lewycky109af622009-04-12 20:47:23 +0000928 // Restore the unshadowed variable.
929 if (OldVal)
930 NamedValues[VarName] = OldVal;
931 else
932 NamedValues.erase(VarName);
933
Nick Lewycky109af622009-04-12 20:47:23 +0000934 // for expr always returns 0.0.
Owen Anderson55f1c092009-08-13 21:58:54 +0000935 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
Nick Lewycky109af622009-04-12 20:47:23 +0000936}
937
938Value *VarExprAST::Codegen() {
939 std::vector<AllocaInst *> OldBindings;
Eric Christopherc0239362014-12-08 18:12:28 +0000940
Nick Lewycky109af622009-04-12 20:47:23 +0000941 Function *TheFunction = Builder.GetInsertBlock()->getParent();
942
943 // Register all variables and emit their initializer.
944 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
945 const std::string &VarName = VarNames[i].first;
946 ExprAST *Init = VarNames[i].second;
Eric Christopherc0239362014-12-08 18:12:28 +0000947
Nick Lewycky109af622009-04-12 20:47:23 +0000948 // Emit the initializer before adding the variable to scope, this prevents
949 // the initializer from referencing the variable itself, and permits stuff
950 // like this:
951 // var a = 1 in
952 // var a = a in ... # refers to outer 'a'.
953 Value *InitVal;
954 if (Init) {
955 InitVal = Init->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000956 if (InitVal == 0)
957 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000958 } else { // If not specified, use 0.0.
Owen Anderson69c464d2009-07-27 20:59:43 +0000959 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
Nick Lewycky109af622009-04-12 20:47:23 +0000960 }
Eric Christopherc0239362014-12-08 18:12:28 +0000961
Nick Lewycky109af622009-04-12 20:47:23 +0000962 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
963 Builder.CreateStore(InitVal, Alloca);
964
965 // Remember the old variable binding so that we can restore the binding when
966 // we unrecurse.
967 OldBindings.push_back(NamedValues[VarName]);
Eric Christopherc0239362014-12-08 18:12:28 +0000968
Nick Lewycky109af622009-04-12 20:47:23 +0000969 // Remember this binding.
970 NamedValues[VarName] = Alloca;
971 }
Eric Christopherc0239362014-12-08 18:12:28 +0000972
Nick Lewycky109af622009-04-12 20:47:23 +0000973 // Codegen the body, now that all vars are in scope.
974 Value *BodyVal = Body->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000975 if (BodyVal == 0)
976 return 0;
977
Nick Lewycky109af622009-04-12 20:47:23 +0000978 // Pop all our variables from scope.
979 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
980 NamedValues[VarNames[i].first] = OldBindings[i];
981
982 // Return the body computation.
983 return BodyVal;
984}
985
Nick Lewycky109af622009-04-12 20:47:23 +0000986Function *PrototypeAST::Codegen() {
987 // Make the function type: double(double,double) etc.
Eric Christopherc0239362014-12-08 18:12:28 +0000988 std::vector<Type *> Doubles(Args.size(),
989 Type::getDoubleTy(getGlobalContext()));
990 FunctionType *FT =
991 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
992
993 Function *F =
994 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
995
Nick Lewycky109af622009-04-12 20:47:23 +0000996 // If F conflicted, there was already something named 'Name'. If it has a
997 // body, don't allow redefinition or reextern.
998 if (F->getName() != Name) {
999 // Delete the one we just made and get the existing one.
1000 F->eraseFromParent();
1001 F = TheModule->getFunction(Name);
Eric Christopherc0239362014-12-08 18:12:28 +00001002
Nick Lewycky109af622009-04-12 20:47:23 +00001003 // If F already has a body, reject this.
1004 if (!F->empty()) {
1005 ErrorF("redefinition of function");
1006 return 0;
1007 }
Eric Christopherc0239362014-12-08 18:12:28 +00001008
Nick Lewycky109af622009-04-12 20:47:23 +00001009 // If F took a different number of args, reject.
1010 if (F->arg_size() != Args.size()) {
1011 ErrorF("redefinition of function with different # args");
1012 return 0;
1013 }
1014 }
Eric Christopherc0239362014-12-08 18:12:28 +00001015
Nick Lewycky109af622009-04-12 20:47:23 +00001016 // Set names for all arguments.
1017 unsigned Idx = 0;
1018 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1019 ++AI, ++Idx)
1020 AI->setName(Args[Idx]);
Eric Christopherc0239362014-12-08 18:12:28 +00001021
Nick Lewycky109af622009-04-12 20:47:23 +00001022 return F;
1023}
1024
1025/// CreateArgumentAllocas - Create an alloca for each argument and register the
1026/// argument in the symbol table so that references to it will succeed.
1027void PrototypeAST::CreateArgumentAllocas(Function *F) {
1028 Function::arg_iterator AI = F->arg_begin();
1029 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1030 // Create an alloca for this variable.
1031 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1032
1033 // Store the initial value into the alloca.
1034 Builder.CreateStore(AI, Alloca);
1035
1036 // Add arguments to variable symbol table.
1037 NamedValues[Args[Idx]] = Alloca;
1038 }
1039}
1040
Nick Lewycky109af622009-04-12 20:47:23 +00001041Function *FunctionAST::Codegen() {
1042 NamedValues.clear();
Eric Christopherc0239362014-12-08 18:12:28 +00001043
Nick Lewycky109af622009-04-12 20:47:23 +00001044 Function *TheFunction = Proto->Codegen();
1045 if (TheFunction == 0)
1046 return 0;
Eric Christopherc0239362014-12-08 18:12:28 +00001047
Nick Lewycky109af622009-04-12 20:47:23 +00001048 // If this is an operator, install it.
1049 if (Proto->isBinaryOp())
1050 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +00001051
Nick Lewycky109af622009-04-12 20:47:23 +00001052 // Create a new basic block to start insertion into.
Owen Anderson55f1c092009-08-13 21:58:54 +00001053 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
Nick Lewycky109af622009-04-12 20:47:23 +00001054 Builder.SetInsertPoint(BB);
Eric Christopherc0239362014-12-08 18:12:28 +00001055
Nick Lewycky109af622009-04-12 20:47:23 +00001056 // Add all arguments to the symbol table and create their allocas.
1057 Proto->CreateArgumentAllocas(TheFunction);
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001058
Nick Lewycky109af622009-04-12 20:47:23 +00001059 if (Value *RetVal = Body->Codegen()) {
1060 // Finish off the function.
1061 Builder.CreateRet(RetVal);
1062
1063 // Validate the generated code, checking for consistency.
1064 verifyFunction(*TheFunction);
1065
1066 // Optimize the function.
1067 TheFPM->run(*TheFunction);
Eric Christopherc0239362014-12-08 18:12:28 +00001068
Nick Lewycky109af622009-04-12 20:47:23 +00001069 return TheFunction;
1070 }
Eric Christopherc0239362014-12-08 18:12:28 +00001071
Nick Lewycky109af622009-04-12 20:47:23 +00001072 // Error reading body, remove function.
1073 TheFunction->eraseFromParent();
1074
1075 if (Proto->isBinaryOp())
1076 BinopPrecedence.erase(Proto->getOperatorName());
1077 return 0;
1078}
1079
1080//===----------------------------------------------------------------------===//
1081// Top-Level parsing and JIT Driver
1082//===----------------------------------------------------------------------===//
1083
1084static ExecutionEngine *TheExecutionEngine;
1085
1086static void HandleDefinition() {
1087 if (FunctionAST *F = ParseDefinition()) {
1088 if (Function *LF = F->Codegen()) {
1089 fprintf(stderr, "Read function definition:");
1090 LF->dump();
1091 }
1092 } else {
1093 // Skip token for error recovery.
1094 getNextToken();
1095 }
1096}
1097
1098static void HandleExtern() {
1099 if (PrototypeAST *P = ParseExtern()) {
1100 if (Function *F = P->Codegen()) {
1101 fprintf(stderr, "Read extern: ");
1102 F->dump();
1103 }
1104 } else {
1105 // Skip token for error recovery.
1106 getNextToken();
1107 }
1108}
1109
1110static void HandleTopLevelExpression() {
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001111 // Evaluate a top-level expression into an anonymous function.
Nick Lewycky109af622009-04-12 20:47:23 +00001112 if (FunctionAST *F = ParseTopLevelExpr()) {
1113 if (Function *LF = F->Codegen()) {
Eric Christopher1b74b652014-12-08 18:00:38 +00001114 TheExecutionEngine->finalizeObject();
Nick Lewycky109af622009-04-12 20:47:23 +00001115 // JIT the function, returning a function pointer.
1116 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
Eric Christopherc0239362014-12-08 18:12:28 +00001117
Nick Lewycky109af622009-04-12 20:47:23 +00001118 // Cast it to the right type (takes no arguments, returns a double) so we
1119 // can call it as a native function.
Chris Lattner0813c0c2009-04-15 00:16:05 +00001120 double (*FP)() = (double (*)())(intptr_t)FPtr;
Nick Lewycky109af622009-04-12 20:47:23 +00001121 fprintf(stderr, "Evaluated to %f\n", FP());
1122 }
1123 } else {
1124 // Skip token for error recovery.
1125 getNextToken();
1126 }
1127}
1128
1129/// top ::= definition | external | expression | ';'
1130static void MainLoop() {
1131 while (1) {
1132 fprintf(stderr, "ready> ");
1133 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +00001134 case tok_eof:
1135 return;
1136 case ';':
1137 getNextToken();
1138 break; // ignore top-level semicolons.
1139 case tok_def:
1140 HandleDefinition();
1141 break;
1142 case tok_extern:
1143 HandleExtern();
1144 break;
1145 default:
1146 HandleTopLevelExpression();
1147 break;
Nick Lewycky109af622009-04-12 20:47:23 +00001148 }
1149 }
1150}
1151
Nick Lewycky109af622009-04-12 20:47:23 +00001152//===----------------------------------------------------------------------===//
1153// "Library" functions that can be "extern'd" from user code.
1154//===----------------------------------------------------------------------===//
1155
1156/// putchard - putchar that takes a double and returns 0.
Eric Christopherc0239362014-12-08 18:12:28 +00001157extern "C" double putchard(double X) {
Nick Lewycky109af622009-04-12 20:47:23 +00001158 putchar((char)X);
1159 return 0;
1160}
1161
1162/// printd - printf that takes a double prints it as "%f\n", returning 0.
Eric Christopherc0239362014-12-08 18:12:28 +00001163extern "C" double printd(double X) {
Nick Lewycky109af622009-04-12 20:47:23 +00001164 printf("%f\n", X);
1165 return 0;
1166}
1167
1168//===----------------------------------------------------------------------===//
1169// Main driver code.
1170//===----------------------------------------------------------------------===//
1171
1172int main() {
Chris Lattnerd24df242009-06-17 16:48:44 +00001173 InitializeNativeTarget();
Eric Christopher1b74b652014-12-08 18:00:38 +00001174 InitializeNativeTargetAsmPrinter();
1175 InitializeNativeTargetAsmParser();
Owen Andersonc277dc42009-07-16 19:05:41 +00001176 LLVMContext &Context = getGlobalContext();
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001177
Nick Lewycky109af622009-04-12 20:47:23 +00001178 // Install standard binary operators.
1179 // 1 is lowest precedence.
1180 BinopPrecedence['='] = 2;
1181 BinopPrecedence['<'] = 10;
1182 BinopPrecedence['+'] = 20;
1183 BinopPrecedence['-'] = 20;
Eric Christopherc0239362014-12-08 18:12:28 +00001184 BinopPrecedence['*'] = 40; // highest.
Nick Lewycky109af622009-04-12 20:47:23 +00001185
1186 // Prime the first token.
1187 fprintf(stderr, "ready> ");
1188 getNextToken();
1189
1190 // Make the module, which holds all the code.
Rafael Espindola2a8a2792014-08-19 04:04:25 +00001191 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1192 TheModule = Owner.get();
Nick Lewycky109af622009-04-12 20:47:23 +00001193
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001194 // Create the JIT. This takes ownership of the module.
Jeffrey Yasskin8a303242010-02-11 19:15:20 +00001195 std::string ErrStr;
Eric Christopherc0239362014-12-08 18:12:28 +00001196 TheExecutionEngine =
1197 EngineBuilder(std::move(Owner))
1198 .setErrorStr(&ErrStr)
1199 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
1200 .create();
Jeffrey Yasskin8a303242010-02-11 19:15:20 +00001201 if (!TheExecutionEngine) {
1202 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1203 exit(1);
1204 }
Reid Klecknere56676a2009-08-24 05:42:21 +00001205
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001206 FunctionPassManager OurFPM(TheModule);
Nick Lewycky109af622009-04-12 20:47:23 +00001207
Reid Klecknerab770042009-08-26 20:58:25 +00001208 // Set up the optimizer pipeline. Start with registering info about how the
1209 // target lays out data structures.
Rafael Espindola339430f2014-02-25 23:25:17 +00001210 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
Rafael Espindolac435adc2014-09-10 21:27:43 +00001211 OurFPM.add(new DataLayoutPass());
Dan Gohman56f3a4c2010-11-15 18:41:10 +00001212 // Provide basic AliasAnalysis support for GVN.
1213 OurFPM.add(createBasicAliasAnalysisPass());
Reid Klecknerab770042009-08-26 20:58:25 +00001214 // Promote allocas to registers.
1215 OurFPM.add(createPromoteMemoryToRegisterPass());
1216 // Do simple "peephole" optimizations and bit-twiddling optzns.
1217 OurFPM.add(createInstructionCombiningPass());
1218 // Reassociate expressions.
1219 OurFPM.add(createReassociatePass());
1220 // Eliminate Common SubExpressions.
1221 OurFPM.add(createGVNPass());
1222 // Simplify the control flow graph (deleting unreachable blocks, etc).
1223 OurFPM.add(createCFGSimplificationPass());
Eli Friedmane04169c2009-07-20 14:50:07 +00001224
Reid Klecknerab770042009-08-26 20:58:25 +00001225 OurFPM.doInitialization();
Nick Lewycky109af622009-04-12 20:47:23 +00001226
Reid Klecknerab770042009-08-26 20:58:25 +00001227 // Set the global so the code gen can use this.
1228 TheFPM = &OurFPM;
1229
1230 // Run the main "interpreter loop" now.
1231 MainLoop();
1232
1233 TheFPM = 0;
1234
1235 // Print out all of the generated code.
1236 TheModule->dump();
1237
Nick Lewycky109af622009-04-12 20:47:23 +00001238 return 0;
1239}