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