15 #ifndef LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H
16 #define LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H
66 template <
typename BaseLayerT,
71 template <
typename MaterializerFtor>
74 LambdaMaterializer(MaterializerFtor M) : M(std::move(M)) {}
76 Value *materialize(
Value *V)
final {
return M(V); }
82 template <
typename MaterializerFtor>
83 LambdaMaterializer<MaterializerFtor>
84 createLambdaMaterializer(MaterializerFtor M) {
85 return LambdaMaterializer<MaterializerFtor>(std::move(M));
91 template <
typename ResourceT>
94 ResourceOwner() =
default;
95 ResourceOwner(
const ResourceOwner &) =
delete;
96 ResourceOwner &operator=(
const ResourceOwner &) =
delete;
97 virtual ~ResourceOwner() =
default;
99 virtual ResourceT& getResource()
const = 0;
102 template <
typename ResourceT,
typename ResourcePtrT>
103 class ResourceOwnerImpl :
public ResourceOwner<ResourceT> {
105 ResourceOwnerImpl(ResourcePtrT ResourcePtr)
106 : ResourcePtr(std::move(ResourcePtr)) {}
108 ResourceT& getResource()
const override {
return *ResourcePtr; }
111 ResourcePtrT ResourcePtr;
114 template <
typename ResourceT,
typename ResourcePtrT>
115 std::unique_ptr<ResourceOwner<ResourceT>>
116 wrapOwnership(ResourcePtrT ResourcePtr) {
117 using RO = ResourceOwnerImpl<ResourceT, ResourcePtrT>;
118 return llvm::make_unique<RO>(std::move(ResourcePtr));
121 class StaticGlobalRenamer {
123 StaticGlobalRenamer() =
default;
124 StaticGlobalRenamer(StaticGlobalRenamer &&) =
default;
125 StaticGlobalRenamer &operator=(StaticGlobalRenamer &&) =
default;
129 if (
F.hasLocalLinkage())
130 F.setName(
"$static." +
Twine(NextId++));
131 for (
auto &
G : M.globals())
132 if (
G.hasLocalLinkage())
133 G.setName(
"$static." +
Twine(NextId++));
140 struct LogicalDylib {
141 using SymbolResolverFtor = std::function<JITSymbol(const std::string&)>;
143 using ModuleAdderFtor =
146 std::unique_ptr<Module>,
147 std::unique_ptr<JITSymbolResolver>)>;
154 using SourceModulesList = std::vector<SourceModuleEntry>;
155 using SourceModuleHandle =
typename SourceModulesList::size_type;
158 addSourceModule(std::shared_ptr<Module> M) {
159 SourceModuleHandle
H = SourceModules.size();
161 SourceModules.back().SourceMod = std::move(M);
165 Module& getSourceModule(SourceModuleHandle
H) {
166 return *SourceModules[
H].SourceMod;
169 std::set<Function*>& getStubsToClone(SourceModuleHandle
H) {
170 return SourceModules[
H].StubsToClone;
174 bool ExportedSymbolsOnly) {
175 if (
auto Sym = StubsMgr->findStub(Name, ExportedSymbolsOnly))
177 for (
auto BLH : BaseLayerHandles)
178 if (
auto Sym = BaseLayer.findSymbolIn(BLH, Name, ExportedSymbolsOnly))
180 else if (
auto Err = Sym.takeError())
181 return std::move(Err);
185 Error removeModulesFromBaseLayer(BaseLayerT &BaseLayer) {
186 for (
auto &BLH : BaseLayerHandles)
187 if (
auto Err = BaseLayer.removeModule(BLH))
192 std::shared_ptr<JITSymbolResolver> ExternalSymbolResolver;
193 std::unique_ptr<IndirectStubsMgrT> StubsMgr;
194 StaticGlobalRenamer StaticRenamer;
195 SourceModulesList SourceModules;
196 std::vector<BaseLayerModuleHandleT> BaseLayerHandles;
199 using LogicalDylibList = std::list<LogicalDylib>;
211 std::function<std::unique_ptr<IndirectStubsMgrT>()>;
215 CompileCallbackMgrT &CallbackMgr,
217 bool CloneStubsIntoPartitions =
true)
218 : BaseLayer(BaseLayer), Partition(std::move(Partition)),
219 CompileCallbackMgr(CallbackMgr),
220 CreateIndirectStubsManager(std::move(CreateIndirectStubsManager)),
221 CloneStubsIntoPartitions(CloneStubsIntoPartitions) {}
225 while (!LogicalDylibs.empty())
232 std::shared_ptr<JITSymbolResolver> Resolver) {
234 LogicalDylibs.push_back(LogicalDylib());
235 auto &
LD = LogicalDylibs.back();
236 LD.ExternalSymbolResolver = std::move(Resolver);
237 LD.StubsMgr = CreateIndirectStubsManager();
240 if (
auto Err = addLogicalModule(
LD, std::move(M)))
241 return std::move(Err);
243 return std::prev(LogicalDylibs.end());
248 return addLogicalModule(*H, std::move(M));
256 auto Err = H->removeModulesFromBaseLayer(BaseLayer);
257 LogicalDylibs.erase(H);
266 for (
auto LDI = LogicalDylibs.begin(), LDE = LogicalDylibs.end();
268 if (
auto Sym = LDI->StubsMgr->findStub(Name, ExportedSymbolsOnly))
270 if (
auto Sym =
findSymbolIn(LDI, Name, ExportedSymbolsOnly))
272 else if (
auto Err = Sym.takeError())
273 return std::move(Err);
275 return BaseLayer.findSymbol(Name, ExportedSymbolsOnly);
281 bool ExportedSymbolsOnly) {
282 return H->findSymbol(BaseLayer, Name, ExportedSymbolsOnly);
295 auto LDI = LogicalDylibs.begin();
296 for (
auto LDE = LogicalDylibs.end(); LDI != LDE; ++LDI) {
297 if (
auto LMResources =
298 LDI->getLogicalModuleResourcesForSymbol(FuncName,
false)) {
299 Module &SrcM = LMResources->SourceModule->getResource();
300 std::string CalledFnName = mangle(FuncName, SrcM.
getDataLayout());
301 if (
auto Err = LMResources->StubsMgr->updatePointer(CalledFnName,
307 return make_error<JITSymbolNotFound>(FuncName);
312 Error addLogicalModule(LogicalDylib &
LD, std::shared_ptr<Module> SrcMPtr) {
317 LD.StaticRenamer.rename(*SrcMPtr);
325 auto LMId = LD.addSourceModule(std::move(SrcMPtr));
330 typename IndirectStubsMgrT::StubInitsMap StubInits;
331 for (
auto &
F : SrcM) {
333 if (
F.isDeclaration())
337 auto MangledName = mangle(
F.getName(), DL);
338 if (
F.hasWeakLinkage() ||
F.hasLinkOnceLinkage()) {
339 if (
auto Sym = LD.findSymbol(BaseLayer, MangledName,
false))
341 else if (
auto Err = Sym.takeError())
342 return std::move(Err);
346 if (CloneStubsIntoPartitions)
347 LD.getStubsToClone(LMId).insert(&
F);
352 auto CCInfo = CompileCallbackMgr.getCompileCallback();
353 StubInits[MangledName] =
354 std::make_pair(CCInfo.getAddress(),
357 if (
auto FnImplAddrOrErr = this->extractAndCompile(LD, LMId,
F))
358 return *FnImplAddrOrErr;
367 if (
auto Err = LD.StubsMgr->createStubs(StubInits))
374 if (SrcM.global_empty() && SrcM.alias_empty() &&
375 !SrcM.getModuleFlagsMetadata())
379 auto GVsM = llvm::make_unique<Module>((SrcM.getName() +
".globals").str(),
381 GVsM->setDataLayout(DL);
386 for (
auto &GV : SrcM.globals())
387 if (!GV.isDeclaration() && !VMap.count(&GV))
391 for (
auto &
A : SrcM.aliases())
403 auto Materializer = createLambdaMaterializer(
404 [&LD, &GVsM, &MaterializerErrors](Value *V) -> Value* {
405 if (
auto *
F = dyn_cast<Function>(V)) {
407 if (
F->isDeclaration())
413 const DataLayout &DL = GVsM->getDataLayout();
414 std::string FName = mangle(
F->getName(), DL);
415 unsigned PtrBitWidth = DL.getPointerTypeSizeInBits(
F->getType());
421 if (
auto StubSym = LD.StubsMgr->findStub(FName,
false)) {
422 if (
auto StubAddrOrErr = StubSym.getAddress())
423 StubAddr = *StubAddrOrErr;
425 MaterializerErrors =
joinErrors(std::move(MaterializerErrors),
426 StubAddrOrErr.takeError());
429 ConstantInt *StubAddrCI =
432 StubAddrCI,
F->getType());
434 F->getType()->getAddressSpace(),
435 F->getLinkage(),
F->getName(),
443 for (
auto &GV : SrcM.globals())
444 if (!GV.isDeclaration())
448 for (
auto &
A : SrcM.aliases()) {
449 auto *NewA = cast<GlobalAlias>(VMap[&
A]);
450 assert(NewA &&
"Alias not cloned?");
453 NewA->setAliasee(cast<Constant>(Init));
456 if (MaterializerErrors)
457 return MaterializerErrors;
461 [
this, &LD](
const std::string &Name) -> JITSymbol {
462 if (
auto Sym = LD.StubsMgr->findStub(Name,
false))
464 if (
auto Sym = LD.findSymbol(BaseLayer, Name,
false))
466 else if (
auto Err = Sym.takeError())
467 return std::move(Err);
468 return LD.ExternalSymbolResolver->findSymbolInLogicalDylib(Name);
470 [&
LD](
const std::string &
Name) {
471 return LD.ExternalSymbolResolver->findSymbol(Name);
475 BaseLayer.addModule(std::move(GVsM), std::move(GVsResolver)))
476 LD.BaseLayerHandles.push_back(*GVsHOrErr);
478 return GVsHOrErr.takeError();
483 static std::string mangle(StringRef Name,
const DataLayout &DL) {
484 std::string MangledName;
486 raw_string_ostream MangledNameStream(MangledName);
492 Expected<JITTargetAddress>
493 extractAndCompile(LogicalDylib &LD,
494 typename LogicalDylib::SourceModuleHandle LMId,
496 Module &SrcM = LD.getSourceModule(LMId);
499 if (F.isDeclaration())
503 std::string CalledFnName = mangle(F.getName(), SrcM.getDataLayout());
506 auto Part = Partition(F);
507 if (
auto PartHOrErr = emitPartition(LD, LMId, Part)) {
508 auto &PartH = *PartHOrErr;
509 for (
auto *SubF : Part) {
510 std::string FnName = mangle(SubF->getName(), SrcM.getDataLayout());
511 if (
auto FnBodySym = BaseLayer.findSymbolIn(PartH, FnName,
false)) {
512 if (
auto FnBodyAddrOrErr = FnBodySym.getAddress()) {
518 CalledAddr = FnBodyAddr;
521 if (
auto EC = LD.StubsMgr->updatePointer(FnName, FnBodyAddr))
525 return FnBodyAddrOrErr.takeError();
526 }
else if (
auto Err = FnBodySym.takeError())
527 return std::move(Err);
532 LD.BaseLayerHandles.push_back(PartH);
534 return PartHOrErr.takeError();
539 template <
typename PartitionT>
540 Expected<BaseLayerModuleHandleT>
541 emitPartition(LogicalDylib &LD,
542 typename LogicalDylib::SourceModuleHandle LMId,
543 const PartitionT &Part) {
544 Module &SrcM = LD.getSourceModule(LMId);
547 std::string NewName = SrcM.getName();
548 for (
auto *F : Part) {
550 NewName += F->getName();
553 auto M = llvm::make_unique<Module>(NewName, SrcM.getContext());
554 M->setDataLayout(SrcM.getDataLayout());
557 auto Materializer = createLambdaMaterializer([&LD, &LMId,
558 &M](Value *V) -> Value * {
559 if (
auto *GV = dyn_cast<GlobalVariable>(V))
562 if (
auto *F = dyn_cast<Function>(V)) {
564 if (!LD.getStubsToClone(LMId).count(F))
570 F->getName() +
"$stub_ptr",
nullptr);
574 ClonedF->addFnAttr(Attribute::AlwaysInline);
578 if (
auto *
A = dyn_cast<GlobalAlias>(V)) {
579 auto *Ty =
A->getValueType();
580 if (Ty->isFunctionTy())
586 nullptr,
A->getName(),
nullptr,
588 A->getType()->getAddressSpace());
604 [
this, &LD](
const std::string &Name) -> JITSymbol {
605 if (
auto Sym = LD.findSymbol(BaseLayer, Name,
false))
607 else if (
auto Err = Sym.takeError())
608 return std::move(Err);
609 return LD.ExternalSymbolResolver->findSymbolInLogicalDylib(Name);
611 [&
LD](
const std::string &
Name) {
612 return LD.ExternalSymbolResolver->findSymbol(Name);
615 return BaseLayer.addModule(std::move(M), std::move(Resolver));
618 BaseLayerT &BaseLayer;
620 CompileCallbackMgrT &CompileCallbackMgr;
623 LogicalDylibList LogicalDylibs;
624 bool CloneStubsIntoPartitions;
631 #endif // LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H
A parsed version of the target data layout string in and methods for querying it. ...
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
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.
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. ...
void cloneModuleFlagsMetadata(Module &Dst, const Module &Src, ValueToValueMapTy &VMap)
Clone module flags metadata into the destination module.
Available for inspection, not emission.
Externally visible function.
Target-independent base class for compile callback management.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
std::function< std::unique_ptr< IndirectStubsMgrT >()> 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...
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...
CompileOnDemandLayer(BaseLayerT &BaseLayer, PartitioningFtor Partition, CompileCallbackMgrT &CallbackMgr, IndirectStubsManagerBuilderT CreateIndirectStubsManager, bool CloneStubsIntoPartitions=true)
Construct a compile-on-demand layer instance.
std::function< std::set< Function * >(Function &)> PartitioningFtor
Module partitioning functor.
uint64_t JITTargetAddress
Represents an address in the target process's address space.
Expected< ModuleHandleT > addModule(std::shared_ptr< Module > M, std::shared_ptr< JITSymbolResolver > Resolver)
Add a module to the compile-on-demand layer.
GlobalVariable * cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV, ValueToValueMapTy *VMap=nullptr)
Clone a global variable declaration into a new module.
This is a class that can be implemented by clients to materialize Values on demand.
std::shared_ptr< Module > SourceMod
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::set< Function * > StubsToClone
void consumeError(Error Err)
Consume a Error without doing anything.
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.
static ErrorSuccess success()
Create a success value.
Error addExtraModule(ModuleHandleT H, std::shared_ptr< Module > M)
Add extra modules to an existing logical module.
Function * cloneFunctionDecl(Module &Dst, const Function &F, ValueToValueMapTy *VMap=nullptr)
Clone a function declaration into a new module.
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.
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...
typename LogicalDylibList::iterator ModuleHandleT
Handle to loaded module.
JITSymbol findSymbolIn(ModuleHandleT H, const std::string &Name, bool ExportedSymbolsOnly)
Get the address of a symbol provided by this layer, or some layer below this one. ...
llvm_unreachable("Unknown RegBank!")
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
Error joinErrors(Error E1, Error E2)
Concatenate errors.
static void rename(GlobalValue *GV)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
std::shared_ptr< LambdaResolver< DylibLookupFtorT, ExternalLookupFtorT > > createLambdaResolver(DylibLookupFtorT DylibLookupFtor, ExternalLookupFtorT ExternalLookupFtor)
Lightweight error class with error context and mandatory checking.
Error removeModule(ModuleHandleT H)
Remove the module represented by the given handle.
JITSymbol findSymbol(StringRef Name, bool ExportedSymbolsOnly)
Search for the given named symbol.
print Print MemDeps of function
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...
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...