1 //===-- MCJIT.cpp - MC-based Just-in-Time Compiler ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "MCJIT.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ExecutionEngine/GenericValue.h"
13 #include "llvm/ExecutionEngine/JITEventListener.h"
14 #include "llvm/ExecutionEngine/MCJIT.h"
15 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
16 #include "llvm/IR/DataLayout.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/Function.h"
19 #include "llvm/IR/LegacyPassManager.h"
20 #include "llvm/IR/Mangler.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Object/Archive.h"
23 #include "llvm/Object/ObjectFile.h"
24 #include "llvm/Support/DynamicLibrary.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/MutexGuard.h"
28 
29 using namespace llvm;
30 
31 namespace {
32 
33 static struct RegisterJIT {
34   RegisterJIT() { MCJIT::Register(); }
35 } JITRegistrator;
36 
37 }
38 
39 extern "C" void LLVMLinkInMCJIT() {
40 }
41 
42 ExecutionEngine*
43 MCJIT::createJIT(std::unique_ptr<Module> M,
44                  std::string *ErrorStr,
45                  std::shared_ptr<MCJITMemoryManager> MemMgr,
46                  std::shared_ptr<JITSymbolResolver> Resolver,
47                  std::unique_ptr<TargetMachine> TM) {
48   // Try to register the program as a source of symbols to resolve against.
49   //
50   // FIXME: Don't do this here.
51   sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
52 
53   if (!MemMgr || !Resolver) {
54     auto RTDyldMM = std::make_shared<SectionMemoryManager>();
55     if (!MemMgr)
56       MemMgr = RTDyldMM;
57     if (!Resolver)
58       Resolver = RTDyldMM;
59   }
60 
61   return new MCJIT(std::move(M), std::move(TM), std::move(MemMgr),
62                    std::move(Resolver));
63 }
64 
65 MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> TM,
66              std::shared_ptr<MCJITMemoryManager> MemMgr,
67              std::shared_ptr<JITSymbolResolver> Resolver)
68     : ExecutionEngine(TM->createDataLayout(), std::move(M)), TM(std::move(TM)),
69       Ctx(nullptr), MemMgr(std::move(MemMgr)),
70       Resolver(*this, std::move(Resolver)), Dyld(*this->MemMgr, this->Resolver),
71       ObjCache(nullptr) {
72   // FIXME: We are managing our modules, so we do not want the base class
73   // ExecutionEngine to manage them as well. To avoid double destruction
74   // of the first (and only) module added in ExecutionEngine constructor
75   // we remove it from EE and will destruct it ourselves.
76   //
77   // It may make sense to move our module manager (based on SmallStPtr) back
78   // into EE if the JIT and Interpreter can live with it.
79   // If so, additional functions: addModule, removeModule, FindFunctionNamed,
80   // runStaticConstructorsDestructors could be moved back to EE as well.
81   //
82   std::unique_ptr<Module> First = std::move(Modules[0]);
83   Modules.clear();
84 
85   if (First->getDataLayout().isDefault())
86     First->setDataLayout(getDataLayout());
87 
88   OwnedModules.addModule(std::move(First));
89   RegisterJITEventListener(JITEventListener::createGDBRegistrationListener());
90 }
91 
92 MCJIT::~MCJIT() {
93   MutexGuard locked(lock);
94 
95   Dyld.deregisterEHFrames();
96 
97   for (auto &Obj : LoadedObjects)
98     if (Obj)
99       NotifyFreeingObject(*Obj);
100 
101   Archives.clear();
102 }
103 
104 void MCJIT::addModule(std::unique_ptr<Module> M) {
105   MutexGuard locked(lock);
106 
107   if (M->getDataLayout().isDefault())
108     M->setDataLayout(getDataLayout());
109 
110   OwnedModules.addModule(std::move(M));
111 }
112 
113 bool MCJIT::removeModule(Module *M) {
114   MutexGuard locked(lock);
115   return OwnedModules.removeModule(M);
116 }
117 
118 void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
119   std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L = Dyld.loadObject(*Obj);
120   if (Dyld.hasError())
121     report_fatal_error(Dyld.getErrorString());
122 
123   NotifyObjectEmitted(*Obj, *L);
124 
125   LoadedObjects.push_back(std::move(Obj));
126 }
127 
128 void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
129   std::unique_ptr<object::ObjectFile> ObjFile;
130   std::unique_ptr<MemoryBuffer> MemBuf;
131   std::tie(ObjFile, MemBuf) = Obj.takeBinary();
132   addObjectFile(std::move(ObjFile));
133   Buffers.push_back(std::move(MemBuf));
134 }
135 
136 void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
137   Archives.push_back(std::move(A));
138 }
139 
140 void MCJIT::setObjectCache(ObjectCache* NewCache) {
141   MutexGuard locked(lock);
142   ObjCache = NewCache;
143 }
144 
145 std::unique_ptr<MemoryBuffer> MCJIT::emitObject(Module *M) {
146   MutexGuard locked(lock);
147 
148   // This must be a module which has already been added but not loaded to this
149   // MCJIT instance, since these conditions are tested by our caller,
150   // generateCodeForModule.
151 
152   legacy::PassManager PM;
153 
154   // The RuntimeDyld will take ownership of this shortly
155   SmallVector<char, 4096> ObjBufferSV;
156   raw_svector_ostream ObjStream(ObjBufferSV);
157 
158   // Turn the machine code intermediate representation into bytes in memory
159   // that may be executed.
160   if (TM->addPassesToEmitMC(PM, Ctx, ObjStream, !getVerifyModules()))
161     report_fatal_error("Target does not support MC emission!");
162 
163   // Initialize passes.
164   PM.run(*M);
165   // Flush the output buffer to get the generated code into memory
166 
167   std::unique_ptr<MemoryBuffer> CompiledObjBuffer(
168                                 new ObjectMemoryBuffer(std::move(ObjBufferSV)));
169 
170   // If we have an object cache, tell it about the new object.
171   // Note that we're using the compiled image, not the loaded image (as below).
172   if (ObjCache) {
173     // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
174     // to create a temporary object here and delete it after the call.
175     MemoryBufferRef MB = CompiledObjBuffer->getMemBufferRef();
176     ObjCache->notifyObjectCompiled(M, MB);
177   }
178 
179   return CompiledObjBuffer;
180 }
181 
182 void MCJIT::generateCodeForModule(Module *M) {
183   // Get a thread lock to make sure we aren't trying to load multiple times
184   MutexGuard locked(lock);
185 
186   // This must be a module which has already been added to this MCJIT instance.
187   assert(OwnedModules.ownsModule(M) &&
188          "MCJIT::generateCodeForModule: Unknown module.");
189 
190   // Re-compilation is not supported
191   if (OwnedModules.hasModuleBeenLoaded(M))
192     return;
193 
194   std::unique_ptr<MemoryBuffer> ObjectToLoad;
195   // Try to load the pre-compiled object from cache if possible
196   if (ObjCache)
197     ObjectToLoad = ObjCache->getObject(M);
198 
199   assert(M->getDataLayout() == getDataLayout() && "DataLayout Mismatch");
200 
201   // If the cache did not contain a suitable object, compile the object
202   if (!ObjectToLoad) {
203     ObjectToLoad = emitObject(M);
204     assert(ObjectToLoad && "Compilation did not produce an object.");
205   }
206 
207   // Load the object into the dynamic linker.
208   // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
209   Expected<std::unique_ptr<object::ObjectFile>> LoadedObject =
210     object::ObjectFile::createObjectFile(ObjectToLoad->getMemBufferRef());
211   if (!LoadedObject) {
212     std::string Buf;
213     raw_string_ostream OS(Buf);
214     logAllUnhandledErrors(LoadedObject.takeError(), OS, "");
215     OS.flush();
216     report_fatal_error(Buf);
217   }
218   std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L =
219     Dyld.loadObject(*LoadedObject.get());
220 
221   if (Dyld.hasError())
222     report_fatal_error(Dyld.getErrorString());
223 
224   NotifyObjectEmitted(*LoadedObject.get(), *L);
225 
226   Buffers.push_back(std::move(ObjectToLoad));
227   LoadedObjects.push_back(std::move(*LoadedObject));
228 
229   OwnedModules.markModuleAsLoaded(M);
230 }
231 
232 void MCJIT::finalizeLoadedModules() {
233   MutexGuard locked(lock);
234 
235   // Resolve any outstanding relocations.
236   Dyld.resolveRelocations();
237 
238   OwnedModules.markAllLoadedModulesAsFinalized();
239 
240   // Register EH frame data for any module we own which has been loaded
241   Dyld.registerEHFrames();
242 
243   // Set page permissions.
244   MemMgr->finalizeMemory();
245 }
246 
247 // FIXME: Rename this.
248 void MCJIT::finalizeObject() {
249   MutexGuard locked(lock);
250 
251   // Generate code for module is going to move objects out of the 'added' list,
252   // so we need to copy that out before using it:
253   SmallVector<Module*, 16> ModsToAdd;
254   for (auto M : OwnedModules.added())
255     ModsToAdd.push_back(M);
256 
257   for (auto M : ModsToAdd)
258     generateCodeForModule(M);
259 
260   finalizeLoadedModules();
261 }
262 
263 void MCJIT::finalizeModule(Module *M) {
264   MutexGuard locked(lock);
265 
266   // This must be a module which has already been added to this MCJIT instance.
267   assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
268 
269   // If the module hasn't been compiled, just do that.
270   if (!OwnedModules.hasModuleBeenLoaded(M))
271     generateCodeForModule(M);
272 
273   finalizeLoadedModules();
274 }
275 
276 JITSymbol MCJIT::findExistingSymbol(const std::string &Name) {
277   if (void *Addr = getPointerToGlobalIfAvailable(Name))
278     return JITSymbol(static_cast<uint64_t>(
279                          reinterpret_cast<uintptr_t>(Addr)),
280                      JITSymbolFlags::Exported);
281 
282   return Dyld.getSymbol(Name);
283 }
284 
285 Module *MCJIT::findModuleForSymbol(const std::string &Name,
286                                    bool CheckFunctionsOnly) {
287   StringRef DemangledName = Name;
288   if (DemangledName[0] == getDataLayout().getGlobalPrefix())
289     DemangledName = DemangledName.substr(1);
290 
291   MutexGuard locked(lock);
292 
293   // If it hasn't already been generated, see if it's in one of our modules.
294   for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
295                               E = OwnedModules.end_added();
296        I != E; ++I) {
297     Module *M = *I;
298     Function *F = M->getFunction(DemangledName);
299     if (F && !F->isDeclaration())
300       return M;
301     if (!CheckFunctionsOnly) {
302       GlobalVariable *G = M->getGlobalVariable(DemangledName);
303       if (G && !G->isDeclaration())
304         return M;
305       // FIXME: Do we need to worry about global aliases?
306     }
307   }
308   // We didn't find the symbol in any of our modules.
309   return nullptr;
310 }
311 
312 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
313                                  bool CheckFunctionsOnly) {
314   std::string MangledName;
315   {
316     raw_string_ostream MangledNameStream(MangledName);
317     Mangler::getNameWithPrefix(MangledNameStream, Name, getDataLayout());
318   }
319   if (auto Sym = findSymbol(MangledName, CheckFunctionsOnly)) {
320     if (auto AddrOrErr = Sym.getAddress())
321       return *AddrOrErr;
322     else
323       report_fatal_error(AddrOrErr.takeError());
324   } else
325     report_fatal_error(Sym.takeError());
326 }
327 
328 JITSymbol MCJIT::findSymbol(const std::string &Name,
329                             bool CheckFunctionsOnly) {
330   MutexGuard locked(lock);
331 
332   // First, check to see if we already have this symbol.
333   if (auto Sym = findExistingSymbol(Name))
334     return Sym;
335 
336   for (object::OwningBinary<object::Archive> &OB : Archives) {
337     object::Archive *A = OB.getBinary();
338     // Look for our symbols in each Archive
339     auto OptionalChildOrErr = A->findSym(Name);
340     if (!OptionalChildOrErr)
341       report_fatal_error(OptionalChildOrErr.takeError());
342     auto &OptionalChild = *OptionalChildOrErr;
343     if (OptionalChild) {
344       // FIXME: Support nested archives?
345       Expected<std::unique_ptr<object::Binary>> ChildBinOrErr =
346           OptionalChild->getAsBinary();
347       if (!ChildBinOrErr) {
348         // TODO: Actually report errors helpfully.
349         consumeError(ChildBinOrErr.takeError());
350         continue;
351       }
352       std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
353       if (ChildBin->isObject()) {
354         std::unique_ptr<object::ObjectFile> OF(
355             static_cast<object::ObjectFile *>(ChildBin.release()));
356         // This causes the object file to be loaded.
357         addObjectFile(std::move(OF));
358         // The address should be here now.
359         if (auto Sym = findExistingSymbol(Name))
360           return Sym;
361       }
362     }
363   }
364 
365   // If it hasn't already been generated, see if it's in one of our modules.
366   Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
367   if (M) {
368     generateCodeForModule(M);
369 
370     // Check the RuntimeDyld table again, it should be there now.
371     return findExistingSymbol(Name);
372   }
373 
374   // If a LazyFunctionCreator is installed, use it to get/create the function.
375   // FIXME: Should we instead have a LazySymbolCreator callback?
376   if (LazyFunctionCreator) {
377     auto Addr = static_cast<uint64_t>(
378                   reinterpret_cast<uintptr_t>(LazyFunctionCreator(Name)));
379     return JITSymbol(Addr, JITSymbolFlags::Exported);
380   }
381 
382   return nullptr;
383 }
384 
385 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
386   MutexGuard locked(lock);
387   uint64_t Result = getSymbolAddress(Name, false);
388   if (Result != 0)
389     finalizeLoadedModules();
390   return Result;
391 }
392 
393 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
394   MutexGuard locked(lock);
395   uint64_t Result = getSymbolAddress(Name, true);
396   if (Result != 0)
397     finalizeLoadedModules();
398   return Result;
399 }
400 
401 // Deprecated.  Use getFunctionAddress instead.
402 void *MCJIT::getPointerToFunction(Function *F) {
403   MutexGuard locked(lock);
404 
405   Mangler Mang;
406   SmallString<128> Name;
407   TM->getNameWithPrefix(Name, F, Mang);
408 
409   if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
410     bool AbortOnFailure = !F->hasExternalWeakLinkage();
411     void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
412     updateGlobalMapping(F, Addr);
413     return Addr;
414   }
415 
416   Module *M = F->getParent();
417   bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
418 
419   // Make sure the relevant module has been compiled and loaded.
420   if (HasBeenAddedButNotLoaded)
421     generateCodeForModule(M);
422   else if (!OwnedModules.hasModuleBeenLoaded(M)) {
423     // If this function doesn't belong to one of our modules, we're done.
424     // FIXME: Asking for the pointer to a function that hasn't been registered,
425     //        and isn't a declaration (which is handled above) should probably
426     //        be an assertion.
427     return nullptr;
428   }
429 
430   // FIXME: Should the Dyld be retaining module information? Probably not.
431   //
432   // This is the accessor for the target address, so make sure to check the
433   // load address of the symbol, not the local address.
434   return (void*)Dyld.getSymbol(Name).getAddress();
435 }
436 
437 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
438     bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
439   for (; I != E; ++I) {
440     ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
441   }
442 }
443 
444 void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
445   // Execute global ctors/dtors for each module in the program.
446   runStaticConstructorsDestructorsInModulePtrSet(
447       isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
448   runStaticConstructorsDestructorsInModulePtrSet(
449       isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
450   runStaticConstructorsDestructorsInModulePtrSet(
451       isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
452 }
453 
454 Function *MCJIT::FindFunctionNamedInModulePtrSet(StringRef FnName,
455                                                  ModulePtrSet::iterator I,
456                                                  ModulePtrSet::iterator E) {
457   for (; I != E; ++I) {
458     Function *F = (*I)->getFunction(FnName);
459     if (F && !F->isDeclaration())
460       return F;
461   }
462   return nullptr;
463 }
464 
465 GlobalVariable *MCJIT::FindGlobalVariableNamedInModulePtrSet(StringRef Name,
466                                                              bool AllowInternal,
467                                                              ModulePtrSet::iterator I,
468                                                              ModulePtrSet::iterator E) {
469   for (; I != E; ++I) {
470     GlobalVariable *GV = (*I)->getGlobalVariable(Name, AllowInternal);
471     if (GV && !GV->isDeclaration())
472       return GV;
473   }
474   return nullptr;
475 }
476 
477 
478 Function *MCJIT::FindFunctionNamed(StringRef FnName) {
479   Function *F = FindFunctionNamedInModulePtrSet(
480       FnName, OwnedModules.begin_added(), OwnedModules.end_added());
481   if (!F)
482     F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
483                                         OwnedModules.end_loaded());
484   if (!F)
485     F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
486                                         OwnedModules.end_finalized());
487   return F;
488 }
489 
490 GlobalVariable *MCJIT::FindGlobalVariableNamed(StringRef Name, bool AllowInternal) {
491   GlobalVariable *GV = FindGlobalVariableNamedInModulePtrSet(
492       Name, AllowInternal, OwnedModules.begin_added(), OwnedModules.end_added());
493   if (!GV)
494     GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_loaded(),
495                                         OwnedModules.end_loaded());
496   if (!GV)
497     GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_finalized(),
498                                         OwnedModules.end_finalized());
499   return GV;
500 }
501 
502 GenericValue MCJIT::runFunction(Function *F, ArrayRef<GenericValue> ArgValues) {
503   assert(F && "Function *F was null at entry to run()");
504 
505   void *FPtr = getPointerToFunction(F);
506   finalizeModule(F->getParent());
507   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
508   FunctionType *FTy = F->getFunctionType();
509   Type *RetTy = FTy->getReturnType();
510 
511   assert((FTy->getNumParams() == ArgValues.size() ||
512           (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
513          "Wrong number of arguments passed into function!");
514   assert(FTy->getNumParams() == ArgValues.size() &&
515          "This doesn't support passing arguments through varargs (yet)!");
516 
517   // Handle some common cases first.  These cases correspond to common `main'
518   // prototypes.
519   if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
520     switch (ArgValues.size()) {
521     case 3:
522       if (FTy->getParamType(0)->isIntegerTy(32) &&
523           FTy->getParamType(1)->isPointerTy() &&
524           FTy->getParamType(2)->isPointerTy()) {
525         int (*PF)(int, char **, const char **) =
526           (int(*)(int, char **, const char **))(intptr_t)FPtr;
527 
528         // Call the function.
529         GenericValue rv;
530         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
531                                  (char **)GVTOP(ArgValues[1]),
532                                  (const char **)GVTOP(ArgValues[2])));
533         return rv;
534       }
535       break;
536     case 2:
537       if (FTy->getParamType(0)->isIntegerTy(32) &&
538           FTy->getParamType(1)->isPointerTy()) {
539         int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
540 
541         // Call the function.
542         GenericValue rv;
543         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
544                                  (char **)GVTOP(ArgValues[1])));
545         return rv;
546       }
547       break;
548     case 1:
549       if (FTy->getNumParams() == 1 &&
550           FTy->getParamType(0)->isIntegerTy(32)) {
551         GenericValue rv;
552         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
553         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
554         return rv;
555       }
556       break;
557     }
558   }
559 
560   // Handle cases where no arguments are passed first.
561   if (ArgValues.empty()) {
562     GenericValue rv;
563     switch (RetTy->getTypeID()) {
564     default: llvm_unreachable("Unknown return type for function call!");
565     case Type::IntegerTyID: {
566       unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
567       if (BitWidth == 1)
568         rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
569       else if (BitWidth <= 8)
570         rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
571       else if (BitWidth <= 16)
572         rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
573       else if (BitWidth <= 32)
574         rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
575       else if (BitWidth <= 64)
576         rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
577       else
578         llvm_unreachable("Integer types > 64 bits not supported");
579       return rv;
580     }
581     case Type::VoidTyID:
582       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
583       return rv;
584     case Type::FloatTyID:
585       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
586       return rv;
587     case Type::DoubleTyID:
588       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
589       return rv;
590     case Type::X86_FP80TyID:
591     case Type::FP128TyID:
592     case Type::PPC_FP128TyID:
593       llvm_unreachable("long double not supported yet");
594     case Type::PointerTyID:
595       return PTOGV(((void*(*)())(intptr_t)FPtr)());
596     }
597   }
598 
599   report_fatal_error("MCJIT::runFunction does not support full-featured "
600                      "argument passing. Please use "
601                      "ExecutionEngine::getFunctionAddress and cast the result "
602                      "to the desired function pointer type.");
603 }
604 
605 void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
606   if (!isSymbolSearchingDisabled()) {
607     if (auto Sym = Resolver.findSymbol(Name)) {
608       if (auto AddrOrErr = Sym.getAddress())
609         return reinterpret_cast<void*>(
610                  static_cast<uintptr_t>(*AddrOrErr));
611     } else if (auto Err = Sym.takeError())
612       report_fatal_error(std::move(Err));
613   }
614 
615   /// If a LazyFunctionCreator is installed, use it to get/create the function.
616   if (LazyFunctionCreator)
617     if (void *RP = LazyFunctionCreator(Name))
618       return RP;
619 
620   if (AbortOnFailure) {
621     report_fatal_error("Program used external function '"+Name+
622                        "' which could not be resolved!");
623   }
624   return nullptr;
625 }
626 
627 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
628   if (!L)
629     return;
630   MutexGuard locked(lock);
631   EventListeners.push_back(L);
632 }
633 
634 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
635   if (!L)
636     return;
637   MutexGuard locked(lock);
638   auto I = find(reverse(EventListeners), L);
639   if (I != EventListeners.rend()) {
640     std::swap(*I, EventListeners.back());
641     EventListeners.pop_back();
642   }
643 }
644 
645 void MCJIT::NotifyObjectEmitted(const object::ObjectFile& Obj,
646                                 const RuntimeDyld::LoadedObjectInfo &L) {
647   MutexGuard locked(lock);
648   MemMgr->notifyObjectLoaded(this, Obj);
649   for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
650     EventListeners[I]->NotifyObjectEmitted(Obj, L);
651   }
652 }
653 
654 void MCJIT::NotifyFreeingObject(const object::ObjectFile& Obj) {
655   MutexGuard locked(lock);
656   for (JITEventListener *L : EventListeners)
657     L->NotifyFreeingObject(Obj);
658 }
659 
660 JITSymbol
661 LinkingSymbolResolver::findSymbol(const std::string &Name) {
662   auto Result = ParentEngine.findSymbol(Name, false);
663   if (Result)
664     return Result;
665   if (ParentEngine.isSymbolSearchingDisabled())
666     return nullptr;
667   return ClientResolver->findSymbol(Name);
668 }
669