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,
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(0, NULL);
55 return new MCJIT(M, TM, MemMgr ? MemMgr : new SectionMemoryManager(),
59 MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM,
60 bool AllocateGVsWithCode)
61 : ExecutionEngine(m), TM(tm), Ctx(0), MemMgr(this, MM), Dyld(&MemMgr),
64 OwnedModules.addModule(m);
65 setDataLayout(TM->getDataLayout());
69 MutexGuard locked(lock);
70 // FIXME: We are managing our modules, so we do not want the base class
71 // ExecutionEngine to manage them as well. To avoid double destruction
72 // of the first (and only) module added in ExecutionEngine constructor
73 // we remove it from EE and will destruct it ourselves.
75 // It may make sense to move our module manager (based on SmallStPtr) back
76 // into EE if the JIT and Interpreter can live with it.
77 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
78 // runStaticConstructorsDestructors could be moved back to EE as well.
81 Dyld.deregisterEHFrames();
83 LoadedObjectList::iterator it, end;
84 for (it = LoadedObjects.begin(), end = LoadedObjects.end(); it != end; ++it) {
85 ObjectImage *Obj = *it;
87 NotifyFreeingObject(*Obj);
91 LoadedObjects.clear();
94 SmallVector<object::Archive *, 2>::iterator ArIt, ArEnd;
95 for (ArIt = Archives.begin(), ArEnd = Archives.end(); ArIt != ArEnd; ++ArIt) {
96 object::Archive *A = *ArIt;
104 void MCJIT::addModule(Module *M) {
105 MutexGuard locked(lock);
106 OwnedModules.addModule(M);
109 bool MCJIT::removeModule(Module *M) {
110 MutexGuard locked(lock);
111 return OwnedModules.removeModule(M);
116 void MCJIT::addObjectFile(object::ObjectFile *Obj) {
117 ObjectImage *LoadedObject = Dyld.loadObject(Obj);
119 report_fatal_error(Dyld.getErrorString());
121 LoadedObjects.push_back(LoadedObject);
123 NotifyObjectEmitted(*LoadedObject);
126 void MCJIT::addArchive(object::Archive *A) {
127 Archives.push_back(A);
131 void MCJIT::setObjectCache(ObjectCache* NewCache) {
132 MutexGuard locked(lock);
136 ObjectBufferStream* MCJIT::emitObject(Module *M) {
137 MutexGuard locked(lock);
139 // This must be a module which has already been added but not loaded to this
140 // MCJIT instance, since these conditions are tested by our caller,
141 // generateCodeForModule.
145 PM.add(new DataLayout(*TM->getDataLayout()));
147 // The RuntimeDyld will take ownership of this shortly
148 OwningPtr<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(), false)) {
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 OwningPtr<MemoryBuffer> MB(CompiledObject->getMemBuffer());
167 ObjCache->notifyObjectCompiled(M, MB.get());
170 return CompiledObject.take();
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 OwningPtr<ObjectBuffer> ObjectToLoad;
186 // Try to load the pre-compiled object from cache if possible
188 OwningPtr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
189 if (0 != PreCompiledObject.get())
190 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.take()));
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.take());
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 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
257 report_fatal_error("not yet implemented");
260 uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
261 Mangler Mang(TM->getDataLayout());
262 SmallString<128> FullName;
263 Mang.getNameWithPrefix(FullName, Name);
264 return Dyld.getSymbolLoadAddress(FullName);
267 Module *MCJIT::findModuleForSymbol(const std::string &Name,
268 bool CheckFunctionsOnly) {
269 MutexGuard locked(lock);
271 // If it hasn't already been generated, see if it's in one of our modules.
272 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
273 E = OwnedModules.end_added();
276 Function *F = M->getFunction(Name);
277 if (F && !F->isDeclaration())
279 if (!CheckFunctionsOnly) {
280 GlobalVariable *G = M->getGlobalVariable(Name);
281 if (G && !G->isDeclaration())
283 // FIXME: Do we need to worry about global aliases?
286 // We didn't find the symbol in any of our modules.
290 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
291 bool CheckFunctionsOnly)
293 MutexGuard locked(lock);
295 // First, check to see if we already have this symbol.
296 uint64_t Addr = getExistingSymbolAddress(Name);
300 SmallVector<object::Archive*, 2>::iterator I, E;
301 for (I = Archives.begin(), E = Archives.end(); I != E; ++I) {
302 object::Archive *A = *I;
303 // Look for our symbols in each Archive
304 object::Archive::child_iterator ChildIt = A->findSym(Name);
305 if (ChildIt != A->child_end()) {
306 OwningPtr<object::Binary> ChildBin;
307 // FIXME: Support nested archives?
308 if (!ChildIt->getAsBinary(ChildBin) && ChildBin->isObject()) {
309 object::ObjectFile *OF = reinterpret_cast<object::ObjectFile *>(
311 // This causes the object file to be loaded.
313 // The address should be here now.
314 Addr = getExistingSymbolAddress(Name);
321 // If it hasn't already been generated, see if it's in one of our modules.
322 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
326 generateCodeForModule(M);
328 // Check the RuntimeDyld table again, it should be there now.
329 return getExistingSymbolAddress(Name);
332 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
333 MutexGuard locked(lock);
334 uint64_t Result = getSymbolAddress(Name, false);
336 finalizeLoadedModules();
340 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
341 MutexGuard locked(lock);
342 uint64_t Result = getSymbolAddress(Name, true);
344 finalizeLoadedModules();
348 // Deprecated. Use getFunctionAddress instead.
349 void *MCJIT::getPointerToFunction(Function *F) {
350 MutexGuard locked(lock);
352 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
353 bool AbortOnFailure = !F->hasExternalWeakLinkage();
354 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
355 addGlobalMapping(F, Addr);
359 Module *M = F->getParent();
360 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
362 // Make sure the relevant module has been compiled and loaded.
363 if (HasBeenAddedButNotLoaded)
364 generateCodeForModule(M);
365 else if (!OwnedModules.hasModuleBeenLoaded(M))
366 // If this function doesn't belong to one of our modules, we're done.
369 // FIXME: Should the Dyld be retaining module information? Probably not.
371 // This is the accessor for the target address, so make sure to check the
372 // load address of the symbol, not the local address.
373 Mangler Mang(TM->getDataLayout());
374 SmallString<128> Name;
375 TM->getTargetLowering()->getNameWithPrefix(Name, F, Mang);
376 return (void*)Dyld.getSymbolLoadAddress(Name);
379 void *MCJIT::recompileAndRelinkFunction(Function *F) {
380 report_fatal_error("not yet implemented");
383 void MCJIT::freeMachineCodeForFunction(Function *F) {
384 report_fatal_error("not yet implemented");
387 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
388 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
389 for (; I != E; ++I) {
390 ExecutionEngine::runStaticConstructorsDestructors(*I, isDtors);
394 void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
395 // Execute global ctors/dtors for each module in the program.
396 runStaticConstructorsDestructorsInModulePtrSet(
397 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
398 runStaticConstructorsDestructorsInModulePtrSet(
399 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
400 runStaticConstructorsDestructorsInModulePtrSet(
401 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
404 Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
405 ModulePtrSet::iterator I,
406 ModulePtrSet::iterator E) {
407 for (; I != E; ++I) {
408 if (Function *F = (*I)->getFunction(FnName))
414 Function *MCJIT::FindFunctionNamed(const char *FnName) {
415 Function *F = FindFunctionNamedInModulePtrSet(
416 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
418 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
419 OwnedModules.end_loaded());
421 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
422 OwnedModules.end_finalized());
426 GenericValue MCJIT::runFunction(Function *F,
427 const std::vector<GenericValue> &ArgValues) {
428 assert(F && "Function *F was null at entry to run()");
430 void *FPtr = getPointerToFunction(F);
431 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
432 FunctionType *FTy = F->getFunctionType();
433 Type *RetTy = FTy->getReturnType();
435 assert((FTy->getNumParams() == ArgValues.size() ||
436 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
437 "Wrong number of arguments passed into function!");
438 assert(FTy->getNumParams() == ArgValues.size() &&
439 "This doesn't support passing arguments through varargs (yet)!");
441 // Handle some common cases first. These cases correspond to common `main'
443 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
444 switch (ArgValues.size()) {
446 if (FTy->getParamType(0)->isIntegerTy(32) &&
447 FTy->getParamType(1)->isPointerTy() &&
448 FTy->getParamType(2)->isPointerTy()) {
449 int (*PF)(int, char **, const char **) =
450 (int(*)(int, char **, const char **))(intptr_t)FPtr;
452 // Call the function.
454 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
455 (char **)GVTOP(ArgValues[1]),
456 (const char **)GVTOP(ArgValues[2])));
461 if (FTy->getParamType(0)->isIntegerTy(32) &&
462 FTy->getParamType(1)->isPointerTy()) {
463 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
465 // Call the function.
467 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
468 (char **)GVTOP(ArgValues[1])));
473 if (FTy->getNumParams() == 1 &&
474 FTy->getParamType(0)->isIntegerTy(32)) {
476 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
477 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
484 // Handle cases where no arguments are passed first.
485 if (ArgValues.empty()) {
487 switch (RetTy->getTypeID()) {
488 default: llvm_unreachable("Unknown return type for function call!");
489 case Type::IntegerTyID: {
490 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
492 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
493 else if (BitWidth <= 8)
494 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
495 else if (BitWidth <= 16)
496 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
497 else if (BitWidth <= 32)
498 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
499 else if (BitWidth <= 64)
500 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
502 llvm_unreachable("Integer types > 64 bits not supported");
506 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
508 case Type::FloatTyID:
509 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
511 case Type::DoubleTyID:
512 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
514 case Type::X86_FP80TyID:
515 case Type::FP128TyID:
516 case Type::PPC_FP128TyID:
517 llvm_unreachable("long double not supported yet");
518 case Type::PointerTyID:
519 return PTOGV(((void*(*)())(intptr_t)FPtr)());
523 llvm_unreachable("Full-featured argument passing not supported yet!");
526 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
527 bool AbortOnFailure) {
528 if (!isSymbolSearchingDisabled()) {
529 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
534 /// If a LazyFunctionCreator is installed, use it to get/create the function.
535 if (LazyFunctionCreator)
536 if (void *RP = LazyFunctionCreator(Name))
539 if (AbortOnFailure) {
540 report_fatal_error("Program used external function '"+Name+
541 "' which could not be resolved!");
546 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
549 MutexGuard locked(lock);
550 EventListeners.push_back(L);
552 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
555 MutexGuard locked(lock);
556 SmallVector<JITEventListener*, 2>::reverse_iterator I=
557 std::find(EventListeners.rbegin(), EventListeners.rend(), L);
558 if (I != EventListeners.rend()) {
559 std::swap(*I, EventListeners.back());
560 EventListeners.pop_back();
563 void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
564 MutexGuard locked(lock);
565 MemMgr.notifyObjectLoaded(this, &Obj);
566 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
567 EventListeners[I]->NotifyObjectEmitted(Obj);
570 void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
571 MutexGuard locked(lock);
572 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
573 EventListeners[I]->NotifyFreeingObject(Obj);
577 uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
578 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
579 // If the symbols wasn't found and it begins with an underscore, try again
580 // without the underscore.
581 if (!Result && Name[0] == '_')
582 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
585 return ClientMM->getSymbolAddress(Name);