blob: 7a71d015ffd2ebd5369a0c4266cf0157ac98e68f [file] [log] [blame]
NAKAMURA Takumi85c9bac2015-03-02 01:04:34 +00001#include "llvm/ADT/STLExtras.h"
Chandler Carruth605e30e2012-12-04 10:16:57 +00002#include "llvm/Analysis/Passes.h"
Nick Lewycky109af622009-04-12 20:47:23 +00003#include "llvm/ExecutionEngine/ExecutionEngine.h"
Eric Christopher1b74b652014-12-08 18:00:38 +00004#include "llvm/ExecutionEngine/MCJIT.h"
5#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Chandler Carruth005f27a2013-01-02 11:56:33 +00006#include "llvm/IR/DataLayout.h"
7#include "llvm/IR/DerivedTypes.h"
8#include "llvm/IR/IRBuilder.h"
9#include "llvm/IR/LLVMContext.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000010#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth005f27a2013-01-02 11:56:33 +000011#include "llvm/IR/Module.h"
Chandler Carruth20d4e6b2014-01-13 09:58:03 +000012#include "llvm/IR/Verifier.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000013#include "llvm/Support/TargetSelect.h"
Chandler Carruth605e30e2012-12-04 10:16:57 +000014#include "llvm/Transforms/Scalar.h"
Will Dietz981af002013-10-12 00:55:57 +000015#include <cctype>
Nick Lewycky109af622009-04-12 20:47:23 +000016#include <cstdio>
Nick Lewycky109af622009-04-12 20:47:23 +000017#include <map>
Chandler Carruth605e30e2012-12-04 10:16:57 +000018#include <string>
Nick Lewycky109af622009-04-12 20:47:23 +000019#include <vector>
20using namespace llvm;
21
22//===----------------------------------------------------------------------===//
23// Lexer
24//===----------------------------------------------------------------------===//
25
26// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
27// of these for known things.
28enum Token {
29 tok_eof = -1,
30
31 // commands
Eric Christopherc0239362014-12-08 18:12:28 +000032 tok_def = -2,
33 tok_extern = -3,
Nick Lewycky109af622009-04-12 20:47:23 +000034
35 // primary
Eric Christopherc0239362014-12-08 18:12:28 +000036 tok_identifier = -4,
37 tok_number = -5,
38
Nick Lewycky109af622009-04-12 20:47:23 +000039 // control
Eric Christopherc0239362014-12-08 18:12:28 +000040 tok_if = -6,
41 tok_then = -7,
42 tok_else = -8,
43 tok_for = -9,
44 tok_in = -10,
45
Nick Lewycky109af622009-04-12 20:47:23 +000046 // operators
Eric Christopherc0239362014-12-08 18:12:28 +000047 tok_binary = -11,
48 tok_unary = -12,
49
Nick Lewycky109af622009-04-12 20:47:23 +000050 // var definition
51 tok_var = -13
52};
53
Eric Christopherc0239362014-12-08 18:12:28 +000054static std::string IdentifierStr; // Filled in if tok_identifier
55static double NumVal; // Filled in if tok_number
Nick Lewycky109af622009-04-12 20:47:23 +000056
57/// gettok - Return the next token from standard input.
58static int gettok() {
59 static int LastChar = ' ';
60
61 // Skip any whitespace.
62 while (isspace(LastChar))
63 LastChar = getchar();
64
65 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
66 IdentifierStr = LastChar;
67 while (isalnum((LastChar = getchar())))
68 IdentifierStr += LastChar;
69
Eric Christopherc0239362014-12-08 18:12:28 +000070 if (IdentifierStr == "def")
71 return tok_def;
72 if (IdentifierStr == "extern")
73 return tok_extern;
74 if (IdentifierStr == "if")
75 return tok_if;
76 if (IdentifierStr == "then")
77 return tok_then;
78 if (IdentifierStr == "else")
79 return tok_else;
80 if (IdentifierStr == "for")
81 return tok_for;
82 if (IdentifierStr == "in")
83 return tok_in;
84 if (IdentifierStr == "binary")
85 return tok_binary;
86 if (IdentifierStr == "unary")
87 return tok_unary;
88 if (IdentifierStr == "var")
89 return tok_var;
Nick Lewycky109af622009-04-12 20:47:23 +000090 return tok_identifier;
91 }
92
Eric Christopherc0239362014-12-08 18:12:28 +000093 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
Nick Lewycky109af622009-04-12 20:47:23 +000094 std::string NumStr;
95 do {
96 NumStr += LastChar;
97 LastChar = getchar();
98 } while (isdigit(LastChar) || LastChar == '.');
99
100 NumVal = strtod(NumStr.c_str(), 0);
101 return tok_number;
102 }
103
104 if (LastChar == '#') {
105 // Comment until end of line.
Eric Christopherc0239362014-12-08 18:12:28 +0000106 do
107 LastChar = getchar();
Nick Lewycky109af622009-04-12 20:47:23 +0000108 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
Eric Christopherc0239362014-12-08 18:12:28 +0000109
Nick Lewycky109af622009-04-12 20:47:23 +0000110 if (LastChar != EOF)
111 return gettok();
112 }
Eric Christopherc0239362014-12-08 18:12:28 +0000113
Nick Lewycky109af622009-04-12 20:47:23 +0000114 // Check for end of file. Don't eat the EOF.
115 if (LastChar == EOF)
116 return tok_eof;
117
118 // Otherwise, just return the character as its ascii value.
119 int ThisChar = LastChar;
120 LastChar = getchar();
121 return ThisChar;
122}
123
124//===----------------------------------------------------------------------===//
125// Abstract Syntax Tree (aka Parse Tree)
126//===----------------------------------------------------------------------===//
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000127namespace {
Nick Lewycky109af622009-04-12 20:47:23 +0000128/// ExprAST - Base class for all expression nodes.
129class ExprAST {
130public:
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000131 virtual ~ExprAST() {}
Nick Lewycky109af622009-04-12 20:47:23 +0000132 virtual Value *Codegen() = 0;
133};
134
135/// NumberExprAST - Expression class for numeric literals like "1.0".
136class NumberExprAST : public ExprAST {
137 double Val;
Eric Christopherc0239362014-12-08 18:12:28 +0000138
Nick Lewycky109af622009-04-12 20:47:23 +0000139public:
140 NumberExprAST(double val) : Val(val) {}
141 virtual Value *Codegen();
142};
143
144/// VariableExprAST - Expression class for referencing a variable, like "a".
145class VariableExprAST : public ExprAST {
146 std::string Name;
Eric Christopherc0239362014-12-08 18:12:28 +0000147
Nick Lewycky109af622009-04-12 20:47:23 +0000148public:
149 VariableExprAST(const std::string &name) : Name(name) {}
150 const std::string &getName() const { return Name; }
151 virtual Value *Codegen();
152};
153
154/// UnaryExprAST - Expression class for a unary operator.
155class UnaryExprAST : public ExprAST {
156 char Opcode;
157 ExprAST *Operand;
Eric Christopherc0239362014-12-08 18:12:28 +0000158
Nick Lewycky109af622009-04-12 20:47:23 +0000159public:
Eric Christopherc0239362014-12-08 18:12:28 +0000160 UnaryExprAST(char opcode, ExprAST *operand)
161 : Opcode(opcode), Operand(operand) {}
Nick Lewycky109af622009-04-12 20:47:23 +0000162 virtual Value *Codegen();
163};
164
165/// BinaryExprAST - Expression class for a binary operator.
166class BinaryExprAST : public ExprAST {
167 char Op;
168 ExprAST *LHS, *RHS;
Eric Christopherc0239362014-12-08 18:12:28 +0000169
Nick Lewycky109af622009-04-12 20:47:23 +0000170public:
Eric Christopherc0239362014-12-08 18:12:28 +0000171 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
172 : Op(op), LHS(lhs), RHS(rhs) {}
Nick Lewycky109af622009-04-12 20:47:23 +0000173 virtual Value *Codegen();
174};
175
176/// CallExprAST - Expression class for function calls.
177class CallExprAST : public ExprAST {
178 std::string Callee;
Eric Christopherc0239362014-12-08 18:12:28 +0000179 std::vector<ExprAST *> Args;
180
Nick Lewycky109af622009-04-12 20:47:23 +0000181public:
Eric Christopherc0239362014-12-08 18:12:28 +0000182 CallExprAST(const std::string &callee, std::vector<ExprAST *> &args)
183 : Callee(callee), Args(args) {}
Nick Lewycky109af622009-04-12 20:47:23 +0000184 virtual Value *Codegen();
185};
186
187/// IfExprAST - Expression class for if/then/else.
188class IfExprAST : public ExprAST {
189 ExprAST *Cond, *Then, *Else;
Eric Christopherc0239362014-12-08 18:12:28 +0000190
Nick Lewycky109af622009-04-12 20:47:23 +0000191public:
192 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
Eric Christopherc0239362014-12-08 18:12:28 +0000193 : Cond(cond), Then(then), Else(_else) {}
Nick Lewycky109af622009-04-12 20:47:23 +0000194 virtual Value *Codegen();
195};
196
197/// ForExprAST - Expression class for for/in.
198class ForExprAST : public ExprAST {
199 std::string VarName;
200 ExprAST *Start, *End, *Step, *Body;
Eric Christopherc0239362014-12-08 18:12:28 +0000201
Nick Lewycky109af622009-04-12 20:47:23 +0000202public:
203 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
204 ExprAST *step, ExprAST *body)
Eric Christopherc0239362014-12-08 18:12:28 +0000205 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
Nick Lewycky109af622009-04-12 20:47:23 +0000206 virtual Value *Codegen();
207};
208
209/// VarExprAST - Expression class for var/in
210class VarExprAST : public ExprAST {
Eric Christopherc0239362014-12-08 18:12:28 +0000211 std::vector<std::pair<std::string, ExprAST *> > VarNames;
Nick Lewycky109af622009-04-12 20:47:23 +0000212 ExprAST *Body;
Eric Christopherc0239362014-12-08 18:12:28 +0000213
Nick Lewycky109af622009-04-12 20:47:23 +0000214public:
Eric Christopherc0239362014-12-08 18:12:28 +0000215 VarExprAST(const std::vector<std::pair<std::string, ExprAST *> > &varnames,
Nick Lewycky109af622009-04-12 20:47:23 +0000216 ExprAST *body)
Eric Christopherc0239362014-12-08 18:12:28 +0000217 : VarNames(varnames), Body(body) {}
218
Nick Lewycky109af622009-04-12 20:47:23 +0000219 virtual Value *Codegen();
220};
221
222/// PrototypeAST - This class represents the "prototype" for a function,
223/// which captures its argument names as well as if it is an operator.
224class PrototypeAST {
225 std::string Name;
226 std::vector<std::string> Args;
227 bool isOperator;
Eric Christopherc0239362014-12-08 18:12:28 +0000228 unsigned Precedence; // Precedence if a binary op.
Nick Lewycky109af622009-04-12 20:47:23 +0000229public:
230 PrototypeAST(const std::string &name, const std::vector<std::string> &args,
231 bool isoperator = false, unsigned prec = 0)
Eric Christopherc0239362014-12-08 18:12:28 +0000232 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
233
Nick Lewycky109af622009-04-12 20:47:23 +0000234 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
235 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
Eric Christopherc0239362014-12-08 18:12:28 +0000236
Nick Lewycky109af622009-04-12 20:47:23 +0000237 char getOperatorName() const {
238 assert(isUnaryOp() || isBinaryOp());
Eric Christopherc0239362014-12-08 18:12:28 +0000239 return Name[Name.size() - 1];
Nick Lewycky109af622009-04-12 20:47:23 +0000240 }
Eric Christopherc0239362014-12-08 18:12:28 +0000241
Nick Lewycky109af622009-04-12 20:47:23 +0000242 unsigned getBinaryPrecedence() const { return Precedence; }
Eric Christopherc0239362014-12-08 18:12:28 +0000243
Nick Lewycky109af622009-04-12 20:47:23 +0000244 Function *Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000245
Nick Lewycky109af622009-04-12 20:47:23 +0000246 void CreateArgumentAllocas(Function *F);
247};
248
249/// FunctionAST - This class represents a function definition itself.
250class FunctionAST {
251 PrototypeAST *Proto;
252 ExprAST *Body;
Eric Christopherc0239362014-12-08 18:12:28 +0000253
Nick Lewycky109af622009-04-12 20:47:23 +0000254public:
Eric Christopherc0239362014-12-08 18:12:28 +0000255 FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
256
Nick Lewycky109af622009-04-12 20:47:23 +0000257 Function *Codegen();
258};
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000259} // end anonymous namespace
Nick Lewycky109af622009-04-12 20:47:23 +0000260
261//===----------------------------------------------------------------------===//
262// Parser
263//===----------------------------------------------------------------------===//
264
265/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000266/// token the parser is looking at. getNextToken reads another token from the
Nick Lewycky109af622009-04-12 20:47:23 +0000267/// lexer and updates CurTok with its results.
268static int CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000269static int getNextToken() { return CurTok = gettok(); }
Nick Lewycky109af622009-04-12 20:47:23 +0000270
271/// BinopPrecedence - This holds the precedence for each binary operator that is
272/// defined.
273static std::map<char, int> BinopPrecedence;
274
275/// GetTokPrecedence - Get the precedence of the pending binary operator token.
276static int GetTokPrecedence() {
277 if (!isascii(CurTok))
278 return -1;
Eric Christopherc0239362014-12-08 18:12:28 +0000279
Nick Lewycky109af622009-04-12 20:47:23 +0000280 // Make sure it's a declared binop.
281 int TokPrec = BinopPrecedence[CurTok];
Eric Christopherc0239362014-12-08 18:12:28 +0000282 if (TokPrec <= 0)
283 return -1;
Nick Lewycky109af622009-04-12 20:47:23 +0000284 return TokPrec;
285}
286
287/// Error* - These are little helper functions for error handling.
Eric Christopherc0239362014-12-08 18:12:28 +0000288ExprAST *Error(const char *Str) {
289 fprintf(stderr, "Error: %s\n", Str);
290 return 0;
291}
292PrototypeAST *ErrorP(const char *Str) {
293 Error(Str);
294 return 0;
295}
296FunctionAST *ErrorF(const char *Str) {
297 Error(Str);
298 return 0;
299}
Nick Lewycky109af622009-04-12 20:47:23 +0000300
301static ExprAST *ParseExpression();
302
303/// identifierexpr
304/// ::= identifier
305/// ::= identifier '(' expression* ')'
306static ExprAST *ParseIdentifierExpr() {
307 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000308
309 getNextToken(); // eat identifier.
310
Nick Lewycky109af622009-04-12 20:47:23 +0000311 if (CurTok != '(') // Simple variable ref.
312 return new VariableExprAST(IdName);
Eric Christopherc0239362014-12-08 18:12:28 +0000313
Nick Lewycky109af622009-04-12 20:47:23 +0000314 // Call.
Eric Christopherc0239362014-12-08 18:12:28 +0000315 getNextToken(); // eat (
316 std::vector<ExprAST *> Args;
Nick Lewycky109af622009-04-12 20:47:23 +0000317 if (CurTok != ')') {
318 while (1) {
319 ExprAST *Arg = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000320 if (!Arg)
321 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000322 Args.push_back(Arg);
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000323
Eric Christopherc0239362014-12-08 18:12:28 +0000324 if (CurTok == ')')
325 break;
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000326
Nick Lewycky109af622009-04-12 20:47:23 +0000327 if (CurTok != ',')
328 return Error("Expected ')' or ',' in argument list");
329 getNextToken();
330 }
331 }
332
333 // Eat the ')'.
334 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000335
Nick Lewycky109af622009-04-12 20:47:23 +0000336 return new CallExprAST(IdName, Args);
337}
338
339/// numberexpr ::= number
340static ExprAST *ParseNumberExpr() {
341 ExprAST *Result = new NumberExprAST(NumVal);
342 getNextToken(); // consume the number
343 return Result;
344}
345
346/// parenexpr ::= '(' expression ')'
347static ExprAST *ParseParenExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000348 getNextToken(); // eat (.
Nick Lewycky109af622009-04-12 20:47:23 +0000349 ExprAST *V = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000350 if (!V)
351 return 0;
352
Nick Lewycky109af622009-04-12 20:47:23 +0000353 if (CurTok != ')')
354 return Error("expected ')'");
Eric Christopherc0239362014-12-08 18:12:28 +0000355 getNextToken(); // eat ).
Nick Lewycky109af622009-04-12 20:47:23 +0000356 return V;
357}
358
359/// ifexpr ::= 'if' expression 'then' expression 'else' expression
360static ExprAST *ParseIfExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000361 getNextToken(); // eat the if.
362
Nick Lewycky109af622009-04-12 20:47:23 +0000363 // condition.
364 ExprAST *Cond = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000365 if (!Cond)
366 return 0;
367
Nick Lewycky109af622009-04-12 20:47:23 +0000368 if (CurTok != tok_then)
369 return Error("expected then");
Eric Christopherc0239362014-12-08 18:12:28 +0000370 getNextToken(); // eat the then
371
Nick Lewycky109af622009-04-12 20:47:23 +0000372 ExprAST *Then = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000373 if (Then == 0)
374 return 0;
375
Nick Lewycky109af622009-04-12 20:47:23 +0000376 if (CurTok != tok_else)
377 return Error("expected else");
Eric Christopherc0239362014-12-08 18:12:28 +0000378
Nick Lewycky109af622009-04-12 20:47:23 +0000379 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000380
Nick Lewycky109af622009-04-12 20:47:23 +0000381 ExprAST *Else = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000382 if (!Else)
383 return 0;
384
Nick Lewycky109af622009-04-12 20:47:23 +0000385 return new IfExprAST(Cond, Then, Else);
386}
387
388/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
389static ExprAST *ParseForExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000390 getNextToken(); // eat the for.
Nick Lewycky109af622009-04-12 20:47:23 +0000391
392 if (CurTok != tok_identifier)
393 return Error("expected identifier after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000394
Nick Lewycky109af622009-04-12 20:47:23 +0000395 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000396 getNextToken(); // eat identifier.
397
Nick Lewycky109af622009-04-12 20:47:23 +0000398 if (CurTok != '=')
399 return Error("expected '=' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000400 getNextToken(); // eat '='.
401
Nick Lewycky109af622009-04-12 20:47:23 +0000402 ExprAST *Start = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000403 if (Start == 0)
404 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000405 if (CurTok != ',')
406 return Error("expected ',' after for start value");
407 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000408
Nick Lewycky109af622009-04-12 20:47:23 +0000409 ExprAST *End = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000410 if (End == 0)
411 return 0;
412
Nick Lewycky109af622009-04-12 20:47:23 +0000413 // The step value is optional.
414 ExprAST *Step = 0;
415 if (CurTok == ',') {
416 getNextToken();
417 Step = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000418 if (Step == 0)
419 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000420 }
Eric Christopherc0239362014-12-08 18:12:28 +0000421
Nick Lewycky109af622009-04-12 20:47:23 +0000422 if (CurTok != tok_in)
423 return Error("expected 'in' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000424 getNextToken(); // eat 'in'.
425
Nick Lewycky109af622009-04-12 20:47:23 +0000426 ExprAST *Body = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000427 if (Body == 0)
428 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000429
430 return new ForExprAST(IdName, Start, End, Step, Body);
431}
432
Eric Christopherc0239362014-12-08 18:12:28 +0000433/// varexpr ::= 'var' identifier ('=' expression)?
Nick Lewycky109af622009-04-12 20:47:23 +0000434// (',' identifier ('=' expression)?)* 'in' expression
435static ExprAST *ParseVarExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000436 getNextToken(); // eat the var.
Nick Lewycky109af622009-04-12 20:47:23 +0000437
Eric Christopherc0239362014-12-08 18:12:28 +0000438 std::vector<std::pair<std::string, ExprAST *> > VarNames;
Nick Lewycky109af622009-04-12 20:47:23 +0000439
440 // At least one variable name is required.
441 if (CurTok != tok_identifier)
442 return Error("expected identifier after var");
Eric Christopherc0239362014-12-08 18:12:28 +0000443
Nick Lewycky109af622009-04-12 20:47:23 +0000444 while (1) {
445 std::string Name = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000446 getNextToken(); // eat identifier.
Nick Lewycky109af622009-04-12 20:47:23 +0000447
448 // Read the optional initializer.
449 ExprAST *Init = 0;
450 if (CurTok == '=') {
451 getNextToken(); // eat the '='.
Eric Christopherc0239362014-12-08 18:12:28 +0000452
Nick Lewycky109af622009-04-12 20:47:23 +0000453 Init = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000454 if (Init == 0)
455 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000456 }
Eric Christopherc0239362014-12-08 18:12:28 +0000457
Nick Lewycky109af622009-04-12 20:47:23 +0000458 VarNames.push_back(std::make_pair(Name, Init));
Eric Christopherc0239362014-12-08 18:12:28 +0000459
Nick Lewycky109af622009-04-12 20:47:23 +0000460 // End of var list, exit loop.
Eric Christopherc0239362014-12-08 18:12:28 +0000461 if (CurTok != ',')
462 break;
Nick Lewycky109af622009-04-12 20:47:23 +0000463 getNextToken(); // eat the ','.
Eric Christopherc0239362014-12-08 18:12:28 +0000464
Nick Lewycky109af622009-04-12 20:47:23 +0000465 if (CurTok != tok_identifier)
466 return Error("expected identifier list after var");
467 }
Eric Christopherc0239362014-12-08 18:12:28 +0000468
Nick Lewycky109af622009-04-12 20:47:23 +0000469 // At this point, we have to have 'in'.
470 if (CurTok != tok_in)
471 return Error("expected 'in' keyword after 'var'");
Eric Christopherc0239362014-12-08 18:12:28 +0000472 getNextToken(); // eat 'in'.
473
Nick Lewycky109af622009-04-12 20:47:23 +0000474 ExprAST *Body = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000475 if (Body == 0)
476 return 0;
477
Nick Lewycky109af622009-04-12 20:47:23 +0000478 return new VarExprAST(VarNames, Body);
479}
480
Nick Lewycky109af622009-04-12 20:47:23 +0000481/// primary
482/// ::= identifierexpr
483/// ::= numberexpr
484/// ::= parenexpr
485/// ::= ifexpr
486/// ::= forexpr
487/// ::= varexpr
488static ExprAST *ParsePrimary() {
489 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +0000490 default:
491 return Error("unknown token when expecting an expression");
492 case tok_identifier:
493 return ParseIdentifierExpr();
494 case tok_number:
495 return ParseNumberExpr();
496 case '(':
497 return ParseParenExpr();
498 case tok_if:
499 return ParseIfExpr();
500 case tok_for:
501 return ParseForExpr();
502 case tok_var:
503 return ParseVarExpr();
Nick Lewycky109af622009-04-12 20:47:23 +0000504 }
505}
506
507/// unary
508/// ::= primary
509/// ::= '!' unary
510static ExprAST *ParseUnary() {
511 // If the current token is not an operator, it must be a primary expr.
512 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
513 return ParsePrimary();
Eric Christopherc0239362014-12-08 18:12:28 +0000514
Nick Lewycky109af622009-04-12 20:47:23 +0000515 // If this is a unary operator, read it.
516 int Opc = CurTok;
517 getNextToken();
518 if (ExprAST *Operand = ParseUnary())
519 return new UnaryExprAST(Opc, Operand);
520 return 0;
521}
522
523/// binoprhs
524/// ::= ('+' unary)*
525static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
526 // If this is a binop, find its precedence.
527 while (1) {
528 int TokPrec = GetTokPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +0000529
Nick Lewycky109af622009-04-12 20:47:23 +0000530 // If this is a binop that binds at least as tightly as the current binop,
531 // consume it, otherwise we are done.
532 if (TokPrec < ExprPrec)
533 return LHS;
Eric Christopherc0239362014-12-08 18:12:28 +0000534
Nick Lewycky109af622009-04-12 20:47:23 +0000535 // Okay, we know this is a binop.
536 int BinOp = CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000537 getNextToken(); // eat binop
538
Nick Lewycky109af622009-04-12 20:47:23 +0000539 // Parse the unary expression after the binary operator.
540 ExprAST *RHS = ParseUnary();
Eric Christopherc0239362014-12-08 18:12:28 +0000541 if (!RHS)
542 return 0;
543
Nick Lewycky109af622009-04-12 20:47:23 +0000544 // If BinOp binds less tightly with RHS than the operator after RHS, let
545 // the pending operator take RHS as its LHS.
546 int NextPrec = GetTokPrecedence();
547 if (TokPrec < NextPrec) {
Eric Christopherc0239362014-12-08 18:12:28 +0000548 RHS = ParseBinOpRHS(TokPrec + 1, RHS);
549 if (RHS == 0)
550 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000551 }
Eric Christopherc0239362014-12-08 18:12:28 +0000552
Nick Lewycky109af622009-04-12 20:47:23 +0000553 // Merge LHS/RHS.
554 LHS = new BinaryExprAST(BinOp, LHS, RHS);
555 }
556}
557
558/// expression
559/// ::= unary binoprhs
560///
561static ExprAST *ParseExpression() {
562 ExprAST *LHS = ParseUnary();
Eric Christopherc0239362014-12-08 18:12:28 +0000563 if (!LHS)
564 return 0;
565
Nick Lewycky109af622009-04-12 20:47:23 +0000566 return ParseBinOpRHS(0, LHS);
567}
568
569/// prototype
570/// ::= id '(' id* ')'
571/// ::= binary LETTER number? (id, id)
572/// ::= unary LETTER (id)
573static PrototypeAST *ParsePrototype() {
574 std::string FnName;
Eric Christopherc0239362014-12-08 18:12:28 +0000575
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000576 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
Nick Lewycky109af622009-04-12 20:47:23 +0000577 unsigned BinaryPrecedence = 30;
Eric Christopherc0239362014-12-08 18:12:28 +0000578
Nick Lewycky109af622009-04-12 20:47:23 +0000579 switch (CurTok) {
580 default:
581 return ErrorP("Expected function name in prototype");
582 case tok_identifier:
583 FnName = IdentifierStr;
584 Kind = 0;
585 getNextToken();
586 break;
587 case tok_unary:
588 getNextToken();
589 if (!isascii(CurTok))
590 return ErrorP("Expected unary operator");
591 FnName = "unary";
592 FnName += (char)CurTok;
593 Kind = 1;
594 getNextToken();
595 break;
596 case tok_binary:
597 getNextToken();
598 if (!isascii(CurTok))
599 return ErrorP("Expected binary operator");
600 FnName = "binary";
601 FnName += (char)CurTok;
602 Kind = 2;
603 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000604
Nick Lewycky109af622009-04-12 20:47:23 +0000605 // Read the precedence if present.
606 if (CurTok == tok_number) {
607 if (NumVal < 1 || NumVal > 100)
608 return ErrorP("Invalid precedecnce: must be 1..100");
609 BinaryPrecedence = (unsigned)NumVal;
610 getNextToken();
611 }
612 break;
613 }
Eric Christopherc0239362014-12-08 18:12:28 +0000614
Nick Lewycky109af622009-04-12 20:47:23 +0000615 if (CurTok != '(')
616 return ErrorP("Expected '(' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000617
Nick Lewycky109af622009-04-12 20:47:23 +0000618 std::vector<std::string> ArgNames;
619 while (getNextToken() == tok_identifier)
620 ArgNames.push_back(IdentifierStr);
621 if (CurTok != ')')
622 return ErrorP("Expected ')' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000623
Nick Lewycky109af622009-04-12 20:47:23 +0000624 // success.
Eric Christopherc0239362014-12-08 18:12:28 +0000625 getNextToken(); // eat ')'.
626
Nick Lewycky109af622009-04-12 20:47:23 +0000627 // Verify right number of names for operator.
628 if (Kind && ArgNames.size() != Kind)
629 return ErrorP("Invalid number of operands for operator");
Eric Christopherc0239362014-12-08 18:12:28 +0000630
Nick Lewycky109af622009-04-12 20:47:23 +0000631 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
632}
633
634/// definition ::= 'def' prototype expression
635static FunctionAST *ParseDefinition() {
Eric Christopherc0239362014-12-08 18:12:28 +0000636 getNextToken(); // eat def.
Nick Lewycky109af622009-04-12 20:47:23 +0000637 PrototypeAST *Proto = ParsePrototype();
Eric Christopherc0239362014-12-08 18:12:28 +0000638 if (Proto == 0)
639 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000640
641 if (ExprAST *E = ParseExpression())
642 return new FunctionAST(Proto, E);
643 return 0;
644}
645
646/// toplevelexpr ::= expression
647static FunctionAST *ParseTopLevelExpr() {
648 if (ExprAST *E = ParseExpression()) {
649 // Make an anonymous proto.
650 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
651 return new FunctionAST(Proto, E);
652 }
653 return 0;
654}
655
656/// external ::= 'extern' prototype
657static PrototypeAST *ParseExtern() {
Eric Christopherc0239362014-12-08 18:12:28 +0000658 getNextToken(); // eat extern.
Nick Lewycky109af622009-04-12 20:47:23 +0000659 return ParsePrototype();
660}
661
662//===----------------------------------------------------------------------===//
663// Code Generation
664//===----------------------------------------------------------------------===//
665
666static Module *TheModule;
Owen Andersona7714592009-07-08 20:50:47 +0000667static IRBuilder<> Builder(getGlobalContext());
Eric Christopherc0239362014-12-08 18:12:28 +0000668static std::map<std::string, AllocaInst *> NamedValues;
Chandler Carruth7ecd9912015-02-13 10:21:05 +0000669static legacy::FunctionPassManager *TheFPM;
Nick Lewycky109af622009-04-12 20:47:23 +0000670
Eric Christopherc0239362014-12-08 18:12:28 +0000671Value *ErrorV(const char *Str) {
672 Error(Str);
673 return 0;
674}
Nick Lewycky109af622009-04-12 20:47:23 +0000675
676/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
677/// the function. This is used for mutable variables etc.
678static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
679 const std::string &VarName) {
680 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
Eric Christopherc0239362014-12-08 18:12:28 +0000681 TheFunction->getEntryBlock().begin());
Owen Anderson55f1c092009-08-13 21:58:54 +0000682 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
683 VarName.c_str());
Nick Lewycky109af622009-04-12 20:47:23 +0000684}
685
Nick Lewycky109af622009-04-12 20:47:23 +0000686Value *NumberExprAST::Codegen() {
Owen Anderson69c464d2009-07-27 20:59:43 +0000687 return ConstantFP::get(getGlobalContext(), APFloat(Val));
Nick Lewycky109af622009-04-12 20:47:23 +0000688}
689
690Value *VariableExprAST::Codegen() {
691 // Look this variable up in the function.
692 Value *V = NamedValues[Name];
Eric Christopherc0239362014-12-08 18:12:28 +0000693 if (V == 0)
694 return ErrorV("Unknown variable name");
Nick Lewycky109af622009-04-12 20:47:23 +0000695
696 // Load the value.
697 return Builder.CreateLoad(V, Name.c_str());
698}
699
700Value *UnaryExprAST::Codegen() {
701 Value *OperandV = Operand->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000702 if (OperandV == 0)
703 return 0;
704
705 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
Nick Lewycky109af622009-04-12 20:47:23 +0000706 if (F == 0)
707 return ErrorV("Unknown unary operator");
Eric Christopherc0239362014-12-08 18:12:28 +0000708
Nick Lewycky109af622009-04-12 20:47:23 +0000709 return Builder.CreateCall(F, OperandV, "unop");
710}
711
Nick Lewycky109af622009-04-12 20:47:23 +0000712Value *BinaryExprAST::Codegen() {
713 // Special case '=' because we don't want to emit the LHS as an expression.
714 if (Op == '=') {
715 // Assignment requires the LHS to be an identifier.
Eric Christopherc0239362014-12-08 18:12:28 +0000716 VariableExprAST *LHSE = dynamic_cast<VariableExprAST *>(LHS);
Nick Lewycky109af622009-04-12 20:47:23 +0000717 if (!LHSE)
718 return ErrorV("destination of '=' must be a variable");
719 // Codegen the RHS.
720 Value *Val = RHS->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000721 if (Val == 0)
722 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000723
724 // Look up the name.
725 Value *Variable = NamedValues[LHSE->getName()];
Eric Christopherc0239362014-12-08 18:12:28 +0000726 if (Variable == 0)
727 return ErrorV("Unknown variable name");
Nick Lewycky109af622009-04-12 20:47:23 +0000728
729 Builder.CreateStore(Val, Variable);
730 return Val;
731 }
Eric Christopherc0239362014-12-08 18:12:28 +0000732
Nick Lewycky109af622009-04-12 20:47:23 +0000733 Value *L = LHS->Codegen();
734 Value *R = RHS->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000735 if (L == 0 || R == 0)
736 return 0;
737
Nick Lewycky109af622009-04-12 20:47:23 +0000738 switch (Op) {
Eric Christopherc0239362014-12-08 18:12:28 +0000739 case '+':
740 return Builder.CreateFAdd(L, R, "addtmp");
741 case '-':
742 return Builder.CreateFSub(L, R, "subtmp");
743 case '*':
744 return Builder.CreateFMul(L, R, "multmp");
Nick Lewycky109af622009-04-12 20:47:23 +0000745 case '<':
746 L = Builder.CreateFCmpULT(L, R, "cmptmp");
747 // Convert bool 0/1 to double 0.0 or 1.0
Owen Anderson55f1c092009-08-13 21:58:54 +0000748 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
749 "booltmp");
Eric Christopherc0239362014-12-08 18:12:28 +0000750 default:
751 break;
Nick Lewycky109af622009-04-12 20:47:23 +0000752 }
Eric Christopherc0239362014-12-08 18:12:28 +0000753
Nick Lewycky109af622009-04-12 20:47:23 +0000754 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
755 // a call to it.
Eric Christopherc0239362014-12-08 18:12:28 +0000756 Function *F = TheModule->getFunction(std::string("binary") + Op);
Nick Lewycky109af622009-04-12 20:47:23 +0000757 assert(F && "binary operator not found!");
Eric Christopherc0239362014-12-08 18:12:28 +0000758
Nick Lewycky109af622009-04-12 20:47:23 +0000759 Value *Ops[] = { L, R };
Francois Pichetc5d10502011-07-15 10:59:52 +0000760 return Builder.CreateCall(F, Ops, "binop");
Nick Lewycky109af622009-04-12 20:47:23 +0000761}
762
763Value *CallExprAST::Codegen() {
764 // Look up the name in the global module table.
765 Function *CalleeF = TheModule->getFunction(Callee);
766 if (CalleeF == 0)
767 return ErrorV("Unknown function referenced");
Eric Christopherc0239362014-12-08 18:12:28 +0000768
Nick Lewycky109af622009-04-12 20:47:23 +0000769 // If argument mismatch error.
770 if (CalleeF->arg_size() != Args.size())
771 return ErrorV("Incorrect # arguments passed");
772
Eric Christopherc0239362014-12-08 18:12:28 +0000773 std::vector<Value *> ArgsV;
Nick Lewycky109af622009-04-12 20:47:23 +0000774 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
775 ArgsV.push_back(Args[i]->Codegen());
Eric Christopherc0239362014-12-08 18:12:28 +0000776 if (ArgsV.back() == 0)
777 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000778 }
Eric Christopherc0239362014-12-08 18:12:28 +0000779
Francois Pichetc5d10502011-07-15 10:59:52 +0000780 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
Nick Lewycky109af622009-04-12 20:47:23 +0000781}
782
783Value *IfExprAST::Codegen() {
784 Value *CondV = Cond->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000785 if (CondV == 0)
786 return 0;
787
Nick Lewycky109af622009-04-12 20:47:23 +0000788 // Convert condition to a bool by comparing equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000789 CondV = Builder.CreateFCmpONE(
790 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
791
Nick Lewycky109af622009-04-12 20:47:23 +0000792 Function *TheFunction = Builder.GetInsertBlock()->getParent();
Eric Christopherc0239362014-12-08 18:12:28 +0000793
Nick Lewycky109af622009-04-12 20:47:23 +0000794 // Create blocks for the then and else cases. Insert the 'then' block at the
795 // end of the function.
Eric Christopherc0239362014-12-08 18:12:28 +0000796 BasicBlock *ThenBB =
797 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
Owen Anderson55f1c092009-08-13 21:58:54 +0000798 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
799 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
Eric Christopherc0239362014-12-08 18:12:28 +0000800
Nick Lewycky109af622009-04-12 20:47:23 +0000801 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000802
Nick Lewycky109af622009-04-12 20:47:23 +0000803 // Emit then value.
804 Builder.SetInsertPoint(ThenBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000805
Nick Lewycky109af622009-04-12 20:47:23 +0000806 Value *ThenV = Then->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000807 if (ThenV == 0)
808 return 0;
809
Nick Lewycky109af622009-04-12 20:47:23 +0000810 Builder.CreateBr(MergeBB);
811 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
812 ThenBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000813
Nick Lewycky109af622009-04-12 20:47:23 +0000814 // Emit else block.
815 TheFunction->getBasicBlockList().push_back(ElseBB);
816 Builder.SetInsertPoint(ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000817
Nick Lewycky109af622009-04-12 20:47:23 +0000818 Value *ElseV = Else->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000819 if (ElseV == 0)
820 return 0;
821
Nick Lewycky109af622009-04-12 20:47:23 +0000822 Builder.CreateBr(MergeBB);
823 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
824 ElseBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000825
Nick Lewycky109af622009-04-12 20:47:23 +0000826 // Emit merge block.
827 TheFunction->getBasicBlockList().push_back(MergeBB);
828 Builder.SetInsertPoint(MergeBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000829 PHINode *PN =
830 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
831
Nick Lewycky109af622009-04-12 20:47:23 +0000832 PN->addIncoming(ThenV, ThenBB);
833 PN->addIncoming(ElseV, ElseBB);
834 return PN;
835}
836
837Value *ForExprAST::Codegen() {
838 // Output this as:
839 // var = alloca double
840 // ...
841 // start = startexpr
842 // store start -> var
843 // goto loop
Eric Christopherc0239362014-12-08 18:12:28 +0000844 // loop:
Nick Lewycky109af622009-04-12 20:47:23 +0000845 // ...
846 // bodyexpr
847 // ...
848 // loopend:
849 // step = stepexpr
850 // endcond = endexpr
851 //
852 // curvar = load var
853 // nextvar = curvar + step
854 // store nextvar -> var
855 // br endcond, loop, endloop
856 // outloop:
Eric Christopherc0239362014-12-08 18:12:28 +0000857
Nick Lewycky109af622009-04-12 20:47:23 +0000858 Function *TheFunction = Builder.GetInsertBlock()->getParent();
859
860 // Create an alloca for the variable in the entry block.
861 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
Eric Christopherc0239362014-12-08 18:12:28 +0000862
Nick Lewycky109af622009-04-12 20:47:23 +0000863 // Emit the start code first, without 'variable' in scope.
864 Value *StartVal = Start->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000865 if (StartVal == 0)
866 return 0;
867
Nick Lewycky109af622009-04-12 20:47:23 +0000868 // Store the value into the alloca.
869 Builder.CreateStore(StartVal, Alloca);
Eric Christopherc0239362014-12-08 18:12:28 +0000870
Nick Lewycky109af622009-04-12 20:47:23 +0000871 // Make the new basic block for the loop header, inserting after current
872 // block.
Eric Christopherc0239362014-12-08 18:12:28 +0000873 BasicBlock *LoopBB =
874 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
875
Nick Lewycky109af622009-04-12 20:47:23 +0000876 // Insert an explicit fall through from the current block to the LoopBB.
877 Builder.CreateBr(LoopBB);
878
879 // Start insertion in LoopBB.
880 Builder.SetInsertPoint(LoopBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000881
Nick Lewycky109af622009-04-12 20:47:23 +0000882 // Within the loop, the variable is defined equal to the PHI node. If it
883 // shadows an existing variable, we have to restore it, so save it now.
884 AllocaInst *OldVal = NamedValues[VarName];
885 NamedValues[VarName] = Alloca;
Eric Christopherc0239362014-12-08 18:12:28 +0000886
Nick Lewycky109af622009-04-12 20:47:23 +0000887 // Emit the body of the loop. This, like any other expr, can change the
888 // current BB. Note that we ignore the value computed by the body, but don't
889 // allow an error.
890 if (Body->Codegen() == 0)
891 return 0;
Eric Christopherc0239362014-12-08 18:12:28 +0000892
Nick Lewycky109af622009-04-12 20:47:23 +0000893 // Emit the step value.
894 Value *StepVal;
895 if (Step) {
896 StepVal = Step->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000897 if (StepVal == 0)
898 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000899 } else {
900 // If not specified, use 1.0.
Owen Anderson69c464d2009-07-27 20:59:43 +0000901 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
Nick Lewycky109af622009-04-12 20:47:23 +0000902 }
Eric Christopherc0239362014-12-08 18:12:28 +0000903
Nick Lewycky109af622009-04-12 20:47:23 +0000904 // Compute the end condition.
905 Value *EndCond = End->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000906 if (EndCond == 0)
907 return EndCond;
908
Nick Lewycky109af622009-04-12 20:47:23 +0000909 // Reload, increment, and restore the alloca. This handles the case where
910 // the body of the loop mutates the variable.
911 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
Chris Lattner26d79502010-06-21 22:51:14 +0000912 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
Nick Lewycky109af622009-04-12 20:47:23 +0000913 Builder.CreateStore(NextVar, Alloca);
Eric Christopherc0239362014-12-08 18:12:28 +0000914
Nick Lewycky109af622009-04-12 20:47:23 +0000915 // Convert condition to a bool by comparing equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000916 EndCond = Builder.CreateFCmpONE(
917 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
918
Nick Lewycky109af622009-04-12 20:47:23 +0000919 // Create the "after loop" block and insert it.
Eric Christopherc0239362014-12-08 18:12:28 +0000920 BasicBlock *AfterBB =
921 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
922
Nick Lewycky109af622009-04-12 20:47:23 +0000923 // Insert the conditional branch into the end of LoopEndBB.
924 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000925
Nick Lewycky109af622009-04-12 20:47:23 +0000926 // Any new code will be inserted in AfterBB.
927 Builder.SetInsertPoint(AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000928
Nick Lewycky109af622009-04-12 20:47:23 +0000929 // Restore the unshadowed variable.
930 if (OldVal)
931 NamedValues[VarName] = OldVal;
932 else
933 NamedValues.erase(VarName);
934
Nick Lewycky109af622009-04-12 20:47:23 +0000935 // for expr always returns 0.0.
Owen Anderson55f1c092009-08-13 21:58:54 +0000936 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
Nick Lewycky109af622009-04-12 20:47:23 +0000937}
938
939Value *VarExprAST::Codegen() {
940 std::vector<AllocaInst *> OldBindings;
Eric Christopherc0239362014-12-08 18:12:28 +0000941
Nick Lewycky109af622009-04-12 20:47:23 +0000942 Function *TheFunction = Builder.GetInsertBlock()->getParent();
943
944 // Register all variables and emit their initializer.
945 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
946 const std::string &VarName = VarNames[i].first;
947 ExprAST *Init = VarNames[i].second;
Eric Christopherc0239362014-12-08 18:12:28 +0000948
Nick Lewycky109af622009-04-12 20:47:23 +0000949 // Emit the initializer before adding the variable to scope, this prevents
950 // the initializer from referencing the variable itself, and permits stuff
951 // like this:
952 // var a = 1 in
953 // var a = a in ... # refers to outer 'a'.
954 Value *InitVal;
955 if (Init) {
956 InitVal = Init->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000957 if (InitVal == 0)
958 return 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000959 } else { // If not specified, use 0.0.
Owen Anderson69c464d2009-07-27 20:59:43 +0000960 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
Nick Lewycky109af622009-04-12 20:47:23 +0000961 }
Eric Christopherc0239362014-12-08 18:12:28 +0000962
Nick Lewycky109af622009-04-12 20:47:23 +0000963 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
964 Builder.CreateStore(InitVal, Alloca);
965
966 // Remember the old variable binding so that we can restore the binding when
967 // we unrecurse.
968 OldBindings.push_back(NamedValues[VarName]);
Eric Christopherc0239362014-12-08 18:12:28 +0000969
Nick Lewycky109af622009-04-12 20:47:23 +0000970 // Remember this binding.
971 NamedValues[VarName] = Alloca;
972 }
Eric Christopherc0239362014-12-08 18:12:28 +0000973
Nick Lewycky109af622009-04-12 20:47:23 +0000974 // Codegen the body, now that all vars are in scope.
975 Value *BodyVal = Body->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000976 if (BodyVal == 0)
977 return 0;
978
Nick Lewycky109af622009-04-12 20:47:23 +0000979 // Pop all our variables from scope.
980 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
981 NamedValues[VarNames[i].first] = OldBindings[i];
982
983 // Return the body computation.
984 return BodyVal;
985}
986
Nick Lewycky109af622009-04-12 20:47:23 +0000987Function *PrototypeAST::Codegen() {
988 // Make the function type: double(double,double) etc.
Eric Christopherc0239362014-12-08 18:12:28 +0000989 std::vector<Type *> Doubles(Args.size(),
990 Type::getDoubleTy(getGlobalContext()));
991 FunctionType *FT =
992 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
993
994 Function *F =
995 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
996
Nick Lewycky109af622009-04-12 20:47:23 +0000997 // If F conflicted, there was already something named 'Name'. If it has a
998 // body, don't allow redefinition or reextern.
999 if (F->getName() != Name) {
1000 // Delete the one we just made and get the existing one.
1001 F->eraseFromParent();
1002 F = TheModule->getFunction(Name);
Eric Christopherc0239362014-12-08 18:12:28 +00001003
Nick Lewycky109af622009-04-12 20:47:23 +00001004 // If F already has a body, reject this.
1005 if (!F->empty()) {
1006 ErrorF("redefinition of function");
1007 return 0;
1008 }
Eric Christopherc0239362014-12-08 18:12:28 +00001009
Nick Lewycky109af622009-04-12 20:47:23 +00001010 // If F took a different number of args, reject.
1011 if (F->arg_size() != Args.size()) {
1012 ErrorF("redefinition of function with different # args");
1013 return 0;
1014 }
1015 }
Eric Christopherc0239362014-12-08 18:12:28 +00001016
Nick Lewycky109af622009-04-12 20:47:23 +00001017 // Set names for all arguments.
1018 unsigned Idx = 0;
1019 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1020 ++AI, ++Idx)
1021 AI->setName(Args[Idx]);
Eric Christopherc0239362014-12-08 18:12:28 +00001022
Nick Lewycky109af622009-04-12 20:47:23 +00001023 return F;
1024}
1025
1026/// CreateArgumentAllocas - Create an alloca for each argument and register the
1027/// argument in the symbol table so that references to it will succeed.
1028void PrototypeAST::CreateArgumentAllocas(Function *F) {
1029 Function::arg_iterator AI = F->arg_begin();
1030 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1031 // Create an alloca for this variable.
1032 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1033
1034 // Store the initial value into the alloca.
1035 Builder.CreateStore(AI, Alloca);
1036
1037 // Add arguments to variable symbol table.
1038 NamedValues[Args[Idx]] = Alloca;
1039 }
1040}
1041
Nick Lewycky109af622009-04-12 20:47:23 +00001042Function *FunctionAST::Codegen() {
1043 NamedValues.clear();
Eric Christopherc0239362014-12-08 18:12:28 +00001044
Nick Lewycky109af622009-04-12 20:47:23 +00001045 Function *TheFunction = Proto->Codegen();
1046 if (TheFunction == 0)
1047 return 0;
Eric Christopherc0239362014-12-08 18:12:28 +00001048
Nick Lewycky109af622009-04-12 20:47:23 +00001049 // If this is an operator, install it.
1050 if (Proto->isBinaryOp())
1051 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +00001052
Nick Lewycky109af622009-04-12 20:47:23 +00001053 // Create a new basic block to start insertion into.
Owen Anderson55f1c092009-08-13 21:58:54 +00001054 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
Nick Lewycky109af622009-04-12 20:47:23 +00001055 Builder.SetInsertPoint(BB);
Eric Christopherc0239362014-12-08 18:12:28 +00001056
Nick Lewycky109af622009-04-12 20:47:23 +00001057 // Add all arguments to the symbol table and create their allocas.
1058 Proto->CreateArgumentAllocas(TheFunction);
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001059
Nick Lewycky109af622009-04-12 20:47:23 +00001060 if (Value *RetVal = Body->Codegen()) {
1061 // Finish off the function.
1062 Builder.CreateRet(RetVal);
1063
1064 // Validate the generated code, checking for consistency.
1065 verifyFunction(*TheFunction);
1066
1067 // Optimize the function.
1068 TheFPM->run(*TheFunction);
Eric Christopherc0239362014-12-08 18:12:28 +00001069
Nick Lewycky109af622009-04-12 20:47:23 +00001070 return TheFunction;
1071 }
Eric Christopherc0239362014-12-08 18:12:28 +00001072
Nick Lewycky109af622009-04-12 20:47:23 +00001073 // Error reading body, remove function.
1074 TheFunction->eraseFromParent();
1075
1076 if (Proto->isBinaryOp())
1077 BinopPrecedence.erase(Proto->getOperatorName());
1078 return 0;
1079}
1080
1081//===----------------------------------------------------------------------===//
1082// Top-Level parsing and JIT Driver
1083//===----------------------------------------------------------------------===//
1084
1085static ExecutionEngine *TheExecutionEngine;
1086
1087static void HandleDefinition() {
1088 if (FunctionAST *F = ParseDefinition()) {
1089 if (Function *LF = F->Codegen()) {
1090 fprintf(stderr, "Read function definition:");
1091 LF->dump();
1092 }
1093 } else {
1094 // Skip token for error recovery.
1095 getNextToken();
1096 }
1097}
1098
1099static void HandleExtern() {
1100 if (PrototypeAST *P = ParseExtern()) {
1101 if (Function *F = P->Codegen()) {
1102 fprintf(stderr, "Read extern: ");
1103 F->dump();
1104 }
1105 } else {
1106 // Skip token for error recovery.
1107 getNextToken();
1108 }
1109}
1110
1111static void HandleTopLevelExpression() {
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001112 // Evaluate a top-level expression into an anonymous function.
Nick Lewycky109af622009-04-12 20:47:23 +00001113 if (FunctionAST *F = ParseTopLevelExpr()) {
1114 if (Function *LF = F->Codegen()) {
Eric Christopher1b74b652014-12-08 18:00:38 +00001115 TheExecutionEngine->finalizeObject();
Nick Lewycky109af622009-04-12 20:47:23 +00001116 // JIT the function, returning a function pointer.
1117 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
Eric Christopherc0239362014-12-08 18:12:28 +00001118
Nick Lewycky109af622009-04-12 20:47:23 +00001119 // Cast it to the right type (takes no arguments, returns a double) so we
1120 // can call it as a native function.
Chris Lattner0813c0c2009-04-15 00:16:05 +00001121 double (*FP)() = (double (*)())(intptr_t)FPtr;
Nick Lewycky109af622009-04-12 20:47:23 +00001122 fprintf(stderr, "Evaluated to %f\n", FP());
1123 }
1124 } else {
1125 // Skip token for error recovery.
1126 getNextToken();
1127 }
1128}
1129
1130/// top ::= definition | external | expression | ';'
1131static void MainLoop() {
1132 while (1) {
1133 fprintf(stderr, "ready> ");
1134 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +00001135 case tok_eof:
1136 return;
1137 case ';':
1138 getNextToken();
1139 break; // ignore top-level semicolons.
1140 case tok_def:
1141 HandleDefinition();
1142 break;
1143 case tok_extern:
1144 HandleExtern();
1145 break;
1146 default:
1147 HandleTopLevelExpression();
1148 break;
Nick Lewycky109af622009-04-12 20:47:23 +00001149 }
1150 }
1151}
1152
Nick Lewycky109af622009-04-12 20:47:23 +00001153//===----------------------------------------------------------------------===//
1154// "Library" functions that can be "extern'd" from user code.
1155//===----------------------------------------------------------------------===//
1156
1157/// putchard - putchar that takes a double and returns 0.
Eric Christopherc0239362014-12-08 18:12:28 +00001158extern "C" double putchard(double X) {
Nick Lewycky109af622009-04-12 20:47:23 +00001159 putchar((char)X);
1160 return 0;
1161}
1162
1163/// printd - printf that takes a double prints it as "%f\n", returning 0.
Eric Christopherc0239362014-12-08 18:12:28 +00001164extern "C" double printd(double X) {
Nick Lewycky109af622009-04-12 20:47:23 +00001165 printf("%f\n", X);
1166 return 0;
1167}
1168
1169//===----------------------------------------------------------------------===//
1170// Main driver code.
1171//===----------------------------------------------------------------------===//
1172
1173int main() {
Chris Lattnerd24df242009-06-17 16:48:44 +00001174 InitializeNativeTarget();
Eric Christopher1b74b652014-12-08 18:00:38 +00001175 InitializeNativeTargetAsmPrinter();
1176 InitializeNativeTargetAsmParser();
Owen Andersonc277dc42009-07-16 19:05:41 +00001177 LLVMContext &Context = getGlobalContext();
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001178
Nick Lewycky109af622009-04-12 20:47:23 +00001179 // Install standard binary operators.
1180 // 1 is lowest precedence.
1181 BinopPrecedence['='] = 2;
1182 BinopPrecedence['<'] = 10;
1183 BinopPrecedence['+'] = 20;
1184 BinopPrecedence['-'] = 20;
Eric Christopherc0239362014-12-08 18:12:28 +00001185 BinopPrecedence['*'] = 40; // highest.
Nick Lewycky109af622009-04-12 20:47:23 +00001186
1187 // Prime the first token.
1188 fprintf(stderr, "ready> ");
1189 getNextToken();
1190
1191 // Make the module, which holds all the code.
Rafael Espindola2a8a2792014-08-19 04:04:25 +00001192 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1193 TheModule = Owner.get();
Nick Lewycky109af622009-04-12 20:47:23 +00001194
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001195 // Create the JIT. This takes ownership of the module.
Jeffrey Yasskin8a303242010-02-11 19:15:20 +00001196 std::string ErrStr;
Eric Christopherc0239362014-12-08 18:12:28 +00001197 TheExecutionEngine =
1198 EngineBuilder(std::move(Owner))
1199 .setErrorStr(&ErrStr)
1200 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
1201 .create();
Jeffrey Yasskin8a303242010-02-11 19:15:20 +00001202 if (!TheExecutionEngine) {
1203 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1204 exit(1);
1205 }
Reid Klecknere56676a2009-08-24 05:42:21 +00001206
Chandler Carruth7ecd9912015-02-13 10:21:05 +00001207 legacy::FunctionPassManager OurFPM(TheModule);
Nick Lewycky109af622009-04-12 20:47:23 +00001208
Reid Klecknerab770042009-08-26 20:58:25 +00001209 // Set up the optimizer pipeline. Start with registering info about how the
1210 // target lays out data structures.
Rafael Espindola339430f2014-02-25 23:25:17 +00001211 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
Rafael Espindolac435adc2014-09-10 21:27:43 +00001212 OurFPM.add(new DataLayoutPass());
Dan Gohman56f3a4c2010-11-15 18:41:10 +00001213 // Provide basic AliasAnalysis support for GVN.
1214 OurFPM.add(createBasicAliasAnalysisPass());
Reid Klecknerab770042009-08-26 20:58:25 +00001215 // Promote allocas to registers.
1216 OurFPM.add(createPromoteMemoryToRegisterPass());
1217 // Do simple "peephole" optimizations and bit-twiddling optzns.
1218 OurFPM.add(createInstructionCombiningPass());
1219 // Reassociate expressions.
1220 OurFPM.add(createReassociatePass());
1221 // Eliminate Common SubExpressions.
1222 OurFPM.add(createGVNPass());
1223 // Simplify the control flow graph (deleting unreachable blocks, etc).
1224 OurFPM.add(createCFGSimplificationPass());
Eli Friedmane04169c2009-07-20 14:50:07 +00001225
Reid Klecknerab770042009-08-26 20:58:25 +00001226 OurFPM.doInitialization();
Nick Lewycky109af622009-04-12 20:47:23 +00001227
Reid Klecknerab770042009-08-26 20:58:25 +00001228 // Set the global so the code gen can use this.
1229 TheFPM = &OurFPM;
1230
1231 // Run the main "interpreter loop" now.
1232 MainLoop();
1233
1234 TheFPM = 0;
1235
1236 // Print out all of the generated code.
1237 TheModule->dump();
1238
Nick Lewycky109af622009-04-12 20:47:23 +00001239 return 0;
1240}