1 //===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tool implements a just-in-time compiler for LLVM, allowing direct
11 // execution of LLVM bytecode in an efficient manner.
13 //===----------------------------------------------------------------------===//
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/CodeGen/MachineCodeEmitter.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/ExecutionEngine/GenericValue.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetJITInfo.h"
25 #include "Support/DynamicLinker.h"
30 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
31 : ExecutionEngine(MP), TM(tm), TJI(tji), PM(MP) {
32 setTargetData(TM.getTargetData());
35 MCE = createEmitter(*this);
38 PM.add (new TargetData (TM.getTargetData ()));
40 // Compile LLVM Code down to machine code in the intermediate representation
41 TJI.addPassesToJITCompile(PM);
43 // Turn the machine code intermediate representation into bytes in memory that
45 if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
46 std::cerr << "lli: target '" << TM.getName()
47 << "' doesn't support machine code emission!\n";
57 /// run - Start execution with the specified function and arguments.
59 GenericValue JIT::runFunction(Function *F,
60 const std::vector<GenericValue> &ArgValues) {
61 assert(F && "Function *F was null at entry to run()");
64 void *FPtr = getPointerToFunction(F);
65 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
66 const Type *RetTy = F->getReturnType();
68 // Handle some common cases first.
69 if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) {
70 if (ArgValues.size() == 3) {
71 int (*PF)(int, char **, const char **) =
72 (int(*)(int, char **, const char **))FPtr;
75 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
76 (const char **)GVTOP(ArgValues[2]));
78 } else if (ArgValues.size() == 1) {
79 int (*PF)(int) = (int(*)(int))FPtr;
80 rv.IntVal = PF(ArgValues[0].IntVal);
82 } else if (ArgValues.size() == 0) {
83 int (*PF)() = (int(*)())FPtr;
89 // FIXME: This code should handle a couple of common cases efficiently, but
90 // it should also implement the general case by code-gening a new anonymous
91 // nullary function to call.
92 std::cerr << "Sorry, unimplemented feature in the LLVM JIT. See LLVM"
93 << " PR#419\n for details.\n";
98 /// runJITOnFunction - Run the FunctionPassManager full of
99 /// just-in-time compilation passes on F, hopefully filling in
100 /// GlobalAddress[F] with the address of F's machine code.
102 void JIT::runJITOnFunction(Function *F) {
103 static bool isAlreadyCodeGenerating = false;
104 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
107 isAlreadyCodeGenerating = true;
109 isAlreadyCodeGenerating = false;
111 // If the function referred to a global variable that had not yet been
112 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
113 // all of these globals now.
114 while (!PendingGlobals.empty()) {
115 const GlobalVariable *GV = PendingGlobals.back();
116 PendingGlobals.pop_back();
117 EmitGlobalVariable(GV);
121 /// getPointerToFunction - This method is used to get the address of the
122 /// specified function, compiling it if neccesary.
124 void *JIT::getPointerToFunction(Function *F) {
125 if (void *Addr = getPointerToGlobalIfAvailable(F))
126 return Addr; // Check if function already code gen'd
128 // Make sure we read in the function if it exists in this Module
130 MP->materializeFunction(F);
131 } catch ( std::string& errmsg ) {
132 std::cerr << "Error reading bytecode file: " << errmsg << "\n";
135 std::cerr << "Error reading bytecode file!\n";
139 if (F->isExternal()) {
140 void *Addr = getPointerToNamedFunction(F->getName());
141 addGlobalMapping(F, Addr);
147 void *Addr = getPointerToGlobalIfAvailable(F);
148 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
152 // getPointerToFunctionOrStub - If the specified function has been
153 // code-gen'd, return a pointer to the function. If not, compile it, or use
154 // a stub to implement lazy compilation if available.
156 void *JIT::getPointerToFunctionOrStub(Function *F) {
157 // If we have already code generated the function, just return the address.
158 if (void *Addr = getPointerToGlobalIfAvailable(F))
161 // If the target supports "stubs" for functions, get a stub now.
162 if (void *Ptr = TJI.getJITStubForFunction(F, *MCE))
165 // Otherwise, if the target doesn't support it, just codegen the function.
166 return getPointerToFunction(F);
169 /// getOrEmitGlobalVariable - Return the address of the specified global
170 /// variable, possibly emitting it to memory if needed. This is used by the
172 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
173 void *Ptr = getPointerToGlobalIfAvailable(GV);
176 // If the global is external, just remember the address.
177 if (GV->isExternal()) {
178 Ptr = GetAddressOfSymbol(GV->getName().c_str());
180 std::cerr << "Could not resolve external global address: "
181 << GV->getName() << "\n";
185 // If the global hasn't been emitted to memory yet, allocate space. We will
186 // actually initialize the global after current function has finished
188 Ptr =new char[getTargetData().getTypeSize(GV->getType()->getElementType())];
189 PendingGlobals.push_back(GV);
191 addGlobalMapping(GV, Ptr);
196 /// recompileAndRelinkFunction - This method is used to force a function
197 /// which has already been compiled, to be compiled again, possibly
198 /// after it has been modified. Then the entry to the old copy is overwritten
199 /// with a branch to the new copy. If there was no old copy, this acts
200 /// just like JIT::getPointerToFunction().
202 void *JIT::recompileAndRelinkFunction(Function *F) {
203 void *OldAddr = getPointerToGlobalIfAvailable(F);
205 // If it's not already compiled there is no reason to patch it up.
206 if (OldAddr == 0) { return getPointerToFunction(F); }
208 // Delete the old function mapping.
209 addGlobalMapping(F, 0);
211 // Recodegen the function
214 // Update state, forward the old function to the new function.
215 void *Addr = getPointerToGlobalIfAvailable(F);
216 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
217 TJI.replaceMachineCodeForFunction(OldAddr, Addr);