3dd205751d1be9b60124d895f7a448a0e4a80edb
[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/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"
31 #include "llvm/Target/TargetSubtargetInfo.h"
32
33 using namespace llvm;
34
35 namespace {
36
37 static struct RegisterJIT {
38   RegisterJIT() { MCJIT::Register(); }
39 } JITRegistrator;
40
41 }
42
43 extern "C" void LLVMLinkInMCJIT() {
44 }
45
46 ExecutionEngine *MCJIT::createJIT(std::unique_ptr<Module> M,
47                                   std::string *ErrorStr,
48                                   RTDyldMemoryManager *MemMgr,
49                                   std::unique_ptr<TargetMachine> TM) {
50   // Try to register the program as a source of symbols to resolve against.
51   //
52   // FIXME: Don't do this here.
53   sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
54
55   return new MCJIT(std::move(M), std::move(TM),
56                    MemMgr ? MemMgr : new SectionMemoryManager());
57 }
58
59 MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> tm,
60              RTDyldMemoryManager *MM)
61     : ExecutionEngine(std::move(M)), TM(std::move(tm)), Ctx(nullptr),
62       MemMgr(this, MM), Dyld(&MemMgr), ObjCache(nullptr) {
63   // FIXME: We are managing our modules, so we do not want the base class
64   // ExecutionEngine to manage them as well. To avoid double destruction
65   // of the first (and only) module added in ExecutionEngine constructor
66   // we remove it from EE and will destruct it ourselves.
67   //
68   // It may make sense to move our module manager (based on SmallStPtr) back
69   // into EE if the JIT and Interpreter can live with it.
70   // If so, additional functions: addModule, removeModule, FindFunctionNamed,
71   // runStaticConstructorsDestructors could be moved back to EE as well.
72   //
73   std::unique_ptr<Module> First = std::move(Modules[0]);
74   Modules.clear();
75
76   OwnedModules.addModule(std::move(First));
77   setDataLayout(TM->getSubtargetImpl()->getDataLayout());
78 }
79
80 MCJIT::~MCJIT() {
81   MutexGuard locked(lock);
82
83   Dyld.deregisterEHFrames();
84
85   for (auto &Obj : LoadedObjects)
86     if (Obj)
87       NotifyFreeingObject(*Obj);
88
89   Archives.clear();
90 }
91
92 void MCJIT::addModule(std::unique_ptr<Module> M) {
93   MutexGuard locked(lock);
94   OwnedModules.addModule(std::move(M));
95 }
96
97 bool MCJIT::removeModule(Module *M) {
98   MutexGuard locked(lock);
99   return OwnedModules.removeModule(M);
100 }
101
102 void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
103   std::unique_ptr<ObjectImage> LoadedObject = Dyld.loadObject(std::move(Obj));
104   if (!LoadedObject || Dyld.hasError())
105     report_fatal_error(Dyld.getErrorString());
106
107   NotifyObjectEmitted(*LoadedObject);
108
109   LoadedObjects.push_back(std::move(LoadedObject));
110 }
111
112 void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
113   addObjectFile(std::move(Obj.getBinary()));
114   Buffers.push_back(std::move(Obj.getBuffer()));
115 }
116
117 void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
118   Archives.push_back(std::move(A));
119 }
120
121 void MCJIT::setObjectCache(ObjectCache* NewCache) {
122   MutexGuard locked(lock);
123   ObjCache = NewCache;
124 }
125
126 std::unique_ptr<ObjectBufferStream> MCJIT::emitObject(Module *M) {
127   MutexGuard locked(lock);
128
129   // This must be a module which has already been added but not loaded to this
130   // MCJIT instance, since these conditions are tested by our caller,
131   // generateCodeForModule.
132
133   PassManager PM;
134
135   M->setDataLayout(TM->getSubtargetImpl()->getDataLayout());
136   PM.add(new DataLayoutPass(M));
137
138   // The RuntimeDyld will take ownership of this shortly
139   std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
140
141   // Turn the machine code intermediate representation into bytes in memory
142   // that may be executed.
143   if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
144                             !getVerifyModules())) {
145     report_fatal_error("Target does not support MC emission!");
146   }
147
148   // Initialize passes.
149   PM.run(*M);
150   // Flush the output buffer to get the generated code into memory
151   CompiledObject->flush();
152
153   // If we have an object cache, tell it about the new object.
154   // Note that we're using the compiled image, not the loaded image (as below).
155   if (ObjCache) {
156     // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
157     // to create a temporary object here and delete it after the call.
158     MemoryBufferRef MB = CompiledObject->getMemBuffer();
159     ObjCache->notifyObjectCompiled(M, MB);
160   }
161
162   return CompiledObject;
163 }
164
165 void MCJIT::generateCodeForModule(Module *M) {
166   // Get a thread lock to make sure we aren't trying to load multiple times
167   MutexGuard locked(lock);
168
169   // This must be a module which has already been added to this MCJIT instance.
170   assert(OwnedModules.ownsModule(M) &&
171          "MCJIT::generateCodeForModule: Unknown module.");
172
173   // Re-compilation is not supported
174   if (OwnedModules.hasModuleBeenLoaded(M))
175     return;
176
177   std::unique_ptr<ObjectBuffer> ObjectToLoad;
178   // Try to load the pre-compiled object from cache if possible
179   if (ObjCache) {
180     if (std::unique_ptr<MemoryBuffer> PreCompiledObject =
181             ObjCache->getObject(M))
182       ObjectToLoad =
183           llvm::make_unique<ObjectBuffer>(std::move(PreCompiledObject));
184   }
185
186   // If the cache did not contain a suitable object, compile the object
187   if (!ObjectToLoad) {
188     ObjectToLoad = emitObject(M);
189     assert(ObjectToLoad && "Compilation did not produce an object.");
190   }
191
192   // Load the object into the dynamic linker.
193   // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
194   std::unique_ptr<ObjectImage> LoadedObject =
195       Dyld.loadObject(std::move(ObjectToLoad));
196   if (!LoadedObject)
197     report_fatal_error(Dyld.getErrorString());
198
199   // FIXME: Make this optional, maybe even move it to a JIT event listener
200   LoadedObject->registerWithDebugger();
201
202   NotifyObjectEmitted(*LoadedObject);
203
204   LoadedObjects.push_back(std::move(LoadedObject));
205
206   OwnedModules.markModuleAsLoaded(M);
207 }
208
209 void MCJIT::finalizeLoadedModules() {
210   MutexGuard locked(lock);
211
212   // Resolve any outstanding relocations.
213   Dyld.resolveRelocations();
214
215   OwnedModules.markAllLoadedModulesAsFinalized();
216
217   // Register EH frame data for any module we own which has been loaded
218   Dyld.registerEHFrames();
219
220   // Set page permissions.
221   MemMgr.finalizeMemory();
222 }
223
224 // FIXME: Rename this.
225 void MCJIT::finalizeObject() {
226   MutexGuard locked(lock);
227
228   for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
229                               E = OwnedModules.end_added();
230        I != E; ++I) {
231     Module *M = *I;
232     generateCodeForModule(M);
233   }
234
235   finalizeLoadedModules();
236 }
237
238 void MCJIT::finalizeModule(Module *M) {
239   MutexGuard locked(lock);
240
241   // This must be a module which has already been added to this MCJIT instance.
242   assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
243
244   // If the module hasn't been compiled, just do that.
245   if (!OwnedModules.hasModuleBeenLoaded(M))
246     generateCodeForModule(M);
247
248   finalizeLoadedModules();
249 }
250
251 uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
252   Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
253   SmallString<128> FullName;
254   Mang.getNameWithPrefix(FullName, Name);
255   return Dyld.getSymbolLoadAddress(FullName);
256 }
257
258 Module *MCJIT::findModuleForSymbol(const std::string &Name,
259                                    bool CheckFunctionsOnly) {
260   MutexGuard locked(lock);
261
262   // If it hasn't already been generated, see if it's in one of our modules.
263   for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
264                               E = OwnedModules.end_added();
265        I != E; ++I) {
266     Module *M = *I;
267     Function *F = M->getFunction(Name);
268     if (F && !F->isDeclaration())
269       return M;
270     if (!CheckFunctionsOnly) {
271       GlobalVariable *G = M->getGlobalVariable(Name);
272       if (G && !G->isDeclaration())
273         return M;
274       // FIXME: Do we need to worry about global aliases?
275     }
276   }
277   // We didn't find the symbol in any of our modules.
278   return nullptr;
279 }
280
281 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
282                                  bool CheckFunctionsOnly)
283 {
284   MutexGuard locked(lock);
285
286   // First, check to see if we already have this symbol.
287   uint64_t Addr = getExistingSymbolAddress(Name);
288   if (Addr)
289     return Addr;
290
291   for (object::OwningBinary<object::Archive> &OB : Archives) {
292     object::Archive *A = OB.getBinary().get();
293     // Look for our symbols in each Archive
294     object::Archive::child_iterator ChildIt = A->findSym(Name);
295     if (ChildIt != A->child_end()) {
296       // FIXME: Support nested archives?
297       ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
298           ChildIt->getAsBinary();
299       if (ChildBinOrErr.getError())
300         continue;
301       std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
302       if (ChildBin->isObject()) {
303         std::unique_ptr<object::ObjectFile> OF(
304             static_cast<object::ObjectFile *>(ChildBin.release()));
305         // This causes the object file to be loaded.
306         addObjectFile(std::move(OF));
307         // The address should be here now.
308         Addr = getExistingSymbolAddress(Name);
309         if (Addr)
310           return Addr;
311       }
312     }
313   }
314
315   // If it hasn't already been generated, see if it's in one of our modules.
316   Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
317   if (M) {
318     generateCodeForModule(M);
319
320     // Check the RuntimeDyld table again, it should be there now.
321     return getExistingSymbolAddress(Name);
322   }
323
324   // If a LazyFunctionCreator is installed, use it to get/create the function.
325   // FIXME: Should we instead have a LazySymbolCreator callback?
326   if (LazyFunctionCreator)
327     Addr = (uint64_t)LazyFunctionCreator(Name);
328
329   return Addr;
330 }
331
332 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
333   MutexGuard locked(lock);
334   uint64_t Result = getSymbolAddress(Name, false);
335   if (Result != 0)
336     finalizeLoadedModules();
337   return Result;
338 }
339
340 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
341   MutexGuard locked(lock);
342   uint64_t Result = getSymbolAddress(Name, true);
343   if (Result != 0)
344     finalizeLoadedModules();
345   return Result;
346 }
347
348 // Deprecated.  Use getFunctionAddress instead.
349 void *MCJIT::getPointerToFunction(Function *F) {
350   MutexGuard locked(lock);
351
352   if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
353     bool AbortOnFailure = !F->hasExternalWeakLinkage();
354     void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
355     addGlobalMapping(F, Addr);
356     return Addr;
357   }
358
359   Module *M = F->getParent();
360   bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
361
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.
367     return nullptr;
368
369   // FIXME: Should the Dyld be retaining module information? Probably not.
370   //
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->getSubtargetImpl()->getDataLayout());
374   SmallString<128> Name;
375   TM->getNameWithPrefix(Name, F, Mang);
376   return (void*)Dyld.getSymbolLoadAddress(Name);
377 }
378
379 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
380     bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
381   for (; I != E; ++I) {
382     ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
383   }
384 }
385
386 void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
387   // Execute global ctors/dtors for each module in the program.
388   runStaticConstructorsDestructorsInModulePtrSet(
389       isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
390   runStaticConstructorsDestructorsInModulePtrSet(
391       isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
392   runStaticConstructorsDestructorsInModulePtrSet(
393       isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
394 }
395
396 Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
397                                                  ModulePtrSet::iterator I,
398                                                  ModulePtrSet::iterator E) {
399   for (; I != E; ++I) {
400     if (Function *F = (*I)->getFunction(FnName))
401       return F;
402   }
403   return nullptr;
404 }
405
406 Function *MCJIT::FindFunctionNamed(const char *FnName) {
407   Function *F = FindFunctionNamedInModulePtrSet(
408       FnName, OwnedModules.begin_added(), OwnedModules.end_added());
409   if (!F)
410     F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
411                                         OwnedModules.end_loaded());
412   if (!F)
413     F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
414                                         OwnedModules.end_finalized());
415   return F;
416 }
417
418 GenericValue MCJIT::runFunction(Function *F,
419                                 const std::vector<GenericValue> &ArgValues) {
420   assert(F && "Function *F was null at entry to run()");
421
422   void *FPtr = getPointerToFunction(F);
423   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
424   FunctionType *FTy = F->getFunctionType();
425   Type *RetTy = FTy->getReturnType();
426
427   assert((FTy->getNumParams() == ArgValues.size() ||
428           (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
429          "Wrong number of arguments passed into function!");
430   assert(FTy->getNumParams() == ArgValues.size() &&
431          "This doesn't support passing arguments through varargs (yet)!");
432
433   // Handle some common cases first.  These cases correspond to common `main'
434   // prototypes.
435   if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
436     switch (ArgValues.size()) {
437     case 3:
438       if (FTy->getParamType(0)->isIntegerTy(32) &&
439           FTy->getParamType(1)->isPointerTy() &&
440           FTy->getParamType(2)->isPointerTy()) {
441         int (*PF)(int, char **, const char **) =
442           (int(*)(int, char **, const char **))(intptr_t)FPtr;
443
444         // Call the function.
445         GenericValue rv;
446         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
447                                  (char **)GVTOP(ArgValues[1]),
448                                  (const char **)GVTOP(ArgValues[2])));
449         return rv;
450       }
451       break;
452     case 2:
453       if (FTy->getParamType(0)->isIntegerTy(32) &&
454           FTy->getParamType(1)->isPointerTy()) {
455         int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
456
457         // Call the function.
458         GenericValue rv;
459         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
460                                  (char **)GVTOP(ArgValues[1])));
461         return rv;
462       }
463       break;
464     case 1:
465       if (FTy->getNumParams() == 1 &&
466           FTy->getParamType(0)->isIntegerTy(32)) {
467         GenericValue rv;
468         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
469         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
470         return rv;
471       }
472       break;
473     }
474   }
475
476   // Handle cases where no arguments are passed first.
477   if (ArgValues.empty()) {
478     GenericValue rv;
479     switch (RetTy->getTypeID()) {
480     default: llvm_unreachable("Unknown return type for function call!");
481     case Type::IntegerTyID: {
482       unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
483       if (BitWidth == 1)
484         rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
485       else if (BitWidth <= 8)
486         rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
487       else if (BitWidth <= 16)
488         rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
489       else if (BitWidth <= 32)
490         rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
491       else if (BitWidth <= 64)
492         rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
493       else
494         llvm_unreachable("Integer types > 64 bits not supported");
495       return rv;
496     }
497     case Type::VoidTyID:
498       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
499       return rv;
500     case Type::FloatTyID:
501       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
502       return rv;
503     case Type::DoubleTyID:
504       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
505       return rv;
506     case Type::X86_FP80TyID:
507     case Type::FP128TyID:
508     case Type::PPC_FP128TyID:
509       llvm_unreachable("long double not supported yet");
510     case Type::PointerTyID:
511       return PTOGV(((void*(*)())(intptr_t)FPtr)());
512     }
513   }
514
515   llvm_unreachable("Full-featured argument passing not supported yet!");
516 }
517
518 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
519                                        bool AbortOnFailure) {
520   if (!isSymbolSearchingDisabled()) {
521     void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
522     if (ptr)
523       return ptr;
524   }
525
526   /// If a LazyFunctionCreator is installed, use it to get/create the function.
527   if (LazyFunctionCreator)
528     if (void *RP = LazyFunctionCreator(Name))
529       return RP;
530
531   if (AbortOnFailure) {
532     report_fatal_error("Program used external function '"+Name+
533                        "' which could not be resolved!");
534   }
535   return nullptr;
536 }
537
538 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
539   if (!L)
540     return;
541   MutexGuard locked(lock);
542   EventListeners.push_back(L);
543 }
544 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
545   if (!L)
546     return;
547   MutexGuard locked(lock);
548   auto I = std::find(EventListeners.rbegin(), EventListeners.rend(), L);
549   if (I != EventListeners.rend()) {
550     std::swap(*I, EventListeners.back());
551     EventListeners.pop_back();
552   }
553 }
554 void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
555   MutexGuard locked(lock);
556   MemMgr.notifyObjectLoaded(this, &Obj);
557   for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
558     EventListeners[I]->NotifyObjectEmitted(Obj);
559   }
560 }
561 void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
562   MutexGuard locked(lock);
563   for (JITEventListener *L : EventListeners)
564     L->NotifyFreeingObject(Obj);
565 }
566
567 uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
568   uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
569   // If the symbols wasn't found and it begins with an underscore, try again
570   // without the underscore.
571   if (!Result && Name[0] == '_')
572     Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
573   if (Result)
574     return Result;
575   if (ParentEngine->isSymbolSearchingDisabled())
576     return 0;
577   return ClientMM->getSymbolAddress(Name);
578 }