LLVM  mainline
MCJIT.cpp
Go to the documentation of this file.
00001 //===-- MCJIT.cpp - MC-based Just-in-Time Compiler ------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "MCJIT.h"
00011 #include "llvm/ADT/STLExtras.h"
00012 #include "llvm/ExecutionEngine/GenericValue.h"
00013 #include "llvm/ExecutionEngine/JITEventListener.h"
00014 #include "llvm/ExecutionEngine/MCJIT.h"
00015 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
00016 #include "llvm/IR/DataLayout.h"
00017 #include "llvm/IR/DerivedTypes.h"
00018 #include "llvm/IR/Function.h"
00019 #include "llvm/IR/LegacyPassManager.h"
00020 #include "llvm/IR/Mangler.h"
00021 #include "llvm/IR/Module.h"
00022 #include "llvm/MC/MCAsmInfo.h"
00023 #include "llvm/Object/Archive.h"
00024 #include "llvm/Object/ObjectFile.h"
00025 #include "llvm/Support/DynamicLibrary.h"
00026 #include "llvm/Support/ErrorHandling.h"
00027 #include "llvm/Support/MemoryBuffer.h"
00028 #include "llvm/Support/MutexGuard.h"
00029 
00030 using namespace llvm;
00031 
00032 void ObjectCache::anchor() {}
00033 
00034 namespace {
00035 
00036 static struct RegisterJIT {
00037   RegisterJIT() { MCJIT::Register(); }
00038 } JITRegistrator;
00039 
00040 }
00041 
00042 extern "C" void LLVMLinkInMCJIT() {
00043 }
00044 
00045 ExecutionEngine*
00046 MCJIT::createJIT(std::unique_ptr<Module> M,
00047                  std::string *ErrorStr,
00048                  std::shared_ptr<MCJITMemoryManager> MemMgr,
00049                  std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
00050                  std::unique_ptr<TargetMachine> TM) {
00051   // Try to register the program as a source of symbols to resolve against.
00052   //
00053   // FIXME: Don't do this here.
00054   sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
00055 
00056   if (!MemMgr || !Resolver) {
00057     auto RTDyldMM = std::make_shared<SectionMemoryManager>();
00058     if (!MemMgr)
00059       MemMgr = RTDyldMM;
00060     if (!Resolver)
00061       Resolver = RTDyldMM;
00062   }
00063 
00064   return new MCJIT(std::move(M), std::move(TM), std::move(MemMgr),
00065                    std::move(Resolver));
00066 }
00067 
00068 MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> tm,
00069              std::shared_ptr<MCJITMemoryManager> MemMgr,
00070              std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver)
00071     : ExecutionEngine(std::move(M)), TM(std::move(tm)), Ctx(nullptr),
00072       MemMgr(std::move(MemMgr)), Resolver(*this, std::move(Resolver)),
00073       Dyld(*this->MemMgr, this->Resolver), ObjCache(nullptr) {
00074   // FIXME: We are managing our modules, so we do not want the base class
00075   // ExecutionEngine to manage them as well. To avoid double destruction
00076   // of the first (and only) module added in ExecutionEngine constructor
00077   // we remove it from EE and will destruct it ourselves.
00078   //
00079   // It may make sense to move our module manager (based on SmallStPtr) back
00080   // into EE if the JIT and Interpreter can live with it.
00081   // If so, additional functions: addModule, removeModule, FindFunctionNamed,
00082   // runStaticConstructorsDestructors could be moved back to EE as well.
00083   //
00084   std::unique_ptr<Module> First = std::move(Modules[0]);
00085   Modules.clear();
00086 
00087   OwnedModules.addModule(std::move(First));
00088   setDataLayout(TM->getDataLayout());
00089   RegisterJITEventListener(JITEventListener::createGDBRegistrationListener());
00090 }
00091 
00092 MCJIT::~MCJIT() {
00093   MutexGuard locked(lock);
00094 
00095   Dyld.deregisterEHFrames();
00096 
00097   for (auto &Obj : LoadedObjects)
00098     if (Obj)
00099       NotifyFreeingObject(*Obj);
00100 
00101   Archives.clear();
00102 }
00103 
00104 void MCJIT::addModule(std::unique_ptr<Module> M) {
00105   MutexGuard locked(lock);
00106   OwnedModules.addModule(std::move(M));
00107 }
00108 
00109 bool MCJIT::removeModule(Module *M) {
00110   MutexGuard locked(lock);
00111   return OwnedModules.removeModule(M);
00112 }
00113 
00114 void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
00115   std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L = Dyld.loadObject(*Obj);
00116   if (Dyld.hasError())
00117     report_fatal_error(Dyld.getErrorString());
00118 
00119   NotifyObjectEmitted(*Obj, *L);
00120 
00121   LoadedObjects.push_back(std::move(Obj));
00122 }
00123 
00124 void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
00125   std::unique_ptr<object::ObjectFile> ObjFile;
00126   std::unique_ptr<MemoryBuffer> MemBuf;
00127   std::tie(ObjFile, MemBuf) = Obj.takeBinary();
00128   addObjectFile(std::move(ObjFile));
00129   Buffers.push_back(std::move(MemBuf));
00130 }
00131 
00132 void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
00133   Archives.push_back(std::move(A));
00134 }
00135 
00136 void MCJIT::setObjectCache(ObjectCache* NewCache) {
00137   MutexGuard locked(lock);
00138   ObjCache = NewCache;
00139 }
00140 
00141 std::unique_ptr<MemoryBuffer> MCJIT::emitObject(Module *M) {
00142   MutexGuard locked(lock);
00143 
00144   // This must be a module which has already been added but not loaded to this
00145   // MCJIT instance, since these conditions are tested by our caller,
00146   // generateCodeForModule.
00147 
00148   legacy::PassManager PM;
00149 
00150   // The RuntimeDyld will take ownership of this shortly
00151   SmallVector<char, 4096> ObjBufferSV;
00152   raw_svector_ostream ObjStream(ObjBufferSV);
00153 
00154   // Turn the machine code intermediate representation into bytes in memory
00155   // that may be executed.
00156   if (TM->addPassesToEmitMC(PM, Ctx, ObjStream, !getVerifyModules()))
00157     report_fatal_error("Target does not support MC emission!");
00158 
00159   // Initialize passes.
00160   PM.run(*M);
00161   // Flush the output buffer to get the generated code into memory
00162   ObjStream.flush();
00163 
00164   std::unique_ptr<MemoryBuffer> CompiledObjBuffer(
00165                                 new ObjectMemoryBuffer(std::move(ObjBufferSV)));
00166 
00167   // If we have an object cache, tell it about the new object.
00168   // Note that we're using the compiled image, not the loaded image (as below).
00169   if (ObjCache) {
00170     // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
00171     // to create a temporary object here and delete it after the call.
00172     MemoryBufferRef MB = CompiledObjBuffer->getMemBufferRef();
00173     ObjCache->notifyObjectCompiled(M, MB);
00174   }
00175 
00176   return CompiledObjBuffer;
00177 }
00178 
00179 void MCJIT::generateCodeForModule(Module *M) {
00180   // Get a thread lock to make sure we aren't trying to load multiple times
00181   MutexGuard locked(lock);
00182 
00183   // This must be a module which has already been added to this MCJIT instance.
00184   assert(OwnedModules.ownsModule(M) &&
00185          "MCJIT::generateCodeForModule: Unknown module.");
00186 
00187   // Re-compilation is not supported
00188   if (OwnedModules.hasModuleBeenLoaded(M))
00189     return;
00190 
00191   std::unique_ptr<MemoryBuffer> ObjectToLoad;
00192   // Try to load the pre-compiled object from cache if possible
00193   if (ObjCache)
00194     ObjectToLoad = ObjCache->getObject(M);
00195 
00196   M->setDataLayout(*TM->getDataLayout());
00197 
00198   // If the cache did not contain a suitable object, compile the object
00199   if (!ObjectToLoad) {
00200     ObjectToLoad = emitObject(M);
00201     assert(ObjectToLoad && "Compilation did not produce an object.");
00202   }
00203 
00204   // Load the object into the dynamic linker.
00205   // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
00206   ErrorOr<std::unique_ptr<object::ObjectFile>> LoadedObject =
00207     object::ObjectFile::createObjectFile(ObjectToLoad->getMemBufferRef());
00208   std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L =
00209     Dyld.loadObject(*LoadedObject.get());
00210 
00211   if (Dyld.hasError())
00212     report_fatal_error(Dyld.getErrorString());
00213 
00214   NotifyObjectEmitted(*LoadedObject.get(), *L);
00215 
00216   Buffers.push_back(std::move(ObjectToLoad));
00217   LoadedObjects.push_back(std::move(*LoadedObject));
00218 
00219   OwnedModules.markModuleAsLoaded(M);
00220 }
00221 
00222 void MCJIT::finalizeLoadedModules() {
00223   MutexGuard locked(lock);
00224 
00225   // Resolve any outstanding relocations.
00226   Dyld.resolveRelocations();
00227 
00228   OwnedModules.markAllLoadedModulesAsFinalized();
00229 
00230   // Register EH frame data for any module we own which has been loaded
00231   Dyld.registerEHFrames();
00232 
00233   // Set page permissions.
00234   MemMgr->finalizeMemory();
00235 }
00236 
00237 // FIXME: Rename this.
00238 void MCJIT::finalizeObject() {
00239   MutexGuard locked(lock);
00240 
00241   // Generate code for module is going to move objects out of the 'added' list,
00242   // so we need to copy that out before using it:
00243   SmallVector<Module*, 16> ModsToAdd;
00244   for (auto M : OwnedModules.added())
00245     ModsToAdd.push_back(M);
00246 
00247   for (auto M : ModsToAdd)
00248     generateCodeForModule(M);
00249 
00250   finalizeLoadedModules();
00251 }
00252 
00253 void MCJIT::finalizeModule(Module *M) {
00254   MutexGuard locked(lock);
00255 
00256   // This must be a module which has already been added to this MCJIT instance.
00257   assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
00258 
00259   // If the module hasn't been compiled, just do that.
00260   if (!OwnedModules.hasModuleBeenLoaded(M))
00261     generateCodeForModule(M);
00262 
00263   finalizeLoadedModules();
00264 }
00265 
00266 RuntimeDyld::SymbolInfo MCJIT::findExistingSymbol(const std::string &Name) {
00267   SmallString<128> FullName;
00268   Mangler::getNameWithPrefix(FullName, Name, *TM->getDataLayout());
00269   return Dyld.getSymbol(FullName);
00270 }
00271 
00272 Module *MCJIT::findModuleForSymbol(const std::string &Name,
00273                                    bool CheckFunctionsOnly) {
00274   MutexGuard locked(lock);
00275 
00276   // If it hasn't already been generated, see if it's in one of our modules.
00277   for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
00278                               E = OwnedModules.end_added();
00279        I != E; ++I) {
00280     Module *M = *I;
00281     Function *F = M->getFunction(Name);
00282     if (F && !F->isDeclaration())
00283       return M;
00284     if (!CheckFunctionsOnly) {
00285       GlobalVariable *G = M->getGlobalVariable(Name);
00286       if (G && !G->isDeclaration())
00287         return M;
00288       // FIXME: Do we need to worry about global aliases?
00289     }
00290   }
00291   // We didn't find the symbol in any of our modules.
00292   return nullptr;
00293 }
00294 
00295 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
00296                                  bool CheckFunctionsOnly) {
00297   return findSymbol(Name, CheckFunctionsOnly).getAddress();
00298 }
00299 
00300 RuntimeDyld::SymbolInfo MCJIT::findSymbol(const std::string &Name,
00301                                           bool CheckFunctionsOnly) {
00302   MutexGuard locked(lock);
00303 
00304   // First, check to see if we already have this symbol.
00305   if (auto Sym = findExistingSymbol(Name))
00306     return Sym;
00307 
00308   for (object::OwningBinary<object::Archive> &OB : Archives) {
00309     object::Archive *A = OB.getBinary();
00310     // Look for our symbols in each Archive
00311     object::Archive::child_iterator ChildIt = A->findSym(Name);
00312     if (ChildIt != A->child_end()) {
00313       // FIXME: Support nested archives?
00314       ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
00315           ChildIt->getAsBinary();
00316       if (ChildBinOrErr.getError())
00317         continue;
00318       std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
00319       if (ChildBin->isObject()) {
00320         std::unique_ptr<object::ObjectFile> OF(
00321             static_cast<object::ObjectFile *>(ChildBin.release()));
00322         // This causes the object file to be loaded.
00323         addObjectFile(std::move(OF));
00324         // The address should be here now.
00325         if (auto Sym = findExistingSymbol(Name))
00326           return Sym;
00327       }
00328     }
00329   }
00330 
00331   // If it hasn't already been generated, see if it's in one of our modules.
00332   Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
00333   if (M) {
00334     generateCodeForModule(M);
00335 
00336     // Check the RuntimeDyld table again, it should be there now.
00337     return findExistingSymbol(Name);
00338   }
00339 
00340   // If a LazyFunctionCreator is installed, use it to get/create the function.
00341   // FIXME: Should we instead have a LazySymbolCreator callback?
00342   if (LazyFunctionCreator) {
00343     auto Addr = static_cast<uint64_t>(
00344                   reinterpret_cast<uintptr_t>(LazyFunctionCreator(Name)));
00345     return RuntimeDyld::SymbolInfo(Addr, JITSymbolFlags::Exported);
00346   }
00347 
00348   return nullptr;
00349 }
00350 
00351 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
00352   MutexGuard locked(lock);
00353   uint64_t Result = getSymbolAddress(Name, false);
00354   if (Result != 0)
00355     finalizeLoadedModules();
00356   return Result;
00357 }
00358 
00359 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
00360   MutexGuard locked(lock);
00361   uint64_t Result = getSymbolAddress(Name, true);
00362   if (Result != 0)
00363     finalizeLoadedModules();
00364   return Result;
00365 }
00366 
00367 // Deprecated.  Use getFunctionAddress instead.
00368 void *MCJIT::getPointerToFunction(Function *F) {
00369   MutexGuard locked(lock);
00370 
00371   Mangler Mang;
00372   SmallString<128> Name;
00373   TM->getNameWithPrefix(Name, F, Mang);
00374 
00375   if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
00376     bool AbortOnFailure = !F->hasExternalWeakLinkage();
00377     void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
00378     updateGlobalMapping(F, Addr);
00379     return Addr;
00380   }
00381 
00382   Module *M = F->getParent();
00383   bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
00384 
00385   // Make sure the relevant module has been compiled and loaded.
00386   if (HasBeenAddedButNotLoaded)
00387     generateCodeForModule(M);
00388   else if (!OwnedModules.hasModuleBeenLoaded(M)) {
00389     // If this function doesn't belong to one of our modules, we're done.
00390     // FIXME: Asking for the pointer to a function that hasn't been registered,
00391     //        and isn't a declaration (which is handled above) should probably
00392     //        be an assertion.
00393     return nullptr;
00394   }
00395 
00396   // FIXME: Should the Dyld be retaining module information? Probably not.
00397   //
00398   // This is the accessor for the target address, so make sure to check the
00399   // load address of the symbol, not the local address.
00400   return (void*)Dyld.getSymbol(Name).getAddress();
00401 }
00402 
00403 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
00404     bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
00405   for (; I != E; ++I) {
00406     ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
00407   }
00408 }
00409 
00410 void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
00411   // Execute global ctors/dtors for each module in the program.
00412   runStaticConstructorsDestructorsInModulePtrSet(
00413       isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
00414   runStaticConstructorsDestructorsInModulePtrSet(
00415       isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
00416   runStaticConstructorsDestructorsInModulePtrSet(
00417       isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
00418 }
00419 
00420 Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
00421                                                  ModulePtrSet::iterator I,
00422                                                  ModulePtrSet::iterator E) {
00423   for (; I != E; ++I) {
00424     Function *F = (*I)->getFunction(FnName);
00425     if (F && !F->isDeclaration())
00426       return F;
00427   }
00428   return nullptr;
00429 }
00430 
00431 GlobalVariable *MCJIT::FindGlobalVariableNamedInModulePtrSet(const char *Name,
00432                                                              bool AllowInternal,
00433                                                              ModulePtrSet::iterator I,
00434                                                              ModulePtrSet::iterator E) {
00435   for (; I != E; ++I) {
00436     GlobalVariable *GV = (*I)->getGlobalVariable(Name, AllowInternal);
00437     if (GV && !GV->isDeclaration())
00438       return GV;
00439   }
00440   return nullptr;
00441 }
00442 
00443 
00444 Function *MCJIT::FindFunctionNamed(const char *FnName) {
00445   Function *F = FindFunctionNamedInModulePtrSet(
00446       FnName, OwnedModules.begin_added(), OwnedModules.end_added());
00447   if (!F)
00448     F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
00449                                         OwnedModules.end_loaded());
00450   if (!F)
00451     F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
00452                                         OwnedModules.end_finalized());
00453   return F;
00454 }
00455 
00456 GlobalVariable *MCJIT::FindGlobalVariableNamed(const char *Name, bool AllowInternal) {
00457   GlobalVariable *GV = FindGlobalVariableNamedInModulePtrSet(
00458       Name, AllowInternal, OwnedModules.begin_added(), OwnedModules.end_added());
00459   if (!GV)
00460     GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_loaded(),
00461                                         OwnedModules.end_loaded());
00462   if (!GV)
00463     GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_finalized(),
00464                                         OwnedModules.end_finalized());
00465   return GV;
00466 }
00467 
00468 GenericValue MCJIT::runFunction(Function *F, ArrayRef<GenericValue> ArgValues) {
00469   assert(F && "Function *F was null at entry to run()");
00470 
00471   void *FPtr = getPointerToFunction(F);
00472   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
00473   FunctionType *FTy = F->getFunctionType();
00474   Type *RetTy = FTy->getReturnType();
00475 
00476   assert((FTy->getNumParams() == ArgValues.size() ||
00477           (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
00478          "Wrong number of arguments passed into function!");
00479   assert(FTy->getNumParams() == ArgValues.size() &&
00480          "This doesn't support passing arguments through varargs (yet)!");
00481 
00482   // Handle some common cases first.  These cases correspond to common `main'
00483   // prototypes.
00484   if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
00485     switch (ArgValues.size()) {
00486     case 3:
00487       if (FTy->getParamType(0)->isIntegerTy(32) &&
00488           FTy->getParamType(1)->isPointerTy() &&
00489           FTy->getParamType(2)->isPointerTy()) {
00490         int (*PF)(int, char **, const char **) =
00491           (int(*)(int, char **, const char **))(intptr_t)FPtr;
00492 
00493         // Call the function.
00494         GenericValue rv;
00495         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
00496                                  (char **)GVTOP(ArgValues[1]),
00497                                  (const char **)GVTOP(ArgValues[2])));
00498         return rv;
00499       }
00500       break;
00501     case 2:
00502       if (FTy->getParamType(0)->isIntegerTy(32) &&
00503           FTy->getParamType(1)->isPointerTy()) {
00504         int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
00505 
00506         // Call the function.
00507         GenericValue rv;
00508         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
00509                                  (char **)GVTOP(ArgValues[1])));
00510         return rv;
00511       }
00512       break;
00513     case 1:
00514       if (FTy->getNumParams() == 1 &&
00515           FTy->getParamType(0)->isIntegerTy(32)) {
00516         GenericValue rv;
00517         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
00518         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
00519         return rv;
00520       }
00521       break;
00522     }
00523   }
00524 
00525   // Handle cases where no arguments are passed first.
00526   if (ArgValues.empty()) {
00527     GenericValue rv;
00528     switch (RetTy->getTypeID()) {
00529     default: llvm_unreachable("Unknown return type for function call!");
00530     case Type::IntegerTyID: {
00531       unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
00532       if (BitWidth == 1)
00533         rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
00534       else if (BitWidth <= 8)
00535         rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
00536       else if (BitWidth <= 16)
00537         rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
00538       else if (BitWidth <= 32)
00539         rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
00540       else if (BitWidth <= 64)
00541         rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
00542       else
00543         llvm_unreachable("Integer types > 64 bits not supported");
00544       return rv;
00545     }
00546     case Type::VoidTyID:
00547       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
00548       return rv;
00549     case Type::FloatTyID:
00550       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
00551       return rv;
00552     case Type::DoubleTyID:
00553       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
00554       return rv;
00555     case Type::X86_FP80TyID:
00556     case Type::FP128TyID:
00557     case Type::PPC_FP128TyID:
00558       llvm_unreachable("long double not supported yet");
00559     case Type::PointerTyID:
00560       return PTOGV(((void*(*)())(intptr_t)FPtr)());
00561     }
00562   }
00563 
00564   llvm_unreachable("Full-featured argument passing not supported yet!");
00565 }
00566 
00567 void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
00568   if (!isSymbolSearchingDisabled()) {
00569     void *ptr =
00570       reinterpret_cast<void*>(
00571         static_cast<uintptr_t>(Resolver.findSymbol(Name).getAddress()));
00572     if (ptr)
00573       return ptr;
00574   }
00575 
00576   /// If a LazyFunctionCreator is installed, use it to get/create the function.
00577   if (LazyFunctionCreator)
00578     if (void *RP = LazyFunctionCreator(Name))
00579       return RP;
00580 
00581   if (AbortOnFailure) {
00582     report_fatal_error("Program used external function '"+Name+
00583                        "' which could not be resolved!");
00584   }
00585   return nullptr;
00586 }
00587 
00588 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
00589   if (!L)
00590     return;
00591   MutexGuard locked(lock);
00592   EventListeners.push_back(L);
00593 }
00594 
00595 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
00596   if (!L)
00597     return;
00598   MutexGuard locked(lock);
00599   auto I = std::find(EventListeners.rbegin(), EventListeners.rend(), L);
00600   if (I != EventListeners.rend()) {
00601     std::swap(*I, EventListeners.back());
00602     EventListeners.pop_back();
00603   }
00604 }
00605 
00606 void MCJIT::NotifyObjectEmitted(const object::ObjectFile& Obj,
00607                                 const RuntimeDyld::LoadedObjectInfo &L) {
00608   MutexGuard locked(lock);
00609   MemMgr->notifyObjectLoaded(this, Obj);
00610   for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
00611     EventListeners[I]->NotifyObjectEmitted(Obj, L);
00612   }
00613 }
00614 
00615 void MCJIT::NotifyFreeingObject(const object::ObjectFile& Obj) {
00616   MutexGuard locked(lock);
00617   for (JITEventListener *L : EventListeners)
00618     L->NotifyFreeingObject(Obj);
00619 }
00620 
00621 RuntimeDyld::SymbolInfo
00622 LinkingSymbolResolver::findSymbol(const std::string &Name) {
00623   auto Result = ParentEngine.findSymbol(Name, false);
00624   // If the symbols wasn't found and it begins with an underscore, try again
00625   // without the underscore.
00626   if (!Result && Name[0] == '_')
00627     Result = ParentEngine.findSymbol(Name.substr(1), false);
00628   if (Result)
00629     return Result;
00630   if (ParentEngine.isSymbolSearchingDisabled())
00631     return nullptr;
00632   return ClientResolver->findSymbol(Name);
00633 }