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