12#include "llvm/Config/llvm-config.h"
18#include <condition_variable>
22#define DEBUG_TYPE "orc"
38void MaterializationUnit::anchor() {}
41 assert((
reinterpret_cast<uintptr_t
>(JD.get()) & 0x1) == 0 &&
42 "JITDylib must be two byte aligned");
44 JDAndFlag.store(
reinterpret_cast<uintptr_t
>(JD.get()));
60void ResourceTracker::makeDefunct() {
61 uintptr_t Val = JDAndFlag.load();
76 OS <<
"Resource tracker " << (
void *)RT.
get() <<
" became defunct";
80 std::shared_ptr<SymbolStringPool> SSP,
81 std::shared_ptr<SymbolDependenceMap> Symbols)
83 assert(this->SSP &&
"String pool cannot be null");
84 assert(!this->Symbols->empty() &&
"Can not fail to resolve an empty set");
88 for (
auto &KV : *this->Symbols)
93 for (
auto &KV : *Symbols)
102 OS <<
"Failed to materialize symbols: " << *Symbols;
108 for (
auto &
Sym : Symbols)
109 this->Symbols.push_back(
Sym);
110 assert(!this->Symbols.
empty() &&
"Can not fail to resolve an empty set");
116 assert(!this->Symbols.empty() &&
"Can not fail to resolve an empty set");
124 OS <<
"Symbols not found: " << Symbols;
128 std::shared_ptr<SymbolStringPool> SSP,
SymbolNameSet Symbols)
130 assert(!this->Symbols.
empty() &&
"Can not fail to resolve an empty set");
138 OS <<
"Symbols could not be removed: " << Symbols;
162 : NotifyComplete(
std::
move(NotifyComplete)), RequiredState(RequiredState) {
164 "Cannot query for a symbols that have not reached the resolve state "
167 OutstandingSymbolsCount = Symbols.size();
169 for (
auto &KV : Symbols)
177 "Resolving symbol outside the requested set");
179 "Redundantly resolving symbol Name");
183 if (
Sym.getFlags().hasMaterializationSideEffectsOnly())
186 I->second = std::move(
Sym);
187 --OutstandingSymbolsCount;
191 assert(OutstandingSymbolsCount == 0 &&
192 "Symbols remain, handleComplete called prematurely");
194 class RunQueryCompleteTask :
public Task {
196 RunQueryCompleteTask(
SymbolMap ResolvedSymbols,
198 : ResolvedSymbols(
std::
move(ResolvedSymbols)),
199 NotifyComplete(
std::
move(NotifyComplete)) {}
201 OS <<
"Execute query complete callback for " << ResolvedSymbols;
203 void run()
override { NotifyComplete(std::move(ResolvedSymbols)); }
210 auto T = std::make_unique<RunQueryCompleteTask>(std::move(ResolvedSymbols),
211 std::move(NotifyComplete));
216void AsynchronousSymbolQuery::handleFailed(Error Err) {
218 OutstandingSymbolsCount == 0 &&
219 "Query should already have been abandoned");
220 NotifyComplete(std::move(Err));
224void AsynchronousSymbolQuery::addQueryDependence(JITDylib &JD,
225 SymbolStringPtr
Name) {
228 assert(Added &&
"Duplicate dependence notification?");
231void AsynchronousSymbolQuery::removeQueryDependence(
232 JITDylib &JD,
const SymbolStringPtr &
Name) {
233 auto QRI = QueryRegistrations.
find(&JD);
234 assert(QRI != QueryRegistrations.
end() &&
235 "No dependencies registered for JD");
236 assert(QRI->second.count(
Name) &&
"No dependency on Name in JD");
237 QRI->second.erase(
Name);
238 if (QRI->second.empty())
239 QueryRegistrations.
erase(QRI);
242void AsynchronousSymbolQuery::dropSymbol(
const SymbolStringPtr &
Name) {
245 "Redundant removal of weakly-referenced symbol");
247 --OutstandingSymbolsCount;
250void AsynchronousSymbolQuery::detach() {
251 ResolvedSymbols.
clear();
252 OutstandingSymbolsCount = 0;
253 for (
auto &KV : QueryRegistrations)
254 KV.first->detachQueryHelper(*
this, KV.second);
255 QueryRegistrations.clear();
263 return "<Absolute Symbols>";
266void AbsoluteSymbolsMaterializationUnit::materialize(
267 std::unique_ptr<MaterializationResponsibility> R) {
273 if (
auto Err = R->notifyResolved(Symbols)) {
274 R->getExecutionSession().reportError(std::move(Err));
275 R->failMaterialization();
278 if (
auto Err = R->notifyEmitted()) {
279 R->getExecutionSession().reportError(std::move(Err));
280 R->failMaterialization();
285void AbsoluteSymbolsMaterializationUnit::discard(
const JITDylib &JD,
286 const SymbolStringPtr &
Name) {
291MaterializationUnit::Interface
292AbsoluteSymbolsMaterializationUnit::extractFlags(
const SymbolMap &Symbols) {
294 for (
const auto &KV : Symbols)
295 Flags[KV.first] = KV.second.getFlags();
296 return MaterializationUnit::Interface(std::move(
Flags),
nullptr);
303 SourceJDLookupFlags(SourceJDLookupFlags), Aliases(
std::
move(Aliases)) {}
306 return "<Reexports>";
309void ReExportsMaterializationUnit::materialize(
310 std::unique_ptr<MaterializationResponsibility> R) {
312 auto &ES = R->getTargetJITDylib().getExecutionSession();
313 JITDylib &TgtJD = R->getTargetJITDylib();
314 JITDylib &SrcJD = SourceJD ? *SourceJD : TgtJD;
319 auto RequestedSymbols = R->getRequestedSymbols();
322 for (
auto &
Name : RequestedSymbols) {
324 assert(
I != Aliases.
end() &&
"Symbol not found in aliases map?");
325 RequestedAliases[
Name] = std::move(
I->second);
331 dbgs() <<
"materializing reexports: target = " << TgtJD.
getName()
332 <<
", source = " << SrcJD.
getName() <<
" " << RequestedAliases
337 if (!Aliases.
empty()) {
338 auto Err = SourceJD ?
R->replace(
reexports(*SourceJD, std::move(Aliases),
339 SourceJDLookupFlags))
346 R->failMaterialization();
353 struct OnResolveInfo {
354 OnResolveInfo(std::unique_ptr<MaterializationResponsibility> R,
355 SymbolAliasMap Aliases)
358 std::unique_ptr<MaterializationResponsibility>
R;
370 std::vector<std::pair<SymbolLookupSet, std::shared_ptr<OnResolveInfo>>>
372 while (!RequestedAliases.
empty()) {
374 SymbolLookupSet QuerySymbols;
378 for (
auto &KV : RequestedAliases) {
380 if (&SrcJD == &TgtJD && (QueryAliases.count(KV.second.Aliasee) ||
381 RequestedAliases.count(KV.second.Aliasee)))
384 ResponsibilitySymbols.
insert(KV.first);
385 QuerySymbols.add(KV.second.Aliasee,
386 KV.second.AliasFlags.hasMaterializationSideEffectsOnly()
389 QueryAliases[KV.first] = std::move(KV.second);
393 for (
auto &KV : QueryAliases)
394 RequestedAliases.erase(KV.first);
396 assert(!QuerySymbols.empty() &&
"Alias cycle detected!");
398 auto NewR =
R->delegate(ResponsibilitySymbols);
401 R->failMaterialization();
405 auto QueryInfo = std::make_shared<OnResolveInfo>(std::move(*NewR),
406 std::move(QueryAliases));
407 QueryInfos.push_back(
408 make_pair(std::move(QuerySymbols), std::move(QueryInfo)));
412 while (!QueryInfos.empty()) {
413 auto QuerySymbols = std::move(QueryInfos.back().first);
414 auto QueryInfo = std::move(QueryInfos.back().second);
416 QueryInfos.pop_back();
418 auto RegisterDependencies = [QueryInfo,
425 assert(Deps.size() == 1 && Deps.count(&SrcJD) &&
426 "Unexpected dependencies for reexports");
428 auto &SrcJDDeps = Deps.find(&SrcJD)->second;
430 auto &PerAliasDeps = PerAliasDepsMap[&SrcJD];
432 for (
auto &KV : QueryInfo->Aliases)
433 if (SrcJDDeps.count(KV.second.Aliasee)) {
434 PerAliasDeps = {KV.second.Aliasee};
435 QueryInfo->R->addDependencies(KV.first, PerAliasDepsMap);
439 auto OnComplete = [QueryInfo](Expected<SymbolMap>
Result) {
440 auto &ES = QueryInfo->R->getTargetJITDylib().getExecutionSession();
443 for (
auto &KV : QueryInfo->Aliases) {
444 assert((KV.second.AliasFlags.hasMaterializationSideEffectsOnly() ||
445 Result->count(KV.second.Aliasee)) &&
446 "Result map missing entry?");
448 if (KV.second.AliasFlags.hasMaterializationSideEffectsOnly())
451 ResolutionMap[KV.first] = {(*Result)[KV.second.Aliasee].getAddress(),
452 KV.second.AliasFlags};
454 if (
auto Err = QueryInfo->R->notifyResolved(ResolutionMap)) {
456 QueryInfo->R->failMaterialization();
459 if (
auto Err = QueryInfo->R->notifyEmitted()) {
461 QueryInfo->R->failMaterialization();
466 QueryInfo->R->failMaterialization();
473 std::move(RegisterDependencies));
477void ReExportsMaterializationUnit::discard(
const JITDylib &JD,
478 const SymbolStringPtr &
Name) {
480 "Symbol not covered by this MaterializationUnit");
484MaterializationUnit::Interface
485ReExportsMaterializationUnit::extractFlags(
const SymbolAliasMap &Aliases) {
487 for (
auto &KV : Aliases)
490 return MaterializationUnit::Interface(std::move(
SymbolFlags),
nullptr);
501 return Flags.takeError();
504 for (
auto &
Name : Symbols) {
524 virtual void complete(std::unique_ptr<InProgressLookupState> IPLS) = 0;
547 OnComplete(
std::
move(OnComplete)) {}
549 void complete(std::unique_ptr<InProgressLookupState> IPLS)
override {
551 auto &ES =
SearchOrder.front().first->getExecutionSession();
552 ES.OL_completeLookupFlags(std::move(IPLS), std::move(OnComplete));
557 OnComplete(std::move(Err));
569 std::shared_ptr<AsynchronousSymbolQuery> Q,
573 Q(
std::
move(Q)), RegisterDependencies(
std::
move(RegisterDependencies)) {
576 void complete(std::unique_ptr<InProgressLookupState> IPLS)
override {
578 auto &ES =
SearchOrder.front().first->getExecutionSession();
579 ES.OL_completeLookup(std::move(IPLS), std::move(Q),
580 std::move(RegisterDependencies));
586 Q->handleFailed(std::move(Err));
590 std::shared_ptr<AsynchronousSymbolQuery> Q;
597 : SourceJD(SourceJD), SourceJDLookupFlags(SourceJDLookupFlags),
604 assert(&JD != &SourceJD &&
"Cannot re-export from the same dylib");
608 K, {{&SourceJD, JDLookupFlags}}, LookupSet);
610 return Flags.takeError();
614 for (
auto &KV : *
Flags)
615 if (!Allow || Allow(KV.first))
618 if (AliasMap.
empty())
628void LookupState::reset(InProgressLookupState *IPLS) { this->IPLS.reset(IPLS); }
636 assert(IPLS &&
"Cannot call continueLookup on empty LookupState");
637 auto &ES = IPLS->SearchOrder.begin()->first->getExecutionSession();
638 ES.OL_applyQueryPhase1(std::move(IPLS), std::move(Err));
648 std::vector<ResourceTrackerSP> TrackersToRemove;
650 assert(State != Closed &&
"JD is defunct");
651 for (
auto &KV : TrackerSymbols)
652 TrackersToRemove.push_back(KV.first);
657 for (
auto &RT : TrackersToRemove)
658 Err =
joinErrors(std::move(Err), RT->remove());
664 assert(State != Closed &&
"JD is defunct");
667 return DefaultTracker;
673 assert(State == Open &&
"JD is defunct");
681 assert(State == Open &&
"JD is defunct");
683 [&](
const std::shared_ptr<DefinitionGenerator> &
H) {
684 return H.get() == &
G;
686 assert(
I != DefGenerators.end() &&
"Generator not found");
687 DefGenerators.erase(
I);
696 std::vector<NonOwningSymbolStringPtr> AddedSyms;
697 std::vector<NonOwningSymbolStringPtr> RejectedWeakDefs;
699 for (
auto SFItr = SymbolFlags.begin(), SFEnd = SymbolFlags.end();
700 SFItr != SFEnd; ++SFItr) {
702 auto &Name = SFItr->first;
703 auto &Flags = SFItr->second;
705 auto EntryItr = Symbols.find(Name);
708 if (EntryItr != Symbols.end()) {
711 if (!Flags.isWeak()) {
713 for (auto &S : AddedSyms)
714 Symbols.erase(Symbols.find_as(S));
717 return make_error<DuplicateDefinition>(std::string(*Name));
721 RejectedWeakDefs.push_back(NonOwningSymbolStringPtr(Name));
732 while (!RejectedWeakDefs.empty()) {
733 SymbolFlags.erase(SymbolFlags.find_as(RejectedWeakDefs.back()));
734 RejectedWeakDefs.pop_back();
741Error JITDylib::replace(MaterializationResponsibility &FromMR,
742 std::unique_ptr<MaterializationUnit> MU) {
743 assert(MU !=
nullptr &&
"Can not replace with a null MaterializationUnit");
744 std::unique_ptr<MaterializationUnit> MustRunMU;
745 std::unique_ptr<MaterializationResponsibility> MustRunMR;
749 if (FromMR.RT->isDefunct())
750 return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
753 for (
auto &KV : MU->getSymbols()) {
754 auto SymI = Symbols.find(KV.first);
755 assert(SymI != Symbols.end() &&
"Replacing unknown symbol");
756 assert(SymI->second.getState() == SymbolState::Materializing &&
757 "Can not replace a symbol that ha is not materializing");
758 assert(!SymI->second.hasMaterializerAttached() &&
759 "Symbol should not have materializer attached already");
760 assert(UnmaterializedInfos.count(KV.first) == 0 &&
761 "Symbol being replaced should have no UnmaterializedInfo");
769 for (
auto &KV : MU->getSymbols()) {
770 auto MII = MaterializingInfos.find(KV.first);
771 if (MII != MaterializingInfos.end()) {
772 if (MII->second.hasQueriesPending()) {
773 MustRunMR = ES.createMaterializationResponsibility(
774 *FromMR.RT, std::move(MU->SymbolFlags),
775 std::move(MU->InitSymbol));
776 MustRunMU = std::move(MU);
777 return Error::success();
783 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU),
785 for (
auto &KV : UMI->MU->getSymbols()) {
786 auto SymI = Symbols.find(KV.first);
787 assert(SymI->second.getState() == SymbolState::Materializing &&
788 "Can not replace a symbol that is not materializing");
789 assert(!SymI->second.hasMaterializerAttached() &&
790 "Can not replace a symbol that has a materializer attached");
791 assert(UnmaterializedInfos.count(KV.first) == 0 &&
792 "Unexpected materializer entry in map");
793 SymI->second.setAddress(SymI->second.getAddress());
794 SymI->second.setMaterializerAttached(
true);
796 auto &UMIEntry = UnmaterializedInfos[KV.first];
797 assert((!UMIEntry || !UMIEntry->MU) &&
798 "Replacing symbol with materializer still attached");
809 assert(MustRunMR &&
"MustRunMU set implies MustRunMR set");
811 std::move(MustRunMU), std::move(MustRunMR)));
813 assert(!MustRunMR &&
"MustRunMU unset implies MustRunMR unset");
819Expected<std::unique_ptr<MaterializationResponsibility>>
820JITDylib::delegate(MaterializationResponsibility &FromMR,
821 SymbolFlagsMap SymbolFlags, SymbolStringPtr InitSymbol) {
824 [&]() -> Expected<std::unique_ptr<MaterializationResponsibility>> {
825 if (FromMR.RT->isDefunct())
826 return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
828 return ES.createMaterializationResponsibility(
829 *FromMR.RT, std::move(SymbolFlags), std::move(InitSymbol));
834JITDylib::getRequestedSymbols(
const SymbolFlagsMap &SymbolFlags)
const {
838 for (
auto &KV : SymbolFlags) {
839 assert(Symbols.count(KV.first) &&
"JITDylib does not cover this symbol?");
840 assert(Symbols.find(KV.first)->second.getState() !=
841 SymbolState::NeverSearched &&
842 Symbols.find(KV.first)->second.getState() != SymbolState::Ready &&
843 "getRequestedSymbols can only be called for symbols that have "
844 "started materializing");
845 auto I = MaterializingInfos.find(KV.first);
846 if (
I == MaterializingInfos.end())
849 if (
I->second.hasQueriesPending())
850 RequestedSymbols.insert(KV.first);
853 return RequestedSymbols;
857void JITDylib::addDependencies(
const SymbolStringPtr &
Name,
858 const SymbolDependenceMap &Dependencies) {
860 assert(Symbols.count(
Name) &&
"Name not in symbol table");
861 assert(Symbols[
Name].getState() < SymbolState::Emitted &&
862 "Can not add dependencies for a symbol that is not materializing");
866 <<
": " << Dependencies <<
"\n";
873 auto &
MI = MaterializingInfos[
Name];
874 assert(Symbols[
Name].getState() != SymbolState::Emitted &&
875 "Can not add dependencies to an emitted symbol");
877 bool DependsOnSymbolInErrorState =
false;
881 for (
auto &KV : Dependencies) {
882 assert(KV.first &&
"Null JITDylib in dependency?");
883 auto &OtherJITDylib = *KV.first;
884 auto &DepsOnOtherJITDylib =
MI.UnemittedDependencies[&OtherJITDylib];
886 for (
auto &OtherSymbol : KV.second) {
889 auto OtherSymI = OtherJITDylib.Symbols.find(OtherSymbol);
893 assert(OtherSymI != OtherJITDylib.Symbols.end() &&
894 "Dependency on unknown symbol");
896 auto &OtherSymEntry = OtherSymI->second;
900 if (OtherSymEntry.getState() == SymbolState::Ready)
905 if (OtherSymEntry.getFlags().hasError()) {
906 DependsOnSymbolInErrorState =
true;
912 auto &OtherMI = OtherJITDylib.MaterializingInfos[OtherSymbol];
914 if (OtherSymEntry.getState() == SymbolState::Emitted)
915 transferEmittedNodeDependencies(
MI,
Name, OtherMI);
916 else if (&OtherJITDylib !=
this || OtherSymbol !=
Name) {
917 OtherMI.Dependants[
this].insert(
Name);
918 DepsOnOtherJITDylib.insert(OtherSymbol);
922 if (DepsOnOtherJITDylib.empty())
923 MI.UnemittedDependencies.erase(&OtherJITDylib);
928 if (DependsOnSymbolInErrorState)
930 JITSymbolFlags::HasError);
934Error JITDylib::resolve(MaterializationResponsibility &MR,
935 const SymbolMap &Resolved) {
936 AsynchronousSymbolQuerySet CompletedQueries;
939 if (MR.RT->isDefunct())
940 return make_error<ResourceTrackerDefunct>(MR.RT);
943 return make_error<StringError>(
"JITDylib " + getName() +
945 inconvertibleErrorCode());
947 struct WorklistEntry {
948 SymbolTable::iterator SymI;
949 ExecutorSymbolDef ResolvedSym;
952 SymbolNameSet SymbolsInErrorState;
953 std::vector<WorklistEntry> Worklist;
957 for (
const auto &KV : Resolved) {
959 assert(!KV.second.getFlags().hasError() &&
960 "Resolution result can not have error flag set");
962 auto SymI = Symbols.find(KV.first);
964 assert(SymI != Symbols.end() &&
"Symbol not found");
965 assert(!SymI->second.hasMaterializerAttached() &&
966 "Resolving symbol with materializer attached?");
967 assert(SymI->second.getState() == SymbolState::Materializing &&
968 "Symbol should be materializing");
969 assert(SymI->second.getAddress() == ExecutorAddr() &&
970 "Symbol has already been resolved");
972 if (SymI->second.getFlags().hasError())
973 SymbolsInErrorState.insert(KV.first);
975 auto Flags = KV.second.getFlags();
976 Flags &= ~JITSymbolFlags::Common;
978 (SymI->second.getFlags() & ~JITSymbolFlags::Common) &&
979 "Resolved flags should match the declared flags");
981 Worklist.push_back({SymI, {KV.second.getAddress(),
Flags}});
986 if (!SymbolsInErrorState.empty()) {
987 auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
988 (*FailedSymbolsDepMap)[
this] = std::move(SymbolsInErrorState);
989 return make_error<FailedToMaterialize>(
990 getExecutionSession().getSymbolStringPool(),
991 std::move(FailedSymbolsDepMap));
994 while (!Worklist.empty()) {
995 auto SymI = Worklist.back().SymI;
996 auto ResolvedSym = Worklist.back().ResolvedSym;
999 auto &
Name = SymI->first;
1002 JITSymbolFlags ResolvedFlags = ResolvedSym.getFlags();
1003 SymI->second.setAddress(ResolvedSym.getAddress());
1004 SymI->second.setFlags(ResolvedFlags);
1005 SymI->second.setState(SymbolState::Resolved);
1007 auto MII = MaterializingInfos.find(
Name);
1008 if (MII == MaterializingInfos.end())
1011 auto &
MI = MII->second;
1012 for (
auto &Q :
MI.takeQueriesMeeting(SymbolState::Resolved)) {
1013 Q->notifySymbolMetRequiredState(
Name, ResolvedSym);
1014 Q->removeQueryDependence(*
this,
Name);
1015 if (Q->isComplete())
1016 CompletedQueries.insert(std::move(Q));
1020 return Error::success();
1025 for (
auto &Q : CompletedQueries) {
1026 assert(Q->isComplete() &&
"Q not completed");
1027 Q->handleComplete(ES);
1030 return Error::success();
1033Error JITDylib::emit(MaterializationResponsibility &MR,
1034 const SymbolFlagsMap &Emitted) {
1035 AsynchronousSymbolQuerySet CompletedQueries;
1036 DenseMap<JITDylib *, SymbolNameVector> ReadySymbols;
1039 if (MR.RT->isDefunct())
1040 return make_error<ResourceTrackerDefunct>(MR.RT);
1043 return make_error<StringError>(
"JITDylib " + getName() +
1045 inconvertibleErrorCode());
1047 SymbolNameSet SymbolsInErrorState;
1048 std::vector<SymbolTable::iterator> Worklist;
1051 for (const auto &KV : Emitted) {
1052 auto &Name = KV.first;
1054 auto SymI = Symbols.find(Name);
1055 assert(SymI != Symbols.end() &&
"No symbol table entry for Name");
1057 if (SymI->second.getFlags().hasError())
1058 SymbolsInErrorState.insert(Name);
1060 Worklist.push_back(SymI);
1064 if (!SymbolsInErrorState.empty()) {
1065 auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
1066 (*FailedSymbolsDepMap)[this] = std::move(SymbolsInErrorState);
1067 return make_error<FailedToMaterialize>(
1068 getExecutionSession().getSymbolStringPool(),
1069 std::move(FailedSymbolsDepMap));
1073 while (!Worklist.empty()) {
1074 auto SymI = Worklist.back();
1075 Worklist.pop_back();
1077 auto &Name = SymI->first;
1078 auto &SymEntry = SymI->second;
1081 assert(((SymEntry.getFlags().hasMaterializationSideEffectsOnly() &&
1082 SymEntry.getState() == SymbolState::Materializing) ||
1083 SymEntry.getState() == SymbolState::Resolved) &&
1084 "Emitting from state other than Resolved");
1085 SymEntry.setState(SymbolState::Emitted);
1087 auto MII = MaterializingInfos.find(Name);
1091 if (MII == MaterializingInfos.end()) {
1092 SymEntry.setState(SymbolState::Ready);
1096 auto &
MI = MII->second;
1101 for (
auto &KV :
MI.Dependants) {
1102 auto &DependantJD = *KV.first;
1103 auto &DependantJDReadySymbols = ReadySymbols[&DependantJD];
1104 for (auto &DependantName : KV.second) {
1106 DependantJD.MaterializingInfos.find(DependantName);
1107 assert(DependantMII != DependantJD.MaterializingInfos.end() &&
1108 "Dependant should have MaterializingInfo");
1110 auto &DependantMI = DependantMII->second;
1113 assert(DependantMI.UnemittedDependencies.count(this) &&
1114 "Dependant does not have an unemitted dependencies record "
1117 assert(DependantMI.UnemittedDependencies[this].count(Name) &&
1118 "Dependant does not count this symbol as a dependency?");
1120 DependantMI.UnemittedDependencies[this].erase(Name);
1121 if (DependantMI.UnemittedDependencies[this].empty())
1122 DependantMI.UnemittedDependencies.erase(this);
1126 DependantJD.transferEmittedNodeDependencies(DependantMI,
1129 auto DependantSymI = DependantJD.Symbols.find(DependantName);
1130 assert(DependantSymI != DependantJD.Symbols.end() &&
1131 "Dependant has no entry in the Symbols table");
1132 auto &DependantSymEntry = DependantSymI->second;
1137 if (DependantSymEntry.getState() == SymbolState::Emitted &&
1138 DependantMI.UnemittedDependencies.empty()) {
1139 assert(DependantMI.Dependants.empty() &&
1140 "Dependants should be empty by now");
1144 DependantSymEntry.setState(SymbolState::Ready);
1145 DependantJDReadySymbols.push_back(DependantName);
1148 DependantMI.takeQueriesMeeting(SymbolState::Ready)) {
1149 Q->notifySymbolMetRequiredState(
1150 DependantName, DependantSymI->second.getSymbol());
1151 if (Q->isComplete())
1152 CompletedQueries.insert(Q);
1153 Q->removeQueryDependence(DependantJD, DependantName);
1155 DependantJD.MaterializingInfos.erase(DependantMII);
1160 auto &ThisJDReadySymbols = ReadySymbols[
this];
1161 MI.Dependants.clear();
1162 if (
MI.UnemittedDependencies.empty()) {
1163 SymI->second.setState(SymbolState::Ready);
1164 ThisJDReadySymbols.push_back(Name);
1165 for (auto &Q : MI.takeQueriesMeeting(SymbolState::Ready)) {
1166 Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
1167 if (Q->isComplete())
1168 CompletedQueries.insert(Q);
1169 Q->removeQueryDependence(*this, Name);
1171 MaterializingInfos.erase(MII);
1175 return Error::success();
1180 for (
auto &Q : CompletedQueries) {
1181 assert(Q->isComplete() &&
"Q is not complete");
1182 Q->handleComplete(ES);
1185 return Error::success();
1188void JITDylib::unlinkMaterializationResponsibility(
1189 MaterializationResponsibility &MR) {
1191 auto I = TrackerMRs.find(MR.RT.get());
1192 assert(
I != TrackerMRs.end() &&
"No MRs in TrackerMRs list for RT");
1193 assert(
I->second.count(&MR) &&
"MR not in TrackerMRs list for RT");
1194 I->second.erase(&MR);
1195 if (
I->second.empty())
1196 TrackerMRs.erase(MR.RT.get());
1200std::pair<JITDylib::AsynchronousSymbolQuerySet,
1201 std::shared_ptr<SymbolDependenceMap>>
1202JITDylib::failSymbols(FailedSymbolsWorklist Worklist) {
1203 AsynchronousSymbolQuerySet FailedQueries;
1204 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
1206 while (!Worklist.empty()) {
1207 assert(Worklist.back().first &&
"Failed JITDylib can not be null");
1208 auto &JD = *Worklist.back().first;
1209 auto Name = std::move(Worklist.back().second);
1210 Worklist.pop_back();
1212 (*FailedSymbolsMap)[&JD].insert(
Name);
1215 auto SymI = JD.Symbols.find(
Name);
1221 if (SymI == JD.Symbols.end())
1223 auto &
Sym = SymI->second;
1228 Sym.setFlags(
Sym.getFlags() | JITSymbolFlags::HasError);
1233 auto MII = JD.MaterializingInfos.find(
Name);
1235 if (MII == JD.MaterializingInfos.end())
1238 auto &
MI = MII->second;
1241 for (
auto &KV :
MI.Dependants) {
1242 auto &DependantJD = *KV.first;
1243 for (
auto &DependantName : KV.second) {
1244 assert(DependantJD.Symbols.count(DependantName) &&
1245 "No symbol table entry for DependantName");
1246 auto &DependantSym = DependantJD.Symbols[DependantName];
1247 DependantSym.setFlags(DependantSym.getFlags() |
1248 JITSymbolFlags::HasError);
1250 assert(DependantJD.MaterializingInfos.count(DependantName) &&
1251 "No MaterializingInfo for dependant");
1252 auto &DependantMI = DependantJD.MaterializingInfos[DependantName];
1254 auto UnemittedDepI = DependantMI.UnemittedDependencies.find(&JD);
1255 assert(UnemittedDepI != DependantMI.UnemittedDependencies.end() &&
1256 "No UnemittedDependencies entry for this JITDylib");
1258 "No UnemittedDependencies entry for this symbol");
1259 UnemittedDepI->second.erase(
Name);
1260 if (UnemittedDepI->second.empty())
1261 DependantMI.UnemittedDependencies.erase(UnemittedDepI);
1266 if (DependantSym.getState() == SymbolState::Emitted) {
1267 assert(DependantMI.Dependants.empty() &&
1268 "Emitted symbol should not have dependants");
1269 Worklist.push_back(std::make_pair(&DependantJD, DependantName));
1273 MI.Dependants.clear();
1276 for (
auto &KV :
MI.UnemittedDependencies) {
1277 auto &UnemittedDepJD = *KV.first;
1278 for (
auto &UnemittedDepName : KV.second) {
1279 auto UnemittedDepMII =
1280 UnemittedDepJD.MaterializingInfos.find(UnemittedDepName);
1281 assert(UnemittedDepMII != UnemittedDepJD.MaterializingInfos.end() &&
1282 "Missing MII for unemitted dependency");
1283 assert(UnemittedDepMII->second.Dependants.count(&JD) &&
1284 "JD not listed as a dependant of unemitted dependency");
1285 assert(UnemittedDepMII->second.Dependants[&JD].count(
Name) &&
1286 "Name is not listed as a dependant of unemitted dependency");
1287 UnemittedDepMII->second.Dependants[&JD].erase(
Name);
1288 if (UnemittedDepMII->second.Dependants[&JD].empty())
1289 UnemittedDepMII->second.Dependants.erase(&JD);
1292 MI.UnemittedDependencies.clear();
1295 AsynchronousSymbolQueryList ToDetach;
1296 for (
auto &Q : MII->second.pendingQueries()) {
1298 FailedQueries.insert(Q);
1299 ToDetach.push_back(Q);
1301 for (
auto &Q : ToDetach)
1305 "Can not delete MaterializingInfo with dependants still attached");
1306 assert(
MI.UnemittedDependencies.empty() &&
1307 "Can not delete MaterializingInfo with unemitted dependencies "
1310 "Can not delete MaterializingInfo with queries pending");
1311 JD.MaterializingInfos.erase(MII);
1314 return std::make_pair(std::move(FailedQueries), std::move(FailedSymbolsMap));
1318 bool LinkAgainstThisJITDylibFirst) {
1320 assert(State == Open &&
"JD is defunct");
1321 if (LinkAgainstThisJITDylibFirst) {
1323 if (NewLinkOrder.empty() || NewLinkOrder.front().first !=
this)
1324 LinkOrder.push_back(
1325 std::make_pair(
this, JITDylibLookupFlags::MatchAllSymbols));
1328 LinkOrder = std::move(NewLinkOrder);
1334 for (
auto &KV : NewLinks) {
1336 if (
llvm::find(LinkOrder, KV) != LinkOrder.end())
1339 LinkOrder.push_back(std::move(KV));
1351 assert(State == Open &&
"JD is defunct");
1352 for (
auto &KV : LinkOrder)
1353 if (KV.first == &OldJD) {
1354 KV = {&NewJD, JDLookupFlags};
1362 assert(State == Open &&
"JD is defunct");
1364 [&](
const JITDylibSearchOrder::value_type &KV) {
1365 return KV.first == &JD;
1367 if (
I != LinkOrder.end())
1374 assert(State == Open &&
"JD is defunct");
1375 using SymbolMaterializerItrPair =
1376 std::pair<SymbolTable::iterator, UnmaterializedInfosMap::iterator>;
1377 std::vector<SymbolMaterializerItrPair> SymbolsToRemove;
1382 auto I = Symbols.find(
Name);
1385 if (
I == Symbols.end()) {
1386 Missing.insert(
Name);
1391 if (
I->second.getState() != SymbolState::NeverSearched &&
1392 I->second.getState() != SymbolState::Ready) {
1397 auto UMII =
I->second.hasMaterializerAttached()
1398 ? UnmaterializedInfos.find(
Name)
1399 : UnmaterializedInfos.end();
1400 SymbolsToRemove.push_back(std::make_pair(
I, UMII));
1404 if (!Missing.empty())
1406 std::move(Missing));
1414 for (
auto &SymbolMaterializerItrPair : SymbolsToRemove) {
1415 auto UMII = SymbolMaterializerItrPair.second;
1418 if (UMII != UnmaterializedInfos.end()) {
1419 UMII->second->MU->doDiscard(*
this, UMII->first);
1420 UnmaterializedInfos.erase(UMII);
1423 auto SymI = SymbolMaterializerItrPair.first;
1424 Symbols.erase(SymI);
1427 return Error::success();
1433 OS <<
"JITDylib \"" <<
getName() <<
"\" (ES: "
1434 <<
format(
"0x%016" PRIx64,
reinterpret_cast<uintptr_t
>(&ES))
1448 if (State == Closed)
1450 OS <<
"Link order: " << LinkOrder <<
"\n"
1451 <<
"Symbol table:\n";
1454 std::vector<std::pair<SymbolStringPtr, SymbolTableEntry *>> SymbolsSorted;
1455 for (
auto &KV : Symbols)
1456 SymbolsSorted.emplace_back(KV.first, &KV.second);
1457 std::sort(SymbolsSorted.begin(), SymbolsSorted.end(),
1458 [](
const auto &L,
const auto &R) { return *L.first < *R.first; });
1460 for (
auto &KV : SymbolsSorted) {
1461 OS <<
" \"" << *KV.first <<
"\": ";
1462 if (
auto Addr = KV.second->getAddress())
1465 OS <<
"<not resolved> ";
1467 OS <<
" " << KV.second->getFlags() <<
" " << KV.second->getState();
1469 if (KV.second->hasMaterializerAttached()) {
1470 OS <<
" (Materializer ";
1471 auto I = UnmaterializedInfos.find(KV.first);
1472 assert(
I != UnmaterializedInfos.end() &&
1473 "Lazy symbol should have UnmaterializedInfo");
1474 OS <<
I->second->MU.get() <<
", " <<
I->second->MU->getName() <<
")\n";
1479 if (!MaterializingInfos.empty())
1480 OS <<
" MaterializingInfos entries:\n";
1481 for (
auto &KV : MaterializingInfos) {
1482 OS <<
" \"" << *KV.first <<
"\":\n"
1483 <<
" " << KV.second.pendingQueries().size()
1484 <<
" pending queries: { ";
1485 for (
const auto &Q : KV.second.pendingQueries())
1486 OS << Q.get() <<
" (" << Q->getRequiredState() <<
") ";
1487 OS <<
"}\n Dependants:\n";
1488 for (
auto &KV2 : KV.second.Dependants)
1489 OS <<
" " << KV2.first->getName() <<
": " << KV2.second <<
"\n";
1490 OS <<
" Unemitted Dependencies:\n";
1491 for (
auto &KV2 : KV.second.UnemittedDependencies)
1492 OS <<
" " << KV2.first->getName() <<
": " << KV2.second <<
"\n";
1493 assert((Symbols[KV.first].getState() != SymbolState::Ready ||
1494 !KV.second.pendingQueries().empty() ||
1495 !KV.second.Dependants.empty() ||
1496 !KV.second.UnemittedDependencies.empty()) &&
1497 "Stale materializing info entry");
1502void JITDylib::MaterializingInfo::addQuery(
1503 std::shared_ptr<AsynchronousSymbolQuery> Q) {
1507 [](
const std::shared_ptr<AsynchronousSymbolQuery> &V,
SymbolState S) {
1508 return V->getRequiredState() <= S;
1510 PendingQueries.insert(
I.base(), std::move(Q));
1513void JITDylib::MaterializingInfo::removeQuery(
1514 const AsynchronousSymbolQuery &Q) {
1517 PendingQueries, [&Q](
const std::shared_ptr<AsynchronousSymbolQuery> &V) {
1518 return V.get() == &Q;
1520 assert(
I != PendingQueries.end() &&
1521 "Query is not attached to this MaterializingInfo");
1522 PendingQueries.erase(
I);
1525JITDylib::AsynchronousSymbolQueryList
1526JITDylib::MaterializingInfo::takeQueriesMeeting(SymbolState RequiredState) {
1527 AsynchronousSymbolQueryList
Result;
1528 while (!PendingQueries.empty()) {
1529 if (PendingQueries.back()->getRequiredState() > RequiredState)
1532 Result.push_back(std::move(PendingQueries.back()));
1533 PendingQueries.pop_back();
1539JITDylib::JITDylib(ExecutionSession &ES, std::string
Name)
1544std::pair<JITDylib::AsynchronousSymbolQuerySet,
1545 std::shared_ptr<SymbolDependenceMap>>
1546JITDylib::removeTracker(ResourceTracker &RT) {
1548 assert(State != Closed &&
"JD is defunct");
1551 std::vector<std::pair<JITDylib *, SymbolStringPtr>> SymbolsToFail;
1553 if (&RT == DefaultTracker.
get()) {
1555 for (
auto &KV : TrackerSymbols)
1556 for (
auto &
Sym : KV.second)
1559 for (
auto &KV : Symbols) {
1560 auto &
Sym = KV.first;
1561 if (!TrackedSymbols.count(
Sym))
1562 SymbolsToRemove.push_back(
Sym);
1565 DefaultTracker.
reset();
1568 auto I = TrackerSymbols.find(&RT);
1569 if (
I != TrackerSymbols.end()) {
1570 SymbolsToRemove = std::move(
I->second);
1571 TrackerSymbols.erase(
I);
1576 for (
auto &
Sym : SymbolsToRemove) {
1577 assert(Symbols.count(
Sym) &&
"Symbol not in symbol table");
1580 auto MII = MaterializingInfos.
find(
Sym);
1581 if (MII != MaterializingInfos.
end())
1582 SymbolsToFail.push_back({
this,
Sym});
1585 AsynchronousSymbolQuerySet QueriesToFail;
1586 auto Result = failSymbols(std::move(SymbolsToFail));
1589 for (
auto &
Sym : SymbolsToRemove) {
1590 auto I = Symbols.find(
Sym);
1591 assert(
I != Symbols.end() &&
"Symbol not present in table");
1594 if (
I->second.hasMaterializerAttached()) {
1599 "Symbol has materializer attached");
1608void JITDylib::transferTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT) {
1609 assert(State != Closed &&
"JD is defunct");
1610 assert(&DstRT != &SrcRT &&
"No-op transfers shouldn't call transferTracker");
1611 assert(&DstRT.getJITDylib() ==
this &&
"DstRT is not for this JITDylib");
1612 assert(&SrcRT.getJITDylib() ==
this &&
"SrcRT is not for this JITDylib");
1615 for (
auto &KV : UnmaterializedInfos) {
1616 if (KV.second->RT == &SrcRT)
1617 KV.second->RT = &DstRT;
1622 auto I = TrackerMRs.find(&SrcRT);
1623 if (
I != TrackerMRs.end()) {
1624 auto &SrcMRs =
I->second;
1625 auto &DstMRs = TrackerMRs[&DstRT];
1626 for (
auto *MR : SrcMRs)
1629 DstMRs = std::move(SrcMRs);
1631 for (
auto *MR : SrcMRs)
1635 TrackerMRs.erase(&SrcRT);
1641 if (&DstRT == DefaultTracker.
get()) {
1642 TrackerSymbols.erase(&SrcRT);
1648 if (&SrcRT == DefaultTracker.
get()) {
1649 assert(!TrackerSymbols.count(&SrcRT) &&
1650 "Default tracker should not appear in TrackerSymbols");
1655 for (
auto &KV : TrackerSymbols)
1656 for (
auto &
Sym : KV.second)
1659 for (
auto &KV : Symbols) {
1660 auto &
Sym = KV.first;
1661 if (!CurrentlyTrackedSymbols.count(
Sym))
1662 SymbolsToTrack.push_back(
Sym);
1665 TrackerSymbols[&DstRT] = std::move(SymbolsToTrack);
1669 auto &DstTrackedSymbols = TrackerSymbols[&DstRT];
1673 auto SI = TrackerSymbols.find(&SrcRT);
1674 if (SI == TrackerSymbols.end())
1677 DstTrackedSymbols.reserve(DstTrackedSymbols.size() +
SI->second.size());
1678 for (
auto &
Sym :
SI->second)
1679 DstTrackedSymbols.push_back(std::move(
Sym));
1680 TrackerSymbols.erase(SI);
1683Error JITDylib::defineImpl(MaterializationUnit &MU) {
1688 std::vector<SymbolStringPtr> ExistingDefsOverridden;
1689 std::vector<SymbolStringPtr> MUDefsOverridden;
1691 for (
const auto &KV : MU.getSymbols()) {
1692 auto I = Symbols.find(KV.first);
1694 if (
I != Symbols.end()) {
1695 if (KV.second.isStrong()) {
1696 if (
I->second.getFlags().isStrong() ||
1698 Duplicates.insert(KV.first);
1701 "Overridden existing def should be in the never-searched "
1703 ExistingDefsOverridden.push_back(KV.first);
1706 MUDefsOverridden.push_back(KV.first);
1711 if (!Duplicates.empty()) {
1713 {
dbgs() <<
" Error: Duplicate symbols " << Duplicates <<
"\n"; });
1714 return make_error<DuplicateDefinition>(std::string(**Duplicates.begin()));
1719 if (!MUDefsOverridden.empty())
1720 dbgs() <<
" Defs in this MU overridden: " << MUDefsOverridden <<
"\n";
1722 for (
auto &S : MUDefsOverridden)
1723 MU.doDiscard(*
this, S);
1727 if (!ExistingDefsOverridden.empty())
1728 dbgs() <<
" Existing defs overridden by this MU: " << MUDefsOverridden
1731 for (
auto &S : ExistingDefsOverridden) {
1733 auto UMII = UnmaterializedInfos.find(S);
1734 assert(UMII != UnmaterializedInfos.end() &&
1735 "Overridden existing def should have an UnmaterializedInfo");
1736 UMII->second->MU->doDiscard(*
this, S);
1740 for (
auto &KV : MU.getSymbols()) {
1741 auto &SymEntry = Symbols[KV.first];
1742 SymEntry.setFlags(KV.second);
1744 SymEntry.setMaterializerAttached(
true);
1750void JITDylib::installMaterializationUnit(
1751 std::unique_ptr<MaterializationUnit> MU, ResourceTracker &RT) {
1754 if (&RT != DefaultTracker.
get()) {
1755 auto &TS = TrackerSymbols[&RT];
1756 TS.reserve(TS.size() + MU->getSymbols().size());
1757 for (
auto &KV : MU->getSymbols())
1758 TS.push_back(KV.first);
1761 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU), &RT);
1762 for (
auto &KV : UMI->MU->getSymbols())
1763 UnmaterializedInfos[KV.first] = UMI;
1766void JITDylib::detachQueryHelper(AsynchronousSymbolQuery &Q,
1768 for (
auto &QuerySymbol : QuerySymbols) {
1770 "QuerySymbol does not have MaterializingInfo");
1771 auto &
MI = MaterializingInfos[QuerySymbol];
1776void JITDylib::transferEmittedNodeDependencies(
1777 MaterializingInfo &DependantMI,
const SymbolStringPtr &DependantName,
1778 MaterializingInfo &EmittedMI) {
1779 for (
auto &KV : EmittedMI.UnemittedDependencies) {
1780 auto &DependencyJD = *KV.first;
1781 SymbolNameSet *UnemittedDependenciesOnDependencyJD =
nullptr;
1783 for (
auto &DependencyName : KV.second) {
1784 auto &DependencyMI = DependencyJD.MaterializingInfos[DependencyName];
1787 if (&DependencyMI == &DependantMI)
1792 if (!UnemittedDependenciesOnDependencyJD)
1793 UnemittedDependenciesOnDependencyJD =
1794 &DependantMI.UnemittedDependencies[&DependencyJD];
1796 DependencyMI.Dependants[
this].
insert(DependantName);
1797 UnemittedDependenciesOnDependencyJD->insert(DependencyName);
1810 std::mutex LookupMutex;
1811 std::condition_variable CV;
1815 dbgs() <<
"Issuing init-symbol lookup:\n";
1816 for (
auto &KV : InitSyms)
1817 dbgs() <<
" " << KV.first->getName() <<
": " << KV.second <<
"\n";
1820 for (
auto &KV : InitSyms) {
1821 auto *JD = KV.first;
1822 auto Names = std::move(KV.second);
1829 std::lock_guard<std::mutex> Lock(LookupMutex);
1833 "Duplicate JITDylib in lookup?");
1834 CompoundResult[JD] = std::move(*
Result);
1844 std::unique_lock<std::mutex> Lock(LookupMutex);
1845 CV.wait(Lock, [&] {
return Count == 0 || CompoundErr; });
1848 return std::move(CompoundErr);
1850 return std::move(CompoundResult);
1857 class TriggerOnComplete {
1860 TriggerOnComplete(OnCompleteFn OnComplete)
1861 : OnComplete(std::move(OnComplete)) {}
1862 ~TriggerOnComplete() { OnComplete(std::move(LookupResult)); }
1863 void reportResult(
Error Err) {
1864 std::lock_guard<std::mutex> Lock(ResultMutex);
1865 LookupResult =
joinErrors(std::move(LookupResult), std::move(Err));
1869 std::mutex ResultMutex;
1870 Error LookupResult{Error::success()};
1871 OnCompleteFn OnComplete;
1875 dbgs() <<
"Issuing init-symbol lookup:\n";
1876 for (
auto &KV : InitSyms)
1877 dbgs() <<
" " << KV.first->getName() <<
": " << KV.second <<
"\n";
1880 auto TOC = std::make_shared<TriggerOnComplete>(std::move(OnComplete));
1882 for (
auto &KV : InitSyms) {
1883 auto *JD = KV.first;
1884 auto Names = std::move(KV.second);
1890 TOC->reportResult(
Result.takeError());
1897 OS <<
"Materialization task: " << MU->getName() <<
" in "
1898 << MR->getTargetJITDylib().getName();
1906 this->EPC->ES =
this;
1912 "Session still open. Did you forget to call endSession?");
1916 LLVM_DEBUG(
dbgs() <<
"Ending ExecutionSession " <<
this <<
"\n");
1919 SessionOpen =
false;
1920 return std::move(JDs);
1926 for (
auto &JD :
reverse(JITDylibsToClose))
1927 Err =
joinErrors(std::move(Err), JD->clear());
1929 Err =
joinErrors(std::move(Err), EPC->disconnect());
1940 assert(!ResourceManagers.empty() &&
"No managers registered");
1941 if (ResourceManagers.back() == &RM)
1942 ResourceManagers.pop_back();
1945 assert(
I != ResourceManagers.end() &&
"RM not registered");
1946 ResourceManagers.erase(
I);
1953 for (
auto &JD : JDs)
1954 if (JD->getName() ==
Name)
1971 if (
auto Err = P->setupJITDylib(JD))
1972 return std::move(Err);
1983 assert(JD.State == JITDylib::Open &&
"JD already closed");
1984 JD.State = JITDylib::Closing;
1986 assert(
I != JDs.end() &&
"JD does not appear in session JDs");
1992 auto Err = JD.
clear();
1996 Err =
joinErrors(std::move(Err), P->teardownJITDylib(JD));
2000 assert(JD.State == JITDylib::Closing &&
"JD should be closing");
2001 JD.State = JITDylib::Closed;
2002 assert(JD.Symbols.
empty() &&
"JD.Symbols is not empty after clear");
2004 "JD.UnmaterializedInfos is not empty after clear");
2006 "JD.MaterializingInfos is not empty after clear");
2007 assert(JD.TrackerSymbols.empty() &&
2008 "TrackerSymbols is not empty after clear");
2009 JD.DefGenerators.clear();
2010 JD.LinkOrder.clear();
2018 return std::vector<JITDylibSP>();
2020 auto &ES = JDs.
front()->getExecutionSession();
2021 return ES.runSessionLocked([&]() ->
Expected<std::vector<JITDylibSP>> {
2023 std::vector<JITDylibSP>
Result;
2025 for (
auto &JD : JDs) {
2027 if (JD->State != Open)
2028 return make_error<StringError>(
2029 "Error building link order: " + JD->getName() +
" is defunct",
2031 if (Visited.
count(JD.get()))
2036 Visited.
insert(JD.get());
2038 while (!WorkStack.empty()) {
2039 Result.push_back(std::move(WorkStack.back()));
2040 WorkStack.pop_back();
2042 for (auto &KV : llvm::reverse(Result.back()->LinkOrder)) {
2043 auto &JD = *KV.first;
2044 if (!Visited.insert(&JD).second)
2046 WorkStack.push_back(&JD);
2074 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
2075 K, std::move(SearchOrder), std::move(LookupSet),
2076 std::move(OnComplete)),
2084 std::promise<MSVCPExpected<SymbolFlagsMap>> ResultP;
2085 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
2086 K, std::move(SearchOrder), std::move(LookupSet),
2088 ResultP.set_value(std::move(
Result));
2092 auto ResultF = ResultP.get_future();
2093 return ResultF.get();
2104 dbgs() <<
"Looking up " << Symbols <<
" in " << SearchOrder
2105 <<
" (required state: " << RequiredState <<
")\n";
2112 dispatchOutstandingMUs();
2114 auto Unresolved = std::move(Symbols);
2115 auto Q = std::make_shared<AsynchronousSymbolQuery>(Unresolved, RequiredState,
2116 std::move(NotifyComplete));
2118 auto IPLS = std::make_unique<InProgressFullLookupState>(
2119 K, SearchOrder, std::move(Unresolved), RequiredState, std::move(Q),
2120 std::move(RegisterDependencies));
2130#if LLVM_ENABLE_THREADS
2132 std::promise<SymbolMap> PromisedResult;
2137 PromisedResult.set_value(std::move(*R));
2140 ResolutionError = R.takeError();
2154 ResolutionError = R.takeError();
2159 lookup(K, SearchOrder, std::move(Symbols), RequiredState, NotifyComplete,
2160 RegisterDependencies);
2162#if LLVM_ENABLE_THREADS
2163 auto ResultFuture = PromisedResult.get_future();
2164 auto Result = ResultFuture.get();
2166 if (ResolutionError)
2167 return std::move(ResolutionError);
2169 return std::move(
Result);
2172 if (ResolutionError)
2173 return std::move(ResolutionError);
2186 assert(ResultMap->size() == 1 &&
"Unexpected number of results");
2187 assert(ResultMap->count(
Name) &&
"Missing result for symbol");
2188 return std::move(ResultMap->begin()->second);
2190 return ResultMap.takeError();
2212 return TagAddrs.takeError();
2215 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
2216 for (
auto &KV : *TagAddrs) {
2217 auto TagAddr = KV.second.getAddress();
2218 if (JITDispatchHandlers.count(TagAddr))
2219 return make_error<StringError>(
"Tag " +
formatv(
"{0:x16}", TagAddr) +
2220 " (for " + *KV.first +
2221 ") already registered",
2223 auto I = WFs.
find(KV.first);
2225 "JITDispatchHandler implementation missing");
2226 JITDispatchHandlers[KV.second.getAddress()] =
2227 std::make_shared<JITDispatchHandlerFunction>(std::move(
I->second));
2229 dbgs() <<
"Associated function tag \"" << *KV.first <<
"\" ("
2230 <<
formatv(
"{0:x}", KV.second.getAddress()) <<
") with handler\n";
2240 std::shared_ptr<JITDispatchHandlerFunction>
F;
2242 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
2243 auto I = JITDispatchHandlers.find(HandlerFnTagAddr);
2244 if (
I != JITDispatchHandlers.end())
2249 (*F)(std::move(SendResult), ArgBuffer.
data(), ArgBuffer.
size());
2252 (
"No function registered for tag " +
2253 formatv(
"{0:x16}", HandlerFnTagAddr))
2259 for (
auto &JD : JDs)
2264void ExecutionSession::dispatchOutstandingMUs() {
2267 std::optional<std::pair<std::unique_ptr<MaterializationUnit>,
2268 std::unique_ptr<MaterializationResponsibility>>>
2272 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2273 if (!OutstandingMUs.empty()) {
2274 JMU.emplace(std::move(OutstandingMUs.back()));
2275 OutstandingMUs.pop_back();
2282 assert(JMU->first &&
"No MU?");
2283 LLVM_DEBUG(
dbgs() <<
" Dispatching \"" << JMU->first->getName() <<
"\"\n");
2284 dispatchTask(std::make_unique<MaterializationTask>(std::move(JMU->first),
2285 std::move(JMU->second)));
2287 LLVM_DEBUG(
dbgs() <<
"Done dispatching MaterializationUnits.\n");
2290Error ExecutionSession::removeResourceTracker(ResourceTracker &RT) {
2292 dbgs() <<
"In " << RT.getJITDylib().getName() <<
" removing tracker "
2293 <<
formatv(
"{0:x}", RT.getKeyUnsafe()) <<
"\n";
2295 std::vector<ResourceManager *> CurrentResourceManagers;
2297 JITDylib::AsynchronousSymbolQuerySet QueriesToFail;
2298 std::shared_ptr<SymbolDependenceMap> FailedSymbols;
2301 CurrentResourceManagers = ResourceManagers;
2303 std::tie(QueriesToFail, FailedSymbols) = RT.getJITDylib().removeTracker(RT);
2308 auto &JD = RT.getJITDylib();
2309 for (
auto *L :
reverse(CurrentResourceManagers))
2311 L->handleRemoveResources(JD, RT.getKeyUnsafe()));
2313 for (
auto &Q : QueriesToFail)
2320void ExecutionSession::transferResourceTracker(ResourceTracker &DstRT,
2321 ResourceTracker &SrcRT) {
2323 dbgs() <<
"In " << SrcRT.getJITDylib().getName()
2324 <<
" transfering resources from tracker "
2325 <<
formatv(
"{0:x}", SrcRT.getKeyUnsafe()) <<
" to tracker "
2326 <<
formatv(
"{0:x}", DstRT.getKeyUnsafe()) <<
"\n";
2330 if (&DstRT == &SrcRT)
2333 assert(&DstRT.getJITDylib() == &SrcRT.getJITDylib() &&
2334 "Can't transfer resources between JITDylibs");
2336 SrcRT.makeDefunct();
2337 auto &JD = DstRT.getJITDylib();
2338 JD.transferTracker(DstRT, SrcRT);
2339 for (
auto *L :
reverse(ResourceManagers))
2340 L->handleTransferResources(JD, DstRT.getKeyUnsafe(),
2341 SrcRT.getKeyUnsafe());
2345void ExecutionSession::destroyResourceTracker(ResourceTracker &RT) {
2348 dbgs() <<
"In " << RT.getJITDylib().getName() <<
" destroying tracker "
2349 <<
formatv(
"{0:x}", RT.getKeyUnsafe()) <<
"\n";
2351 if (!RT.isDefunct())
2352 transferResourceTracker(*RT.getJITDylib().getDefaultResourceTracker(),
2357Error ExecutionSession::IL_updateCandidatesFor(
2359 SymbolLookupSet &Candidates, SymbolLookupSet *NonCandidates) {
2360 return Candidates.forEachWithRemoval(
2361 [&](
const SymbolStringPtr &
Name,
2365 auto SymI = JD.Symbols.find(
Name);
2366 if (SymI == JD.Symbols.end())
2374 if (!SymI->second.getFlags().isExported() &&
2377 NonCandidates->add(Name, SymLookupFlags);
2386 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2393 if (SymI->second.getFlags().hasError()) {
2394 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2395 (*FailedSymbolsMap)[&JD] = {Name};
2397 std::move(FailedSymbolsMap));
2405void ExecutionSession::OL_applyQueryPhase1(
2406 std::unique_ptr<InProgressLookupState> IPLS, Error Err) {
2409 dbgs() <<
"Entering OL_applyQueryPhase1:\n"
2410 <<
" Lookup kind: " << IPLS->K <<
"\n"
2411 <<
" Search order: " << IPLS->SearchOrder
2412 <<
", Current index = " << IPLS->CurSearchOrderIndex
2413 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2414 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2415 <<
" Definition generator candidates: "
2416 << IPLS->DefGeneratorCandidates <<
"\n"
2417 <<
" Definition generator non-candidates: "
2418 << IPLS->DefGeneratorNonCandidates <<
"\n";
2426 while (IPLS->CurSearchOrderIndex != IPLS->SearchOrder.size()) {
2432 return IPLS->fail(std::move(Err));
2435 auto &KV = IPLS->SearchOrder[IPLS->CurSearchOrderIndex];
2436 auto &JD = *KV.first;
2437 auto JDLookupFlags = KV.second;
2440 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2441 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2445 if (IPLS->NewJITDylib) {
2448 IPLS->GeneratorLock = std::unique_lock<std::mutex>(JD.GeneratorsMutex);
2453 SymbolLookupSet Tmp;
2454 std::swap(IPLS->DefGeneratorNonCandidates, Tmp);
2455 IPLS->DefGeneratorCandidates.append(std::move(Tmp));
2458 dbgs() <<
" First time visiting " << JD.getName()
2459 <<
", resetting candidate sets and building generator stack\n";
2464 IPLS->CurDefGeneratorStack.reserve(JD.DefGenerators.size());
2466 IPLS->CurDefGeneratorStack.push_back(DG);
2470 IPLS->NewJITDylib =
false;
2479 Err = IL_updateCandidatesFor(
2480 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2481 JD.DefGenerators.empty() ?
nullptr
2482 : &IPLS->DefGeneratorNonCandidates);
2484 dbgs() <<
" Remaining candidates = " << IPLS->DefGeneratorCandidates
2492 return IPLS->fail(std::move(Err));
2496 if (IPLS->CurDefGeneratorStack.empty())
2497 LLVM_DEBUG(
dbgs() <<
" No generators to run for this JITDylib.\n");
2498 else if (IPLS->DefGeneratorCandidates.empty())
2501 dbgs() <<
" Running " << IPLS->CurDefGeneratorStack.size()
2502 <<
" remaining generators for "
2503 << IPLS->DefGeneratorCandidates.size() <<
" candidates\n";
2505 while (!IPLS->CurDefGeneratorStack.empty() &&
2506 !IPLS->DefGeneratorCandidates.empty()) {
2507 auto DG = IPLS->CurDefGeneratorStack.back().lock();
2508 IPLS->CurDefGeneratorStack.pop_back();
2511 return IPLS->fail(make_error<StringError>(
2512 "DefinitionGenerator removed while lookup in progress",
2516 auto &LookupSet = IPLS->DefGeneratorCandidates;
2521 LLVM_DEBUG(
dbgs() <<
" Attempting to generate " << LookupSet <<
"\n");
2523 Err = DG->tryToGenerate(LS, K, JD, JDLookupFlags, LookupSet);
2524 IPLS = std::move(
LS.IPLS);
2530 dbgs() <<
" Error attempting to generate " << LookupSet <<
"\n";
2532 assert(IPLS &&
"LS cannot be retained if error is returned");
2533 return IPLS->fail(std::move(Err));
2539 {
dbgs() <<
" LookupState captured. Exiting phase1 for now.\n"; });
2546 LLVM_DEBUG(
dbgs() <<
" Updating candidate set post-generation\n");
2547 Err = IL_updateCandidatesFor(
2548 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2549 JD.DefGenerators.empty() ?
nullptr
2550 : &IPLS->DefGeneratorNonCandidates);
2555 LLVM_DEBUG(
dbgs() <<
" Error encountered while updating candidates\n");
2556 return IPLS->fail(std::move(Err));
2560 if (IPLS->DefGeneratorCandidates.empty() &&
2561 IPLS->DefGeneratorNonCandidates.empty()) {
2564 IPLS->CurSearchOrderIndex = IPLS->SearchOrder.size();
2570 ++IPLS->CurSearchOrderIndex;
2571 IPLS->NewJITDylib =
true;
2576 IPLS->DefGeneratorCandidates.remove_if(
2584 if (IPLS->DefGeneratorCandidates.empty()) {
2586 IPLS->complete(std::move(IPLS));
2588 LLVM_DEBUG(
dbgs() <<
"Phase 1 failed with unresolved symbols.\n");
2589 IPLS->fail(make_error<SymbolsNotFound>(
2594void ExecutionSession::OL_completeLookup(
2595 std::unique_ptr<InProgressLookupState> IPLS,
2596 std::shared_ptr<AsynchronousSymbolQuery> Q,
2600 dbgs() <<
"Entering OL_completeLookup:\n"
2601 <<
" Lookup kind: " << IPLS->K <<
"\n"
2602 <<
" Search order: " << IPLS->SearchOrder
2603 <<
", Current index = " << IPLS->CurSearchOrderIndex
2604 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2605 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2606 <<
" Definition generator candidates: "
2607 << IPLS->DefGeneratorCandidates <<
"\n"
2608 <<
" Definition generator non-candidates: "
2609 << IPLS->DefGeneratorNonCandidates <<
"\n";
2612 bool QueryComplete =
false;
2613 DenseMap<JITDylib *, JITDylib::UnmaterializedInfosList> CollectedUMIs;
2616 for (
auto &KV : IPLS->SearchOrder) {
2617 auto &JD = *KV.first;
2618 auto JDLookupFlags = KV.second;
2620 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2621 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2624 auto Err = IPLS->LookupSet.forEachWithRemoval(
2625 [&](
const SymbolStringPtr &
Name,
2628 dbgs() <<
" Attempting to match \"" <<
Name <<
"\" ("
2629 << SymLookupFlags <<
")... ";
2634 auto SymI = JD.Symbols.find(
Name);
2635 if (SymI == JD.Symbols.end()) {
2642 if (!SymI->second.getFlags().isExported() &&
2654 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2658 "required, but symbol is has-side-effects-only\n";
2666 if (SymI->second.getFlags().hasError()) {
2668 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2669 (*FailedSymbolsMap)[&JD] = {
Name};
2670 return make_error<FailedToMaterialize>(
2678 if (SymI->second.getState() >= Q->getRequiredState()) {
2680 <<
"matched, symbol already in required state\n");
2681 Q->notifySymbolMetRequiredState(
Name, SymI->second.getSymbol());
2688 if (SymI->second.hasMaterializerAttached()) {
2689 assert(SymI->second.getAddress() == ExecutorAddr() &&
2690 "Symbol not resolved but already has address?");
2691 auto UMII = JD.UnmaterializedInfos.find(
Name);
2692 assert(UMII != JD.UnmaterializedInfos.end() &&
2693 "Lazy symbol should have UnmaterializedInfo");
2695 auto UMI = UMII->second;
2696 assert(UMI->MU &&
"Materializer should not be null");
2697 assert(UMI->RT &&
"Tracker should not be null");
2699 dbgs() <<
"matched, preparing to dispatch MU@" << UMI->MU.get()
2700 <<
" (" << UMI->MU->getName() <<
")\n";
2705 for (
auto &KV : UMI->MU->getSymbols()) {
2706 auto SymK = JD.Symbols.find(KV.first);
2707 assert(SymK != JD.Symbols.end() &&
2708 "No entry for symbol covered by MaterializationUnit");
2709 SymK->second.setMaterializerAttached(
false);
2711 JD.UnmaterializedInfos.erase(KV.first);
2715 CollectedUMIs[&JD].push_back(std::move(UMI));
2723 "By this line the symbol should be materializing");
2724 auto &
MI = JD.MaterializingInfos[
Name];
2726 Q->addQueryDependence(JD,
Name);
2735 dbgs() <<
"Lookup failed. Detaching query and replacing MUs.\n";
2742 for (
auto &KV : CollectedUMIs) {
2743 auto &JD = *KV.first;
2744 for (
auto &UMI : KV.second)
2745 for (
auto &KV2 : UMI->MU->getSymbols()) {
2746 assert(!JD.UnmaterializedInfos.count(KV2.first) &&
2747 "Unexpected materializer in map");
2748 auto SymI = JD.Symbols.find(KV2.first);
2749 assert(SymI != JD.Symbols.end() &&
"Missing symbol entry");
2751 "Can not replace symbol that is not materializing");
2752 assert(!SymI->second.hasMaterializerAttached() &&
2753 "MaterializerAttached flag should not be set");
2754 SymI->second.setMaterializerAttached(
true);
2755 JD.UnmaterializedInfos[KV2.first] = UMI;
2763 LLVM_DEBUG(
dbgs() <<
"Stripping unmatched weakly-referenced symbols\n");
2764 IPLS->LookupSet.forEachWithRemoval(
2767 Q->dropSymbol(
Name);
2773 if (!IPLS->LookupSet.empty()) {
2776 IPLS->LookupSet.getSymbolNames());
2780 QueryComplete = Q->isComplete();
2783 dbgs() <<
"Query successfully "
2784 << (QueryComplete ?
"completed" :
"lodged") <<
"\n";
2788 if (!CollectedUMIs.empty()) {
2789 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2792 for (
auto &KV : CollectedUMIs) {
2794 auto &JD = *KV.first;
2795 dbgs() <<
" For " << JD.getName() <<
": Adding " << KV.second.size()
2798 for (
auto &UMI : KV.second) {
2799 auto MR = createMaterializationResponsibility(
2800 *UMI->RT, std::move(UMI->MU->SymbolFlags),
2801 std::move(UMI->MU->InitSymbol));
2802 OutstandingMUs.push_back(
2803 std::make_pair(std::move(UMI->MU), std::move(MR)));
2809 if (RegisterDependencies && !Q->QueryRegistrations.empty()) {
2811 RegisterDependencies(Q->QueryRegistrations);
2821 Q->handleFailed(std::move(LodgingErr));
2825 if (QueryComplete) {
2827 Q->handleComplete(*
this);
2830 dispatchOutstandingMUs();
2833void ExecutionSession::OL_completeLookupFlags(
2834 std::unique_ptr<InProgressLookupState> IPLS,
2835 unique_function<
void(Expected<SymbolFlagsMap>)> OnComplete) {
2839 dbgs() <<
"Entering OL_completeLookupFlags:\n"
2840 <<
" Lookup kind: " << IPLS->K <<
"\n"
2841 <<
" Search order: " << IPLS->SearchOrder
2842 <<
", Current index = " << IPLS->CurSearchOrderIndex
2843 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2844 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2845 <<
" Definition generator candidates: "
2846 << IPLS->DefGeneratorCandidates <<
"\n"
2847 <<
" Definition generator non-candidates: "
2848 << IPLS->DefGeneratorNonCandidates <<
"\n";
2854 for (
auto &KV : IPLS->SearchOrder) {
2855 auto &JD = *KV.first;
2856 auto JDLookupFlags = KV.second;
2858 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2859 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2862 IPLS->LookupSet.forEachWithRemoval([&](
const SymbolStringPtr &
Name,
2865 dbgs() <<
" Attempting to match \"" <<
Name <<
"\" ("
2866 << SymLookupFlags <<
")... ";
2871 auto SymI = JD.Symbols.find(
Name);
2872 if (SymI == JD.Symbols.end()) {
2878 if (!SymI->second.getFlags().isExported() &&
2885 dbgs() <<
"matched, \"" <<
Name <<
"\" -> " << SymI->second.getFlags()
2894 IPLS->LookupSet.remove_if(
2899 if (!IPLS->LookupSet.empty()) {
2902 IPLS->LookupSet.getSymbolNames());
2911 OnComplete(std::move(
Result));
2914void ExecutionSession::OL_destroyMaterializationResponsibility(
2915 MaterializationResponsibility &MR) {
2917 assert(MR.SymbolFlags.empty() &&
2918 "All symbols should have been explicitly materialized or failed");
2919 MR.JD.unlinkMaterializationResponsibility(MR);
2923 const MaterializationResponsibility &MR) {
2924 return MR.JD.getRequestedSymbols(MR.SymbolFlags);
2927Error ExecutionSession::OL_notifyResolved(MaterializationResponsibility &MR,
2930 dbgs() <<
"In " << MR.JD.getName() <<
" resolving " << Symbols <<
"\n";
2933 for (
auto &KV : Symbols) {
2934 auto I = MR.SymbolFlags.find(KV.first);
2935 assert(
I != MR.SymbolFlags.end() &&
2936 "Resolving symbol outside this responsibility set");
2937 assert(!
I->second.hasMaterializationSideEffectsOnly() &&
2938 "Can't resolve materialization-side-effects-only symbol");
2941 "Resolving symbol with incorrect flags");
2945 return MR.JD.resolve(MR, Symbols);
2948Error ExecutionSession::OL_notifyEmitted(MaterializationResponsibility &MR) {
2950 dbgs() <<
"In " << MR.JD.getName() <<
" emitting " << MR.SymbolFlags
2954 if (
auto Err = MR.JD.emit(MR, MR.SymbolFlags))
2957 MR.SymbolFlags.clear();
2961Error ExecutionSession::OL_defineMaterializing(
2962 MaterializationResponsibility &MR,
SymbolFlagsMap NewSymbolFlags) {
2965 dbgs() <<
"In " << MR.JD.getName() <<
" defining materializing symbols "
2966 << NewSymbolFlags <<
"\n";
2968 if (
auto AcceptedDefs =
2969 MR.JD.defineMaterializing(std::move(NewSymbolFlags))) {
2971 for (
auto &KV : *AcceptedDefs)
2972 MR.SymbolFlags.insert(KV);
2975 return AcceptedDefs.takeError();
2978void ExecutionSession::OL_notifyFailed(MaterializationResponsibility &MR) {
2981 dbgs() <<
"In " << MR.JD.getName() <<
" failing materialization for "
2982 << MR.SymbolFlags <<
"\n";
2985 JITDylib::FailedSymbolsWorklist Worklist;
2987 for (
auto &KV : MR.SymbolFlags)
2988 Worklist.push_back(std::make_pair(&MR.JD, KV.first));
2989 MR.SymbolFlags.clear();
2991 if (Worklist.empty())
2994 JITDylib::AsynchronousSymbolQuerySet FailedQueries;
2995 std::shared_ptr<SymbolDependenceMap> FailedSymbols;
2999 if (MR.RT->isDefunct())
3002 std::tie(FailedQueries, FailedSymbols) =
3003 JITDylib::failSymbols(std::move(Worklist));
3006 for (
auto &Q : FailedQueries)
3011Error ExecutionSession::OL_replace(MaterializationResponsibility &MR,
3012 std::unique_ptr<MaterializationUnit> MU) {
3013 for (
auto &KV : MU->getSymbols()) {
3014 assert(MR.SymbolFlags.count(KV.first) &&
3015 "Replacing definition outside this responsibility set");
3016 MR.SymbolFlags.erase(KV.first);
3019 if (MU->getInitializerSymbol() == MR.InitSymbol)
3020 MR.InitSymbol =
nullptr;
3022 LLVM_DEBUG(MR.JD.getExecutionSession().runSessionLocked([&]() {
3023 dbgs() <<
"In " << MR.JD.getName() <<
" replacing symbols with " << *MU
3027 return MR.JD.replace(MR, std::move(MU));
3030Expected<std::unique_ptr<MaterializationResponsibility>>
3031ExecutionSession::OL_delegate(MaterializationResponsibility &MR,
3034 SymbolStringPtr DelegatedInitSymbol;
3037 for (
auto &
Name : Symbols) {
3038 auto I = MR.SymbolFlags.find(
Name);
3039 assert(
I != MR.SymbolFlags.end() &&
3040 "Symbol is not tracked by this MaterializationResponsibility "
3043 DelegatedFlags[
Name] = std::move(
I->second);
3044 if (
Name == MR.InitSymbol)
3045 std::swap(MR.InitSymbol, DelegatedInitSymbol);
3047 MR.SymbolFlags.erase(
I);
3050 return MR.JD.delegate(MR, std::move(DelegatedFlags),
3051 std::move(DelegatedInitSymbol));
3054void ExecutionSession::OL_addDependencies(
3055 MaterializationResponsibility &MR,
const SymbolStringPtr &
Name,
3058 dbgs() <<
"Adding dependencies for " <<
Name <<
": " << Dependencies
3062 "Symbol not covered by this MaterializationResponsibility instance");
3063 MR.JD.addDependencies(
Name, Dependencies);
3066void ExecutionSession::OL_addDependenciesForAll(
3067 MaterializationResponsibility &MR,
3070 dbgs() <<
"Adding dependencies for all symbols in " << MR.SymbolFlags <<
": "
3071 << Dependencies <<
"\n";
3073 for (
auto &KV : MR.SymbolFlags)
3074 MR.JD.addDependencies(KV.first, Dependencies);
3078void ExecutionSession::dumpDispatchInfo(Task &
T) {
3080 dbgs() <<
"Dispatching: ";
3081 T.printDescription(
dbgs());
static StringRef getName(Value *V)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static uint32_t getFlags(const Symbol *Sym)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
const T & front() const
front - Get the first element.
size_t size() const
size - Get the array size.
bool empty() const
empty - Check if the array is empty.
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
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.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Symbol info for RuntimeDyld.
std::pair< iterator, bool > insert(const ValueT &V)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
const std::string & getName() const
Get the name for this JITLinkDylib.
StringRef getName() const override
Return the name of this materialization unit.
AbsoluteSymbolsMaterializationUnit(SymbolMap Symbols)
AsynchronousSymbolQuery(const SymbolLookupSet &Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete)
Create a query for the given symbols.
void notifySymbolMetRequiredState(const SymbolStringPtr &Name, ExecutorSymbolDef Sym)
Notify the query that a requested symbol has reached the required state.
Definition generators can be attached to JITDylibs to generate new definitions for otherwise unresolv...
virtual ~DefinitionGenerator()
An ExecutionSession represents a running JIT program.
Error endSession()
End the session.
void reportError(Error Err)
Report a error for this execution session.
void lookupFlags(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet Symbols, unique_function< void(Expected< SymbolFlagsMap >)> OnComplete)
Search the given JITDylibs to find the flags associated with each of the given symbols.
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
JITDylib * getJITDylibByName(StringRef Name)
Return a pointer to the "name" JITDylib.
JITDylib & createBareJITDylib(std::string Name)
Add a new bare JITDylib to this ExecutionSession.
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete, RegisterDependenciesFunction RegisterDependencies)
Search the given JITDylibs for the given symbols.
Error registerJITDispatchHandlers(JITDylib &JD, JITDispatchHandlerAssociationMap WFs)
For each tag symbol name, associate the corresponding AsyncHandlerWrapperFunction with the address of...
void registerResourceManager(ResourceManager &RM)
Register the given ResourceManager with this ExecutionSession.
~ExecutionSession()
Destroy an ExecutionSession.
void runJITDispatchHandler(SendResultFunction SendResult, ExecutorAddr HandlerFnTagAddr, ArrayRef< char > ArgBuffer)
Run a registered jit-side wrapper function.
void deregisterResourceManager(ResourceManager &RM)
Deregister the given ResourceManager with this ExecutionSession.
ExecutionSession(std::unique_ptr< ExecutorProcessControl > EPC)
Construct an ExecutionSession with the given ExecutorProcessControl object.
decltype(auto) runSessionLocked(Func &&F)
Run the given lambda with the session mutex locked.
void dump(raw_ostream &OS)
Dump the state of all the JITDylibs in this session.
Expected< JITDylib & > createJITDylib(std::string Name)
Add a new JITDylib to this ExecutionSession.
void dispatchTask(std::unique_ptr< Task > T)
Materialize the given unit.
Error removeJITDylib(JITDylib &JD)
Closes the given JITDylib.
Represents an address in the executor process.
Represents a defining location for a JIT symbol.
FailedToMaterialize(std::shared_ptr< SymbolStringPool > SSP, std::shared_ptr< SymbolDependenceMap > Symbols)
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
void log(raw_ostream &OS) const override
Print an error message to an output stream.
InProgressFullLookupState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, SymbolState RequiredState, std::shared_ptr< AsynchronousSymbolQuery > Q, RegisterDependenciesFunction RegisterDependencies)
void complete(std::unique_ptr< InProgressLookupState > IPLS) override
void fail(Error Err) override
void complete(std::unique_ptr< InProgressLookupState > IPLS) override
void fail(Error Err) override
InProgressLookupFlagsState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, unique_function< void(Expected< SymbolFlagsMap >)> OnComplete)
virtual ~InProgressLookupState()=default
SymbolLookupSet DefGeneratorCandidates
JITDylibSearchOrder SearchOrder
std::vector< std::weak_ptr< DefinitionGenerator > > CurDefGeneratorStack
size_t CurSearchOrderIndex
SymbolLookupSet LookupSet
virtual void complete(std::unique_ptr< InProgressLookupState > IPLS)=0
InProgressLookupState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, SymbolState RequiredState)
SymbolState RequiredState
SymbolLookupSet DefGeneratorNonCandidates
virtual void fail(Error Err)=0
std::unique_lock< std::mutex > GeneratorLock
Represents a JIT'd dynamic library.
Error clear()
Calls remove on all trackers currently associated with this JITDylib.
Error define(std::unique_ptr< MaterializationUnitType > &&MU, ResourceTrackerSP RT=nullptr)
Define all symbols provided by the materialization unit to be part of this JITDylib.
ExecutionSession & getExecutionSession() const
Get a reference to the ExecutionSession for this JITDylib.
ResourceTrackerSP createResourceTracker()
Create a resource tracker for this JITDylib.
Expected< std::vector< JITDylibSP > > getReverseDFSLinkOrder()
Rteurn this JITDylib and its transitive dependencies in reverse DFS order based on linkage relationsh...
ResourceTrackerSP getDefaultResourceTracker()
Get the default resource tracker for this JITDylib.
void removeGenerator(DefinitionGenerator &G)
Remove a definition generator from this JITDylib.
Expected< std::vector< JITDylibSP > > getDFSLinkOrder()
Return this JITDylib and its transitive dependencies in DFS order based on linkage relationships.
Wraps state for a lookup-in-progress.
void continueLookup(Error Err)
Continue the lookup.
LookupState & operator=(LookupState &&)
void printDescription(raw_ostream &OS) override
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
SymbolFlagsMap SymbolFlags
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Non-owning SymbolStringPool entry pointer.
StringRef getName() const override
Return the name of this materialization unit.
ReExportsMaterializationUnit(JITDylib *SourceJD, JITDylibLookupFlags SourceJDLookupFlags, SymbolAliasMap Aliases)
SourceJD is allowed to be nullptr, in which case the source JITDylib is taken to be whatever JITDylib...
std::function< bool(SymbolStringPtr)> SymbolPredicate
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &LookupSet) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
ReexportsGenerator(JITDylib &SourceJD, JITDylibLookupFlags SourceJDLookupFlags, SymbolPredicate Allow=SymbolPredicate())
Create a reexports generator.
Listens for ResourceTracker operations.
virtual ~ResourceManager()
ResourceTrackerDefunct(ResourceTrackerSP RT)
void log(raw_ostream &OS) const override
Print an error message to an output stream.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
API to remove / transfer ownership of JIT resources.
JITDylib & getJITDylib() const
Return the JITDylib targeted by this tracker.
void transferTo(ResourceTracker &DstRT)
Transfer all resources associated with this key to the given tracker, which must target the same JITD...
ResourceTracker(const ResourceTracker &)=delete
Error remove()
Remove all resources associated with this key.
A set of symbols to look up, each associated with a SymbolLookupFlags value.
static SymbolLookupSet fromMapKeys(const DenseMap< SymbolStringPtr, KeyT > &M, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Construct a SymbolLookupSet from DenseMap keys.
Pointer to a pooled string representing a symbol name.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
void log(raw_ostream &OS) const override
Print an error message to an output stream.
SymbolsCouldNotBeRemoved(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
void log(raw_ostream &OS) const override
Print an error message to an output stream.
SymbolsNotFound(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Represents an abstract task for ORC to run.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
void log(raw_ostream &OS) const override
Print an error message to an output stream.
static WrapperFunctionResult createOutOfBandError(const char *Msg)
Create an out-of-band error by copying the given string.
This class implements an extremely fast bulk output stream that can only output to a stream.
IntrusiveRefCntPtr< JITDylib > JITDylibSP
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...
std::vector< std::pair< JITDylib *, JITDylibLookupFlags > > JITDylibSearchOrder
A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search order during symbol lookup.
std::function< void(const SymbolDependenceMap &)> RegisterDependenciesFunction
Callback to register the dependencies for a given query.
@ MissingSymbolDefinitions
@ UnexpectedSymbolDefinitions
std::unique_ptr< ReExportsMaterializationUnit > symbolAliases(SymbolAliasMap Aliases)
Create a ReExportsMaterializationUnit with the given aliases.
SymbolLookupFlags
Lookup flags that apply to each symbol in a lookup.
std::unique_ptr< ReExportsMaterializationUnit > reexports(JITDylib &SourceJD, SymbolAliasMap Aliases, JITDylibLookupFlags SourceJDLookupFlags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Create a materialization unit for re-exporting symbols from another JITDylib with alternative names/f...
DenseMap< SymbolStringPtr, SymbolAliasMapEntry > SymbolAliasMap
A map of Symbols to (Symbol, Flags) pairs.
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
@ MatchExportedSymbolsOnly
DenseMap< SymbolStringPtr, ExecutorSymbolDef > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
DenseMap< SymbolStringPtr, JITSymbolFlags > SymbolFlagsMap
A map from symbol names (as SymbolStringPtrs) to JITSymbolFlags.
unique_function< void(Expected< SymbolMap >)> SymbolsResolvedCallback
Callback to notify client that symbols have been resolved.
DenseSet< SymbolStringPtr > SymbolNameSet
A set of symbol names (represented by SymbolStringPtrs for.
LookupKind
Describes the kind of lookup being performed.
RegisterDependenciesFunction NoDependenciesToRegister
This can be used as the value for a RegisterDependenciesFunction if there are no dependants to regist...
std::vector< SymbolStringPtr > SymbolNameVector
A vector of symbol names.
SymbolState
Represents the state that a symbol has reached during materialization.
@ Materializing
Added to the symbol table, never queried.
@ NeverSearched
No symbol should be in this state.
@ Ready
Emitted to memory, but waiting on transitive dependencies.
@ Resolved
Queried, materialization begun.
std::error_code orcError(OrcErrorCode ErrCode)
DenseMap< JITDylib *, SymbolNameSet > SymbolDependenceMap
A map from JITDylibs to sets of symbols.
Expected< SymbolAliasMap > buildSimpleReexportsAliasMap(JITDylib &SourceJD, const SymbolNameSet &Symbols)
Build a SymbolAliasMap for the common case where you want to re-export symbols from another JITDylib ...
This is an optimization pass for GlobalISel generic memory operations.
auto formatv(const char *Fmt, Ts &&... Vals) -> formatv_object< decltype(std::make_tuple(detail::build_format_adapter(std::forward< Ts >(Vals))...))>
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
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 a range to a container.
auto reverse(ContainerTy &&C)
Error joinErrors(Error E1, Error E2)
Concatenate errors.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.