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/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/ModuleProvider.h"
22 #include "llvm/CodeGen/MachineCodeEmitter.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/ExecutionEngine/GenericValue.h"
25 #include "llvm/System/DynamicLibrary.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetJITInfo.h"
32 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
33 : ExecutionEngine(MP), TM(tm), TJI(tji), state(MP) {
34 setTargetData(TM.getTargetData());
37 MCE = createEmitter(*this);
40 MutexGuard locked(lock);
41 FunctionPassManager& PM = state.getPM(locked);
42 PM.add(new TargetData(TM.getTargetData()));
44 // Compile LLVM Code down to machine code in the intermediate representation
45 TJI.addPassesToJITCompile(PM);
47 // Turn the machine code intermediate representation into bytes in memory that
49 if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
50 std::cerr << "Target '" << TM.getName()
51 << "' doesn't support machine code emission!\n";
61 /// run - Start execution with the specified function and arguments.
63 GenericValue JIT::runFunction(Function *F,
64 const std::vector<GenericValue> &ArgValues) {
65 assert(F && "Function *F was null at entry to run()");
67 void *FPtr = getPointerToFunction(F);
68 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
69 const FunctionType *FTy = F->getFunctionType();
70 const Type *RetTy = FTy->getReturnType();
72 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
73 "Too many arguments passed into function!");
74 assert(FTy->getNumParams() == ArgValues.size() &&
75 "This doesn't support passing arguments through varargs (yet)!");
77 // Handle some common cases first. These cases correspond to common `main'
79 if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) {
80 switch (ArgValues.size()) {
82 if ((FTy->getParamType(0) == Type::IntTy ||
83 FTy->getParamType(0) == Type::UIntTy) &&
84 isa<PointerType>(FTy->getParamType(1)) &&
85 isa<PointerType>(FTy->getParamType(2))) {
86 int (*PF)(int, char **, const char **) =
87 (int(*)(int, char **, const char **))FPtr;
91 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
92 (const char **)GVTOP(ArgValues[2]));
97 if ((FTy->getParamType(0) == Type::IntTy ||
98 FTy->getParamType(0) == Type::UIntTy) &&
99 isa<PointerType>(FTy->getParamType(1))) {
100 int (*PF)(int, char **) = (int(*)(int, char **))FPtr;
102 // Call the function.
104 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]));
109 if (FTy->getNumParams() == 1 &&
110 (FTy->getParamType(0) == Type::IntTy ||
111 FTy->getParamType(0) == Type::UIntTy)) {
113 int (*PF)(int) = (int(*)(int))FPtr;
114 rv.IntVal = PF(ArgValues[0].IntVal);
121 // Handle cases where no arguments are passed first.
122 if (ArgValues.empty()) {
124 switch (RetTy->getTypeID()) {
125 default: assert(0 && "Unknown return type for function call!");
127 rv.BoolVal = ((bool(*)())FPtr)();
129 case Type::SByteTyID:
130 case Type::UByteTyID:
131 rv.SByteVal = ((char(*)())FPtr)();
133 case Type::ShortTyID:
134 case Type::UShortTyID:
135 rv.ShortVal = ((short(*)())FPtr)();
140 rv.IntVal = ((int(*)())FPtr)();
143 case Type::ULongTyID:
144 rv.LongVal = ((int64_t(*)())FPtr)();
146 case Type::FloatTyID:
147 rv.FloatVal = ((float(*)())FPtr)();
149 case Type::DoubleTyID:
150 rv.DoubleVal = ((double(*)())FPtr)();
152 case Type::PointerTyID:
153 return PTOGV(((void*(*)())FPtr)());
157 // Okay, this is not one of our quick and easy cases. Because we don't have a
158 // full FFI, we have to codegen a nullary stub function that just calls the
159 // function we are interested in, passing in constants for all of the
160 // arguments. Make this function and return.
162 // First, create the function.
163 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
164 Function *Stub = new Function(STy, Function::InternalLinkage, "",
167 // Insert a basic block.
168 BasicBlock *StubBB = new BasicBlock("", Stub);
170 // Convert all of the GenericValue arguments over to constants. Note that we
171 // currently don't support varargs.
172 std::vector<Value*> Args;
173 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
175 const Type *ArgTy = FTy->getParamType(i);
176 const GenericValue &AV = ArgValues[i];
177 switch (ArgTy->getTypeID()) {
178 default: assert(0 && "Unknown argument type for function call!");
179 case Type::BoolTyID: C = ConstantBool::get(AV.BoolVal); break;
180 case Type::SByteTyID: C = ConstantSInt::get(ArgTy, AV.SByteVal); break;
181 case Type::UByteTyID: C = ConstantUInt::get(ArgTy, AV.UByteVal); break;
182 case Type::ShortTyID: C = ConstantSInt::get(ArgTy, AV.ShortVal); break;
183 case Type::UShortTyID: C = ConstantUInt::get(ArgTy, AV.UShortVal); break;
184 case Type::IntTyID: C = ConstantSInt::get(ArgTy, AV.IntVal); break;
185 case Type::UIntTyID: C = ConstantUInt::get(ArgTy, AV.UIntVal); break;
186 case Type::LongTyID: C = ConstantSInt::get(ArgTy, AV.LongVal); break;
187 case Type::ULongTyID: C = ConstantUInt::get(ArgTy, AV.ULongVal); break;
188 case Type::FloatTyID: C = ConstantFP ::get(ArgTy, AV.FloatVal); break;
189 case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, AV.DoubleVal); break;
190 case Type::PointerTyID:
191 void *ArgPtr = GVTOP(AV);
192 if (sizeof(void*) == 4) {
193 C = ConstantSInt::get(Type::IntTy, (int)(intptr_t)ArgPtr);
195 C = ConstantSInt::get(Type::LongTy, (intptr_t)ArgPtr);
197 C = ConstantExpr::getCast(C, ArgTy); // Cast the integer to pointer
203 CallInst *TheCall = new CallInst(F, Args, "", StubBB);
204 TheCall->setTailCall();
205 if (TheCall->getType() != Type::VoidTy)
206 new ReturnInst(TheCall, StubBB); // Return result of the call.
208 new ReturnInst(StubBB); // Just return void.
210 // Finally, return the value returned by our nullary stub function.
211 return runFunction(Stub, std::vector<GenericValue>());
214 /// runJITOnFunction - Run the FunctionPassManager full of
215 /// just-in-time compilation passes on F, hopefully filling in
216 /// GlobalAddress[F] with the address of F's machine code.
218 void JIT::runJITOnFunction(Function *F) {
219 static bool isAlreadyCodeGenerating = false;
220 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
222 MutexGuard locked(lock);
225 isAlreadyCodeGenerating = true;
226 state.getPM(locked).run(*F);
227 isAlreadyCodeGenerating = false;
229 // If the function referred to a global variable that had not yet been
230 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
231 // all of these globals now.
232 while (!state.getPendingGlobals(locked).empty()) {
233 const GlobalVariable *GV = state.getPendingGlobals(locked).back();
234 state.getPendingGlobals(locked).pop_back();
235 EmitGlobalVariable(GV);
239 /// getPointerToFunction - This method is used to get the address of the
240 /// specified function, compiling it if neccesary.
242 void *JIT::getPointerToFunction(Function *F) {
243 MutexGuard locked(lock);
245 if (void *Addr = getPointerToGlobalIfAvailable(F))
246 return Addr; // Check if function already code gen'd
248 // Make sure we read in the function if it exists in this Module
249 if (F->hasNotBeenReadFromBytecode())
251 MP->materializeFunction(F);
252 } catch ( std::string& errmsg ) {
253 std::cerr << "Error reading function '" << F->getName()
254 << "' from bytecode file: " << errmsg << "\n";
257 std::cerr << "Error reading function '" << F->getName()
258 << "from bytecode file!\n";
262 if (F->isExternal()) {
263 void *Addr = getPointerToNamedFunction(F->getName());
264 addGlobalMapping(F, Addr);
270 void *Addr = getPointerToGlobalIfAvailable(F);
271 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
275 /// getOrEmitGlobalVariable - Return the address of the specified global
276 /// variable, possibly emitting it to memory if needed. This is used by the
278 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
279 MutexGuard locked(lock);
281 void *Ptr = getPointerToGlobalIfAvailable(GV);
284 // If the global is external, just remember the address.
285 if (GV->isExternal()) {
286 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
288 std::cerr << "Could not resolve external global address: "
289 << GV->getName() << "\n";
293 // If the global hasn't been emitted to memory yet, allocate space. We will
294 // actually initialize the global after current function has finished
296 uint64_t S = getTargetData().getTypeSize(GV->getType()->getElementType());
297 Ptr = new char[(size_t)S];
298 state.getPendingGlobals(locked).push_back(GV);
300 addGlobalMapping(GV, Ptr);
305 /// recompileAndRelinkFunction - This method is used to force a function
306 /// which has already been compiled, to be compiled again, possibly
307 /// after it has been modified. Then the entry to the old copy is overwritten
308 /// with a branch to the new copy. If there was no old copy, this acts
309 /// just like JIT::getPointerToFunction().
311 void *JIT::recompileAndRelinkFunction(Function *F) {
312 void *OldAddr = getPointerToGlobalIfAvailable(F);
314 // If it's not already compiled there is no reason to patch it up.
315 if (OldAddr == 0) { return getPointerToFunction(F); }
317 // Delete the old function mapping.
318 addGlobalMapping(F, 0);
320 // Recodegen the function
323 // Update state, forward the old function to the new function.
324 void *Addr = getPointerToGlobalIfAvailable(F);
325 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
326 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
330 /// freeMachineCodeForFunction - release machine code memory for given Function
332 void JIT::freeMachineCodeForFunction(Function *F) {