1 //===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tool implements a just-in-time compiler for LLVM, allowing direct
11 // execution of LLVM bitcode 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"
31 #include "llvm/Config/config.h"
36 // Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
37 // of atexit). It passes the address of linker generated symbol __dso_handle
39 // This configuration change happened at version 5330.
40 # include <AvailabilityMacros.h>
41 # if defined(MAC_OS_X_VERSION_10_4) && \
42 ((MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
43 (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
44 __APPLE_CC__ >= 5330))
45 # ifndef HAVE___DSO_HANDLE
46 # define HAVE___DSO_HANDLE 1
52 extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
57 static struct RegisterJIT {
58 RegisterJIT() { JIT::Register(); }
68 #if defined (__GNUC__)
69 extern "C" void __register_frame(void*);
72 /// createJIT - This is the factory method for creating a JIT for the current
73 /// machine, it does not fall back to the interpreter. This takes ownership
74 /// of the module provider.
75 ExecutionEngine *ExecutionEngine::createJIT(ModuleProvider *MP,
76 std::string *ErrorStr,
77 JITMemoryManager *JMM) {
78 ExecutionEngine *EE = JIT::createJIT(MP, ErrorStr, JMM);
81 // Register routine for informing unwinding runtime about new EH frames
83 EE->InstallExceptionTableRegister(__register_frame);
86 // Make sure we can resolve symbols in the program as well. The zero arg
87 // to the function tells DynamicLibrary to load the program, not a library.
88 sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr);
92 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji,
93 JITMemoryManager *JMM)
94 : ExecutionEngine(MP), TM(tm), TJI(tji), jitstate(MP) {
95 setTargetData(TM.getTargetData());
98 MCE = createEmitter(*this, JMM);
101 MutexGuard locked(lock);
102 FunctionPassManager &PM = jitstate.getPM(locked);
103 PM.add(new TargetData(*TM.getTargetData()));
105 // Turn the machine code intermediate representation into bytes in memory that
107 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
108 cerr << "Target does not support machine code emission!\n";
112 // Initialize passes.
113 PM.doInitialization();
121 /// run - Start execution with the specified function and arguments.
123 GenericValue JIT::runFunction(Function *F,
124 const std::vector<GenericValue> &ArgValues) {
125 assert(F && "Function *F was null at entry to run()");
127 void *FPtr = getPointerToFunction(F);
128 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
129 const FunctionType *FTy = F->getFunctionType();
130 const Type *RetTy = FTy->getReturnType();
132 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
133 "Too many arguments passed into function!");
134 assert(FTy->getNumParams() == ArgValues.size() &&
135 "This doesn't support passing arguments through varargs (yet)!");
137 // Handle some common cases first. These cases correspond to common `main'
139 if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
140 switch (ArgValues.size()) {
142 if (FTy->getParamType(0) == Type::Int32Ty &&
143 isa<PointerType>(FTy->getParamType(1)) &&
144 isa<PointerType>(FTy->getParamType(2))) {
145 int (*PF)(int, char **, const char **) =
146 (int(*)(int, char **, const char **))(intptr_t)FPtr;
148 // Call the function.
150 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
151 (char **)GVTOP(ArgValues[1]),
152 (const char **)GVTOP(ArgValues[2])));
157 if (FTy->getParamType(0) == Type::Int32Ty &&
158 isa<PointerType>(FTy->getParamType(1))) {
159 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
161 // Call the function.
163 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
164 (char **)GVTOP(ArgValues[1])));
169 if (FTy->getNumParams() == 1 &&
170 FTy->getParamType(0) == Type::Int32Ty) {
172 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
173 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
180 // Handle cases where no arguments are passed first.
181 if (ArgValues.empty()) {
183 switch (RetTy->getTypeID()) {
184 default: assert(0 && "Unknown return type for function call!");
185 case Type::IntegerTyID: {
186 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
188 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
189 else if (BitWidth <= 8)
190 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
191 else if (BitWidth <= 16)
192 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
193 else if (BitWidth <= 32)
194 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
195 else if (BitWidth <= 64)
196 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
198 assert(0 && "Integer types > 64 bits not supported");
202 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
204 case Type::FloatTyID:
205 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
207 case Type::DoubleTyID:
208 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
210 case Type::X86_FP80TyID:
211 case Type::FP128TyID:
212 case Type::PPC_FP128TyID:
213 assert(0 && "long double not supported yet");
215 case Type::PointerTyID:
216 return PTOGV(((void*(*)())(intptr_t)FPtr)());
220 // Okay, this is not one of our quick and easy cases. Because we don't have a
221 // full FFI, we have to codegen a nullary stub function that just calls the
222 // function we are interested in, passing in constants for all of the
223 // arguments. Make this function and return.
225 // First, create the function.
226 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
227 Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
230 // Insert a basic block.
231 BasicBlock *StubBB = BasicBlock::Create("", Stub);
233 // Convert all of the GenericValue arguments over to constants. Note that we
234 // currently don't support varargs.
235 SmallVector<Value*, 8> Args;
236 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
238 const Type *ArgTy = FTy->getParamType(i);
239 const GenericValue &AV = ArgValues[i];
240 switch (ArgTy->getTypeID()) {
241 default: assert(0 && "Unknown argument type for function call!");
242 case Type::IntegerTyID:
243 C = ConstantInt::get(AV.IntVal);
245 case Type::FloatTyID:
246 C = ConstantFP::get(APFloat(AV.FloatVal));
248 case Type::DoubleTyID:
249 C = ConstantFP::get(APFloat(AV.DoubleVal));
251 case Type::PPC_FP128TyID:
252 case Type::X86_FP80TyID:
253 case Type::FP128TyID:
254 C = ConstantFP::get(APFloat(AV.IntVal));
256 case Type::PointerTyID:
257 void *ArgPtr = GVTOP(AV);
258 if (sizeof(void*) == 4)
259 C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
261 C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
262 C = ConstantExpr::getIntToPtr(C, ArgTy); // Cast the integer to pointer
268 CallInst *TheCall = CallInst::Create(F, Args.begin(), Args.end(),
270 TheCall->setTailCall();
271 if (TheCall->getType() != Type::VoidTy)
272 ReturnInst::Create(TheCall, StubBB); // Return result of the call.
274 ReturnInst::Create(StubBB); // Just return void.
276 // Finally, return the value returned by our nullary stub function.
277 return runFunction(Stub, std::vector<GenericValue>());
280 /// runJITOnFunction - Run the FunctionPassManager full of
281 /// just-in-time compilation passes on F, hopefully filling in
282 /// GlobalAddress[F] with the address of F's machine code.
284 void JIT::runJITOnFunction(Function *F) {
285 static bool isAlreadyCodeGenerating = false;
287 MutexGuard locked(lock);
288 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
291 isAlreadyCodeGenerating = true;
292 jitstate.getPM(locked).run(*F);
293 isAlreadyCodeGenerating = false;
295 // If the function referred to a global variable that had not yet been
296 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
297 // all of these globals now.
298 while (!jitstate.getPendingGlobals(locked).empty()) {
299 const GlobalVariable *GV = jitstate.getPendingGlobals(locked).back();
300 jitstate.getPendingGlobals(locked).pop_back();
301 EmitGlobalVariable(GV);
305 /// getPointerToFunction - This method is used to get the address of the
306 /// specified function, compiling it if neccesary.
308 void *JIT::getPointerToFunction(Function *F) {
310 if (void *Addr = getPointerToGlobalIfAvailable(F))
311 return Addr; // Check if function already code gen'd
313 // Make sure we read in the function if it exists in this Module.
314 if (F->hasNotBeenReadFromBitcode()) {
315 // Determine the module provider this function is provided by.
316 Module *M = F->getParent();
317 ModuleProvider *MP = 0;
318 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
319 if (Modules[i]->getModule() == M) {
324 assert(MP && "Function isn't in a module we know about!");
326 std::string ErrorMsg;
327 if (MP->materializeFunction(F, &ErrorMsg)) {
328 cerr << "Error reading function '" << F->getName()
329 << "' from bitcode file: " << ErrorMsg << "\n";
334 if (void *Addr = getPointerToGlobalIfAvailable(F)) {
338 MutexGuard locked(lock);
340 if (F->isDeclaration()) {
341 void *Addr = getPointerToNamedFunction(F->getName());
342 addGlobalMapping(F, Addr);
348 void *Addr = getPointerToGlobalIfAvailable(F);
349 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
353 /// getOrEmitGlobalVariable - Return the address of the specified global
354 /// variable, possibly emitting it to memory if needed. This is used by the
356 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
357 MutexGuard locked(lock);
359 void *Ptr = getPointerToGlobalIfAvailable(GV);
362 // If the global is external, just remember the address.
363 if (GV->isDeclaration()) {
364 #if HAVE___DSO_HANDLE
365 if (GV->getName() == "__dso_handle")
366 return (void*)&__dso_handle;
368 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
370 cerr << "Could not resolve external global address: "
371 << GV->getName() << "\n";
375 // If the global hasn't been emitted to memory yet, allocate space. We will
376 // actually initialize the global after current function has finished
378 const Type *GlobalType = GV->getType()->getElementType();
379 size_t S = getTargetData()->getABITypeSize(GlobalType);
380 size_t A = getTargetData()->getPreferredAlignment(GV);
384 // Allocate S+A bytes of memory, then use an aligned pointer within that
387 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
388 Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
390 jitstate.getPendingGlobals(locked).push_back(GV);
392 addGlobalMapping(GV, Ptr);
397 /// recompileAndRelinkFunction - This method is used to force a function
398 /// which has already been compiled, to be compiled again, possibly
399 /// after it has been modified. Then the entry to the old copy is overwritten
400 /// with a branch to the new copy. If there was no old copy, this acts
401 /// just like JIT::getPointerToFunction().
403 void *JIT::recompileAndRelinkFunction(Function *F) {
404 void *OldAddr = getPointerToGlobalIfAvailable(F);
406 // If it's not already compiled there is no reason to patch it up.
407 if (OldAddr == 0) { return getPointerToFunction(F); }
409 // Delete the old function mapping.
410 addGlobalMapping(F, 0);
412 // Recodegen the function
415 // Update state, forward the old function to the new function.
416 void *Addr = getPointerToGlobalIfAvailable(F);
417 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
418 TJI.replaceMachineCodeForFunction(OldAddr, Addr);