LLVM  5.0.0
MCJIT.cpp
Go to the documentation of this file.
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/ADT/STLExtras.h"
16 #include "llvm/IR/DataLayout.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/Function.h"
20 #include "llvm/IR/Mangler.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/Object/Archive.h"
24 #include "llvm/Object/ObjectFile.h"
29 
30 using namespace llvm;
31 
32 namespace {
33 
34 static struct RegisterJIT {
35  RegisterJIT() { MCJIT::Register(); }
36 } JITRegistrator;
37 
38 }
39 
40 extern "C" void LLVMLinkInMCJIT() {
41 }
42 
44 MCJIT::createJIT(std::unique_ptr<Module> M,
45  std::string *ErrorStr,
46  std::shared_ptr<MCJITMemoryManager> MemMgr,
47  std::shared_ptr<JITSymbolResolver> Resolver,
48  std::unique_ptr<TargetMachine> TM) {
49  // Try to register the program as a source of symbols to resolve against.
50  //
51  // FIXME: Don't do this here.
53 
54  if (!MemMgr || !Resolver) {
55  auto RTDyldMM = std::make_shared<SectionMemoryManager>();
56  if (!MemMgr)
57  MemMgr = RTDyldMM;
58  if (!Resolver)
59  Resolver = RTDyldMM;
60  }
61 
62  return new MCJIT(std::move(M), std::move(TM), std::move(MemMgr),
63  std::move(Resolver));
64 }
65 
66 MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> TM,
67  std::shared_ptr<MCJITMemoryManager> MemMgr,
68  std::shared_ptr<JITSymbolResolver> Resolver)
69  : ExecutionEngine(TM->createDataLayout(), std::move(M)), TM(std::move(TM)),
70  Ctx(nullptr), MemMgr(std::move(MemMgr)),
71  Resolver(*this, std::move(Resolver)), Dyld(*this->MemMgr, this->Resolver),
72  ObjCache(nullptr) {
73  // FIXME: We are managing our modules, so we do not want the base class
74  // ExecutionEngine to manage them as well. To avoid double destruction
75  // of the first (and only) module added in ExecutionEngine constructor
76  // we remove it from EE and will destruct it ourselves.
77  //
78  // It may make sense to move our module manager (based on SmallStPtr) back
79  // into EE if the JIT and Interpreter can live with it.
80  // If so, additional functions: addModule, removeModule, FindFunctionNamed,
81  // runStaticConstructorsDestructors could be moved back to EE as well.
82  //
83  std::unique_ptr<Module> First = std::move(Modules[0]);
84  Modules.clear();
85 
86  if (First->getDataLayout().isDefault())
87  First->setDataLayout(getDataLayout());
88 
89  OwnedModules.addModule(std::move(First));
91 }
92 
94  MutexGuard locked(lock);
95 
96  Dyld.deregisterEHFrames();
97 
98  for (auto &Obj : LoadedObjects)
99  if (Obj)
100  NotifyFreeingObject(*Obj);
101 
102  Archives.clear();
103 }
104 
105 void MCJIT::addModule(std::unique_ptr<Module> M) {
106  MutexGuard locked(lock);
107 
108  if (M->getDataLayout().isDefault())
109  M->setDataLayout(getDataLayout());
110 
111  OwnedModules.addModule(std::move(M));
112 }
113 
115  MutexGuard locked(lock);
116  return OwnedModules.removeModule(M);
117 }
118 
119 void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
120  std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L = Dyld.loadObject(*Obj);
121  if (Dyld.hasError())
123 
124  NotifyObjectEmitted(*Obj, *L);
125 
126  LoadedObjects.push_back(std::move(Obj));
127 }
128 
130  std::unique_ptr<object::ObjectFile> ObjFile;
131  std::unique_ptr<MemoryBuffer> MemBuf;
132  std::tie(ObjFile, MemBuf) = Obj.takeBinary();
133  addObjectFile(std::move(ObjFile));
134  Buffers.push_back(std::move(MemBuf));
135 }
136 
138  Archives.push_back(std::move(A));
139 }
140 
142  MutexGuard locked(lock);
143  ObjCache = NewCache;
144 }
145 
146 std::unique_ptr<MemoryBuffer> MCJIT::emitObject(Module *M) {
147  MutexGuard locked(lock);
148 
149  // This must be a module which has already been added but not loaded to this
150  // MCJIT instance, since these conditions are tested by our caller,
151  // generateCodeForModule.
152 
154 
155  // The RuntimeDyld will take ownership of this shortly
156  SmallVector<char, 4096> ObjBufferSV;
157  raw_svector_ostream ObjStream(ObjBufferSV);
158 
159  // Turn the machine code intermediate representation into bytes in memory
160  // that may be executed.
161  if (TM->addPassesToEmitMC(PM, Ctx, ObjStream, !getVerifyModules()))
162  report_fatal_error("Target does not support MC emission!");
163 
164  // Initialize passes.
165  PM.run(*M);
166  // Flush the output buffer to get the generated code into memory
167 
168  std::unique_ptr<MemoryBuffer> CompiledObjBuffer(
169  new ObjectMemoryBuffer(std::move(ObjBufferSV)));
170 
171  // If we have an object cache, tell it about the new object.
172  // Note that we're using the compiled image, not the loaded image (as below).
173  if (ObjCache) {
174  // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
175  // to create a temporary object here and delete it after the call.
176  MemoryBufferRef MB = CompiledObjBuffer->getMemBufferRef();
177  ObjCache->notifyObjectCompiled(M, MB);
178  }
179 
180  return CompiledObjBuffer;
181 }
182 
184  // Get a thread lock to make sure we aren't trying to load multiple times
185  MutexGuard locked(lock);
186 
187  // This must be a module which has already been added to this MCJIT instance.
188  assert(OwnedModules.ownsModule(M) &&
189  "MCJIT::generateCodeForModule: Unknown module.");
190 
191  // Re-compilation is not supported
192  if (OwnedModules.hasModuleBeenLoaded(M))
193  return;
194 
195  std::unique_ptr<MemoryBuffer> ObjectToLoad;
196  // Try to load the pre-compiled object from cache if possible
197  if (ObjCache)
198  ObjectToLoad = ObjCache->getObject(M);
199 
200  assert(M->getDataLayout() == getDataLayout() && "DataLayout Mismatch");
201 
202  // If the cache did not contain a suitable object, compile the object
203  if (!ObjectToLoad) {
204  ObjectToLoad = emitObject(M);
205  assert(ObjectToLoad && "Compilation did not produce an object.");
206  }
207 
208  // Load the object into the dynamic linker.
209  // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
211  object::ObjectFile::createObjectFile(ObjectToLoad->getMemBufferRef());
212  if (!LoadedObject) {
213  std::string Buf;
214  raw_string_ostream OS(Buf);
215  logAllUnhandledErrors(LoadedObject.takeError(), OS, "");
216  OS.flush();
217  report_fatal_error(Buf);
218  }
219  std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L =
220  Dyld.loadObject(*LoadedObject.get());
221 
222  if (Dyld.hasError())
224 
225  NotifyObjectEmitted(*LoadedObject.get(), *L);
226 
227  Buffers.push_back(std::move(ObjectToLoad));
228  LoadedObjects.push_back(std::move(*LoadedObject));
229 
230  OwnedModules.markModuleAsLoaded(M);
231 }
232 
234  MutexGuard locked(lock);
235 
236  // Resolve any outstanding relocations.
237  Dyld.resolveRelocations();
238 
239  OwnedModules.markAllLoadedModulesAsFinalized();
240 
241  // Register EH frame data for any module we own which has been loaded
242  Dyld.registerEHFrames();
243 
244  // Set page permissions.
245  MemMgr->finalizeMemory();
246 }
247 
248 // FIXME: Rename this.
250  MutexGuard locked(lock);
251 
252  // Generate code for module is going to move objects out of the 'added' list,
253  // so we need to copy that out before using it:
254  SmallVector<Module*, 16> ModsToAdd;
255  for (auto M : OwnedModules.added())
256  ModsToAdd.push_back(M);
257 
258  for (auto M : ModsToAdd)
260 
262 }
263 
265  MutexGuard locked(lock);
266 
267  // This must be a module which has already been added to this MCJIT instance.
268  assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
269 
270  // If the module hasn't been compiled, just do that.
271  if (!OwnedModules.hasModuleBeenLoaded(M))
273 
275 }
276 
278  if (void *Addr = getPointerToGlobalIfAvailable(Name))
279  return JITSymbol(static_cast<uint64_t>(
280  reinterpret_cast<uintptr_t>(Addr)),
282 
283  return Dyld.getSymbol(Name);
284 }
285 
287  bool CheckFunctionsOnly) {
288  StringRef DemangledName = Name;
289  if (DemangledName[0] == getDataLayout().getGlobalPrefix())
290  DemangledName = DemangledName.substr(1);
291 
292  MutexGuard locked(lock);
293 
294  // If it hasn't already been generated, see if it's in one of our modules.
295  for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
296  E = OwnedModules.end_added();
297  I != E; ++I) {
298  Module *M = *I;
299  Function *F = M->getFunction(DemangledName);
300  if (F && !F->isDeclaration())
301  return M;
302  if (!CheckFunctionsOnly) {
303  GlobalVariable *G = M->getGlobalVariable(DemangledName);
304  if (G && !G->isDeclaration())
305  return M;
306  // FIXME: Do we need to worry about global aliases?
307  }
308  }
309  // We didn't find the symbol in any of our modules.
310  return nullptr;
311 }
312 
313 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
314  bool CheckFunctionsOnly) {
315  std::string MangledName;
316  {
317  raw_string_ostream MangledNameStream(MangledName);
318  Mangler::getNameWithPrefix(MangledNameStream, Name, getDataLayout());
319  }
320  if (auto Sym = findSymbol(MangledName, CheckFunctionsOnly)) {
321  if (auto AddrOrErr = Sym.getAddress())
322  return *AddrOrErr;
323  else
324  report_fatal_error(AddrOrErr.takeError());
325  } else
326  report_fatal_error(Sym.takeError());
327 }
328 
329 JITSymbol MCJIT::findSymbol(const std::string &Name,
330  bool CheckFunctionsOnly) {
331  MutexGuard locked(lock);
332 
333  // First, check to see if we already have this symbol.
334  if (auto Sym = findExistingSymbol(Name))
335  return Sym;
336 
337  for (object::OwningBinary<object::Archive> &OB : Archives) {
338  object::Archive *A = OB.getBinary();
339  // Look for our symbols in each Archive
340  auto OptionalChildOrErr = A->findSym(Name);
341  if (!OptionalChildOrErr)
342  report_fatal_error(OptionalChildOrErr.takeError());
343  auto &OptionalChild = *OptionalChildOrErr;
344  if (OptionalChild) {
345  // FIXME: Support nested archives?
347  OptionalChild->getAsBinary();
348  if (!ChildBinOrErr) {
349  // TODO: Actually report errors helpfully.
350  consumeError(ChildBinOrErr.takeError());
351  continue;
352  }
353  std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
354  if (ChildBin->isObject()) {
355  std::unique_ptr<object::ObjectFile> OF(
356  static_cast<object::ObjectFile *>(ChildBin.release()));
357  // This causes the object file to be loaded.
358  addObjectFile(std::move(OF));
359  // The address should be here now.
360  if (auto Sym = findExistingSymbol(Name))
361  return Sym;
362  }
363  }
364  }
365 
366  // If it hasn't already been generated, see if it's in one of our modules.
367  Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
368  if (M) {
370 
371  // Check the RuntimeDyld table again, it should be there now.
372  return findExistingSymbol(Name);
373  }
374 
375  // If a LazyFunctionCreator is installed, use it to get/create the function.
376  // FIXME: Should we instead have a LazySymbolCreator callback?
377  if (LazyFunctionCreator) {
378  auto Addr = static_cast<uint64_t>(
379  reinterpret_cast<uintptr_t>(LazyFunctionCreator(Name)));
380  return JITSymbol(Addr, JITSymbolFlags::Exported);
381  }
382 
383  return nullptr;
384 }
385 
386 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
387  MutexGuard locked(lock);
388  uint64_t Result = getSymbolAddress(Name, false);
389  if (Result != 0)
391  return Result;
392 }
393 
394 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
395  MutexGuard locked(lock);
396  uint64_t Result = getSymbolAddress(Name, true);
397  if (Result != 0)
399  return Result;
400 }
401 
402 // Deprecated. Use getFunctionAddress instead.
404  MutexGuard locked(lock);
405 
406  Mangler Mang;
408  TM->getNameWithPrefix(Name, F, Mang);
409 
410  if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
411  bool AbortOnFailure = !F->hasExternalWeakLinkage();
412  void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
413  updateGlobalMapping(F, Addr);
414  return Addr;
415  }
416 
417  Module *M = F->getParent();
418  bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
419 
420  // Make sure the relevant module has been compiled and loaded.
421  if (HasBeenAddedButNotLoaded)
423  else if (!OwnedModules.hasModuleBeenLoaded(M)) {
424  // If this function doesn't belong to one of our modules, we're done.
425  // FIXME: Asking for the pointer to a function that hasn't been registered,
426  // and isn't a declaration (which is handled above) should probably
427  // be an assertion.
428  return nullptr;
429  }
430 
431  // FIXME: Should the Dyld be retaining module information? Probably not.
432  //
433  // This is the accessor for the target address, so make sure to check the
434  // load address of the symbol, not the local address.
435  return (void*)Dyld.getSymbol(Name).getAddress();
436 }
437 
438 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
439  bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
440  for (; I != E; ++I) {
442  }
443 }
444 
446  // Execute global ctors/dtors for each module in the program.
447  runStaticConstructorsDestructorsInModulePtrSet(
448  isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
449  runStaticConstructorsDestructorsInModulePtrSet(
450  isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
451  runStaticConstructorsDestructorsInModulePtrSet(
452  isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
453 }
454 
455 Function *MCJIT::FindFunctionNamedInModulePtrSet(StringRef FnName,
456  ModulePtrSet::iterator I,
457  ModulePtrSet::iterator E) {
458  for (; I != E; ++I) {
459  Function *F = (*I)->getFunction(FnName);
460  if (F && !F->isDeclaration())
461  return F;
462  }
463  return nullptr;
464 }
465 
466 GlobalVariable *MCJIT::FindGlobalVariableNamedInModulePtrSet(StringRef Name,
467  bool AllowInternal,
468  ModulePtrSet::iterator I,
469  ModulePtrSet::iterator E) {
470  for (; I != E; ++I) {
471  GlobalVariable *GV = (*I)->getGlobalVariable(Name, AllowInternal);
472  if (GV && !GV->isDeclaration())
473  return GV;
474  }
475  return nullptr;
476 }
477 
478 
480  Function *F = FindFunctionNamedInModulePtrSet(
481  FnName, OwnedModules.begin_added(), OwnedModules.end_added());
482  if (!F)
483  F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
484  OwnedModules.end_loaded());
485  if (!F)
486  F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
487  OwnedModules.end_finalized());
488  return F;
489 }
490 
492  GlobalVariable *GV = FindGlobalVariableNamedInModulePtrSet(
493  Name, AllowInternal, OwnedModules.begin_added(), OwnedModules.end_added());
494  if (!GV)
495  GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_loaded(),
496  OwnedModules.end_loaded());
497  if (!GV)
498  GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_finalized(),
499  OwnedModules.end_finalized());
500  return GV;
501 }
502 
504  assert(F && "Function *F was null at entry to run()");
505 
506  void *FPtr = getPointerToFunction(F);
508  assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
509  FunctionType *FTy = F->getFunctionType();
510  Type *RetTy = FTy->getReturnType();
511 
512  assert((FTy->getNumParams() == ArgValues.size() ||
513  (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
514  "Wrong number of arguments passed into function!");
515  assert(FTy->getNumParams() == ArgValues.size() &&
516  "This doesn't support passing arguments through varargs (yet)!");
517 
518  // Handle some common cases first. These cases correspond to common `main'
519  // prototypes.
520  if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
521  switch (ArgValues.size()) {
522  case 3:
523  if (FTy->getParamType(0)->isIntegerTy(32) &&
524  FTy->getParamType(1)->isPointerTy() &&
525  FTy->getParamType(2)->isPointerTy()) {
526  int (*PF)(int, char **, const char **) =
527  (int(*)(int, char **, const char **))(intptr_t)FPtr;
528 
529  // Call the function.
530  GenericValue rv;
531  rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
532  (char **)GVTOP(ArgValues[1]),
533  (const char **)GVTOP(ArgValues[2])));
534  return rv;
535  }
536  break;
537  case 2:
538  if (FTy->getParamType(0)->isIntegerTy(32) &&
539  FTy->getParamType(1)->isPointerTy()) {
540  int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
541 
542  // Call the function.
543  GenericValue rv;
544  rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
545  (char **)GVTOP(ArgValues[1])));
546  return rv;
547  }
548  break;
549  case 1:
550  if (FTy->getNumParams() == 1 &&
551  FTy->getParamType(0)->isIntegerTy(32)) {
552  GenericValue rv;
553  int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
554  rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
555  return rv;
556  }
557  break;
558  }
559  }
560 
561  // Handle cases where no arguments are passed first.
562  if (ArgValues.empty()) {
563  GenericValue rv;
564  switch (RetTy->getTypeID()) {
565  default: llvm_unreachable("Unknown return type for function call!");
566  case Type::IntegerTyID: {
567  unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
568  if (BitWidth == 1)
569  rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
570  else if (BitWidth <= 8)
571  rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
572  else if (BitWidth <= 16)
573  rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
574  else if (BitWidth <= 32)
575  rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
576  else if (BitWidth <= 64)
577  rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
578  else
579  llvm_unreachable("Integer types > 64 bits not supported");
580  return rv;
581  }
582  case Type::VoidTyID:
583  rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
584  return rv;
585  case Type::FloatTyID:
586  rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
587  return rv;
588  case Type::DoubleTyID:
589  rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
590  return rv;
591  case Type::X86_FP80TyID:
592  case Type::FP128TyID:
593  case Type::PPC_FP128TyID:
594  llvm_unreachable("long double not supported yet");
595  case Type::PointerTyID:
596  return PTOGV(((void*(*)())(intptr_t)FPtr)());
597  }
598  }
599 
600  report_fatal_error("MCJIT::runFunction does not support full-featured "
601  "argument passing. Please use "
602  "ExecutionEngine::getFunctionAddress and cast the result "
603  "to the desired function pointer type.");
604 }
605 
606 void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
607  if (!isSymbolSearchingDisabled()) {
608  if (auto Sym = Resolver.findSymbol(Name)) {
609  if (auto AddrOrErr = Sym.getAddress())
610  return reinterpret_cast<void*>(
611  static_cast<uintptr_t>(*AddrOrErr));
612  } else if (auto Err = Sym.takeError())
613  report_fatal_error(std::move(Err));
614  }
615 
616  /// If a LazyFunctionCreator is installed, use it to get/create the function.
618  if (void *RP = LazyFunctionCreator(Name))
619  return RP;
620 
621  if (AbortOnFailure) {
622  report_fatal_error("Program used external function '"+Name+
623  "' which could not be resolved!");
624  }
625  return nullptr;
626 }
627 
629  if (!L)
630  return;
631  MutexGuard locked(lock);
632  EventListeners.push_back(L);
633 }
634 
636  if (!L)
637  return;
638  MutexGuard locked(lock);
639  auto I = find(reverse(EventListeners), L);
640  if (I != EventListeners.rend()) {
641  std::swap(*I, EventListeners.back());
642  EventListeners.pop_back();
643  }
644 }
645 
648  MutexGuard locked(lock);
649  MemMgr->notifyObjectLoaded(this, Obj);
650  for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
651  EventListeners[I]->NotifyObjectEmitted(Obj, L);
652  }
653 }
654 
656  MutexGuard locked(lock);
657  for (JITEventListener *L : EventListeners)
658  L->NotifyFreeingObject(Obj);
659 }
660 
661 JITSymbol
662 LinkingSymbolResolver::findSymbol(const std::string &Name) {
663  auto Result = ParentEngine.findSymbol(Name, false);
664  if (Result)
665  return Result;
666  if (ParentEngine.isSymbolSearchingDisabled())
667  return nullptr;
668  return ClientResolver->findSymbol(Name);
669 }
MachineLoop * L
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Function * FindFunctionNamed(StringRef FnName) override
FindFunctionNamed - Search all of the active modules to find the function that defines FnName...
Definition: MCJIT.cpp:479
static Expected< OwningBinary< ObjectFile > > createObjectFile(StringRef ObjectPath)
Create ObjectFile from path.
Definition: ObjectFile.cpp:125
Information about the loaded object.
Definition: RuntimeDyld.h:69
void setObjectCache(ObjectCache *manager) override
Sets the object manager that MCJIT should use to avoid compilation.
Definition: MCJIT.cpp:141
void push_back(const T &Elt)
Definition: SmallVector.h:211
std::unique_ptr< LoadedObjectInfo > loadObject(const object::ObjectFile &O)
Add the referenced object file to the list of objects to be loaded and relocated. ...
void registerEHFrames()
Register any EH frame sections that have been loaded but not previously registered with the memory ma...
Represents a symbol in the JIT.
Definition: JITSymbol.h:122
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:103
Expected< Optional< Child > > findSym(StringRef name) const
Definition: Archive.cpp:974
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Definition: DerivedTypes.h:139
2: 32-bit floating point type
Definition: Type.h:59
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner)
Log all errors (if any) in E to OS.
Definition: Error.cpp:57
virtual std::unique_ptr< MemoryBuffer > getObject(const Module *M)=0
Returns a pointer to a newly allocated MemoryBuffer that contains the object which corresponds with M...
void * getPointerToGlobalIfAvailable(StringRef S)
getPointerToGlobalIfAvailable - This returns the address of the specified global value if it is has a...
sys::Mutex lock
lock - This lock protects the ExecutionEngine and MCJIT classes.
static ExecutionEngine * createJIT(std::unique_ptr< Module > M, std::string *ErrorStr, std::shared_ptr< MCJITMemoryManager > MemMgr, std::shared_ptr< JITSymbolResolver > Resolver, std::unique_ptr< TargetMachine > TM)
Definition: MCJIT.cpp:44
uint64_t updateGlobalMapping(const GlobalValue *GV, void *Addr)
updateGlobalMapping - Replace an existing mapping for GV with a new address.
JITEventListener - Abstract interface for use by the JIT to notify clients about significant events d...
StringRef getErrorString()
static JITEventListener * createGDBRegistrationListener()
This class is the base class for all object file types.
Definition: ObjectFile.h:189
bool hasAvailableExternallyLinkage() const
Definition: GlobalValue.h:403
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:490
void generateCodeForModule(Module *M) override
generateCodeForModule - Run code generation for the specified module and load it into memory...
Definition: MCJIT.cpp:183
4: 80-bit floating point type (X87)
Definition: Type.h:61
Error takeError()
Take ownership of the stored error.
Definition: Error.h:764
15: Pointers
Definition: Type.h:75
void UnregisterJITEventListener(JITEventListener *L) override
Definition: MCJIT.cpp:635
static void Register()
Definition: MCJIT.h:299
const DataLayout & getDataLayout() const
virtual void runStaticConstructorsDestructors(bool isDtors)
runStaticConstructorsDestructors - This method is used to execute all of the static constructors or d...
static bool LoadLibraryPermanently(const char *Filename, std::string *ErrMsg=nullptr)
This function permanently loads the dynamic library at the given path.
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
void runStaticConstructorsDestructors(bool isDtors) override
runStaticConstructorsDestructors - This method is used to execute all of the static constructors or d...
Definition: MCJIT.cpp:445
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:250
uint64_t getGlobalValueAddress(const std::string &Name) override
getGlobalValueAddress - Return the address of the specified global value.
Definition: MCJIT.cpp:386
Class to represent function types.
Definition: DerivedTypes.h:103
virtual void finalizeModule(Module *)
Definition: MCJIT.cpp:264
#define F(x, y, z)
Definition: MD5.cpp:55
GlobalVariable * FindGlobalVariableNamed(StringRef Name, bool AllowInternal=false) override
FindGlobalVariableNamed - Search all of the active modules to find the global variable that defines N...
Definition: MCJIT.cpp:491
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
TypeID getTypeID() const
Return the type id for the type.
Definition: Type.h:138
void * getPointerToFunction(Function *F) override
getPointerToFunction - The different EE's represent function bodies in different ways.
Definition: MCJIT.cpp:403
JITSymbol findSymbol(const std::string &Name) override
This method returns the address of the specified function or variable.
Definition: MCJIT.cpp:662
JITEvaluatedSymbol getSymbol(StringRef Name) const
Get the target address and flags for the named symbol.
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
const char * Name
JITSymbol findExistingSymbol(const std::string &Name)
Definition: MCJIT.cpp:277
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition: Module.cpp:172
void finalizeObject() override
finalizeObject - ensure the module is fully processed and is usable.
Definition: MCJIT.cpp:249
11: Arbitrary bit width integers
Definition: Type.h:71
PassManager manages ModulePassManagers.
Instances of this class acquire a given Mutex Lock when constructed and hold that lock until destruct...
Definition: MutexGuard.h:27
0: type with no size
Definition: Type.h:57
Type * getParamType(unsigned i) const
Parameter type accessors.
Definition: DerivedTypes.h:135
void addModule(std::unique_ptr< Module > M) override
Add a Module to the list of modules that we can JIT from.
Definition: MCJIT.cpp:105
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:137
bool removeModule(Module *M) override
removeModule - Removes a Module from the list of modules, but does not free the module's memory...
Definition: MCJIT.cpp:114
void * getPointerToNamedFunction(StringRef Name, bool AbortOnFailure=true) override
getPointerToNamedFunction - This method returns the address of the specified function by using the dl...
Definition: MCJIT.cpp:606
void LLVMLinkInMCJIT()
Definition: MCJIT.cpp:40
bool isSymbolSearchingDisabled() const
#define A
Definition: LargeTest.cpp:12
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:598
uint64_t getFunctionAddress(const std::string &Name) override
getFunctionAddress - Return the address of the specified function.
Definition: MCJIT.cpp:394
6: 128-bit floating point type (two 64-bits, PowerPC)
Definition: Type.h:63
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144
JITSymbol findSymbol(const std::string &Name, bool CheckFunctionsOnly)
Definition: MCJIT.cpp:329
bool getVerifyModules() const
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:221
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:593
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
Abstract interface for implementation execution of LLVM modules, designed to support both interpreter...
virtual void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj)=0
notifyObjectCompiled - Provides a pointer to compiled code for Module M.
void * GVTOP(const GenericValue &GV)
Definition: GenericValue.h:51
std::pair< std::unique_ptr< T >, std::unique_ptr< MemoryBuffer > > takeBinary()
Definition: Binary.h:190
void addArchive(object::OwningBinary< object::Archive > O) override
addArchive - Add an Archive to the execution engine.
Definition: MCJIT.cpp:137
SmallPtrSetIterator - This implements a const_iterator for SmallPtrSet.
Definition: SmallPtrSet.h:268
bool hasExternalWeakLinkage() const
Definition: GlobalValue.h:417
#define E
Definition: LargeTest.cpp:27
auto find(R &&Range, const T &Val) -> decltype(std::begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:839
Module.h This file contains the declarations for the Module class.
const DataFlowGraph & G
Definition: RDFGraph.cpp:206
reference get()
Returns a reference to the stored T value.
Definition: Error.h:744
uint64_t getSymbolAddress(const std::string &Name, bool CheckFunctionsOnly)
Definition: MCJIT.cpp:313
void RegisterJITEventListener(JITEventListener *L) override
Registers a listener to be called back on various events within the JIT.
Definition: MCJIT.cpp:628
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:923
GenericValue PTOGV(void *P)
Definition: GenericValue.h:50
Class for arbitrary precision integers.
Definition: APInt.h:69
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:197
Module * findModuleForSymbol(const std::string &Name, bool CheckFunctionsOnly)
Definition: MCJIT.cpp:286
GenericValue runFunction(Function *F, ArrayRef< GenericValue > ArgValues) override
runFunction - Execute the specified function with the specified arguments, and return the result...
Definition: MCJIT.cpp:503
std::unique_ptr< MemoryBuffer > emitObject(Module *M)
emitObject – Generate a JITed object in memory from the specified module Currently, MCJIT only supports a single module and the module passed to this function call is expected to be the contained module.
Definition: MCJIT.cpp:146
SmallVector< std::unique_ptr< Module >, 1 > Modules
The list of Modules that we are JIT'ing from.
llvm_unreachable("Unknown RegBank!")
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:361
JITTargetAddress getAddress() const
Return the address of this symbol.
Definition: JITSymbol.h:111
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:200
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
Definition: Mangler.cpp:109
#define I(x, y, z)
Definition: MD5.cpp:58
SmallVector-backed MemoryBuffer instance.
This is the base ObjectCache type which can be provided to an ExecutionEngine for the purpose of avoi...
Definition: ObjectCache.h:23
void resolveRelocations()
Resolve the relocations for all symbols we currently know about.
bool isVarArg() const
Definition: DerivedTypes.h:123
3: 64-bit floating point type
Definition: Type.h:60
~MCJIT() override
Definition: MCJIT.cpp:93
Type * getReturnType() const
Definition: DerivedTypes.h:124
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
FunctionCreator LazyFunctionCreator
LazyFunctionCreator - If an unknown function is needed, this function pointer is invoked to create it...
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:463
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:545
void NotifyFreeingObject(const object::ObjectFile &Obj)
Definition: MCJIT.cpp:655
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
void NotifyObjectEmitted(const object::ObjectFile &Obj, const RuntimeDyld::LoadedObjectInfo &L)
Definition: MCJIT.cpp:646
void finalizeLoadedModules()
Definition: MCJIT.cpp:233
GlobalVariable * getGlobalVariable(StringRef Name) const
Look up the specified global variable in the module symbol table.
Definition: Module.h:368
bool isVoidTy() const
Return true if this is 'void'.
Definition: Type.h:141
5: 128-bit floating point type (112-bit mantissa)
Definition: Type.h:62
void addObjectFile(std::unique_ptr< object::ObjectFile > O) override
addObjectFile - Add an ObjectFile to the execution engine.
Definition: MCJIT.cpp:119