LLVM  7.0.0svn
CompileOnDemandLayer.h
Go to the documentation of this file.
1 //===- CompileOnDemandLayer.h - Compile each function on demand -*- 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 // JIT layer for breaking up modules and inserting callbacks to allow
11 // individual functions to be compiled on demand.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H
16 #define LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H
17 
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Twine.h"
28 #include "llvm/IR/Attributes.h"
29 #include "llvm/IR/Constant.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GlobalAlias.h"
34 #include "llvm/IR/GlobalValue.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Instruction.h"
37 #include "llvm/IR/Mangler.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/Support/Casting.h"
43 #include <algorithm>
44 #include <cassert>
45 #include <functional>
46 #include <iterator>
47 #include <list>
48 #include <memory>
49 #include <set>
50 #include <string>
51 #include <utility>
52 #include <vector>
53 
54 namespace llvm {
55 
56 class Value;
57 
58 namespace orc {
59 
61 
64 
65 public:
66  /// Builder for IndirectStubsManagers.
68  std::function<std::unique_ptr<IndirectStubsManager>()>;
69 
70  /// Retrieve symbol resolver for the given VModuleKey.
72  std::function<std::shared_ptr<SymbolResolver>(VModuleKey K)>;
73 
74  /// Set the symbol resolver for the given VModuleKey.
76  std::function<void(VModuleKey K, std::shared_ptr<SymbolResolver> R)>;
77 
78  using GetAvailableContextFunction = std::function<LLVMContext &()>;
79 
82  IndirectStubsManagerBuilder BuildIndirectStubsManager,
83  GetSymbolResolverFunction GetSymbolResolver,
84  SetSymbolResolverFunction SetSymbolResolver,
85  GetAvailableContextFunction GetAvailableContext);
86 
87  Error add(VSO &V, VModuleKey K, std::unique_ptr<Module> M) override;
88 
90  std::unique_ptr<Module> M) override;
91 
92 private:
93  using StubManagersMap =
94  std::map<const VSO *, std::unique_ptr<IndirectStubsManager>>;
95 
96  using SymbolNameToDefinitionMap =
98 
99  IndirectStubsManager &getStubsManager(const VSO &V);
100 
101  std::unique_ptr<Module>
102  extractFunctions(Module &M, const SymbolNameSet &SymbolNames,
103  const SymbolNameToDefinitionMap &SymbolToDefiniton);
104 
105  void emitExtractedFunctionsModule(MaterializationResponsibility R,
106  std::unique_ptr<Module> M,
107  std::shared_ptr<SymbolResolver> Resolver);
108 
109  mutable std::mutex CODLayerMutex;
110 
111  IRLayer &BaseLayer;
113  IndirectStubsManagerBuilder BuildIndirectStubsManager;
114  StubManagersMap StubsMgrs;
115  GetSymbolResolverFunction GetSymbolResolver;
116  SetSymbolResolverFunction SetSymbolResolver;
117  GetAvailableContextFunction GetAvailableContext;
118 };
119 
120 /// Compile-on-demand layer.
121 ///
122 /// When a module is added to this layer a stub is created for each of its
123 /// function definitions. The stubs and other global values are immediately
124 /// added to the layer below. When a stub is called it triggers the extraction
125 /// of the function body from the original module. The extracted body is then
126 /// compiled and executed.
127 template <typename BaseLayerT,
128  typename CompileCallbackMgrT = JITCompileCallbackManager,
129  typename IndirectStubsMgrT = IndirectStubsManager>
131 private:
132  template <typename MaterializerFtor>
133  class LambdaMaterializer final : public ValueMaterializer {
134  public:
135  LambdaMaterializer(MaterializerFtor M) : M(std::move(M)) {}
136 
137  Value *materialize(Value *V) final { return M(V); }
138 
139  private:
140  MaterializerFtor M;
141  };
142 
143  template <typename MaterializerFtor>
144  LambdaMaterializer<MaterializerFtor>
145  createLambdaMaterializer(MaterializerFtor M) {
146  return LambdaMaterializer<MaterializerFtor>(std::move(M));
147  }
148 
149  // Provide type-erasure for the Modules and MemoryManagers.
150  template <typename ResourceT>
151  class ResourceOwner {
152  public:
153  ResourceOwner() = default;
154  ResourceOwner(const ResourceOwner &) = delete;
155  ResourceOwner &operator=(const ResourceOwner &) = delete;
156  virtual ~ResourceOwner() = default;
157 
158  virtual ResourceT& getResource() const = 0;
159  };
160 
161  template <typename ResourceT, typename ResourcePtrT>
162  class ResourceOwnerImpl : public ResourceOwner<ResourceT> {
163  public:
164  ResourceOwnerImpl(ResourcePtrT ResourcePtr)
165  : ResourcePtr(std::move(ResourcePtr)) {}
166 
167  ResourceT& getResource() const override { return *ResourcePtr; }
168 
169  private:
170  ResourcePtrT ResourcePtr;
171  };
172 
173  template <typename ResourceT, typename ResourcePtrT>
174  std::unique_ptr<ResourceOwner<ResourceT>>
175  wrapOwnership(ResourcePtrT ResourcePtr) {
176  using RO = ResourceOwnerImpl<ResourceT, ResourcePtrT>;
177  return llvm::make_unique<RO>(std::move(ResourcePtr));
178  }
179 
180  class StaticGlobalRenamer {
181  public:
182  StaticGlobalRenamer() = default;
183  StaticGlobalRenamer(StaticGlobalRenamer &&) = default;
184  StaticGlobalRenamer &operator=(StaticGlobalRenamer &&) = default;
185 
186  void rename(Module &M) {
187  for (auto &F : M)
188  if (F.hasLocalLinkage())
189  F.setName("$static." + Twine(NextId++));
190  for (auto &G : M.globals())
191  if (G.hasLocalLinkage())
192  G.setName("$static." + Twine(NextId++));
193  }
194 
195  private:
196  unsigned NextId = 0;
197  };
198 
199  struct LogicalDylib {
201  std::unique_ptr<Module> SourceMod;
202  std::set<Function*> StubsToClone;
203  };
204 
205  using SourceModulesList = std::vector<SourceModuleEntry>;
206  using SourceModuleHandle = typename SourceModulesList::size_type;
207 
208  LogicalDylib() = default;
209 
210  LogicalDylib(VModuleKey K, std::shared_ptr<SymbolResolver> BackingResolver,
211  std::unique_ptr<IndirectStubsMgrT> StubsMgr)
212  : K(std::move(K)), BackingResolver(std::move(BackingResolver)),
213  StubsMgr(std::move(StubsMgr)) {}
214 
215  SourceModuleHandle addSourceModule(std::unique_ptr<Module> M) {
216  SourceModuleHandle H = SourceModules.size();
217  SourceModules.push_back(SourceModuleEntry());
218  SourceModules.back().SourceMod = std::move(M);
219  return H;
220  }
221 
222  Module& getSourceModule(SourceModuleHandle H) {
223  return *SourceModules[H].SourceMod;
224  }
225 
226  std::set<Function*>& getStubsToClone(SourceModuleHandle H) {
227  return SourceModules[H].StubsToClone;
228  }
229 
230  JITSymbol findSymbol(BaseLayerT &BaseLayer, const std::string &Name,
231  bool ExportedSymbolsOnly) {
232  if (auto Sym = StubsMgr->findStub(Name, ExportedSymbolsOnly))
233  return Sym;
234  for (auto BLK : BaseLayerVModuleKeys)
235  if (auto Sym = BaseLayer.findSymbolIn(BLK, Name, ExportedSymbolsOnly))
236  return Sym;
237  else if (auto Err = Sym.takeError())
238  return std::move(Err);
239  return nullptr;
240  }
241 
242  Error removeModulesFromBaseLayer(BaseLayerT &BaseLayer) {
243  for (auto &BLK : BaseLayerVModuleKeys)
244  if (auto Err = BaseLayer.removeModule(BLK))
245  return Err;
246  return Error::success();
247  }
248 
249  VModuleKey K;
250  std::shared_ptr<SymbolResolver> BackingResolver;
251  std::unique_ptr<IndirectStubsMgrT> StubsMgr;
252  StaticGlobalRenamer StaticRenamer;
253  SourceModulesList SourceModules;
254  std::vector<VModuleKey> BaseLayerVModuleKeys;
255  };
256 
257 public:
258 
259  /// Module partitioning functor.
260  using PartitioningFtor = std::function<std::set<Function*>(Function&)>;
261 
262  /// Builder for IndirectStubsManagers.
264  std::function<std::unique_ptr<IndirectStubsMgrT>()>;
265 
266  using SymbolResolverGetter =
267  std::function<std::shared_ptr<SymbolResolver>(VModuleKey K)>;
268 
269  using SymbolResolverSetter =
270  std::function<void(VModuleKey K, std::shared_ptr<SymbolResolver> R)>;
271 
272  /// Construct a compile-on-demand layer instance.
273  CompileOnDemandLayer(ExecutionSession &ES, BaseLayerT &BaseLayer,
274  SymbolResolverGetter GetSymbolResolver,
275  SymbolResolverSetter SetSymbolResolver,
276  PartitioningFtor Partition,
277  CompileCallbackMgrT &CallbackMgr,
278  IndirectStubsManagerBuilderT CreateIndirectStubsManager,
279  bool CloneStubsIntoPartitions = true)
280  : ES(ES), BaseLayer(BaseLayer),
281  GetSymbolResolver(std::move(GetSymbolResolver)),
282  SetSymbolResolver(std::move(SetSymbolResolver)),
283  Partition(std::move(Partition)), CompileCallbackMgr(CallbackMgr),
284  CreateIndirectStubsManager(std::move(CreateIndirectStubsManager)),
285  CloneStubsIntoPartitions(CloneStubsIntoPartitions) {}
286 
288  // FIXME: Report error on log.
289  while (!LogicalDylibs.empty())
290  consumeError(removeModule(LogicalDylibs.begin()->first));
291  }
292 
293  /// Add a module to the compile-on-demand layer.
294  Error addModule(VModuleKey K, std::unique_ptr<Module> M) {
295 
296  assert(!LogicalDylibs.count(K) && "VModuleKey K already in use");
297  auto I = LogicalDylibs.insert(
298  LogicalDylibs.end(),
299  std::make_pair(K, LogicalDylib(K, GetSymbolResolver(K),
300  CreateIndirectStubsManager())));
301 
302  return addLogicalModule(I->second, std::move(M));
303  }
304 
305  /// Add extra modules to an existing logical module.
306  Error addExtraModule(VModuleKey K, std::unique_ptr<Module> M) {
307  return addLogicalModule(LogicalDylibs[K], std::move(M));
308  }
309 
310  /// Remove the module represented by the given key.
311  ///
312  /// This will remove all modules in the layers below that were derived from
313  /// the module represented by K.
315  auto I = LogicalDylibs.find(K);
316  assert(I != LogicalDylibs.end() && "VModuleKey K not valid here");
317  auto Err = I->second.removeModulesFromBaseLayer(BaseLayer);
318  LogicalDylibs.erase(I);
319  return Err;
320  }
321 
322  /// Search for the given named symbol.
323  /// @param Name The name of the symbol to search for.
324  /// @param ExportedSymbolsOnly If true, search only for exported symbols.
325  /// @return A handle for the given named symbol, if it exists.
326  JITSymbol findSymbol(StringRef Name, bool ExportedSymbolsOnly) {
327  for (auto &KV : LogicalDylibs) {
328  if (auto Sym = KV.second.StubsMgr->findStub(Name, ExportedSymbolsOnly))
329  return Sym;
330  if (auto Sym = findSymbolIn(KV.first, Name, ExportedSymbolsOnly))
331  return Sym;
332  else if (auto Err = Sym.takeError())
333  return std::move(Err);
334  }
335  return BaseLayer.findSymbol(Name, ExportedSymbolsOnly);
336  }
337 
338  /// Get the address of a symbol provided by this layer, or some layer
339  /// below this one.
340  JITSymbol findSymbolIn(VModuleKey K, const std::string &Name,
341  bool ExportedSymbolsOnly) {
342  assert(LogicalDylibs.count(K) && "VModuleKey K is not valid here");
343  return LogicalDylibs[K].findSymbol(BaseLayer, Name, ExportedSymbolsOnly);
344  }
345 
346  /// Update the stub for the given function to point at FnBodyAddr.
347  /// This can be used to support re-optimization.
348  /// @return true if the function exists and the stub is updated, false
349  /// otherwise.
350  //
351  // FIXME: We should track and free associated resources (unused compile
352  // callbacks, uncompiled IR, and no-longer-needed/reachable function
353  // implementations).
354  Error updatePointer(std::string FuncName, JITTargetAddress FnBodyAddr) {
355  //Find out which logical dylib contains our symbol
356  auto LDI = LogicalDylibs.begin();
357  for (auto LDE = LogicalDylibs.end(); LDI != LDE; ++LDI) {
358  if (auto LMResources =
359  LDI->getLogicalModuleResourcesForSymbol(FuncName, false)) {
360  Module &SrcM = LMResources->SourceModule->getResource();
361  std::string CalledFnName = mangle(FuncName, SrcM.getDataLayout());
362  if (auto Err = LMResources->StubsMgr->updatePointer(CalledFnName,
363  FnBodyAddr))
364  return Err;
365  return Error::success();
366  }
367  }
368  return make_error<JITSymbolNotFound>(FuncName);
369  }
370 
371 private:
372  Error addLogicalModule(LogicalDylib &LD, std::unique_ptr<Module> SrcMPtr) {
373 
374  // Rename all static functions / globals to $static.X :
375  // This will unique the names across all modules in the logical dylib,
376  // simplifying symbol lookup.
377  LD.StaticRenamer.rename(*SrcMPtr);
378 
379  // Bump the linkage and rename any anonymous/privote members in SrcM to
380  // ensure that everything will resolve properly after we partition SrcM.
382 
383  // Create a logical module handle for SrcM within the logical dylib.
384  Module &SrcM = *SrcMPtr;
385  auto LMId = LD.addSourceModule(std::move(SrcMPtr));
386 
387  // Create stub functions.
388  const DataLayout &DL = SrcM.getDataLayout();
389  {
390  typename IndirectStubsMgrT::StubInitsMap StubInits;
391  for (auto &F : SrcM) {
392  // Skip declarations.
393  if (F.isDeclaration())
394  continue;
395 
396  // Skip weak functions for which we already have definitions.
397  auto MangledName = mangle(F.getName(), DL);
398  if (F.hasWeakLinkage() || F.hasLinkOnceLinkage()) {
399  if (auto Sym = LD.findSymbol(BaseLayer, MangledName, false))
400  continue;
401  else if (auto Err = Sym.takeError())
402  return std::move(Err);
403  }
404 
405  // Record all functions defined by this module.
406  if (CloneStubsIntoPartitions)
407  LD.getStubsToClone(LMId).insert(&F);
408 
409  // Create a callback, associate it with the stub for the function,
410  // and set the compile action to compile the partition containing the
411  // function.
412  auto CompileAction = [this, &LD, LMId, &F]() -> JITTargetAddress {
413  if (auto FnImplAddrOrErr = this->extractAndCompile(LD, LMId, F))
414  return *FnImplAddrOrErr;
415  else {
416  // FIXME: Report error, return to 'abort' or something similar.
417  consumeError(FnImplAddrOrErr.takeError());
418  return 0;
419  }
420  };
421  if (auto CCAddr =
422  CompileCallbackMgr.getCompileCallback(std::move(CompileAction)))
423  StubInits[MangledName] =
424  std::make_pair(*CCAddr, JITSymbolFlags::fromGlobalValue(F));
425  else
426  return CCAddr.takeError();
427  }
428 
429  if (auto Err = LD.StubsMgr->createStubs(StubInits))
430  return Err;
431  }
432 
433  // If this module doesn't contain any globals, aliases, or module flags then
434  // we can bail out early and avoid the overhead of creating and managing an
435  // empty globals module.
436  if (SrcM.global_empty() && SrcM.alias_empty() &&
437  !SrcM.getModuleFlagsMetadata())
438  return Error::success();
439 
440  // Create the GlobalValues module.
441  auto GVsM = llvm::make_unique<Module>((SrcM.getName() + ".globals").str(),
442  SrcM.getContext());
443  GVsM->setDataLayout(DL);
444 
445  ValueToValueMapTy VMap;
446 
447  // Clone global variable decls.
448  for (auto &GV : SrcM.globals())
449  if (!GV.isDeclaration() && !VMap.count(&GV))
450  cloneGlobalVariableDecl(*GVsM, GV, &VMap);
451 
452  // And the aliases.
453  for (auto &A : SrcM.aliases())
454  if (!VMap.count(&A))
455  cloneGlobalAliasDecl(*GVsM, A, VMap);
456 
457  // Clone the module flags.
458  cloneModuleFlagsMetadata(*GVsM, SrcM, VMap);
459 
460  // Now we need to clone the GV and alias initializers.
461 
462  // Initializers may refer to functions declared (but not defined) in this
463  // module. Build a materializer to clone decls on demand.
464  auto Materializer = createLambdaMaterializer(
465  [&LD, &GVsM](Value *V) -> Value* {
466  if (auto *F = dyn_cast<Function>(V)) {
467  // Decls in the original module just get cloned.
468  if (F->isDeclaration())
469  return cloneFunctionDecl(*GVsM, *F);
470 
471  // Definitions in the original module (which we have emitted stubs
472  // for at this point) get turned into a constant alias to the stub
473  // instead.
474  const DataLayout &DL = GVsM->getDataLayout();
475  std::string FName = mangle(F->getName(), DL);
476  unsigned PtrBitWidth = DL.getPointerTypeSizeInBits(F->getType());
477  JITTargetAddress StubAddr =
478  LD.StubsMgr->findStub(FName, false).getAddress();
479 
480  ConstantInt *StubAddrCI =
481  ConstantInt::get(GVsM->getContext(), APInt(PtrBitWidth, StubAddr));
482  Constant *Init = ConstantExpr::getCast(Instruction::IntToPtr,
483  StubAddrCI, F->getType());
484  return GlobalAlias::create(F->getFunctionType(),
485  F->getType()->getAddressSpace(),
486  F->getLinkage(), F->getName(),
487  Init, GVsM.get());
488  }
489  // else....
490  return nullptr;
491  });
492 
493  // Clone the global variable initializers.
494  for (auto &GV : SrcM.globals())
495  if (!GV.isDeclaration())
496  moveGlobalVariableInitializer(GV, VMap, &Materializer);
497 
498  // Clone the global alias initializers.
499  for (auto &A : SrcM.aliases()) {
500  auto *NewA = cast<GlobalAlias>(VMap[&A]);
501  assert(NewA && "Alias not cloned?");
502  Value *Init = MapValue(A.getAliasee(), VMap, RF_None, nullptr,
503  &Materializer);
504  NewA->setAliasee(cast<Constant>(Init));
505  }
506 
507  // Build a resolver for the globals module and add it to the base layer.
508  auto LegacyLookup = [this, &LD](const std::string &Name) -> JITSymbol {
509  if (auto Sym = LD.StubsMgr->findStub(Name, false))
510  return Sym;
511 
512  if (auto Sym = LD.findSymbol(BaseLayer, Name, false))
513  return Sym;
514  else if (auto Err = Sym.takeError())
515  return std::move(Err);
516 
517  return nullptr;
518  };
519 
520  auto GVsResolver = createSymbolResolver(
521  [&LD, LegacyLookup](SymbolFlagsMap &SymbolFlags,
522  const SymbolNameSet &Symbols) {
523  auto NotFoundViaLegacyLookup =
524  lookupFlagsWithLegacyFn(SymbolFlags, Symbols, LegacyLookup);
525 
526  if (!NotFoundViaLegacyLookup) {
527  logAllUnhandledErrors(NotFoundViaLegacyLookup.takeError(), errs(),
528  "CODLayer/GVsResolver flags lookup failed: ");
529  SymbolFlags.clear();
530  return SymbolNameSet();
531  }
532 
533  return LD.BackingResolver->lookupFlags(SymbolFlags,
534  *NotFoundViaLegacyLookup);
535  },
536  [this, &LD,
537  LegacyLookup](std::shared_ptr<AsynchronousSymbolQuery> Query,
538  SymbolNameSet Symbols) {
539  auto NotFoundViaLegacyLookup =
540  lookupWithLegacyFn(ES, *Query, Symbols, LegacyLookup);
541  return LD.BackingResolver->lookup(Query, NotFoundViaLegacyLookup);
542  });
543 
544  SetSymbolResolver(LD.K, std::move(GVsResolver));
545 
546  if (auto Err = BaseLayer.addModule(LD.K, std::move(GVsM)))
547  return Err;
548 
549  LD.BaseLayerVModuleKeys.push_back(LD.K);
550 
551  return Error::success();
552  }
553 
554  static std::string mangle(StringRef Name, const DataLayout &DL) {
555  std::string MangledName;
556  {
557  raw_string_ostream MangledNameStream(MangledName);
558  Mangler::getNameWithPrefix(MangledNameStream, Name, DL);
559  }
560  return MangledName;
561  }
562 
564  extractAndCompile(LogicalDylib &LD,
565  typename LogicalDylib::SourceModuleHandle LMId,
566  Function &F) {
567  Module &SrcM = LD.getSourceModule(LMId);
568 
569  // If F is a declaration we must already have compiled it.
570  if (F.isDeclaration())
571  return 0;
572 
573  // Grab the name of the function being called here.
574  std::string CalledFnName = mangle(F.getName(), SrcM.getDataLayout());
575 
576  JITTargetAddress CalledAddr = 0;
577  auto Part = Partition(F);
578  if (auto PartKeyOrErr = emitPartition(LD, LMId, Part)) {
579  auto &PartKey = *PartKeyOrErr;
580  for (auto *SubF : Part) {
581  std::string FnName = mangle(SubF->getName(), SrcM.getDataLayout());
582  if (auto FnBodySym = BaseLayer.findSymbolIn(PartKey, FnName, false)) {
583  if (auto FnBodyAddrOrErr = FnBodySym.getAddress()) {
584  JITTargetAddress FnBodyAddr = *FnBodyAddrOrErr;
585 
586  // If this is the function we're calling record the address so we can
587  // return it from this function.
588  if (SubF == &F)
589  CalledAddr = FnBodyAddr;
590 
591  // Update the function body pointer for the stub.
592  if (auto EC = LD.StubsMgr->updatePointer(FnName, FnBodyAddr))
593  return 0;
594 
595  } else
596  return FnBodyAddrOrErr.takeError();
597  } else if (auto Err = FnBodySym.takeError())
598  return std::move(Err);
599  else
600  llvm_unreachable("Function not emitted for partition");
601  }
602 
603  LD.BaseLayerVModuleKeys.push_back(PartKey);
604  } else
605  return PartKeyOrErr.takeError();
606 
607  return CalledAddr;
608  }
609 
610  template <typename PartitionT>
612  emitPartition(LogicalDylib &LD,
613  typename LogicalDylib::SourceModuleHandle LMId,
614  const PartitionT &Part) {
615  Module &SrcM = LD.getSourceModule(LMId);
616 
617  // Create the module.
618  std::string NewName = SrcM.getName();
619  for (auto *F : Part) {
620  NewName += ".";
621  NewName += F->getName();
622  }
623 
624  auto M = llvm::make_unique<Module>(NewName, SrcM.getContext());
625  M->setDataLayout(SrcM.getDataLayout());
626  ValueToValueMapTy VMap;
627 
628  auto Materializer = createLambdaMaterializer([&LD, &LMId,
629  &M](Value *V) -> Value * {
630  if (auto *GV = dyn_cast<GlobalVariable>(V))
631  return cloneGlobalVariableDecl(*M, *GV);
632 
633  if (auto *F = dyn_cast<Function>(V)) {
634  // Check whether we want to clone an available_externally definition.
635  if (!LD.getStubsToClone(LMId).count(F))
636  return cloneFunctionDecl(*M, *F);
637 
638  // Ok - we want an inlinable stub. For that to work we need a decl
639  // for the stub pointer.
640  auto *StubPtr = createImplPointer(*F->getType(), *M,
641  F->getName() + "$stub_ptr", nullptr);
642  auto *ClonedF = cloneFunctionDecl(*M, *F);
643  makeStub(*ClonedF, *StubPtr);
644  ClonedF->setLinkage(GlobalValue::AvailableExternallyLinkage);
645  ClonedF->addFnAttr(Attribute::AlwaysInline);
646  return ClonedF;
647  }
648 
649  if (auto *A = dyn_cast<GlobalAlias>(V)) {
650  auto *Ty = A->getValueType();
651  if (Ty->isFunctionTy())
652  return Function::Create(cast<FunctionType>(Ty),
653  GlobalValue::ExternalLinkage, A->getName(),
654  M.get());
655 
656  return new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage,
657  nullptr, A->getName(), nullptr,
659  A->getType()->getAddressSpace());
660  }
661 
662  return nullptr;
663  });
664 
665  // Create decls in the new module.
666  for (auto *F : Part)
667  cloneFunctionDecl(*M, *F, &VMap);
668 
669  // Move the function bodies.
670  for (auto *F : Part)
671  moveFunctionBody(*F, VMap, &Materializer);
672 
673  auto K = ES.allocateVModule();
674 
675  auto LegacyLookup = [this, &LD](const std::string &Name) -> JITSymbol {
676  return LD.findSymbol(BaseLayer, Name, false);
677  };
678 
679  // Create memory manager and symbol resolver.
681  [&LD, LegacyLookup](SymbolFlagsMap &SymbolFlags,
682  const SymbolNameSet &Symbols) {
683  auto NotFoundViaLegacyLookup =
684  lookupFlagsWithLegacyFn(SymbolFlags, Symbols, LegacyLookup);
685  if (!NotFoundViaLegacyLookup) {
686  logAllUnhandledErrors(NotFoundViaLegacyLookup.takeError(), errs(),
687  "CODLayer/SubResolver flags lookup failed: ");
688  SymbolFlags.clear();
689  return SymbolNameSet();
690  }
691  return LD.BackingResolver->lookupFlags(SymbolFlags,
692  *NotFoundViaLegacyLookup);
693  },
694  [this, &LD, LegacyLookup](std::shared_ptr<AsynchronousSymbolQuery> Q,
695  SymbolNameSet Symbols) {
696  auto NotFoundViaLegacyLookup =
697  lookupWithLegacyFn(ES, *Q, Symbols, LegacyLookup);
698  return LD.BackingResolver->lookup(Q,
699  std::move(NotFoundViaLegacyLookup));
700  });
701  SetSymbolResolver(K, std::move(Resolver));
702 
703  if (auto Err = BaseLayer.addModule(std::move(K), std::move(M)))
704  return std::move(Err);
705 
706  return K;
707  }
708 
709  ExecutionSession &ES;
710  BaseLayerT &BaseLayer;
711  SymbolResolverGetter GetSymbolResolver;
712  SymbolResolverSetter SetSymbolResolver;
713  PartitioningFtor Partition;
714  CompileCallbackMgrT &CompileCallbackMgr;
715  IndirectStubsManagerBuilderT CreateIndirectStubsManager;
716 
717  std::map<VModuleKey, LogicalDylib> LogicalDylibs;
718  bool CloneStubsIntoPartitions;
719 };
720 
721 } // end namespace orc
722 
723 } // end namespace llvm
724 
725 #endif // LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Base class for managing collections of named indirect stubs.
static JITSymbolFlags fromGlobalValue(const GlobalValue &GV)
Construct a JITSymbolFlags value based on the flags of the given global value.
Definition: JITSymbol.cpp:20
Represents a symbol in the JIT.
Definition: JITSymbol.h:186
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
GlobalAlias * cloneGlobalAliasDecl(Module &Dst, const GlobalAlias &OrigA, ValueToValueMapTy &VMap)
Clone a global alias declaration into a new module.
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
A symbol table that supports asynchoronous symbol queries.
Definition: Core.h:475
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner)
Log all errors (if any) in E to OS.
Definition: Error.cpp:57
JITSymbol findSymbolIn(VModuleKey K, const std::string &Name, bool ExportedSymbolsOnly)
Get the address of a symbol provided by this layer, or some layer below this one. ...
Error addExtraModule(VModuleKey K, std::unique_ptr< Module > M)
Add extra modules to an existing logical module.
void cloneModuleFlagsMetadata(Module &Dst, const Module &Src, ValueToValueMapTy &VMap)
Clone module flags metadata into the destination module.
Available for inspection, not emission.
Definition: GlobalValue.h:50
std::function< std::shared_ptr< SymbolResolver >(VModuleKey K)> GetSymbolResolverFunction
Retrieve symbol resolver for the given VModuleKey.
bool global_empty() const
Definition: Module.h:564
Externally visible function.
Definition: GlobalValue.h:49
StringRef getName() const
Get a short "name" for the module.
Definition: Module.h:225
F(f)
uint64_t VModuleKey
VModuleKey provides a unique identifier (allocated and managed by ExecutionSessions) for a module add...
Definition: Core.h:40
Target-independent base class for compile callback management.
std::function< std::unique_ptr< IndirectStubsManager >()> IndirectStubsManagerBuilder
Builder for IndirectStubsManagers.
Definition: BitVector.h:921
Expected< SymbolNameSet > lookupFlagsWithLegacyFn(SymbolFlagsMap &SymbolFlags, const SymbolNameSet &Symbols, FindSymbolFn FindSymbol)
Use the given legacy-style FindSymbol function (i.e.
Definition: Legacy.h:46
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:361
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
Definition: DataLayout.cpp:638
std::map< SymbolStringPtr, JITSymbolFlags > SymbolFlagsMap
A map from symbol names (as SymbolStringPtrs) to JITSymbolFlags.
Definition: Core.h:57
std::function< std::unique_ptr< IndirectStubsManager >()> IndirectStubsManagerBuilderT
Builder for IndirectStubsManagers.
GlobalVariable * createImplPointer(PointerType &PT, Module &M, const Twine &Name, Constant *Initializer)
Create a function pointer with the given type, name, and initializer in the given Module...
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:242
This file contains the simple types necessary to represent the attributes associated with functions a...
void moveGlobalVariableInitializer(GlobalVariable &OrigGV, ValueToValueMapTy &VMap, ValueMaterializer *Materializer=nullptr, GlobalVariable *NewGV=nullptr)
Move global variable GV from its parent module to cloned global declaration in a different module...
std::map< SymbolStringPtr, GlobalValue * > SymbolNameToDefinitionMap
Definition: Layer.h:62
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
This file implements a class to represent arbitrary precision integral constant values and operations...
void makeStub(Function &F, Value &ImplPointer)
Turn a function declaration into a stub function that makes an indirect call using the given function...
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
Definition: Core.h:104
std::function< std::set< Function *>(Function &)> PartitioningFtor
Module partitioning functor.
uint64_t JITTargetAddress
Represents an address in the target process&#39;s address space.
Definition: JITSymbol.h:40
GlobalVariable * cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV, ValueToValueMapTy *VMap=nullptr)
Clone a global variable declaration into a new module.
bool alias_empty() const
Definition: Module.h:604
std::function< void(VModuleKey K, std::shared_ptr< SymbolResolver > R)> SymbolResolverSetter
This is a class that can be implemented by clients to materialize Values on demand.
Definition: ValueMapper.h:51
void getModuleFlagsMetadata(SmallVectorImpl< ModuleFlagEntry > &Flags) const
Returns the module flags in the provided vector.
Definition: Module.cpp:282
This is an important base class in LLVM.
Definition: Constant.h:42
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define H(x, y, z)
Definition: MD5.cpp:57
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition: Record.h:1774
SymbolNameSet lookupWithLegacyFn(ExecutionSession &ES, AsynchronousSymbolQuery &Query, const SymbolNameSet &Symbols, FindSymbolFn FindSymbol)
Use the given legacy-style FindSymbol function (i.e.
Definition: Legacy.h:74
std::function< std::shared_ptr< SymbolResolver >(VModuleKey K)> SymbolResolverGetter
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.
Value * MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Look up or compute a value in the value map.
Definition: ValueMapper.h:206
Interface for layers that accept LLVM IR.
Definition: Layer.h:37
CompileOnDemandLayer(ExecutionSession &ES, BaseLayerT &BaseLayer, SymbolResolverGetter GetSymbolResolver, SymbolResolverSetter SetSymbolResolver, PartitioningFtor Partition, CompileCallbackMgrT &CallbackMgr, IndirectStubsManagerBuilderT CreateIndirectStubsManager, bool CloneStubsIntoPartitions=true)
Construct a compile-on-demand layer instance.
static ErrorSuccess success()
Create a success value.
Definition: Error.h:313
std::function< LLVMContext &()> GetAvailableContextFunction
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
Function * cloneFunctionDecl(Module &Dst, const Function &F, ValueToValueMapTy *VMap=nullptr)
Clone a function declaration into a new module.
Error removeModule(VModuleKey K)
Remove the module represented by the given key.
Module.h This file contains the declarations for the Module class.
const DataFlowGraph & G
Definition: RDFGraph.cpp:211
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:611
An ExecutionSession represents a running JIT program.
Definition: Core.h:625
std::function< void(VModuleKey K, std::shared_ptr< SymbolResolver > R)> SetSymbolResolverFunction
Set the symbol resolver for the given VModuleKey.
Class for arbitrary precision integers.
Definition: APInt.h:69
Error updatePointer(std::string FuncName, JITTargetAddress FnBodyAddr)
Update the stub for the given function to point at FnBodyAddr.
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:1497
void makeAllSymbolsExternallyAccessible(Module &M)
Raise linkage types and rename as necessary to ensure that all symbols are accessible for other modul...
void emit(MaterializationResponsibility R, VModuleKey K, std::unique_ptr< Module > M) override
Emit should materialize the given IR.
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:224
#define I(x, y, z)
Definition: MD5.cpp:58
Error addModule(VModuleKey K, std::unique_ptr< Module > M)
Add a module to the compile-on-demand layer.
static void rename(GlobalValue *GV)
Definition: AutoUpgrade.cpp:34
static void Query(const MachineInstr &MI, AliasAnalysis &AA, bool &Read, bool &Write, bool &Effects, bool &StackPointer)
CompileOnDemandLayer2(ExecutionSession &ES, IRLayer &BaseLayer, JITCompileCallbackManager &CCMgr, IndirectStubsManagerBuilder BuildIndirectStubsManager, GetSymbolResolverFunction GetSymbolResolver, SetSymbolResolverFunction SetSymbolResolver, GetAvailableContextFunction GetAvailableContext)
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:201
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: ValueMap.h:158
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:477
LLVM Value Representation.
Definition: Value.h:73
Error add(VSO &V, VModuleKey K, std::unique_ptr< Module > M) override
Adds a MaterializationUnit representing the given IR to the given VSO.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable&#39;s name.
Definition: Mangler.cpp:112
JITSymbol findSymbol(StringRef Name, bool ExportedSymbolsOnly)
Search for the given named symbol.
iterator_range< global_iterator > globals()
Definition: Module.h:566
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
Definition: Function.h:136
void moveFunctionBody(Function &OrigF, ValueToValueMapTy &VMap, ValueMaterializer *Materializer=nullptr, Function *NewF=nullptr)
Move the body of function &#39;F&#39; to a cloned function declaration in a different module (See related clo...
std::set< SymbolStringPtr > SymbolNameSet
A set of symbol names (represented by SymbolStringPtrs for.
Definition: Core.h:44
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:418
std::unique_ptr< LambdaSymbolResolver< typename std::remove_cv< typename std::remove_reference< LookupFlagsFn >::type >::type, typename std::remove_cv< typename std::remove_reference< LookupFn >::type >::type > > createSymbolResolver(LookupFlagsFn &&LookupFlags, LookupFn &&Lookup)
Creates a SymbolResolver implementation from the pair of supplied function objects.
Definition: Core.h:459
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:273
iterator_range< alias_iterator > aliases()
Definition: Module.h:606