18#define DEBUG_TYPE "orc"
26 : ES(ES), ErrorHandlerAddr(ErrorHandlerAddr), TP(TP) {}
31 assert(TP &&
"TrampolinePool not set");
33 std::lock_guard<std::mutex> Lock(LCTMMutex);
34 auto Trampoline = TP->getTrampoline();
37 return Trampoline.takeError();
39 Reexports[*Trampoline] =
ReexportsEntry{&SourceJD, std::move(SymbolName)};
40 Notifiers[*Trampoline] = std::move(NotifyResolved);
45 ES.reportError(std::move(Err));
46 return ErrorHandlerAddr;
51 std::lock_guard<std::mutex> Lock(LCTMMutex);
52 auto I = Reexports.find(TrampolineAddr);
53 if (
I == Reexports.end())
55 "Missing reexport for trampoline address %p" +
56 formatv(
"{0:x}", TrampolineAddr));
64 std::lock_guard<std::mutex> Lock(LCTMMutex);
65 auto I = Notifiers.find(TrampolineAddr);
66 if (
I != Notifiers.end()) {
67 NotifyResolved = std::move(
I->second);
72 return NotifyResolved ? NotifyResolved(ResolvedAddr) :
Error::success();
86 auto Callback = [
this, TrampolineAddr, SymbolName = Entry->SymbolName,
87 NotifyLandingResolved = std::move(NotifyLandingResolved)](
91 assert(
Result->count(SymbolName) &&
"Unexpected result value");
92 ExecutorAddr LandingAddr = (*Result)[SymbolName].getAddress();
97 NotifyLandingResolved(LandingAddr);
113 switch (
T.getArch()) {
116 std::string(
"No callback manager available for ") +
T.str(),
129 ES, ErrorHandlerAddr);
154 ES, ErrorHandlerAddr);
157 ES, ErrorHandlerAddr);
165 LCTManager(LCTManager), RSManager(RSManager), SourceJD(SourceJD),
166 CallableAliases(
std::
move(CallableAliases)), AliaseeTable(SrcJDLoc) {}
169 return "<Lazy Reexports>";
172void LazyReexportsMaterializationUnit::materialize(
173 std::unique_ptr<MaterializationResponsibility> R) {
174 auto RequestedSymbols = R->getRequestedSymbols();
177 for (
auto &RequestedSymbol : RequestedSymbols) {
178 auto I = CallableAliases.
find(RequestedSymbol);
179 assert(
I != CallableAliases.
end() &&
"Symbol not found in alias map?");
180 RequestedAliases[
I->first] = std::move(
I->second);
184 if (!CallableAliases.
empty())
185 if (
auto Err = R->replace(
lazyReexports(LCTManager, RSManager, SourceJD,
186 std::move(CallableAliases),
188 R->getExecutionSession().reportError(std::move(Err));
189 R->failMaterialization();
194 for (
auto &Alias : RequestedAliases) {
196 SourceJD, Alias.second.Aliasee,
197 [&TargetJD = R->getTargetJITDylib(), &RSManager = this->RSManager,
198 StubSym = Alias.first](ExecutorAddr ResolvedAddr) -> Error {
199 return RSManager.redirect(TargetJD, StubSym,
200 ExecutorSymbolDef(ResolvedAddr, {}));
203 if (!CallThroughTrampoline) {
204 R->getExecutionSession().reportError(CallThroughTrampoline.takeError());
205 R->failMaterialization();
209 Inits[Alias.first] = {*CallThroughTrampoline, Alias.second.AliasFlags};
212 if (AliaseeTable !=
nullptr && !RequestedAliases.empty())
213 AliaseeTable->trackImpls(RequestedAliases, &SourceJD);
215 if (
auto Err =
R->replace(std::make_unique<RedirectableMaterializationUnit>(
216 RSManager, std::move(Inits)))) {
217 R->getExecutionSession().reportError(std::move(Err));
218 return R->failMaterialization();
222void LazyReexportsMaterializationUnit::discard(
const JITDylib &JD,
223 const SymbolStringPtr &Name) {
224 assert(CallableAliases.count(Name) &&
225 "Symbol not covered by this MaterializationUnit");
226 CallableAliases.erase(Name);
229MaterializationUnit::Interface
230LazyReexportsMaterializationUnit::extractFlags(
const SymbolAliasMap &Aliases) {
232 for (
auto &KV : Aliases) {
233 assert(KV.second.AliasFlags.isCallable() &&
234 "Lazy re-exports must be callable symbols");
237 return MaterializationUnit::Interface(std::move(SymbolFlags),
nullptr);
244 Reexports(
std::
move(Reexports)) {}
249 for (
auto &[Alias, AI] : Reexports)
250 SF[Alias] = AI.AliasFlags;
251 return {std::move(SF),
nullptr};
256 void materialize(std::unique_ptr<MaterializationResponsibility> R)
override {
257 LRMgr.emitReentryTrampolines(std::move(R), std::move(Reexports));
260 void discard(
const JITDylib &JD,
const SymbolStringPtr &Name)
override {
261 Reexports.
erase(Name);
264 LazyReexportsManager &LRMgr;
294 std::move(EmitTrampolines), RSMgr, PlatformJD, L, Err));
296 return std::move(Err);
297 return std::move(LRM);
302 auto I = KeyToReentryAddrs.find(
K);
303 if (
I == KeyToReentryAddrs.end())
306 auto &ReentryAddrs =
I->second;
307 for (
auto &ReentryAddr : ReentryAddrs) {
308 assert(CallThroughs.count(ReentryAddr) &&
"CallTrhough missing");
309 CallThroughs.erase(ReentryAddr);
311 KeyToReentryAddrs.erase(
I);
319 auto I = KeyToReentryAddrs.find(SrcK);
320 if (
I != KeyToReentryAddrs.end()) {
321 auto J = KeyToReentryAddrs.find(DstK);
322 if (J == KeyToReentryAddrs.end()) {
323 auto Tmp = std::move(
I->second);
324 KeyToReentryAddrs.erase(
I);
325 KeyToReentryAddrs[DstK] = std::move(Tmp);
327 auto &SrcAddrs =
I->second;
328 auto &DstAddrs = J->second;
330 KeyToReentryAddrs.erase(
I);
333 L->onLazyReexportsTransfered(JD, DstK, SrcK);
342 shared::SPSExecutorAddr)> {
352 : ES(PlatformJD.getExecutionSession()),
353 EmitTrampolines(
std::
move(EmitTrampolines)), RSMgr(RSMgr), L(L) {
357 Err = ES.registerCallControllerHandlers(
360 this, &LazyReexportsManager::resolve));
363std::unique_ptr<MaterializationUnit>
364LazyReexportsManager::createLazyReexports(
SymbolAliasMap Reexports) {
365 return std::make_unique<MU>(*
this, std::move(Reexports));
368void LazyReexportsManager::emitReentryTrampolines(
369 std::unique_ptr<MaterializationResponsibility> MR,
371 size_t NumTrampolines = Reexports.size();
372 auto RT = MR->getResourceTracker();
374 std::move(RT), NumTrampolines,
375 [
this, MR = std::move(MR), Reexports = std::move(Reexports)](
376 Expected<std::vector<ExecutorSymbolDef>> ReentryPoints)
mutable {
377 emitRedirectableSymbols(std::move(MR), std::move(Reexports),
378 std::move(ReentryPoints));
382void LazyReexportsManager::emitRedirectableSymbols(
383 std::unique_ptr<MaterializationResponsibility> MR,
SymbolAliasMap Reexports,
384 Expected<std::vector<ExecutorSymbolDef>> ReentryPoints) {
386 if (!ReentryPoints) {
387 MR->getExecutionSession().reportError(ReentryPoints.takeError());
388 MR->failMaterialization();
392 assert(Reexports.size() == ReentryPoints->size() &&
393 "Number of reentry points doesn't match number of reexports");
398 for (
auto &[Name, AI] : Reexports)
399 Redirs[
Name] = {(*ReentryPoints)[
I++].getAddress(), AI.AliasFlags};
402 if (!Reexports.empty()) {
403 if (
auto Err = MR->withResourceKeyDo([&](
ResourceKey K) {
404 auto &JD = MR->getTargetJITDylib();
405 auto &ReentryAddrsForK = KeyToReentryAddrs[K];
406 for (auto &[Name, AI] : Reexports) {
407 const auto &ReentryPoint = (*ReentryPoints)[I++];
408 CallThroughs[ReentryPoint.getAddress()] = {&JD, Name, AI.Aliasee};
409 ReentryAddrsForK.push_back(ReentryPoint.getAddress());
412 L->onLazyReexportsCreated(JD, K, Reexports);
414 MR->getExecutionSession().reportError(std::move(Err));
415 MR->failMaterialization();
423void LazyReexportsManager::resolve(ResolveSendResultFn SendResult,
428 ES.runSessionLocked([&]() {
429 auto I = CallThroughs.find(ReentryStubAddr);
430 if (
I == CallThroughs.end())
432 "Reentry address " +
formatv(
"{0:x}", ReentryStubAddr) +
435 LandingInfo =
I->second;
439 L->onLazyReexportCalled(LandingInfo);
445 [
this, JD = std::move(LandingInfo.JD),
446 ReentryName = std::move(LandingInfo.Name),
447 SendResult = std::move(SendResult)](Expected<SymbolMap>
Result)
mutable {
449 return SendResult(
Result.takeError());
451 assert(
Result->size() == 1 &&
"Unexpected number of results");
452 auto BodySym =
Result->begin()->second;
453 if (
auto Err = RSMgr.redirect(*JD, ReentryName, BodySym))
454 SendResult(std::move(Err));
463 : Speculator(
std::
move(Speculator)) {}
466 OS <<
"Speculative Lookup Task";
470 if (
auto S = Speculator.lock())
471 S->doNextSpeculativeLookup();
475 std::weak_ptr<SimpleLazyReexportsSpeculator>
Speculator;
479 for (
auto &[JD,
_] : LazyReexports)
485 if (!LazyReexports.count(&JD))
487 auto &BodiesVec = LazyReexports[&JD][
K];
488 for (
auto &[Name, AI] : Reexports)
489 BodiesVec.push_back(AI.Aliasee);
490 if (!SpeculateTaskActive) {
491 SpeculateTaskActive =
true;
492 ES.dispatchTask(std::make_unique<SpeculateTask>(WeakThis));
499 auto I = LazyReexports.find(&JD);
500 if (
I == LazyReexports.end())
503 auto &MapForJD =
I->second;
504 auto J = MapForJD.find(SrcK);
505 if (J == MapForJD.end())
509 auto K = MapForJD.find(DstK);
510 if (
K == MapForJD.end()) {
511 auto Tmp = std::move(J->second);
513 MapForJD[DstK] = std::move(Tmp);
515 auto &SrcNames = J->second;
516 auto &DstNames =
K->second;
525 auto I = LazyReexports.find(&JD);
526 if (
I == LazyReexports.end())
529 auto &MapForJD =
I->second;
532 if (MapForJD.empty()) {
533 LazyReexports.erase(
I);
547 std::vector<std::pair<std::string, SymbolStringPtr>> NewSuggestions) {
548 ES.runSessionLocked([&]() {
549 for (
auto &[JDName, SymbolName] : NewSuggestions)
550 SpeculateSuggestions.push_back(
551 {std::move(JDName), std::move(SymbolName)});
555bool SimpleLazyReexportsSpeculator::doNextSpeculativeLookup() {
562 while (!SpeculateSuggestions.empty()) {
563 auto [JDName, SymbolName] = std::move(SpeculateSuggestions.front());
564 SpeculateSuggestions.pop_front();
568 SpeculateFn = std::move(SymbolName);
574 assert(!LazyReexports.empty() &&
"LazyReexports map is empty");
576 std::next(LazyReexports.begin(), rand() % LazyReexports.size());
577 auto &[JD, KeyToFnBodies] = *LRItr;
579 assert(!KeyToFnBodies.empty() &&
"Key to function bodies map empty");
580 auto KeyToFnBodiesItr =
581 std::next(KeyToFnBodies.begin(), rand() % KeyToFnBodies.size());
582 auto &[
Key, FnBodies] = *KeyToFnBodiesItr;
584 assert(!FnBodies.empty() &&
"Function bodies list empty");
585 auto FnBodyItr = std::next(FnBodies.begin(), rand() % FnBodies.size());
588 SpeculateFn = std::move(*FnBodyItr);
590 FnBodies.erase(FnBodyItr);
591 if (FnBodies.empty()) {
592 KeyToFnBodies.erase(KeyToFnBodiesItr);
593 if (KeyToFnBodies.empty()) {
594 LRItr->first->Release();
595 LazyReexports.erase(LRItr);
600 SpeculateTaskActive =
601 !SpeculateSuggestions.empty() || !LazyReexports.empty();
602 return SpeculateTaskActive;
606 dbgs() <<
"Issuing speculative lookup for ( " << SpeculateJD->getName()
607 <<
", " << SpeculateFn <<
" )...\n";
612 {{std::move(SpeculateFn), SymbolLookupFlags::WeaklyReferencedSymbol}},
618 ES.dispatchTask(std::make_unique<SpeculateTask>(WeakThis));
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
if(!TBB||Cond.size()< 1) return false
static StringRef getName(Value *V)
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
Helper for Errors used as out-parameters.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Represent a constant reference to a string, i.e.
Triple - Helper class for working with autoconf configuration names.
An ExecutionSession represents a running JIT program.
LLVM_ABI JITDylib * getJITDylibByName(StringRef Name)
Return a pointer to the "name" JITDylib.
decltype(auto) runSessionLocked(Func &&F)
Run the given lambda with the session mutex locked.
Represents an address in the executor process.
IdleTask can be used as the basis for low-priority tasks, e.g.
Represents a JIT'd dynamic library.
ExecutionSession & getExecutionSession() const
Get a reference to the ExecutionSession for this JITDylib.
Manages a set of 'lazy call-through' trampolines.
LLVM_ABI ExecutorAddr reportCallThroughError(Error Err)
TrampolinePool::NotifyLandingResolvedFunction NotifyLandingResolvedFunction
LLVM_ABI Expected< ReexportsEntry > findReexport(ExecutorAddr TrampolineAddr)
LLVM_ABI Error notifyResolved(ExecutorAddr TrampolineAddr, ExecutorAddr ResolvedAddr)
LLVM_ABI void resolveTrampolineLandingAddress(ExecutorAddr TrampolineAddr, TrampolinePool::NotifyLandingResolvedFunction NotifyLandingResolved)
unique_function< Error(ExecutorAddr ResolvedAddr)> NotifyResolvedFunction
LLVM_ABI LazyCallThroughManager(ExecutionSession &ES, ExecutorAddr ErrorHandlerAddr, TrampolinePool *TP)
LLVM_ABI Expected< ExecutorAddr > getCallThroughTrampoline(JITDylib &SourceJD, SymbolStringPtr SymbolName, NotifyResolvedFunction NotifyResolved)
LazyReexportsManager::CallThroughInfo CallThroughInfo
MU(LazyReexportsManager &LRMgr, SymbolAliasMap Reexports)
void modifyPassConfig(MaterializationResponsibility &MR, jitlink::LinkGraph &G, jitlink::PassConfiguration &Config) override
void notifyTransferringResources(JITDylib &JD, ResourceKey DstKey, ResourceKey SrcKey) override
Error notifyFailed(MaterializationResponsibility &MR) override
Error notifyRemovingResources(JITDylib &JD, ResourceKey K) override
void handleTransferResources(JITDylib &JD, ResourceKey DstK, ResourceKey SrcK) override
This function will be called inside the session lock.
Error handleRemoveResources(JITDylib &JD, ResourceKey K) override
This function will be called outside the session lock.
unique_function< void(ResourceTrackerSP RT, size_t NumTrampolines, OnTrampolinesReadyFn OnTrampolinesReady)> EmitTrampolinesFn
LazyReexportsManager(LazyReexportsManager &&)=delete
static Expected< std::unique_ptr< LazyReexportsManager > > Create(EmitTrampolinesFn EmitTrampolines, RedirectableSymbolManager &RSMgr, JITDylib &PlatformJD, Listener *L=nullptr)
Create a LazyReexportsManager that uses the ORC runtime for reentry.
LazyReexportsMaterializationUnit(LazyCallThroughManager &LCTManager, RedirectableSymbolManager &RSManager, JITDylib &SourceJD, SymbolAliasMap CallableAliases, ImplSymbolMap *SrcJDLoc)
StringRef getName() const override
Return the name of this materialization unit.
Plugin instances can be added to the ObjectLinkingLayer to receive callbacks when code is loaded or e...
static Expected< std::unique_ptr< LocalLazyCallThroughManager > > Create(ExecutionSession &ES, ExecutorAddr ErrorHandlerAddr)
Create a LocalLazyCallThroughManager using the given ABI.
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
MaterializationUnit(Interface I)
Base class for managing redirectable symbols in which a call gets redirected to another symbol in run...
virtual void emitRedirectableSymbols(std::unique_ptr< MaterializationResponsibility > MR, SymbolMap InitialDests)=0
Emit redirectable symbol.
SpeculateTask(std::weak_ptr< SimpleLazyReexportsSpeculator > Speculator)
void printDescription(raw_ostream &OS) override
Error onLazyReexportsRemoved(JITDylib &JD, ResourceKey K) override
Called under the session lock when lazy reexports are removed.
~SimpleLazyReexportsSpeculator() override
void onLazyReexportsCreated(JITDylib &JD, ResourceKey K, const SymbolAliasMap &Reexports) override
Called under the session lock when new lazy reexports are created.
void onLazyReexportCalled(const CallThroughInfo &CTI) override
Called outside the session lock when a lazy reexport is called.
void onLazyReexportsTransfered(JITDylib &JD, ResourceKey DstK, ResourceKey SrcK) override
Called under the session lock when lazy reexports have their ownership transferred to a new ResourceK...
void addSpeculationSuggestions(std::vector< std::pair< std::string, SymbolStringPtr > > NewSuggestions)
A set of symbols to look up, each associated with a SymbolLookupFlags value.
A symbol name together with the naming level (SymbolNameKind) it is expressed in, so that a Mangler /...
static constexpr SymbolNameSpec c(StringRef Name)
Pointer to a pooled string representing a symbol name.
Base class for pools of compiler re-entry trampolines.
Base class for specs that bind handlers for calls with the SPS signature SPSSigT.
This class implements an extremely fast bulk output stream that can only output to a stream.
JITDylibSearchOrder makeJITDylibSearchOrder(ArrayRef< JITDylib * > JDs, JITDylibLookupFlags Flags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Convenience function for creating a search order from an ArrayRef of JITDylib*, all with the same fla...
IntrusiveRefCntPtr< JITDylib > JITDylibSP
ExecutionSession::CallControllerHandlerBinding bindCallControllerHandler(HandlerT &&H, SymbolLookupFlags LF=SymbolLookupFlags::RequiredSymbol)
Bind H, using the given spec, to the tag with the spec's default name.
DenseMap< SymbolStringPtr, ExecutorSymbolDef > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
LLVM_ABI Expected< std::unique_ptr< LazyCallThroughManager > > createLocalLazyCallThroughManager(const Triple &T, ExecutionSession &ES, ExecutorAddr ErrorHandlerAddr)
Create a LocalLazyCallThroughManager from the given triple and execution session.
std::unique_ptr< LazyReexportsMaterializationUnit > lazyReexports(LazyCallThroughManager &LCTManager, RedirectableSymbolManager &RSManager, JITDylib &SourceJD, SymbolAliasMap CallableAliases, ImplSymbolMap *SrcJDLoc=nullptr)
Define lazy-reexports based on the given SymbolAliasMap.
LLVM_ABI RegisterDependenciesFunction NoDependenciesToRegister
This can be used as the value for a RegisterDependenciesFunction if there are no dependants to regist...
@ Ready
Emitted to memory, but waiting on transitive dependencies.
DenseMap< SymbolStringPtr, SymbolAliasMapEntry > SymbolAliasMap
A map of Symbols to (Symbol, Flags) pairs.
DenseMap< SymbolStringPtr, JITSymbolFlags > SymbolFlagsMap
A map from symbol names (as SymbolStringPtrs) to JITSymbolFlags.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
void consumeError(Error Err)
Consume a Error without doing anything.
Implement std::hash so that hash_code can be used in STL containers.
An LinkGraph pass configuration, consisting of a list of pre-prune, post-prune, and post-fixup passes...
static constexpr SymbolNameSpec Name