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/Target/TargetLowering.h"
35 static struct RegisterJIT {
36 RegisterJIT() { MCJIT::Register(); }
41 extern "C" void LLVMLinkInMCJIT() {
44 ExecutionEngine *MCJIT::createJIT(Module *M,
45 std::string *ErrorStr,
46 RTDyldMemoryManager *MemMgr,
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(M, TM, MemMgr ? MemMgr : new SectionMemoryManager(),
58 MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM,
59 bool AllocateGVsWithCode)
60 : ExecutionEngine(m), TM(tm), Ctx(nullptr), MemMgr(this, MM), Dyld(&MemMgr),
63 OwnedModules.addModule(m);
64 setDataLayout(TM->getDataLayout());
68 std::lock_guard<std::recursive_mutex> locked(lock);
69 // FIXME: We are managing our modules, so we do not want the base class
70 // ExecutionEngine to manage them as well. To avoid double destruction
71 // of the first (and only) module added in ExecutionEngine constructor
72 // we remove it from EE and will destruct it ourselves.
74 // It may make sense to move our module manager (based on SmallStPtr) back
75 // into EE if the JIT and Interpreter can live with it.
76 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
77 // runStaticConstructorsDestructors could be moved back to EE as well.
80 Dyld.deregisterEHFrames();
82 LoadedObjectList::iterator it, end;
83 for (it = LoadedObjects.begin(), end = LoadedObjects.end(); it != end; ++it) {
84 ObjectImage *Obj = *it;
86 NotifyFreeingObject(*Obj);
90 LoadedObjects.clear();
93 SmallVector<object::Archive *, 2>::iterator ArIt, ArEnd;
94 for (ArIt = Archives.begin(), ArEnd = Archives.end(); ArIt != ArEnd; ++ArIt) {
95 object::Archive *A = *ArIt;
103 void MCJIT::addModule(Module *M) {
104 std::lock_guard<std::recursive_mutex> locked(lock);
105 OwnedModules.addModule(M);
108 bool MCJIT::removeModule(Module *M) {
109 std::lock_guard<std::recursive_mutex> locked(lock);
110 return OwnedModules.removeModule(M);
115 void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
116 ObjectImage *LoadedObject = Dyld.loadObject(std::move(Obj));
117 if (!LoadedObject || Dyld.hasError())
118 report_fatal_error(Dyld.getErrorString());
120 LoadedObjects.push_back(LoadedObject);
122 NotifyObjectEmitted(*LoadedObject);
125 void MCJIT::addArchive(object::Archive *A) {
126 Archives.push_back(A);
130 void MCJIT::setObjectCache(ObjectCache* NewCache) {
131 std::lock_guard<std::recursive_mutex> locked(lock);
135 ObjectBufferStream* MCJIT::emitObject(Module *M) {
136 std::lock_guard<std::recursive_mutex> locked(lock);
138 // This must be a module which has already been added but not loaded to this
139 // MCJIT instance, since these conditions are tested by our caller,
140 // generateCodeForModule.
144 M->setDataLayout(TM->getDataLayout());
145 PM.add(new DataLayoutPass(M));
147 // The RuntimeDyld will take ownership of this shortly
148 std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
150 // Turn the machine code intermediate representation into bytes in memory
151 // that may be executed.
152 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
153 !getVerifyModules())) {
154 report_fatal_error("Target does not support MC emission!");
157 // Initialize passes.
159 // Flush the output buffer to get the generated code into memory
160 CompiledObject->flush();
162 // If we have an object cache, tell it about the new object.
163 // Note that we're using the compiled image, not the loaded image (as below).
165 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
166 // to create a temporary object here and delete it after the call.
167 std::unique_ptr<MemoryBuffer> MB(CompiledObject->getMemBuffer());
168 ObjCache->notifyObjectCompiled(M, MB.get());
171 return CompiledObject.release();
174 void MCJIT::generateCodeForModule(Module *M) {
175 // Get a thread lock to make sure we aren't trying to load multiple times
176 std::lock_guard<std::recursive_mutex> locked(lock);
178 // This must be a module which has already been added to this MCJIT instance.
179 assert(OwnedModules.ownsModule(M) &&
180 "MCJIT::generateCodeForModule: Unknown module.");
182 // Re-compilation is not supported
183 if (OwnedModules.hasModuleBeenLoaded(M))
186 std::unique_ptr<ObjectBuffer> ObjectToLoad;
187 // Try to load the pre-compiled object from cache if possible
189 std::unique_ptr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
190 if (PreCompiledObject.get())
191 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.release()));
194 // If the cache did not contain a suitable object, compile the object
196 ObjectToLoad.reset(emitObject(M));
197 assert(ObjectToLoad.get() && "Compilation did not produce an object.");
200 // Load the object into the dynamic linker.
201 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
202 ObjectImage *LoadedObject = Dyld.loadObject(ObjectToLoad.release());
203 LoadedObjects.push_back(LoadedObject);
205 report_fatal_error(Dyld.getErrorString());
207 // FIXME: Make this optional, maybe even move it to a JIT event listener
208 LoadedObject->registerWithDebugger();
210 NotifyObjectEmitted(*LoadedObject);
212 OwnedModules.markModuleAsLoaded(M);
215 void MCJIT::finalizeLoadedModules() {
216 std::lock_guard<std::recursive_mutex> locked(lock);
218 // Resolve any outstanding relocations.
219 Dyld.resolveRelocations();
221 OwnedModules.markAllLoadedModulesAsFinalized();
223 // Register EH frame data for any module we own which has been loaded
224 Dyld.registerEHFrames();
226 // Set page permissions.
227 MemMgr.finalizeMemory();
230 // FIXME: Rename this.
231 void MCJIT::finalizeObject() {
232 std::lock_guard<std::recursive_mutex> locked(lock);
234 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
235 E = OwnedModules.end_added();
238 generateCodeForModule(M);
241 finalizeLoadedModules();
244 void MCJIT::finalizeModule(Module *M) {
245 std::lock_guard<std::recursive_mutex> locked(lock);
247 // This must be a module which has already been added to this MCJIT instance.
248 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
250 // If the module hasn't been compiled, just do that.
251 if (!OwnedModules.hasModuleBeenLoaded(M))
252 generateCodeForModule(M);
254 finalizeLoadedModules();
257 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
258 report_fatal_error("not yet implemented");
261 uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
262 Mangler Mang(TM->getDataLayout());
263 SmallString<128> FullName;
264 Mang.getNameWithPrefix(FullName, Name);
265 return Dyld.getSymbolLoadAddress(FullName);
268 Module *MCJIT::findModuleForSymbol(const std::string &Name,
269 bool CheckFunctionsOnly) {
270 std::lock_guard<std::recursive_mutex> locked(lock);
272 // If it hasn't already been generated, see if it's in one of our modules.
273 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
274 E = OwnedModules.end_added();
277 Function *F = M->getFunction(Name);
278 if (F && !F->isDeclaration())
280 if (!CheckFunctionsOnly) {
281 GlobalVariable *G = M->getGlobalVariable(Name);
282 if (G && !G->isDeclaration())
284 // FIXME: Do we need to worry about global aliases?
287 // We didn't find the symbol in any of our modules.
291 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
292 bool CheckFunctionsOnly)
294 std::lock_guard<std::recursive_mutex> locked(lock);
296 // First, check to see if we already have this symbol.
297 uint64_t Addr = getExistingSymbolAddress(Name);
301 SmallVector<object::Archive*, 2>::iterator I, E;
302 for (I = Archives.begin(), E = Archives.end(); I != E; ++I) {
303 object::Archive *A = *I;
304 // Look for our symbols in each Archive
305 object::Archive::child_iterator ChildIt = A->findSym(Name);
306 if (ChildIt != A->child_end()) {
307 // FIXME: Support nested archives?
308 ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
309 ChildIt->getAsBinary();
310 if (ChildBinOrErr.getError())
312 std::unique_ptr<object::Binary> ChildBin = std::move(ChildBinOrErr.get());
313 if (ChildBin->isObject()) {
314 std::unique_ptr<object::ObjectFile> OF(
315 static_cast<object::ObjectFile *>(ChildBin.release()));
316 // This causes the object file to be loaded.
317 addObjectFile(std::move(OF));
318 // The address should be here now.
319 Addr = getExistingSymbolAddress(Name);
326 // If it hasn't already been generated, see if it's in one of our modules.
327 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
331 generateCodeForModule(M);
333 // Check the RuntimeDyld table again, it should be there now.
334 return getExistingSymbolAddress(Name);
337 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
338 std::lock_guard<std::recursive_mutex> locked(lock);
339 uint64_t Result = getSymbolAddress(Name, false);
341 finalizeLoadedModules();
345 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
346 std::lock_guard<std::recursive_mutex> locked(lock);
347 uint64_t Result = getSymbolAddress(Name, true);
349 finalizeLoadedModules();
353 // Deprecated. Use getFunctionAddress instead.
354 void *MCJIT::getPointerToFunction(Function *F) {
355 std::lock_guard<std::recursive_mutex> 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->getDataLayout());
379 SmallString<128> Name;
380 TM->getNameWithPrefix(Name, F, Mang);
381 return (void*)Dyld.getSymbolLoadAddress(Name);
384 void *MCJIT::recompileAndRelinkFunction(Function *F) {
385 report_fatal_error("not yet implemented");
388 void MCJIT::freeMachineCodeForFunction(Function *F) {
389 report_fatal_error("not yet implemented");
392 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
393 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
394 for (; I != E; ++I) {
395 ExecutionEngine::runStaticConstructorsDestructors(*I, isDtors);
399 void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
400 // Execute global ctors/dtors for each module in the program.
401 runStaticConstructorsDestructorsInModulePtrSet(
402 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
403 runStaticConstructorsDestructorsInModulePtrSet(
404 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
405 runStaticConstructorsDestructorsInModulePtrSet(
406 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
409 Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
410 ModulePtrSet::iterator I,
411 ModulePtrSet::iterator E) {
412 for (; I != E; ++I) {
413 if (Function *F = (*I)->getFunction(FnName))
419 Function *MCJIT::FindFunctionNamed(const char *FnName) {
420 Function *F = FindFunctionNamedInModulePtrSet(
421 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
423 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
424 OwnedModules.end_loaded());
426 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
427 OwnedModules.end_finalized());
431 GenericValue MCJIT::runFunction(Function *F,
432 const std::vector<GenericValue> &ArgValues) {
433 assert(F && "Function *F was null at entry to run()");
435 void *FPtr = getPointerToFunction(F);
436 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
437 FunctionType *FTy = F->getFunctionType();
438 Type *RetTy = FTy->getReturnType();
440 assert((FTy->getNumParams() == ArgValues.size() ||
441 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
442 "Wrong number of arguments passed into function!");
443 assert(FTy->getNumParams() == ArgValues.size() &&
444 "This doesn't support passing arguments through varargs (yet)!");
446 // Handle some common cases first. These cases correspond to common `main'
448 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
449 switch (ArgValues.size()) {
451 if (FTy->getParamType(0)->isIntegerTy(32) &&
452 FTy->getParamType(1)->isPointerTy() &&
453 FTy->getParamType(2)->isPointerTy()) {
454 int (*PF)(int, char **, const char **) =
455 (int(*)(int, char **, const char **))(intptr_t)FPtr;
457 // Call the function.
459 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
460 (char **)GVTOP(ArgValues[1]),
461 (const char **)GVTOP(ArgValues[2])));
466 if (FTy->getParamType(0)->isIntegerTy(32) &&
467 FTy->getParamType(1)->isPointerTy()) {
468 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
470 // Call the function.
472 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
473 (char **)GVTOP(ArgValues[1])));
478 if (FTy->getNumParams() == 1 &&
479 FTy->getParamType(0)->isIntegerTy(32)) {
481 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
482 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
489 // Handle cases where no arguments are passed first.
490 if (ArgValues.empty()) {
492 switch (RetTy->getTypeID()) {
493 default: llvm_unreachable("Unknown return type for function call!");
494 case Type::IntegerTyID: {
495 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
497 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
498 else if (BitWidth <= 8)
499 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
500 else if (BitWidth <= 16)
501 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
502 else if (BitWidth <= 32)
503 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
504 else if (BitWidth <= 64)
505 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
507 llvm_unreachable("Integer types > 64 bits not supported");
511 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
513 case Type::FloatTyID:
514 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
516 case Type::DoubleTyID:
517 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
519 case Type::X86_FP80TyID:
520 case Type::FP128TyID:
521 case Type::PPC_FP128TyID:
522 llvm_unreachable("long double not supported yet");
523 case Type::PointerTyID:
524 return PTOGV(((void*(*)())(intptr_t)FPtr)());
528 llvm_unreachable("Full-featured argument passing not supported yet!");
531 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
532 bool AbortOnFailure) {
533 if (!isSymbolSearchingDisabled()) {
534 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
539 /// If a LazyFunctionCreator is installed, use it to get/create the function.
540 if (LazyFunctionCreator)
541 if (void *RP = LazyFunctionCreator(Name))
544 if (AbortOnFailure) {
545 report_fatal_error("Program used external function '"+Name+
546 "' which could not be resolved!");
551 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
554 std::lock_guard<std::recursive_mutex> locked(lock);
555 EventListeners.push_back(L);
557 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
560 std::lock_guard<std::recursive_mutex> locked(lock);
561 SmallVector<JITEventListener*, 2>::reverse_iterator I=
562 std::find(EventListeners.rbegin(), EventListeners.rend(), L);
563 if (I != EventListeners.rend()) {
564 std::swap(*I, EventListeners.back());
565 EventListeners.pop_back();
568 void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
569 std::lock_guard<std::recursive_mutex> locked(lock);
570 MemMgr.notifyObjectLoaded(this, &Obj);
571 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
572 EventListeners[I]->NotifyObjectEmitted(Obj);
575 void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
576 std::lock_guard<std::recursive_mutex> locked(lock);
577 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
578 EventListeners[I]->NotifyFreeingObject(Obj);
582 uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
583 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
584 // If the symbols wasn't found and it begins with an underscore, try again
585 // without the underscore.
586 if (!Result && Name[0] == '_')
587 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
590 return ClientMM->getSymbolAddress(Name);