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/SectionMemoryManager.h"
15 #include "llvm/IR/DataLayout.h"
16 #include "llvm/IR/DerivedTypes.h"
17 #include "llvm/IR/Function.h"
18 #include "llvm/IR/Mangler.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/Object/Archive.h"
22 #include "llvm/Object/ObjectFile.h"
23 #include "llvm/PassManager.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 #include "llvm/Target/TargetLowering.h"
29 #include "llvm/Target/TargetSubtargetInfo.h"
33 void ObjectCache::anchor() {}
37 static struct RegisterJIT {
38 RegisterJIT() { MCJIT::Register(); }
43 extern "C" void LLVMLinkInMCJIT() {
46 ExecutionEngine *MCJIT::createJIT(std::unique_ptr<Module> M,
47 std::string *ErrorStr,
48 RTDyldMemoryManager *MemMgr,
49 std::unique_ptr<TargetMachine> TM) {
50 // Try to register the program as a source of symbols to resolve against.
52 // FIXME: Don't do this here.
53 sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
55 return new MCJIT(std::move(M), std::move(TM),
56 MemMgr ? MemMgr : new SectionMemoryManager());
59 MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> tm,
60 RTDyldMemoryManager *MM)
61 : ExecutionEngine(std::move(M)), TM(std::move(tm)), Ctx(nullptr),
62 MemMgr(this, MM), Dyld(&MemMgr), ObjCache(nullptr) {
63 // FIXME: We are managing our modules, so we do not want the base class
64 // ExecutionEngine to manage them as well. To avoid double destruction
65 // of the first (and only) module added in ExecutionEngine constructor
66 // we remove it from EE and will destruct it ourselves.
68 // It may make sense to move our module manager (based on SmallStPtr) back
69 // into EE if the JIT and Interpreter can live with it.
70 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
71 // runStaticConstructorsDestructors could be moved back to EE as well.
73 std::unique_ptr<Module> First = std::move(Modules[0]);
76 OwnedModules.addModule(std::move(First));
77 setDataLayout(TM->getSubtargetImpl()->getDataLayout());
78 RegisterJITEventListener(JITEventListener::createGDBRegistrationListener());
82 MutexGuard locked(lock);
84 Dyld.deregisterEHFrames();
86 for (auto &Obj : LoadedObjects)
88 NotifyFreeingObject(*Obj);
93 void MCJIT::addModule(std::unique_ptr<Module> M) {
94 MutexGuard locked(lock);
95 OwnedModules.addModule(std::move(M));
98 bool MCJIT::removeModule(Module *M) {
99 MutexGuard locked(lock);
100 return OwnedModules.removeModule(M);
103 void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
104 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L = Dyld.loadObject(*Obj);
106 report_fatal_error(Dyld.getErrorString());
108 NotifyObjectEmitted(*Obj, *L);
110 LoadedObjects.push_back(std::move(Obj));
113 void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
114 std::unique_ptr<object::ObjectFile> ObjFile;
115 std::unique_ptr<MemoryBuffer> MemBuf;
116 std::tie(ObjFile, MemBuf) = Obj.takeBinary();
117 addObjectFile(std::move(ObjFile));
118 Buffers.push_back(std::move(MemBuf));
121 void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
122 Archives.push_back(std::move(A));
125 void MCJIT::setObjectCache(ObjectCache* NewCache) {
126 MutexGuard locked(lock);
130 std::unique_ptr<MemoryBuffer> MCJIT::emitObject(Module *M) {
131 MutexGuard locked(lock);
133 // This must be a module which has already been added but not loaded to this
134 // MCJIT instance, since these conditions are tested by our caller,
135 // generateCodeForModule.
139 M->setDataLayout(TM->getSubtargetImpl()->getDataLayout());
140 PM.add(new DataLayoutPass());
142 // The RuntimeDyld will take ownership of this shortly
143 SmallVector<char, 4096> ObjBufferSV;
144 raw_svector_ostream ObjStream(ObjBufferSV);
146 // Turn the machine code intermediate representation into bytes in memory
147 // that may be executed.
148 if (TM->addPassesToEmitMC(PM, Ctx, ObjStream, !getVerifyModules()))
149 report_fatal_error("Target does not support MC emission!");
151 // Initialize passes.
153 // Flush the output buffer to get the generated code into memory
156 std::unique_ptr<MemoryBuffer> CompiledObjBuffer(
157 new ObjectMemoryBuffer(std::move(ObjBufferSV)));
159 // If we have an object cache, tell it about the new object.
160 // Note that we're using the compiled image, not the loaded image (as below).
162 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
163 // to create a temporary object here and delete it after the call.
164 MemoryBufferRef MB = CompiledObjBuffer->getMemBufferRef();
165 ObjCache->notifyObjectCompiled(M, MB);
168 return CompiledObjBuffer;
171 void MCJIT::generateCodeForModule(Module *M) {
172 // Get a thread lock to make sure we aren't trying to load multiple times
173 MutexGuard locked(lock);
175 // This must be a module which has already been added to this MCJIT instance.
176 assert(OwnedModules.ownsModule(M) &&
177 "MCJIT::generateCodeForModule: Unknown module.");
179 // Re-compilation is not supported
180 if (OwnedModules.hasModuleBeenLoaded(M))
183 std::unique_ptr<MemoryBuffer> ObjectToLoad;
184 // Try to load the pre-compiled object from cache if possible
186 ObjectToLoad = ObjCache->getObject(M);
188 // If the cache did not contain a suitable object, compile the object
190 ObjectToLoad = emitObject(M);
191 assert(ObjectToLoad && "Compilation did not produce an object.");
194 // Load the object into the dynamic linker.
195 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
196 ErrorOr<std::unique_ptr<object::ObjectFile>> LoadedObject =
197 object::ObjectFile::createObjectFile(ObjectToLoad->getMemBufferRef());
198 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L =
199 Dyld.loadObject(*LoadedObject.get());
202 report_fatal_error(Dyld.getErrorString());
204 NotifyObjectEmitted(*LoadedObject.get(), *L);
206 Buffers.push_back(std::move(ObjectToLoad));
207 LoadedObjects.push_back(std::move(*LoadedObject));
209 OwnedModules.markModuleAsLoaded(M);
212 void MCJIT::finalizeLoadedModules() {
213 MutexGuard locked(lock);
215 // Resolve any outstanding relocations.
216 Dyld.resolveRelocations();
218 OwnedModules.markAllLoadedModulesAsFinalized();
220 // Register EH frame data for any module we own which has been loaded
221 Dyld.registerEHFrames();
223 // Set page permissions.
224 MemMgr.finalizeMemory();
227 // FIXME: Rename this.
228 void MCJIT::finalizeObject() {
229 MutexGuard locked(lock);
231 // Generate code for module is going to move objects out of the 'added' list,
232 // so we need to copy that out before using it:
233 SmallVector<Module*, 16> ModsToAdd;
234 for (auto M : OwnedModules.added())
235 ModsToAdd.push_back(M);
237 for (auto M : ModsToAdd)
238 generateCodeForModule(M);
240 finalizeLoadedModules();
243 void MCJIT::finalizeModule(Module *M) {
244 MutexGuard locked(lock);
246 // This must be a module which has already been added to this MCJIT instance.
247 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
249 // If the module hasn't been compiled, just do that.
250 if (!OwnedModules.hasModuleBeenLoaded(M))
251 generateCodeForModule(M);
253 finalizeLoadedModules();
256 uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
257 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
258 SmallString<128> FullName;
259 Mang.getNameWithPrefix(FullName, Name);
260 return Dyld.getSymbolLoadAddress(FullName);
263 Module *MCJIT::findModuleForSymbol(const std::string &Name,
264 bool CheckFunctionsOnly) {
265 MutexGuard locked(lock);
267 // If it hasn't already been generated, see if it's in one of our modules.
268 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
269 E = OwnedModules.end_added();
272 Function *F = M->getFunction(Name);
273 if (F && !F->isDeclaration())
275 if (!CheckFunctionsOnly) {
276 GlobalVariable *G = M->getGlobalVariable(Name);
277 if (G && !G->isDeclaration())
279 // FIXME: Do we need to worry about global aliases?
282 // We didn't find the symbol in any of our modules.
286 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
287 bool CheckFunctionsOnly)
289 MutexGuard locked(lock);
291 // First, check to see if we already have this symbol.
292 uint64_t Addr = getExistingSymbolAddress(Name);
296 for (object::OwningBinary<object::Archive> &OB : Archives) {
297 object::Archive *A = OB.getBinary();
298 // Look for our symbols in each Archive
299 object::Archive::child_iterator ChildIt = A->findSym(Name);
300 if (ChildIt != A->child_end()) {
301 // FIXME: Support nested archives?
302 ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
303 ChildIt->getAsBinary();
304 if (ChildBinOrErr.getError())
306 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
307 if (ChildBin->isObject()) {
308 std::unique_ptr<object::ObjectFile> OF(
309 static_cast<object::ObjectFile *>(ChildBin.release()));
310 // This causes the object file to be loaded.
311 addObjectFile(std::move(OF));
312 // The address should be here now.
313 Addr = getExistingSymbolAddress(Name);
320 // If it hasn't already been generated, see if it's in one of our modules.
321 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
323 generateCodeForModule(M);
325 // Check the RuntimeDyld table again, it should be there now.
326 return getExistingSymbolAddress(Name);
329 // If a LazyFunctionCreator is installed, use it to get/create the function.
330 // FIXME: Should we instead have a LazySymbolCreator callback?
331 if (LazyFunctionCreator)
332 Addr = (uint64_t)LazyFunctionCreator(Name);
337 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
338 MutexGuard locked(lock);
339 uint64_t Result = getSymbolAddress(Name, false);
341 finalizeLoadedModules();
345 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
346 MutexGuard locked(lock);
347 uint64_t Result = getSymbolAddress(Name, true);
349 finalizeLoadedModules();
353 // Deprecated. Use getFunctionAddress instead.
354 void *MCJIT::getPointerToFunction(Function *F) {
355 MutexGuard locked(lock);
357 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
358 SmallString<128> Name;
359 TM->getNameWithPrefix(Name, F, Mang);
361 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
362 bool AbortOnFailure = !F->hasExternalWeakLinkage();
363 void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
364 updateGlobalMapping(F, Addr);
368 Module *M = F->getParent();
369 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
371 // Make sure the relevant module has been compiled and loaded.
372 if (HasBeenAddedButNotLoaded)
373 generateCodeForModule(M);
374 else if (!OwnedModules.hasModuleBeenLoaded(M)) {
375 // If this function doesn't belong to one of our modules, we're done.
376 // FIXME: Asking for the pointer to a function that hasn't been registered,
377 // and isn't a declaration (which is handled above) should probably
382 // FIXME: Should the Dyld be retaining module information? Probably not.
384 // This is the accessor for the target address, so make sure to check the
385 // load address of the symbol, not the local address.
386 return (void*)Dyld.getSymbolLoadAddress(Name);
389 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
390 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
391 for (; I != E; ++I) {
392 ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
396 void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
397 // Execute global ctors/dtors for each module in the program.
398 runStaticConstructorsDestructorsInModulePtrSet(
399 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
400 runStaticConstructorsDestructorsInModulePtrSet(
401 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
402 runStaticConstructorsDestructorsInModulePtrSet(
403 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
406 Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
407 ModulePtrSet::iterator I,
408 ModulePtrSet::iterator E) {
409 for (; I != E; ++I) {
410 if (Function *F = (*I)->getFunction(FnName))
416 Function *MCJIT::FindFunctionNamed(const char *FnName) {
417 Function *F = FindFunctionNamedInModulePtrSet(
418 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
420 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
421 OwnedModules.end_loaded());
423 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
424 OwnedModules.end_finalized());
428 GenericValue MCJIT::runFunction(Function *F,
429 const std::vector<GenericValue> &ArgValues) {
430 assert(F && "Function *F was null at entry to run()");
432 void *FPtr = getPointerToFunction(F);
433 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
434 FunctionType *FTy = F->getFunctionType();
435 Type *RetTy = FTy->getReturnType();
437 assert((FTy->getNumParams() == ArgValues.size() ||
438 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
439 "Wrong number of arguments passed into function!");
440 assert(FTy->getNumParams() == ArgValues.size() &&
441 "This doesn't support passing arguments through varargs (yet)!");
443 // Handle some common cases first. These cases correspond to common `main'
445 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
446 switch (ArgValues.size()) {
448 if (FTy->getParamType(0)->isIntegerTy(32) &&
449 FTy->getParamType(1)->isPointerTy() &&
450 FTy->getParamType(2)->isPointerTy()) {
451 int (*PF)(int, char **, const char **) =
452 (int(*)(int, char **, const char **))(intptr_t)FPtr;
454 // Call the function.
456 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
457 (char **)GVTOP(ArgValues[1]),
458 (const char **)GVTOP(ArgValues[2])));
463 if (FTy->getParamType(0)->isIntegerTy(32) &&
464 FTy->getParamType(1)->isPointerTy()) {
465 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
467 // Call the function.
469 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
470 (char **)GVTOP(ArgValues[1])));
475 if (FTy->getNumParams() == 1 &&
476 FTy->getParamType(0)->isIntegerTy(32)) {
478 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
479 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
486 // Handle cases where no arguments are passed first.
487 if (ArgValues.empty()) {
489 switch (RetTy->getTypeID()) {
490 default: llvm_unreachable("Unknown return type for function call!");
491 case Type::IntegerTyID: {
492 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
494 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
495 else if (BitWidth <= 8)
496 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
497 else if (BitWidth <= 16)
498 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
499 else if (BitWidth <= 32)
500 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
501 else if (BitWidth <= 64)
502 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
504 llvm_unreachable("Integer types > 64 bits not supported");
508 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
510 case Type::FloatTyID:
511 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
513 case Type::DoubleTyID:
514 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
516 case Type::X86_FP80TyID:
517 case Type::FP128TyID:
518 case Type::PPC_FP128TyID:
519 llvm_unreachable("long double not supported yet");
520 case Type::PointerTyID:
521 return PTOGV(((void*(*)())(intptr_t)FPtr)());
525 llvm_unreachable("Full-featured argument passing not supported yet!");
528 void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
529 if (!isSymbolSearchingDisabled()) {
530 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
535 /// If a LazyFunctionCreator is installed, use it to get/create the function.
536 if (LazyFunctionCreator)
537 if (void *RP = LazyFunctionCreator(Name))
540 if (AbortOnFailure) {
541 report_fatal_error("Program used external function '"+Name+
542 "' which could not be resolved!");
547 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
550 MutexGuard locked(lock);
551 EventListeners.push_back(L);
554 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
557 MutexGuard locked(lock);
558 auto I = std::find(EventListeners.rbegin(), EventListeners.rend(), L);
559 if (I != EventListeners.rend()) {
560 std::swap(*I, EventListeners.back());
561 EventListeners.pop_back();
565 void MCJIT::NotifyObjectEmitted(const object::ObjectFile& Obj,
566 const RuntimeDyld::LoadedObjectInfo &L) {
567 MutexGuard locked(lock);
568 MemMgr.notifyObjectLoaded(this, Obj);
569 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
570 EventListeners[I]->NotifyObjectEmitted(Obj, L);
574 void MCJIT::NotifyFreeingObject(const object::ObjectFile& Obj) {
575 MutexGuard locked(lock);
576 for (JITEventListener *L : EventListeners)
577 L->NotifyFreeingObject(Obj);
580 uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
581 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
582 // If the symbols wasn't found and it begins with an underscore, try again
583 // without the underscore.
584 if (!Result && Name[0] == '_')
585 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
588 if (ParentEngine->isSymbolSearchingDisabled())
590 return ClientMM->getSymbolAddress(Name);