23 template <
typename MaterializerFtor>
26 LambdaValueMaterializer(MaterializerFtor M) : M(
std::move(M)) {}
34 template <
typename MaterializerFtor>
35 LambdaValueMaterializer<MaterializerFtor>
36 createLambdaValueMaterializer(MaterializerFtor M) {
37 return LambdaValueMaterializer<MaterializerFtor>(std::move(M));
45 std::vector<GlobalAlias *> ModAliases;
47 ModAliases.push_back(&A);
49 for (
auto *A : ModAliases) {
51 assert(A->hasName() &&
"Anonymous alias?");
53 std::string AliasName = A->getName();
58 if (isa<Function>(Aliasee)) {
60 A->replaceAllUsesWith(
F);
62 F->setName(AliasName);
63 }
else if (isa<GlobalValue>(Aliasee)) {
65 A->replaceAllUsesWith(
G);
67 G->setName(AliasName);
74 static std::unique_ptr<Module>
80 std::set<GlobalValue *> ClonedDefsInSrc;
83 if (ShouldCloneDefinition(GV)) {
84 ClonedDefsInSrc.
insert(const_cast<GlobalValue *>(GV));
90 for (
auto *GV : ClonedDefsInSrc) {
92 if (isa<Function>(GV)) {
93 auto &
F = *cast<Function>(GV);
95 F.setPersonalityFn(
nullptr);
96 }
else if (isa<GlobalVariable>(GV)) {
97 cast<GlobalVariable>(GV)->setInitializer(
nullptr);
113 "cloned module buffer");
117 ClonedModule->setModuleIdentifier((M.
getName() + Suffix).str());
124 return isa<GlobalVariable>(GV);
135 std::unique_ptr<Module> M)
143 std::move(SymbolToDefinition)),
156 std::unique_ptr<Module> ExtractedFunctionsModule;
157 if (!RequestedSymbols.empty()) {
159 std::set<const GlobalValue *> FunctionsToClone;
160 for (
auto &
Name : RequestedSymbols) {
161 auto I = SymbolToDefinition.find(
Name);
162 assert(
I != SymbolToDefinition.end() &&
I->second !=
nullptr &&
163 "Should have a non-null definition");
164 FunctionsToClone.insert(
I->second);
169 std::lock_guard<std::mutex>
Lock(SourceModuleMutex);
170 ExtractedFunctionsModule =
173 return FunctionsToClone.count(GV);
181 DelegatedSymbolToDefinition;
182 for (
auto &KV : SymbolToDefinition) {
183 if (RequestedSymbols.count(KV.first))
185 DelegatedSymbolFlags[KV.first] =
187 DelegatedSymbolToDefinition[KV.first] = KV.second;
190 if (!DelegatedSymbolFlags.empty()) {
191 assert(DelegatedSymbolFlags.size() ==
192 DelegatedSymbolToDefinition.size() &&
193 "SymbolFlags and SymbolToDefinition should have the same number " 195 R.
replace(llvm::make_unique<ExtractingIRMaterializationUnit>(
196 std::move(M), std::move(DelegatedSymbolFlags),
197 std::move(DelegatedSymbolToDefinition), Parent));
200 if (ExtractedFunctionsModule)
201 Parent.emitExtractedFunctionsModule(std::move(R),
202 std::move(ExtractedFunctionsModule));
209 "ExtractingIRMaterializationUnit");
212 mutable std::mutex SourceModuleMutex;
220 :
IRLayer(ES), BaseLayer(BaseLayer), CCMgr(CCMgr),
221 BuildIndirectStubsManager(
std::move(BuildIndirectStubsManager)),
222 GetAvailableContext(
std::move(GetAvailableContext)) {}
225 std::unique_ptr<Module> M) {
230 std::unique_ptr<Module> M) {
232 assert(M &&
"M should not be null");
234 for (
auto &GV : M->global_values())
235 if (GV.hasWeakLinkage())
246 std::map<SymbolStringPtr, std::pair<JITTargetAddress, JITSymbolFlags>>
247 StubCallbacksAndLinkages;
250 for (
auto &
F : M->functions()) {
251 if (
F.isDeclaration())
254 if (
F.hasAvailableExternallyLinkage()) {
256 F.setPersonalityFn(
nullptr);
260 assert(
F.hasName() &&
"Function should have a name");
261 std::string StubUnmangledName =
F.getName();
262 F.setName(
F.getName() +
"$body");
264 StubDecl->setName(StubUnmangledName);
265 StubDecl->setPersonalityFn(
nullptr);
267 F.replaceAllUsesWith(StubDecl);
269 auto StubName =
Mangle(StubUnmangledName);
270 auto BodyName =
Mangle(
F.getName());
273 if (auto Sym = lookup({&TargetVSO}, BodyName))
274 return Sym->getAddress();
276 ES.reportError(Sym.takeError());
282 StubCallbacksAndLinkages[std::move(StubName)] =
283 std::make_pair(*CallbackAddr, Flags);
285 ES.reportError(CallbackAddr.takeError());
293 for (
auto &KV : StubCallbacksAndLinkages)
294 StubInits[*KV.first] = KV.second;
297 if (
auto Err = R.getTargetVSO().define(
298 llvm::make_unique<ExtractingIRMaterializationUnit>(ES, *
this,
300 ES.reportError(std::move(Err));
301 R.failMaterialization();
307 auto &StubsMgr = getStubsManager(TargetVSO);
308 if (
auto Err = StubsMgr.createStubs(StubInits)) {
309 ES.reportError(std::move(Err));
310 R.failMaterialization();
316 for (
auto &KV : StubCallbacksAndLinkages) {
317 if (
auto Sym = StubsMgr.findStub(*KV.first,
false))
318 ResolvedStubs[KV.first] = Sym;
323 R.resolve(ResolvedStubs);
325 BaseLayer.
emit(std::move(R), std::move(K), std::move(GlobalsModule));
329 std::lock_guard<std::mutex>
Lock(CODLayerMutex);
330 StubManagersMap::iterator
I = StubsMgrs.find(&V);
331 if (I == StubsMgrs.end())
332 I = StubsMgrs.insert(std::make_pair(&V, BuildIndirectStubsManager())).first;
336 void CompileOnDemandLayer2::emitExtractedFunctionsModule(
339 BaseLayer.
emit(std::move(R), std::move(K), std::move(M));
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
virtual Error add(VSO &V, VModuleKey K, std::unique_ptr< Module > M)
Adds a MaterializationUnit representing the given IR to the given VSO.
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.
Compute iterated dominance frontiers using a linear time algorithm.
std::unique_ptr< ReExportsMaterializationUnit > symbolAliases(SymbolAliasMap Aliases)
Create a ReExportsMaterializationUnit with the given aliases.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
A Module instance is used to store all the information related to an LLVM module. ...
A symbol table that supports asynchoronous symbol queries.
void replace(std::unique_ptr< MaterializationUnit > MU)
Transfers responsibility to the given MaterializationUnit for all symbols defined by that Materializa...
An efficient, type-erasing, non-owning reference to a callable.
void writeSymtab()
Attempt to write a symbol table to the bitcode file.
Externally visible function.
std::map< SymbolStringPtr, JITEvaluatedSymbol > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
StringRef getName() const
Get a short "name" for the module.
static void extractAliases(MaterializationResponsibility &R, Module &M, MangleAndInterner &Mangle)
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.
void writeModule(const Module &M, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the buffer specified at construction time.
std::function< std::unique_ptr< IndirectStubsManager >()> IndirectStubsManagerBuilder
Builder for IndirectStubsManagers.
std::map< SymbolStringPtr, JITSymbolFlags > SymbolFlagsMap
A map from symbol names (as SymbolStringPtrs) to JITSymbolFlags.
Mangles symbol names then uniques them in the context of an ExecutionSession.
static std::unique_ptr< Module > extractAndClone(Module &M, LLVMContext &NewContext, StringRef Suffix, function_ref< bool(const GlobalValue *)> ShouldCloneDefinition)
std::map< SymbolStringPtr, GlobalValue * > SymbolNameToDefinitionMap
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
virtual void emit(MaterializationResponsibility R, VModuleKey K, std::unique_ptr< Module > M)=0
Emit should materialize the given IR.
IRMaterializationUnit is a convenient base class for MaterializationUnits wrapping LLVM IR...
VModuleKey allocateVModule()
Allocate a module key for a new module to add to the JIT.
ExecutionSession & getExecutionSession()
Returns the ExecutionSession for this layer.
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.
Pointer to a pooled string representing a symbol name.
std::unique_ptr< Module > CloneModule(const Module &M)
Return an exact copy of the specified module.
This is a class that can be implemented by clients to materialize Values on demand.
This is an important class for using LLVM in a threaded context.
This is an important base class in LLVM.
Flags for symbols in the JIT.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
VSO & getTargetVSO() const
Returns the target VSO that these symbols are being materialized into.
Interface for layers that accept LLVM IR.
std::function< LLVMContext &()> GetAvailableContextFunction
Function * cloneFunctionDecl(Module &Dst, const Function &F, ValueToValueMapTy *VMap=nullptr)
Clone a function declaration into a new module.
SymbolNameSet getRequestedSymbols()
Returns the names of any symbols covered by this MaterializationResponsibility object that have queri...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Expected< JITTargetAddress > getCompileCallback(CompileFunction Compile)
Reserve a compile callback.
void setLinkage(LinkageTypes LT)
An ExecutionSession represents a running JIT program.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context)
Read the specified bitcode file, returning the module.
void emit(MaterializationResponsibility R, VModuleKey K, std::unique_ptr< Module > M) override
Emit should materialize the given IR.
pointer data()
Return a pointer to the vector's buffer, even if empty().
StringRef getName() const
Return a constant reference to the value's name.
static std::unique_ptr< Module > extractGlobals(Module &M, LLVMContext &NewContext)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void failMaterialization()
Notify all unfinalized symbols that an error has occurred.
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.
StringRef - Represent a constant reference to a string, i.e.
void writeStrtab()
Write the bitcode file's string table.
std::map< SymbolStringPtr, SymbolAliasMapEntry > SymbolAliasMap
A map of Symbols to (Symbol, Flags) pairs.
CompileOnDemandLayer2(ExecutionSession &ES, IRLayer &BaseLayer, JITCompileCallbackManager &CCMgr, IndirectStubsManagerBuilder BuildIndirectStubsManager, GetAvailableContextFunction GetAvailableContext)
iterator_range< alias_iterator > aliases()