blob: f880bb8ea0f0eeadbc1ddc7990741c0e19f74879 [file] [log] [blame]
Eugene Zelenkof981ec42016-05-19 01:08:04 +00001#include "llvm/ADT/APFloat.h"
NAKAMURA Takumi85c9bac2015-03-02 01:04:34 +00002#include "llvm/ADT/STLExtras.h"
Wilfred Hughes945f43e2016-07-02 17:01:59 +00003#include "llvm/ADT/SmallVector.h"
4#include "llvm/Analysis/Passes.h"
Eric Christopher05917fa2014-12-08 18:00:47 +00005#include "llvm/IR/IRBuilder.h"
6#include "llvm/IR/LLVMContext.h"
Wilfred Hughes945f43e2016-07-02 17:01:59 +00007#include "llvm/IR/LegacyPassManager.h"
Eugene Zelenkof981ec42016-05-19 01:08:04 +00008#include "llvm/IR/Metadata.h"
Eric Christopher05917fa2014-12-08 18:00:47 +00009#include "llvm/IR/Module.h"
Eugene Zelenkof981ec42016-05-19 01:08:04 +000010#include "llvm/IR/Type.h"
Eric Christopher05917fa2014-12-08 18:00:47 +000011#include "llvm/IR/Verifier.h"
Wilfred Hughes945f43e2016-07-02 17:01:59 +000012#include "llvm/Support/FileSystem.h"
13#include "llvm/Support/TargetRegistry.h"
Eric Christopher05917fa2014-12-08 18:00:47 +000014#include "llvm/Support/TargetSelect.h"
Eugene Zelenkof981ec42016-05-19 01:08:04 +000015#include "llvm/Target/TargetMachine.h"
Wilfred Hughes945f43e2016-07-02 17:01:59 +000016#include "llvm/Target/TargetOptions.h"
17#include "llvm/Transforms/Scalar.h"
Eric Christopher05917fa2014-12-08 18:00:47 +000018#include <cctype>
19#include <cstdio>
Eugene Zelenkof981ec42016-05-19 01:08:04 +000020#include <cstdlib>
Eric Christopher05917fa2014-12-08 18:00:47 +000021#include <map>
Eugene Zelenkof981ec42016-05-19 01:08:04 +000022#include <memory>
Eric Christopher05917fa2014-12-08 18:00:47 +000023#include <string>
Eugene Zelenkof981ec42016-05-19 01:08:04 +000024#include <utility>
Eric Christopher05917fa2014-12-08 18:00:47 +000025#include <vector>
Lang Hames2d789c32015-08-26 03:07:41 +000026
Eric Christopher05917fa2014-12-08 18:00:47 +000027using namespace llvm;
Wilfred Hughes945f43e2016-07-02 17:01:59 +000028using namespace llvm::sys;
Eric Christopher05917fa2014-12-08 18:00:47 +000029
30//===----------------------------------------------------------------------===//
31// Lexer
32//===----------------------------------------------------------------------===//
33
34// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
35// of these for known things.
36enum Token {
37 tok_eof = -1,
38
39 // commands
40 tok_def = -2,
41 tok_extern = -3,
42
43 // primary
44 tok_identifier = -4,
45 tok_number = -5,
46
47 // control
48 tok_if = -6,
49 tok_then = -7,
50 tok_else = -8,
51 tok_for = -9,
52 tok_in = -10,
53
54 // operators
55 tok_binary = -11,
56 tok_unary = -12,
57
58 // var definition
59 tok_var = -13
60};
61
Lang Hames2d789c32015-08-26 03:07:41 +000062static std::string IdentifierStr; // Filled in if tok_identifier
63static double NumVal; // Filled in if tok_number
64
Eric Christopher05917fa2014-12-08 18:00:47 +000065/// gettok - Return the next token from standard input.
66static int gettok() {
67 static int LastChar = ' ';
68
69 // Skip any whitespace.
70 while (isspace(LastChar))
Wilfred Hughes945f43e2016-07-02 17:01:59 +000071 LastChar = getchar();
Eric Christopher05917fa2014-12-08 18:00:47 +000072
73 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
74 IdentifierStr = LastChar;
Wilfred Hughes945f43e2016-07-02 17:01:59 +000075 while (isalnum((LastChar = getchar())))
Eric Christopher05917fa2014-12-08 18:00:47 +000076 IdentifierStr += LastChar;
77
78 if (IdentifierStr == "def")
79 return tok_def;
80 if (IdentifierStr == "extern")
81 return tok_extern;
82 if (IdentifierStr == "if")
83 return tok_if;
84 if (IdentifierStr == "then")
85 return tok_then;
86 if (IdentifierStr == "else")
87 return tok_else;
88 if (IdentifierStr == "for")
89 return tok_for;
90 if (IdentifierStr == "in")
91 return tok_in;
92 if (IdentifierStr == "binary")
93 return tok_binary;
94 if (IdentifierStr == "unary")
95 return tok_unary;
96 if (IdentifierStr == "var")
97 return tok_var;
98 return tok_identifier;
99 }
100
101 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
102 std::string NumStr;
103 do {
104 NumStr += LastChar;
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000105 LastChar = getchar();
Eric Christopher05917fa2014-12-08 18:00:47 +0000106 } while (isdigit(LastChar) || LastChar == '.');
107
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000108 NumVal = strtod(NumStr.c_str(), nullptr);
Eric Christopher05917fa2014-12-08 18:00:47 +0000109 return tok_number;
110 }
111
112 if (LastChar == '#') {
113 // Comment until end of line.
114 do
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000115 LastChar = getchar();
Eric Christopher05917fa2014-12-08 18:00:47 +0000116 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
117
118 if (LastChar != EOF)
119 return gettok();
120 }
121
122 // Check for end of file. Don't eat the EOF.
123 if (LastChar == EOF)
124 return tok_eof;
125
126 // Otherwise, just return the character as its ascii value.
127 int ThisChar = LastChar;
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000128 LastChar = getchar();
Eric Christopher05917fa2014-12-08 18:00:47 +0000129 return ThisChar;
130}
131
132//===----------------------------------------------------------------------===//
133// Abstract Syntax Tree (aka Parse Tree)
134//===----------------------------------------------------------------------===//
135namespace {
Eric Christopher05917fa2014-12-08 18:00:47 +0000136/// ExprAST - Base class for all expression nodes.
137class ExprAST {
Eric Christopher05917fa2014-12-08 18:00:47 +0000138public:
Eric Christopher05917fa2014-12-08 18:00:47 +0000139 virtual ~ExprAST() {}
Lang Hames2d789c32015-08-26 03:07:41 +0000140 virtual Value *codegen() = 0;
Eric Christopher05917fa2014-12-08 18:00:47 +0000141};
142
143/// NumberExprAST - Expression class for numeric literals like "1.0".
144class NumberExprAST : public ExprAST {
145 double Val;
Lang Hames59b0da82015-08-19 18:15:58 +0000146
Eric Christopher05917fa2014-12-08 18:00:47 +0000147public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000148 NumberExprAST(double Val) : Val(Val) {}
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000149 Value *codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000150};
151
152/// VariableExprAST - Expression class for referencing a variable, like "a".
153class VariableExprAST : public ExprAST {
154 std::string Name;
Lang Hames59b0da82015-08-19 18:15:58 +0000155
Eric Christopher05917fa2014-12-08 18:00:47 +0000156public:
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000157 VariableExprAST(const std::string &Name) : Name(Name) {}
Eric Christopher05917fa2014-12-08 18:00:47 +0000158 const std::string &getName() const { return Name; }
Lang Hames2d789c32015-08-26 03:07:41 +0000159 Value *codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000160};
161
162/// UnaryExprAST - Expression class for a unary operator.
163class UnaryExprAST : public ExprAST {
164 char Opcode;
Lang Hames09bf4c12015-08-18 18:11:06 +0000165 std::unique_ptr<ExprAST> Operand;
Lang Hames59b0da82015-08-19 18:15:58 +0000166
Eric Christopher05917fa2014-12-08 18:00:47 +0000167public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000168 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
169 : Opcode(Opcode), Operand(std::move(Operand)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000170 Value *codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000171};
172
173/// BinaryExprAST - Expression class for a binary operator.
174class BinaryExprAST : public ExprAST {
175 char Op;
Lang Hames09bf4c12015-08-18 18:11:06 +0000176 std::unique_ptr<ExprAST> LHS, RHS;
Lang Hames59b0da82015-08-19 18:15:58 +0000177
Eric Christopher05917fa2014-12-08 18:00:47 +0000178public:
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000179 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
Lang Hames09bf4c12015-08-18 18:11:06 +0000180 std::unique_ptr<ExprAST> RHS)
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000181 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000182 Value *codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000183};
184
185/// CallExprAST - Expression class for function calls.
186class CallExprAST : public ExprAST {
187 std::string Callee;
Lang Hames09bf4c12015-08-18 18:11:06 +0000188 std::vector<std::unique_ptr<ExprAST>> Args;
Lang Hames59b0da82015-08-19 18:15:58 +0000189
Eric Christopher05917fa2014-12-08 18:00:47 +0000190public:
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000191 CallExprAST(const std::string &Callee,
Lang Hames09bf4c12015-08-18 18:11:06 +0000192 std::vector<std::unique_ptr<ExprAST>> Args)
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000193 : Callee(Callee), Args(std::move(Args)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000194 Value *codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000195};
196
197/// IfExprAST - Expression class for if/then/else.
198class IfExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000199 std::unique_ptr<ExprAST> Cond, Then, Else;
Lang Hames59b0da82015-08-19 18:15:58 +0000200
Eric Christopher05917fa2014-12-08 18:00:47 +0000201public:
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000202 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
203 std::unique_ptr<ExprAST> Else)
204 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000205 Value *codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000206};
207
208/// ForExprAST - Expression class for for/in.
209class ForExprAST : public ExprAST {
210 std::string VarName;
Lang Hames09bf4c12015-08-18 18:11:06 +0000211 std::unique_ptr<ExprAST> Start, End, Step, Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000212
Eric Christopher05917fa2014-12-08 18:00:47 +0000213public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000214 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
215 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
216 std::unique_ptr<ExprAST> Body)
217 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
218 Step(std::move(Step)), Body(std::move(Body)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000219 Value *codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000220};
221
222/// VarExprAST - Expression class for var/in
223class VarExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000224 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
225 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000226
Eric Christopher05917fa2014-12-08 18:00:47 +0000227public:
Lang Hames59b0da82015-08-19 18:15:58 +0000228 VarExprAST(
229 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames,
230 std::unique_ptr<ExprAST> Body)
Lang Hames09bf4c12015-08-18 18:11:06 +0000231 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000232 Value *codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000233};
234
235/// PrototypeAST - This class represents the "prototype" for a function,
Lang Hames59b0da82015-08-19 18:15:58 +0000236/// which captures its name, and its argument names (thus implicitly the number
237/// of arguments the function takes), as well as if it is an operator.
Eric Christopher05917fa2014-12-08 18:00:47 +0000238class PrototypeAST {
239 std::string Name;
240 std::vector<std::string> Args;
Lang Hames09bf4c12015-08-18 18:11:06 +0000241 bool IsOperator;
Eric Christopher05917fa2014-12-08 18:00:47 +0000242 unsigned Precedence; // Precedence if a binary op.
Lang Hames59b0da82015-08-19 18:15:58 +0000243
Eric Christopher05917fa2014-12-08 18:00:47 +0000244public:
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000245 PrototypeAST(const std::string &Name, std::vector<std::string> Args,
246 bool IsOperator = false, unsigned Prec = 0)
Lang Hames59b0da82015-08-19 18:15:58 +0000247 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000248 Precedence(Prec) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000249 Function *codegen();
250 const std::string &getName() const { return Name; }
Eric Christopher05917fa2014-12-08 18:00:47 +0000251
Lang Hames09bf4c12015-08-18 18:11:06 +0000252 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
253 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
Eric Christopher05917fa2014-12-08 18:00:47 +0000254
255 char getOperatorName() const {
256 assert(isUnaryOp() || isBinaryOp());
257 return Name[Name.size() - 1];
258 }
259
260 unsigned getBinaryPrecedence() const { return Precedence; }
Eric Christopher05917fa2014-12-08 18:00:47 +0000261};
262
263/// FunctionAST - This class represents a function definition itself.
264class FunctionAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000265 std::unique_ptr<PrototypeAST> Proto;
266 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000267
Eric Christopher05917fa2014-12-08 18:00:47 +0000268public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000269 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
270 std::unique_ptr<ExprAST> Body)
271 : Proto(std::move(Proto)), Body(std::move(Body)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000272 Function *codegen();
Eric Christopher05917fa2014-12-08 18:00:47 +0000273};
274} // end anonymous namespace
275
276//===----------------------------------------------------------------------===//
277// Parser
278//===----------------------------------------------------------------------===//
279
280/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
281/// token the parser is looking at. getNextToken reads another token from the
282/// lexer and updates CurTok with its results.
283static int CurTok;
284static int getNextToken() { return CurTok = gettok(); }
285
286/// BinopPrecedence - This holds the precedence for each binary operator that is
287/// defined.
288static std::map<char, int> BinopPrecedence;
289
290/// GetTokPrecedence - Get the precedence of the pending binary operator token.
291static int GetTokPrecedence() {
292 if (!isascii(CurTok))
293 return -1;
294
295 // Make sure it's a declared binop.
296 int TokPrec = BinopPrecedence[CurTok];
297 if (TokPrec <= 0)
298 return -1;
299 return TokPrec;
300}
301
Lang Hamesf9878c52016-03-25 17:33:32 +0000302/// LogError* - These are little helper functions for error handling.
303std::unique_ptr<ExprAST> LogError(const char *Str) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000304 fprintf(stderr, "Error: %s\n", Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000305 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000306}
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000307
Lang Hamesf9878c52016-03-25 17:33:32 +0000308std::unique_ptr<PrototypeAST> LogErrorP(const char *Str) {
309 LogError(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000310 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000311}
Eric Christopher05917fa2014-12-08 18:00:47 +0000312
Lang Hames09bf4c12015-08-18 18:11:06 +0000313static std::unique_ptr<ExprAST> ParseExpression();
Eric Christopher05917fa2014-12-08 18:00:47 +0000314
Eric Christopher05917fa2014-12-08 18:00:47 +0000315/// numberexpr ::= number
Lang Hames09bf4c12015-08-18 18:11:06 +0000316static std::unique_ptr<ExprAST> ParseNumberExpr() {
317 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
Eric Christopher05917fa2014-12-08 18:00:47 +0000318 getNextToken(); // consume the number
Lang Hames09bf4c12015-08-18 18:11:06 +0000319 return std::move(Result);
Eric Christopher05917fa2014-12-08 18:00:47 +0000320}
321
322/// parenexpr ::= '(' expression ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000323static std::unique_ptr<ExprAST> ParseParenExpr() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000324 getNextToken(); // eat (.
Lang Hames09bf4c12015-08-18 18:11:06 +0000325 auto V = ParseExpression();
Eric Christopher05917fa2014-12-08 18:00:47 +0000326 if (!V)
Lang Hames09bf4c12015-08-18 18:11:06 +0000327 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000328
329 if (CurTok != ')')
Lang Hamesf9878c52016-03-25 17:33:32 +0000330 return LogError("expected ')'");
Eric Christopher05917fa2014-12-08 18:00:47 +0000331 getNextToken(); // eat ).
332 return V;
333}
334
Lang Hames59b0da82015-08-19 18:15:58 +0000335/// identifierexpr
336/// ::= identifier
337/// ::= identifier '(' expression* ')'
338static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
339 std::string IdName = IdentifierStr;
340
Lang Hames59b0da82015-08-19 18:15:58 +0000341 getNextToken(); // eat identifier.
342
343 if (CurTok != '(') // Simple variable ref.
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000344 return llvm::make_unique<VariableExprAST>(IdName);
Lang Hames59b0da82015-08-19 18:15:58 +0000345
346 // Call.
347 getNextToken(); // eat (
348 std::vector<std::unique_ptr<ExprAST>> Args;
349 if (CurTok != ')') {
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000350 while (true) {
Lang Hames59b0da82015-08-19 18:15:58 +0000351 if (auto Arg = ParseExpression())
352 Args.push_back(std::move(Arg));
353 else
354 return nullptr;
355
356 if (CurTok == ')')
357 break;
358
359 if (CurTok != ',')
Lang Hamesf9878c52016-03-25 17:33:32 +0000360 return LogError("Expected ')' or ',' in argument list");
Lang Hames59b0da82015-08-19 18:15:58 +0000361 getNextToken();
362 }
363 }
364
365 // Eat the ')'.
366 getNextToken();
367
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000368 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
Lang Hames59b0da82015-08-19 18:15:58 +0000369}
370
Eric Christopher05917fa2014-12-08 18:00:47 +0000371/// ifexpr ::= 'if' expression 'then' expression 'else' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000372static std::unique_ptr<ExprAST> ParseIfExpr() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000373 getNextToken(); // eat the if.
374
375 // condition.
Lang Hames09bf4c12015-08-18 18:11:06 +0000376 auto Cond = ParseExpression();
Eric Christopher05917fa2014-12-08 18:00:47 +0000377 if (!Cond)
Lang Hames09bf4c12015-08-18 18:11:06 +0000378 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000379
380 if (CurTok != tok_then)
Lang Hamesf9878c52016-03-25 17:33:32 +0000381 return LogError("expected then");
Eric Christopher05917fa2014-12-08 18:00:47 +0000382 getNextToken(); // eat the then
383
Lang Hames09bf4c12015-08-18 18:11:06 +0000384 auto Then = ParseExpression();
385 if (!Then)
386 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000387
388 if (CurTok != tok_else)
Lang Hamesf9878c52016-03-25 17:33:32 +0000389 return LogError("expected else");
Eric Christopher05917fa2014-12-08 18:00:47 +0000390
391 getNextToken();
392
Lang Hames09bf4c12015-08-18 18:11:06 +0000393 auto Else = ParseExpression();
Eric Christopher05917fa2014-12-08 18:00:47 +0000394 if (!Else)
Lang Hames09bf4c12015-08-18 18:11:06 +0000395 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000396
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000397 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
Lang Hames09bf4c12015-08-18 18:11:06 +0000398 std::move(Else));
Eric Christopher05917fa2014-12-08 18:00:47 +0000399}
400
401/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000402static std::unique_ptr<ExprAST> ParseForExpr() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000403 getNextToken(); // eat the for.
404
405 if (CurTok != tok_identifier)
Lang Hamesf9878c52016-03-25 17:33:32 +0000406 return LogError("expected identifier after for");
Eric Christopher05917fa2014-12-08 18:00:47 +0000407
408 std::string IdName = IdentifierStr;
409 getNextToken(); // eat identifier.
410
411 if (CurTok != '=')
Lang Hamesf9878c52016-03-25 17:33:32 +0000412 return LogError("expected '=' after for");
Eric Christopher05917fa2014-12-08 18:00:47 +0000413 getNextToken(); // eat '='.
414
Lang Hames09bf4c12015-08-18 18:11:06 +0000415 auto Start = ParseExpression();
416 if (!Start)
417 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000418 if (CurTok != ',')
Lang Hamesf9878c52016-03-25 17:33:32 +0000419 return LogError("expected ',' after for start value");
Eric Christopher05917fa2014-12-08 18:00:47 +0000420 getNextToken();
421
Lang Hames09bf4c12015-08-18 18:11:06 +0000422 auto End = ParseExpression();
423 if (!End)
424 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000425
426 // The step value is optional.
Lang Hames09bf4c12015-08-18 18:11:06 +0000427 std::unique_ptr<ExprAST> Step;
Eric Christopher05917fa2014-12-08 18:00:47 +0000428 if (CurTok == ',') {
429 getNextToken();
430 Step = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000431 if (!Step)
432 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000433 }
434
435 if (CurTok != tok_in)
Lang Hamesf9878c52016-03-25 17:33:32 +0000436 return LogError("expected 'in' after for");
Eric Christopher05917fa2014-12-08 18:00:47 +0000437 getNextToken(); // eat 'in'.
438
Lang Hames09bf4c12015-08-18 18:11:06 +0000439 auto Body = ParseExpression();
440 if (!Body)
441 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000442
Lang Hames09bf4c12015-08-18 18:11:06 +0000443 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
444 std::move(Step), std::move(Body));
Eric Christopher05917fa2014-12-08 18:00:47 +0000445}
446
447/// varexpr ::= 'var' identifier ('=' expression)?
448// (',' identifier ('=' expression)?)* 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000449static std::unique_ptr<ExprAST> ParseVarExpr() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000450 getNextToken(); // eat the var.
451
Lang Hames09bf4c12015-08-18 18:11:06 +0000452 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
Eric Christopher05917fa2014-12-08 18:00:47 +0000453
454 // At least one variable name is required.
455 if (CurTok != tok_identifier)
Lang Hamesf9878c52016-03-25 17:33:32 +0000456 return LogError("expected identifier after var");
Eric Christopher05917fa2014-12-08 18:00:47 +0000457
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000458 while (true) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000459 std::string Name = IdentifierStr;
460 getNextToken(); // eat identifier.
461
462 // Read the optional initializer.
Lang Hames09bf4c12015-08-18 18:11:06 +0000463 std::unique_ptr<ExprAST> Init = nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000464 if (CurTok == '=') {
465 getNextToken(); // eat the '='.
466
467 Init = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000468 if (!Init)
469 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000470 }
471
Lang Hames09bf4c12015-08-18 18:11:06 +0000472 VarNames.push_back(std::make_pair(Name, std::move(Init)));
Eric Christopher05917fa2014-12-08 18:00:47 +0000473
474 // End of var list, exit loop.
475 if (CurTok != ',')
476 break;
477 getNextToken(); // eat the ','.
478
479 if (CurTok != tok_identifier)
Lang Hamesf9878c52016-03-25 17:33:32 +0000480 return LogError("expected identifier list after var");
Eric Christopher05917fa2014-12-08 18:00:47 +0000481 }
482
483 // At this point, we have to have 'in'.
484 if (CurTok != tok_in)
Lang Hamesf9878c52016-03-25 17:33:32 +0000485 return LogError("expected 'in' keyword after 'var'");
Eric Christopher05917fa2014-12-08 18:00:47 +0000486 getNextToken(); // eat 'in'.
487
Lang Hames09bf4c12015-08-18 18:11:06 +0000488 auto Body = ParseExpression();
489 if (!Body)
490 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000491
Lang Hames09bf4c12015-08-18 18:11:06 +0000492 return llvm::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
Eric Christopher05917fa2014-12-08 18:00:47 +0000493}
494
495/// primary
496/// ::= identifierexpr
497/// ::= numberexpr
498/// ::= parenexpr
499/// ::= ifexpr
500/// ::= forexpr
501/// ::= varexpr
Lang Hames09bf4c12015-08-18 18:11:06 +0000502static std::unique_ptr<ExprAST> ParsePrimary() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000503 switch (CurTok) {
504 default:
Lang Hamesf9878c52016-03-25 17:33:32 +0000505 return LogError("unknown token when expecting an expression");
Eric Christopher05917fa2014-12-08 18:00:47 +0000506 case tok_identifier:
507 return ParseIdentifierExpr();
508 case tok_number:
509 return ParseNumberExpr();
510 case '(':
511 return ParseParenExpr();
512 case tok_if:
513 return ParseIfExpr();
514 case tok_for:
515 return ParseForExpr();
516 case tok_var:
517 return ParseVarExpr();
518 }
519}
520
521/// unary
522/// ::= primary
523/// ::= '!' unary
Lang Hames09bf4c12015-08-18 18:11:06 +0000524static std::unique_ptr<ExprAST> ParseUnary() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000525 // If the current token is not an operator, it must be a primary expr.
526 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
527 return ParsePrimary();
528
529 // If this is a unary operator, read it.
530 int Opc = CurTok;
531 getNextToken();
Lang Hames09bf4c12015-08-18 18:11:06 +0000532 if (auto Operand = ParseUnary())
533 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
534 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000535}
536
537/// binoprhs
538/// ::= ('+' unary)*
Lang Hames59b0da82015-08-19 18:15:58 +0000539static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
540 std::unique_ptr<ExprAST> LHS) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000541 // If this is a binop, find its precedence.
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000542 while (true) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000543 int TokPrec = GetTokPrecedence();
544
545 // If this is a binop that binds at least as tightly as the current binop,
546 // consume it, otherwise we are done.
547 if (TokPrec < ExprPrec)
548 return LHS;
549
550 // Okay, we know this is a binop.
551 int BinOp = CurTok;
Eric Christopher05917fa2014-12-08 18:00:47 +0000552 getNextToken(); // eat binop
553
554 // Parse the unary expression after the binary operator.
Lang Hames09bf4c12015-08-18 18:11:06 +0000555 auto RHS = ParseUnary();
Eric Christopher05917fa2014-12-08 18:00:47 +0000556 if (!RHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000557 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000558
559 // If BinOp binds less tightly with RHS than the operator after RHS, let
560 // the pending operator take RHS as its LHS.
561 int NextPrec = GetTokPrecedence();
562 if (TokPrec < NextPrec) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000563 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
564 if (!RHS)
565 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000566 }
567
568 // Merge LHS/RHS.
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000569 LHS =
570 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
Eric Christopher05917fa2014-12-08 18:00:47 +0000571 }
572}
573
574/// expression
575/// ::= unary binoprhs
576///
Lang Hames09bf4c12015-08-18 18:11:06 +0000577static std::unique_ptr<ExprAST> ParseExpression() {
578 auto LHS = ParseUnary();
Eric Christopher05917fa2014-12-08 18:00:47 +0000579 if (!LHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000580 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000581
Lang Hames09bf4c12015-08-18 18:11:06 +0000582 return ParseBinOpRHS(0, std::move(LHS));
Eric Christopher05917fa2014-12-08 18:00:47 +0000583}
584
585/// prototype
586/// ::= id '(' id* ')'
587/// ::= binary LETTER number? (id, id)
588/// ::= unary LETTER (id)
Lang Hames09bf4c12015-08-18 18:11:06 +0000589static std::unique_ptr<PrototypeAST> ParsePrototype() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000590 std::string FnName;
591
Eric Christopher05917fa2014-12-08 18:00:47 +0000592 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
593 unsigned BinaryPrecedence = 30;
594
595 switch (CurTok) {
596 default:
Lang Hamesf9878c52016-03-25 17:33:32 +0000597 return LogErrorP("Expected function name in prototype");
Eric Christopher05917fa2014-12-08 18:00:47 +0000598 case tok_identifier:
599 FnName = IdentifierStr;
600 Kind = 0;
601 getNextToken();
602 break;
603 case tok_unary:
604 getNextToken();
605 if (!isascii(CurTok))
Lang Hamesf9878c52016-03-25 17:33:32 +0000606 return LogErrorP("Expected unary operator");
Eric Christopher05917fa2014-12-08 18:00:47 +0000607 FnName = "unary";
608 FnName += (char)CurTok;
609 Kind = 1;
610 getNextToken();
611 break;
612 case tok_binary:
613 getNextToken();
614 if (!isascii(CurTok))
Lang Hamesf9878c52016-03-25 17:33:32 +0000615 return LogErrorP("Expected binary operator");
Eric Christopher05917fa2014-12-08 18:00:47 +0000616 FnName = "binary";
617 FnName += (char)CurTok;
618 Kind = 2;
619 getNextToken();
620
621 // Read the precedence if present.
622 if (CurTok == tok_number) {
623 if (NumVal < 1 || NumVal > 100)
Lang Hamesf9878c52016-03-25 17:33:32 +0000624 return LogErrorP("Invalid precedecnce: must be 1..100");
Eric Christopher05917fa2014-12-08 18:00:47 +0000625 BinaryPrecedence = (unsigned)NumVal;
626 getNextToken();
627 }
628 break;
629 }
630
631 if (CurTok != '(')
Lang Hamesf9878c52016-03-25 17:33:32 +0000632 return LogErrorP("Expected '(' in prototype");
Eric Christopher05917fa2014-12-08 18:00:47 +0000633
634 std::vector<std::string> ArgNames;
635 while (getNextToken() == tok_identifier)
636 ArgNames.push_back(IdentifierStr);
637 if (CurTok != ')')
Lang Hamesf9878c52016-03-25 17:33:32 +0000638 return LogErrorP("Expected ')' in prototype");
Eric Christopher05917fa2014-12-08 18:00:47 +0000639
640 // success.
641 getNextToken(); // eat ')'.
642
643 // Verify right number of names for operator.
644 if (Kind && ArgNames.size() != Kind)
Lang Hamesf9878c52016-03-25 17:33:32 +0000645 return LogErrorP("Invalid number of operands for operator");
Eric Christopher05917fa2014-12-08 18:00:47 +0000646
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000647 return llvm::make_unique<PrototypeAST>(FnName, ArgNames, Kind != 0,
Lang Hames09bf4c12015-08-18 18:11:06 +0000648 BinaryPrecedence);
Eric Christopher05917fa2014-12-08 18:00:47 +0000649}
650
651/// definition ::= 'def' prototype expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000652static std::unique_ptr<FunctionAST> ParseDefinition() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000653 getNextToken(); // eat def.
Lang Hames09bf4c12015-08-18 18:11:06 +0000654 auto Proto = ParsePrototype();
655 if (!Proto)
656 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000657
Lang Hames09bf4c12015-08-18 18:11:06 +0000658 if (auto E = ParseExpression())
659 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
660 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000661}
662
663/// toplevelexpr ::= expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000664static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
Lang Hames09bf4c12015-08-18 18:11:06 +0000665 if (auto E = ParseExpression()) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000666 // Make an anonymous proto.
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000667 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
Lang Hames59b0da82015-08-19 18:15:58 +0000668 std::vector<std::string>());
Lang Hames09bf4c12015-08-18 18:11:06 +0000669 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
Eric Christopher05917fa2014-12-08 18:00:47 +0000670 }
Lang Hames09bf4c12015-08-18 18:11:06 +0000671 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000672}
673
674/// external ::= 'extern' prototype
Lang Hames09bf4c12015-08-18 18:11:06 +0000675static std::unique_ptr<PrototypeAST> ParseExtern() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000676 getNextToken(); // eat extern.
677 return ParsePrototype();
678}
679
680//===----------------------------------------------------------------------===//
Eric Christopher05917fa2014-12-08 18:00:47 +0000681// Code Generation
682//===----------------------------------------------------------------------===//
683
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000684static LLVMContext TheContext;
685static IRBuilder<> Builder(TheContext);
Lang Hames2d789c32015-08-26 03:07:41 +0000686static std::unique_ptr<Module> TheModule;
Eric Christopher05917fa2014-12-08 18:00:47 +0000687static std::map<std::string, AllocaInst *> NamedValues;
Lang Hames2d789c32015-08-26 03:07:41 +0000688static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
Eric Christopher05917fa2014-12-08 18:00:47 +0000689
Lang Hamesf9878c52016-03-25 17:33:32 +0000690Value *LogErrorV(const char *Str) {
691 LogError(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000692 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000693}
694
Lang Hames2d789c32015-08-26 03:07:41 +0000695Function *getFunction(std::string Name) {
696 // First, see if the function has already been added to the current module.
697 if (auto *F = TheModule->getFunction(Name))
698 return F;
699
700 // If not, check whether we can codegen the declaration from some existing
701 // prototype.
702 auto FI = FunctionProtos.find(Name);
703 if (FI != FunctionProtos.end())
704 return FI->second->codegen();
705
706 // If no existing prototype exists, return null.
707 return nullptr;
708}
709
Eric Christopher05917fa2014-12-08 18:00:47 +0000710/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
711/// the function. This is used for mutable variables etc.
712static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
713 const std::string &VarName) {
714 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
715 TheFunction->getEntryBlock().begin());
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000716 return TmpB.CreateAlloca(Type::getDoubleTy(TheContext), nullptr, VarName);
Eric Christopher05917fa2014-12-08 18:00:47 +0000717}
718
Lang Hames2d789c32015-08-26 03:07:41 +0000719Value *NumberExprAST::codegen() {
Mehdi Amini03b42e42016-04-14 21:59:01 +0000720 return ConstantFP::get(TheContext, APFloat(Val));
Eric Christopher05917fa2014-12-08 18:00:47 +0000721}
722
Lang Hames2d789c32015-08-26 03:07:41 +0000723Value *VariableExprAST::codegen() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000724 // Look this variable up in the function.
725 Value *V = NamedValues[Name];
Lang Hames09bf4c12015-08-18 18:11:06 +0000726 if (!V)
Lang Hamesf9878c52016-03-25 17:33:32 +0000727 return LogErrorV("Unknown variable name");
Eric Christopher05917fa2014-12-08 18:00:47 +0000728
Eric Christopher05917fa2014-12-08 18:00:47 +0000729 // Load the value.
730 return Builder.CreateLoad(V, Name.c_str());
731}
732
Lang Hames2d789c32015-08-26 03:07:41 +0000733Value *UnaryExprAST::codegen() {
734 Value *OperandV = Operand->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000735 if (!OperandV)
736 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000737
Lang Hames2d789c32015-08-26 03:07:41 +0000738 Function *F = getFunction(std::string("unary") + Opcode);
Lang Hames09bf4c12015-08-18 18:11:06 +0000739 if (!F)
Lang Hamesf9878c52016-03-25 17:33:32 +0000740 return LogErrorV("Unknown unary operator");
Eric Christopher05917fa2014-12-08 18:00:47 +0000741
Eric Christopher05917fa2014-12-08 18:00:47 +0000742 return Builder.CreateCall(F, OperandV, "unop");
743}
744
Lang Hames2d789c32015-08-26 03:07:41 +0000745Value *BinaryExprAST::codegen() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000746 // Special case '=' because we don't want to emit the LHS as an expression.
747 if (Op == '=') {
748 // Assignment requires the LHS to be an identifier.
Lang Hamese7c28bc2015-04-22 20:41:34 +0000749 // This assume we're building without RTTI because LLVM builds that way by
750 // default. If you build LLVM with RTTI this can be changed to a
751 // dynamic_cast for automatic error checking.
Lang Hames59b0da82015-08-19 18:15:58 +0000752 VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS.get());
Eric Christopher05917fa2014-12-08 18:00:47 +0000753 if (!LHSE)
Lang Hamesf9878c52016-03-25 17:33:32 +0000754 return LogErrorV("destination of '=' must be a variable");
Eric Christopher05917fa2014-12-08 18:00:47 +0000755 // Codegen the RHS.
Lang Hames2d789c32015-08-26 03:07:41 +0000756 Value *Val = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000757 if (!Val)
758 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000759
760 // Look up the name.
761 Value *Variable = NamedValues[LHSE->getName()];
Lang Hames09bf4c12015-08-18 18:11:06 +0000762 if (!Variable)
Lang Hamesf9878c52016-03-25 17:33:32 +0000763 return LogErrorV("Unknown variable name");
Eric Christopher05917fa2014-12-08 18:00:47 +0000764
765 Builder.CreateStore(Val, Variable);
766 return Val;
767 }
768
Lang Hames2d789c32015-08-26 03:07:41 +0000769 Value *L = LHS->codegen();
770 Value *R = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000771 if (!L || !R)
772 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000773
774 switch (Op) {
775 case '+':
776 return Builder.CreateFAdd(L, R, "addtmp");
777 case '-':
778 return Builder.CreateFSub(L, R, "subtmp");
779 case '*':
780 return Builder.CreateFMul(L, R, "multmp");
781 case '<':
782 L = Builder.CreateFCmpULT(L, R, "cmptmp");
783 // Convert bool 0/1 to double 0.0 or 1.0
Mehdi Amini03b42e42016-04-14 21:59:01 +0000784 return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext), "booltmp");
Eric Christopher05917fa2014-12-08 18:00:47 +0000785 default:
786 break;
787 }
788
789 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
790 // a call to it.
Lang Hames2d789c32015-08-26 03:07:41 +0000791 Function *F = getFunction(std::string("binary") + Op);
Eric Christopher05917fa2014-12-08 18:00:47 +0000792 assert(F && "binary operator not found!");
793
Lang Hames59b0da82015-08-19 18:15:58 +0000794 Value *Ops[] = {L, R};
Eric Christopher05917fa2014-12-08 18:00:47 +0000795 return Builder.CreateCall(F, Ops, "binop");
796}
797
Lang Hames2d789c32015-08-26 03:07:41 +0000798Value *CallExprAST::codegen() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000799 // Look up the name in the global module table.
Lang Hames2d789c32015-08-26 03:07:41 +0000800 Function *CalleeF = getFunction(Callee);
Lang Hames09bf4c12015-08-18 18:11:06 +0000801 if (!CalleeF)
Lang Hamesf9878c52016-03-25 17:33:32 +0000802 return LogErrorV("Unknown function referenced");
Eric Christopher05917fa2014-12-08 18:00:47 +0000803
804 // If argument mismatch error.
805 if (CalleeF->arg_size() != Args.size())
Lang Hamesf9878c52016-03-25 17:33:32 +0000806 return LogErrorV("Incorrect # arguments passed");
Eric Christopher05917fa2014-12-08 18:00:47 +0000807
808 std::vector<Value *> ArgsV;
809 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Lang Hames2d789c32015-08-26 03:07:41 +0000810 ArgsV.push_back(Args[i]->codegen());
Lang Hames09bf4c12015-08-18 18:11:06 +0000811 if (!ArgsV.back())
812 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000813 }
814
815 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
816}
817
Lang Hames2d789c32015-08-26 03:07:41 +0000818Value *IfExprAST::codegen() {
Lang Hames2d789c32015-08-26 03:07:41 +0000819 Value *CondV = Cond->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000820 if (!CondV)
821 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000822
823 // Convert condition to a bool by comparing equal to 0.0.
824 CondV = Builder.CreateFCmpONE(
Mehdi Amini03b42e42016-04-14 21:59:01 +0000825 CondV, ConstantFP::get(TheContext, APFloat(0.0)), "ifcond");
Eric Christopher05917fa2014-12-08 18:00:47 +0000826
827 Function *TheFunction = Builder.GetInsertBlock()->getParent();
828
829 // Create blocks for the then and else cases. Insert the 'then' block at the
830 // end of the function.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000831 BasicBlock *ThenBB = BasicBlock::Create(TheContext, "then", TheFunction);
832 BasicBlock *ElseBB = BasicBlock::Create(TheContext, "else");
833 BasicBlock *MergeBB = BasicBlock::Create(TheContext, "ifcont");
Eric Christopher05917fa2014-12-08 18:00:47 +0000834
835 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
836
837 // Emit then value.
838 Builder.SetInsertPoint(ThenBB);
839
Lang Hames2d789c32015-08-26 03:07:41 +0000840 Value *ThenV = Then->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000841 if (!ThenV)
842 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000843
844 Builder.CreateBr(MergeBB);
845 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
846 ThenBB = Builder.GetInsertBlock();
847
848 // Emit else block.
849 TheFunction->getBasicBlockList().push_back(ElseBB);
850 Builder.SetInsertPoint(ElseBB);
851
Lang Hames2d789c32015-08-26 03:07:41 +0000852 Value *ElseV = Else->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000853 if (!ElseV)
854 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000855
856 Builder.CreateBr(MergeBB);
857 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
858 ElseBB = Builder.GetInsertBlock();
859
860 // Emit merge block.
861 TheFunction->getBasicBlockList().push_back(MergeBB);
862 Builder.SetInsertPoint(MergeBB);
Mehdi Amini03b42e42016-04-14 21:59:01 +0000863 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(TheContext), 2, "iftmp");
Eric Christopher05917fa2014-12-08 18:00:47 +0000864
865 PN->addIncoming(ThenV, ThenBB);
866 PN->addIncoming(ElseV, ElseBB);
867 return PN;
868}
869
Lang Hames59b0da82015-08-19 18:15:58 +0000870// Output for-loop as:
871// var = alloca double
872// ...
873// start = startexpr
874// store start -> var
875// goto loop
876// loop:
877// ...
878// bodyexpr
879// ...
880// loopend:
881// step = stepexpr
882// endcond = endexpr
883//
884// curvar = load var
885// nextvar = curvar + step
886// store nextvar -> var
887// br endcond, loop, endloop
888// outloop:
Lang Hames2d789c32015-08-26 03:07:41 +0000889Value *ForExprAST::codegen() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000890 Function *TheFunction = Builder.GetInsertBlock()->getParent();
891
892 // Create an alloca for the variable in the entry block.
893 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
894
Eric Christopher05917fa2014-12-08 18:00:47 +0000895 // Emit the start code first, without 'variable' in scope.
Lang Hames2d789c32015-08-26 03:07:41 +0000896 Value *StartVal = Start->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000897 if (!StartVal)
898 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000899
900 // Store the value into the alloca.
901 Builder.CreateStore(StartVal, Alloca);
902
903 // Make the new basic block for the loop header, inserting after current
904 // block.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000905 BasicBlock *LoopBB = BasicBlock::Create(TheContext, "loop", TheFunction);
Eric Christopher05917fa2014-12-08 18:00:47 +0000906
907 // Insert an explicit fall through from the current block to the LoopBB.
908 Builder.CreateBr(LoopBB);
909
910 // Start insertion in LoopBB.
911 Builder.SetInsertPoint(LoopBB);
912
913 // Within the loop, the variable is defined equal to the PHI node. If it
914 // shadows an existing variable, we have to restore it, so save it now.
915 AllocaInst *OldVal = NamedValues[VarName];
916 NamedValues[VarName] = Alloca;
917
918 // Emit the body of the loop. This, like any other expr, can change the
919 // current BB. Note that we ignore the value computed by the body, but don't
920 // allow an error.
Lang Hames2d789c32015-08-26 03:07:41 +0000921 if (!Body->codegen())
Lang Hames09bf4c12015-08-18 18:11:06 +0000922 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000923
924 // Emit the step value.
Lang Hames59b0da82015-08-19 18:15:58 +0000925 Value *StepVal = nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000926 if (Step) {
Lang Hames2d789c32015-08-26 03:07:41 +0000927 StepVal = Step->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000928 if (!StepVal)
929 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000930 } else {
931 // If not specified, use 1.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000932 StepVal = ConstantFP::get(TheContext, APFloat(1.0));
Eric Christopher05917fa2014-12-08 18:00:47 +0000933 }
934
935 // Compute the end condition.
Lang Hames2d789c32015-08-26 03:07:41 +0000936 Value *EndCond = End->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000937 if (!EndCond)
Lang Hames59b0da82015-08-19 18:15:58 +0000938 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000939
940 // Reload, increment, and restore the alloca. This handles the case where
941 // the body of the loop mutates the variable.
942 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
943 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
944 Builder.CreateStore(NextVar, Alloca);
945
946 // Convert condition to a bool by comparing equal to 0.0.
947 EndCond = Builder.CreateFCmpONE(
Mehdi Amini03b42e42016-04-14 21:59:01 +0000948 EndCond, ConstantFP::get(TheContext, APFloat(0.0)), "loopcond");
Eric Christopher05917fa2014-12-08 18:00:47 +0000949
950 // Create the "after loop" block and insert it.
951 BasicBlock *AfterBB =
Mehdi Amini03b42e42016-04-14 21:59:01 +0000952 BasicBlock::Create(TheContext, "afterloop", TheFunction);
Eric Christopher05917fa2014-12-08 18:00:47 +0000953
954 // Insert the conditional branch into the end of LoopEndBB.
955 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
956
957 // Any new code will be inserted in AfterBB.
958 Builder.SetInsertPoint(AfterBB);
959
960 // Restore the unshadowed variable.
961 if (OldVal)
962 NamedValues[VarName] = OldVal;
963 else
964 NamedValues.erase(VarName);
965
966 // for expr always returns 0.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000967 return Constant::getNullValue(Type::getDoubleTy(TheContext));
Eric Christopher05917fa2014-12-08 18:00:47 +0000968}
969
Lang Hames2d789c32015-08-26 03:07:41 +0000970Value *VarExprAST::codegen() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000971 std::vector<AllocaInst *> OldBindings;
972
973 Function *TheFunction = Builder.GetInsertBlock()->getParent();
974
975 // Register all variables and emit their initializer.
976 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
977 const std::string &VarName = VarNames[i].first;
Lang Hames09bf4c12015-08-18 18:11:06 +0000978 ExprAST *Init = VarNames[i].second.get();
Eric Christopher05917fa2014-12-08 18:00:47 +0000979
980 // Emit the initializer before adding the variable to scope, this prevents
981 // the initializer from referencing the variable itself, and permits stuff
982 // like this:
983 // var a = 1 in
984 // var a = a in ... # refers to outer 'a'.
985 Value *InitVal;
986 if (Init) {
Lang Hames2d789c32015-08-26 03:07:41 +0000987 InitVal = Init->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000988 if (!InitVal)
989 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000990 } else { // If not specified, use 0.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000991 InitVal = ConstantFP::get(TheContext, APFloat(0.0));
Eric Christopher05917fa2014-12-08 18:00:47 +0000992 }
993
994 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
995 Builder.CreateStore(InitVal, Alloca);
996
997 // Remember the old variable binding so that we can restore the binding when
998 // we unrecurse.
999 OldBindings.push_back(NamedValues[VarName]);
1000
1001 // Remember this binding.
1002 NamedValues[VarName] = Alloca;
1003 }
1004
Eric Christopher05917fa2014-12-08 18:00:47 +00001005 // Codegen the body, now that all vars are in scope.
Lang Hames2d789c32015-08-26 03:07:41 +00001006 Value *BodyVal = Body->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001007 if (!BodyVal)
1008 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001009
1010 // Pop all our variables from scope.
1011 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1012 NamedValues[VarNames[i].first] = OldBindings[i];
1013
1014 // Return the body computation.
1015 return BodyVal;
1016}
1017
Lang Hames2d789c32015-08-26 03:07:41 +00001018Function *PrototypeAST::codegen() {
Eric Christopher05917fa2014-12-08 18:00:47 +00001019 // Make the function type: double(double,double) etc.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001020 std::vector<Type *> Doubles(Args.size(), Type::getDoubleTy(TheContext));
Eric Christopher05917fa2014-12-08 18:00:47 +00001021 FunctionType *FT =
Mehdi Amini03b42e42016-04-14 21:59:01 +00001022 FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);
Eric Christopher05917fa2014-12-08 18:00:47 +00001023
1024 Function *F =
Lang Hames2d789c32015-08-26 03:07:41 +00001025 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
Eric Christopher05917fa2014-12-08 18:00:47 +00001026
1027 // Set names for all arguments.
1028 unsigned Idx = 0;
Lang Hames2d789c32015-08-26 03:07:41 +00001029 for (auto &Arg : F->args())
1030 Arg.setName(Args[Idx++]);
1031
1032 return F;
1033}
1034
1035Function *FunctionAST::codegen() {
1036 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
1037 // reference to it for use below.
1038 auto &P = *Proto;
1039 FunctionProtos[Proto->getName()] = std::move(Proto);
1040 Function *TheFunction = getFunction(P.getName());
1041 if (!TheFunction)
1042 return nullptr;
1043
1044 // If this is an operator, install it.
1045 if (P.isBinaryOp())
1046 BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
1047
1048 // Create a new basic block to start insertion into.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001049 BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
Lang Hames2d789c32015-08-26 03:07:41 +00001050 Builder.SetInsertPoint(BB);
Eric Christopher05917fa2014-12-08 18:00:47 +00001051
Lang Hames2d789c32015-08-26 03:07:41 +00001052 // Record the function arguments in the NamedValues map.
1053 NamedValues.clear();
Lang Hames2d789c32015-08-26 03:07:41 +00001054 for (auto &Arg : TheFunction->args()) {
1055 // Create an alloca for this variable.
1056 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName());
Eric Christopher05917fa2014-12-08 18:00:47 +00001057
Lang Hames2d789c32015-08-26 03:07:41 +00001058 // Store the initial value into the alloca.
1059 Builder.CreateStore(&Arg, Alloca);
1060
1061 // Add arguments to variable symbol table.
1062 NamedValues[Arg.getName()] = Alloca;
1063 }
Eric Christopher05917fa2014-12-08 18:00:47 +00001064
Lang Hames2d789c32015-08-26 03:07:41 +00001065 if (Value *RetVal = Body->codegen()) {
Eric Christopher05917fa2014-12-08 18:00:47 +00001066 // Finish off the function.
1067 Builder.CreateRet(RetVal);
1068
Eric Christopher05917fa2014-12-08 18:00:47 +00001069 // Validate the generated code, checking for consistency.
1070 verifyFunction(*TheFunction);
1071
Eric Christopher05917fa2014-12-08 18:00:47 +00001072 return TheFunction;
1073 }
1074
1075 // Error reading body, remove function.
1076 TheFunction->eraseFromParent();
1077
Lang Hames2d789c32015-08-26 03:07:41 +00001078 if (P.isBinaryOp())
Eric Christopher05917fa2014-12-08 18:00:47 +00001079 BinopPrecedence.erase(Proto->getOperatorName());
Lang Hames09bf4c12015-08-18 18:11:06 +00001080 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001081}
1082
1083//===----------------------------------------------------------------------===//
1084// Top-Level parsing and JIT Driver
1085//===----------------------------------------------------------------------===//
1086
Wilfred Hughes945f43e2016-07-02 17:01:59 +00001087static void InitializeModuleAndPassManager() {
Lang Hames2d789c32015-08-26 03:07:41 +00001088 // Open a new module.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001089 TheModule = llvm::make_unique<Module>("my cool jit", TheContext);
Lang Hames2d789c32015-08-26 03:07:41 +00001090}
Eric Christopher05917fa2014-12-08 18:00:47 +00001091
1092static void HandleDefinition() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001093 if (auto FnAST = ParseDefinition()) {
Wilfred Hughes945f43e2016-07-02 17:01:59 +00001094 if (auto *FnIR = FnAST->codegen()) {
1095 fprintf(stderr, "Read function definition:");
1096 FnIR->dump();
1097 }
Eric Christopher05917fa2014-12-08 18:00:47 +00001098 } else {
1099 // Skip token for error recovery.
1100 getNextToken();
1101 }
1102}
1103
1104static void HandleExtern() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001105 if (auto ProtoAST = ParseExtern()) {
Wilfred Hughes945f43e2016-07-02 17:01:59 +00001106 if (auto *FnIR = ProtoAST->codegen()) {
1107 fprintf(stderr, "Read extern: ");
1108 FnIR->dump();
Lang Hames2d789c32015-08-26 03:07:41 +00001109 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
Wilfred Hughes945f43e2016-07-02 17:01:59 +00001110 }
Eric Christopher05917fa2014-12-08 18:00:47 +00001111 } else {
1112 // Skip token for error recovery.
1113 getNextToken();
1114 }
1115}
1116
1117static void HandleTopLevelExpression() {
1118 // Evaluate a top-level expression into an anonymous function.
Lang Hames09bf4c12015-08-18 18:11:06 +00001119 if (auto FnAST = ParseTopLevelExpr()) {
Wilfred Hughes945f43e2016-07-02 17:01:59 +00001120 FnAST->codegen();
Eric Christopher05917fa2014-12-08 18:00:47 +00001121 } else {
1122 // Skip token for error recovery.
1123 getNextToken();
1124 }
1125}
1126
1127/// top ::= definition | external | expression | ';'
1128static void MainLoop() {
Eugene Zelenkof981ec42016-05-19 01:08:04 +00001129 while (true) {
Eric Christopher05917fa2014-12-08 18:00:47 +00001130 switch (CurTok) {
1131 case tok_eof:
1132 return;
Lang Hames59b0da82015-08-19 18:15:58 +00001133 case ';': // ignore top-level semicolons.
Eric Christopher05917fa2014-12-08 18:00:47 +00001134 getNextToken();
Lang Hames59b0da82015-08-19 18:15:58 +00001135 break;
Eric Christopher05917fa2014-12-08 18:00:47 +00001136 case tok_def:
1137 HandleDefinition();
1138 break;
1139 case tok_extern:
1140 HandleExtern();
1141 break;
1142 default:
1143 HandleTopLevelExpression();
1144 break;
1145 }
1146 }
1147}
1148
1149//===----------------------------------------------------------------------===//
1150// "Library" functions that can be "extern'd" from user code.
1151//===----------------------------------------------------------------------===//
1152
1153/// putchard - putchar that takes a double and returns 0.
NAKAMURA Takumiac9d3732015-08-28 03:34:33 +00001154extern "C" double putchard(double X) {
Lang Hamesd76e0672015-08-27 20:31:44 +00001155 fputc((char)X, stderr);
Eric Christopher05917fa2014-12-08 18:00:47 +00001156 return 0;
1157}
1158
1159/// printd - printf that takes a double prints it as "%f\n", returning 0.
NAKAMURA Takumiac9d3732015-08-28 03:34:33 +00001160extern "C" double printd(double X) {
Lang Hamesd76e0672015-08-27 20:31:44 +00001161 fprintf(stderr, "%f\n", X);
Eric Christopher05917fa2014-12-08 18:00:47 +00001162 return 0;
1163}
1164
1165//===----------------------------------------------------------------------===//
1166// Main driver code.
1167//===----------------------------------------------------------------------===//
1168
1169int main() {
Eric Christopher05917fa2014-12-08 18:00:47 +00001170 // Install standard binary operators.
1171 // 1 is lowest precedence.
Eric Christopher05917fa2014-12-08 18:00:47 +00001172 BinopPrecedence['<'] = 10;
1173 BinopPrecedence['+'] = 20;
1174 BinopPrecedence['-'] = 20;
1175 BinopPrecedence['*'] = 40; // highest.
1176
1177 // Prime the first token.
Wilfred Hughes945f43e2016-07-02 17:01:59 +00001178 fprintf(stderr, "ready> ");
Eric Christopher05917fa2014-12-08 18:00:47 +00001179 getNextToken();
1180
Wilfred Hughes945f43e2016-07-02 17:01:59 +00001181 InitializeModuleAndPassManager();
Eric Christopher05917fa2014-12-08 18:00:47 +00001182
Eric Christopher05917fa2014-12-08 18:00:47 +00001183 // Run the main "interpreter loop" now.
1184 MainLoop();
1185
Wilfred Hughes945f43e2016-07-02 17:01:59 +00001186 // Initialize the target registry etc.
1187 InitializeAllTargetInfos();
1188 InitializeAllTargets();
1189 InitializeAllTargetMCs();
1190 InitializeAllAsmParsers();
1191 InitializeAllAsmPrinters();
Eric Christopher05917fa2014-12-08 18:00:47 +00001192
Wilfred Hughes945f43e2016-07-02 17:01:59 +00001193 auto TargetTriple = sys::getDefaultTargetTriple();
1194 TheModule->setTargetTriple(TargetTriple);
1195
1196 std::string Error;
1197 auto Target = TargetRegistry::lookupTarget(TargetTriple, Error);
1198
1199 // Print an error and exit if we couldn't find the requested target.
1200 // This generally occurs if we've forgotten to initialise the
1201 // TargetRegistry or we have a bogus target triple.
1202 if (!Target) {
1203 errs() << Error;
1204 return 1;
1205 }
1206
1207 auto CPU = "generic";
1208 auto Features = "";
1209
1210 TargetOptions opt;
1211 auto RM = Optional<Reloc::Model>();
1212 auto TheTargetMachine =
1213 Target->createTargetMachine(TargetTriple, CPU, Features, opt, RM);
1214
1215 TheModule->setDataLayout(TheTargetMachine->createDataLayout());
1216
1217 auto Filename = "output.o";
1218 std::error_code EC;
1219 raw_fd_ostream dest(Filename, EC, sys::fs::F_None);
1220
1221 if (EC) {
1222 errs() << "Could not open file: " << EC.message();
1223 return 1;
1224 }
1225
1226 legacy::PassManager pass;
1227 auto FileType = TargetMachine::CGFT_ObjectFile;
1228
1229 if (TheTargetMachine->addPassesToEmitFile(pass, dest, FileType)) {
1230 errs() << "TheTargetMachine can't emit a file of this type";
1231 return 1;
1232 }
1233
1234 pass.run(*TheModule);
1235 dest.flush();
1236
1237 outs() << "Wrote " << Filename << "\n";
Eric Christopher05917fa2014-12-08 18:00:47 +00001238
1239 return 0;
1240}