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/ADT/SmallPtrSet.h"
17 #include "llvm/CodeGen/JITCodeEmitter.h"
18 #include "llvm/CodeGen/MachineCodeInfo.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/ExecutionEngine/GenericValue.h"
21 #include "llvm/ExecutionEngine/JITEventListener.h"
22 #include "llvm/ExecutionEngine/JITMemoryManager.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/GlobalVariable.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/Support/Dwarf.h"
31 #include "llvm/Support/DynamicLibrary.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MutexGuard.h"
35 #include "llvm/Target/TargetJITInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetSubtargetInfo.h"
42 // Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
43 // of atexit). It passes the address of linker generated symbol __dso_handle
45 // This configuration change happened at version 5330.
46 # include <AvailabilityMacros.h>
47 # if defined(MAC_OS_X_VERSION_10_4) && \
48 ((MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
49 (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
50 __APPLE_CC__ >= 5330))
51 # ifndef HAVE___DSO_HANDLE
52 # define HAVE___DSO_HANDLE 1
58 extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
63 static struct RegisterJIT {
64 RegisterJIT() { JIT::Register(); }
69 extern "C" void LLVMLinkInJIT() {
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
75 ExecutionEngine *JIT::createJIT(Module *M,
76 std::string *ErrorStr,
77 JITMemoryManager *JMM,
80 // Try to register the program as a source of symbols to resolve against.
82 // FIXME: Don't do this here.
83 sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
85 // If the target supports JIT code generation, create the JIT.
86 if (TargetJITInfo *TJ = TM->getSubtargetImpl()->getJITInfo()) {
87 return new JIT(M, *TM, *TJ, JMM, GVsWithCode);
90 *ErrorStr = "target does not support JIT code generation";
96 /// This class supports the global getPointerToNamedFunction(), which allows
97 /// bugpoint or gdb users to search for a function by name without any context.
99 SmallPtrSet<JIT*, 1> JITs; // Optimize for process containing just 1 JIT.
100 mutable sys::Mutex Lock;
103 MutexGuard guard(Lock);
106 void Remove(JIT *jit) {
107 MutexGuard guard(Lock);
110 void *getPointerToNamedFunction(const char *Name) const {
111 MutexGuard guard(Lock);
112 assert(JITs.size() != 0 && "No Jit registered");
113 //search function in every instance of JIT
114 for (SmallPtrSet<JIT*, 1>::const_iterator Jit = JITs.begin(),
117 if (Function *F = (*Jit)->FindFunctionNamed(Name))
118 return (*Jit)->getPointerToFunction(F);
120 // The function is not available : fallback on the first created (will
121 // search in symbol of the current program/library)
122 return (*JITs.begin())->getPointerToNamedFunction(Name);
125 ManagedStatic<JitPool> AllJits;
128 // getPointerToNamedFunction - This function is used as a global wrapper to
129 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
130 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
131 // need to resolve function(s) that are being mis-codegenerated, so we need to
132 // resolve their addresses at runtime, and this is the way to do it.
133 void *getPointerToNamedFunction(const char *Name) {
134 return AllJits->getPointerToNamedFunction(Name);
138 JIT::JIT(Module *M, TargetMachine &tm, TargetJITInfo &tji,
139 JITMemoryManager *jmm, bool GVsWithCode)
140 : ExecutionEngine(M), TM(tm), TJI(tji),
141 JMM(jmm ? jmm : JITMemoryManager::CreateDefaultMemManager()),
142 AllocateGVsWithCode(GVsWithCode), isAlreadyCodeGenerating(false) {
143 setDataLayout(TM.getSubtargetImpl()->getDataLayout());
145 jitstate = new JITState(M);
148 JCE = createEmitter(*this, JMM, TM);
150 // Register in global list of all JITs.
154 MutexGuard locked(lock);
155 FunctionPassManager &PM = jitstate->getPM();
156 M->setDataLayout(TM.getSubtargetImpl()->getDataLayout());
157 PM.add(new DataLayoutPass(M));
159 // Turn the machine code intermediate representation into bytes in memory that
161 if (TM.addPassesToEmitMachineCode(PM, *JCE, !getVerifyModules())) {
162 report_fatal_error("Target does not support machine code emission!");
165 // Initialize passes.
166 PM.doInitialization();
171 AllJits->Remove(this);
174 // JMM is a ownership of JCE, so we no need delete JMM here.
178 /// addModule - Add a new Module to the JIT. If we previously removed the last
179 /// Module, we need re-initialize jitstate with a valid Module.
180 void JIT::addModule(Module *M) {
181 MutexGuard locked(lock);
183 if (Modules.empty()) {
184 assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
186 jitstate = new JITState(M);
188 FunctionPassManager &PM = jitstate->getPM();
189 M->setDataLayout(TM.getSubtargetImpl()->getDataLayout());
190 PM.add(new DataLayoutPass(M));
192 // Turn the machine code intermediate representation into bytes in memory
193 // that may be executed.
194 if (TM.addPassesToEmitMachineCode(PM, *JCE, !getVerifyModules())) {
195 report_fatal_error("Target does not support machine code emission!");
198 // Initialize passes.
199 PM.doInitialization();
202 ExecutionEngine::addModule(M);
205 /// removeModule - If we are removing the last Module, invalidate the jitstate
206 /// since the PassManager it contains references a released Module.
207 bool JIT::removeModule(Module *M) {
208 bool result = ExecutionEngine::removeModule(M);
210 MutexGuard locked(lock);
212 if (jitstate && jitstate->getModule() == M) {
217 if (!jitstate && !Modules.empty()) {
218 jitstate = new JITState(Modules[0]);
220 FunctionPassManager &PM = jitstate->getPM();
221 M->setDataLayout(TM.getSubtargetImpl()->getDataLayout());
222 PM.add(new DataLayoutPass(M));
224 // Turn the machine code intermediate representation into bytes in memory
225 // that may be executed.
226 if (TM.addPassesToEmitMachineCode(PM, *JCE, !getVerifyModules())) {
227 report_fatal_error("Target does not support machine code emission!");
230 // Initialize passes.
231 PM.doInitialization();
236 /// run - Start execution with the specified function and arguments.
238 GenericValue JIT::runFunction(Function *F,
239 const std::vector<GenericValue> &ArgValues) {
240 assert(F && "Function *F was null at entry to run()");
242 void *FPtr = getPointerToFunction(F);
243 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
244 FunctionType *FTy = F->getFunctionType();
245 Type *RetTy = FTy->getReturnType();
247 assert((FTy->getNumParams() == ArgValues.size() ||
248 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
249 "Wrong number of arguments passed into function!");
250 assert(FTy->getNumParams() == ArgValues.size() &&
251 "This doesn't support passing arguments through varargs (yet)!");
253 // Handle some common cases first. These cases correspond to common `main'
255 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
256 switch (ArgValues.size()) {
258 if (FTy->getParamType(0)->isIntegerTy(32) &&
259 FTy->getParamType(1)->isPointerTy() &&
260 FTy->getParamType(2)->isPointerTy()) {
261 int (*PF)(int, char **, const char **) =
262 (int(*)(int, char **, const char **))(intptr_t)FPtr;
264 // Call the function.
266 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
267 (char **)GVTOP(ArgValues[1]),
268 (const char **)GVTOP(ArgValues[2])));
273 if (FTy->getParamType(0)->isIntegerTy(32) &&
274 FTy->getParamType(1)->isPointerTy()) {
275 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
277 // Call the function.
279 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
280 (char **)GVTOP(ArgValues[1])));
285 if (FTy->getParamType(0)->isIntegerTy(32)) {
287 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
288 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
291 if (FTy->getParamType(0)->isPointerTy()) {
293 int (*PF)(char *) = (int(*)(char *))(intptr_t)FPtr;
294 rv.IntVal = APInt(32, PF((char*)GVTOP(ArgValues[0])));
301 // Handle cases where no arguments are passed first.
302 if (ArgValues.empty()) {
304 switch (RetTy->getTypeID()) {
305 default: llvm_unreachable("Unknown return type for function call!");
306 case Type::IntegerTyID: {
307 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
309 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
310 else if (BitWidth <= 8)
311 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
312 else if (BitWidth <= 16)
313 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
314 else if (BitWidth <= 32)
315 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
316 else if (BitWidth <= 64)
317 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
319 llvm_unreachable("Integer types > 64 bits not supported");
323 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
325 case Type::FloatTyID:
326 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
328 case Type::DoubleTyID:
329 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
331 case Type::X86_FP80TyID:
332 case Type::FP128TyID:
333 case Type::PPC_FP128TyID:
334 llvm_unreachable("long double not supported yet");
335 case Type::PointerTyID:
336 return PTOGV(((void*(*)())(intptr_t)FPtr)());
340 // Okay, this is not one of our quick and easy cases. Because we don't have a
341 // full FFI, we have to codegen a nullary stub function that just calls the
342 // function we are interested in, passing in constants for all of the
343 // arguments. Make this function and return.
345 // First, create the function.
346 FunctionType *STy=FunctionType::get(RetTy, false);
347 Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
350 // Insert a basic block.
351 BasicBlock *StubBB = BasicBlock::Create(F->getContext(), "", Stub);
353 // Convert all of the GenericValue arguments over to constants. Note that we
354 // currently don't support varargs.
355 SmallVector<Value*, 8> Args;
356 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
357 Constant *C = nullptr;
358 Type *ArgTy = FTy->getParamType(i);
359 const GenericValue &AV = ArgValues[i];
360 switch (ArgTy->getTypeID()) {
361 default: llvm_unreachable("Unknown argument type for function call!");
362 case Type::IntegerTyID:
363 C = ConstantInt::get(F->getContext(), AV.IntVal);
365 case Type::FloatTyID:
366 C = ConstantFP::get(F->getContext(), APFloat(AV.FloatVal));
368 case Type::DoubleTyID:
369 C = ConstantFP::get(F->getContext(), APFloat(AV.DoubleVal));
371 case Type::PPC_FP128TyID:
372 case Type::X86_FP80TyID:
373 case Type::FP128TyID:
374 C = ConstantFP::get(F->getContext(), APFloat(ArgTy->getFltSemantics(),
377 case Type::PointerTyID:
378 void *ArgPtr = GVTOP(AV);
379 if (sizeof(void*) == 4)
380 C = ConstantInt::get(Type::getInt32Ty(F->getContext()),
381 (int)(intptr_t)ArgPtr);
383 C = ConstantInt::get(Type::getInt64Ty(F->getContext()),
385 // Cast the integer to pointer
386 C = ConstantExpr::getIntToPtr(C, ArgTy);
392 CallInst *TheCall = CallInst::Create(F, Args, "", StubBB);
393 TheCall->setCallingConv(F->getCallingConv());
394 TheCall->setTailCall();
395 if (!TheCall->getType()->isVoidTy())
396 // Return result of the call.
397 ReturnInst::Create(F->getContext(), TheCall, StubBB);
399 ReturnInst::Create(F->getContext(), StubBB); // Just return void.
401 // Finally, call our nullary stub function.
402 GenericValue Result = runFunction(Stub, std::vector<GenericValue>());
403 // Erase it, since no other function can have a reference to it.
404 Stub->eraseFromParent();
405 // And return the result.
409 void JIT::RegisterJITEventListener(JITEventListener *L) {
412 MutexGuard locked(lock);
413 EventListeners.push_back(L);
415 void JIT::UnregisterJITEventListener(JITEventListener *L) {
418 MutexGuard locked(lock);
419 std::vector<JITEventListener*>::reverse_iterator I=
420 std::find(EventListeners.rbegin(), EventListeners.rend(), L);
421 if (I != EventListeners.rend()) {
422 std::swap(*I, EventListeners.back());
423 EventListeners.pop_back();
426 void JIT::NotifyFunctionEmitted(
428 void *Code, size_t Size,
429 const JITEvent_EmittedFunctionDetails &Details) {
430 MutexGuard locked(lock);
431 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
432 EventListeners[I]->NotifyFunctionEmitted(F, Code, Size, Details);
436 void JIT::NotifyFreeingMachineCode(void *OldPtr) {
437 MutexGuard locked(lock);
438 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
439 EventListeners[I]->NotifyFreeingMachineCode(OldPtr);
443 /// runJITOnFunction - Run the FunctionPassManager full of
444 /// just-in-time compilation passes on F, hopefully filling in
445 /// GlobalAddress[F] with the address of F's machine code.
447 void JIT::runJITOnFunction(Function *F, MachineCodeInfo *MCI) {
448 MutexGuard locked(lock);
450 class MCIListener : public JITEventListener {
451 MachineCodeInfo *const MCI;
453 MCIListener(MachineCodeInfo *mci) : MCI(mci) {}
454 void NotifyFunctionEmitted(const Function &, void *Code, size_t Size,
455 const EmittedFunctionDetails &) override {
456 MCI->setAddress(Code);
460 MCIListener MCIL(MCI);
462 RegisterJITEventListener(&MCIL);
464 runJITOnFunctionUnlocked(F);
467 UnregisterJITEventListener(&MCIL);
470 void JIT::runJITOnFunctionUnlocked(Function *F) {
471 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
473 jitTheFunctionUnlocked(F);
475 // If the function referred to another function that had not yet been
476 // read from bitcode, and we are jitting non-lazily, emit it now.
477 while (!jitstate->getPendingFunctions().empty()) {
478 Function *PF = jitstate->getPendingFunctions().back();
479 jitstate->getPendingFunctions().pop_back();
481 assert(!PF->hasAvailableExternallyLinkage() &&
482 "Externally-defined function should not be in pending list.");
484 jitTheFunctionUnlocked(PF);
486 // Now that the function has been jitted, ask the JITEmitter to rewrite
487 // the stub with real address of the function.
488 updateFunctionStubUnlocked(PF);
492 void JIT::jitTheFunctionUnlocked(Function *F) {
493 isAlreadyCodeGenerating = true;
494 jitstate->getPM().run(*F);
495 isAlreadyCodeGenerating = false;
497 // clear basic block addresses after this function is done
498 getBasicBlockAddressMap().clear();
501 /// getPointerToFunction - This method is used to get the address of the
502 /// specified function, compiling it if necessary.
504 void *JIT::getPointerToFunction(Function *F) {
506 if (void *Addr = getPointerToGlobalIfAvailable(F))
507 return Addr; // Check if function already code gen'd
509 MutexGuard locked(lock);
511 // Now that this thread owns the lock, make sure we read in the function if it
512 // exists in this Module.
513 std::string ErrorMsg;
514 if (F->Materialize(&ErrorMsg)) {
515 report_fatal_error("Error reading function '" + F->getName()+
516 "' from bitcode file: " + ErrorMsg);
519 // ... and check if another thread has already code gen'd the function.
520 if (void *Addr = getPointerToGlobalIfAvailable(F))
523 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
524 bool AbortOnFailure = !F->hasExternalWeakLinkage();
525 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
526 addGlobalMapping(F, Addr);
530 runJITOnFunctionUnlocked(F);
532 void *Addr = getPointerToGlobalIfAvailable(F);
533 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
537 void JIT::addPointerToBasicBlock(const BasicBlock *BB, void *Addr) {
538 MutexGuard locked(lock);
540 BasicBlockAddressMapTy::iterator I =
541 getBasicBlockAddressMap().find(BB);
542 if (I == getBasicBlockAddressMap().end()) {
543 getBasicBlockAddressMap()[BB] = Addr;
545 // ignore repeats: some BBs can be split into few MBBs?
549 void JIT::clearPointerToBasicBlock(const BasicBlock *BB) {
550 MutexGuard locked(lock);
551 getBasicBlockAddressMap().erase(BB);
554 void *JIT::getPointerToBasicBlock(BasicBlock *BB) {
555 // make sure it's function is compiled by JIT
556 (void)getPointerToFunction(BB->getParent());
558 // resolve basic block address
559 MutexGuard locked(lock);
561 BasicBlockAddressMapTy::iterator I =
562 getBasicBlockAddressMap().find(BB);
563 if (I != getBasicBlockAddressMap().end()) {
566 llvm_unreachable("JIT does not have BB address for address-of-label, was"
567 " it eliminated by optimizer?");
571 void *JIT::getPointerToNamedFunction(const std::string &Name,
572 bool AbortOnFailure){
573 if (!isSymbolSearchingDisabled()) {
574 void *ptr = JMM->getPointerToNamedFunction(Name, false);
579 /// If a LazyFunctionCreator is installed, use it to get/create the function.
580 if (LazyFunctionCreator)
581 if (void *RP = LazyFunctionCreator(Name))
584 if (AbortOnFailure) {
585 report_fatal_error("Program used external function '"+Name+
586 "' which could not be resolved!");
592 /// getOrEmitGlobalVariable - Return the address of the specified global
593 /// variable, possibly emitting it to memory if needed. This is used by the
595 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
596 MutexGuard locked(lock);
598 void *Ptr = getPointerToGlobalIfAvailable(GV);
601 // If the global is external, just remember the address.
602 if (GV->isDeclaration() || GV->hasAvailableExternallyLinkage()) {
603 #if HAVE___DSO_HANDLE
604 if (GV->getName() == "__dso_handle")
605 return (void*)&__dso_handle;
607 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName());
609 report_fatal_error("Could not resolve external global address: "
612 addGlobalMapping(GV, Ptr);
614 // If the global hasn't been emitted to memory yet, allocate space and
615 // emit it into memory.
616 Ptr = getMemoryForGV(GV);
617 addGlobalMapping(GV, Ptr);
618 EmitGlobalVariable(GV); // Initialize the variable.
623 /// recompileAndRelinkFunction - This method is used to force a function
624 /// which has already been compiled, to be compiled again, possibly
625 /// after it has been modified. Then the entry to the old copy is overwritten
626 /// with a branch to the new copy. If there was no old copy, this acts
627 /// just like JIT::getPointerToFunction().
629 void *JIT::recompileAndRelinkFunction(Function *F) {
630 void *OldAddr = getPointerToGlobalIfAvailable(F);
632 // If it's not already compiled there is no reason to patch it up.
633 if (!OldAddr) return getPointerToFunction(F);
635 // Delete the old function mapping.
636 addGlobalMapping(F, nullptr);
638 // Recodegen the function
641 // Update state, forward the old function to the new function.
642 void *Addr = getPointerToGlobalIfAvailable(F);
643 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
644 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
648 /// getMemoryForGV - This method abstracts memory allocation of global
649 /// variable so that the JIT can allocate thread local variables depending
652 char* JIT::getMemoryForGV(const GlobalVariable* GV) {
655 // GlobalVariable's which are not "constant" will cause trouble in a server
656 // situation. It's returned in the same block of memory as code which may
658 if (isGVCompilationDisabled() && !GV->isConstant()) {
659 report_fatal_error("Compilation of non-internal GlobalValue is disabled!");
662 // Some applications require globals and code to live together, so they may
663 // be allocated into the same buffer, but in general globals are allocated
664 // through the memory manager which puts them near the code but not in the
666 Type *GlobalType = GV->getType()->getElementType();
667 size_t S = getDataLayout()->getTypeAllocSize(GlobalType);
668 size_t A = getDataLayout()->getPreferredAlignment(GV);
669 if (GV->isThreadLocal()) {
670 MutexGuard locked(lock);
671 Ptr = TJI.allocateThreadLocalMemory(S);
672 } else if (TJI.allocateSeparateGVMemory()) {
674 Ptr = (char*)malloc(S);
676 // Allocate S+A bytes of memory, then use an aligned pointer within that
678 Ptr = (char*)malloc(S+A);
679 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
680 Ptr = Ptr + (MisAligned ? (A-MisAligned) : 0);
682 } else if (AllocateGVsWithCode) {
683 Ptr = (char*)JCE->allocateSpace(S, A);
685 Ptr = (char*)JCE->allocateGlobal(S, A);
690 void JIT::addPendingFunction(Function *F) {
691 MutexGuard locked(lock);
692 jitstate->getPendingFunctions().push_back(F);
696 JITEventListener::~JITEventListener() {}