blob: fe8ec17b4e897ca308223366f225f82ae201c009 [file] [log] [blame]
Lang Hames09bf4c12015-08-18 18:11:06 +00001#include "llvm/ADT/STLExtras.h"
Chandler Carruth17e0bc32015-08-06 07:33:15 +00002#include "llvm/Analysis/BasicAliasAnalysis.h"
Chandler Carruth605e30e2012-12-04 10:16:57 +00003#include "llvm/Analysis/Passes.h"
Chandler Carruth005f27a2013-01-02 11:56:33 +00004#include "llvm/IR/IRBuilder.h"
5#include "llvm/IR/LLVMContext.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +00006#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth005f27a2013-01-02 11:56:33 +00007#include "llvm/IR/Module.h"
Chandler Carruth20d4e6b2014-01-13 09:58:03 +00008#include "llvm/IR/Verifier.h"
Evan Cheng2bb40352011-08-24 18:08:43 +00009#include "llvm/Support/TargetSelect.h"
Chandler Carruth605e30e2012-12-04 10:16:57 +000010#include "llvm/Transforms/Scalar.h"
Will Dietz981af002013-10-12 00:55:57 +000011#include <cctype>
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000012#include <cstdio>
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000013#include <map>
Chandler Carruth605e30e2012-12-04 10:16:57 +000014#include <string>
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000015#include <vector>
Lang Hames2d789c32015-08-26 03:07:41 +000016#include "../include/KaleidoscopeJIT.h"
17
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000018using namespace llvm;
Lang Hames2d789c32015-08-26 03:07:41 +000019using namespace llvm::orc;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000020
21//===----------------------------------------------------------------------===//
22// Lexer
23//===----------------------------------------------------------------------===//
24
25// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
26// of these for known things.
27enum Token {
28 tok_eof = -1,
29
30 // commands
Eric Christopherc0239362014-12-08 18:12:28 +000031 tok_def = -2,
32 tok_extern = -3,
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000033
34 // primary
Eric Christopherc0239362014-12-08 18:12:28 +000035 tok_identifier = -4,
36 tok_number = -5
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000037};
38
Eric Christopherc0239362014-12-08 18:12:28 +000039static std::string IdentifierStr; // Filled in if tok_identifier
40static double NumVal; // Filled in if tok_number
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000041
42/// gettok - Return the next token from standard input.
43static int gettok() {
44 static int LastChar = ' ';
45
46 // Skip any whitespace.
47 while (isspace(LastChar))
48 LastChar = getchar();
49
50 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
51 IdentifierStr = LastChar;
52 while (isalnum((LastChar = getchar())))
53 IdentifierStr += LastChar;
54
Eric Christopherc0239362014-12-08 18:12:28 +000055 if (IdentifierStr == "def")
56 return tok_def;
57 if (IdentifierStr == "extern")
58 return tok_extern;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000059 return tok_identifier;
60 }
61
Eric Christopherc0239362014-12-08 18:12:28 +000062 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000063 std::string NumStr;
64 do {
65 NumStr += LastChar;
66 LastChar = getchar();
67 } while (isdigit(LastChar) || LastChar == '.');
68
69 NumVal = strtod(NumStr.c_str(), 0);
70 return tok_number;
71 }
72
73 if (LastChar == '#') {
74 // Comment until end of line.
Eric Christopherc0239362014-12-08 18:12:28 +000075 do
76 LastChar = getchar();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000077 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
Eric Christopherc0239362014-12-08 18:12:28 +000078
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000079 if (LastChar != EOF)
80 return gettok();
81 }
Eric Christopherc0239362014-12-08 18:12:28 +000082
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000083 // Check for end of file. Don't eat the EOF.
84 if (LastChar == EOF)
85 return tok_eof;
86
87 // Otherwise, just return the character as its ascii value.
88 int ThisChar = LastChar;
89 LastChar = getchar();
90 return ThisChar;
91}
92
93//===----------------------------------------------------------------------===//
94// Abstract Syntax Tree (aka Parse Tree)
95//===----------------------------------------------------------------------===//
Juergen Ributzka05c5a932013-11-19 03:08:35 +000096namespace {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000097/// ExprAST - Base class for all expression nodes.
98class ExprAST {
99public:
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000100 virtual ~ExprAST() {}
Lang Hames2d789c32015-08-26 03:07:41 +0000101 virtual Value *codegen() = 0;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000102};
103
104/// NumberExprAST - Expression class for numeric literals like "1.0".
105class NumberExprAST : public ExprAST {
106 double Val;
Lang Hames59b0da82015-08-19 18:15:58 +0000107
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000108public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000109 NumberExprAST(double Val) : Val(Val) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000110 Value *codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000111};
112
113/// VariableExprAST - Expression class for referencing a variable, like "a".
114class VariableExprAST : public ExprAST {
115 std::string Name;
Lang Hames59b0da82015-08-19 18:15:58 +0000116
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000117public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000118 VariableExprAST(const std::string &Name) : Name(Name) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000119 Value *codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000120};
121
122/// BinaryExprAST - Expression class for a binary operator.
123class BinaryExprAST : public ExprAST {
124 char Op;
Lang Hames09bf4c12015-08-18 18:11:06 +0000125 std::unique_ptr<ExprAST> LHS, RHS;
Lang Hames59b0da82015-08-19 18:15:58 +0000126
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000127public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000128 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
129 std::unique_ptr<ExprAST> RHS)
130 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000131 Value *codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000132};
133
134/// CallExprAST - Expression class for function calls.
135class CallExprAST : public ExprAST {
136 std::string Callee;
Lang Hames09bf4c12015-08-18 18:11:06 +0000137 std::vector<std::unique_ptr<ExprAST>> Args;
Lang Hames59b0da82015-08-19 18:15:58 +0000138
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000139public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000140 CallExprAST(const std::string &Callee,
141 std::vector<std::unique_ptr<ExprAST>> Args)
142 : Callee(Callee), Args(std::move(Args)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000143 Value *codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000144};
145
146/// PrototypeAST - This class represents the "prototype" for a function,
147/// which captures its name, and its argument names (thus implicitly the number
148/// of arguments the function takes).
149class PrototypeAST {
150 std::string Name;
151 std::vector<std::string> Args;
Lang Hames59b0da82015-08-19 18:15:58 +0000152
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000153public:
Lang Hames59b0da82015-08-19 18:15:58 +0000154 PrototypeAST(const std::string &Name, std::vector<std::string> Args)
155 : Name(Name), Args(std::move(Args)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000156 Function *codegen();
157 const std::string &getName() const { return Name; }
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000158};
159
160/// FunctionAST - This class represents a function definition itself.
161class FunctionAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000162 std::unique_ptr<PrototypeAST> Proto;
163 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000164
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000165public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000166 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
167 std::unique_ptr<ExprAST> Body)
Lang Hames59b0da82015-08-19 18:15:58 +0000168 : Proto(std::move(Proto)), Body(std::move(Body)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000169 Function *codegen();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000170};
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000171} // end anonymous namespace
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000172
173//===----------------------------------------------------------------------===//
174// Parser
175//===----------------------------------------------------------------------===//
176
177/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
178/// token the parser is looking at. getNextToken reads another token from the
179/// lexer and updates CurTok with its results.
180static int CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000181static int getNextToken() { return CurTok = gettok(); }
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000182
183/// BinopPrecedence - This holds the precedence for each binary operator that is
184/// defined.
185static std::map<char, int> BinopPrecedence;
186
187/// GetTokPrecedence - Get the precedence of the pending binary operator token.
188static int GetTokPrecedence() {
189 if (!isascii(CurTok))
190 return -1;
Eric Christopherc0239362014-12-08 18:12:28 +0000191
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000192 // Make sure it's a declared binop.
193 int TokPrec = BinopPrecedence[CurTok];
Eric Christopherc0239362014-12-08 18:12:28 +0000194 if (TokPrec <= 0)
195 return -1;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000196 return TokPrec;
197}
198
199/// Error* - These are little helper functions for error handling.
Lang Hames09bf4c12015-08-18 18:11:06 +0000200std::unique_ptr<ExprAST> Error(const char *Str) {
Eric Christopherc0239362014-12-08 18:12:28 +0000201 fprintf(stderr, "Error: %s\n", Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000202 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000203}
Lang Hames09bf4c12015-08-18 18:11:06 +0000204std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
Eric Christopherc0239362014-12-08 18:12:28 +0000205 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000206 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000207}
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000208
Lang Hames09bf4c12015-08-18 18:11:06 +0000209static std::unique_ptr<ExprAST> ParseExpression();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000210
Lang Hames59b0da82015-08-19 18:15:58 +0000211/// numberexpr ::= number
212static std::unique_ptr<ExprAST> ParseNumberExpr() {
213 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
214 getNextToken(); // consume the number
215 return std::move(Result);
216}
217
218/// parenexpr ::= '(' expression ')'
219static std::unique_ptr<ExprAST> ParseParenExpr() {
220 getNextToken(); // eat (.
221 auto V = ParseExpression();
222 if (!V)
223 return nullptr;
224
225 if (CurTok != ')')
226 return Error("expected ')'");
227 getNextToken(); // eat ).
228 return V;
229}
230
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000231/// identifierexpr
232/// ::= identifier
233/// ::= identifier '(' expression* ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000234static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000235 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000236
237 getNextToken(); // eat identifier.
238
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000239 if (CurTok != '(') // Simple variable ref.
Lang Hames09bf4c12015-08-18 18:11:06 +0000240 return llvm::make_unique<VariableExprAST>(IdName);
Eric Christopherc0239362014-12-08 18:12:28 +0000241
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000242 // Call.
Eric Christopherc0239362014-12-08 18:12:28 +0000243 getNextToken(); // eat (
Lang Hames09bf4c12015-08-18 18:11:06 +0000244 std::vector<std::unique_ptr<ExprAST>> Args;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000245 if (CurTok != ')') {
246 while (1) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000247 if (auto Arg = ParseExpression())
248 Args.push_back(std::move(Arg));
249 else
250 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000251
Eric Christopherc0239362014-12-08 18:12:28 +0000252 if (CurTok == ')')
253 break;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000254
255 if (CurTok != ',')
256 return Error("Expected ')' or ',' in argument list");
257 getNextToken();
258 }
259 }
260
261 // Eat the ')'.
262 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000263
Lang Hames09bf4c12015-08-18 18:11:06 +0000264 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000265}
266
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000267/// primary
268/// ::= identifierexpr
269/// ::= numberexpr
270/// ::= parenexpr
Lang Hames09bf4c12015-08-18 18:11:06 +0000271static std::unique_ptr<ExprAST> ParsePrimary() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000272 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +0000273 default:
274 return Error("unknown token when expecting an expression");
275 case tok_identifier:
276 return ParseIdentifierExpr();
277 case tok_number:
278 return ParseNumberExpr();
279 case '(':
280 return ParseParenExpr();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000281 }
282}
283
284/// binoprhs
285/// ::= ('+' primary)*
Lang Hames09bf4c12015-08-18 18:11:06 +0000286static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
287 std::unique_ptr<ExprAST> LHS) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000288 // If this is a binop, find its precedence.
289 while (1) {
290 int TokPrec = GetTokPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +0000291
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000292 // If this is a binop that binds at least as tightly as the current binop,
293 // consume it, otherwise we are done.
294 if (TokPrec < ExprPrec)
295 return LHS;
Eric Christopherc0239362014-12-08 18:12:28 +0000296
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000297 // Okay, we know this is a binop.
298 int BinOp = CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000299 getNextToken(); // eat binop
300
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000301 // Parse the primary expression after the binary operator.
Lang Hames09bf4c12015-08-18 18:11:06 +0000302 auto RHS = ParsePrimary();
Eric Christopherc0239362014-12-08 18:12:28 +0000303 if (!RHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000304 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000305
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000306 // If BinOp binds less tightly with RHS than the operator after RHS, let
307 // the pending operator take RHS as its LHS.
308 int NextPrec = GetTokPrecedence();
309 if (TokPrec < NextPrec) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000310 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
311 if (!RHS)
312 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000313 }
Eric Christopherc0239362014-12-08 18:12:28 +0000314
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000315 // Merge LHS/RHS.
Lang Hames59b0da82015-08-19 18:15:58 +0000316 LHS =
317 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000318 }
319}
320
321/// expression
322/// ::= primary binoprhs
323///
Lang Hames09bf4c12015-08-18 18:11:06 +0000324static std::unique_ptr<ExprAST> ParseExpression() {
325 auto LHS = ParsePrimary();
Eric Christopherc0239362014-12-08 18:12:28 +0000326 if (!LHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000327 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000328
Lang Hames09bf4c12015-08-18 18:11:06 +0000329 return ParseBinOpRHS(0, std::move(LHS));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000330}
331
332/// prototype
333/// ::= id '(' id* ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000334static std::unique_ptr<PrototypeAST> ParsePrototype() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000335 if (CurTok != tok_identifier)
336 return ErrorP("Expected function name in prototype");
337
338 std::string FnName = IdentifierStr;
339 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000340
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000341 if (CurTok != '(')
342 return ErrorP("Expected '(' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000343
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000344 std::vector<std::string> ArgNames;
345 while (getNextToken() == tok_identifier)
346 ArgNames.push_back(IdentifierStr);
347 if (CurTok != ')')
348 return ErrorP("Expected ')' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000349
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000350 // success.
Eric Christopherc0239362014-12-08 18:12:28 +0000351 getNextToken(); // eat ')'.
352
Lang Hames09bf4c12015-08-18 18:11:06 +0000353 return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000354}
355
356/// definition ::= 'def' prototype expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000357static std::unique_ptr<FunctionAST> ParseDefinition() {
Eric Christopherc0239362014-12-08 18:12:28 +0000358 getNextToken(); // eat def.
Lang Hames09bf4c12015-08-18 18:11:06 +0000359 auto Proto = ParsePrototype();
360 if (!Proto)
361 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000362
Lang Hames09bf4c12015-08-18 18:11:06 +0000363 if (auto E = ParseExpression())
364 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
365 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000366}
367
368/// toplevelexpr ::= expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000369static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
370 if (auto E = ParseExpression()) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000371 // Make an anonymous proto.
Lang Hames2d789c32015-08-26 03:07:41 +0000372 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
373 std::vector<std::string>());
Lang Hames09bf4c12015-08-18 18:11:06 +0000374 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000375 }
Lang Hames09bf4c12015-08-18 18:11:06 +0000376 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000377}
378
379/// external ::= 'extern' prototype
Lang Hames09bf4c12015-08-18 18:11:06 +0000380static std::unique_ptr<PrototypeAST> ParseExtern() {
Eric Christopherc0239362014-12-08 18:12:28 +0000381 getNextToken(); // eat extern.
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000382 return ParsePrototype();
383}
384
385//===----------------------------------------------------------------------===//
386// Code Generation
387//===----------------------------------------------------------------------===//
388
Lang Hames2d789c32015-08-26 03:07:41 +0000389static std::unique_ptr<Module> TheModule;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000390static IRBuilder<> Builder(getGlobalContext());
Eric Christopherc0239362014-12-08 18:12:28 +0000391static std::map<std::string, Value *> NamedValues;
Lang Hames2d789c32015-08-26 03:07:41 +0000392static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
393static std::unique_ptr<KaleidoscopeJIT> TheJIT;
394static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000395
Eric Christopherc0239362014-12-08 18:12:28 +0000396Value *ErrorV(const char *Str) {
397 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000398 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000399}
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000400
Lang Hames2d789c32015-08-26 03:07:41 +0000401Function *getFunction(std::string Name) {
402 // First, see if the function has already been added to the current module.
403 if (auto *F = TheModule->getFunction(Name))
404 return F;
405
406 // If not, check whether we can codegen the declaration from some existing
407 // prototype.
408 auto FI = FunctionProtos.find(Name);
409 if (FI != FunctionProtos.end())
410 return FI->second->codegen();
411
412 // If no existing prototype exists, return null.
413 return nullptr;
414}
415
416Value *NumberExprAST::codegen() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000417 return ConstantFP::get(getGlobalContext(), APFloat(Val));
418}
419
Lang Hames2d789c32015-08-26 03:07:41 +0000420Value *VariableExprAST::codegen() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000421 // Look this variable up in the function.
422 Value *V = NamedValues[Name];
Lang Hames596aec92015-08-19 18:32:58 +0000423 if (!V)
424 return ErrorV("Unknown variable name");
425 return V;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000426}
427
Lang Hames2d789c32015-08-26 03:07:41 +0000428Value *BinaryExprAST::codegen() {
429 Value *L = LHS->codegen();
430 Value *R = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000431 if (!L || !R)
432 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000433
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000434 switch (Op) {
Eric Christopherc0239362014-12-08 18:12:28 +0000435 case '+':
436 return Builder.CreateFAdd(L, R, "addtmp");
437 case '-':
438 return Builder.CreateFSub(L, R, "subtmp");
439 case '*':
440 return Builder.CreateFMul(L, R, "multmp");
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000441 case '<':
442 L = Builder.CreateFCmpULT(L, R, "cmptmp");
443 // Convert bool 0/1 to double 0.0 or 1.0
444 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
445 "booltmp");
Eric Christopherc0239362014-12-08 18:12:28 +0000446 default:
447 return ErrorV("invalid binary operator");
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000448 }
449}
450
Lang Hames2d789c32015-08-26 03:07:41 +0000451Value *CallExprAST::codegen() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000452 // Look up the name in the global module table.
Lang Hames2d789c32015-08-26 03:07:41 +0000453 Function *CalleeF = getFunction(Callee);
Lang Hames09bf4c12015-08-18 18:11:06 +0000454 if (!CalleeF)
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000455 return ErrorV("Unknown function referenced");
Eric Christopherc0239362014-12-08 18:12:28 +0000456
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000457 // If argument mismatch error.
458 if (CalleeF->arg_size() != Args.size())
459 return ErrorV("Incorrect # arguments passed");
460
Eric Christopherc0239362014-12-08 18:12:28 +0000461 std::vector<Value *> ArgsV;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000462 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Lang Hames2d789c32015-08-26 03:07:41 +0000463 ArgsV.push_back(Args[i]->codegen());
Lang Hames09bf4c12015-08-18 18:11:06 +0000464 if (!ArgsV.back())
465 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000466 }
Eric Christopherc0239362014-12-08 18:12:28 +0000467
Francois Pichetc5d10502011-07-15 10:59:52 +0000468 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000469}
470
Lang Hames2d789c32015-08-26 03:07:41 +0000471Function *PrototypeAST::codegen() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000472 // Make the function type: double(double,double) etc.
Eric Christopherc0239362014-12-08 18:12:28 +0000473 std::vector<Type *> Doubles(Args.size(),
474 Type::getDoubleTy(getGlobalContext()));
475 FunctionType *FT =
476 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
477
Lang Hames2d789c32015-08-26 03:07:41 +0000478 Function *F =
479 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
Eric Christopherc0239362014-12-08 18:12:28 +0000480
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000481 // Set names for all arguments.
482 unsigned Idx = 0;
Lang Hames2d789c32015-08-26 03:07:41 +0000483 for (auto &Arg : F->args())
484 Arg.setName(Args[Idx++]);
Eric Christopherc0239362014-12-08 18:12:28 +0000485
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000486 return F;
487}
488
Lang Hames2d789c32015-08-26 03:07:41 +0000489Function *FunctionAST::codegen() {
490 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
491 // reference to it for use below.
492 auto &P = *Proto;
493 FunctionProtos[Proto->getName()] = std::move(Proto);
494 Function *TheFunction = getFunction(P.getName());
Lang Hames09bf4c12015-08-18 18:11:06 +0000495 if (!TheFunction)
496 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000497
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000498 // Create a new basic block to start insertion into.
499 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
500 Builder.SetInsertPoint(BB);
Eric Christopherc0239362014-12-08 18:12:28 +0000501
Lang Hames2d789c32015-08-26 03:07:41 +0000502 // Record the function arguments in the NamedValues map.
503 NamedValues.clear();
504 for (auto &Arg : TheFunction->args())
505 NamedValues[Arg.getName()] = &Arg;
506
507 if (Value *RetVal = Body->codegen()) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000508 // Finish off the function.
509 Builder.CreateRet(RetVal);
510
511 // Validate the generated code, checking for consistency.
512 verifyFunction(*TheFunction);
513
Lang Hames2d789c32015-08-26 03:07:41 +0000514 // Run the optimizer on the function.
515 TheFPM->run(*TheFunction);
516
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000517 return TheFunction;
518 }
Eric Christopherc0239362014-12-08 18:12:28 +0000519
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000520 // Error reading body, remove function.
521 TheFunction->eraseFromParent();
Lang Hames09bf4c12015-08-18 18:11:06 +0000522 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000523}
524
525//===----------------------------------------------------------------------===//
526// Top-Level parsing and JIT Driver
527//===----------------------------------------------------------------------===//
528
Lang Hames2d789c32015-08-26 03:07:41 +0000529static void InitializeModuleAndPassManager() {
530 // Open a new module.
531 TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
532 TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
533
534 // Create a new pass manager attached to it.
535 TheFPM = llvm::make_unique<legacy::FunctionPassManager>(TheModule.get());
536
537 // Provide basic AliasAnalysis support for GVN.
538 TheFPM->add(createBasicAliasAnalysisPass());
539 // Do simple "peephole" optimizations and bit-twiddling optzns.
540 TheFPM->add(createInstructionCombiningPass());
541 // Reassociate expressions.
542 TheFPM->add(createReassociatePass());
543 // Eliminate Common SubExpressions.
544 TheFPM->add(createGVNPass());
545 // Simplify the control flow graph (deleting unreachable blocks, etc).
546 TheFPM->add(createCFGSimplificationPass());
547
548 TheFPM->doInitialization();
549}
550
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000551static void HandleDefinition() {
Lang Hames09bf4c12015-08-18 18:11:06 +0000552 if (auto FnAST = ParseDefinition()) {
Lang Hames2d789c32015-08-26 03:07:41 +0000553 if (auto *FnIR = FnAST->codegen()) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000554 fprintf(stderr, "Read function definition:");
Lang Hames09bf4c12015-08-18 18:11:06 +0000555 FnIR->dump();
Lang Hames2d789c32015-08-26 03:07:41 +0000556 TheJIT->addModule(std::move(TheModule));
557 InitializeModuleAndPassManager();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000558 }
559 } else {
560 // Skip token for error recovery.
561 getNextToken();
562 }
563}
564
565static void HandleExtern() {
Lang Hames09bf4c12015-08-18 18:11:06 +0000566 if (auto ProtoAST = ParseExtern()) {
Lang Hames2d789c32015-08-26 03:07:41 +0000567 if (auto *FnIR = ProtoAST->codegen()) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000568 fprintf(stderr, "Read extern: ");
Lang Hames09bf4c12015-08-18 18:11:06 +0000569 FnIR->dump();
Lang Hames2d789c32015-08-26 03:07:41 +0000570 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000571 }
572 } else {
573 // Skip token for error recovery.
574 getNextToken();
575 }
576}
577
578static void HandleTopLevelExpression() {
579 // Evaluate a top-level expression into an anonymous function.
Lang Hames09bf4c12015-08-18 18:11:06 +0000580 if (auto FnAST = ParseTopLevelExpr()) {
Lang Hames2d789c32015-08-26 03:07:41 +0000581 if (FnAST->codegen()) {
Eric Christopherc0239362014-12-08 18:12:28 +0000582
Lang Hames2d789c32015-08-26 03:07:41 +0000583 // JIT the module containing the anonymous expression, keeping a handle so
584 // we can free it later.
585 auto H = TheJIT->addModule(std::move(TheModule));
586 InitializeModuleAndPassManager();
587
588 // Search the JIT for the __anon_expr symbol.
589 auto ExprSymbol = TheJIT->findSymbol("__anon_expr");
590 assert(ExprSymbol && "Function not found");
591
592 // Get the symbol's address and cast it to the right type (takes no
593 // arguments, returns a double) so we can call it as a native function.
594 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000595 fprintf(stderr, "Evaluated to %f\n", FP());
Lang Hames2d789c32015-08-26 03:07:41 +0000596
597 // Delete the anonymous expression module from the JIT.
598 TheJIT->removeModule(H);
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000599 }
600 } else {
601 // Skip token for error recovery.
602 getNextToken();
603 }
604}
605
606/// top ::= definition | external | expression | ';'
607static void MainLoop() {
608 while (1) {
609 fprintf(stderr, "ready> ");
610 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +0000611 case tok_eof:
612 return;
Lang Hames59b0da82015-08-19 18:15:58 +0000613 case ';': // ignore top-level semicolons.
Eric Christopherc0239362014-12-08 18:12:28 +0000614 getNextToken();
Lang Hames59b0da82015-08-19 18:15:58 +0000615 break;
Eric Christopherc0239362014-12-08 18:12:28 +0000616 case tok_def:
617 HandleDefinition();
618 break;
619 case tok_extern:
620 HandleExtern();
621 break;
622 default:
623 HandleTopLevelExpression();
624 break;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000625 }
626 }
627}
628
629//===----------------------------------------------------------------------===//
630// "Library" functions that can be "extern'd" from user code.
631//===----------------------------------------------------------------------===//
632
633/// putchard - putchar that takes a double and returns 0.
Lang Hamesd76e0672015-08-27 20:31:44 +0000634__attribute__((used)) extern "C" double putchard(double X) {
635 fputc((char)X, stderr);
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000636 return 0;
637}
638
Lang Hames59b0da82015-08-19 18:15:58 +0000639/// printd - printf that takes a double prints it as "%f\n", returning 0.
Lang Hamesd76e0672015-08-27 20:31:44 +0000640__attribute__((used)) extern "C" double printd(double X) {
641 fprintf(stderr, "%f\n", X);
Lang Hames59b0da82015-08-19 18:15:58 +0000642 return 0;
643}
644
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000645//===----------------------------------------------------------------------===//
646// Main driver code.
647//===----------------------------------------------------------------------===//
648
649int main() {
650 InitializeNativeTarget();
Eric Christopher1b74b652014-12-08 18:00:38 +0000651 InitializeNativeTargetAsmPrinter();
652 InitializeNativeTargetAsmParser();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000653
654 // Install standard binary operators.
655 // 1 is lowest precedence.
656 BinopPrecedence['<'] = 10;
657 BinopPrecedence['+'] = 20;
658 BinopPrecedence['-'] = 20;
Eric Christopherc0239362014-12-08 18:12:28 +0000659 BinopPrecedence['*'] = 40; // highest.
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000660
661 // Prime the first token.
662 fprintf(stderr, "ready> ");
663 getNextToken();
664
Lang Hames2d789c32015-08-26 03:07:41 +0000665 TheJIT = llvm::make_unique<KaleidoscopeJIT>();
666
667 InitializeModuleAndPassManager();
668
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000669 // Run the main "interpreter loop" now.
670 MainLoop();
671
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000672 return 0;
673}