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/JITMemoryManager.h"
14 #include "llvm/ExecutionEngine/MCJIT.h"
15 #include "llvm/ExecutionEngine/ObjectBuffer.h"
16 #include "llvm/ExecutionEngine/ObjectImage.h"
17 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/Mangler.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/Object/Archive.h"
25 #include "llvm/PassManager.h"
26 #include "llvm/Support/DynamicLibrary.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/MutexGuard.h"
30 #include "llvm/Target/TargetLowering.h"
31 #include "llvm/Target/TargetSubtargetInfo.h"
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,
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), TM,
56 MemMgr ? MemMgr : new SectionMemoryManager());
59 MCJIT::MCJIT(std::unique_ptr<Module> M, TargetMachine *tm,
60 RTDyldMemoryManager *MM)
61 : ExecutionEngine(std::move(M)), TM(tm), Ctx(nullptr), MemMgr(this, MM),
62 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());
81 MutexGuard locked(lock);
83 Dyld.deregisterEHFrames();
85 LoadedObjectList::iterator it, end;
86 for (it = LoadedObjects.begin(), end = LoadedObjects.end(); it != end; ++it) {
87 ObjectImage *Obj = *it;
89 NotifyFreeingObject(*Obj);
93 LoadedObjects.clear();
100 void MCJIT::addModule(std::unique_ptr<Module> M) {
101 MutexGuard locked(lock);
102 OwnedModules.addModule(std::move(M));
105 bool MCJIT::removeModule(Module *M) {
106 MutexGuard locked(lock);
107 return OwnedModules.removeModule(M);
110 void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
111 ObjectImage *LoadedObject = Dyld.loadObject(std::move(Obj));
112 if (!LoadedObject || Dyld.hasError())
113 report_fatal_error(Dyld.getErrorString());
115 LoadedObjects.push_back(LoadedObject);
117 NotifyObjectEmitted(*LoadedObject);
120 void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
121 addObjectFile(std::move(Obj.getBinary()));
122 Buffers.push_back(std::move(Obj.getBuffer()));
125 void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
126 Archives.push_back(std::move(A));
129 void MCJIT::setObjectCache(ObjectCache* NewCache) {
130 MutexGuard locked(lock);
134 ObjectBufferStream* MCJIT::emitObject(Module *M) {
135 MutexGuard locked(lock);
137 // This must be a module which has already been added but not loaded to this
138 // MCJIT instance, since these conditions are tested by our caller,
139 // generateCodeForModule.
143 M->setDataLayout(TM->getSubtargetImpl()->getDataLayout());
144 PM.add(new DataLayoutPass(M));
146 // The RuntimeDyld will take ownership of this shortly
147 std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
149 // Turn the machine code intermediate representation into bytes in memory
150 // that may be executed.
151 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
152 !getVerifyModules())) {
153 report_fatal_error("Target does not support MC emission!");
156 // Initialize passes.
158 // Flush the output buffer to get the generated code into memory
159 CompiledObject->flush();
161 // If we have an object cache, tell it about the new object.
162 // Note that we're using the compiled image, not the loaded image (as below).
164 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
165 // to create a temporary object here and delete it after the call.
166 MemoryBufferRef MB = CompiledObject->getMemBuffer();
167 ObjCache->notifyObjectCompiled(M, MB);
170 return CompiledObject.release();
173 void MCJIT::generateCodeForModule(Module *M) {
174 // Get a thread lock to make sure we aren't trying to load multiple times
175 MutexGuard locked(lock);
177 // This must be a module which has already been added to this MCJIT instance.
178 assert(OwnedModules.ownsModule(M) &&
179 "MCJIT::generateCodeForModule: Unknown module.");
181 // Re-compilation is not supported
182 if (OwnedModules.hasModuleBeenLoaded(M))
185 std::unique_ptr<ObjectBuffer> ObjectToLoad;
186 // Try to load the pre-compiled object from cache if possible
188 std::unique_ptr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
189 if (PreCompiledObject.get())
190 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.release()));
193 // If the cache did not contain a suitable object, compile the object
195 ObjectToLoad.reset(emitObject(M));
196 assert(ObjectToLoad.get() && "Compilation did not produce an object.");
199 // Load the object into the dynamic linker.
200 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
201 ObjectImage *LoadedObject = Dyld.loadObject(ObjectToLoad.release());
202 LoadedObjects.push_back(LoadedObject);
204 report_fatal_error(Dyld.getErrorString());
206 // FIXME: Make this optional, maybe even move it to a JIT event listener
207 LoadedObject->registerWithDebugger();
209 NotifyObjectEmitted(*LoadedObject);
211 OwnedModules.markModuleAsLoaded(M);
214 void MCJIT::finalizeLoadedModules() {
215 MutexGuard locked(lock);
217 // Resolve any outstanding relocations.
218 Dyld.resolveRelocations();
220 OwnedModules.markAllLoadedModulesAsFinalized();
222 // Register EH frame data for any module we own which has been loaded
223 Dyld.registerEHFrames();
225 // Set page permissions.
226 MemMgr.finalizeMemory();
229 // FIXME: Rename this.
230 void MCJIT::finalizeObject() {
231 MutexGuard locked(lock);
233 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
234 E = OwnedModules.end_added();
237 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().get();
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 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
358 bool AbortOnFailure = !F->hasExternalWeakLinkage();
359 void *Addr = getPointerToNamedFunction(F->getName(), 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.
374 // FIXME: Should the Dyld be retaining module information? Probably not.
376 // This is the accessor for the target address, so make sure to check the
377 // load address of the symbol, not the local address.
378 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
379 SmallString<128> Name;
380 TM->getNameWithPrefix(Name, F, Mang);
381 return (void*)Dyld.getSymbolLoadAddress(Name);
384 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
385 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
386 for (; I != E; ++I) {
387 ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
391 void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
392 // Execute global ctors/dtors for each module in the program.
393 runStaticConstructorsDestructorsInModulePtrSet(
394 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
395 runStaticConstructorsDestructorsInModulePtrSet(
396 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
397 runStaticConstructorsDestructorsInModulePtrSet(
398 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
401 Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
402 ModulePtrSet::iterator I,
403 ModulePtrSet::iterator E) {
404 for (; I != E; ++I) {
405 if (Function *F = (*I)->getFunction(FnName))
411 Function *MCJIT::FindFunctionNamed(const char *FnName) {
412 Function *F = FindFunctionNamedInModulePtrSet(
413 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
415 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
416 OwnedModules.end_loaded());
418 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
419 OwnedModules.end_finalized());
423 GenericValue MCJIT::runFunction(Function *F,
424 const std::vector<GenericValue> &ArgValues) {
425 assert(F && "Function *F was null at entry to run()");
427 void *FPtr = getPointerToFunction(F);
428 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
429 FunctionType *FTy = F->getFunctionType();
430 Type *RetTy = FTy->getReturnType();
432 assert((FTy->getNumParams() == ArgValues.size() ||
433 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
434 "Wrong number of arguments passed into function!");
435 assert(FTy->getNumParams() == ArgValues.size() &&
436 "This doesn't support passing arguments through varargs (yet)!");
438 // Handle some common cases first. These cases correspond to common `main'
440 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
441 switch (ArgValues.size()) {
443 if (FTy->getParamType(0)->isIntegerTy(32) &&
444 FTy->getParamType(1)->isPointerTy() &&
445 FTy->getParamType(2)->isPointerTy()) {
446 int (*PF)(int, char **, const char **) =
447 (int(*)(int, char **, const char **))(intptr_t)FPtr;
449 // Call the function.
451 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
452 (char **)GVTOP(ArgValues[1]),
453 (const char **)GVTOP(ArgValues[2])));
458 if (FTy->getParamType(0)->isIntegerTy(32) &&
459 FTy->getParamType(1)->isPointerTy()) {
460 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
462 // Call the function.
464 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
465 (char **)GVTOP(ArgValues[1])));
470 if (FTy->getNumParams() == 1 &&
471 FTy->getParamType(0)->isIntegerTy(32)) {
473 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
474 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
481 // Handle cases where no arguments are passed first.
482 if (ArgValues.empty()) {
484 switch (RetTy->getTypeID()) {
485 default: llvm_unreachable("Unknown return type for function call!");
486 case Type::IntegerTyID: {
487 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
489 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
490 else if (BitWidth <= 8)
491 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
492 else if (BitWidth <= 16)
493 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
494 else if (BitWidth <= 32)
495 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
496 else if (BitWidth <= 64)
497 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
499 llvm_unreachable("Integer types > 64 bits not supported");
503 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
505 case Type::FloatTyID:
506 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
508 case Type::DoubleTyID:
509 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
511 case Type::X86_FP80TyID:
512 case Type::FP128TyID:
513 case Type::PPC_FP128TyID:
514 llvm_unreachable("long double not supported yet");
515 case Type::PointerTyID:
516 return PTOGV(((void*(*)())(intptr_t)FPtr)());
520 llvm_unreachable("Full-featured argument passing not supported yet!");
523 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
524 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 (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
569 JITEventListener *L = EventListeners[I];
570 L->NotifyFreeingObject(Obj);
574 uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
575 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
576 // If the symbols wasn't found and it begins with an underscore, try again
577 // without the underscore.
578 if (!Result && Name[0] == '_')
579 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
582 if (ParentEngine->isSymbolSearchingDisabled())
584 return ClientMM->getSymbolAddress(Name);