1 #define MINIMAL_STDERR_OUTPUT
3 #include "llvm/Analysis/Passes.h"
4 #include "llvm/ExecutionEngine/ExecutionEngine.h"
5 #include "llvm/ExecutionEngine/MCJIT.h"
6 #include "llvm/ExecutionEngine/ObjectCache.h"
7 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
8 #include "llvm/IR/DataLayout.h"
9 #include "llvm/IR/DerivedTypes.h"
10 #include "llvm/IR/IRBuilder.h"
11 #include "llvm/IR/LLVMContext.h"
12 #include "llvm/IR/Module.h"
13 #include "llvm/IR/Verifier.h"
14 #include "llvm/IRReader/IRReader.h"
15 #include "llvm/PassManager.h"
16 #include "llvm/Support/CommandLine.h"
17 #include "llvm/Support/FileSystem.h"
18 #include "llvm/Support/Path.h"
19 #include "llvm/Support/SourceMgr.h"
20 #include "llvm/Support/TargetSelect.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Transforms/Scalar.h"
30 //===----------------------------------------------------------------------===//
31 // Command-line options
32 //===----------------------------------------------------------------------===//
36 cl::desc("Specify the name of an IR file to load for function definitions"),
37 cl::value_desc("input IR file name"));
40 UseObjectCache("use-object-cache",
41 cl::desc("Enable use of the MCJIT object caching"),
44 //===----------------------------------------------------------------------===//
46 //===----------------------------------------------------------------------===//
48 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
49 // of these for known things.
54 tok_def = -2, tok_extern = -3,
57 tok_identifier = -4, tok_number = -5,
60 tok_if = -6, tok_then = -7, tok_else = -8,
61 tok_for = -9, tok_in = -10,
64 tok_binary = -11, tok_unary = -12,
70 static std::string IdentifierStr; // Filled in if tok_identifier
71 static double NumVal; // Filled in if tok_number
73 /// gettok - Return the next token from standard input.
75 static int LastChar = ' ';
77 // Skip any whitespace.
78 while (isspace(LastChar))
81 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
82 IdentifierStr = LastChar;
83 while (isalnum((LastChar = getchar())))
84 IdentifierStr += LastChar;
86 if (IdentifierStr == "def") return tok_def;
87 if (IdentifierStr == "extern") return tok_extern;
88 if (IdentifierStr == "if") return tok_if;
89 if (IdentifierStr == "then") return tok_then;
90 if (IdentifierStr == "else") return tok_else;
91 if (IdentifierStr == "for") return tok_for;
92 if (IdentifierStr == "in") return tok_in;
93 if (IdentifierStr == "binary") return tok_binary;
94 if (IdentifierStr == "unary") return tok_unary;
95 if (IdentifierStr == "var") return tok_var;
96 return tok_identifier;
99 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
103 LastChar = getchar();
104 } while (isdigit(LastChar) || LastChar == '.');
106 NumVal = strtod(NumStr.c_str(), 0);
110 if (LastChar == '#') {
111 // Comment until end of line.
112 do LastChar = getchar();
113 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
119 // Check for end of file. Don't eat the EOF.
123 // Otherwise, just return the character as its ascii value.
124 int ThisChar = LastChar;
125 LastChar = getchar();
129 //===----------------------------------------------------------------------===//
130 // Abstract Syntax Tree (aka Parse Tree)
131 //===----------------------------------------------------------------------===//
133 /// ExprAST - Base class for all expression nodes.
136 virtual ~ExprAST() {}
137 virtual Value *Codegen() = 0;
140 /// NumberExprAST - Expression class for numeric literals like "1.0".
141 class NumberExprAST : public ExprAST {
144 NumberExprAST(double val) : Val(val) {}
145 virtual Value *Codegen();
148 /// VariableExprAST - Expression class for referencing a variable, like "a".
149 class VariableExprAST : public ExprAST {
152 VariableExprAST(const std::string &name) : Name(name) {}
153 const std::string &getName() const { return Name; }
154 virtual Value *Codegen();
157 /// UnaryExprAST - Expression class for a unary operator.
158 class UnaryExprAST : public ExprAST {
162 UnaryExprAST(char opcode, ExprAST *operand)
163 : Opcode(opcode), Operand(operand) {}
164 virtual Value *Codegen();
167 /// BinaryExprAST - Expression class for a binary operator.
168 class BinaryExprAST : public ExprAST {
172 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
173 : Op(op), LHS(lhs), RHS(rhs) {}
174 virtual Value *Codegen();
177 /// CallExprAST - Expression class for function calls.
178 class CallExprAST : public ExprAST {
180 std::vector<ExprAST*> Args;
182 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
183 : Callee(callee), Args(args) {}
184 virtual Value *Codegen();
187 /// IfExprAST - Expression class for if/then/else.
188 class IfExprAST : public ExprAST {
189 ExprAST *Cond, *Then, *Else;
191 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
192 : Cond(cond), Then(then), Else(_else) {}
193 virtual Value *Codegen();
196 /// ForExprAST - Expression class for for/in.
197 class ForExprAST : public ExprAST {
199 ExprAST *Start, *End, *Step, *Body;
201 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
202 ExprAST *step, ExprAST *body)
203 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
204 virtual Value *Codegen();
207 /// VarExprAST - Expression class for var/in
208 class VarExprAST : public ExprAST {
209 std::vector<std::pair<std::string, ExprAST*> > VarNames;
212 VarExprAST(const std::vector<std::pair<std::string, ExprAST*> > &varnames,
214 : VarNames(varnames), Body(body) {}
216 virtual Value *Codegen();
219 /// PrototypeAST - This class represents the "prototype" for a function,
220 /// which captures its argument names as well as if it is an operator.
223 std::vector<std::string> Args;
225 unsigned Precedence; // Precedence if a binary op.
227 PrototypeAST(const std::string &name, const std::vector<std::string> &args,
228 bool isoperator = false, unsigned prec = 0)
229 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
231 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
232 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
234 char getOperatorName() const {
235 assert(isUnaryOp() || isBinaryOp());
236 return Name[Name.size()-1];
239 unsigned getBinaryPrecedence() const { return Precedence; }
243 void CreateArgumentAllocas(Function *F);
246 /// FunctionAST - This class represents a function definition itself.
251 FunctionAST(PrototypeAST *proto, ExprAST *body)
252 : Proto(proto), Body(body) {}
257 //===----------------------------------------------------------------------===//
259 //===----------------------------------------------------------------------===//
261 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
262 /// token the parser is looking at. getNextToken reads another token from the
263 /// lexer and updates CurTok with its results.
265 static int getNextToken() {
266 return CurTok = gettok();
269 /// BinopPrecedence - This holds the precedence for each binary operator that is
271 static std::map<char, int> BinopPrecedence;
273 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
274 static int GetTokPrecedence() {
275 if (!isascii(CurTok))
278 // Make sure it's a declared binop.
279 int TokPrec = BinopPrecedence[CurTok];
280 if (TokPrec <= 0) return -1;
284 /// Error* - These are little helper functions for error handling.
285 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
286 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
287 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
289 static ExprAST *ParseExpression();
293 /// ::= identifier '(' expression* ')'
294 static ExprAST *ParseIdentifierExpr() {
295 std::string IdName = IdentifierStr;
297 getNextToken(); // eat identifier.
299 if (CurTok != '(') // Simple variable ref.
300 return new VariableExprAST(IdName);
303 getNextToken(); // eat (
304 std::vector<ExprAST*> Args;
307 ExprAST *Arg = ParseExpression();
311 if (CurTok == ')') break;
314 return Error("Expected ')' or ',' in argument list");
322 return new CallExprAST(IdName, Args);
325 /// numberexpr ::= number
326 static ExprAST *ParseNumberExpr() {
327 ExprAST *Result = new NumberExprAST(NumVal);
328 getNextToken(); // consume the number
332 /// parenexpr ::= '(' expression ')'
333 static ExprAST *ParseParenExpr() {
334 getNextToken(); // eat (.
335 ExprAST *V = ParseExpression();
339 return Error("expected ')'");
340 getNextToken(); // eat ).
344 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
345 static ExprAST *ParseIfExpr() {
346 getNextToken(); // eat the if.
349 ExprAST *Cond = ParseExpression();
352 if (CurTok != tok_then)
353 return Error("expected then");
354 getNextToken(); // eat the then
356 ExprAST *Then = ParseExpression();
357 if (Then == 0) return 0;
359 if (CurTok != tok_else)
360 return Error("expected else");
364 ExprAST *Else = ParseExpression();
367 return new IfExprAST(Cond, Then, Else);
370 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
371 static ExprAST *ParseForExpr() {
372 getNextToken(); // eat the for.
374 if (CurTok != tok_identifier)
375 return Error("expected identifier after for");
377 std::string IdName = IdentifierStr;
378 getNextToken(); // eat identifier.
381 return Error("expected '=' after for");
382 getNextToken(); // eat '='.
385 ExprAST *Start = ParseExpression();
386 if (Start == 0) return 0;
388 return Error("expected ',' after for start value");
391 ExprAST *End = ParseExpression();
392 if (End == 0) return 0;
394 // The step value is optional.
398 Step = ParseExpression();
399 if (Step == 0) return 0;
402 if (CurTok != tok_in)
403 return Error("expected 'in' after for");
404 getNextToken(); // eat 'in'.
406 ExprAST *Body = ParseExpression();
407 if (Body == 0) return 0;
409 return new ForExprAST(IdName, Start, End, Step, Body);
412 /// varexpr ::= 'var' identifier ('=' expression)?
413 // (',' identifier ('=' expression)?)* 'in' expression
414 static ExprAST *ParseVarExpr() {
415 getNextToken(); // eat the var.
417 std::vector<std::pair<std::string, ExprAST*> > VarNames;
419 // At least one variable name is required.
420 if (CurTok != tok_identifier)
421 return Error("expected identifier after var");
424 std::string Name = IdentifierStr;
425 getNextToken(); // eat identifier.
427 // Read the optional initializer.
430 getNextToken(); // eat the '='.
432 Init = ParseExpression();
433 if (Init == 0) return 0;
436 VarNames.push_back(std::make_pair(Name, Init));
438 // End of var list, exit loop.
439 if (CurTok != ',') break;
440 getNextToken(); // eat the ','.
442 if (CurTok != tok_identifier)
443 return Error("expected identifier list after var");
446 // At this point, we have to have 'in'.
447 if (CurTok != tok_in)
448 return Error("expected 'in' keyword after 'var'");
449 getNextToken(); // eat 'in'.
451 ExprAST *Body = ParseExpression();
452 if (Body == 0) return 0;
454 return new VarExprAST(VarNames, Body);
458 /// ::= identifierexpr
464 static ExprAST *ParsePrimary() {
466 default: return Error("unknown token when expecting an expression");
467 case tok_identifier: return ParseIdentifierExpr();
468 case tok_number: return ParseNumberExpr();
469 case '(': return ParseParenExpr();
470 case tok_if: return ParseIfExpr();
471 case tok_for: return ParseForExpr();
472 case tok_var: return ParseVarExpr();
479 static ExprAST *ParseUnary() {
480 // If the current token is not an operator, it must be a primary expr.
481 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
482 return ParsePrimary();
484 // If this is a unary operator, read it.
487 if (ExprAST *Operand = ParseUnary())
488 return new UnaryExprAST(Opc, Operand);
494 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
495 // If this is a binop, find its precedence.
497 int TokPrec = GetTokPrecedence();
499 // If this is a binop that binds at least as tightly as the current binop,
500 // consume it, otherwise we are done.
501 if (TokPrec < ExprPrec)
504 // Okay, we know this is a binop.
506 getNextToken(); // eat binop
508 // Parse the unary expression after the binary operator.
509 ExprAST *RHS = ParseUnary();
512 // If BinOp binds less tightly with RHS than the operator after RHS, let
513 // the pending operator take RHS as its LHS.
514 int NextPrec = GetTokPrecedence();
515 if (TokPrec < NextPrec) {
516 RHS = ParseBinOpRHS(TokPrec+1, RHS);
517 if (RHS == 0) return 0;
521 LHS = new BinaryExprAST(BinOp, LHS, RHS);
526 /// ::= unary binoprhs
528 static ExprAST *ParseExpression() {
529 ExprAST *LHS = ParseUnary();
532 return ParseBinOpRHS(0, LHS);
536 /// ::= id '(' id* ')'
537 /// ::= binary LETTER number? (id, id)
538 /// ::= unary LETTER (id)
539 static PrototypeAST *ParsePrototype() {
542 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
543 unsigned BinaryPrecedence = 30;
547 return ErrorP("Expected function name in prototype");
549 FnName = IdentifierStr;
555 if (!isascii(CurTok))
556 return ErrorP("Expected unary operator");
558 FnName += (char)CurTok;
564 if (!isascii(CurTok))
565 return ErrorP("Expected binary operator");
567 FnName += (char)CurTok;
571 // Read the precedence if present.
572 if (CurTok == tok_number) {
573 if (NumVal < 1 || NumVal > 100)
574 return ErrorP("Invalid precedecnce: must be 1..100");
575 BinaryPrecedence = (unsigned)NumVal;
582 return ErrorP("Expected '(' in prototype");
584 std::vector<std::string> ArgNames;
585 while (getNextToken() == tok_identifier)
586 ArgNames.push_back(IdentifierStr);
588 return ErrorP("Expected ')' in prototype");
591 getNextToken(); // eat ')'.
593 // Verify right number of names for operator.
594 if (Kind && ArgNames.size() != Kind)
595 return ErrorP("Invalid number of operands for operator");
597 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
600 /// definition ::= 'def' prototype expression
601 static FunctionAST *ParseDefinition() {
602 getNextToken(); // eat def.
603 PrototypeAST *Proto = ParsePrototype();
604 if (Proto == 0) return 0;
606 if (ExprAST *E = ParseExpression())
607 return new FunctionAST(Proto, E);
611 /// toplevelexpr ::= expression
612 static FunctionAST *ParseTopLevelExpr() {
613 if (ExprAST *E = ParseExpression()) {
614 // Make an anonymous proto.
615 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
616 return new FunctionAST(Proto, E);
621 /// external ::= 'extern' prototype
622 static PrototypeAST *ParseExtern() {
623 getNextToken(); // eat extern.
624 return ParsePrototype();
627 //===----------------------------------------------------------------------===//
628 // Quick and dirty hack
629 //===----------------------------------------------------------------------===//
631 // FIXME: Obviously we can do better than this
632 std::string GenerateUniqueName(const char *root)
636 sprintf(s, "%s%d", root, i++);
641 std::string MakeLegalFunctionName(std::string Name)
645 return GenerateUniqueName("anon_func_");
647 // Start with what we have
650 // Look for a numberic first character
651 if (NewName.find_first_of("0123456789") == 0) {
652 NewName.insert(0, 1, 'n');
655 // Replace illegal characters with their ASCII equivalent
656 std::string legal_elements = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
658 while ((pos = NewName.find_first_not_of(legal_elements)) != std::string::npos) {
659 char old_c = NewName.at(pos);
661 sprintf(new_str, "%d", (int)old_c);
662 NewName = NewName.replace(pos, 1, new_str);
668 //===----------------------------------------------------------------------===//
669 // MCJIT object cache class
670 //===----------------------------------------------------------------------===//
672 class MCJITObjectCache : public ObjectCache {
675 // Set IR cache directory
676 sys::fs::current_path(CacheDir);
677 sys::path::append(CacheDir, "toy_object_cache");
680 virtual ~MCJITObjectCache() {
683 virtual void notifyObjectCompiled(const Module *M, const MemoryBuffer *Obj) {
685 const std::string ModuleID = M->getModuleIdentifier();
687 // If we've flagged this as an IR file, cache it
688 if (0 == ModuleID.compare(0, 3, "IR:")) {
689 std::string IRFileName = ModuleID.substr(3);
690 SmallString<128>IRCacheFile = CacheDir;
691 sys::path::append(IRCacheFile, IRFileName);
692 if (!sys::fs::exists(CacheDir.str()) && sys::fs::create_directory(CacheDir.str())) {
693 fprintf(stderr, "Unable to create cache directory\n");
697 raw_fd_ostream IRObjectFile(IRCacheFile.c_str(), ErrStr, raw_fd_ostream::F_Binary);
698 IRObjectFile << Obj->getBuffer();
702 // MCJIT will call this function before compiling any module
703 // MCJIT takes ownership of both the MemoryBuffer object and the memory
704 // to which it refers.
705 virtual MemoryBuffer* getObject(const Module* M) {
707 const std::string ModuleID = M->getModuleIdentifier();
709 // If we've flagged this as an IR file, cache it
710 if (0 == ModuleID.compare(0, 3, "IR:")) {
711 std::string IRFileName = ModuleID.substr(3);
712 SmallString<128> IRCacheFile = CacheDir;
713 sys::path::append(IRCacheFile, IRFileName);
714 if (!sys::fs::exists(IRCacheFile.str())) {
715 // This file isn't in our cache
718 std::unique_ptr<MemoryBuffer> IRObjectBuffer;
719 MemoryBuffer::getFile(IRCacheFile.c_str(), IRObjectBuffer, -1, false);
720 // MCJIT will want to write into this buffer, and we don't want that
721 // because the file has probably just been mmapped. Instead we make
722 // a copy. The filed-based buffer will be released when it goes
724 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer->getBuffer());
731 SmallString<128> CacheDir;
734 //===----------------------------------------------------------------------===//
735 // MCJIT helper class
736 //===----------------------------------------------------------------------===//
741 MCJITHelper(LLVMContext& C) : Context(C), OpenModule(NULL) {}
744 Function *getFunction(const std::string FnName);
745 Module *getModuleForNewFunction();
746 void *getPointerToFunction(Function* F);
747 void *getPointerToNamedFunction(const std::string &Name);
748 ExecutionEngine *compileModule(Module *M);
749 void closeCurrentModule();
750 void addModule(Module *M);
754 typedef std::vector<Module*> ModuleVector;
756 LLVMContext &Context;
758 ModuleVector Modules;
759 std::map<Module *, ExecutionEngine *> EngineMap;
760 MCJITObjectCache OurObjectCache;
763 class HelpingMemoryManager : public SectionMemoryManager
765 HelpingMemoryManager(const HelpingMemoryManager&) LLVM_DELETED_FUNCTION;
766 void operator=(const HelpingMemoryManager&) LLVM_DELETED_FUNCTION;
769 HelpingMemoryManager(MCJITHelper *Helper) : MasterHelper(Helper) {}
770 virtual ~HelpingMemoryManager() {}
772 /// This method returns the address of the specified function.
773 /// Our implementation will attempt to find functions in other
774 /// modules associated with the MCJITHelper to cross link functions
775 /// from one generated module to another.
777 /// If \p AbortOnFailure is false and no function with the given name is
778 /// found, this function returns a null pointer. Otherwise, it prints a
779 /// message to stderr and aborts.
780 virtual void *getPointerToNamedFunction(const std::string &Name,
781 bool AbortOnFailure = true);
783 MCJITHelper *MasterHelper;
786 void *HelpingMemoryManager::getPointerToNamedFunction(const std::string &Name,
789 // Try the standard symbol resolution first, but ask it not to abort.
790 void *pfn = SectionMemoryManager::getPointerToNamedFunction(Name, false);
794 pfn = MasterHelper->getPointerToNamedFunction(Name);
795 if (!pfn && AbortOnFailure)
796 report_fatal_error("Program used external function '" + Name +
797 "' which could not be resolved!");
801 MCJITHelper::~MCJITHelper()
803 // Walk the vector of modules.
804 ModuleVector::iterator it, end;
805 for (it = Modules.begin(), end = Modules.end();
807 // See if we have an execution engine for this module.
808 std::map<Module*, ExecutionEngine*>::iterator mapIt = EngineMap.find(*it);
809 // If we have an EE, the EE owns the module so just delete the EE.
810 if (mapIt != EngineMap.end()) {
811 delete mapIt->second;
813 // Otherwise, we still own the module. Delete it now.
819 Function *MCJITHelper::getFunction(const std::string FnName) {
820 ModuleVector::iterator begin = Modules.begin();
821 ModuleVector::iterator end = Modules.end();
822 ModuleVector::iterator it;
823 for (it = begin; it != end; ++it) {
824 Function *F = (*it)->getFunction(FnName);
826 if (*it == OpenModule)
829 assert(OpenModule != NULL);
831 // This function is in a module that has already been JITed.
832 // We need to generate a new prototype for external linkage.
833 Function *PF = OpenModule->getFunction(FnName);
834 if (PF && !PF->empty()) {
835 ErrorF("redefinition of function across modules");
839 // If we don't have a prototype yet, create one.
841 PF = Function::Create(F->getFunctionType(),
842 Function::ExternalLinkage,
851 Module *MCJITHelper::getModuleForNewFunction() {
852 // If we have a Module that hasn't been JITed, use that.
856 // Otherwise create a new Module.
857 std::string ModName = GenerateUniqueName("mcjit_module_");
858 Module *M = new Module(ModName, Context);
859 Modules.push_back(M);
864 void *MCJITHelper::getPointerToFunction(Function* F) {
865 // Look for this function in an existing module
866 ModuleVector::iterator begin = Modules.begin();
867 ModuleVector::iterator end = Modules.end();
868 ModuleVector::iterator it;
869 std::string FnName = F->getName();
870 for (it = begin; it != end; ++it) {
871 Function *MF = (*it)->getFunction(FnName);
873 std::map<Module*, ExecutionEngine*>::iterator eeIt = EngineMap.find(*it);
874 if (eeIt != EngineMap.end()) {
875 void *P = eeIt->second->getPointerToFunction(F);
879 ExecutionEngine *EE = compileModule(*it);
880 void *P = EE->getPointerToFunction(F);
889 void MCJITHelper::closeCurrentModule() {
893 ExecutionEngine *MCJITHelper::compileModule(Module *M) {
895 closeCurrentModule();
898 ExecutionEngine *NewEngine = EngineBuilder(M)
899 .setErrorStr(&ErrStr)
900 .setMCJITMemoryManager(new HelpingMemoryManager(this))
903 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
908 NewEngine->setObjectCache(&OurObjectCache);
910 // Get the ModuleID so we can identify IR input files
911 const std::string ModuleID = M->getModuleIdentifier();
913 // If we've flagged this as an IR file, it doesn't need function passes run.
914 if (0 != ModuleID.compare(0, 3, "IR:")) {
915 // Create a function pass manager for this engine
916 FunctionPassManager *FPM = new FunctionPassManager(M);
918 // Set up the optimizer pipeline. Start with registering info about how the
919 // target lays out data structures.
920 FPM->add(new DataLayout(*NewEngine->getDataLayout()));
921 // Provide basic AliasAnalysis support for GVN.
922 FPM->add(createBasicAliasAnalysisPass());
923 // Promote allocas to registers.
924 FPM->add(createPromoteMemoryToRegisterPass());
925 // Do simple "peephole" optimizations and bit-twiddling optzns.
926 FPM->add(createInstructionCombiningPass());
927 // Reassociate expressions.
928 FPM->add(createReassociatePass());
929 // Eliminate Common SubExpressions.
930 FPM->add(createGVNPass());
931 // Simplify the control flow graph (deleting unreachable blocks, etc).
932 FPM->add(createCFGSimplificationPass());
933 FPM->doInitialization();
935 // For each function in the module
937 Module::iterator end = M->end();
938 for (it = M->begin(); it != end; ++it) {
939 // Run the FPM on this function
943 // We don't need this anymore
948 EngineMap[M] = NewEngine;
949 NewEngine->finalizeObject();
954 void *MCJITHelper::getPointerToNamedFunction(const std::string &Name)
956 // Look for the functions in our modules, compiling only as necessary
957 ModuleVector::iterator begin = Modules.begin();
958 ModuleVector::iterator end = Modules.end();
959 ModuleVector::iterator it;
960 for (it = begin; it != end; ++it) {
961 Function *F = (*it)->getFunction(Name);
962 if (F && !F->empty()) {
963 std::map<Module*, ExecutionEngine*>::iterator eeIt = EngineMap.find(*it);
964 if (eeIt != EngineMap.end()) {
965 void *P = eeIt->second->getPointerToFunction(F);
969 ExecutionEngine *EE = compileModule(*it);
970 void *P = EE->getPointerToFunction(F);
979 void MCJITHelper::addModule(Module* M) {
980 Modules.push_back(M);
983 void MCJITHelper::dump()
985 ModuleVector::iterator begin = Modules.begin();
986 ModuleVector::iterator end = Modules.end();
987 ModuleVector::iterator it;
988 for (it = begin; it != end; ++it)
992 //===----------------------------------------------------------------------===//
994 //===----------------------------------------------------------------------===//
996 static MCJITHelper *TheHelper;
997 static IRBuilder<> Builder(getGlobalContext());
998 static std::map<std::string, AllocaInst*> NamedValues;
1000 Value *ErrorV(const char *Str) { Error(Str); return 0; }
1002 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
1003 /// the function. This is used for mutable variables etc.
1004 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
1005 const std::string &VarName) {
1006 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
1007 TheFunction->getEntryBlock().begin());
1008 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
1012 Value *NumberExprAST::Codegen() {
1013 return ConstantFP::get(getGlobalContext(), APFloat(Val));
1016 Value *VariableExprAST::Codegen() {
1017 // Look this variable up in the function.
1018 Value *V = NamedValues[Name];
1020 sprintf(ErrStr, "Unknown variable name %s", Name.c_str());
1021 if (V == 0) return ErrorV(ErrStr);
1024 return Builder.CreateLoad(V, Name.c_str());
1027 Value *UnaryExprAST::Codegen() {
1028 Value *OperandV = Operand->Codegen();
1029 if (OperandV == 0) return 0;
1031 Function *F = TheHelper->getFunction(MakeLegalFunctionName(std::string("unary")+Opcode));
1033 return ErrorV("Unknown unary operator");
1035 return Builder.CreateCall(F, OperandV, "unop");
1038 Value *BinaryExprAST::Codegen() {
1039 // Special case '=' because we don't want to emit the LHS as an expression.
1041 // Assignment requires the LHS to be an identifier.
1042 VariableExprAST *LHSE = reinterpret_cast<VariableExprAST*>(LHS);
1044 return ErrorV("destination of '=' must be a variable");
1046 Value *Val = RHS->Codegen();
1047 if (Val == 0) return 0;
1049 // Look up the name.
1050 Value *Variable = NamedValues[LHSE->getName()];
1051 if (Variable == 0) return ErrorV("Unknown variable name");
1053 Builder.CreateStore(Val, Variable);
1057 Value *L = LHS->Codegen();
1058 Value *R = RHS->Codegen();
1059 if (L == 0 || R == 0) return 0;
1062 case '+': return Builder.CreateFAdd(L, R, "addtmp");
1063 case '-': return Builder.CreateFSub(L, R, "subtmp");
1064 case '*': return Builder.CreateFMul(L, R, "multmp");
1065 case '/': return Builder.CreateFDiv(L, R, "divtmp");
1067 L = Builder.CreateFCmpULT(L, R, "cmptmp");
1068 // Convert bool 0/1 to double 0.0 or 1.0
1069 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
1074 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
1076 Function *F = TheHelper->getFunction(MakeLegalFunctionName(std::string("binary")+Op));
1077 assert(F && "binary operator not found!");
1079 Value *Ops[] = { L, R };
1080 return Builder.CreateCall(F, Ops, "binop");
1083 Value *CallExprAST::Codegen() {
1084 // Look up the name in the global module table.
1085 Function *CalleeF = TheHelper->getFunction(Callee);
1087 return ErrorV("Unknown function referenced");
1089 // If argument mismatch error.
1090 if (CalleeF->arg_size() != Args.size())
1091 return ErrorV("Incorrect # arguments passed");
1093 std::vector<Value*> ArgsV;
1094 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1095 ArgsV.push_back(Args[i]->Codegen());
1096 if (ArgsV.back() == 0) return 0;
1099 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
1102 Value *IfExprAST::Codegen() {
1103 Value *CondV = Cond->Codegen();
1104 if (CondV == 0) return 0;
1106 // Convert condition to a bool by comparing equal to 0.0.
1107 CondV = Builder.CreateFCmpONE(CondV,
1108 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
1111 Function *TheFunction = Builder.GetInsertBlock()->getParent();
1113 // Create blocks for the then and else cases. Insert the 'then' block at the
1114 // end of the function.
1115 BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
1116 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
1117 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
1119 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
1122 Builder.SetInsertPoint(ThenBB);
1124 Value *ThenV = Then->Codegen();
1125 if (ThenV == 0) return 0;
1127 Builder.CreateBr(MergeBB);
1128 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
1129 ThenBB = Builder.GetInsertBlock();
1132 TheFunction->getBasicBlockList().push_back(ElseBB);
1133 Builder.SetInsertPoint(ElseBB);
1135 Value *ElseV = Else->Codegen();
1136 if (ElseV == 0) return 0;
1138 Builder.CreateBr(MergeBB);
1139 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
1140 ElseBB = Builder.GetInsertBlock();
1142 // Emit merge block.
1143 TheFunction->getBasicBlockList().push_back(MergeBB);
1144 Builder.SetInsertPoint(MergeBB);
1145 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
1148 PN->addIncoming(ThenV, ThenBB);
1149 PN->addIncoming(ElseV, ElseBB);
1153 Value *ForExprAST::Codegen() {
1155 // var = alloca double
1157 // start = startexpr
1158 // store start -> var
1166 // endcond = endexpr
1168 // curvar = load var
1169 // nextvar = curvar + step
1170 // store nextvar -> var
1171 // br endcond, loop, endloop
1174 Function *TheFunction = Builder.GetInsertBlock()->getParent();
1176 // Create an alloca for the variable in the entry block.
1177 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1179 // Emit the start code first, without 'variable' in scope.
1180 Value *StartVal = Start->Codegen();
1181 if (StartVal == 0) return 0;
1183 // Store the value into the alloca.
1184 Builder.CreateStore(StartVal, Alloca);
1186 // Make the new basic block for the loop header, inserting after current
1188 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
1190 // Insert an explicit fall through from the current block to the LoopBB.
1191 Builder.CreateBr(LoopBB);
1193 // Start insertion in LoopBB.
1194 Builder.SetInsertPoint(LoopBB);
1196 // Within the loop, the variable is defined equal to the PHI node. If it
1197 // shadows an existing variable, we have to restore it, so save it now.
1198 AllocaInst *OldVal = NamedValues[VarName];
1199 NamedValues[VarName] = Alloca;
1201 // Emit the body of the loop. This, like any other expr, can change the
1202 // current BB. Note that we ignore the value computed by the body, but don't
1204 if (Body->Codegen() == 0)
1207 // Emit the step value.
1210 StepVal = Step->Codegen();
1211 if (StepVal == 0) return 0;
1213 // If not specified, use 1.0.
1214 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
1217 // Compute the end condition.
1218 Value *EndCond = End->Codegen();
1219 if (EndCond == 0) return EndCond;
1221 // Reload, increment, and restore the alloca. This handles the case where
1222 // the body of the loop mutates the variable.
1223 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
1224 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
1225 Builder.CreateStore(NextVar, Alloca);
1227 // Convert condition to a bool by comparing equal to 0.0.
1228 EndCond = Builder.CreateFCmpONE(EndCond,
1229 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
1232 // Create the "after loop" block and insert it.
1233 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
1235 // Insert the conditional branch into the end of LoopEndBB.
1236 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
1238 // Any new code will be inserted in AfterBB.
1239 Builder.SetInsertPoint(AfterBB);
1241 // Restore the unshadowed variable.
1243 NamedValues[VarName] = OldVal;
1245 NamedValues.erase(VarName);
1248 // for expr always returns 0.0.
1249 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
1252 Value *VarExprAST::Codegen() {
1253 std::vector<AllocaInst *> OldBindings;
1255 Function *TheFunction = Builder.GetInsertBlock()->getParent();
1257 // Register all variables and emit their initializer.
1258 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
1259 const std::string &VarName = VarNames[i].first;
1260 ExprAST *Init = VarNames[i].second;
1262 // Emit the initializer before adding the variable to scope, this prevents
1263 // the initializer from referencing the variable itself, and permits stuff
1266 // var a = a in ... # refers to outer 'a'.
1269 InitVal = Init->Codegen();
1270 if (InitVal == 0) return 0;
1271 } else { // If not specified, use 0.0.
1272 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
1275 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1276 Builder.CreateStore(InitVal, Alloca);
1278 // Remember the old variable binding so that we can restore the binding when
1280 OldBindings.push_back(NamedValues[VarName]);
1282 // Remember this binding.
1283 NamedValues[VarName] = Alloca;
1286 // Codegen the body, now that all vars are in scope.
1287 Value *BodyVal = Body->Codegen();
1288 if (BodyVal == 0) return 0;
1290 // Pop all our variables from scope.
1291 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1292 NamedValues[VarNames[i].first] = OldBindings[i];
1294 // Return the body computation.
1298 Function *PrototypeAST::Codegen() {
1299 // Make the function type: double(double,double) etc.
1300 std::vector<Type*> Doubles(Args.size(),
1301 Type::getDoubleTy(getGlobalContext()));
1302 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
1305 std::string FnName = MakeLegalFunctionName(Name);
1307 Module* M = TheHelper->getModuleForNewFunction();
1309 Function *F = Function::Create(FT, Function::ExternalLinkage, FnName, M);
1311 // If F conflicted, there was already something named 'FnName'. If it has a
1312 // body, don't allow redefinition or reextern.
1313 if (F->getName() != FnName) {
1314 // Delete the one we just made and get the existing one.
1315 F->eraseFromParent();
1316 F = M->getFunction(Name);
1318 // If F already has a body, reject this.
1320 ErrorF("redefinition of function");
1324 // If F took a different number of args, reject.
1325 if (F->arg_size() != Args.size()) {
1326 ErrorF("redefinition of function with different # args");
1331 // Set names for all arguments.
1333 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1335 AI->setName(Args[Idx]);
1340 /// CreateArgumentAllocas - Create an alloca for each argument and register the
1341 /// argument in the symbol table so that references to it will succeed.
1342 void PrototypeAST::CreateArgumentAllocas(Function *F) {
1343 Function::arg_iterator AI = F->arg_begin();
1344 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1345 // Create an alloca for this variable.
1346 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1348 // Store the initial value into the alloca.
1349 Builder.CreateStore(AI, Alloca);
1351 // Add arguments to variable symbol table.
1352 NamedValues[Args[Idx]] = Alloca;
1356 Function *FunctionAST::Codegen() {
1357 NamedValues.clear();
1359 Function *TheFunction = Proto->Codegen();
1360 if (TheFunction == 0)
1363 // If this is an operator, install it.
1364 if (Proto->isBinaryOp())
1365 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
1367 // Create a new basic block to start insertion into.
1368 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1369 Builder.SetInsertPoint(BB);
1371 // Add all arguments to the symbol table and create their allocas.
1372 Proto->CreateArgumentAllocas(TheFunction);
1374 if (Value *RetVal = Body->Codegen()) {
1375 // Finish off the function.
1376 Builder.CreateRet(RetVal);
1378 // Validate the generated code, checking for consistency.
1379 verifyFunction(*TheFunction);
1384 // Error reading body, remove function.
1385 TheFunction->eraseFromParent();
1387 if (Proto->isBinaryOp())
1388 BinopPrecedence.erase(Proto->getOperatorName());
1392 //===----------------------------------------------------------------------===//
1393 // Top-Level parsing and JIT Driver
1394 //===----------------------------------------------------------------------===//
1396 static void HandleDefinition() {
1397 if (FunctionAST *F = ParseDefinition()) {
1398 TheHelper->closeCurrentModule();
1399 if (Function *LF = F->Codegen()) {
1400 #ifndef MINIMAL_STDERR_OUTPUT
1401 fprintf(stderr, "Read function definition:");
1406 // Skip token for error recovery.
1411 static void HandleExtern() {
1412 if (PrototypeAST *P = ParseExtern()) {
1413 if (Function *F = P->Codegen()) {
1414 #ifndef MINIMAL_STDERR_OUTPUT
1415 fprintf(stderr, "Read extern: ");
1420 // Skip token for error recovery.
1425 static void HandleTopLevelExpression() {
1426 // Evaluate a top-level expression into an anonymous function.
1427 if (FunctionAST *F = ParseTopLevelExpr()) {
1428 if (Function *LF = F->Codegen()) {
1429 // JIT the function, returning a function pointer.
1430 void *FPtr = TheHelper->getPointerToFunction(LF);
1432 // Cast it to the right type (takes no arguments, returns a double) so we
1433 // can call it as a native function.
1434 double (*FP)() = (double (*)())(intptr_t)FPtr;
1435 #ifdef MINIMAL_STDERR_OUTPUT
1438 fprintf(stderr, "Evaluated to %f\n", FP());
1442 // Skip token for error recovery.
1447 /// top ::= definition | external | expression | ';'
1448 static void MainLoop() {
1450 #ifndef MINIMAL_STDERR_OUTPUT
1451 fprintf(stderr, "ready> ");
1454 case tok_eof: return;
1455 case ';': getNextToken(); break; // ignore top-level semicolons.
1456 case tok_def: HandleDefinition(); break;
1457 case tok_extern: HandleExtern(); break;
1458 default: HandleTopLevelExpression(); break;
1463 //===----------------------------------------------------------------------===//
1464 // "Library" functions that can be "extern'd" from user code.
1465 //===----------------------------------------------------------------------===//
1467 /// putchard - putchar that takes a double and returns 0.
1469 double putchard(double X) {
1474 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1476 double printd(double X) {
1487 //===----------------------------------------------------------------------===//
1488 // Command line input file handler
1489 //===----------------------------------------------------------------------===//
1491 Module* parseInputIR(std::string InputFile) {
1493 Module *M = ParseIRFile(InputFile, Err, getGlobalContext());
1495 Err.print("IR parsing failed: ", errs());
1500 sprintf(ModID, "IR:%s", InputFile.c_str());
1501 M->setModuleIdentifier(ModID);
1503 TheHelper->addModule(M);
1507 //===----------------------------------------------------------------------===//
1508 // Main driver code.
1509 //===----------------------------------------------------------------------===//
1511 int main(int argc, char **argv) {
1512 InitializeNativeTarget();
1513 InitializeNativeTargetAsmPrinter();
1514 InitializeNativeTargetAsmParser();
1515 LLVMContext &Context = getGlobalContext();
1517 cl::ParseCommandLineOptions(argc, argv,
1518 "Kaleidoscope example program\n");
1520 // Install standard binary operators.
1521 // 1 is lowest precedence.
1522 BinopPrecedence['='] = 2;
1523 BinopPrecedence['<'] = 10;
1524 BinopPrecedence['+'] = 20;
1525 BinopPrecedence['-'] = 20;
1526 BinopPrecedence['/'] = 40;
1527 BinopPrecedence['*'] = 40; // highest.
1529 // Prime the first token.
1530 #ifndef MINIMAL_STDERR_OUTPUT
1531 fprintf(stderr, "ready> ");
1535 // Make the helper, which holds all the code.
1536 TheHelper = new MCJITHelper(Context);
1538 if (!InputIR.empty()) {
1539 parseInputIR(InputIR);
1542 // Run the main "interpreter loop" now.
1545 #ifndef MINIMAL_STDERR_OUTPUT
1546 // Print out all of the generated code.