15 #ifndef LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H 16 #define LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H 69 std::function<std::unique_ptr<IndirectStubsManager>()>;
81 std::unique_ptr<Module> M)
override;
84 using StubManagersMap =
85 std::map<const VSO *, std::unique_ptr<IndirectStubsManager>>;
90 std::unique_ptr<Module> M);
92 mutable std::mutex CODLayerMutex;
97 StubManagersMap StubsMgrs;
108 template <
typename BaseLayerT,
113 template <
typename MaterializerFtor>
116 LambdaMaterializer(MaterializerFtor M) : M(std::move(M)) {}
118 Value *materialize(
Value *V)
final {
return M(V); }
124 template <
typename MaterializerFtor>
125 LambdaMaterializer<MaterializerFtor>
126 createLambdaMaterializer(MaterializerFtor M) {
127 return LambdaMaterializer<MaterializerFtor>(std::move(M));
131 template <
typename ResourceT>
132 class ResourceOwner {
134 ResourceOwner() =
default;
135 ResourceOwner(
const ResourceOwner &) =
delete;
136 ResourceOwner &operator=(
const ResourceOwner &) =
delete;
137 virtual ~ResourceOwner() =
default;
139 virtual ResourceT& getResource()
const = 0;
142 template <
typename ResourceT,
typename ResourcePtrT>
143 class ResourceOwnerImpl :
public ResourceOwner<ResourceT> {
145 ResourceOwnerImpl(ResourcePtrT ResourcePtr)
146 : ResourcePtr(std::move(ResourcePtr)) {}
148 ResourceT& getResource()
const override {
return *ResourcePtr; }
151 ResourcePtrT ResourcePtr;
154 template <
typename ResourceT,
typename ResourcePtrT>
155 std::unique_ptr<ResourceOwner<ResourceT>>
156 wrapOwnership(ResourcePtrT ResourcePtr) {
157 using RO = ResourceOwnerImpl<ResourceT, ResourcePtrT>;
158 return llvm::make_unique<RO>(std::move(ResourcePtr));
161 class StaticGlobalRenamer {
163 StaticGlobalRenamer() =
default;
164 StaticGlobalRenamer(StaticGlobalRenamer &&) =
default;
165 StaticGlobalRenamer &operator=(StaticGlobalRenamer &&) =
default;
169 if (
F.hasLocalLinkage())
170 F.setName(
"$static." +
Twine(NextId++));
171 for (
auto &
G : M.globals())
172 if (
G.hasLocalLinkage())
173 G.setName(
"$static." +
Twine(NextId++));
180 struct LogicalDylib {
186 using SourceModulesList = std::vector<SourceModuleEntry>;
187 using SourceModuleHandle =
typename SourceModulesList::size_type;
189 LogicalDylib() =
default;
191 LogicalDylib(
VModuleKey K, std::shared_ptr<SymbolResolver> BackingResolver,
192 std::unique_ptr<IndirectStubsMgrT> StubsMgr)
193 : K(
std::move(K)), BackingResolver(
std::move(BackingResolver)),
194 StubsMgr(
std::move(StubsMgr)) {}
196 SourceModuleHandle addSourceModule(std::unique_ptr<Module> M) {
197 SourceModuleHandle
H = SourceModules.size();
199 SourceModules.back().SourceMod = std::move(M);
203 Module& getSourceModule(SourceModuleHandle
H) {
204 return *SourceModules[
H].SourceMod;
207 std::set<Function*>& getStubsToClone(SourceModuleHandle H) {
208 return SourceModules[
H].StubsToClone;
211 JITSymbol findSymbol(BaseLayerT &BaseLayer,
const std::string &
Name,
212 bool ExportedSymbolsOnly) {
213 if (
auto Sym = StubsMgr->findStub(Name, ExportedSymbolsOnly))
215 for (
auto BLK : BaseLayerVModuleKeys)
216 if (
auto Sym = BaseLayer.findSymbolIn(BLK, Name, ExportedSymbolsOnly))
218 else if (
auto Err = Sym.takeError())
219 return std::move(Err);
223 Error removeModulesFromBaseLayer(BaseLayerT &BaseLayer) {
224 for (
auto &BLK : BaseLayerVModuleKeys)
225 if (
auto Err = BaseLayer.removeModule(BLK))
231 std::shared_ptr<SymbolResolver> BackingResolver;
232 std::unique_ptr<IndirectStubsMgrT> StubsMgr;
233 StaticGlobalRenamer StaticRenamer;
234 SourceModulesList SourceModules;
235 std::vector<VModuleKey> BaseLayerVModuleKeys;
245 std::function<std::unique_ptr<IndirectStubsMgrT>()>;
248 std::function<std::shared_ptr<SymbolResolver>(
VModuleKey K)>;
251 std::function<void(VModuleKey K, std::shared_ptr<SymbolResolver> R)>;
255 SymbolResolverGetter GetSymbolResolver,
256 SymbolResolverSetter SetSymbolResolver,
258 CompileCallbackMgrT &CallbackMgr,
259 IndirectStubsManagerBuilderT CreateIndirectStubsManager,
260 bool CloneStubsIntoPartitions =
true)
261 : ES(ES), BaseLayer(BaseLayer),
262 GetSymbolResolver(
std::move(GetSymbolResolver)),
263 SetSymbolResolver(
std::move(SetSymbolResolver)),
264 Partition(
std::move(Partition)), CompileCallbackMgr(CallbackMgr),
265 CreateIndirectStubsManager(
std::move(CreateIndirectStubsManager)),
266 CloneStubsIntoPartitions(CloneStubsIntoPartitions) {}
270 while (!LogicalDylibs.empty())
271 consumeError(removeModule(LogicalDylibs.begin()->first));
277 assert(!LogicalDylibs.count(K) &&
"VModuleKey K already in use");
278 auto I = LogicalDylibs.insert(
280 std::make_pair(K, LogicalDylib(K, GetSymbolResolver(K),
281 CreateIndirectStubsManager())));
283 return addLogicalModule(I->second, std::move(M));
288 return addLogicalModule(LogicalDylibs[K], std::move(M));
296 auto I = LogicalDylibs.find(K);
297 assert(
I != LogicalDylibs.end() &&
"VModuleKey K not valid here");
298 auto Err =
I->second.removeModulesFromBaseLayer(BaseLayer);
299 LogicalDylibs.erase(
I);
308 for (
auto &KV : LogicalDylibs) {
309 if (
auto Sym = KV.second.StubsMgr->findStub(Name, ExportedSymbolsOnly))
311 if (
auto Sym = findSymbolIn(KV.first, Name, ExportedSymbolsOnly))
313 else if (
auto Err = Sym.takeError())
314 return std::move(Err);
316 return BaseLayer.findSymbol(Name, ExportedSymbolsOnly);
322 bool ExportedSymbolsOnly) {
323 assert(LogicalDylibs.count(K) &&
"VModuleKey K is not valid here");
324 return LogicalDylibs[K].findSymbol(BaseLayer, Name, ExportedSymbolsOnly);
337 auto LDI = LogicalDylibs.begin();
338 for (
auto LDE = LogicalDylibs.end(); LDI != LDE; ++LDI) {
339 if (
auto LMResources =
340 LDI->getLogicalModuleResourcesForSymbol(FuncName,
false)) {
341 Module &SrcM = LMResources->SourceModule->getResource();
342 std::string CalledFnName = mangle(FuncName, SrcM.
getDataLayout());
343 if (
auto Err = LMResources->StubsMgr->updatePointer(CalledFnName,
349 return make_error<JITSymbolNotFound>(FuncName);
353 Error addLogicalModule(LogicalDylib &
LD, std::unique_ptr<Module> SrcMPtr) {
358 LD.StaticRenamer.rename(*SrcMPtr);
366 auto LMId = LD.addSourceModule(std::move(SrcMPtr));
371 typename IndirectStubsMgrT::StubInitsMap StubInits;
372 for (
auto &
F : SrcM) {
374 if (
F.isDeclaration())
378 auto MangledName = mangle(
F.getName(), DL);
379 if (
F.hasWeakLinkage() ||
F.hasLinkOnceLinkage()) {
380 if (
auto Sym = LD.findSymbol(BaseLayer, MangledName,
false))
382 else if (
auto Err = Sym.takeError())
383 return std::move(Err);
387 if (CloneStubsIntoPartitions)
388 LD.getStubsToClone(LMId).insert(&
F);
394 if (
auto FnImplAddrOrErr = this->extractAndCompile(LD, LMId,
F))
395 return *FnImplAddrOrErr;
403 CompileCallbackMgr.getCompileCallback(std::move(CompileAction)))
404 StubInits[MangledName] =
407 return CCAddr.takeError();
410 if (
auto Err = LD.StubsMgr->createStubs(StubInits))
422 auto GVsM = llvm::make_unique<Module>((SrcM.
getName() +
".globals").str(),
424 GVsM->setDataLayout(DL);
429 for (
auto &GV : SrcM.
globals())
430 if (!GV.isDeclaration() && !VMap.
count(&GV))
445 auto Materializer = createLambdaMaterializer(
447 if (
auto *
F = dyn_cast<Function>(V)) {
449 if (
F->isDeclaration())
456 std::string FName = mangle(
F->getName(), DL);
459 LD.StubsMgr->findStub(FName,
false).getAddress();
464 StubAddrCI,
F->getType());
466 F->getType()->getAddressSpace(),
467 F->getLinkage(),
F->getName(),
475 for (
auto &GV : SrcM.
globals())
476 if (!GV.isDeclaration())
480 for (
auto &A : SrcM.
aliases()) {
481 auto *NewA = cast<GlobalAlias>(VMap[&A]);
482 assert(NewA &&
"Alias not cloned?");
485 NewA->setAliasee(cast<Constant>(Init));
489 auto LegacyLookup = [
this, &
LD](
const std::string &
Name) ->
JITSymbol {
490 if (
auto Sym = LD.StubsMgr->findStub(
Name,
false))
493 if (
auto Sym = LD.findSymbol(BaseLayer,
Name,
false))
495 else if (
auto Err = Sym.takeError())
496 return std::move(Err);
507 "CODLayer/GVsResolver flags lookup failed: ");
511 if (SymbolFlags->size() == Symbols.size())
515 for (
auto &S : Symbols)
516 if (!SymbolFlags->count(S))
517 NotFoundViaLegacyLookup.insert(S);
519 LD.BackingResolver->lookupFlags(NotFoundViaLegacyLookup);
521 for (
auto &KV : SymbolFlags2)
522 (*SymbolFlags)[KV.first] = std::move(KV.second);
527 LegacyLookup](std::shared_ptr<AsynchronousSymbolQuery>
Query,
529 auto NotFoundViaLegacyLookup =
531 return LD.BackingResolver->lookup(Query, NotFoundViaLegacyLookup);
534 SetSymbolResolver(LD.K, std::move(GVsResolver));
536 if (
auto Err = BaseLayer.addModule(LD.K, std::move(GVsM)))
539 LD.BaseLayerVModuleKeys.push_back(LD.K);
545 std::string MangledName;
554 extractAndCompile(LogicalDylib &LD,
555 typename LogicalDylib::SourceModuleHandle LMId,
557 Module &SrcM = LD.getSourceModule(LMId);
567 auto Part = Partition(F);
568 if (
auto PartKeyOrErr = emitPartition(LD, LMId, Part)) {
569 auto &PartKey = *PartKeyOrErr;
570 for (
auto *SubF : Part) {
571 std::string FnName = mangle(SubF->getName(), SrcM.
getDataLayout());
572 if (
auto FnBodySym = BaseLayer.findSymbolIn(PartKey, FnName,
false)) {
573 if (
auto FnBodyAddrOrErr = FnBodySym.getAddress()) {
579 CalledAddr = FnBodyAddr;
582 if (
auto EC = LD.StubsMgr->updatePointer(FnName, FnBodyAddr))
586 return FnBodyAddrOrErr.takeError();
587 }
else if (
auto Err = FnBodySym.takeError())
588 return std::move(Err);
593 LD.BaseLayerVModuleKeys.push_back(PartKey);
595 return PartKeyOrErr.takeError();
600 template <
typename PartitionT>
602 emitPartition(LogicalDylib &LD,
603 typename LogicalDylib::SourceModuleHandle LMId,
604 const PartitionT &Part) {
605 Module &SrcM = LD.getSourceModule(LMId);
608 std::string NewName = SrcM.
getName();
609 for (
auto *F : Part) {
614 auto M = llvm::make_unique<Module>(NewName, SrcM.
getContext());
618 auto Materializer = createLambdaMaterializer([&LD, &LMId,
620 if (
auto *GV = dyn_cast<GlobalVariable>(V))
623 if (
auto *F = dyn_cast<Function>(V)) {
625 if (!LD.getStubsToClone(LMId).count(F))
631 F->
getName() +
"$stub_ptr",
nullptr);
635 ClonedF->addFnAttr(Attribute::AlwaysInline);
639 if (
auto *A = dyn_cast<GlobalAlias>(V)) {
640 auto *Ty = A->getValueType();
641 if (Ty->isFunctionTy())
647 nullptr, A->getName(),
nullptr,
649 A->getType()->getAddressSpace());
663 auto K = ES.allocateVModule();
665 auto LegacyLookup = [
this, &
LD](
const std::string &
Name) ->
JITSymbol {
666 return LD.findSymbol(BaseLayer, Name,
false);
675 "CODLayer/SubResolver flags lookup failed: ");
679 if (SymbolFlags->size() == Symbols.size())
683 for (
auto &S : Symbols)
684 if (!SymbolFlags->count(S))
685 NotFoundViaLegacyLookup.insert(S);
688 LD.BackingResolver->lookupFlags(NotFoundViaLegacyLookup);
690 for (
auto &KV : SymbolFlags2)
691 (*SymbolFlags)[KV.first] = std::move(KV.second);
695 [
this, &
LD, LegacyLookup](std::shared_ptr<AsynchronousSymbolQuery> Q,
697 auto NotFoundViaLegacyLookup =
699 return LD.BackingResolver->lookup(Q,
700 std::move(NotFoundViaLegacyLookup));
702 SetSymbolResolver(K, std::move(
Resolver));
704 if (
auto Err = BaseLayer.addModule(std::move(K), std::move(M)))
705 return std::move(Err);
711 BaseLayerT &BaseLayer;
712 SymbolResolverGetter GetSymbolResolver;
713 SymbolResolverSetter SetSymbolResolver;
715 CompileCallbackMgrT &CompileCallbackMgr;
716 IndirectStubsManagerBuilderT CreateIndirectStubsManager;
718 std::map<VModuleKey, LogicalDylib> LogicalDylibs;
719 bool CloneStubsIntoPartitions;
726 #endif // LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H A parsed version of the target data layout string in and methods for querying it. ...
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.
Represents a symbol in the JIT.
Compute iterated dominance frontiers using a linear time algorithm.
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. ...
A symbol table that supports asynchoronous symbol queries.
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner)
Log all errors (if any) in E to OS.
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.
bool global_empty() const
Externally visible function.
StringRef getName() const
Get a short "name" for the module.
uint64_t VModuleKey
VModuleKey provides a unique identifier (allocated and managed by ExecutionSessions) for a module add...
Target-independent base class for compile callback management.
std::function< std::unique_ptr< IndirectStubsManager >()> IndirectStubsManagerBuilder
Builder for IndirectStubsManagers.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
std::map< SymbolStringPtr, JITSymbolFlags > SymbolFlagsMap
A map from symbol names (as SymbolStringPtrs) to JITSymbolFlags.
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.
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...
Tagged union holding either a T or a Error.
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...
std::function< std::set< Function *>(Function &)> PartitioningFtor
Module partitioning functor.
uint64_t JITTargetAddress
Represents an address in the target process's address space.
GlobalVariable * cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV, ValueToValueMapTy *VMap=nullptr)
Clone a global variable declaration into a new module.
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.
void getModuleFlagsMetadata(SmallVectorImpl< ModuleFlagEntry > &Flags) const
Returns the module flags in the provided vector.
This is an important base class in LLVM.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
SymbolNameSet lookupWithLegacyFn(ExecutionSession &ES, AsynchronousSymbolQuery &Query, const SymbolNameSet &Symbols, FindSymbolFn FindSymbol)
Use the given legacy-style FindSymbol function (i.e.
std::function< std::shared_ptr< SymbolResolver >(VModuleKey K)> SymbolResolverGetter
std::set< Function * > StubsToClone
void consumeError(Error Err)
Consume a Error without doing anything.
#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.
Interface for layers that accept LLVM IR.
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.
std::function< LLVMContext &()> GetAvailableContextFunction
std::unique_ptr< Module > SourceMod
This is the shared class of boolean and integer constants.
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.
Expected< SymbolFlagsMap > lookupFlagsWithLegacyFn(const SymbolNameSet &Symbols, FindSymbolFn FindSymbol)
Use the given legacy-style FindSymbol function (i.e.
Module.h This file contains the declarations for the Module class.
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.
An ExecutionSession represents a running JIT program.
Class for arbitrary precision integers.
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.
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's name.
Error addModule(VModuleKey K, std::unique_ptr< Module > M)
Add a module to the compile-on-demand layer.
static void rename(GlobalValue *GV)
static void Query(const MachineInstr &MI, AliasAnalysis &AA, bool &Read, bool &Write, bool &Effects, bool &StackPointer)
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
LLVM Value Representation.
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.
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
JITSymbol findSymbol(StringRef Name, bool ExportedSymbolsOnly)
Search for the given named symbol.
iterator_range< global_iterator > globals()
StringRef - Represent a constant reference to a string, i.e.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
void moveFunctionBody(Function &OrigF, ValueToValueMapTy &VMap, ValueMaterializer *Materializer=nullptr, Function *NewF=nullptr)
Move the body of function 'F' 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.
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...
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.
CompileOnDemandLayer2(ExecutionSession &ES, IRLayer &BaseLayer, JITCompileCallbackManager &CCMgr, IndirectStubsManagerBuilder BuildIndirectStubsManager, GetAvailableContextFunction GetAvailableContext)
PointerType * getType() const
Global values are always pointers.
iterator_range< alias_iterator > aliases()