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/ExecutionEngine/GenericValue.h"
24 #include "llvm/Support/MutexGuard.h"
25 #include "llvm/System/DynamicLibrary.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetJITInfo.h"
30 #include "llvm/Config/config.h"
35 // Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
36 // of atexit). It passes the address of linker generated symbol __dso_handle
38 // This configuration change happened at version 5330.
39 # include <AvailabilityMacros.h>
40 # if defined(MAC_OS_X_VERSION_10_4) && \
41 ((MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
42 (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
43 __APPLE_CC__ >= 5330))
44 # ifndef HAVE___DSO_HANDLE
45 # define HAVE___DSO_HANDLE 1
51 extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
56 static struct RegisterJIT {
57 RegisterJIT() { JIT::Register(); }
67 #if defined (__GNUC__)
68 extern "C" void __register_frame(void*);
71 /// createJIT - This is the factory method for creating a JIT for the current
72 /// machine, it does not fall back to the interpreter. This takes ownership
73 /// of the module provider.
74 ExecutionEngine *ExecutionEngine::createJIT(ModuleProvider *MP,
75 std::string *ErrorStr,
76 JITMemoryManager *JMM) {
77 ExecutionEngine *EE = JIT::createJIT(MP, ErrorStr, JMM);
80 // Register routine for informing unwinding runtime about new EH frames
82 EE->InstallExceptionTableRegister(__register_frame);
85 // Make sure we can resolve symbols in the program as well. The zero arg
86 // to the function tells DynamicLibrary to load the program, not a library.
87 sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr);
91 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji,
92 JITMemoryManager *JMM)
93 : ExecutionEngine(MP), TM(tm), TJI(tji) {
94 setTargetData(TM.getTargetData());
96 jitstate = new JITState(MP);
99 MCE = createEmitter(*this, JMM);
102 MutexGuard locked(lock);
103 FunctionPassManager &PM = jitstate->getPM(locked);
104 PM.add(new TargetData(*TM.getTargetData()));
106 // Turn the machine code intermediate representation into bytes in memory that
108 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
109 cerr << "Target does not support machine code emission!\n";
113 // Initialize passes.
114 PM.doInitialization();
123 /// addModuleProvider - Add a new ModuleProvider to the JIT. If we previously
124 /// removed the last ModuleProvider, we need re-initialize jitstate with a valid
126 void JIT::addModuleProvider(ModuleProvider *MP) {
127 MutexGuard locked(lock);
129 if (Modules.empty()) {
130 assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
132 jitstate = new JITState(MP);
134 FunctionPassManager &PM = jitstate->getPM(locked);
135 PM.add(new TargetData(*TM.getTargetData()));
137 // Turn the machine code intermediate representation into bytes in memory
138 // that may be executed.
139 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
140 cerr << "Target does not support machine code emission!\n";
144 // Initialize passes.
145 PM.doInitialization();
148 ExecutionEngine::addModuleProvider(MP);
151 /// removeModuleProvider - If we are removing the last ModuleProvider,
152 /// invalidate the jitstate since the PassManager it contains references a
153 /// released ModuleProvider.
154 Module *JIT::removeModuleProvider(ModuleProvider *MP, std::string *E) {
155 Module *result = ExecutionEngine::removeModuleProvider(MP, E);
157 MutexGuard locked(lock);
158 if (Modules.empty()) {
166 /// run - Start execution with the specified function and arguments.
168 GenericValue JIT::runFunction(Function *F,
169 const std::vector<GenericValue> &ArgValues) {
170 assert(F && "Function *F was null at entry to run()");
172 void *FPtr = getPointerToFunction(F);
173 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
174 const FunctionType *FTy = F->getFunctionType();
175 const Type *RetTy = FTy->getReturnType();
177 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
178 "Too many arguments passed into function!");
179 assert(FTy->getNumParams() == ArgValues.size() &&
180 "This doesn't support passing arguments through varargs (yet)!");
182 // Handle some common cases first. These cases correspond to common `main'
184 if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
185 switch (ArgValues.size()) {
187 if (FTy->getParamType(0) == Type::Int32Ty &&
188 isa<PointerType>(FTy->getParamType(1)) &&
189 isa<PointerType>(FTy->getParamType(2))) {
190 int (*PF)(int, char **, const char **) =
191 (int(*)(int, char **, const char **))(intptr_t)FPtr;
193 // Call the function.
195 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
196 (char **)GVTOP(ArgValues[1]),
197 (const char **)GVTOP(ArgValues[2])));
202 if (FTy->getParamType(0) == Type::Int32Ty &&
203 isa<PointerType>(FTy->getParamType(1))) {
204 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
206 // Call the function.
208 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
209 (char **)GVTOP(ArgValues[1])));
214 if (FTy->getNumParams() == 1 &&
215 FTy->getParamType(0) == Type::Int32Ty) {
217 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
218 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
225 // Handle cases where no arguments are passed first.
226 if (ArgValues.empty()) {
228 switch (RetTy->getTypeID()) {
229 default: assert(0 && "Unknown return type for function call!");
230 case Type::IntegerTyID: {
231 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
233 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
234 else if (BitWidth <= 8)
235 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
236 else if (BitWidth <= 16)
237 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
238 else if (BitWidth <= 32)
239 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
240 else if (BitWidth <= 64)
241 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
243 assert(0 && "Integer types > 64 bits not supported");
247 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
249 case Type::FloatTyID:
250 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
252 case Type::DoubleTyID:
253 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
255 case Type::X86_FP80TyID:
256 case Type::FP128TyID:
257 case Type::PPC_FP128TyID:
258 assert(0 && "long double not supported yet");
260 case Type::PointerTyID:
261 return PTOGV(((void*(*)())(intptr_t)FPtr)());
265 // Okay, this is not one of our quick and easy cases. Because we don't have a
266 // full FFI, we have to codegen a nullary stub function that just calls the
267 // function we are interested in, passing in constants for all of the
268 // arguments. Make this function and return.
270 // First, create the function.
271 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
272 Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
275 // Insert a basic block.
276 BasicBlock *StubBB = BasicBlock::Create("", Stub);
278 // Convert all of the GenericValue arguments over to constants. Note that we
279 // currently don't support varargs.
280 SmallVector<Value*, 8> Args;
281 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
283 const Type *ArgTy = FTy->getParamType(i);
284 const GenericValue &AV = ArgValues[i];
285 switch (ArgTy->getTypeID()) {
286 default: assert(0 && "Unknown argument type for function call!");
287 case Type::IntegerTyID:
288 C = ConstantInt::get(AV.IntVal);
290 case Type::FloatTyID:
291 C = ConstantFP::get(APFloat(AV.FloatVal));
293 case Type::DoubleTyID:
294 C = ConstantFP::get(APFloat(AV.DoubleVal));
296 case Type::PPC_FP128TyID:
297 case Type::X86_FP80TyID:
298 case Type::FP128TyID:
299 C = ConstantFP::get(APFloat(AV.IntVal));
301 case Type::PointerTyID:
302 void *ArgPtr = GVTOP(AV);
303 if (sizeof(void*) == 4)
304 C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
306 C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
307 C = ConstantExpr::getIntToPtr(C, ArgTy); // Cast the integer to pointer
313 CallInst *TheCall = CallInst::Create(F, Args.begin(), Args.end(),
315 TheCall->setTailCall();
316 if (TheCall->getType() != Type::VoidTy)
317 ReturnInst::Create(TheCall, StubBB); // Return result of the call.
319 ReturnInst::Create(StubBB); // Just return void.
321 // Finally, return the value returned by our nullary stub function.
322 return runFunction(Stub, std::vector<GenericValue>());
325 /// runJITOnFunction - Run the FunctionPassManager full of
326 /// just-in-time compilation passes on F, hopefully filling in
327 /// GlobalAddress[F] with the address of F's machine code.
329 void JIT::runJITOnFunction(Function *F) {
330 static bool isAlreadyCodeGenerating = false;
332 MutexGuard locked(lock);
333 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
336 isAlreadyCodeGenerating = true;
337 jitstate->getPM(locked).run(*F);
338 isAlreadyCodeGenerating = false;
340 // If the function referred to a global variable that had not yet been
341 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
342 // all of these globals now.
343 while (!jitstate->getPendingGlobals(locked).empty()) {
344 const GlobalVariable *GV = jitstate->getPendingGlobals(locked).back();
345 jitstate->getPendingGlobals(locked).pop_back();
346 EmitGlobalVariable(GV);
350 /// getPointerToFunction - This method is used to get the address of the
351 /// specified function, compiling it if neccesary.
353 void *JIT::getPointerToFunction(Function *F) {
355 if (void *Addr = getPointerToGlobalIfAvailable(F))
356 return Addr; // Check if function already code gen'd
358 // Make sure we read in the function if it exists in this Module.
359 if (F->hasNotBeenReadFromBitcode()) {
360 // Determine the module provider this function is provided by.
361 Module *M = F->getParent();
362 ModuleProvider *MP = 0;
363 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
364 if (Modules[i]->getModule() == M) {
369 assert(MP && "Function isn't in a module we know about!");
371 std::string ErrorMsg;
372 if (MP->materializeFunction(F, &ErrorMsg)) {
373 cerr << "Error reading function '" << F->getName()
374 << "' from bitcode file: " << ErrorMsg << "\n";
379 if (void *Addr = getPointerToGlobalIfAvailable(F)) {
383 MutexGuard locked(lock);
385 if (F->isDeclaration()) {
386 void *Addr = getPointerToNamedFunction(F->getName());
387 addGlobalMapping(F, Addr);
393 void *Addr = getPointerToGlobalIfAvailable(F);
394 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
398 /// getOrEmitGlobalVariable - Return the address of the specified global
399 /// variable, possibly emitting it to memory if needed. This is used by the
401 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
402 MutexGuard locked(lock);
404 void *Ptr = getPointerToGlobalIfAvailable(GV);
407 // If the global is external, just remember the address.
408 if (GV->isDeclaration()) {
409 #if HAVE___DSO_HANDLE
410 if (GV->getName() == "__dso_handle")
411 return (void*)&__dso_handle;
413 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
415 cerr << "Could not resolve external global address: "
416 << GV->getName() << "\n";
420 // If the global hasn't been emitted to memory yet, allocate space. We will
421 // actually initialize the global after current function has finished
423 const Type *GlobalType = GV->getType()->getElementType();
424 size_t S = getTargetData()->getABITypeSize(GlobalType);
425 size_t A = getTargetData()->getPreferredAlignment(GV);
429 // Allocate S+A bytes of memory, then use an aligned pointer within that
432 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
433 Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
435 jitstate->getPendingGlobals(locked).push_back(GV);
437 addGlobalMapping(GV, Ptr);
442 /// recompileAndRelinkFunction - This method is used to force a function
443 /// which has already been compiled, to be compiled again, possibly
444 /// after it has been modified. Then the entry to the old copy is overwritten
445 /// with a branch to the new copy. If there was no old copy, this acts
446 /// just like JIT::getPointerToFunction().
448 void *JIT::recompileAndRelinkFunction(Function *F) {
449 void *OldAddr = getPointerToGlobalIfAvailable(F);
451 // If it's not already compiled there is no reason to patch it up.
452 if (OldAddr == 0) { return getPointerToFunction(F); }
454 // Delete the old function mapping.
455 addGlobalMapping(F, 0);
457 // Recodegen the function
460 // Update state, forward the old function to the new function.
461 void *Addr = getPointerToGlobalIfAvailable(F);
462 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
463 TJI.replaceMachineCodeForFunction(OldAddr, Addr);