1 //===-- MCJIT.cpp - MC-based 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 //===----------------------------------------------------------------------===//
11 #include "llvm/ExecutionEngine/GenericValue.h"
12 #include "llvm/ExecutionEngine/JITEventListener.h"
13 #include "llvm/ExecutionEngine/MCJIT.h"
14 #include "llvm/ExecutionEngine/ObjectBuffer.h"
15 #include "llvm/ExecutionEngine/ObjectImage.h"
16 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/Mangler.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/Object/Archive.h"
24 #include "llvm/PassManager.h"
25 #include "llvm/Support/DynamicLibrary.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/MutexGuard.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetSubtargetInfo.h"
36 static struct RegisterJIT {
37 RegisterJIT() { MCJIT::Register(); }
42 extern "C" void LLVMLinkInMCJIT() {
45 ExecutionEngine *MCJIT::createJIT(std::unique_ptr<Module> M,
46 std::string *ErrorStr,
47 RTDyldMemoryManager *MemMgr,
48 std::unique_ptr<TargetMachine> TM) {
49 // Try to register the program as a source of symbols to resolve against.
51 // FIXME: Don't do this here.
52 sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
54 return new MCJIT(std::move(M), std::move(TM),
55 MemMgr ? MemMgr : new SectionMemoryManager());
58 MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> tm,
59 RTDyldMemoryManager *MM)
60 : ExecutionEngine(std::move(M)), TM(std::move(tm)), Ctx(nullptr),
61 MemMgr(this, MM), Dyld(&MemMgr), ObjCache(nullptr) {
62 // FIXME: We are managing our modules, so we do not want the base class
63 // ExecutionEngine to manage them as well. To avoid double destruction
64 // of the first (and only) module added in ExecutionEngine constructor
65 // we remove it from EE and will destruct it ourselves.
67 // It may make sense to move our module manager (based on SmallStPtr) back
68 // into EE if the JIT and Interpreter can live with it.
69 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
70 // runStaticConstructorsDestructors could be moved back to EE as well.
72 std::unique_ptr<Module> First = std::move(Modules[0]);
75 OwnedModules.addModule(std::move(First));
76 setDataLayout(TM->getSubtargetImpl()->getDataLayout());
80 MutexGuard locked(lock);
82 Dyld.deregisterEHFrames();
84 for (auto &Obj : LoadedObjects)
86 NotifyFreeingObject(*Obj);
91 void MCJIT::addModule(std::unique_ptr<Module> M) {
92 MutexGuard locked(lock);
93 OwnedModules.addModule(std::move(M));
96 bool MCJIT::removeModule(Module *M) {
97 MutexGuard locked(lock);
98 return OwnedModules.removeModule(M);
101 void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
102 std::unique_ptr<ObjectImage> LoadedObject = Dyld.loadObject(std::move(Obj));
103 if (!LoadedObject || Dyld.hasError())
104 report_fatal_error(Dyld.getErrorString());
106 NotifyObjectEmitted(*LoadedObject);
108 LoadedObjects.push_back(std::move(LoadedObject));
111 void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
112 addObjectFile(std::move(Obj.getBinary()));
113 Buffers.push_back(std::move(Obj.getBuffer()));
116 void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
117 Archives.push_back(std::move(A));
120 void MCJIT::setObjectCache(ObjectCache* NewCache) {
121 MutexGuard locked(lock);
125 std::unique_ptr<ObjectBufferStream> MCJIT::emitObject(Module *M) {
126 MutexGuard locked(lock);
128 // This must be a module which has already been added but not loaded to this
129 // MCJIT instance, since these conditions are tested by our caller,
130 // generateCodeForModule.
134 M->setDataLayout(TM->getSubtargetImpl()->getDataLayout());
135 PM.add(new DataLayoutPass());
137 // The RuntimeDyld will take ownership of this shortly
138 std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
140 // Turn the machine code intermediate representation into bytes in memory
141 // that may be executed.
142 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
143 !getVerifyModules())) {
144 report_fatal_error("Target does not support MC emission!");
147 // Initialize passes.
149 // Flush the output buffer to get the generated code into memory
150 CompiledObject->flush();
152 // If we have an object cache, tell it about the new object.
153 // Note that we're using the compiled image, not the loaded image (as below).
155 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
156 // to create a temporary object here and delete it after the call.
157 MemoryBufferRef MB = CompiledObject->getMemBuffer();
158 ObjCache->notifyObjectCompiled(M, MB);
161 return CompiledObject;
164 void MCJIT::generateCodeForModule(Module *M) {
165 // Get a thread lock to make sure we aren't trying to load multiple times
166 MutexGuard locked(lock);
168 // This must be a module which has already been added to this MCJIT instance.
169 assert(OwnedModules.ownsModule(M) &&
170 "MCJIT::generateCodeForModule: Unknown module.");
172 // Re-compilation is not supported
173 if (OwnedModules.hasModuleBeenLoaded(M))
176 std::unique_ptr<ObjectBuffer> ObjectToLoad;
177 // Try to load the pre-compiled object from cache if possible
179 if (std::unique_ptr<MemoryBuffer> PreCompiledObject =
180 ObjCache->getObject(M))
182 llvm::make_unique<ObjectBuffer>(std::move(PreCompiledObject));
185 // If the cache did not contain a suitable object, compile the object
187 ObjectToLoad = emitObject(M);
188 assert(ObjectToLoad && "Compilation did not produce an object.");
191 // Load the object into the dynamic linker.
192 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
193 std::unique_ptr<ObjectImage> LoadedObject =
194 Dyld.loadObject(std::move(ObjectToLoad));
196 report_fatal_error(Dyld.getErrorString());
198 // FIXME: Make this optional, maybe even move it to a JIT event listener
199 LoadedObject->registerWithDebugger();
201 NotifyObjectEmitted(*LoadedObject);
203 LoadedObjects.push_back(std::move(LoadedObject));
205 OwnedModules.markModuleAsLoaded(M);
208 void MCJIT::finalizeLoadedModules() {
209 MutexGuard locked(lock);
211 // Resolve any outstanding relocations.
212 Dyld.resolveRelocations();
214 OwnedModules.markAllLoadedModulesAsFinalized();
216 // Register EH frame data for any module we own which has been loaded
217 Dyld.registerEHFrames();
219 // Set page permissions.
220 MemMgr.finalizeMemory();
223 // FIXME: Rename this.
224 void MCJIT::finalizeObject() {
225 MutexGuard locked(lock);
227 // Generate code for module is going to move objects out of the 'added' list,
228 // so we need to copy that out before using it:
229 SmallVector<Module*, 16> ModsToAdd;
230 for (auto M : OwnedModules.added())
231 ModsToAdd.push_back(M);
233 for (auto M : ModsToAdd)
234 generateCodeForModule(M);
236 finalizeLoadedModules();
239 void MCJIT::finalizeModule(Module *M) {
240 MutexGuard locked(lock);
242 // This must be a module which has already been added to this MCJIT instance.
243 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
245 // If the module hasn't been compiled, just do that.
246 if (!OwnedModules.hasModuleBeenLoaded(M))
247 generateCodeForModule(M);
249 finalizeLoadedModules();
252 uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
253 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
254 SmallString<128> FullName;
255 Mang.getNameWithPrefix(FullName, Name);
256 return Dyld.getSymbolLoadAddress(FullName);
259 Module *MCJIT::findModuleForSymbol(const std::string &Name,
260 bool CheckFunctionsOnly) {
261 MutexGuard locked(lock);
263 // If it hasn't already been generated, see if it's in one of our modules.
264 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
265 E = OwnedModules.end_added();
268 Function *F = M->getFunction(Name);
269 if (F && !F->isDeclaration())
271 if (!CheckFunctionsOnly) {
272 GlobalVariable *G = M->getGlobalVariable(Name);
273 if (G && !G->isDeclaration())
275 // FIXME: Do we need to worry about global aliases?
278 // We didn't find the symbol in any of our modules.
282 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
283 bool CheckFunctionsOnly)
285 MutexGuard locked(lock);
287 // First, check to see if we already have this symbol.
288 uint64_t Addr = getExistingSymbolAddress(Name);
292 for (object::OwningBinary<object::Archive> &OB : Archives) {
293 object::Archive *A = OB.getBinary().get();
294 // Look for our symbols in each Archive
295 object::Archive::child_iterator ChildIt = A->findSym(Name);
296 if (ChildIt != A->child_end()) {
297 // FIXME: Support nested archives?
298 ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
299 ChildIt->getAsBinary();
300 if (ChildBinOrErr.getError())
302 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
303 if (ChildBin->isObject()) {
304 std::unique_ptr<object::ObjectFile> OF(
305 static_cast<object::ObjectFile *>(ChildBin.release()));
306 // This causes the object file to be loaded.
307 addObjectFile(std::move(OF));
308 // The address should be here now.
309 Addr = getExistingSymbolAddress(Name);
316 // If it hasn't already been generated, see if it's in one of our modules.
317 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
319 generateCodeForModule(M);
321 // Check the RuntimeDyld table again, it should be there now.
322 return getExistingSymbolAddress(Name);
325 // If a LazyFunctionCreator is installed, use it to get/create the function.
326 // FIXME: Should we instead have a LazySymbolCreator callback?
327 if (LazyFunctionCreator)
328 Addr = (uint64_t)LazyFunctionCreator(Name);
333 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
334 MutexGuard locked(lock);
335 uint64_t Result = getSymbolAddress(Name, false);
337 finalizeLoadedModules();
341 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
342 MutexGuard locked(lock);
343 uint64_t Result = getSymbolAddress(Name, true);
345 finalizeLoadedModules();
349 // Deprecated. Use getFunctionAddress instead.
350 void *MCJIT::getPointerToFunction(Function *F) {
351 MutexGuard locked(lock);
353 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
354 SmallString<128> Name;
355 TM->getNameWithPrefix(Name, F, Mang);
357 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
358 bool AbortOnFailure = !F->hasExternalWeakLinkage();
359 void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
360 addGlobalMapping(F, Addr);
364 Module *M = F->getParent();
365 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
367 // Make sure the relevant module has been compiled and loaded.
368 if (HasBeenAddedButNotLoaded)
369 generateCodeForModule(M);
370 else if (!OwnedModules.hasModuleBeenLoaded(M)) {
371 // If this function doesn't belong to one of our modules, we're done.
372 // FIXME: Asking for the pointer to a function that hasn't been registered,
373 // and isn't a declaration (which is handled above) should probably
378 // FIXME: Should the Dyld be retaining module information? Probably not.
380 // This is the accessor for the target address, so make sure to check the
381 // load address of the symbol, not the local address.
382 return (void*)Dyld.getSymbolLoadAddress(Name);
385 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
386 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
387 for (; I != E; ++I) {
388 ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
392 void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
393 // Execute global ctors/dtors for each module in the program.
394 runStaticConstructorsDestructorsInModulePtrSet(
395 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
396 runStaticConstructorsDestructorsInModulePtrSet(
397 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
398 runStaticConstructorsDestructorsInModulePtrSet(
399 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
402 Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
403 ModulePtrSet::iterator I,
404 ModulePtrSet::iterator E) {
405 for (; I != E; ++I) {
406 if (Function *F = (*I)->getFunction(FnName))
412 Function *MCJIT::FindFunctionNamed(const char *FnName) {
413 Function *F = FindFunctionNamedInModulePtrSet(
414 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
416 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
417 OwnedModules.end_loaded());
419 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
420 OwnedModules.end_finalized());
424 GenericValue MCJIT::runFunction(Function *F,
425 const std::vector<GenericValue> &ArgValues) {
426 assert(F && "Function *F was null at entry to run()");
428 void *FPtr = getPointerToFunction(F);
429 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
430 FunctionType *FTy = F->getFunctionType();
431 Type *RetTy = FTy->getReturnType();
433 assert((FTy->getNumParams() == ArgValues.size() ||
434 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
435 "Wrong number of arguments passed into function!");
436 assert(FTy->getNumParams() == ArgValues.size() &&
437 "This doesn't support passing arguments through varargs (yet)!");
439 // Handle some common cases first. These cases correspond to common `main'
441 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
442 switch (ArgValues.size()) {
444 if (FTy->getParamType(0)->isIntegerTy(32) &&
445 FTy->getParamType(1)->isPointerTy() &&
446 FTy->getParamType(2)->isPointerTy()) {
447 int (*PF)(int, char **, const char **) =
448 (int(*)(int, char **, const char **))(intptr_t)FPtr;
450 // Call the function.
452 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
453 (char **)GVTOP(ArgValues[1]),
454 (const char **)GVTOP(ArgValues[2])));
459 if (FTy->getParamType(0)->isIntegerTy(32) &&
460 FTy->getParamType(1)->isPointerTy()) {
461 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
463 // Call the function.
465 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
466 (char **)GVTOP(ArgValues[1])));
471 if (FTy->getNumParams() == 1 &&
472 FTy->getParamType(0)->isIntegerTy(32)) {
474 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
475 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
482 // Handle cases where no arguments are passed first.
483 if (ArgValues.empty()) {
485 switch (RetTy->getTypeID()) {
486 default: llvm_unreachable("Unknown return type for function call!");
487 case Type::IntegerTyID: {
488 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
490 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
491 else if (BitWidth <= 8)
492 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
493 else if (BitWidth <= 16)
494 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
495 else if (BitWidth <= 32)
496 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
497 else if (BitWidth <= 64)
498 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
500 llvm_unreachable("Integer types > 64 bits not supported");
504 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
506 case Type::FloatTyID:
507 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
509 case Type::DoubleTyID:
510 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
512 case Type::X86_FP80TyID:
513 case Type::FP128TyID:
514 case Type::PPC_FP128TyID:
515 llvm_unreachable("long double not supported yet");
516 case Type::PointerTyID:
517 return PTOGV(((void*(*)())(intptr_t)FPtr)());
521 llvm_unreachable("Full-featured argument passing not supported yet!");
524 void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
525 if (!isSymbolSearchingDisabled()) {
526 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
531 /// If a LazyFunctionCreator is installed, use it to get/create the function.
532 if (LazyFunctionCreator)
533 if (void *RP = LazyFunctionCreator(Name))
536 if (AbortOnFailure) {
537 report_fatal_error("Program used external function '"+Name+
538 "' which could not be resolved!");
543 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
546 MutexGuard locked(lock);
547 EventListeners.push_back(L);
549 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
552 MutexGuard locked(lock);
553 auto I = std::find(EventListeners.rbegin(), EventListeners.rend(), L);
554 if (I != EventListeners.rend()) {
555 std::swap(*I, EventListeners.back());
556 EventListeners.pop_back();
559 void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
560 MutexGuard locked(lock);
561 MemMgr.notifyObjectLoaded(this, &Obj);
562 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
563 EventListeners[I]->NotifyObjectEmitted(Obj);
566 void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
567 MutexGuard locked(lock);
568 for (JITEventListener *L : EventListeners)
569 L->NotifyFreeingObject(Obj);
572 uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
573 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
574 // If the symbols wasn't found and it begins with an underscore, try again
575 // without the underscore.
576 if (!Result && Name[0] == '_')
577 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
580 if (ParentEngine->isSymbolSearchingDisabled())
582 return ClientMM->getSymbolAddress(Name);