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 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
108 // to create a temporary object here and delete it after the call.
109 OwningPtr<MemoryBuffer> MB(CompiledObject->getMemBuffer());
110 ObjCache->notifyObjectCompiled(m, MB.get());
113 return CompiledObject.take();
116 void MCJIT::loadObject(Module *M) {
118 // Get a thread lock to make sure we aren't trying to load multiple times
119 MutexGuard locked(lock);
121 // FIXME: Track compilation state on a per-module basis when multiple modules
123 // Re-compilation is not supported
127 OwningPtr<ObjectBuffer> ObjectToLoad;
128 // Try to load the pre-compiled object from cache if possible
130 OwningPtr<MemoryBuffer> PreCompiledObject(ObjCache->getObjectCopy(M));
131 if (0 != PreCompiledObject.get())
132 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.take()));
135 // If the cache did not contain a suitable object, compile the object
137 ObjectToLoad.reset(emitObject(M));
138 assert(ObjectToLoad.get() && "Compilation did not produce an object.");
141 // Load the object into the dynamic linker.
142 // handing off ownership of the buffer
143 LoadedObject.reset(Dyld.loadObject(ObjectToLoad.take()));
145 report_fatal_error(Dyld.getErrorString());
147 // Resolve any relocations.
148 Dyld.resolveRelocations();
150 // FIXME: Make this optional, maybe even move it to a JIT event listener
151 LoadedObject->registerWithDebugger();
153 NotifyObjectEmitted(*LoadedObject);
155 // FIXME: Add support for per-module compilation state
159 // FIXME: Add a parameter to identify which object is being finalized when
160 // MCJIT supports multiple modules.
161 // FIXME: Provide a way to separate code emission, relocations and page
162 // protection in the interface.
163 void MCJIT::finalizeObject() {
164 // If the module hasn't been compiled, just do that.
166 // If the call to Dyld.resolveRelocations() is removed from loadObject()
167 // we'll need to do that here.
170 // Set page permissions.
171 MemMgr->applyPermissions();
176 // Resolve any relocations.
177 Dyld.resolveRelocations();
179 // Set page permissions.
180 MemMgr->applyPermissions();
183 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
184 report_fatal_error("not yet implemented");
187 void *MCJIT::getPointerToFunction(Function *F) {
188 // FIXME: This should really return a uint64_t since it's a pointer in the
189 // target address space, not our local address space. That's part of the
190 // ExecutionEngine interface, though. Fix that when the old JIT finally
193 // FIXME: Add support for per-module compilation state
197 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
198 bool AbortOnFailure = !F->hasExternalWeakLinkage();
199 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
200 addGlobalMapping(F, Addr);
204 // FIXME: Should the Dyld be retaining module information? Probably not.
205 // FIXME: Should we be using the mangler for this? Probably.
207 // This is the accessor for the target address, so make sure to check the
208 // load address of the symbol, not the local address.
209 StringRef BaseName = F->getName();
210 if (BaseName[0] == '\1')
211 return (void*)Dyld.getSymbolLoadAddress(BaseName.substr(1));
212 return (void*)Dyld.getSymbolLoadAddress((TM->getMCAsmInfo()->getGlobalPrefix()
216 void *MCJIT::recompileAndRelinkFunction(Function *F) {
217 report_fatal_error("not yet implemented");
220 void MCJIT::freeMachineCodeForFunction(Function *F) {
221 report_fatal_error("not yet implemented");
224 GenericValue MCJIT::runFunction(Function *F,
225 const std::vector<GenericValue> &ArgValues) {
226 assert(F && "Function *F was null at entry to run()");
228 void *FPtr = getPointerToFunction(F);
229 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
230 FunctionType *FTy = F->getFunctionType();
231 Type *RetTy = FTy->getReturnType();
233 assert((FTy->getNumParams() == ArgValues.size() ||
234 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
235 "Wrong number of arguments passed into function!");
236 assert(FTy->getNumParams() == ArgValues.size() &&
237 "This doesn't support passing arguments through varargs (yet)!");
239 // Handle some common cases first. These cases correspond to common `main'
241 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
242 switch (ArgValues.size()) {
244 if (FTy->getParamType(0)->isIntegerTy(32) &&
245 FTy->getParamType(1)->isPointerTy() &&
246 FTy->getParamType(2)->isPointerTy()) {
247 int (*PF)(int, char **, const char **) =
248 (int(*)(int, char **, const char **))(intptr_t)FPtr;
250 // Call the function.
252 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
253 (char **)GVTOP(ArgValues[1]),
254 (const char **)GVTOP(ArgValues[2])));
259 if (FTy->getParamType(0)->isIntegerTy(32) &&
260 FTy->getParamType(1)->isPointerTy()) {
261 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
263 // Call the function.
265 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
266 (char **)GVTOP(ArgValues[1])));
271 if (FTy->getNumParams() == 1 &&
272 FTy->getParamType(0)->isIntegerTy(32)) {
274 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
275 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
282 // Handle cases where no arguments are passed first.
283 if (ArgValues.empty()) {
285 switch (RetTy->getTypeID()) {
286 default: llvm_unreachable("Unknown return type for function call!");
287 case Type::IntegerTyID: {
288 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
290 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
291 else if (BitWidth <= 8)
292 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
293 else if (BitWidth <= 16)
294 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
295 else if (BitWidth <= 32)
296 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
297 else if (BitWidth <= 64)
298 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
300 llvm_unreachable("Integer types > 64 bits not supported");
304 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
306 case Type::FloatTyID:
307 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
309 case Type::DoubleTyID:
310 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
312 case Type::X86_FP80TyID:
313 case Type::FP128TyID:
314 case Type::PPC_FP128TyID:
315 llvm_unreachable("long double not supported yet");
316 case Type::PointerTyID:
317 return PTOGV(((void*(*)())(intptr_t)FPtr)());
321 llvm_unreachable("Full-featured argument passing not supported yet!");
324 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
325 bool AbortOnFailure) {
326 // FIXME: Add support for per-module compilation state
330 if (!isSymbolSearchingDisabled() && MemMgr) {
331 void *ptr = MemMgr->getPointerToNamedFunction(Name, false);
336 /// If a LazyFunctionCreator is installed, use it to get/create the function.
337 if (LazyFunctionCreator)
338 if (void *RP = LazyFunctionCreator(Name))
341 if (AbortOnFailure) {
342 report_fatal_error("Program used external function '"+Name+
343 "' which could not be resolved!");
348 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
351 MutexGuard locked(lock);
352 EventListeners.push_back(L);
354 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
357 MutexGuard locked(lock);
358 SmallVector<JITEventListener*, 2>::reverse_iterator I=
359 std::find(EventListeners.rbegin(), EventListeners.rend(), L);
360 if (I != EventListeners.rend()) {
361 std::swap(*I, EventListeners.back());
362 EventListeners.pop_back();
365 void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
366 MutexGuard locked(lock);
367 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
368 EventListeners[I]->NotifyObjectEmitted(Obj);
371 void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
372 MutexGuard locked(lock);
373 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
374 EventListeners[I]->NotifyFreeingObject(Obj);