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/Module.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/Support/DynamicLibrary.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/MutexGuard.h"
32 static struct RegisterJIT {
33 RegisterJIT() { MCJIT::Register(); }
38 extern "C" void LLVMLinkInMCJIT() {
41 ExecutionEngine *MCJIT::createJIT(Module *M,
42 std::string *ErrorStr,
43 RTDyldMemoryManager *MemMgr,
46 // Try to register the program as a source of symbols to resolve against.
48 // FIXME: Don't do this here.
49 sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
51 return new MCJIT(M, TM, MemMgr ? MemMgr : new SectionMemoryManager(),
55 MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM,
56 bool AllocateGVsWithCode)
57 : ExecutionEngine(m), TM(tm), Ctx(0), MemMgr(this, MM), Dyld(&MemMgr),
60 ModuleStates[m] = ModuleAdded;
61 setDataLayout(TM->getDataLayout());
65 LoadedObjectMap::iterator it, end = LoadedObjects.end();
66 for (it = LoadedObjects.begin(); it != end; ++it) {
67 ObjectImage *Obj = it->second;
69 NotifyFreeingObject(*Obj);
73 LoadedObjects.clear();
77 void MCJIT::addModule(Module *M) {
79 ModuleStates[M] = MCJITModuleState();
82 void MCJIT::setObjectCache(ObjectCache* NewCache) {
86 ObjectBufferStream* MCJIT::emitObject(Module *M) {
87 // This must be a module which has already been added to this MCJIT instance.
88 assert(std::find(Modules.begin(), Modules.end(), M) != Modules.end());
89 assert(ModuleStates.find(M) != ModuleStates.end());
91 // Get a thread lock to make sure we aren't trying to compile multiple times
92 MutexGuard locked(lock);
94 // Re-compilation is not supported
95 assert(!ModuleStates[M].hasBeenEmitted());
99 PM.add(new DataLayout(*TM->getDataLayout()));
101 // The RuntimeDyld will take ownership of this shortly
102 OwningPtr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
104 // Turn the machine code intermediate representation into bytes in memory
105 // that may be executed.
106 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(), false)) {
107 report_fatal_error("Target does not support MC emission!");
110 // Initialize passes.
112 // Flush the output buffer to get the generated code into memory
113 CompiledObject->flush();
115 // If we have an object cache, tell it about the new object.
116 // Note that we're using the compiled image, not the loaded image (as below).
118 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
119 // to create a temporary object here and delete it after the call.
120 OwningPtr<MemoryBuffer> MB(CompiledObject->getMemBuffer());
121 ObjCache->notifyObjectCompiled(M, MB.get());
124 return CompiledObject.take();
127 void MCJIT::generateCodeForModule(Module *M) {
128 // This must be a module which has already been added to this MCJIT instance.
129 assert(std::find(Modules.begin(), Modules.end(), M) != Modules.end());
130 assert(ModuleStates.find(M) != ModuleStates.end());
132 // Get a thread lock to make sure we aren't trying to load multiple times
133 MutexGuard locked(lock);
135 // Re-compilation is not supported
136 if (ModuleStates[M].hasBeenLoaded())
139 OwningPtr<ObjectBuffer> ObjectToLoad;
140 // Try to load the pre-compiled object from cache if possible
142 OwningPtr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
143 if (0 != PreCompiledObject.get())
144 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.take()));
147 // If the cache did not contain a suitable object, compile the object
149 ObjectToLoad.reset(emitObject(M));
150 assert(ObjectToLoad.get() && "Compilation did not produce an object.");
153 // Load the object into the dynamic linker.
154 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects map).
155 ObjectImage *LoadedObject = Dyld.loadObject(ObjectToLoad.take());
156 LoadedObjects[M] = LoadedObject;
158 report_fatal_error(Dyld.getErrorString());
160 // FIXME: Make this optional, maybe even move it to a JIT event listener
161 LoadedObject->registerWithDebugger();
163 NotifyObjectEmitted(*LoadedObject);
165 ModuleStates[M] = ModuleLoaded;
168 void MCJIT::finalizeLoadedModules() {
169 // Resolve any outstanding relocations.
170 Dyld.resolveRelocations();
172 // Register EH frame data for any module we own which has been loaded
173 SmallVector<Module *, 1>::iterator end = Modules.end();
174 SmallVector<Module *, 1>::iterator it;
175 for (it = Modules.begin(); it != end; ++it) {
177 assert(ModuleStates.find(M) != ModuleStates.end());
179 if (ModuleStates[M].hasBeenLoaded() &&
180 !ModuleStates[M].hasBeenFinalized()) {
181 ModuleStates[M] = ModuleFinalized;
185 Dyld.registerEHFrames();
187 // Set page permissions.
188 MemMgr.finalizeMemory();
191 // FIXME: Rename this.
192 void MCJIT::finalizeObject() {
193 // FIXME: This is a temporary hack to get around problems with calling
194 // finalize multiple times.
195 bool finalizeNeeded = false;
196 SmallVector<Module *, 1>::iterator end = Modules.end();
197 SmallVector<Module *, 1>::iterator it;
198 for (it = Modules.begin(); it != end; ++it) {
200 assert(ModuleStates.find(M) != ModuleStates.end());
201 if (!ModuleStates[M].hasBeenFinalized())
202 finalizeNeeded = true;
204 // I don't really like this, but the C API depends on this behavior.
205 // I suppose it's OK for a deprecated function.
206 if (!ModuleStates[M].hasBeenLoaded())
207 generateCodeForModule(M);
212 // Resolve any outstanding relocations.
213 Dyld.resolveRelocations();
215 // Register EH frame data for any module we own which has been loaded
216 for (it = Modules.begin(); it != end; ++it) {
218 assert(ModuleStates.find(M) != ModuleStates.end());
220 if (ModuleStates[M].hasBeenLoaded() &&
221 !ModuleStates[M].hasBeenFinalized()) {
222 ModuleStates[M] = ModuleFinalized;
226 Dyld.registerEHFrames();
228 // Set page permissions.
229 MemMgr.finalizeMemory();
232 void MCJIT::finalizeModule(Module *M) {
233 // This must be a module which has already been added to this MCJIT instance.
234 assert(std::find(Modules.begin(), Modules.end(), M) != Modules.end());
235 assert(ModuleStates.find(M) != ModuleStates.end());
237 if (ModuleStates[M].hasBeenFinalized())
240 // If the module hasn't been compiled, just do that.
241 if (!ModuleStates[M].hasBeenLoaded())
242 generateCodeForModule(M);
244 // Resolve any outstanding relocations.
245 Dyld.resolveRelocations();
247 Dyld.registerEHFrames();
249 // Set page permissions.
250 MemMgr.finalizeMemory();
252 ModuleStates[M] = ModuleFinalized;
255 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
256 report_fatal_error("not yet implemented");
259 uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
260 // Check with the RuntimeDyld to see if we already have this symbol.
262 return Dyld.getSymbolLoadAddress(Name.substr(1));
263 return Dyld.getSymbolLoadAddress((TM->getMCAsmInfo()->getGlobalPrefix()
267 Module *MCJIT::findModuleForSymbol(const std::string &Name,
268 bool CheckFunctionsOnly) {
269 // If it hasn't already been generated, see if it's in one of our modules.
270 SmallVector<Module *, 1>::iterator end = Modules.end();
271 SmallVector<Module *, 1>::iterator it;
272 for (it = Modules.begin(); it != end; ++it) {
274 Function *F = M->getFunction(Name);
275 if (F && !F->empty())
277 if (!CheckFunctionsOnly) {
278 GlobalVariable *G = M->getGlobalVariable(Name);
281 // FIXME: Do we need to worry about global aliases?
284 // We didn't find the symbol in any of our modules.
288 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
289 bool CheckFunctionsOnly)
291 // First, check to see if we already have this symbol.
292 uint64_t Addr = getExistingSymbolAddress(Name);
296 // If it hasn't already been generated, see if it's in one of our modules.
297 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
301 // If this is in one of our modules, generate code for that module.
302 assert(ModuleStates.find(M) != ModuleStates.end());
303 // If the module code has already been generated, we won't find the symbol.
304 if (ModuleStates[M].hasBeenLoaded())
307 // FIXME: We probably need to make sure we aren't in the process of
308 // loading or finalizing this module.
309 generateCodeForModule(M);
311 // Check the RuntimeDyld table again, it should be there now.
312 return getExistingSymbolAddress(Name);
315 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
316 uint64_t Result = getSymbolAddress(Name, false);
318 finalizeLoadedModules();
322 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
323 uint64_t Result = getSymbolAddress(Name, true);
325 finalizeLoadedModules();
329 // Deprecated. Use getFunctionAddress instead.
330 void *MCJIT::getPointerToFunction(Function *F) {
332 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
333 bool AbortOnFailure = !F->hasExternalWeakLinkage();
334 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
335 addGlobalMapping(F, Addr);
339 // If this function doesn't belong to one of our modules, we're done.
340 Module *M = F->getParent();
341 if (std::find(Modules.begin(), Modules.end(), M) == Modules.end())
344 assert(ModuleStates.find(M) != ModuleStates.end());
346 // Make sure the relevant module has been compiled and loaded.
347 if (!ModuleStates[M].hasBeenLoaded())
348 generateCodeForModule(M);
350 // FIXME: Should the Dyld be retaining module information? Probably not.
351 // FIXME: Should we be using the mangler for this? Probably.
353 // This is the accessor for the target address, so make sure to check the
354 // load address of the symbol, not the local address.
355 StringRef BaseName = F->getName();
356 if (BaseName[0] == '\1')
357 return (void*)Dyld.getSymbolLoadAddress(BaseName.substr(1));
358 return (void*)Dyld.getSymbolLoadAddress((TM->getMCAsmInfo()->getGlobalPrefix()
362 void *MCJIT::recompileAndRelinkFunction(Function *F) {
363 report_fatal_error("not yet implemented");
366 void MCJIT::freeMachineCodeForFunction(Function *F) {
367 report_fatal_error("not yet implemented");
370 GenericValue MCJIT::runFunction(Function *F,
371 const std::vector<GenericValue> &ArgValues) {
372 assert(F && "Function *F was null at entry to run()");
374 void *FPtr = getPointerToFunction(F);
375 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
376 FunctionType *FTy = F->getFunctionType();
377 Type *RetTy = FTy->getReturnType();
379 assert((FTy->getNumParams() == ArgValues.size() ||
380 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
381 "Wrong number of arguments passed into function!");
382 assert(FTy->getNumParams() == ArgValues.size() &&
383 "This doesn't support passing arguments through varargs (yet)!");
385 // Handle some common cases first. These cases correspond to common `main'
387 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
388 switch (ArgValues.size()) {
390 if (FTy->getParamType(0)->isIntegerTy(32) &&
391 FTy->getParamType(1)->isPointerTy() &&
392 FTy->getParamType(2)->isPointerTy()) {
393 int (*PF)(int, char **, const char **) =
394 (int(*)(int, char **, const char **))(intptr_t)FPtr;
396 // Call the function.
398 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
399 (char **)GVTOP(ArgValues[1]),
400 (const char **)GVTOP(ArgValues[2])));
405 if (FTy->getParamType(0)->isIntegerTy(32) &&
406 FTy->getParamType(1)->isPointerTy()) {
407 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
409 // Call the function.
411 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
412 (char **)GVTOP(ArgValues[1])));
417 if (FTy->getNumParams() == 1 &&
418 FTy->getParamType(0)->isIntegerTy(32)) {
420 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
421 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
428 // Handle cases where no arguments are passed first.
429 if (ArgValues.empty()) {
431 switch (RetTy->getTypeID()) {
432 default: llvm_unreachable("Unknown return type for function call!");
433 case Type::IntegerTyID: {
434 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
436 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
437 else if (BitWidth <= 8)
438 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
439 else if (BitWidth <= 16)
440 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
441 else if (BitWidth <= 32)
442 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
443 else if (BitWidth <= 64)
444 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
446 llvm_unreachable("Integer types > 64 bits not supported");
450 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
452 case Type::FloatTyID:
453 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
455 case Type::DoubleTyID:
456 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
458 case Type::X86_FP80TyID:
459 case Type::FP128TyID:
460 case Type::PPC_FP128TyID:
461 llvm_unreachable("long double not supported yet");
462 case Type::PointerTyID:
463 return PTOGV(((void*(*)())(intptr_t)FPtr)());
467 llvm_unreachable("Full-featured argument passing not supported yet!");
470 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
471 bool AbortOnFailure) {
472 if (!isSymbolSearchingDisabled()) {
473 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
478 /// If a LazyFunctionCreator is installed, use it to get/create the function.
479 if (LazyFunctionCreator)
480 if (void *RP = LazyFunctionCreator(Name))
483 if (AbortOnFailure) {
484 report_fatal_error("Program used external function '"+Name+
485 "' which could not be resolved!");
490 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
493 MutexGuard locked(lock);
494 EventListeners.push_back(L);
496 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
499 MutexGuard locked(lock);
500 SmallVector<JITEventListener*, 2>::reverse_iterator I=
501 std::find(EventListeners.rbegin(), EventListeners.rend(), L);
502 if (I != EventListeners.rend()) {
503 std::swap(*I, EventListeners.back());
504 EventListeners.pop_back();
507 void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
508 MutexGuard locked(lock);
509 MemMgr.notifyObjectLoaded(this, &Obj);
510 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
511 EventListeners[I]->NotifyObjectEmitted(Obj);
514 void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
515 MutexGuard locked(lock);
516 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
517 EventListeners[I]->NotifyFreeingObject(Obj);
521 uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
522 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
523 // If the symbols wasn't found and it begins with an underscore, try again
524 // without the underscore.
525 if (!Result && Name[0] == '_')
526 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
529 return ClientMM->getSymbolAddress(Name);