blob: f9e61825fbd147c3ba559325c9b70f530f7b8b13 [file] [log] [blame]
Chandler Carruth17e0bc32015-08-06 07:33:15 +00001#include "llvm/Analysis/BasicAliasAnalysis.h"
Chandler Carruth605e30e2012-12-04 10:16:57 +00002#include "llvm/Analysis/Passes.h"
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +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>
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000016#include <cstdio>
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000017#include <map>
Chandler Carruth605e30e2012-12-04 10:16:57 +000018#include <string>
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +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,
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000034
35 // primary
Eric Christopherc0239362014-12-08 18:12:28 +000036 tok_identifier = -4,
37 tok_number = -5
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000038};
39
Eric Christopherc0239362014-12-08 18:12:28 +000040static std::string IdentifierStr; // Filled in if tok_identifier
41static double NumVal; // Filled in if tok_number
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000042
43/// gettok - Return the next token from standard input.
44static int gettok() {
45 static int LastChar = ' ';
46
47 // Skip any whitespace.
48 while (isspace(LastChar))
49 LastChar = getchar();
50
51 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
52 IdentifierStr = LastChar;
53 while (isalnum((LastChar = getchar())))
54 IdentifierStr += LastChar;
55
Eric Christopherc0239362014-12-08 18:12:28 +000056 if (IdentifierStr == "def")
57 return tok_def;
58 if (IdentifierStr == "extern")
59 return tok_extern;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000060 return tok_identifier;
61 }
62
Eric Christopherc0239362014-12-08 18:12:28 +000063 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000064 std::string NumStr;
65 do {
66 NumStr += LastChar;
67 LastChar = getchar();
68 } while (isdigit(LastChar) || LastChar == '.');
69
70 NumVal = strtod(NumStr.c_str(), 0);
71 return tok_number;
72 }
73
74 if (LastChar == '#') {
75 // Comment until end of line.
Eric Christopherc0239362014-12-08 18:12:28 +000076 do
77 LastChar = getchar();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000078 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
Eric Christopherc0239362014-12-08 18:12:28 +000079
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000080 if (LastChar != EOF)
81 return gettok();
82 }
Eric Christopherc0239362014-12-08 18:12:28 +000083
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000084 // Check for end of file. Don't eat the EOF.
85 if (LastChar == EOF)
86 return tok_eof;
87
88 // Otherwise, just return the character as its ascii value.
89 int ThisChar = LastChar;
90 LastChar = getchar();
91 return ThisChar;
92}
93
94//===----------------------------------------------------------------------===//
95// Abstract Syntax Tree (aka Parse Tree)
96//===----------------------------------------------------------------------===//
Juergen Ributzka05c5a932013-11-19 03:08:35 +000097namespace {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000098/// ExprAST - Base class for all expression nodes.
99class ExprAST {
100public:
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000101 virtual ~ExprAST() {}
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000102 virtual Value *Codegen() = 0;
103};
104
105/// NumberExprAST - Expression class for numeric literals like "1.0".
106class NumberExprAST : public ExprAST {
107 double Val;
Eric Christopherc0239362014-12-08 18:12:28 +0000108
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000109public:
110 NumberExprAST(double val) : Val(val) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000111 Value *Codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000112};
113
114/// VariableExprAST - Expression class for referencing a variable, like "a".
115class VariableExprAST : public ExprAST {
116 std::string Name;
Eric Christopherc0239362014-12-08 18:12:28 +0000117
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000118public:
119 VariableExprAST(const std::string &name) : Name(name) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000120 Value *Codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000121};
122
123/// BinaryExprAST - Expression class for a binary operator.
124class BinaryExprAST : public ExprAST {
125 char Op;
126 ExprAST *LHS, *RHS;
Eric Christopherc0239362014-12-08 18:12:28 +0000127
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000128public:
Eric Christopherc0239362014-12-08 18:12:28 +0000129 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
130 : Op(op), LHS(lhs), RHS(rhs) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +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;
Eric Christopherc0239362014-12-08 18:12:28 +0000137 std::vector<ExprAST *> Args;
138
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000139public:
Eric Christopherc0239362014-12-08 18:12:28 +0000140 CallExprAST(const std::string &callee, std::vector<ExprAST *> &args)
141 : Callee(callee), Args(args) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000142 Value *Codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000143};
144
145/// PrototypeAST - This class represents the "prototype" for a function,
146/// which captures its name, and its argument names (thus implicitly the number
147/// of arguments the function takes).
148class PrototypeAST {
149 std::string Name;
150 std::vector<std::string> Args;
Eric Christopherc0239362014-12-08 18:12:28 +0000151
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000152public:
153 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
Eric Christopherc0239362014-12-08 18:12:28 +0000154 : Name(name), Args(args) {}
155
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000156 Function *Codegen();
157};
158
159/// FunctionAST - This class represents a function definition itself.
160class FunctionAST {
161 PrototypeAST *Proto;
162 ExprAST *Body;
Eric Christopherc0239362014-12-08 18:12:28 +0000163
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000164public:
Eric Christopherc0239362014-12-08 18:12:28 +0000165 FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
166
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000167 Function *Codegen();
168};
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000169} // end anonymous namespace
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000170
171//===----------------------------------------------------------------------===//
172// Parser
173//===----------------------------------------------------------------------===//
174
175/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
176/// token the parser is looking at. getNextToken reads another token from the
177/// lexer and updates CurTok with its results.
178static int CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000179static int getNextToken() { return CurTok = gettok(); }
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000180
181/// BinopPrecedence - This holds the precedence for each binary operator that is
182/// defined.
183static std::map<char, int> BinopPrecedence;
184
185/// GetTokPrecedence - Get the precedence of the pending binary operator token.
186static int GetTokPrecedence() {
187 if (!isascii(CurTok))
188 return -1;
Eric Christopherc0239362014-12-08 18:12:28 +0000189
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000190 // Make sure it's a declared binop.
191 int TokPrec = BinopPrecedence[CurTok];
Eric Christopherc0239362014-12-08 18:12:28 +0000192 if (TokPrec <= 0)
193 return -1;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000194 return TokPrec;
195}
196
197/// Error* - These are little helper functions for error handling.
Eric Christopherc0239362014-12-08 18:12:28 +0000198ExprAST *Error(const char *Str) {
199 fprintf(stderr, "Error: %s\n", Str);
200 return 0;
201}
202PrototypeAST *ErrorP(const char *Str) {
203 Error(Str);
204 return 0;
205}
206FunctionAST *ErrorF(const char *Str) {
207 Error(Str);
208 return 0;
209}
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000210
211static ExprAST *ParseExpression();
212
213/// identifierexpr
214/// ::= identifier
215/// ::= identifier '(' expression* ')'
216static ExprAST *ParseIdentifierExpr() {
217 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000218
219 getNextToken(); // eat identifier.
220
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000221 if (CurTok != '(') // Simple variable ref.
222 return new VariableExprAST(IdName);
Eric Christopherc0239362014-12-08 18:12:28 +0000223
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000224 // Call.
Eric Christopherc0239362014-12-08 18:12:28 +0000225 getNextToken(); // eat (
226 std::vector<ExprAST *> Args;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000227 if (CurTok != ')') {
228 while (1) {
229 ExprAST *Arg = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000230 if (!Arg)
231 return 0;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000232 Args.push_back(Arg);
233
Eric Christopherc0239362014-12-08 18:12:28 +0000234 if (CurTok == ')')
235 break;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000236
237 if (CurTok != ',')
238 return Error("Expected ')' or ',' in argument list");
239 getNextToken();
240 }
241 }
242
243 // Eat the ')'.
244 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000245
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000246 return new CallExprAST(IdName, Args);
247}
248
249/// numberexpr ::= number
250static ExprAST *ParseNumberExpr() {
251 ExprAST *Result = new NumberExprAST(NumVal);
252 getNextToken(); // consume the number
253 return Result;
254}
255
256/// parenexpr ::= '(' expression ')'
257static ExprAST *ParseParenExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000258 getNextToken(); // eat (.
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000259 ExprAST *V = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000260 if (!V)
261 return 0;
262
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000263 if (CurTok != ')')
264 return Error("expected ')'");
Eric Christopherc0239362014-12-08 18:12:28 +0000265 getNextToken(); // eat ).
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000266 return V;
267}
268
269/// primary
270/// ::= identifierexpr
271/// ::= numberexpr
272/// ::= parenexpr
273static ExprAST *ParsePrimary() {
274 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +0000275 default:
276 return Error("unknown token when expecting an expression");
277 case tok_identifier:
278 return ParseIdentifierExpr();
279 case tok_number:
280 return ParseNumberExpr();
281 case '(':
282 return ParseParenExpr();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000283 }
284}
285
286/// binoprhs
287/// ::= ('+' primary)*
288static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
289 // If this is a binop, find its precedence.
290 while (1) {
291 int TokPrec = GetTokPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +0000292
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000293 // If this is a binop that binds at least as tightly as the current binop,
294 // consume it, otherwise we are done.
295 if (TokPrec < ExprPrec)
296 return LHS;
Eric Christopherc0239362014-12-08 18:12:28 +0000297
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000298 // Okay, we know this is a binop.
299 int BinOp = CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000300 getNextToken(); // eat binop
301
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000302 // Parse the primary expression after the binary operator.
303 ExprAST *RHS = ParsePrimary();
Eric Christopherc0239362014-12-08 18:12:28 +0000304 if (!RHS)
305 return 0;
306
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000307 // If BinOp binds less tightly with RHS than the operator after RHS, let
308 // the pending operator take RHS as its LHS.
309 int NextPrec = GetTokPrecedence();
310 if (TokPrec < NextPrec) {
Eric Christopherc0239362014-12-08 18:12:28 +0000311 RHS = ParseBinOpRHS(TokPrec + 1, RHS);
312 if (RHS == 0)
313 return 0;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000314 }
Eric Christopherc0239362014-12-08 18:12:28 +0000315
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000316 // Merge LHS/RHS.
317 LHS = new BinaryExprAST(BinOp, LHS, RHS);
318 }
319}
320
321/// expression
322/// ::= primary binoprhs
323///
324static ExprAST *ParseExpression() {
325 ExprAST *LHS = ParsePrimary();
Eric Christopherc0239362014-12-08 18:12:28 +0000326 if (!LHS)
327 return 0;
328
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000329 return ParseBinOpRHS(0, LHS);
330}
331
332/// prototype
333/// ::= id '(' id* ')'
334static PrototypeAST *ParsePrototype() {
335 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
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000353 return new PrototypeAST(FnName, ArgNames);
354}
355
356/// definition ::= 'def' prototype expression
357static FunctionAST *ParseDefinition() {
Eric Christopherc0239362014-12-08 18:12:28 +0000358 getNextToken(); // eat def.
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000359 PrototypeAST *Proto = ParsePrototype();
Eric Christopherc0239362014-12-08 18:12:28 +0000360 if (Proto == 0)
361 return 0;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000362
363 if (ExprAST *E = ParseExpression())
364 return new FunctionAST(Proto, E);
365 return 0;
366}
367
368/// toplevelexpr ::= expression
369static FunctionAST *ParseTopLevelExpr() {
370 if (ExprAST *E = ParseExpression()) {
371 // Make an anonymous proto.
372 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
373 return new FunctionAST(Proto, E);
374 }
375 return 0;
376}
377
378/// external ::= 'extern' prototype
379static PrototypeAST *ParseExtern() {
Eric Christopherc0239362014-12-08 18:12:28 +0000380 getNextToken(); // eat extern.
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000381 return ParsePrototype();
382}
383
384//===----------------------------------------------------------------------===//
Lang Hames1cb54812015-01-16 19:44:46 +0000385// Quick and dirty hack
386//===----------------------------------------------------------------------===//
387
388// FIXME: Obviously we can do better than this
Lang Hames37679192015-01-16 21:42:07 +0000389std::string GenerateUniqueName(const char *root) {
Lang Hames1cb54812015-01-16 19:44:46 +0000390 static int i = 0;
391 char s[16];
392 sprintf(s, "%s%d", root, i++);
393 std::string S = s;
394 return S;
395}
396
Lang Hames37679192015-01-16 21:42:07 +0000397std::string MakeLegalFunctionName(std::string Name) {
Lang Hames1cb54812015-01-16 19:44:46 +0000398 std::string NewName;
399 if (!Name.length())
Lang Hames37679192015-01-16 21:42:07 +0000400 return GenerateUniqueName("anon_func_");
Lang Hames1cb54812015-01-16 19:44:46 +0000401
402 // Start with what we have
403 NewName = Name;
404
405 // Look for a numberic first character
406 if (NewName.find_first_of("0123456789") == 0) {
407 NewName.insert(0, 1, 'n');
408 }
409
410 // Replace illegal characters with their ASCII equivalent
Lang Hames37679192015-01-16 21:42:07 +0000411 std::string legal_elements =
412 "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Lang Hames1cb54812015-01-16 19:44:46 +0000413 size_t pos;
Lang Hames37679192015-01-16 21:42:07 +0000414 while ((pos = NewName.find_first_not_of(legal_elements)) !=
415 std::string::npos) {
Lang Hames1cb54812015-01-16 19:44:46 +0000416 char old_c = NewName.at(pos);
417 char new_str[16];
418 sprintf(new_str, "%d", (int)old_c);
419 NewName = NewName.replace(pos, 1, new_str);
420 }
421
422 return NewName;
423}
424
425//===----------------------------------------------------------------------===//
426// MCJIT helper class
427//===----------------------------------------------------------------------===//
428
Lang Hames37679192015-01-16 21:42:07 +0000429class MCJITHelper {
Lang Hames1cb54812015-01-16 19:44:46 +0000430public:
Lang Hames37679192015-01-16 21:42:07 +0000431 MCJITHelper(LLVMContext &C) : Context(C), OpenModule(NULL) {}
Lang Hames1cb54812015-01-16 19:44:46 +0000432 ~MCJITHelper();
433
434 Function *getFunction(const std::string FnName);
435 Module *getModuleForNewFunction();
Lang Hames37679192015-01-16 21:42:07 +0000436 void *getPointerToFunction(Function *F);
Lang Hames1cb54812015-01-16 19:44:46 +0000437 void *getSymbolAddress(const std::string &Name);
438 void dump();
439
440private:
Lang Hames37679192015-01-16 21:42:07 +0000441 typedef std::vector<Module *> ModuleVector;
442 typedef std::vector<ExecutionEngine *> EngineVector;
Lang Hames1cb54812015-01-16 19:44:46 +0000443
Lang Hames37679192015-01-16 21:42:07 +0000444 LLVMContext &Context;
445 Module *OpenModule;
446 ModuleVector Modules;
447 EngineVector Engines;
Lang Hames1cb54812015-01-16 19:44:46 +0000448};
449
Lang Hames37679192015-01-16 21:42:07 +0000450class HelpingMemoryManager : public SectionMemoryManager {
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000451 HelpingMemoryManager(const HelpingMemoryManager &) = delete;
452 void operator=(const HelpingMemoryManager &) = delete;
Lang Hames1cb54812015-01-16 19:44:46 +0000453
454public:
455 HelpingMemoryManager(MCJITHelper *Helper) : MasterHelper(Helper) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000456 ~HelpingMemoryManager() override {}
Lang Hames1cb54812015-01-16 19:44:46 +0000457
458 /// This method returns the address of the specified symbol.
459 /// Our implementation will attempt to find symbols in other
460 /// modules associated with the MCJITHelper to cross link symbols
461 /// from one generated module to another.
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000462 uint64_t getSymbolAddress(const std::string &Name) override;
Lang Hames37679192015-01-16 21:42:07 +0000463
Lang Hames1cb54812015-01-16 19:44:46 +0000464private:
465 MCJITHelper *MasterHelper;
466};
467
Lang Hames37679192015-01-16 21:42:07 +0000468uint64_t HelpingMemoryManager::getSymbolAddress(const std::string &Name) {
Lang Hames1cb54812015-01-16 19:44:46 +0000469 uint64_t FnAddr = SectionMemoryManager::getSymbolAddress(Name);
470 if (FnAddr)
471 return FnAddr;
472
Lang Hames37679192015-01-16 21:42:07 +0000473 uint64_t HelperFun = (uint64_t)MasterHelper->getSymbolAddress(Name);
Lang Hames1cb54812015-01-16 19:44:46 +0000474 if (!HelperFun)
475 report_fatal_error("Program used extern function '" + Name +
476 "' which could not be resolved!");
477
478 return HelperFun;
479}
480
Lang Hames37679192015-01-16 21:42:07 +0000481MCJITHelper::~MCJITHelper() {
Lang Hames1cb54812015-01-16 19:44:46 +0000482 if (OpenModule)
483 delete OpenModule;
484 EngineVector::iterator begin = Engines.begin();
485 EngineVector::iterator end = Engines.end();
486 EngineVector::iterator it;
487 for (it = begin; it != end; ++it)
488 delete *it;
489}
490
491Function *MCJITHelper::getFunction(const std::string FnName) {
492 ModuleVector::iterator begin = Modules.begin();
493 ModuleVector::iterator end = Modules.end();
494 ModuleVector::iterator it;
495 for (it = begin; it != end; ++it) {
496 Function *F = (*it)->getFunction(FnName);
497 if (F) {
498 if (*it == OpenModule)
Lang Hames37679192015-01-16 21:42:07 +0000499 return F;
Lang Hames1cb54812015-01-16 19:44:46 +0000500
501 assert(OpenModule != NULL);
502
503 // This function is in a module that has already been JITed.
504 // We need to generate a new prototype for external linkage.
505 Function *PF = OpenModule->getFunction(FnName);
506 if (PF && !PF->empty()) {
507 ErrorF("redefinition of function across modules");
508 return 0;
509 }
510
511 // If we don't have a prototype yet, create one.
512 if (!PF)
Lang Hames37679192015-01-16 21:42:07 +0000513 PF = Function::Create(F->getFunctionType(), Function::ExternalLinkage,
514 FnName, OpenModule);
Lang Hames1cb54812015-01-16 19:44:46 +0000515 return PF;
516 }
517 }
518 return NULL;
519}
520
521Module *MCJITHelper::getModuleForNewFunction() {
522 // If we have a Module that hasn't been JITed, use that.
523 if (OpenModule)
524 return OpenModule;
525
526 // Otherwise create a new Module.
527 std::string ModName = GenerateUniqueName("mcjit_module_");
528 Module *M = new Module(ModName, Context);
529 Modules.push_back(M);
530 OpenModule = M;
531 return M;
532}
533
Lang Hames37679192015-01-16 21:42:07 +0000534void *MCJITHelper::getPointerToFunction(Function *F) {
Lang Hames1cb54812015-01-16 19:44:46 +0000535 // See if an existing instance of MCJIT has this function.
536 EngineVector::iterator begin = Engines.begin();
537 EngineVector::iterator end = Engines.end();
538 EngineVector::iterator it;
539 for (it = begin; it != end; ++it) {
540 void *P = (*it)->getPointerToFunction(F);
541 if (P)
542 return P;
543 }
544
545 // If we didn't find the function, see if we can generate it.
546 if (OpenModule) {
547 std::string ErrStr;
Lang Hames37679192015-01-16 21:42:07 +0000548 ExecutionEngine *NewEngine =
549 EngineBuilder(std::unique_ptr<Module>(OpenModule))
550 .setErrorStr(&ErrStr)
551 .setMCJITMemoryManager(std::unique_ptr<HelpingMemoryManager>(
552 new HelpingMemoryManager(this)))
553 .create();
Lang Hames1cb54812015-01-16 19:44:46 +0000554 if (!NewEngine) {
555 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
556 exit(1);
557 }
558
559 // Create a function pass manager for this engine
Chandler Carruth7ecd9912015-02-13 10:21:05 +0000560 auto *FPM = new legacy::FunctionPassManager(OpenModule);
Lang Hames1cb54812015-01-16 19:44:46 +0000561
562 // Set up the optimizer pipeline. Start with registering info about how the
563 // target lays out data structures.
Mehdi Aminicd253da2015-07-16 16:47:18 +0000564 OpenModule->setDataLayout(NewEngine->getDataLayout());
Lang Hames1cb54812015-01-16 19:44:46 +0000565 // Provide basic AliasAnalysis support for GVN.
566 FPM->add(createBasicAliasAnalysisPass());
567 // Promote allocas to registers.
568 FPM->add(createPromoteMemoryToRegisterPass());
569 // Do simple "peephole" optimizations and bit-twiddling optzns.
570 FPM->add(createInstructionCombiningPass());
571 // Reassociate expressions.
572 FPM->add(createReassociatePass());
573 // Eliminate Common SubExpressions.
574 FPM->add(createGVNPass());
575 // Simplify the control flow graph (deleting unreachable blocks, etc).
576 FPM->add(createCFGSimplificationPass());
577 FPM->doInitialization();
578
579 // For each function in the module
580 Module::iterator it;
581 Module::iterator end = OpenModule->end();
582 for (it = OpenModule->begin(); it != end; ++it) {
583 // Run the FPM on this function
584 FPM->run(*it);
585 }
586
587 // We don't need this anymore
588 delete FPM;
589
590 OpenModule = NULL;
591 Engines.push_back(NewEngine);
592 NewEngine->finalizeObject();
593 return NewEngine->getPointerToFunction(F);
594 }
595 return NULL;
596}
597
Lang Hames37679192015-01-16 21:42:07 +0000598void *MCJITHelper::getSymbolAddress(const std::string &Name) {
Lang Hames1cb54812015-01-16 19:44:46 +0000599 // Look for the symbol in each of our execution engines.
600 EngineVector::iterator begin = Engines.begin();
601 EngineVector::iterator end = Engines.end();
602 EngineVector::iterator it;
603 for (it = begin; it != end; ++it) {
604 uint64_t FAddr = (*it)->getFunctionAddress(Name);
605 if (FAddr) {
Lang Hames37679192015-01-16 21:42:07 +0000606 return (void *)FAddr;
Lang Hames1cb54812015-01-16 19:44:46 +0000607 }
608 }
609 return NULL;
610}
611
Lang Hames37679192015-01-16 21:42:07 +0000612void MCJITHelper::dump() {
Lang Hames1cb54812015-01-16 19:44:46 +0000613 ModuleVector::iterator begin = Modules.begin();
614 ModuleVector::iterator end = Modules.end();
615 ModuleVector::iterator it;
616 for (it = begin; it != end; ++it)
617 (*it)->dump();
618}
619//===----------------------------------------------------------------------===//
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000620// Code Generation
621//===----------------------------------------------------------------------===//
622
Lang Hames1cb54812015-01-16 19:44:46 +0000623static MCJITHelper *JITHelper;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000624static IRBuilder<> Builder(getGlobalContext());
Eric Christopherc0239362014-12-08 18:12:28 +0000625static std::map<std::string, Value *> NamedValues;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000626
Eric Christopherc0239362014-12-08 18:12:28 +0000627Value *ErrorV(const char *Str) {
628 Error(Str);
629 return 0;
630}
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000631
632Value *NumberExprAST::Codegen() {
633 return ConstantFP::get(getGlobalContext(), APFloat(Val));
634}
635
636Value *VariableExprAST::Codegen() {
637 // Look this variable up in the function.
638 Value *V = NamedValues[Name];
639 return V ? V : ErrorV("Unknown variable name");
640}
641
642Value *BinaryExprAST::Codegen() {
643 Value *L = LHS->Codegen();
644 Value *R = RHS->Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000645 if (L == 0 || R == 0)
646 return 0;
647
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000648 switch (Op) {
Eric Christopherc0239362014-12-08 18:12:28 +0000649 case '+':
650 return Builder.CreateFAdd(L, R, "addtmp");
651 case '-':
652 return Builder.CreateFSub(L, R, "subtmp");
653 case '*':
654 return Builder.CreateFMul(L, R, "multmp");
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000655 case '<':
656 L = Builder.CreateFCmpULT(L, R, "cmptmp");
657 // Convert bool 0/1 to double 0.0 or 1.0
658 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
659 "booltmp");
Eric Christopherc0239362014-12-08 18:12:28 +0000660 default:
661 return ErrorV("invalid binary operator");
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000662 }
663}
664
665Value *CallExprAST::Codegen() {
666 // Look up the name in the global module table.
Lang Hames1cb54812015-01-16 19:44:46 +0000667 Function *CalleeF = JITHelper->getFunction(Callee);
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000668 if (CalleeF == 0)
669 return ErrorV("Unknown function referenced");
Eric Christopherc0239362014-12-08 18:12:28 +0000670
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000671 // If argument mismatch error.
672 if (CalleeF->arg_size() != Args.size())
673 return ErrorV("Incorrect # arguments passed");
674
Eric Christopherc0239362014-12-08 18:12:28 +0000675 std::vector<Value *> ArgsV;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000676 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
677 ArgsV.push_back(Args[i]->Codegen());
Eric Christopherc0239362014-12-08 18:12:28 +0000678 if (ArgsV.back() == 0)
679 return 0;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000680 }
Eric Christopherc0239362014-12-08 18:12:28 +0000681
Francois Pichetc5d10502011-07-15 10:59:52 +0000682 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000683}
684
685Function *PrototypeAST::Codegen() {
686 // Make the function type: double(double,double) etc.
Eric Christopherc0239362014-12-08 18:12:28 +0000687 std::vector<Type *> Doubles(Args.size(),
688 Type::getDoubleTy(getGlobalContext()));
689 FunctionType *FT =
690 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
691
Lang Hames1cb54812015-01-16 19:44:46 +0000692 std::string FnName = MakeLegalFunctionName(Name);
693
694 Module *M = JITHelper->getModuleForNewFunction();
695
Lang Hames37679192015-01-16 21:42:07 +0000696 Function *F = Function::Create(FT, Function::ExternalLinkage, FnName, M);
Eric Christopherc0239362014-12-08 18:12:28 +0000697
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000698 // If F conflicted, there was already something named 'Name'. If it has a
699 // body, don't allow redefinition or reextern.
Lang Hames1cb54812015-01-16 19:44:46 +0000700 if (F->getName() != FnName) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000701 // Delete the one we just made and get the existing one.
702 F->eraseFromParent();
Lang Hames37679192015-01-16 21:42:07 +0000703 F = JITHelper->getFunction(Name);
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000704 // If F already has a body, reject this.
705 if (!F->empty()) {
706 ErrorF("redefinition of function");
707 return 0;
708 }
Eric Christopherc0239362014-12-08 18:12:28 +0000709
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000710 // If F took a different number of args, reject.
711 if (F->arg_size() != Args.size()) {
712 ErrorF("redefinition of function with different # args");
713 return 0;
714 }
715 }
Eric Christopherc0239362014-12-08 18:12:28 +0000716
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000717 // Set names for all arguments.
718 unsigned Idx = 0;
719 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
720 ++AI, ++Idx) {
721 AI->setName(Args[Idx]);
Eric Christopherc0239362014-12-08 18:12:28 +0000722
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000723 // Add arguments to variable symbol table.
724 NamedValues[Args[Idx]] = AI;
725 }
Eric Christopherc0239362014-12-08 18:12:28 +0000726
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000727 return F;
728}
729
730Function *FunctionAST::Codegen() {
731 NamedValues.clear();
Eric Christopherc0239362014-12-08 18:12:28 +0000732
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000733 Function *TheFunction = Proto->Codegen();
734 if (TheFunction == 0)
735 return 0;
Eric Christopherc0239362014-12-08 18:12:28 +0000736
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000737 // Create a new basic block to start insertion into.
738 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
739 Builder.SetInsertPoint(BB);
Eric Christopherc0239362014-12-08 18:12:28 +0000740
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000741 if (Value *RetVal = Body->Codegen()) {
742 // Finish off the function.
743 Builder.CreateRet(RetVal);
744
745 // Validate the generated code, checking for consistency.
746 verifyFunction(*TheFunction);
747
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000748 return TheFunction;
749 }
Eric Christopherc0239362014-12-08 18:12:28 +0000750
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000751 // Error reading body, remove function.
752 TheFunction->eraseFromParent();
753 return 0;
754}
755
756//===----------------------------------------------------------------------===//
757// Top-Level parsing and JIT Driver
758//===----------------------------------------------------------------------===//
759
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000760static void HandleDefinition() {
761 if (FunctionAST *F = ParseDefinition()) {
762 if (Function *LF = F->Codegen()) {
763 fprintf(stderr, "Read function definition:");
764 LF->dump();
765 }
766 } else {
767 // Skip token for error recovery.
768 getNextToken();
769 }
770}
771
772static void HandleExtern() {
773 if (PrototypeAST *P = ParseExtern()) {
774 if (Function *F = P->Codegen()) {
775 fprintf(stderr, "Read extern: ");
776 F->dump();
777 }
778 } else {
779 // Skip token for error recovery.
780 getNextToken();
781 }
782}
783
784static void HandleTopLevelExpression() {
785 // Evaluate a top-level expression into an anonymous function.
786 if (FunctionAST *F = ParseTopLevelExpr()) {
787 if (Function *LF = F->Codegen()) {
788 // JIT the function, returning a function pointer.
Lang Hames1cb54812015-01-16 19:44:46 +0000789 void *FPtr = JITHelper->getPointerToFunction(LF);
Eric Christopherc0239362014-12-08 18:12:28 +0000790
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000791 // Cast it to the right type (takes no arguments, returns a double) so we
792 // can call it as a native function.
793 double (*FP)() = (double (*)())(intptr_t)FPtr;
794 fprintf(stderr, "Evaluated to %f\n", FP());
795 }
796 } else {
797 // Skip token for error recovery.
798 getNextToken();
799 }
800}
801
802/// top ::= definition | external | expression | ';'
803static void MainLoop() {
804 while (1) {
805 fprintf(stderr, "ready> ");
806 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +0000807 case tok_eof:
808 return;
809 case ';':
810 getNextToken();
811 break; // ignore top-level semicolons.
812 case tok_def:
813 HandleDefinition();
814 break;
815 case tok_extern:
816 HandleExtern();
817 break;
818 default:
819 HandleTopLevelExpression();
820 break;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000821 }
822 }
823}
824
825//===----------------------------------------------------------------------===//
826// "Library" functions that can be "extern'd" from user code.
827//===----------------------------------------------------------------------===//
828
829/// putchard - putchar that takes a double and returns 0.
Eric Christopherc0239362014-12-08 18:12:28 +0000830extern "C" double putchard(double X) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000831 putchar((char)X);
832 return 0;
833}
834
835//===----------------------------------------------------------------------===//
836// Main driver code.
837//===----------------------------------------------------------------------===//
838
839int main() {
840 InitializeNativeTarget();
Eric Christopher1b74b652014-12-08 18:00:38 +0000841 InitializeNativeTargetAsmPrinter();
842 InitializeNativeTargetAsmParser();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000843 LLVMContext &Context = getGlobalContext();
Lang Hames1cb54812015-01-16 19:44:46 +0000844 JITHelper = new MCJITHelper(Context);
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000845
846 // Install standard binary operators.
847 // 1 is lowest precedence.
848 BinopPrecedence['<'] = 10;
849 BinopPrecedence['+'] = 20;
850 BinopPrecedence['-'] = 20;
Eric Christopherc0239362014-12-08 18:12:28 +0000851 BinopPrecedence['*'] = 40; // highest.
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000852
853 // Prime the first token.
854 fprintf(stderr, "ready> ");
855 getNextToken();
856
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000857 // Run the main "interpreter loop" now.
858 MainLoop();
859
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000860 // Print out all of the generated code.
Lang Hames1cb54812015-01-16 19:44:46 +0000861 JITHelper->dump();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000862
863 return 0;
864}