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/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/MC/MCAsmInfo.h"
23 #include "llvm/Object/Archive.h"
24 #include "llvm/Object/ObjectFile.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"
32 void ObjectCache::anchor() {}
36 static struct RegisterJIT {
37 RegisterJIT() { MCJIT::Register(); }
42 extern "C" void LLVMLinkInMCJIT() {
46 MCJIT::createJIT(std::unique_ptr<Module> M,
47 std::string *ErrorStr,
48 std::shared_ptr<MCJITMemoryManager> MemMgr,
49 std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
50 std::unique_ptr<TargetMachine> TM) {
51 // Try to register the program as a source of symbols to resolve against.
53 // FIXME: Don't do this here.
54 sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
56 if (!MemMgr || !Resolver) {
57 auto RTDyldMM = std::make_shared<SectionMemoryManager>();
64 return new MCJIT(std::move(M), std::move(TM), std::move(MemMgr),
68 MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> TM,
69 std::shared_ptr<MCJITMemoryManager> MemMgr,
70 std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver)
71 : ExecutionEngine(*TM->getDataLayout(), std::move(M)), TM(std::move(TM)),
72 Ctx(nullptr), MemMgr(std::move(MemMgr)),
73 Resolver(*this, std::move(Resolver)), Dyld(*this->MemMgr, this->Resolver),
75 // FIXME: We are managing our modules, so we do not want the base class
76 // ExecutionEngine to manage them as well. To avoid double destruction
77 // of the first (and only) module added in ExecutionEngine constructor
78 // we remove it from EE and will destruct it ourselves.
80 // It may make sense to move our module manager (based on SmallStPtr) back
81 // into EE if the JIT and Interpreter can live with it.
82 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
83 // runStaticConstructorsDestructors could be moved back to EE as well.
85 std::unique_ptr<Module> First = std::move(Modules[0]);
88 OwnedModules.addModule(std::move(First));
89 RegisterJITEventListener(JITEventListener::createGDBRegistrationListener());
93 MutexGuard locked(lock);
95 Dyld.deregisterEHFrames();
97 for (auto &Obj : LoadedObjects)
99 NotifyFreeingObject(*Obj);
104 void MCJIT::addModule(std::unique_ptr<Module> M) {
105 MutexGuard locked(lock);
106 OwnedModules.addModule(std::move(M));
109 bool MCJIT::removeModule(Module *M) {
110 MutexGuard locked(lock);
111 return OwnedModules.removeModule(M);
114 void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
115 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L = Dyld.loadObject(*Obj);
117 report_fatal_error(Dyld.getErrorString());
119 NotifyObjectEmitted(*Obj, *L);
121 LoadedObjects.push_back(std::move(Obj));
124 void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
125 std::unique_ptr<object::ObjectFile> ObjFile;
126 std::unique_ptr<MemoryBuffer> MemBuf;
127 std::tie(ObjFile, MemBuf) = Obj.takeBinary();
128 addObjectFile(std::move(ObjFile));
129 Buffers.push_back(std::move(MemBuf));
132 void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
133 Archives.push_back(std::move(A));
136 void MCJIT::setObjectCache(ObjectCache* NewCache) {
137 MutexGuard locked(lock);
141 std::unique_ptr<MemoryBuffer> MCJIT::emitObject(Module *M) {
142 MutexGuard locked(lock);
144 // This must be a module which has already been added but not loaded to this
145 // MCJIT instance, since these conditions are tested by our caller,
146 // generateCodeForModule.
148 legacy::PassManager PM;
150 // The RuntimeDyld will take ownership of this shortly
151 SmallVector<char, 4096> ObjBufferSV;
152 raw_svector_ostream ObjStream(ObjBufferSV);
154 // Turn the machine code intermediate representation into bytes in memory
155 // that may be executed.
156 if (TM->addPassesToEmitMC(PM, Ctx, ObjStream, !getVerifyModules()))
157 report_fatal_error("Target does not support MC emission!");
159 // Initialize passes.
161 // Flush the output buffer to get the generated code into memory
164 std::unique_ptr<MemoryBuffer> CompiledObjBuffer(
165 new ObjectMemoryBuffer(std::move(ObjBufferSV)));
167 // If we have an object cache, tell it about the new object.
168 // Note that we're using the compiled image, not the loaded image (as below).
170 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
171 // to create a temporary object here and delete it after the call.
172 MemoryBufferRef MB = CompiledObjBuffer->getMemBufferRef();
173 ObjCache->notifyObjectCompiled(M, MB);
176 return CompiledObjBuffer;
179 void MCJIT::generateCodeForModule(Module *M) {
180 // Get a thread lock to make sure we aren't trying to load multiple times
181 MutexGuard locked(lock);
183 // This must be a module which has already been added to this MCJIT instance.
184 assert(OwnedModules.ownsModule(M) &&
185 "MCJIT::generateCodeForModule: Unknown module.");
187 // Re-compilation is not supported
188 if (OwnedModules.hasModuleBeenLoaded(M))
191 std::unique_ptr<MemoryBuffer> ObjectToLoad;
192 // Try to load the pre-compiled object from cache if possible
194 ObjectToLoad = ObjCache->getObject(M);
196 if (M->getDataLayout().isDefault()) {
197 M->setDataLayout(getDataLayout());
199 assert(M->getDataLayout() == getDataLayout() && "DataLayout Mismatch");
202 // If the cache did not contain a suitable object, compile the object
204 ObjectToLoad = emitObject(M);
205 assert(ObjectToLoad && "Compilation did not produce an object.");
208 // Load the object into the dynamic linker.
209 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
210 ErrorOr<std::unique_ptr<object::ObjectFile>> LoadedObject =
211 object::ObjectFile::createObjectFile(ObjectToLoad->getMemBufferRef());
212 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L =
213 Dyld.loadObject(*LoadedObject.get());
216 report_fatal_error(Dyld.getErrorString());
218 NotifyObjectEmitted(*LoadedObject.get(), *L);
220 Buffers.push_back(std::move(ObjectToLoad));
221 LoadedObjects.push_back(std::move(*LoadedObject));
223 OwnedModules.markModuleAsLoaded(M);
226 void MCJIT::finalizeLoadedModules() {
227 MutexGuard locked(lock);
229 // Resolve any outstanding relocations.
230 Dyld.resolveRelocations();
232 OwnedModules.markAllLoadedModulesAsFinalized();
234 // Register EH frame data for any module we own which has been loaded
235 Dyld.registerEHFrames();
237 // Set page permissions.
238 MemMgr->finalizeMemory();
241 // FIXME: Rename this.
242 void MCJIT::finalizeObject() {
243 MutexGuard locked(lock);
245 // Generate code for module is going to move objects out of the 'added' list,
246 // so we need to copy that out before using it:
247 SmallVector<Module*, 16> ModsToAdd;
248 for (auto M : OwnedModules.added())
249 ModsToAdd.push_back(M);
251 for (auto M : ModsToAdd)
252 generateCodeForModule(M);
254 finalizeLoadedModules();
257 void MCJIT::finalizeModule(Module *M) {
258 MutexGuard locked(lock);
260 // This must be a module which has already been added to this MCJIT instance.
261 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
263 // If the module hasn't been compiled, just do that.
264 if (!OwnedModules.hasModuleBeenLoaded(M))
265 generateCodeForModule(M);
267 finalizeLoadedModules();
270 RuntimeDyld::SymbolInfo MCJIT::findExistingSymbol(const std::string &Name) {
271 SmallString<128> FullName;
272 Mangler::getNameWithPrefix(FullName, Name, getDataLayout());
273 return Dyld.getSymbol(FullName);
276 Module *MCJIT::findModuleForSymbol(const std::string &Name,
277 bool CheckFunctionsOnly) {
278 MutexGuard locked(lock);
280 // If it hasn't already been generated, see if it's in one of our modules.
281 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
282 E = OwnedModules.end_added();
285 Function *F = M->getFunction(Name);
286 if (F && !F->isDeclaration())
288 if (!CheckFunctionsOnly) {
289 GlobalVariable *G = M->getGlobalVariable(Name);
290 if (G && !G->isDeclaration())
292 // FIXME: Do we need to worry about global aliases?
295 // We didn't find the symbol in any of our modules.
299 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
300 bool CheckFunctionsOnly) {
301 return findSymbol(Name, CheckFunctionsOnly).getAddress();
304 RuntimeDyld::SymbolInfo MCJIT::findSymbol(const std::string &Name,
305 bool CheckFunctionsOnly) {
306 MutexGuard locked(lock);
308 // First, check to see if we already have this symbol.
309 if (auto Sym = findExistingSymbol(Name))
312 for (object::OwningBinary<object::Archive> &OB : Archives) {
313 object::Archive *A = OB.getBinary();
314 // Look for our symbols in each Archive
315 object::Archive::child_iterator ChildIt = A->findSym(Name);
316 if (ChildIt != A->child_end()) {
317 // FIXME: Support nested archives?
318 ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
319 ChildIt->getAsBinary();
320 if (ChildBinOrErr.getError())
322 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
323 if (ChildBin->isObject()) {
324 std::unique_ptr<object::ObjectFile> OF(
325 static_cast<object::ObjectFile *>(ChildBin.release()));
326 // This causes the object file to be loaded.
327 addObjectFile(std::move(OF));
328 // The address should be here now.
329 if (auto Sym = findExistingSymbol(Name))
335 // If it hasn't already been generated, see if it's in one of our modules.
336 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
338 generateCodeForModule(M);
340 // Check the RuntimeDyld table again, it should be there now.
341 return findExistingSymbol(Name);
344 // If a LazyFunctionCreator is installed, use it to get/create the function.
345 // FIXME: Should we instead have a LazySymbolCreator callback?
346 if (LazyFunctionCreator) {
347 auto Addr = static_cast<uint64_t>(
348 reinterpret_cast<uintptr_t>(LazyFunctionCreator(Name)));
349 return RuntimeDyld::SymbolInfo(Addr, JITSymbolFlags::Exported);
355 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
356 MutexGuard locked(lock);
357 uint64_t Result = getSymbolAddress(Name, false);
359 finalizeLoadedModules();
363 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
364 MutexGuard locked(lock);
365 uint64_t Result = getSymbolAddress(Name, true);
367 finalizeLoadedModules();
371 // Deprecated. Use getFunctionAddress instead.
372 void *MCJIT::getPointerToFunction(Function *F) {
373 MutexGuard locked(lock);
376 SmallString<128> Name;
377 TM->getNameWithPrefix(Name, F, Mang);
379 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
380 bool AbortOnFailure = !F->hasExternalWeakLinkage();
381 void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
382 updateGlobalMapping(F, Addr);
386 Module *M = F->getParent();
387 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
389 // Make sure the relevant module has been compiled and loaded.
390 if (HasBeenAddedButNotLoaded)
391 generateCodeForModule(M);
392 else if (!OwnedModules.hasModuleBeenLoaded(M)) {
393 // If this function doesn't belong to one of our modules, we're done.
394 // FIXME: Asking for the pointer to a function that hasn't been registered,
395 // and isn't a declaration (which is handled above) should probably
400 // FIXME: Should the Dyld be retaining module information? Probably not.
402 // This is the accessor for the target address, so make sure to check the
403 // load address of the symbol, not the local address.
404 return (void*)Dyld.getSymbol(Name).getAddress();
407 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
408 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
409 for (; I != E; ++I) {
410 ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
414 void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
415 // Execute global ctors/dtors for each module in the program.
416 runStaticConstructorsDestructorsInModulePtrSet(
417 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
418 runStaticConstructorsDestructorsInModulePtrSet(
419 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
420 runStaticConstructorsDestructorsInModulePtrSet(
421 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
424 Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
425 ModulePtrSet::iterator I,
426 ModulePtrSet::iterator E) {
427 for (; I != E; ++I) {
428 Function *F = (*I)->getFunction(FnName);
429 if (F && !F->isDeclaration())
435 GlobalVariable *MCJIT::FindGlobalVariableNamedInModulePtrSet(const char *Name,
437 ModulePtrSet::iterator I,
438 ModulePtrSet::iterator E) {
439 for (; I != E; ++I) {
440 GlobalVariable *GV = (*I)->getGlobalVariable(Name, AllowInternal);
441 if (GV && !GV->isDeclaration())
448 Function *MCJIT::FindFunctionNamed(const char *FnName) {
449 Function *F = FindFunctionNamedInModulePtrSet(
450 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
452 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
453 OwnedModules.end_loaded());
455 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
456 OwnedModules.end_finalized());
460 GlobalVariable *MCJIT::FindGlobalVariableNamed(const char *Name, bool AllowInternal) {
461 GlobalVariable *GV = FindGlobalVariableNamedInModulePtrSet(
462 Name, AllowInternal, OwnedModules.begin_added(), OwnedModules.end_added());
464 GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_loaded(),
465 OwnedModules.end_loaded());
467 GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_finalized(),
468 OwnedModules.end_finalized());
472 GenericValue MCJIT::runFunction(Function *F, ArrayRef<GenericValue> ArgValues) {
473 assert(F && "Function *F was null at entry to run()");
475 void *FPtr = getPointerToFunction(F);
476 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
477 FunctionType *FTy = F->getFunctionType();
478 Type *RetTy = FTy->getReturnType();
480 assert((FTy->getNumParams() == ArgValues.size() ||
481 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
482 "Wrong number of arguments passed into function!");
483 assert(FTy->getNumParams() == ArgValues.size() &&
484 "This doesn't support passing arguments through varargs (yet)!");
486 // Handle some common cases first. These cases correspond to common `main'
488 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
489 switch (ArgValues.size()) {
491 if (FTy->getParamType(0)->isIntegerTy(32) &&
492 FTy->getParamType(1)->isPointerTy() &&
493 FTy->getParamType(2)->isPointerTy()) {
494 int (*PF)(int, char **, const char **) =
495 (int(*)(int, char **, const char **))(intptr_t)FPtr;
497 // Call the function.
499 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
500 (char **)GVTOP(ArgValues[1]),
501 (const char **)GVTOP(ArgValues[2])));
506 if (FTy->getParamType(0)->isIntegerTy(32) &&
507 FTy->getParamType(1)->isPointerTy()) {
508 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
510 // Call the function.
512 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
513 (char **)GVTOP(ArgValues[1])));
518 if (FTy->getNumParams() == 1 &&
519 FTy->getParamType(0)->isIntegerTy(32)) {
521 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
522 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
529 // Handle cases where no arguments are passed first.
530 if (ArgValues.empty()) {
532 switch (RetTy->getTypeID()) {
533 default: llvm_unreachable("Unknown return type for function call!");
534 case Type::IntegerTyID: {
535 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
537 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
538 else if (BitWidth <= 8)
539 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
540 else if (BitWidth <= 16)
541 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
542 else if (BitWidth <= 32)
543 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
544 else if (BitWidth <= 64)
545 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
547 llvm_unreachable("Integer types > 64 bits not supported");
551 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
553 case Type::FloatTyID:
554 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
556 case Type::DoubleTyID:
557 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
559 case Type::X86_FP80TyID:
560 case Type::FP128TyID:
561 case Type::PPC_FP128TyID:
562 llvm_unreachable("long double not supported yet");
563 case Type::PointerTyID:
564 return PTOGV(((void*(*)())(intptr_t)FPtr)());
568 llvm_unreachable("Full-featured argument passing not supported yet!");
571 void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
572 if (!isSymbolSearchingDisabled()) {
574 reinterpret_cast<void*>(
575 static_cast<uintptr_t>(Resolver.findSymbol(Name).getAddress()));
580 /// If a LazyFunctionCreator is installed, use it to get/create the function.
581 if (LazyFunctionCreator)
582 if (void *RP = LazyFunctionCreator(Name))
585 if (AbortOnFailure) {
586 report_fatal_error("Program used external function '"+Name+
587 "' which could not be resolved!");
592 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
595 MutexGuard locked(lock);
596 EventListeners.push_back(L);
599 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
602 MutexGuard locked(lock);
603 auto I = std::find(EventListeners.rbegin(), EventListeners.rend(), L);
604 if (I != EventListeners.rend()) {
605 std::swap(*I, EventListeners.back());
606 EventListeners.pop_back();
610 void MCJIT::NotifyObjectEmitted(const object::ObjectFile& Obj,
611 const RuntimeDyld::LoadedObjectInfo &L) {
612 MutexGuard locked(lock);
613 MemMgr->notifyObjectLoaded(this, Obj);
614 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
615 EventListeners[I]->NotifyObjectEmitted(Obj, L);
619 void MCJIT::NotifyFreeingObject(const object::ObjectFile& Obj) {
620 MutexGuard locked(lock);
621 for (JITEventListener *L : EventListeners)
622 L->NotifyFreeingObject(Obj);
625 RuntimeDyld::SymbolInfo
626 LinkingSymbolResolver::findSymbol(const std::string &Name) {
627 auto Result = ParentEngine.findSymbol(Name, false);
628 // If the symbols wasn't found and it begins with an underscore, try again
629 // without the underscore.
630 if (!Result && Name[0] == '_')
631 Result = ParentEngine.findSymbol(Name.substr(1), false);
634 if (ParentEngine.isSymbolSearchingDisabled())
636 return ClientResolver->findSymbol(Name);