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/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetJITInfo.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/MutexGuard.h"
29 #include "llvm/System/DynamicLibrary.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(); }
68 #if defined(__GNUC__) && !defined(__ARM__EABI__)
70 // libgcc defines the __register_frame function to dynamically register new
71 // dwarf frames for exception handling. This functionality is not portable
72 // across compilers and is only provided by GCC. We use the __register_frame
73 // function here so that code generated by the JIT cooperates with the unwinding
74 // runtime of libgcc. When JITting with exception handling enable, LLVM
75 // generates dwarf frames and registers it to libgcc with __register_frame.
77 // The __register_frame function works with Linux.
79 // Unfortunately, this functionality seems to be in libgcc after the unwinding
80 // library of libgcc for darwin was written. The code for darwin overwrites the
81 // value updated by __register_frame with a value fetched with "keymgr".
82 // "keymgr" is an obsolete functionality, which should be rewritten some day.
83 // In the meantime, since "keymgr" is on all libgccs shipped with apple-gcc, we
84 // need a workaround in LLVM which uses the "keymgr" to dynamically modify the
85 // values of an opaque key, used by libgcc to find dwarf tables.
87 extern "C" void __register_frame(void*);
89 #if defined(__APPLE__)
93 // LibgccObject - This is the structure defined in libgcc. There is no #include
94 // provided for this structure, so we also define it here. libgcc calls it
95 // "struct object". The structure is undocumented in libgcc.
101 /// frame - Pointer to the exception table.
104 /// encoding - The encoding of the object?
107 unsigned long sorted : 1;
108 unsigned long from_array : 1;
109 unsigned long mixed_encoding : 1;
110 unsigned long encoding : 8;
111 unsigned long count : 21;
116 /// fde_end - libgcc defines this field only if some macro is defined. We
117 /// include this field even if it may not there, to make libgcc happy.
120 /// next - At least we know it's a chained list!
121 struct LibgccObject *next;
124 // "kemgr" stuff. Apparently, all frame tables are stored there.
125 extern "C" void _keymgr_set_and_unlock_processwide_ptr(int, void *);
126 extern "C" void *_keymgr_get_and_lock_processwide_ptr(int);
127 #define KEYMGR_GCC3_DW2_OBJ_LIST 302 /* Dwarf2 object list */
129 /// LibgccObjectInfo - libgcc defines this struct as km_object_info. It
130 /// probably contains all dwarf tables that are loaded.
131 struct LibgccObjectInfo {
133 /// seenObjects - LibgccObjects already parsed by the unwinding runtime.
135 struct LibgccObject* seenObjects;
137 /// unseenObjects - LibgccObjects not parsed yet by the unwinding runtime.
139 struct LibgccObject* unseenObjects;
144 /// darwin_register_frame - Since __register_frame does not work with darwin's
145 /// libgcc,we provide our own function, which "tricks" libgcc by modifying the
146 /// "Dwarf2 object list" key.
147 void DarwinRegisterFrame(void* FrameBegin) {
149 LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
150 _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
151 assert(LOI && "This should be preallocated by the runtime");
153 // Allocate a new LibgccObject to represent this frame. Deallocation of this
154 // object may be impossible: since darwin code in libgcc was written after
155 // the ability to dynamically register frames, things may crash if we
157 struct LibgccObject* ob = (struct LibgccObject*)
158 malloc(sizeof(struct LibgccObject));
160 // Do like libgcc for the values of the field.
161 ob->unused1 = (void *)-1;
164 ob->frame = FrameBegin;
166 ob->encoding.b.encoding = llvm::dwarf::DW_EH_PE_omit;
168 // Put the info on both places, as libgcc uses the first or the the second
169 // field. Note that we rely on having two pointers here. If fde_end was a
170 // char, things would get complicated.
171 ob->fde_end = (char*)LOI->unseenObjects;
172 ob->next = LOI->unseenObjects;
174 // Update the key's unseenObjects list.
175 LOI->unseenObjects = ob;
177 // Finally update the "key". Apparently, libgcc requires it.
178 _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST,
187 /// createJIT - This is the factory method for creating a JIT for the current
188 /// machine, it does not fall back to the interpreter. This takes ownership
189 /// of the module provider.
190 ExecutionEngine *ExecutionEngine::createJIT(ModuleProvider *MP,
191 std::string *ErrorStr,
192 JITMemoryManager *JMM,
194 ExecutionEngine *EE = JIT::createJIT(MP, ErrorStr, JMM, Fast);
197 // Make sure we can resolve symbols in the program as well. The zero arg
198 // to the function tells DynamicLibrary to load the program, not a library.
199 sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr);
203 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji,
204 JITMemoryManager *JMM, bool Fast)
205 : ExecutionEngine(MP), TM(tm), TJI(tji) {
206 setTargetData(TM.getTargetData());
208 jitstate = new JITState(MP);
211 MCE = createEmitter(*this, JMM);
214 MutexGuard locked(lock);
215 FunctionPassManager &PM = jitstate->getPM(locked);
216 PM.add(new TargetData(*TM.getTargetData()));
218 // Turn the machine code intermediate representation into bytes in memory that
220 if (TM.addPassesToEmitMachineCode(PM, *MCE, Fast)) {
221 cerr << "Target does not support machine code emission!\n";
225 // Register routine for informing unwinding runtime about new EH frames
226 #if defined(__GNUC__) && !defined(__ARM_EABI__)
227 #if defined(__APPLE__)
228 struct LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
229 _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
231 // The key is created on demand, and libgcc creates it the first time an
232 // exception occurs. Since we need the key to register frames, we create
235 LOI = (LibgccObjectInfo*)malloc(sizeof(struct LibgccObjectInfo));
236 _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST,
239 InstallExceptionTableRegister(DarwinRegisterFrame);
241 InstallExceptionTableRegister(__register_frame);
245 // Initialize passes.
246 PM.doInitialization();
255 /// addModuleProvider - Add a new ModuleProvider to the JIT. If we previously
256 /// removed the last ModuleProvider, we need re-initialize jitstate with a valid
258 void JIT::addModuleProvider(ModuleProvider *MP) {
259 MutexGuard locked(lock);
261 if (Modules.empty()) {
262 assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
264 jitstate = new JITState(MP);
266 FunctionPassManager &PM = jitstate->getPM(locked);
267 PM.add(new TargetData(*TM.getTargetData()));
269 // Turn the machine code intermediate representation into bytes in memory
270 // that may be executed.
271 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
272 cerr << "Target does not support machine code emission!\n";
276 // Initialize passes.
277 PM.doInitialization();
280 ExecutionEngine::addModuleProvider(MP);
283 /// removeModuleProvider - If we are removing the last ModuleProvider,
284 /// invalidate the jitstate since the PassManager it contains references a
285 /// released ModuleProvider.
286 Module *JIT::removeModuleProvider(ModuleProvider *MP, std::string *E) {
287 Module *result = ExecutionEngine::removeModuleProvider(MP, E);
289 MutexGuard locked(lock);
291 if (jitstate->getMP() == MP) {
296 if (!jitstate && !Modules.empty()) {
297 jitstate = new JITState(Modules[0]);
299 FunctionPassManager &PM = jitstate->getPM(locked);
300 PM.add(new TargetData(*TM.getTargetData()));
302 // Turn the machine code intermediate representation into bytes in memory
303 // that may be executed.
304 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
305 cerr << "Target does not support machine code emission!\n";
309 // Initialize passes.
310 PM.doInitialization();
315 /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
316 /// and deletes the ModuleProvider and owned Module. Avoids materializing
317 /// the underlying module.
318 void JIT::deleteModuleProvider(ModuleProvider *MP, std::string *E) {
319 ExecutionEngine::deleteModuleProvider(MP, E);
321 MutexGuard locked(lock);
323 if (jitstate->getMP() == MP) {
328 if (!jitstate && !Modules.empty()) {
329 jitstate = new JITState(Modules[0]);
331 FunctionPassManager &PM = jitstate->getPM(locked);
332 PM.add(new TargetData(*TM.getTargetData()));
334 // Turn the machine code intermediate representation into bytes in memory
335 // that may be executed.
336 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
337 cerr << "Target does not support machine code emission!\n";
341 // Initialize passes.
342 PM.doInitialization();
346 /// run - Start execution with the specified function and arguments.
348 GenericValue JIT::runFunction(Function *F,
349 const std::vector<GenericValue> &ArgValues) {
350 assert(F && "Function *F was null at entry to run()");
352 void *FPtr = getPointerToFunction(F);
353 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
354 const FunctionType *FTy = F->getFunctionType();
355 const Type *RetTy = FTy->getReturnType();
357 assert((FTy->getNumParams() == ArgValues.size() ||
358 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
359 "Wrong number of arguments passed into function!");
360 assert(FTy->getNumParams() == ArgValues.size() &&
361 "This doesn't support passing arguments through varargs (yet)!");
363 // Handle some common cases first. These cases correspond to common `main'
365 if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
366 switch (ArgValues.size()) {
368 if (FTy->getParamType(0) == Type::Int32Ty &&
369 isa<PointerType>(FTy->getParamType(1)) &&
370 isa<PointerType>(FTy->getParamType(2))) {
371 int (*PF)(int, char **, const char **) =
372 (int(*)(int, char **, const char **))(intptr_t)FPtr;
374 // Call the function.
376 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
377 (char **)GVTOP(ArgValues[1]),
378 (const char **)GVTOP(ArgValues[2])));
383 if (FTy->getParamType(0) == Type::Int32Ty &&
384 isa<PointerType>(FTy->getParamType(1))) {
385 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
387 // Call the function.
389 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
390 (char **)GVTOP(ArgValues[1])));
395 if (FTy->getNumParams() == 1 &&
396 FTy->getParamType(0) == Type::Int32Ty) {
398 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
399 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
406 // Handle cases where no arguments are passed first.
407 if (ArgValues.empty()) {
409 switch (RetTy->getTypeID()) {
410 default: assert(0 && "Unknown return type for function call!");
411 case Type::IntegerTyID: {
412 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
414 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
415 else if (BitWidth <= 8)
416 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
417 else if (BitWidth <= 16)
418 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
419 else if (BitWidth <= 32)
420 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
421 else if (BitWidth <= 64)
422 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
424 assert(0 && "Integer types > 64 bits not supported");
428 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
430 case Type::FloatTyID:
431 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
433 case Type::DoubleTyID:
434 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
436 case Type::X86_FP80TyID:
437 case Type::FP128TyID:
438 case Type::PPC_FP128TyID:
439 assert(0 && "long double not supported yet");
441 case Type::PointerTyID:
442 return PTOGV(((void*(*)())(intptr_t)FPtr)());
446 // Okay, this is not one of our quick and easy cases. Because we don't have a
447 // full FFI, we have to codegen a nullary stub function that just calls the
448 // function we are interested in, passing in constants for all of the
449 // arguments. Make this function and return.
451 // First, create the function.
452 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
453 Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
456 // Insert a basic block.
457 BasicBlock *StubBB = BasicBlock::Create("", Stub);
459 // Convert all of the GenericValue arguments over to constants. Note that we
460 // currently don't support varargs.
461 SmallVector<Value*, 8> Args;
462 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
464 const Type *ArgTy = FTy->getParamType(i);
465 const GenericValue &AV = ArgValues[i];
466 switch (ArgTy->getTypeID()) {
467 default: assert(0 && "Unknown argument type for function call!");
468 case Type::IntegerTyID:
469 C = ConstantInt::get(AV.IntVal);
471 case Type::FloatTyID:
472 C = ConstantFP::get(APFloat(AV.FloatVal));
474 case Type::DoubleTyID:
475 C = ConstantFP::get(APFloat(AV.DoubleVal));
477 case Type::PPC_FP128TyID:
478 case Type::X86_FP80TyID:
479 case Type::FP128TyID:
480 C = ConstantFP::get(APFloat(AV.IntVal));
482 case Type::PointerTyID:
483 void *ArgPtr = GVTOP(AV);
484 if (sizeof(void*) == 4)
485 C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
487 C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
488 C = ConstantExpr::getIntToPtr(C, ArgTy); // Cast the integer to pointer
494 CallInst *TheCall = CallInst::Create(F, Args.begin(), Args.end(),
496 TheCall->setCallingConv(F->getCallingConv());
497 TheCall->setTailCall();
498 if (TheCall->getType() != Type::VoidTy)
499 ReturnInst::Create(TheCall, StubBB); // Return result of the call.
501 ReturnInst::Create(StubBB); // Just return void.
503 // Finally, return the value returned by our nullary stub function.
504 return runFunction(Stub, std::vector<GenericValue>());
507 /// runJITOnFunction - Run the FunctionPassManager full of
508 /// just-in-time compilation passes on F, hopefully filling in
509 /// GlobalAddress[F] with the address of F's machine code.
511 void JIT::runJITOnFunction(Function *F) {
512 MutexGuard locked(lock);
513 runJITOnFunctionUnlocked(F, locked);
516 void JIT::runJITOnFunctionUnlocked(Function *F, const MutexGuard &locked) {
517 static bool isAlreadyCodeGenerating = false;
518 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
521 isAlreadyCodeGenerating = true;
522 jitstate->getPM(locked).run(*F);
523 isAlreadyCodeGenerating = false;
525 // If the function referred to another function that had not yet been
526 // read from bitcode, but we are jitting non-lazily, emit it now.
527 while (!jitstate->getPendingFunctions(locked).empty()) {
528 Function *PF = jitstate->getPendingFunctions(locked).back();
529 jitstate->getPendingFunctions(locked).pop_back();
532 isAlreadyCodeGenerating = true;
533 jitstate->getPM(locked).run(*PF);
534 isAlreadyCodeGenerating = false;
536 // Now that the function has been jitted, ask the JITEmitter to rewrite
537 // the stub with real address of the function.
538 updateFunctionStub(PF);
541 // If the JIT is configured to emit info so that dlsym can be used to
542 // rewrite stubs to external globals, do so now.
543 if (areDlsymStubsEnabled() && isLazyCompilationDisabled())
544 updateDlsymStubTable();
547 /// getPointerToFunction - This method is used to get the address of the
548 /// specified function, compiling it if neccesary.
550 void *JIT::getPointerToFunction(Function *F) {
552 if (void *Addr = getPointerToGlobalIfAvailable(F))
553 return Addr; // Check if function already code gen'd
555 MutexGuard locked(lock);
557 // Make sure we read in the function if it exists in this Module.
558 if (F->hasNotBeenReadFromBitcode()) {
559 // Determine the module provider this function is provided by.
560 Module *M = F->getParent();
561 ModuleProvider *MP = 0;
562 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
563 if (Modules[i]->getModule() == M) {
568 assert(MP && "Function isn't in a module we know about!");
570 std::string ErrorMsg;
571 if (MP->materializeFunction(F, &ErrorMsg)) {
572 cerr << "Error reading function '" << F->getName()
573 << "' from bitcode file: " << ErrorMsg << "\n";
577 // Now retry to get the address.
578 if (void *Addr = getPointerToGlobalIfAvailable(F))
582 if (F->isDeclaration()) {
583 bool AbortOnFailure =
584 !areDlsymStubsEnabled() && !F->hasExternalWeakLinkage();
585 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
586 addGlobalMapping(F, Addr);
590 runJITOnFunctionUnlocked(F, locked);
592 void *Addr = getPointerToGlobalIfAvailable(F);
593 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
597 /// getOrEmitGlobalVariable - Return the address of the specified global
598 /// variable, possibly emitting it to memory if needed. This is used by the
600 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
601 MutexGuard locked(lock);
603 void *Ptr = getPointerToGlobalIfAvailable(GV);
606 // If the global is external, just remember the address.
607 if (GV->isDeclaration()) {
608 #if HAVE___DSO_HANDLE
609 if (GV->getName() == "__dso_handle")
610 return (void*)&__dso_handle;
612 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
613 if (Ptr == 0 && !areDlsymStubsEnabled()) {
614 cerr << "Could not resolve external global address: "
615 << GV->getName() << "\n";
618 addGlobalMapping(GV, Ptr);
620 // GlobalVariable's which are not "constant" will cause trouble in a server
621 // situation. It's returned in the same block of memory as code which may
623 if (isGVCompilationDisabled() && !GV->isConstant()) {
624 cerr << "Compilation of non-internal GlobalValue is disabled!\n";
627 // If the global hasn't been emitted to memory yet, allocate space and
628 // emit it into memory. It goes in the same array as the generated
629 // code, jump tables, etc.
630 const Type *GlobalType = GV->getType()->getElementType();
631 size_t S = getTargetData()->getTypePaddedSize(GlobalType);
632 size_t A = getTargetData()->getPreferredAlignment(GV);
633 if (GV->isThreadLocal()) {
634 MutexGuard locked(lock);
635 Ptr = TJI.allocateThreadLocalMemory(S);
636 } else if (TJI.allocateSeparateGVMemory()) {
640 // Allocate S+A bytes of memory, then use an aligned pointer within that
643 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
644 Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
647 Ptr = MCE->allocateSpace(S, A);
649 addGlobalMapping(GV, Ptr);
650 EmitGlobalVariable(GV);
655 /// recompileAndRelinkFunction - This method is used to force a function
656 /// which has already been compiled, to be compiled again, possibly
657 /// after it has been modified. Then the entry to the old copy is overwritten
658 /// with a branch to the new copy. If there was no old copy, this acts
659 /// just like JIT::getPointerToFunction().
661 void *JIT::recompileAndRelinkFunction(Function *F) {
662 void *OldAddr = getPointerToGlobalIfAvailable(F);
664 // If it's not already compiled there is no reason to patch it up.
665 if (OldAddr == 0) { return getPointerToFunction(F); }
667 // Delete the old function mapping.
668 addGlobalMapping(F, 0);
670 // Recodegen the function
673 // Update state, forward the old function to the new function.
674 void *Addr = getPointerToGlobalIfAvailable(F);
675 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
676 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
680 /// getMemoryForGV - This method abstracts memory allocation of global
681 /// variable so that the JIT can allocate thread local variables depending
684 char* JIT::getMemoryForGV(const GlobalVariable* GV) {
685 const Type *ElTy = GV->getType()->getElementType();
686 size_t GVSize = (size_t)getTargetData()->getTypePaddedSize(ElTy);
687 if (GV->isThreadLocal()) {
688 MutexGuard locked(lock);
689 return TJI.allocateThreadLocalMemory(GVSize);
691 return new char[GVSize];
695 void JIT::addPendingFunction(Function *F) {
696 MutexGuard locked(lock);
697 jitstate->getPendingFunctions(locked).push_back(F);