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/Support/MutexGuard.h"
26 #include "llvm/System/DynamicLibrary.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetJITInfo.h"
34 #include <AvailabilityMacros.h>
35 #if (MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
36 (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
38 // __dso_handle is resolved by Mac OS X dynamic linker.
39 extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
43 static struct RegisterJIT {
44 RegisterJIT() { JIT::Register(); }
52 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
53 : ExecutionEngine(MP), TM(tm), TJI(tji), state(MP) {
54 setTargetData(TM.getTargetData());
57 MCE = createEmitter(*this);
60 MutexGuard locked(lock);
61 FunctionPassManager& PM = state.getPM(locked);
62 PM.add(new TargetData(*TM.getTargetData()));
64 // Compile LLVM Code down to machine code in the intermediate representation
65 TJI.addPassesToJITCompile(PM);
67 // Turn the machine code intermediate representation into bytes in memory that
69 if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
70 std::cerr << "Target '" << TM.getName()
71 << "' doesn't support machine code emission!\n";
81 /// run - Start execution with the specified function and arguments.
83 GenericValue JIT::runFunction(Function *F,
84 const std::vector<GenericValue> &ArgValues) {
85 assert(F && "Function *F was null at entry to run()");
87 void *FPtr = getPointerToFunction(F);
88 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
89 const FunctionType *FTy = F->getFunctionType();
90 const Type *RetTy = FTy->getReturnType();
92 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
93 "Too many arguments passed into function!");
94 assert(FTy->getNumParams() == ArgValues.size() &&
95 "This doesn't support passing arguments through varargs (yet)!");
97 // Handle some common cases first. These cases correspond to common `main'
99 if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) {
100 switch (ArgValues.size()) {
102 if ((FTy->getParamType(0) == Type::IntTy ||
103 FTy->getParamType(0) == Type::UIntTy) &&
104 isa<PointerType>(FTy->getParamType(1)) &&
105 isa<PointerType>(FTy->getParamType(2))) {
106 int (*PF)(int, char **, const char **) =
107 (int(*)(int, char **, const char **))(intptr_t)FPtr;
109 // Call the function.
111 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
112 (const char **)GVTOP(ArgValues[2]));
117 if ((FTy->getParamType(0) == Type::IntTy ||
118 FTy->getParamType(0) == Type::UIntTy) &&
119 isa<PointerType>(FTy->getParamType(1))) {
120 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
122 // Call the function.
124 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]));
129 if (FTy->getNumParams() == 1 &&
130 (FTy->getParamType(0) == Type::IntTy ||
131 FTy->getParamType(0) == Type::UIntTy)) {
133 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
134 rv.IntVal = PF(ArgValues[0].IntVal);
141 // Handle cases where no arguments are passed first.
142 if (ArgValues.empty()) {
144 switch (RetTy->getTypeID()) {
145 default: assert(0 && "Unknown return type for function call!");
147 rv.BoolVal = ((bool(*)())(intptr_t)FPtr)();
149 case Type::SByteTyID:
150 case Type::UByteTyID:
151 rv.SByteVal = ((char(*)())(intptr_t)FPtr)();
153 case Type::ShortTyID:
154 case Type::UShortTyID:
155 rv.ShortVal = ((short(*)())(intptr_t)FPtr)();
160 rv.IntVal = ((int(*)())(intptr_t)FPtr)();
163 case Type::ULongTyID:
164 rv.LongVal = ((int64_t(*)())(intptr_t)FPtr)();
166 case Type::FloatTyID:
167 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
169 case Type::DoubleTyID:
170 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
172 case Type::PointerTyID:
173 return PTOGV(((void*(*)())(intptr_t)FPtr)());
177 // Okay, this is not one of our quick and easy cases. Because we don't have a
178 // full FFI, we have to codegen a nullary stub function that just calls the
179 // function we are interested in, passing in constants for all of the
180 // arguments. Make this function and return.
182 // First, create the function.
183 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
184 Function *Stub = new Function(STy, Function::InternalLinkage, "",
187 // Insert a basic block.
188 BasicBlock *StubBB = new BasicBlock("", Stub);
190 // Convert all of the GenericValue arguments over to constants. Note that we
191 // currently don't support varargs.
192 std::vector<Value*> Args;
193 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
195 const Type *ArgTy = FTy->getParamType(i);
196 const GenericValue &AV = ArgValues[i];
197 switch (ArgTy->getTypeID()) {
198 default: assert(0 && "Unknown argument type for function call!");
199 case Type::BoolTyID: C = ConstantBool::get(AV.BoolVal); break;
200 case Type::SByteTyID: C = ConstantSInt::get(ArgTy, AV.SByteVal); break;
201 case Type::UByteTyID: C = ConstantUInt::get(ArgTy, AV.UByteVal); break;
202 case Type::ShortTyID: C = ConstantSInt::get(ArgTy, AV.ShortVal); break;
203 case Type::UShortTyID: C = ConstantUInt::get(ArgTy, AV.UShortVal); break;
204 case Type::IntTyID: C = ConstantSInt::get(ArgTy, AV.IntVal); break;
205 case Type::UIntTyID: C = ConstantUInt::get(ArgTy, AV.UIntVal); break;
206 case Type::LongTyID: C = ConstantSInt::get(ArgTy, AV.LongVal); break;
207 case Type::ULongTyID: C = ConstantUInt::get(ArgTy, AV.ULongVal); break;
208 case Type::FloatTyID: C = ConstantFP ::get(ArgTy, AV.FloatVal); break;
209 case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, AV.DoubleVal); break;
210 case Type::PointerTyID:
211 void *ArgPtr = GVTOP(AV);
212 if (sizeof(void*) == 4) {
213 C = ConstantSInt::get(Type::IntTy, (int)(intptr_t)ArgPtr);
215 C = ConstantSInt::get(Type::LongTy, (intptr_t)ArgPtr);
217 C = ConstantExpr::getCast(C, ArgTy); // Cast the integer to pointer
223 CallInst *TheCall = new CallInst(F, Args, "", StubBB);
224 TheCall->setTailCall();
225 if (TheCall->getType() != Type::VoidTy)
226 new ReturnInst(TheCall, StubBB); // Return result of the call.
228 new ReturnInst(StubBB); // Just return void.
230 // Finally, return the value returned by our nullary stub function.
231 return runFunction(Stub, std::vector<GenericValue>());
234 /// runJITOnFunction - Run the FunctionPassManager full of
235 /// just-in-time compilation passes on F, hopefully filling in
236 /// GlobalAddress[F] with the address of F's machine code.
238 void JIT::runJITOnFunction(Function *F) {
239 static bool isAlreadyCodeGenerating = false;
240 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
242 MutexGuard locked(lock);
245 isAlreadyCodeGenerating = true;
246 state.getPM(locked).run(*F);
247 isAlreadyCodeGenerating = false;
249 // If the function referred to a global variable that had not yet been
250 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
251 // all of these globals now.
252 while (!state.getPendingGlobals(locked).empty()) {
253 const GlobalVariable *GV = state.getPendingGlobals(locked).back();
254 state.getPendingGlobals(locked).pop_back();
255 EmitGlobalVariable(GV);
259 /// getPointerToFunction - This method is used to get the address of the
260 /// specified function, compiling it if neccesary.
262 void *JIT::getPointerToFunction(Function *F) {
263 MutexGuard locked(lock);
265 if (void *Addr = getPointerToGlobalIfAvailable(F))
266 return Addr; // Check if function already code gen'd
268 // Make sure we read in the function if it exists in this Module.
269 if (F->hasNotBeenReadFromBytecode()) {
270 // Determine the module provider this function is provided by.
271 Module *M = F->getParent();
272 ModuleProvider *MP = 0;
273 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
274 if (Modules[i]->getModule() == M) {
279 assert(MP && "Function isn't in a module we know about!");
281 std::string ErrorMsg;
282 if (MP->materializeFunction(F, &ErrorMsg)) {
283 std::cerr << "Error reading function '" << F->getName()
284 << "' from bytecode file: " << ErrorMsg << "\n";
289 if (F->isExternal()) {
290 void *Addr = getPointerToNamedFunction(F->getName());
291 addGlobalMapping(F, Addr);
297 void *Addr = getPointerToGlobalIfAvailable(F);
298 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
302 /// getOrEmitGlobalVariable - Return the address of the specified global
303 /// variable, possibly emitting it to memory if needed. This is used by the
305 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
306 MutexGuard locked(lock);
308 void *Ptr = getPointerToGlobalIfAvailable(GV);
311 // If the global is external, just remember the address.
312 if (GV->isExternal()) {
314 #if (MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
315 (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
316 __APPLE_CC__ >= 5330)
317 // Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
318 // of atexit). It passes the address of linker generated symbol __dso_handle
320 // This configuration change happened at version 5330.
321 if (GV->getName() == "__dso_handle")
322 return (void*)&__dso_handle;
325 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
327 std::cerr << "Could not resolve external global address: "
328 << GV->getName() << "\n";
332 // If the global hasn't been emitted to memory yet, allocate space. We will
333 // actually initialize the global after current function has finished
335 const Type *GlobalType = GV->getType()->getElementType();
336 size_t S = getTargetData()->getTypeSize(GlobalType);
337 size_t A = getTargetData()->getTypeAlignment(GlobalType);
341 // Allocate S+A bytes of memory, then use an aligned pointer within that
344 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
345 Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
347 state.getPendingGlobals(locked).push_back(GV);
349 addGlobalMapping(GV, Ptr);
354 /// recompileAndRelinkFunction - This method is used to force a function
355 /// which has already been compiled, to be compiled again, possibly
356 /// after it has been modified. Then the entry to the old copy is overwritten
357 /// with a branch to the new copy. If there was no old copy, this acts
358 /// just like JIT::getPointerToFunction().
360 void *JIT::recompileAndRelinkFunction(Function *F) {
361 void *OldAddr = getPointerToGlobalIfAvailable(F);
363 // If it's not already compiled there is no reason to patch it up.
364 if (OldAddr == 0) { return getPointerToFunction(F); }
366 // Delete the old function mapping.
367 addGlobalMapping(F, 0);
369 // Recodegen the function
372 // Update state, forward the old function to the new function.
373 void *Addr = getPointerToGlobalIfAvailable(F);
374 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
375 TJI.replaceMachineCodeForFunction(OldAddr, Addr);