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(TM->createDataLayout(), std::move(M)), TM(std::move(TM)),
00072       Ctx(nullptr), MemMgr(std::move(MemMgr)),
00073       Resolver(*this, std::move(Resolver)), Dyld(*this->MemMgr, this->Resolver),
00074       ObjCache(nullptr) {
00075   // FIXME: We are managing our modules, so we do not want the base class
00076   // ExecutionEngine to manage them as well. To avoid double destruction
00077   // of the first (and only) module added in ExecutionEngine constructor
00078   // we remove it from EE and will destruct it ourselves.
00079   //
00080   // It may make sense to move our module manager (based on SmallStPtr) back
00081   // into EE if the JIT and Interpreter can live with it.
00082   // If so, additional functions: addModule, removeModule, FindFunctionNamed,
00083   // runStaticConstructorsDestructors could be moved back to EE as well.
00084   //
00085   std::unique_ptr<Module> First = std::move(Modules[0]);
00086   Modules.clear();
00087 
00088   OwnedModules.addModule(std::move(First));
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 
00163   std::unique_ptr<MemoryBuffer> CompiledObjBuffer(
00164                                 new ObjectMemoryBuffer(std::move(ObjBufferSV)));
00165 
00166   // If we have an object cache, tell it about the new object.
00167   // Note that we're using the compiled image, not the loaded image (as below).
00168   if (ObjCache) {
00169     // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
00170     // to create a temporary object here and delete it after the call.
00171     MemoryBufferRef MB = CompiledObjBuffer->getMemBufferRef();
00172     ObjCache->notifyObjectCompiled(M, MB);
00173   }
00174 
00175   return CompiledObjBuffer;
00176 }
00177 
00178 void MCJIT::generateCodeForModule(Module *M) {
00179   // Get a thread lock to make sure we aren't trying to load multiple times
00180   MutexGuard locked(lock);
00181 
00182   // This must be a module which has already been added to this MCJIT instance.
00183   assert(OwnedModules.ownsModule(M) &&
00184          "MCJIT::generateCodeForModule: Unknown module.");
00185 
00186   // Re-compilation is not supported
00187   if (OwnedModules.hasModuleBeenLoaded(M))
00188     return;
00189 
00190   std::unique_ptr<MemoryBuffer> ObjectToLoad;
00191   // Try to load the pre-compiled object from cache if possible
00192   if (ObjCache)
00193     ObjectToLoad = ObjCache->getObject(M);
00194 
00195   if (M->getDataLayout().isDefault()) {
00196     M->setDataLayout(getDataLayout());
00197   } else {
00198     assert(M->getDataLayout() == getDataLayout() && "DataLayout Mismatch");
00199   }
00200 
00201   // If the cache did not contain a suitable object, compile the object
00202   if (!ObjectToLoad) {
00203     ObjectToLoad = emitObject(M);
00204     assert(ObjectToLoad && "Compilation did not produce an object.");
00205   }
00206 
00207   // Load the object into the dynamic linker.
00208   // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
00209   ErrorOr<std::unique_ptr<object::ObjectFile>> LoadedObject =
00210     object::ObjectFile::createObjectFile(ObjectToLoad->getMemBufferRef());
00211   std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L =
00212     Dyld.loadObject(*LoadedObject.get());
00213 
00214   if (Dyld.hasError())
00215     report_fatal_error(Dyld.getErrorString());
00216 
00217   NotifyObjectEmitted(*LoadedObject.get(), *L);
00218 
00219   Buffers.push_back(std::move(ObjectToLoad));
00220   LoadedObjects.push_back(std::move(*LoadedObject));
00221 
00222   OwnedModules.markModuleAsLoaded(M);
00223 }
00224 
00225 void MCJIT::finalizeLoadedModules() {
00226   MutexGuard locked(lock);
00227 
00228   // Resolve any outstanding relocations.
00229   Dyld.resolveRelocations();
00230 
00231   OwnedModules.markAllLoadedModulesAsFinalized();
00232 
00233   // Register EH frame data for any module we own which has been loaded
00234   Dyld.registerEHFrames();
00235 
00236   // Set page permissions.
00237   MemMgr->finalizeMemory();
00238 }
00239 
00240 // FIXME: Rename this.
00241 void MCJIT::finalizeObject() {
00242   MutexGuard locked(lock);
00243 
00244   // Generate code for module is going to move objects out of the 'added' list,
00245   // so we need to copy that out before using it:
00246   SmallVector<Module*, 16> ModsToAdd;
00247   for (auto M : OwnedModules.added())
00248     ModsToAdd.push_back(M);
00249 
00250   for (auto M : ModsToAdd)
00251     generateCodeForModule(M);
00252 
00253   finalizeLoadedModules();
00254 }
00255 
00256 void MCJIT::finalizeModule(Module *M) {
00257   MutexGuard locked(lock);
00258 
00259   // This must be a module which has already been added to this MCJIT instance.
00260   assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
00261 
00262   // If the module hasn't been compiled, just do that.
00263   if (!OwnedModules.hasModuleBeenLoaded(M))
00264     generateCodeForModule(M);
00265 
00266   finalizeLoadedModules();
00267 }
00268 
00269 RuntimeDyld::SymbolInfo MCJIT::findExistingSymbol(const std::string &Name) {
00270   SmallString<128> FullName;
00271   Mangler::getNameWithPrefix(FullName, Name, getDataLayout());
00272 
00273   if (void *Addr = getPointerToGlobalIfAvailable(FullName))
00274     return RuntimeDyld::SymbolInfo(static_cast<uint64_t>(
00275                                      reinterpret_cast<uintptr_t>(Addr)),
00276                                    JITSymbolFlags::Exported);
00277 
00278   return Dyld.getSymbol(FullName);
00279 }
00280 
00281 Module *MCJIT::findModuleForSymbol(const std::string &Name,
00282                                    bool CheckFunctionsOnly) {
00283   MutexGuard locked(lock);
00284 
00285   // If it hasn't already been generated, see if it's in one of our modules.
00286   for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
00287                               E = OwnedModules.end_added();
00288        I != E; ++I) {
00289     Module *M = *I;
00290     Function *F = M->getFunction(Name);
00291     if (F && !F->isDeclaration())
00292       return M;
00293     if (!CheckFunctionsOnly) {
00294       GlobalVariable *G = M->getGlobalVariable(Name);
00295       if (G && !G->isDeclaration())
00296         return M;
00297       // FIXME: Do we need to worry about global aliases?
00298     }
00299   }
00300   // We didn't find the symbol in any of our modules.
00301   return nullptr;
00302 }
00303 
00304 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
00305                                  bool CheckFunctionsOnly) {
00306   return findSymbol(Name, CheckFunctionsOnly).getAddress();
00307 }
00308 
00309 RuntimeDyld::SymbolInfo MCJIT::findSymbol(const std::string &Name,
00310                                           bool CheckFunctionsOnly) {
00311   MutexGuard locked(lock);
00312 
00313   // First, check to see if we already have this symbol.
00314   if (auto Sym = findExistingSymbol(Name))
00315     return Sym;
00316 
00317   for (object::OwningBinary<object::Archive> &OB : Archives) {
00318     object::Archive *A = OB.getBinary();
00319     // Look for our symbols in each Archive
00320     object::Archive::child_iterator ChildIt = A->findSym(Name);
00321     if (std::error_code EC = ChildIt->getError())
00322       report_fatal_error(EC.message());
00323     if (ChildIt != A->child_end()) {
00324       // FIXME: Support nested archives?
00325       ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
00326           (*ChildIt)->getAsBinary();
00327       if (ChildBinOrErr.getError())
00328         continue;
00329       std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
00330       if (ChildBin->isObject()) {
00331         std::unique_ptr<object::ObjectFile> OF(
00332             static_cast<object::ObjectFile *>(ChildBin.release()));
00333         // This causes the object file to be loaded.
00334         addObjectFile(std::move(OF));
00335         // The address should be here now.
00336         if (auto Sym = findExistingSymbol(Name))
00337           return Sym;
00338       }
00339     }
00340   }
00341 
00342   // If it hasn't already been generated, see if it's in one of our modules.
00343   Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
00344   if (M) {
00345     generateCodeForModule(M);
00346 
00347     // Check the RuntimeDyld table again, it should be there now.
00348     return findExistingSymbol(Name);
00349   }
00350 
00351   // If a LazyFunctionCreator is installed, use it to get/create the function.
00352   // FIXME: Should we instead have a LazySymbolCreator callback?
00353   if (LazyFunctionCreator) {
00354     auto Addr = static_cast<uint64_t>(
00355                   reinterpret_cast<uintptr_t>(LazyFunctionCreator(Name)));
00356     return RuntimeDyld::SymbolInfo(Addr, JITSymbolFlags::Exported);
00357   }
00358 
00359   return nullptr;
00360 }
00361 
00362 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
00363   MutexGuard locked(lock);
00364   uint64_t Result = getSymbolAddress(Name, false);
00365   if (Result != 0)
00366     finalizeLoadedModules();
00367   return Result;
00368 }
00369 
00370 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
00371   MutexGuard locked(lock);
00372   uint64_t Result = getSymbolAddress(Name, true);
00373   if (Result != 0)
00374     finalizeLoadedModules();
00375   return Result;
00376 }
00377 
00378 // Deprecated.  Use getFunctionAddress instead.
00379 void *MCJIT::getPointerToFunction(Function *F) {
00380   MutexGuard locked(lock);
00381 
00382   Mangler Mang;
00383   SmallString<128> Name;
00384   TM->getNameWithPrefix(Name, F, Mang);
00385 
00386   if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
00387     bool AbortOnFailure = !F->hasExternalWeakLinkage();
00388     void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
00389     updateGlobalMapping(F, Addr);
00390     return Addr;
00391   }
00392 
00393   Module *M = F->getParent();
00394   bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
00395 
00396   // Make sure the relevant module has been compiled and loaded.
00397   if (HasBeenAddedButNotLoaded)
00398     generateCodeForModule(M);
00399   else if (!OwnedModules.hasModuleBeenLoaded(M)) {
00400     // If this function doesn't belong to one of our modules, we're done.
00401     // FIXME: Asking for the pointer to a function that hasn't been registered,
00402     //        and isn't a declaration (which is handled above) should probably
00403     //        be an assertion.
00404     return nullptr;
00405   }
00406 
00407   // FIXME: Should the Dyld be retaining module information? Probably not.
00408   //
00409   // This is the accessor for the target address, so make sure to check the
00410   // load address of the symbol, not the local address.
00411   return (void*)Dyld.getSymbol(Name).getAddress();
00412 }
00413 
00414 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
00415     bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
00416   for (; I != E; ++I) {
00417     ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
00418   }
00419 }
00420 
00421 void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
00422   // Execute global ctors/dtors for each module in the program.
00423   runStaticConstructorsDestructorsInModulePtrSet(
00424       isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
00425   runStaticConstructorsDestructorsInModulePtrSet(
00426       isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
00427   runStaticConstructorsDestructorsInModulePtrSet(
00428       isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
00429 }
00430 
00431 Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
00432                                                  ModulePtrSet::iterator I,
00433                                                  ModulePtrSet::iterator E) {
00434   for (; I != E; ++I) {
00435     Function *F = (*I)->getFunction(FnName);
00436     if (F && !F->isDeclaration())
00437       return F;
00438   }
00439   return nullptr;
00440 }
00441 
00442 GlobalVariable *MCJIT::FindGlobalVariableNamedInModulePtrSet(const char *Name,
00443                                                              bool AllowInternal,
00444                                                              ModulePtrSet::iterator I,
00445                                                              ModulePtrSet::iterator E) {
00446   for (; I != E; ++I) {
00447     GlobalVariable *GV = (*I)->getGlobalVariable(Name, AllowInternal);
00448     if (GV && !GV->isDeclaration())
00449       return GV;
00450   }
00451   return nullptr;
00452 }
00453 
00454 
00455 Function *MCJIT::FindFunctionNamed(const char *FnName) {
00456   Function *F = FindFunctionNamedInModulePtrSet(
00457       FnName, OwnedModules.begin_added(), OwnedModules.end_added());
00458   if (!F)
00459     F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
00460                                         OwnedModules.end_loaded());
00461   if (!F)
00462     F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
00463                                         OwnedModules.end_finalized());
00464   return F;
00465 }
00466 
00467 GlobalVariable *MCJIT::FindGlobalVariableNamed(const char *Name, bool AllowInternal) {
00468   GlobalVariable *GV = FindGlobalVariableNamedInModulePtrSet(
00469       Name, AllowInternal, OwnedModules.begin_added(), OwnedModules.end_added());
00470   if (!GV)
00471     GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_loaded(),
00472                                         OwnedModules.end_loaded());
00473   if (!GV)
00474     GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_finalized(),
00475                                         OwnedModules.end_finalized());
00476   return GV;
00477 }
00478 
00479 GenericValue MCJIT::runFunction(Function *F, ArrayRef<GenericValue> ArgValues) {
00480   assert(F && "Function *F was null at entry to run()");
00481 
00482   void *FPtr = getPointerToFunction(F);
00483   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
00484   FunctionType *FTy = F->getFunctionType();
00485   Type *RetTy = FTy->getReturnType();
00486 
00487   assert((FTy->getNumParams() == ArgValues.size() ||
00488           (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
00489          "Wrong number of arguments passed into function!");
00490   assert(FTy->getNumParams() == ArgValues.size() &&
00491          "This doesn't support passing arguments through varargs (yet)!");
00492 
00493   // Handle some common cases first.  These cases correspond to common `main'
00494   // prototypes.
00495   if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
00496     switch (ArgValues.size()) {
00497     case 3:
00498       if (FTy->getParamType(0)->isIntegerTy(32) &&
00499           FTy->getParamType(1)->isPointerTy() &&
00500           FTy->getParamType(2)->isPointerTy()) {
00501         int (*PF)(int, char **, const char **) =
00502           (int(*)(int, char **, const char **))(intptr_t)FPtr;
00503 
00504         // Call the function.
00505         GenericValue rv;
00506         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
00507                                  (char **)GVTOP(ArgValues[1]),
00508                                  (const char **)GVTOP(ArgValues[2])));
00509         return rv;
00510       }
00511       break;
00512     case 2:
00513       if (FTy->getParamType(0)->isIntegerTy(32) &&
00514           FTy->getParamType(1)->isPointerTy()) {
00515         int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
00516 
00517         // Call the function.
00518         GenericValue rv;
00519         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
00520                                  (char **)GVTOP(ArgValues[1])));
00521         return rv;
00522       }
00523       break;
00524     case 1:
00525       if (FTy->getNumParams() == 1 &&
00526           FTy->getParamType(0)->isIntegerTy(32)) {
00527         GenericValue rv;
00528         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
00529         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
00530         return rv;
00531       }
00532       break;
00533     }
00534   }
00535 
00536   // Handle cases where no arguments are passed first.
00537   if (ArgValues.empty()) {
00538     GenericValue rv;
00539     switch (RetTy->getTypeID()) {
00540     default: llvm_unreachable("Unknown return type for function call!");
00541     case Type::IntegerTyID: {
00542       unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
00543       if (BitWidth == 1)
00544         rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
00545       else if (BitWidth <= 8)
00546         rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
00547       else if (BitWidth <= 16)
00548         rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
00549       else if (BitWidth <= 32)
00550         rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
00551       else if (BitWidth <= 64)
00552         rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
00553       else
00554         llvm_unreachable("Integer types > 64 bits not supported");
00555       return rv;
00556     }
00557     case Type::VoidTyID:
00558       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
00559       return rv;
00560     case Type::FloatTyID:
00561       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
00562       return rv;
00563     case Type::DoubleTyID:
00564       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
00565       return rv;
00566     case Type::X86_FP80TyID:
00567     case Type::FP128TyID:
00568     case Type::PPC_FP128TyID:
00569       llvm_unreachable("long double not supported yet");
00570     case Type::PointerTyID:
00571       return PTOGV(((void*(*)())(intptr_t)FPtr)());
00572     }
00573   }
00574 
00575   llvm_unreachable("Full-featured argument passing not supported yet!");
00576 }
00577 
00578 void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
00579   if (!isSymbolSearchingDisabled()) {
00580     void *ptr =
00581       reinterpret_cast<void*>(
00582         static_cast<uintptr_t>(Resolver.findSymbol(Name).getAddress()));
00583     if (ptr)
00584       return ptr;
00585   }
00586 
00587   /// If a LazyFunctionCreator is installed, use it to get/create the function.
00588   if (LazyFunctionCreator)
00589     if (void *RP = LazyFunctionCreator(Name))
00590       return RP;
00591 
00592   if (AbortOnFailure) {
00593     report_fatal_error("Program used external function '"+Name+
00594                        "' which could not be resolved!");
00595   }
00596   return nullptr;
00597 }
00598 
00599 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
00600   if (!L)
00601     return;
00602   MutexGuard locked(lock);
00603   EventListeners.push_back(L);
00604 }
00605 
00606 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
00607   if (!L)
00608     return;
00609   MutexGuard locked(lock);
00610   auto I = std::find(EventListeners.rbegin(), EventListeners.rend(), L);
00611   if (I != EventListeners.rend()) {
00612     std::swap(*I, EventListeners.back());
00613     EventListeners.pop_back();
00614   }
00615 }
00616 
00617 void MCJIT::NotifyObjectEmitted(const object::ObjectFile& Obj,
00618                                 const RuntimeDyld::LoadedObjectInfo &L) {
00619   MutexGuard locked(lock);
00620   MemMgr->notifyObjectLoaded(this, Obj);
00621   for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
00622     EventListeners[I]->NotifyObjectEmitted(Obj, L);
00623   }
00624 }
00625 
00626 void MCJIT::NotifyFreeingObject(const object::ObjectFile& Obj) {
00627   MutexGuard locked(lock);
00628   for (JITEventListener *L : EventListeners)
00629     L->NotifyFreeingObject(Obj);
00630 }
00631 
00632 RuntimeDyld::SymbolInfo
00633 LinkingSymbolResolver::findSymbol(const std::string &Name) {
00634   auto Result = ParentEngine.findSymbol(Name, false);
00635   // If the symbols wasn't found and it begins with an underscore, try again
00636   // without the underscore.
00637   if (!Result && Name[0] == '_')
00638     Result = ParentEngine.findSymbol(Name.substr(1), false);
00639   if (Result)
00640     return Result;
00641   if (ParentEngine.isSymbolSearchingDisabled())
00642     return nullptr;
00643   return ClientResolver->findSymbol(Name);
00644 }