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/IR/DataLayout.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/Support/DynamicLibrary.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/MutexGuard.h"
30 static struct RegisterJIT {
31 RegisterJIT() { MCJIT::Register(); }
36 extern "C" void LLVMLinkInMCJIT() {
39 ExecutionEngine *MCJIT::createJIT(Module *M,
40 std::string *ErrorStr,
41 JITMemoryManager *JMM,
44 // Try to register the program as a source of symbols to resolve against.
46 // FIXME: Don't do this here.
47 sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
49 return new MCJIT(M, TM, JMM, GVsWithCode);
52 MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM,
53 bool AllocateGVsWithCode)
54 : ExecutionEngine(m), TM(tm), Ctx(0), MemMgr(MM), Dyld(MM),
55 IsLoaded(false), M(m), ObjCache(0) {
57 setDataLayout(TM->getDataLayout());
62 NotifyFreeingObject(*LoadedObject.get());
67 void MCJIT::setObjectCache(ObjectCache* NewCache) {
71 ObjectBufferStream* MCJIT::emitObject(Module *m) {
72 /// Currently, MCJIT only supports a single module and the module passed to
73 /// this function call is expected to be the contained module. The module
74 /// is passed as a parameter here to prepare for multiple module support in
78 // Get a thread lock to make sure we aren't trying to compile multiple times
79 MutexGuard locked(lock);
81 // FIXME: Track compilation state on a per-module basis when multiple modules
83 // Re-compilation is not supported
88 PM.add(new DataLayout(*TM->getDataLayout()));
90 // The RuntimeDyld will take ownership of this shortly
91 OwningPtr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
93 // Turn the machine code intermediate representation into bytes in memory
94 // that may be executed.
95 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(), false)) {
96 report_fatal_error("Target does not support MC emission!");
101 // Flush the output buffer to get the generated code into memory
102 CompiledObject->flush();
104 // If we have an object cache, tell it about the new object.
105 // Note that we're using the compiled image, not the loaded image (as below).
107 ObjCache->notifyObjectCompiled(m, CompiledObject->getMemBuffer());
110 return CompiledObject.take();
113 void MCJIT::loadObject(Module *M) {
115 // Get a thread lock to make sure we aren't trying to load multiple times
116 MutexGuard locked(lock);
118 // FIXME: Track compilation state on a per-module basis when multiple modules
120 // Re-compilation is not supported
124 OwningPtr<ObjectBuffer> ObjectToLoad;
125 // Try to load the pre-compiled object from cache if possible
127 OwningPtr<MemoryBuffer> PreCompiledObject(ObjCache->getObjectCopy(M));
128 if (0 != PreCompiledObject.get())
129 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.take()));
132 // If the cache did not contain a suitable object, compile the object
134 ObjectToLoad.reset(emitObject(M));
135 assert(ObjectToLoad.get() && "Compilation did not produce an object.");
138 // Load the object into the dynamic linker.
139 // handing off ownership of the buffer
140 LoadedObject.reset(Dyld.loadObject(ObjectToLoad.take()));
142 report_fatal_error(Dyld.getErrorString());
144 // Resolve any relocations.
145 Dyld.resolveRelocations();
147 // FIXME: Make this optional, maybe even move it to a JIT event listener
148 LoadedObject->registerWithDebugger();
150 NotifyObjectEmitted(*LoadedObject);
152 // FIXME: Add support for per-module compilation state
156 // FIXME: Add a parameter to identify which object is being finalized when
157 // MCJIT supports multiple modules.
158 // FIXME: Provide a way to separate code emission, relocations and page
159 // protection in the interface.
160 void MCJIT::finalizeObject() {
161 // If the module hasn't been compiled, just do that.
163 // If the call to Dyld.resolveRelocations() is removed from loadObject()
164 // we'll need to do that here.
167 // Set page permissions.
168 MemMgr->applyPermissions();
173 // Resolve any relocations.
174 Dyld.resolveRelocations();
176 // Set page permissions.
177 MemMgr->applyPermissions();
180 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
181 report_fatal_error("not yet implemented");
184 void *MCJIT::getPointerToFunction(Function *F) {
185 // FIXME: This should really return a uint64_t since it's a pointer in the
186 // target address space, not our local address space. That's part of the
187 // ExecutionEngine interface, though. Fix that when the old JIT finally
190 // FIXME: Add support for per-module compilation state
194 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
195 bool AbortOnFailure = !F->hasExternalWeakLinkage();
196 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
197 addGlobalMapping(F, Addr);
201 // FIXME: Should the Dyld be retaining module information? Probably not.
202 // FIXME: Should we be using the mangler for this? Probably.
204 // This is the accessor for the target address, so make sure to check the
205 // load address of the symbol, not the local address.
206 StringRef BaseName = F->getName();
207 if (BaseName[0] == '\1')
208 return (void*)Dyld.getSymbolLoadAddress(BaseName.substr(1));
209 return (void*)Dyld.getSymbolLoadAddress((TM->getMCAsmInfo()->getGlobalPrefix()
213 void *MCJIT::recompileAndRelinkFunction(Function *F) {
214 report_fatal_error("not yet implemented");
217 void MCJIT::freeMachineCodeForFunction(Function *F) {
218 report_fatal_error("not yet implemented");
221 GenericValue MCJIT::runFunction(Function *F,
222 const std::vector<GenericValue> &ArgValues) {
223 assert(F && "Function *F was null at entry to run()");
225 void *FPtr = getPointerToFunction(F);
226 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
227 FunctionType *FTy = F->getFunctionType();
228 Type *RetTy = FTy->getReturnType();
230 assert((FTy->getNumParams() == ArgValues.size() ||
231 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
232 "Wrong number of arguments passed into function!");
233 assert(FTy->getNumParams() == ArgValues.size() &&
234 "This doesn't support passing arguments through varargs (yet)!");
236 // Handle some common cases first. These cases correspond to common `main'
238 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
239 switch (ArgValues.size()) {
241 if (FTy->getParamType(0)->isIntegerTy(32) &&
242 FTy->getParamType(1)->isPointerTy() &&
243 FTy->getParamType(2)->isPointerTy()) {
244 int (*PF)(int, char **, const char **) =
245 (int(*)(int, char **, const char **))(intptr_t)FPtr;
247 // Call the function.
249 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
250 (char **)GVTOP(ArgValues[1]),
251 (const char **)GVTOP(ArgValues[2])));
256 if (FTy->getParamType(0)->isIntegerTy(32) &&
257 FTy->getParamType(1)->isPointerTy()) {
258 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
260 // Call the function.
262 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
263 (char **)GVTOP(ArgValues[1])));
268 if (FTy->getNumParams() == 1 &&
269 FTy->getParamType(0)->isIntegerTy(32)) {
271 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
272 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
279 // Handle cases where no arguments are passed first.
280 if (ArgValues.empty()) {
282 switch (RetTy->getTypeID()) {
283 default: llvm_unreachable("Unknown return type for function call!");
284 case Type::IntegerTyID: {
285 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
287 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
288 else if (BitWidth <= 8)
289 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
290 else if (BitWidth <= 16)
291 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
292 else if (BitWidth <= 32)
293 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
294 else if (BitWidth <= 64)
295 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
297 llvm_unreachable("Integer types > 64 bits not supported");
301 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
303 case Type::FloatTyID:
304 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
306 case Type::DoubleTyID:
307 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
309 case Type::X86_FP80TyID:
310 case Type::FP128TyID:
311 case Type::PPC_FP128TyID:
312 llvm_unreachable("long double not supported yet");
313 case Type::PointerTyID:
314 return PTOGV(((void*(*)())(intptr_t)FPtr)());
318 llvm_unreachable("Full-featured argument passing not supported yet!");
321 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
322 bool AbortOnFailure) {
323 // FIXME: Add support for per-module compilation state
327 if (!isSymbolSearchingDisabled() && MemMgr) {
328 void *ptr = MemMgr->getPointerToNamedFunction(Name, false);
333 /// If a LazyFunctionCreator is installed, use it to get/create the function.
334 if (LazyFunctionCreator)
335 if (void *RP = LazyFunctionCreator(Name))
338 if (AbortOnFailure) {
339 report_fatal_error("Program used external function '"+Name+
340 "' which could not be resolved!");
345 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
348 MutexGuard locked(lock);
349 EventListeners.push_back(L);
351 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
354 MutexGuard locked(lock);
355 SmallVector<JITEventListener*, 2>::reverse_iterator I=
356 std::find(EventListeners.rbegin(), EventListeners.rend(), L);
357 if (I != EventListeners.rend()) {
358 std::swap(*I, EventListeners.back());
359 EventListeners.pop_back();
362 void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
363 MutexGuard locked(lock);
364 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
365 EventListeners[I]->NotifyObjectEmitted(Obj);
368 void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
369 MutexGuard locked(lock);
370 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
371 EventListeners[I]->NotifyFreeingObject(Obj);