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"
36 static struct RegisterJIT {
37 RegisterJIT() { MCJIT::Register(); }
42 extern "C" void LLVMLinkInMCJIT() {
45 ExecutionEngine *MCJIT::createJIT(Module *M,
46 std::string *ErrorStr,
47 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());
57 MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM)
58 : ExecutionEngine(m), TM(tm), Ctx(nullptr), MemMgr(this, MM), Dyld(&MemMgr),
61 OwnedModules.addModule(m);
62 setDataLayout(TM->getDataLayout());
66 MutexGuard locked(lock);
67 // FIXME: We are managing our modules, so we do not want the base class
68 // ExecutionEngine to manage them as well. To avoid double destruction
69 // of the first (and only) module added in ExecutionEngine constructor
70 // we remove it from EE and will destruct it ourselves.
72 // It may make sense to move our module manager (based on SmallStPtr) back
73 // into EE if the JIT and Interpreter can live with it.
74 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
75 // runStaticConstructorsDestructors could be moved back to EE as well.
78 Dyld.deregisterEHFrames();
80 LoadedObjectList::iterator it, end;
81 for (it = LoadedObjects.begin(), end = LoadedObjects.end(); it != end; ++it) {
82 ObjectImage *Obj = *it;
84 NotifyFreeingObject(*Obj);
88 LoadedObjects.clear();
91 for (object::Archive *A : Archives)
99 void MCJIT::addModule(Module *M) {
100 MutexGuard locked(lock);
101 OwnedModules.addModule(M);
104 bool MCJIT::removeModule(Module *M) {
105 MutexGuard locked(lock);
106 return OwnedModules.removeModule(M);
111 void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
112 ObjectImage *LoadedObject = Dyld.loadObject(std::move(Obj));
113 if (!LoadedObject || Dyld.hasError())
114 report_fatal_error(Dyld.getErrorString());
116 LoadedObjects.push_back(LoadedObject);
118 NotifyObjectEmitted(*LoadedObject);
121 void MCJIT::addArchive(object::Archive *A) {
122 Archives.push_back(A);
126 void MCJIT::setObjectCache(ObjectCache* NewCache) {
127 MutexGuard locked(lock);
131 ObjectBufferStream* MCJIT::emitObject(Module *M) {
132 MutexGuard locked(lock);
134 // This must be a module which has already been added but not loaded to this
135 // MCJIT instance, since these conditions are tested by our caller,
136 // generateCodeForModule.
140 M->setDataLayout(TM->getDataLayout());
141 PM.add(new DataLayoutPass(M));
143 // The RuntimeDyld will take ownership of this shortly
144 std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
146 // Turn the machine code intermediate representation into bytes in memory
147 // that may be executed.
148 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
149 !getVerifyModules())) {
150 report_fatal_error("Target does not support MC emission!");
153 // Initialize passes.
155 // Flush the output buffer to get the generated code into memory
156 CompiledObject->flush();
158 // If we have an object cache, tell it about the new object.
159 // Note that we're using the compiled image, not the loaded image (as below).
161 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
162 // to create a temporary object here and delete it after the call.
163 std::unique_ptr<MemoryBuffer> MB(CompiledObject->getMemBuffer());
164 ObjCache->notifyObjectCompiled(M, MB.get());
167 return CompiledObject.release();
170 void MCJIT::generateCodeForModule(Module *M) {
171 // Get a thread lock to make sure we aren't trying to load multiple times
172 MutexGuard locked(lock);
174 // This must be a module which has already been added to this MCJIT instance.
175 assert(OwnedModules.ownsModule(M) &&
176 "MCJIT::generateCodeForModule: Unknown module.");
178 // Re-compilation is not supported
179 if (OwnedModules.hasModuleBeenLoaded(M))
182 std::unique_ptr<ObjectBuffer> ObjectToLoad;
183 // Try to load the pre-compiled object from cache if possible
185 std::unique_ptr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
186 if (PreCompiledObject.get())
187 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.release()));
190 // If the cache did not contain a suitable object, compile the object
192 ObjectToLoad.reset(emitObject(M));
193 assert(ObjectToLoad.get() && "Compilation did not produce an object.");
196 // Load the object into the dynamic linker.
197 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
198 ObjectImage *LoadedObject = Dyld.loadObject(ObjectToLoad.release());
199 LoadedObjects.push_back(LoadedObject);
201 report_fatal_error(Dyld.getErrorString());
203 // FIXME: Make this optional, maybe even move it to a JIT event listener
204 LoadedObject->registerWithDebugger();
206 NotifyObjectEmitted(*LoadedObject);
208 OwnedModules.markModuleAsLoaded(M);
211 void MCJIT::finalizeLoadedModules() {
212 MutexGuard locked(lock);
214 // Resolve any outstanding relocations.
215 Dyld.resolveRelocations();
217 OwnedModules.markAllLoadedModulesAsFinalized();
219 // Register EH frame data for any module we own which has been loaded
220 Dyld.registerEHFrames();
222 // Set page permissions.
223 MemMgr.finalizeMemory();
226 // FIXME: Rename this.
227 void MCJIT::finalizeObject() {
228 MutexGuard locked(lock);
230 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
231 E = OwnedModules.end_added();
234 generateCodeForModule(M);
237 finalizeLoadedModules();
240 void MCJIT::finalizeModule(Module *M) {
241 MutexGuard locked(lock);
243 // This must be a module which has already been added to this MCJIT instance.
244 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
246 // If the module hasn't been compiled, just do that.
247 if (!OwnedModules.hasModuleBeenLoaded(M))
248 generateCodeForModule(M);
250 finalizeLoadedModules();
253 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
254 report_fatal_error("not yet implemented");
257 uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
258 Mangler Mang(TM->getDataLayout());
259 SmallString<128> FullName;
260 Mang.getNameWithPrefix(FullName, Name);
261 return Dyld.getSymbolLoadAddress(FullName);
264 Module *MCJIT::findModuleForSymbol(const std::string &Name,
265 bool CheckFunctionsOnly) {
266 MutexGuard locked(lock);
268 // If it hasn't already been generated, see if it's in one of our modules.
269 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
270 E = OwnedModules.end_added();
273 Function *F = M->getFunction(Name);
274 if (F && !F->isDeclaration())
276 if (!CheckFunctionsOnly) {
277 GlobalVariable *G = M->getGlobalVariable(Name);
278 if (G && !G->isDeclaration())
280 // FIXME: Do we need to worry about global aliases?
283 // We didn't find the symbol in any of our modules.
287 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
288 bool CheckFunctionsOnly)
290 MutexGuard locked(lock);
292 // First, check to see if we already have this symbol.
293 uint64_t Addr = getExistingSymbolAddress(Name);
297 for (object::Archive *A : Archives) {
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);
325 generateCodeForModule(M);
327 // Check the RuntimeDyld table again, it should be there now.
328 return getExistingSymbolAddress(Name);
331 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
332 MutexGuard locked(lock);
333 uint64_t Result = getSymbolAddress(Name, false);
335 finalizeLoadedModules();
339 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
340 MutexGuard locked(lock);
341 uint64_t Result = getSymbolAddress(Name, true);
343 finalizeLoadedModules();
347 // Deprecated. Use getFunctionAddress instead.
348 void *MCJIT::getPointerToFunction(Function *F) {
349 MutexGuard locked(lock);
351 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
352 bool AbortOnFailure = !F->hasExternalWeakLinkage();
353 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
354 addGlobalMapping(F, Addr);
358 Module *M = F->getParent();
359 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
361 // Make sure the relevant module has been compiled and loaded.
362 if (HasBeenAddedButNotLoaded)
363 generateCodeForModule(M);
364 else if (!OwnedModules.hasModuleBeenLoaded(M))
365 // If this function doesn't belong to one of our modules, we're done.
368 // FIXME: Should the Dyld be retaining module information? Probably not.
370 // This is the accessor for the target address, so make sure to check the
371 // load address of the symbol, not the local address.
372 Mangler Mang(TM->getDataLayout());
373 SmallString<128> Name;
374 TM->getNameWithPrefix(Name, F, Mang);
375 return (void*)Dyld.getSymbolLoadAddress(Name);
378 void *MCJIT::recompileAndRelinkFunction(Function *F) {
379 report_fatal_error("not yet implemented");
382 void MCJIT::freeMachineCodeForFunction(Function *F) {
383 report_fatal_error("not yet implemented");
386 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
387 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
388 for (; I != E; ++I) {
389 ExecutionEngine::runStaticConstructorsDestructors(*I, isDtors);
393 void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
394 // Execute global ctors/dtors for each module in the program.
395 runStaticConstructorsDestructorsInModulePtrSet(
396 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
397 runStaticConstructorsDestructorsInModulePtrSet(
398 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
399 runStaticConstructorsDestructorsInModulePtrSet(
400 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
403 Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
404 ModulePtrSet::iterator I,
405 ModulePtrSet::iterator E) {
406 for (; I != E; ++I) {
407 if (Function *F = (*I)->getFunction(FnName))
413 Function *MCJIT::FindFunctionNamed(const char *FnName) {
414 Function *F = FindFunctionNamedInModulePtrSet(
415 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
417 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
418 OwnedModules.end_loaded());
420 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
421 OwnedModules.end_finalized());
425 GenericValue MCJIT::runFunction(Function *F,
426 const std::vector<GenericValue> &ArgValues) {
427 assert(F && "Function *F was null at entry to run()");
429 void *FPtr = getPointerToFunction(F);
430 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
431 FunctionType *FTy = F->getFunctionType();
432 Type *RetTy = FTy->getReturnType();
434 assert((FTy->getNumParams() == ArgValues.size() ||
435 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
436 "Wrong number of arguments passed into function!");
437 assert(FTy->getNumParams() == ArgValues.size() &&
438 "This doesn't support passing arguments through varargs (yet)!");
440 // Handle some common cases first. These cases correspond to common `main'
442 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
443 switch (ArgValues.size()) {
445 if (FTy->getParamType(0)->isIntegerTy(32) &&
446 FTy->getParamType(1)->isPointerTy() &&
447 FTy->getParamType(2)->isPointerTy()) {
448 int (*PF)(int, char **, const char **) =
449 (int(*)(int, char **, const char **))(intptr_t)FPtr;
451 // Call the function.
453 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
454 (char **)GVTOP(ArgValues[1]),
455 (const char **)GVTOP(ArgValues[2])));
460 if (FTy->getParamType(0)->isIntegerTy(32) &&
461 FTy->getParamType(1)->isPointerTy()) {
462 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
464 // Call the function.
466 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
467 (char **)GVTOP(ArgValues[1])));
472 if (FTy->getNumParams() == 1 &&
473 FTy->getParamType(0)->isIntegerTy(32)) {
475 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
476 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
483 // Handle cases where no arguments are passed first.
484 if (ArgValues.empty()) {
486 switch (RetTy->getTypeID()) {
487 default: llvm_unreachable("Unknown return type for function call!");
488 case Type::IntegerTyID: {
489 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
491 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
492 else if (BitWidth <= 8)
493 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
494 else if (BitWidth <= 16)
495 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
496 else if (BitWidth <= 32)
497 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
498 else if (BitWidth <= 64)
499 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
501 llvm_unreachable("Integer types > 64 bits not supported");
505 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
507 case Type::FloatTyID:
508 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
510 case Type::DoubleTyID:
511 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
513 case Type::X86_FP80TyID:
514 case Type::FP128TyID:
515 case Type::PPC_FP128TyID:
516 llvm_unreachable("long double not supported yet");
517 case Type::PointerTyID:
518 return PTOGV(((void*(*)())(intptr_t)FPtr)());
522 llvm_unreachable("Full-featured argument passing not supported yet!");
525 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
526 bool AbortOnFailure) {
527 if (!isSymbolSearchingDisabled()) {
528 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
533 /// If a LazyFunctionCreator is installed, use it to get/create the function.
534 if (LazyFunctionCreator)
535 if (void *RP = LazyFunctionCreator(Name))
538 if (AbortOnFailure) {
539 report_fatal_error("Program used external function '"+Name+
540 "' which could not be resolved!");
545 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
548 MutexGuard locked(lock);
549 EventListeners.push_back(L);
551 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
554 MutexGuard locked(lock);
555 SmallVector<JITEventListener*, 2>::reverse_iterator I=
556 std::find(EventListeners.rbegin(), EventListeners.rend(), L);
557 if (I != EventListeners.rend()) {
558 std::swap(*I, EventListeners.back());
559 EventListeners.pop_back();
562 void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
563 MutexGuard locked(lock);
564 MemMgr.notifyObjectLoaded(this, &Obj);
565 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
566 EventListeners[I]->NotifyObjectEmitted(Obj);
569 void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
570 MutexGuard locked(lock);
571 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
572 EventListeners[I]->NotifyFreeingObject(Obj);
576 uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
577 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
578 // If the symbols wasn't found and it begins with an underscore, try again
579 // without the underscore.
580 if (!Result && Name[0] == '_')
581 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
584 return ClientMM->getSymbolAddress(Name);