Adding object caching support to MCJIT
[oota-llvm.git] / lib / ExecutionEngine / MCJIT / MCJIT.cpp
1 //===-- MCJIT.cpp - MC-based Just-in-Time Compiler ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "MCJIT.h"
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"
25
26 using namespace llvm;
27
28 namespace {
29
30 static struct RegisterJIT {
31   RegisterJIT() { MCJIT::Register(); }
32 } JITRegistrator;
33
34 }
35
36 extern "C" void LLVMLinkInMCJIT() {
37 }
38
39 ExecutionEngine *MCJIT::createJIT(Module *M,
40                                   std::string *ErrorStr,
41                                   JITMemoryManager *JMM,
42                                   bool GVsWithCode,
43                                   TargetMachine *TM) {
44   // Try to register the program as a source of symbols to resolve against.
45   //
46   // FIXME: Don't do this here.
47   sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
48
49   return new MCJIT(M, TM, JMM, GVsWithCode);
50 }
51
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)  {
56
57   setDataLayout(TM->getDataLayout());
58 }
59
60 MCJIT::~MCJIT() {
61   if (LoadedObject)
62     NotifyFreeingObject(*LoadedObject.get());
63   delete MemMgr;
64   delete TM;
65 }
66
67 void MCJIT::setObjectCache(ObjectCache* NewCache) {
68   ObjCache = NewCache;
69 }
70
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
75   /// the future.
76   assert(M == m);
77
78   // Get a thread lock to make sure we aren't trying to compile multiple times
79   MutexGuard locked(lock);
80
81   // FIXME: Track compilation state on a per-module basis when multiple modules
82   //        are supported.
83   // Re-compilation is not supported
84   assert(!IsLoaded);
85
86   PassManager PM;
87
88   PM.add(new DataLayout(*TM->getDataLayout()));
89
90   // The RuntimeDyld will take ownership of this shortly
91   OwningPtr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
92
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!");
97   }
98
99   // Initialize passes.
100   PM.run(*m);
101   // Flush the output buffer to get the generated code into memory
102   CompiledObject->flush();
103
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).
106   if (ObjCache) {
107     ObjCache->notifyObjectCompiled(m, CompiledObject->getMemBuffer());
108   }
109
110   return CompiledObject.take();
111 }
112
113 void MCJIT::loadObject(Module *M) {
114
115   // Get a thread lock to make sure we aren't trying to load multiple times
116   MutexGuard locked(lock);
117
118   // FIXME: Track compilation state on a per-module basis when multiple modules
119   //        are supported.
120   // Re-compilation is not supported
121   if (IsLoaded)
122     return;
123
124   OwningPtr<ObjectBuffer> ObjectToLoad;
125   // Try to load the pre-compiled object from cache if possible
126   if (0 != ObjCache) {
127     OwningPtr<MemoryBuffer> PreCompiledObject(ObjCache->getObjectCopy(M));
128     if (0 != PreCompiledObject.get())
129       ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.take()));
130   }
131
132   // If the cache did not contain a suitable object, compile the object
133   if (!ObjectToLoad) {
134     ObjectToLoad.reset(emitObject(M));
135     assert(ObjectToLoad.get() && "Compilation did not produce an object.");
136   }
137
138   // Load the object into the dynamic linker.
139   // handing off ownership of the buffer
140   LoadedObject.reset(Dyld.loadObject(ObjectToLoad.take()));
141   if (!LoadedObject)
142     report_fatal_error(Dyld.getErrorString());
143
144   // Resolve any relocations.
145   Dyld.resolveRelocations();
146
147   // FIXME: Make this optional, maybe even move it to a JIT event listener
148   LoadedObject->registerWithDebugger();
149
150   NotifyObjectEmitted(*LoadedObject);
151
152   // FIXME: Add support for per-module compilation state
153   IsLoaded = true;
154 }
155
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.
162   if (!IsLoaded) {
163     // If the call to Dyld.resolveRelocations() is removed from loadObject()
164     // we'll need to do that here.
165     loadObject(M);
166
167     // Set page permissions.
168     MemMgr->applyPermissions();
169
170     return;
171   }
172
173   // Resolve any relocations.
174   Dyld.resolveRelocations();
175
176   // Set page permissions.
177   MemMgr->applyPermissions();
178 }
179
180 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
181   report_fatal_error("not yet implemented");
182 }
183
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
188   // dies.
189
190   // FIXME: Add support for per-module compilation state
191   if (!IsLoaded)
192     loadObject(M);
193
194   if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
195     bool AbortOnFailure = !F->hasExternalWeakLinkage();
196     void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
197     addGlobalMapping(F, Addr);
198     return Addr;
199   }
200
201   // FIXME: Should the Dyld be retaining module information? Probably not.
202   // FIXME: Should we be using the mangler for this? Probably.
203   //
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()
210                                        + BaseName).str());
211 }
212
213 void *MCJIT::recompileAndRelinkFunction(Function *F) {
214   report_fatal_error("not yet implemented");
215 }
216
217 void MCJIT::freeMachineCodeForFunction(Function *F) {
218   report_fatal_error("not yet implemented");
219 }
220
221 GenericValue MCJIT::runFunction(Function *F,
222                                 const std::vector<GenericValue> &ArgValues) {
223   assert(F && "Function *F was null at entry to run()");
224
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();
229
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)!");
235
236   // Handle some common cases first.  These cases correspond to common `main'
237   // prototypes.
238   if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
239     switch (ArgValues.size()) {
240     case 3:
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;
246
247         // Call the function.
248         GenericValue rv;
249         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
250                                  (char **)GVTOP(ArgValues[1]),
251                                  (const char **)GVTOP(ArgValues[2])));
252         return rv;
253       }
254       break;
255     case 2:
256       if (FTy->getParamType(0)->isIntegerTy(32) &&
257           FTy->getParamType(1)->isPointerTy()) {
258         int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
259
260         // Call the function.
261         GenericValue rv;
262         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
263                                  (char **)GVTOP(ArgValues[1])));
264         return rv;
265       }
266       break;
267     case 1:
268       if (FTy->getNumParams() == 1 &&
269           FTy->getParamType(0)->isIntegerTy(32)) {
270         GenericValue rv;
271         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
272         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
273         return rv;
274       }
275       break;
276     }
277   }
278
279   // Handle cases where no arguments are passed first.
280   if (ArgValues.empty()) {
281     GenericValue rv;
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();
286       if (BitWidth == 1)
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)());
296       else
297         llvm_unreachable("Integer types > 64 bits not supported");
298       return rv;
299     }
300     case Type::VoidTyID:
301       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
302       return rv;
303     case Type::FloatTyID:
304       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
305       return rv;
306     case Type::DoubleTyID:
307       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
308       return rv;
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)());
315     }
316   }
317
318   llvm_unreachable("Full-featured argument passing not supported yet!");
319 }
320
321 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
322                                        bool AbortOnFailure) {
323   // FIXME: Add support for per-module compilation state
324   if (!IsLoaded)
325     loadObject(M);
326
327   if (!isSymbolSearchingDisabled() && MemMgr) {
328     void *ptr = MemMgr->getPointerToNamedFunction(Name, false);
329     if (ptr)
330       return ptr;
331   }
332
333   /// If a LazyFunctionCreator is installed, use it to get/create the function.
334   if (LazyFunctionCreator)
335     if (void *RP = LazyFunctionCreator(Name))
336       return RP;
337
338   if (AbortOnFailure) {
339     report_fatal_error("Program used external function '"+Name+
340                        "' which could not be resolved!");
341   }
342   return 0;
343 }
344
345 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
346   if (L == NULL)
347     return;
348   MutexGuard locked(lock);
349   EventListeners.push_back(L);
350 }
351 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
352   if (L == NULL)
353     return;
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();
360   }
361 }
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);
366   }
367 }
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);
372   }
373 }