LLVM  6.0.0svn
OrcMCJITReplacement.h
Go to the documentation of this file.
1 //===- OrcMCJITReplacement.h - Orc based MCJIT replacement ------*- C++ -*-===//
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 // Orc based MCJIT replacement.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_LIB_EXECUTIONENGINE_ORC_ORCMCJITREPLACEMENT_H
15 #define LLVM_LIB_EXECUTIONENGINE_ORC_ORCMCJITREPLACEMENT_H
16 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringRef.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/Mangler.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/Object/Archive.h"
34 #include "llvm/Object/Binary.h"
35 #include "llvm/Object/ObjectFile.h"
36 #include "llvm/Support/Error.h"
40 #include <algorithm>
41 #include <cassert>
42 #include <cstddef>
43 #include <cstdint>
44 #include <map>
45 #include <memory>
46 #include <set>
47 #include <string>
48 #include <vector>
49 
50 namespace llvm {
51 
52 class ObjectCache;
53 
54 namespace orc {
55 
57  // OrcMCJITReplacement needs to do a little extra book-keeping to ensure that
58  // Orc's automatic finalization doesn't kick in earlier than MCJIT clients are
59  // expecting - see finalizeMemory.
60  class MCJITReplacementMemMgr : public MCJITMemoryManager {
61  public:
62  MCJITReplacementMemMgr(OrcMCJITReplacement &M,
63  std::shared_ptr<MCJITMemoryManager> ClientMM)
64  : M(M), ClientMM(std::move(ClientMM)) {}
65 
66  uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
67  unsigned SectionID,
68  StringRef SectionName) override {
69  uint8_t *Addr =
70  ClientMM->allocateCodeSection(Size, Alignment, SectionID,
71  SectionName);
72  M.SectionsAllocatedSinceLastLoad.insert(Addr);
73  return Addr;
74  }
75 
76  uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
77  unsigned SectionID, StringRef SectionName,
78  bool IsReadOnly) override {
79  uint8_t *Addr = ClientMM->allocateDataSection(Size, Alignment, SectionID,
80  SectionName, IsReadOnly);
81  M.SectionsAllocatedSinceLastLoad.insert(Addr);
82  return Addr;
83  }
84 
85  void reserveAllocationSpace(uintptr_t CodeSize, uint32_t CodeAlign,
86  uintptr_t RODataSize, uint32_t RODataAlign,
87  uintptr_t RWDataSize,
88  uint32_t RWDataAlign) override {
89  return ClientMM->reserveAllocationSpace(CodeSize, CodeAlign,
90  RODataSize, RODataAlign,
91  RWDataSize, RWDataAlign);
92  }
93 
94  bool needsToReserveAllocationSpace() override {
95  return ClientMM->needsToReserveAllocationSpace();
96  }
97 
98  void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
99  size_t Size) override {
100  return ClientMM->registerEHFrames(Addr, LoadAddr, Size);
101  }
102 
103  void deregisterEHFrames() override {
104  return ClientMM->deregisterEHFrames();
105  }
106 
107  void notifyObjectLoaded(RuntimeDyld &RTDyld,
108  const object::ObjectFile &O) override {
109  return ClientMM->notifyObjectLoaded(RTDyld, O);
110  }
111 
112  void notifyObjectLoaded(ExecutionEngine *EE,
113  const object::ObjectFile &O) override {
114  return ClientMM->notifyObjectLoaded(EE, O);
115  }
116 
117  bool finalizeMemory(std::string *ErrMsg = nullptr) override {
118  // Each set of objects loaded will be finalized exactly once, but since
119  // symbol lookup during relocation may recursively trigger the
120  // loading/relocation of other modules, and since we're forwarding all
121  // finalizeMemory calls to a single underlying memory manager, we need to
122  // defer forwarding the call on until all necessary objects have been
123  // loaded. Otherwise, during the relocation of a leaf object, we will end
124  // up finalizing memory, causing a crash further up the stack when we
125  // attempt to apply relocations to finalized memory.
126  // To avoid finalizing too early, look at how many objects have been
127  // loaded but not yet finalized. This is a bit of a hack that relies on
128  // the fact that we're lazily emitting object files: The only way you can
129  // get more than one set of objects loaded but not yet finalized is if
130  // they were loaded during relocation of another set.
131  if (M.UnfinalizedSections.size() == 1)
132  return ClientMM->finalizeMemory(ErrMsg);
133  return false;
134  }
135 
136  private:
138  std::shared_ptr<MCJITMemoryManager> ClientMM;
139  };
140 
141  class LinkingResolver : public JITSymbolResolver {
142  public:
143  LinkingResolver(OrcMCJITReplacement &M) : M(M) {}
144 
145  JITSymbol findSymbol(const std::string &Name) override {
146  return M.ClientResolver->findSymbol(Name);
147  }
148 
149  JITSymbol findSymbolInLogicalDylib(const std::string &Name) override {
150  if (auto Sym = M.findMangledSymbol(Name))
151  return Sym;
152  return M.ClientResolver->findSymbolInLogicalDylib(Name);
153  }
154 
155  private:
157  };
158 
159 private:
160  static ExecutionEngine *
161  createOrcMCJITReplacement(std::string *ErrorMsg,
162  std::shared_ptr<MCJITMemoryManager> MemMgr,
163  std::shared_ptr<JITSymbolResolver> Resolver,
164  std::unique_ptr<TargetMachine> TM) {
165  return new OrcMCJITReplacement(std::move(MemMgr), std::move(Resolver),
166  std::move(TM));
167  }
168 
169 public:
171  std::shared_ptr<MCJITMemoryManager> MemMgr,
172  std::shared_ptr<JITSymbolResolver> ClientResolver,
173  std::unique_ptr<TargetMachine> TM)
174  : ExecutionEngine(TM->createDataLayout()), TM(std::move(TM)),
175  MemMgr(std::make_shared<MCJITReplacementMemMgr>(*this,
176  std::move(MemMgr))),
177  Resolver(std::make_shared<LinkingResolver>(*this)),
178  ClientResolver(std::move(ClientResolver)), NotifyObjectLoaded(*this),
179  NotifyFinalized(*this),
180  ObjectLayer([this]() { return this->MemMgr; }, NotifyObjectLoaded,
181  NotifyFinalized),
182  CompileLayer(ObjectLayer, SimpleCompiler(*this->TM)),
183  LazyEmitLayer(CompileLayer) {}
184 
185  static void Register() {
186  OrcMCJITReplacementCtor = createOrcMCJITReplacement;
187  }
188 
189  void addModule(std::unique_ptr<Module> M) override {
190  // If this module doesn't have a DataLayout attached then attach the
191  // default.
192  if (M->getDataLayout().isDefault()) {
193  M->setDataLayout(getDataLayout());
194  } else {
195  assert(M->getDataLayout() == getDataLayout() && "DataLayout Mismatch");
196  }
197  auto *MPtr = M.release();
198  ShouldDelete[MPtr] = true;
199  auto Deleter = [this](Module *Mod) {
200  auto I = ShouldDelete.find(Mod);
201  if (I != ShouldDelete.end() && I->second)
202  delete Mod;
203  };
204  LocalModules.push_back(std::shared_ptr<Module>(MPtr, std::move(Deleter)));
205  cantFail(LazyEmitLayer.addModule(LocalModules.back(), Resolver));
206  }
207 
208  void addObjectFile(std::unique_ptr<object::ObjectFile> O) override {
209  auto Obj =
210  std::make_shared<object::OwningBinary<object::ObjectFile>>(std::move(O),
211  nullptr);
212  cantFail(ObjectLayer.addObject(std::move(Obj), Resolver));
213  }
214 
216  auto Obj =
217  std::make_shared<object::OwningBinary<object::ObjectFile>>(std::move(O));
218  cantFail(ObjectLayer.addObject(std::move(Obj), Resolver));
219  }
220 
222  Archives.push_back(std::move(A));
223  }
224 
225  bool removeModule(Module *M) override {
226  for (auto I = LocalModules.begin(), E = LocalModules.end(); I != E; ++I) {
227  if (I->get() == M) {
228  ShouldDelete[M] = false;
229  LocalModules.erase(I);
230  return true;
231  }
232  }
233  return false;
234  }
235 
237  return cantFail(findSymbol(Name).getAddress());
238  }
239 
241  return findMangledSymbol(Mangle(Name));
242  }
243 
244  void finalizeObject() override {
245  // This is deprecated - Aim to remove in ExecutionEngine.
246  // REMOVE IF POSSIBLE - Doesn't make sense for New JIT.
247  }
248 
249  void mapSectionAddress(const void *LocalAddress,
250  uint64_t TargetAddress) override {
251  for (auto &P : UnfinalizedSections)
252  if (P.second.count(LocalAddress))
253  ObjectLayer.mapSectionAddress(P.first, LocalAddress, TargetAddress);
254  }
255 
256  uint64_t getGlobalValueAddress(const std::string &Name) override {
257  return getSymbolAddress(Name);
258  }
259 
260  uint64_t getFunctionAddress(const std::string &Name) override {
261  return getSymbolAddress(Name);
262  }
263 
264  void *getPointerToFunction(Function *F) override {
265  uint64_t FAddr = getSymbolAddress(F->getName());
266  return reinterpret_cast<void *>(static_cast<uintptr_t>(FAddr));
267  }
268 
270  bool AbortOnFailure = true) override {
271  uint64_t Addr = getSymbolAddress(Name);
272  if (!Addr && AbortOnFailure)
273  llvm_unreachable("Missing symbol!");
274  return reinterpret_cast<void *>(static_cast<uintptr_t>(Addr));
275  }
276 
278  ArrayRef<GenericValue> ArgValues) override;
279 
280  void setObjectCache(ObjectCache *NewCache) override {
281  CompileLayer.getCompiler().setObjectCache(NewCache);
282  }
283 
284  void setProcessAllSections(bool ProcessAllSections) override {
285  ObjectLayer.setProcessAllSections(ProcessAllSections);
286  }
287 
288  void runStaticConstructorsDestructors(bool isDtors) override;
289 
290 private:
291  JITSymbol findMangledSymbol(StringRef Name) {
292  if (auto Sym = LazyEmitLayer.findSymbol(Name, false))
293  return Sym;
294  if (auto Sym = ClientResolver->findSymbol(Name))
295  return Sym;
296  if (auto Sym = scanArchives(Name))
297  return Sym;
298 
299  return nullptr;
300  }
301 
302  JITSymbol scanArchives(StringRef Name) {
303  for (object::OwningBinary<object::Archive> &OB : Archives) {
304  object::Archive *A = OB.getBinary();
305  // Look for our symbols in each Archive
306  auto OptionalChildOrErr = A->findSym(Name);
307  if (!OptionalChildOrErr)
308  report_fatal_error(OptionalChildOrErr.takeError());
309  auto &OptionalChild = *OptionalChildOrErr;
310  if (OptionalChild) {
311  // FIXME: Support nested archives?
313  OptionalChild->getAsBinary();
314  if (!ChildBinOrErr) {
315  // TODO: Actually report errors helpfully.
316  consumeError(ChildBinOrErr.takeError());
317  continue;
318  }
319  std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
320  if (ChildBin->isObject()) {
321  std::unique_ptr<object::ObjectFile> ChildObj(
322  static_cast<object::ObjectFile*>(ChildBinOrErr->release()));
323  auto Obj =
324  std::make_shared<object::OwningBinary<object::ObjectFile>>(
325  std::move(ChildObj), nullptr);
326  cantFail(ObjectLayer.addObject(std::move(Obj), Resolver));
327  if (auto Sym = ObjectLayer.findSymbol(Name, true))
328  return Sym;
329  }
330  }
331  }
332  return nullptr;
333  }
334 
335  class NotifyObjectLoadedT {
336  public:
337  using LoadedObjInfoListT =
338  std::vector<std::unique_ptr<RuntimeDyld::LoadedObjectInfo>>;
339 
340  NotifyObjectLoadedT(OrcMCJITReplacement &M) : M(M) {}
341 
344  const RuntimeDyld::LoadedObjectInfo &Info) const {
345  M.UnfinalizedSections[H] = std::move(M.SectionsAllocatedSinceLastLoad);
346  M.SectionsAllocatedSinceLastLoad = SectionAddrSet();
347  M.MemMgr->notifyObjectLoaded(&M, *Obj->getBinary());
348  }
349  private:
351  };
352 
353  class NotifyFinalizedT {
354  public:
355  NotifyFinalizedT(OrcMCJITReplacement &M) : M(M) {}
356 
358  M.UnfinalizedSections.erase(H);
359  }
360 
361  private:
363  };
364 
365  std::string Mangle(StringRef Name) {
366  std::string MangledName;
367  {
368  raw_string_ostream MangledNameStream(MangledName);
369  Mang.getNameWithPrefix(MangledNameStream, Name, getDataLayout());
370  }
371  return MangledName;
372  }
373 
377 
378  std::unique_ptr<TargetMachine> TM;
379  std::shared_ptr<MCJITReplacementMemMgr> MemMgr;
380  std::shared_ptr<LinkingResolver> Resolver;
381  std::shared_ptr<JITSymbolResolver> ClientResolver;
382  Mangler Mang;
383 
384  // IMPORTANT: ShouldDelete *must* come before LocalModules: The shared_ptr
385  // delete blocks in LocalModules refer to the ShouldDelete map, so
386  // LocalModules needs to be destructed before ShouldDelete.
387  std::map<Module*, bool> ShouldDelete;
388  std::vector<std::shared_ptr<Module>> LocalModules;
389 
390  NotifyObjectLoadedT NotifyObjectLoaded;
391  NotifyFinalizedT NotifyFinalized;
392 
393  ObjectLayerT ObjectLayer;
394  CompileLayerT CompileLayer;
395  LazyEmitLayerT LazyEmitLayer;
396 
397  // We need to store ObjLayerT::ObjSetHandles for each of the object sets
398  // that have been emitted but not yet finalized so that we can forward the
399  // mapSectionAddress calls appropriately.
400  using SectionAddrSet = std::set<const void *>;
401  struct ObjHandleCompare {
402  bool operator()(ObjectLayerT::ObjHandleT H1,
403  ObjectLayerT::ObjHandleT H2) const {
404  return &*H1 < &*H2;
405  }
406  };
407  SectionAddrSet SectionsAllocatedSinceLastLoad;
408  std::map<ObjectLayerT::ObjHandleT, SectionAddrSet, ObjHandleCompare>
409  UnfinalizedSections;
410 
411  std::vector<object::OwningBinary<object::Archive>> Archives;
412 };
413 
414 } // end namespace orc
415 
416 } // end namespace llvm
417 
418 #endif // LLVM_LIB_EXECUTIONENGINE_ORC_MCJITREPLACEMENT_H
void addObjectFile(std::unique_ptr< object::ObjectFile > O) override
addObjectFile - Add an ObjectFile to the execution engine.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:688
Information about the loaded object.
Definition: RuntimeDyld.h:69
Represents a symbol in the JIT.
Definition: JITSymbol.h:159
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:115
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
void finalizeObject() override
finalizeObject - ensure the module is fully processed and is usable.
Expected< Optional< Child > > findSym(StringRef name) const
Definition: Archive.cpp:974
Bare bones object linking layer.
This class is the base class for all object file types.
Definition: ObjectFile.h:189
std::shared_ptr< object::OwningBinary< object::ObjectFile > > ObjectPtr
F(f)
const DataLayout & getDataLayout() const
Error takeError()
Take ownership of the stored error.
Definition: Error.h:537
LinkedObjectListT::iterator ObjHandleT
Handle to a loaded object.
Definition: BitVector.h:920
uint64_t getFunctionAddress(const std::string &Name) override
getFunctionAddress - Return the address of the specified function.
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
Simple compile functor: Takes a single IR module and returns an ObjectFile.
Definition: CompileUtils.h:40
OrcMCJITReplacement(std::shared_ptr< MCJITMemoryManager > MemMgr, std::shared_ptr< JITSymbolResolver > ClientResolver, std::unique_ptr< TargetMachine > TM)
bool removeModule(Module *M) override
removeModule - Removes a Module from the list of modules, but does not free the module&#39;s memory...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
GenericValue runFunction(Function *F, ArrayRef< GenericValue > ArgValues) override
runFunction - Execute the specified function with the specified arguments, and return the result...
uint64_t getGlobalValueAddress(const std::string &Name) override
getGlobalValueAddress - Return the address of the specified global value.
#define P(N)
static ExecutionEngine *(* OrcMCJITReplacementCtor)(std::string *ErrorStr, std::shared_ptr< MCJITMemoryManager > MM, std::shared_ptr< JITSymbolResolver > SR, std::unique_ptr< TargetMachine > TM)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
void addObjectFile(object::OwningBinary< object::ObjectFile > O) override
#define H(x, y, z)
Definition: MD5.cpp:57
Symbol resolution.
Definition: JITSymbol.h:260
void setObjectCache(ObjectCache *NewCache) override
Sets the pre-compiled object cache.
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:962
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void * getPointerToFunction(Function *F) override
getPointerToFunction - The different EE&#39;s represent function bodies in different ways.
Abstract interface for implementation execution of LLVM modules, designed to support both interpreter...
void runStaticConstructorsDestructors(bool isDtors) override
runStaticConstructorsDestructors - This method is used to execute all of the static constructors or d...
Module.h This file contains the declarations for the Module class.
JITSymbol findSymbol(StringRef Name)
uint64_t getSymbolAddress(StringRef Name)
reference get()
Returns a reference to the stored T value.
Definition: Error.h:517
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:220
#define I(x, y, z)
Definition: MD5.cpp:58
void setProcessAllSections(bool ProcessAllSections) override
setProcessAllSections (MCJIT Only): By default, only sections that are "required for execution" are p...
This is the base ObjectCache type which can be provided to an ExecutionEngine for the purpose of avoi...
Definition: ObjectCache.h:23
void addModule(std::unique_ptr< Module > M) override
Add a Module to the list of modules that we can JIT from.
void * getPointerToNamedFunction(StringRef Name, bool AbortOnFailure=true) override
getPointerToNamedFunction - This method returns the address of the specified function by using the dl...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:462
void addArchive(object::OwningBinary< object::Archive > A) override
addArchive - Add an Archive to the execution engine.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress) override
mapSectionAddress - map a section to its target address space value.