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