12#include "llvm/Config/llvm-config.h"
20#include <condition_variable>
24#define DEBUG_TYPE "orc"
43void MaterializationUnit::anchor() {}
47 "JITDylib must be two byte aligned");
49 JDAndFlag.store(
reinterpret_cast<uintptr_t>(JD.get()));
65void ResourceTracker::makeDefunct() {
81 OS <<
"Resource tracker " << (
void *)RT.get() <<
" became defunct";
89 OS <<
"JITDylib " << JD->getName() <<
" (" << (
void *)JD.get()
94 std::shared_ptr<SymbolStringPool> SSP,
95 std::shared_ptr<SymbolDependenceMap> Symbols)
97 assert(this->SSP &&
"String pool cannot be null");
98 assert(!this->Symbols->empty() &&
"Can not fail to resolve an empty set");
102 for (
auto &[JD, Syms] : *this->Symbols)
107 for (
auto &[JD, Syms] : *Symbols)
116 OS <<
"Failed to materialize symbols: " << *Symbols;
120 std::shared_ptr<SymbolStringPool> SSP,
JITDylibSP JD,
122 std::string Explanation)
124 FailedSymbols(
std::
move(FailedSymbols)), BadDeps(
std::
move(BadDeps)),
125 Explanation(
std::
move(Explanation)) {}
132 OS <<
"In " << JD->getName() <<
", failed to materialize " << FailedSymbols
133 <<
", due to unsatisfied dependencies " << BadDeps;
134 if (!Explanation.empty())
135 OS <<
" (" << Explanation <<
")";
142 assert(!this->Symbols.
empty() &&
"Can not fail to resolve an empty set");
148 assert(!this->Symbols.empty() &&
"Can not fail to resolve an empty set");
156 OS <<
"Symbols not found: " << Symbols;
160 std::shared_ptr<SymbolStringPool> SSP,
SymbolNameSet Symbols)
162 assert(!this->Symbols.
empty() &&
"Can not fail to resolve an empty set");
170 OS <<
"Symbols could not be removed: " << Symbols;
178 OS <<
"Missing definitions in module " << ModuleName
187 OS <<
"Unexpected definitions in module " << ModuleName
194 : NotifyComplete(
std::
move(NotifyComplete)), RequiredState(RequiredState) {
196 "Cannot query for a symbols that have not reached the resolve state "
199 OutstandingSymbolsCount = Symbols.size();
201 for (
auto &[Name, Flags] : Symbols)
207 auto I = ResolvedSymbols.find(Name);
208 assert(
I != ResolvedSymbols.end() &&
209 "Resolving symbol outside the requested set");
211 "Redundantly resolving symbol Name");
216 ResolvedSymbols.erase(
I);
218 I->second = std::move(Sym);
219 --OutstandingSymbolsCount;
223 assert(OutstandingSymbolsCount == 0 &&
224 "Symbols remain, handleComplete called prematurely");
226 class RunQueryCompleteTask :
public Task {
228 RunQueryCompleteTask(
SymbolMap ResolvedSymbols,
230 : ResolvedSymbols(
std::
move(ResolvedSymbols)),
231 NotifyComplete(
std::
move(NotifyComplete)) {}
233 OS <<
"Execute query complete callback for " << ResolvedSymbols;
235 void run()
override { NotifyComplete(std::move(ResolvedSymbols)); }
242 auto T = std::make_unique<RunQueryCompleteTask>(std::move(ResolvedSymbols),
243 std::move(NotifyComplete));
248void AsynchronousSymbolQuery::handleFailed(
Error Err) {
249 assert(QueryRegistrations.empty() && ResolvedSymbols.empty() &&
250 OutstandingSymbolsCount == 0 &&
251 "Query should already have been abandoned");
252 NotifyComplete(std::move(Err));
256void AsynchronousSymbolQuery::addQueryDependence(
JITDylib &JD,
258 bool Added = QueryRegistrations[&JD].insert(std::move(Name)).second;
260 assert(Added &&
"Duplicate dependence notification?");
263void AsynchronousSymbolQuery::removeQueryDependence(
265 auto QRI = QueryRegistrations.find(&JD);
266 assert(QRI != QueryRegistrations.end() &&
267 "No dependencies registered for JD");
268 assert(QRI->second.count(Name) &&
"No dependency on Name in JD");
269 QRI->second.erase(Name);
270 if (QRI->second.empty())
271 QueryRegistrations.erase(QRI);
275 auto I = ResolvedSymbols.find(Name);
276 assert(
I != ResolvedSymbols.end() &&
277 "Redundant removal of weakly-referenced symbol");
278 ResolvedSymbols.erase(
I);
279 --OutstandingSymbolsCount;
282void AsynchronousSymbolQuery::detach() {
283 ResolvedSymbols.clear();
284 OutstandingSymbolsCount = 0;
285 for (
auto &[JD, Syms] : QueryRegistrations)
286 JD->detachQueryHelper(*
this, Syms);
287 QueryRegistrations.clear();
294 SourceJDLookupFlags(SourceJDLookupFlags), Aliases(
std::
move(Aliases)) {}
297 return "<Reexports>";
300void ReExportsMaterializationUnit::materialize(
301 std::unique_ptr<MaterializationResponsibility> R) {
303 auto &ES = R->getTargetJITDylib().getExecutionSession();
304 JITDylib &TgtJD = R->getTargetJITDylib();
305 JITDylib &SrcJD = SourceJD ? *SourceJD : TgtJD;
310 auto RequestedSymbols = R->getRequestedSymbols();
313 for (
auto &Name : RequestedSymbols) {
314 auto I = Aliases.
find(Name);
315 assert(
I != Aliases.
end() &&
"Symbol not found in aliases map?");
316 RequestedAliases[Name] = std::move(
I->second);
322 dbgs() <<
"materializing reexports: target = " << TgtJD.
getName()
323 <<
", source = " << SrcJD.
getName() <<
" " << RequestedAliases
328 if (!Aliases.empty()) {
329 auto Err = SourceJD ?
R->replace(
reexports(*SourceJD, std::move(Aliases),
330 SourceJDLookupFlags))
337 R->failMaterialization();
344 struct OnResolveInfo {
345 OnResolveInfo(std::unique_ptr<MaterializationResponsibility> R,
346 SymbolAliasMap Aliases)
347 :
R(std::
move(
R)), Aliases(std::
move(Aliases)) {}
349 std::unique_ptr<MaterializationResponsibility>
R;
351 std::vector<SymbolDependenceGroup> SDGs;
362 std::vector<std::pair<SymbolLookupSet, std::shared_ptr<OnResolveInfo>>>
364 while (!RequestedAliases.
empty()) {
365 SymbolNameSet ResponsibilitySymbols;
366 SymbolLookupSet QuerySymbols;
367 SymbolAliasMap QueryAliases;
370 for (auto &[Alias, AliasInfo] : RequestedAliases) {
372 if (&SrcJD == &TgtJD && (QueryAliases.count(AliasInfo.Aliasee) ||
373 RequestedAliases.count(AliasInfo.Aliasee)))
376 ResponsibilitySymbols.insert(Alias);
377 QuerySymbols.add(AliasInfo.Aliasee,
378 AliasInfo.AliasFlags.hasMaterializationSideEffectsOnly()
379 ? SymbolLookupFlags::WeaklyReferencedSymbol
380 : SymbolLookupFlags::RequiredSymbol);
381 QueryAliases[Alias] = std::move(AliasInfo);
385 for (
auto &KV : QueryAliases)
386 RequestedAliases.
erase(KV.first);
388 assert(!QuerySymbols.empty() &&
"Alias cycle detected!");
390 auto NewR =
R->delegate(ResponsibilitySymbols);
393 R->failMaterialization();
397 auto QueryInfo = std::make_shared<OnResolveInfo>(std::move(*NewR),
398 std::move(QueryAliases));
399 QueryInfos.push_back(
400 make_pair(std::move(QuerySymbols), std::move(QueryInfo)));
404 while (!QueryInfos.empty()) {
405 auto QuerySymbols = std::move(QueryInfos.back().first);
406 auto QueryInfo = std::move(QueryInfos.back().second);
408 QueryInfos.pop_back();
410 auto RegisterDependencies = [QueryInfo,
417 assert(Deps.size() == 1 && Deps.count(&SrcJD) &&
418 "Unexpected dependencies for reexports");
420 auto &SrcJDDeps = Deps.find(&SrcJD)->second;
422 for (
auto &[Alias, AliasInfo] : QueryInfo->Aliases)
423 if (SrcJDDeps.count(AliasInfo.Aliasee))
424 QueryInfo->SDGs.push_back({{Alias}, {{&SrcJD, {AliasInfo.Aliasee}}}});
427 auto OnComplete = [QueryInfo](Expected<SymbolMap>
Result) {
428 auto &ES = QueryInfo->R->getTargetJITDylib().getExecutionSession();
431 for (
auto &KV : QueryInfo->Aliases) {
432 assert((KV.second.AliasFlags.hasMaterializationSideEffectsOnly() ||
433 Result->count(KV.second.Aliasee)) &&
434 "Result map missing entry?");
436 if (KV.second.AliasFlags.hasMaterializationSideEffectsOnly())
439 ResolutionMap[KV.first] = {(*Result)[KV.second.Aliasee].getAddress(),
440 KV.second.AliasFlags};
442 if (
auto Err = QueryInfo->R->notifyResolved(ResolutionMap)) {
444 QueryInfo->R->failMaterialization();
447 if (
auto Err = QueryInfo->R->notifyEmitted(QueryInfo->SDGs)) {
449 QueryInfo->R->failMaterialization();
454 QueryInfo->R->failMaterialization();
461 std::move(RegisterDependencies));
465void ReExportsMaterializationUnit::discard(
const JITDylib &JD,
466 const SymbolStringPtr &Name) {
467 assert(Aliases.count(Name) &&
468 "Symbol not covered by this MaterializationUnit");
472MaterializationUnit::Interface
473ReExportsMaterializationUnit::extractFlags(
const SymbolAliasMap &Aliases) {
475 for (
auto &KV : Aliases)
478 return MaterializationUnit::Interface(std::move(SymbolFlags),
nullptr);
489 return Flags.takeError();
492 for (
auto &Name : Symbols) {
493 assert(Flags->count(Name) &&
"Missing entry in flags map");
512 virtual void complete(std::unique_ptr<InProgressLookupState> IPLS) = 0;
529 } GenState = NotInGenerator;
540 OnComplete(
std::
move(OnComplete)) {}
542 void complete(std::unique_ptr<InProgressLookupState> IPLS)
override {
543 auto &ES =
SearchOrder.front().first->getExecutionSession();
544 ES.OL_completeLookupFlags(std::move(IPLS), std::move(OnComplete));
547 void fail(
Error Err)
override { OnComplete(std::move(Err)); }
558 std::shared_ptr<AsynchronousSymbolQuery> Q,
562 Q(
std::
move(Q)), RegisterDependencies(
std::
move(RegisterDependencies)) {
565 void complete(std::unique_ptr<InProgressLookupState> IPLS)
override {
566 auto &ES =
SearchOrder.front().first->getExecutionSession();
567 ES.OL_completeLookup(std::move(IPLS), std::move(Q),
568 std::move(RegisterDependencies));
573 Q->handleFailed(std::move(Err));
577 std::shared_ptr<AsynchronousSymbolQuery> Q;
584 : SourceJD(SourceJD), SourceJDLookupFlags(SourceJDLookupFlags),
591 assert(&JD != &SourceJD &&
"Cannot re-export from the same dylib");
595 K, {{&SourceJD, JDLookupFlags}}, LookupSet);
597 return Flags.takeError();
601 for (
auto &KV : *Flags)
602 if (!Allow || Allow(KV.first))
605 if (AliasMap.empty())
615void LookupState::reset(InProgressLookupState *IPLS) { this->IPLS.reset(IPLS); }
623 assert(IPLS &&
"Cannot call continueLookup on empty LookupState");
624 auto &ES = IPLS->SearchOrder.begin()->first->getExecutionSession();
625 ES.OL_applyQueryPhase1(std::move(IPLS), std::move(Err));
629 std::deque<LookupState> LookupsToFail;
631 std::lock_guard<std::mutex> Lock(M);
632 std::swap(PendingLookups, LookupsToFail);
636 for (
auto &LS : LookupsToFail)
638 "Query waiting on DefinitionGenerator that was destroyed",
647 std::vector<ResourceTrackerSP> TrackersToRemove;
648 ES.runSessionLocked([&]() {
649 assert(State != Closed &&
"JD is defunct");
650 for (
auto &KV : TrackerSymbols)
651 TrackersToRemove.push_back(KV.first);
656 for (
auto &RT : TrackersToRemove)
657 Err =
joinErrors(std::move(Err), RT->remove());
662 return ES.runSessionLocked([
this] {
663 assert(State != Closed &&
"JD is defunct");
666 return DefaultTracker;
671 return ES.runSessionLocked([
this] {
672 assert(State == Open &&
"JD is defunct");
681 std::shared_ptr<DefinitionGenerator> TmpDG;
683 ES.runSessionLocked([&] {
684 assert(State == Open &&
"JD is defunct");
686 [&](
const std::shared_ptr<DefinitionGenerator> &
H) {
687 return H.get() == &
G;
689 assert(
I != DefGenerators.end() &&
"Generator not found");
690 TmpDG = std::move(*
I);
691 DefGenerators.erase(
I);
700 if (FromMR.RT->isDefunct())
703 std::vector<NonOwningSymbolStringPtr> AddedSyms;
704 std::vector<NonOwningSymbolStringPtr> RejectedWeakDefs;
706 for (
auto &[Name, Flags] : SymbolFlags) {
707 auto EntryItr = Symbols.
find(Name);
710 if (EntryItr != Symbols.
end()) {
713 if (!Flags.isWeak()) {
715 for (
auto &S : AddedSyms)
720 std::string(*Name),
"defineMaterializing operation");
724 RejectedWeakDefs.push_back(NonOwningSymbolStringPtr(Name));
728 Symbols.
insert(std::make_pair(Name, SymbolTableEntry(Flags))).first;
730 AddedSyms.push_back(NonOwningSymbolStringPtr(Name));
735 while (!RejectedWeakDefs.empty()) {
737 RejectedWeakDefs.pop_back();
745 std::unique_ptr<MaterializationUnit> MU) {
746 assert(MU !=
nullptr &&
"Can not replace with a null MaterializationUnit");
747 std::unique_ptr<MaterializationUnit> MustRunMU;
748 std::unique_ptr<MaterializationResponsibility> MustRunMR;
751 ES.runSessionLocked([&,
this]() ->
Error {
752 if (FromMR.RT->isDefunct())
756 for (
auto &KV : MU->getSymbols()) {
757 auto SymI = Symbols.find(KV.first);
758 assert(SymI != Symbols.end() &&
"Replacing unknown symbol");
760 "Can not replace a symbol that ha is not materializing");
761 assert(!SymI->second.hasMaterializerAttached() &&
762 "Symbol should not have materializer attached already");
763 assert(UnmaterializedInfos.count(KV.first) == 0 &&
764 "Symbol being replaced should have no UnmaterializedInfo");
772 for (
auto &KV : MU->getSymbols()) {
773 auto MII = MaterializingInfos.find(KV.first);
774 if (MII != MaterializingInfos.end()) {
775 if (MII->second.hasQueriesPending()) {
776 MustRunMR = ES.createMaterializationResponsibility(
777 *FromMR.RT, std::move(MU->SymbolFlags),
778 std::move(MU->InitSymbol));
779 MustRunMU = std::move(MU);
786 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU),
788 for (
auto &KV : UMI->MU->getSymbols()) {
789 auto SymI = Symbols.find(KV.first);
791 "Can not replace a symbol that is not materializing");
792 assert(!SymI->second.hasMaterializerAttached() &&
793 "Can not replace a symbol that has a materializer attached");
794 assert(UnmaterializedInfos.count(KV.first) == 0 &&
795 "Unexpected materializer entry in map");
796 SymI->second.setAddress(SymI->second.getAddress());
797 SymI->second.setMaterializerAttached(
true);
799 auto &UMIEntry = UnmaterializedInfos[KV.first];
800 assert((!UMIEntry || !UMIEntry->MU) &&
801 "Replacing symbol with materializer still attached");
812 assert(MustRunMR &&
"MustRunMU set implies MustRunMR set");
813 ES.dispatchTask(std::make_unique<MaterializationTask>(
814 std::move(MustRunMU), std::move(MustRunMR)));
816 assert(!MustRunMR &&
"MustRunMU unset implies MustRunMR unset");
822Expected<std::unique_ptr<MaterializationResponsibility>>
826 return ES.runSessionLocked(
827 [&]() -> Expected<std::unique_ptr<MaterializationResponsibility>> {
828 if (FromMR.RT->isDefunct())
831 return ES.createMaterializationResponsibility(
832 *FromMR.RT, std::move(SymbolFlags), std::move(InitSymbol));
837JITDylib::getRequestedSymbols(
const SymbolFlagsMap &SymbolFlags)
const {
838 return ES.runSessionLocked([&]() {
841 for (
auto &KV : SymbolFlags) {
842 assert(Symbols.count(KV.first) &&
"JITDylib does not cover this symbol?");
843 assert(Symbols.find(KV.first)->second.getState() !=
846 "getRequestedSymbols can only be called for symbols that have "
847 "started materializing");
848 auto I = MaterializingInfos.find(KV.first);
849 if (
I == MaterializingInfos.end())
852 if (
I->second.hasQueriesPending())
853 RequestedSymbols.insert(KV.first);
856 return RequestedSymbols;
862 AsynchronousSymbolQuerySet CompletedQueries;
864 if (
auto Err = ES.runSessionLocked([&,
this]() ->
Error {
865 if (MR.RT->isDefunct())
866 return make_error<ResourceTrackerDefunct>(MR.RT);
869 return make_error<StringError>(
"JITDylib " + getName() +
871 inconvertibleErrorCode());
873 struct WorklistEntry {
874 SymbolTable::iterator SymI;
875 ExecutorSymbolDef ResolvedSym;
879 std::vector<WorklistEntry> Worklist;
885 assert(!KV.second.getFlags().hasError() &&
886 "Resolution result can not have error flag set");
888 auto SymI = Symbols.find(KV.first);
890 assert(SymI != Symbols.end() &&
"Symbol not found");
891 assert(!SymI->second.hasMaterializerAttached() &&
892 "Resolving symbol with materializer attached?");
894 "Symbol should be materializing");
895 assert(SymI->second.getAddress() == ExecutorAddr() &&
896 "Symbol has already been resolved");
898 if (SymI->second.getFlags().hasError())
899 SymbolsInErrorState.insert(KV.first);
902 [[maybe_unused]]
auto WeakOrCommon =
904 assert((KV.second.getFlags() & WeakOrCommon) &&
905 "Common symbols must be resolved as common or weak");
906 assert((KV.second.getFlags() & ~WeakOrCommon) ==
908 "Resolving symbol with incorrect flags");
911 assert(KV.second.getFlags() == SymI->second.getFlags() &&
912 "Resolved flags should match the declared flags");
915 {SymI, {KV.second.getAddress(), SymI->second.getFlags()}});
920 if (!SymbolsInErrorState.empty()) {
921 auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
922 (*FailedSymbolsDepMap)[this] = std::move(SymbolsInErrorState);
923 return make_error<FailedToMaterialize>(
924 getExecutionSession().getSymbolStringPool(),
925 std::move(FailedSymbolsDepMap));
928 while (!Worklist.empty()) {
929 auto SymI = Worklist.back().SymI;
930 auto ResolvedSym = Worklist.back().ResolvedSym;
933 auto &Name = SymI->first;
936 JITSymbolFlags ResolvedFlags = ResolvedSym.getFlags();
937 SymI->second.setAddress(ResolvedSym.getAddress());
938 SymI->second.setFlags(ResolvedFlags);
939 SymI->second.setState(SymbolState::Resolved);
941 auto MII = MaterializingInfos.find(Name);
942 if (MII == MaterializingInfos.end())
945 auto &MI = MII->second;
946 for (auto &Q : MI.takeQueriesMeeting(SymbolState::Resolved)) {
947 Q->notifySymbolMetRequiredState(Name, ResolvedSym);
949 CompletedQueries.insert(std::move(Q));
958 for (
auto &Q : CompletedQueries) {
959 assert(Q->isComplete() &&
"Q not completed");
960 Q->handleComplete(ES);
966void JITDylib::unlinkMaterializationResponsibility(
967 MaterializationResponsibility &MR) {
969 auto I = TrackerMRs.find(MR.RT.get());
970 assert(
I != TrackerMRs.end() &&
"No MRs in TrackerMRs list for RT");
971 assert(
I->second.count(&MR) &&
"MR not in TrackerMRs list for RT");
972 I->second.erase(&MR);
973 if (
I->second.empty())
974 TrackerMRs.erase(MR.RT.get());
978void JITDylib::shrinkMaterializationInfoMemory() {
982 if (UnmaterializedInfos.empty())
983 UnmaterializedInfos.clear();
985 if (MaterializingInfos.empty())
986 MaterializingInfos.clear();
990 bool LinkAgainstThisJITDylibFirst) {
991 ES.runSessionLocked([&]() {
992 assert(State == Open &&
"JD is defunct");
993 if (LinkAgainstThisJITDylibFirst) {
995 if (NewLinkOrder.empty() || NewLinkOrder.front().first !=
this)
1000 LinkOrder = std::move(NewLinkOrder);
1005 ES.runSessionLocked([&]() {
1006 for (
auto &KV : NewLinks) {
1011 LinkOrder.push_back(std::move(KV));
1017 ES.runSessionLocked([&]() { LinkOrder.push_back({&JD, JDLookupFlags}); });
1022 ES.runSessionLocked([&]() {
1023 assert(State == Open &&
"JD is defunct");
1024 for (
auto &KV : LinkOrder)
1025 if (KV.first == &OldJD) {
1026 KV = {&NewJD, JDLookupFlags};
1033 ES.runSessionLocked([&]() {
1034 assert(State == Open &&
"JD is defunct");
1036 [&](
const JITDylibSearchOrder::value_type &KV) {
1037 return KV.first == &JD;
1039 if (
I != LinkOrder.end())
1045 return ES.runSessionLocked([&]() ->
Error {
1046 assert(State == Open &&
"JD is defunct");
1051 for (
auto &Name : Names) {
1052 auto I = Symbols.find(Name);
1055 if (
I == Symbols.end()) {
1056 Missing.insert(Name);
1071 if (!Missing.empty())
1073 std::move(Missing));
1085 auto UMII = UnmaterializedInfos.find(Name);
1086 if (UMII != UnmaterializedInfos.end()) {
1087 UMII->second->MU->doDiscard(*
this, UMII->first);
1088 UnmaterializedInfos.erase(UMII);
1091 Symbols.erase(Name);
1094 shrinkMaterializationInfoMemory();
1101 ES.runSessionLocked([&,
this]() {
1102 OS <<
"JITDylib \"" <<
getName() <<
"\" (ES: "
1117 if (State == Closed)
1119 OS <<
"Link order: " << LinkOrder <<
"\n"
1120 <<
"Symbol table:\n";
1123 std::vector<std::pair<SymbolStringPtr, SymbolTableEntry *>> SymbolsSorted;
1124 for (
auto &KV : Symbols)
1125 SymbolsSorted.emplace_back(KV.first, &KV.second);
1126 std::sort(SymbolsSorted.begin(), SymbolsSorted.end(),
1127 [](
const auto &L,
const auto &R) { return *L.first < *R.first; });
1129 for (
auto &KV : SymbolsSorted) {
1130 OS <<
" \"" << *KV.first <<
"\": ";
1131 if (
auto Addr = KV.second->getAddress())
1134 OS <<
"<not resolved> ";
1136 OS <<
" " << KV.second->getFlags() <<
" " << KV.second->getState();
1138 if (KV.second->hasMaterializerAttached()) {
1139 OS <<
" (Materializer ";
1140 auto I = UnmaterializedInfos.find(KV.first);
1141 assert(
I != UnmaterializedInfos.end() &&
1142 "Lazy symbol should have UnmaterializedInfo");
1143 OS <<
I->second->MU.get() <<
", " <<
I->second->MU->getName() <<
")\n";
1148 if (!MaterializingInfos.empty())
1149 OS <<
" MaterializingInfos entries:\n";
1150 for (
auto &KV : MaterializingInfos) {
1151 OS <<
" \"" << *KV.first <<
"\":\n"
1152 <<
" " << KV.second.pendingQueries().size()
1153 <<
" pending queries: { ";
1154 for (
const auto &Q : KV.second.pendingQueries())
1155 OS << Q.get() <<
" (" << Q->getRequiredState() <<
") ";
1161void JITDylib::MaterializingInfo::addQuery(
1162 std::shared_ptr<AsynchronousSymbolQuery> Q) {
1166 [](
const std::shared_ptr<AsynchronousSymbolQuery> &V,
SymbolState S) {
1167 return V->getRequiredState() <= S;
1169 PendingQueries.insert(
I.base(), std::move(Q));
1172void JITDylib::MaterializingInfo::removeQuery(
1173 const AsynchronousSymbolQuery &Q) {
1176 PendingQueries, [&Q](
const std::shared_ptr<AsynchronousSymbolQuery> &V) {
1177 return V.get() == &Q;
1179 if (
I != PendingQueries.end())
1180 PendingQueries.erase(
I);
1183JITDylib::AsynchronousSymbolQueryList
1184JITDylib::MaterializingInfo::takeQueriesMeeting(SymbolState RequiredState) {
1185 AsynchronousSymbolQueryList
Result;
1186 while (!PendingQueries.empty()) {
1187 if (PendingQueries.back()->getRequiredState() > RequiredState)
1190 Result.push_back(std::move(PendingQueries.back()));
1191 PendingQueries.pop_back();
1197JITDylib::JITDylib(ExecutionSession &ES, std::string Name)
1198 : JITLinkDylib(std::
move(
Name)), ES(ES) {
1202JITDylib::RemoveTrackerResult JITDylib::IL_removeTracker(
ResourceTracker &RT) {
1204 assert(State != Closed &&
"JD is defunct");
1209 if (&RT == DefaultTracker.get()) {
1211 for (
auto &KV : TrackerSymbols)
1214 for (
auto &KV : Symbols) {
1215 auto &Sym = KV.first;
1216 if (!TrackedSymbols.count(Sym))
1217 SymbolsToRemove.push_back(Sym);
1220 DefaultTracker.reset();
1223 auto I = TrackerSymbols.find(&RT);
1224 if (
I != TrackerSymbols.end()) {
1225 SymbolsToRemove = std::move(
I->second);
1226 TrackerSymbols.erase(
I);
1231 for (
auto &Sym : SymbolsToRemove) {
1232 assert(Symbols.count(Sym) &&
"Symbol not in symbol table");
1235 auto MII = MaterializingInfos.find(Sym);
1236 if (MII != MaterializingInfos.end())
1237 SymbolsToFail.push_back(Sym);
1240 auto [QueriesToFail, FailedSymbols] =
1241 ES.IL_failSymbols(*
this, std::move(SymbolsToFail));
1243 std::vector<std::unique_ptr<MaterializationUnit>> DefunctMUs;
1246 for (
auto &Sym : SymbolsToRemove) {
1247 auto I = Symbols.find(Sym);
1248 assert(
I != Symbols.end() &&
"Symbol not present in table");
1251 if (
I->second.hasMaterializerAttached()) {
1253 auto J = UnmaterializedInfos.find(Sym);
1254 assert(J != UnmaterializedInfos.end() &&
1255 "Symbol table indicates MU present, but no UMI record");
1257 DefunctMUs.push_back(std::move(J->second->MU));
1258 UnmaterializedInfos.erase(J);
1260 assert(!UnmaterializedInfos.count(Sym) &&
1261 "Symbol has materializer attached");
1267 shrinkMaterializationInfoMemory();
1269 return {std::move(QueriesToFail), std::move(FailedSymbols),
1270 std::move(DefunctMUs)};
1274 assert(State != Closed &&
"JD is defunct");
1275 assert(&DstRT != &SrcRT &&
"No-op transfers shouldn't call transferTracker");
1276 assert(&DstRT.getJITDylib() ==
this &&
"DstRT is not for this JITDylib");
1277 assert(&SrcRT.getJITDylib() ==
this &&
"SrcRT is not for this JITDylib");
1280 for (
auto &KV : UnmaterializedInfos) {
1281 if (KV.second->RT == &SrcRT)
1282 KV.second->RT = &DstRT;
1287 auto I = TrackerMRs.find(&SrcRT);
1288 if (
I != TrackerMRs.end()) {
1289 auto &SrcMRs =
I->second;
1290 auto &DstMRs = TrackerMRs[&DstRT];
1291 for (
auto *MR : SrcMRs)
1294 DstMRs = std::move(SrcMRs);
1296 DstMRs.insert_range(SrcMRs);
1299 TrackerMRs.erase(&SrcRT);
1305 if (&DstRT == DefaultTracker.get()) {
1306 TrackerSymbols.erase(&SrcRT);
1312 if (&SrcRT == DefaultTracker.get()) {
1313 assert(!TrackerSymbols.count(&SrcRT) &&
1314 "Default tracker should not appear in TrackerSymbols");
1319 for (
auto &KV : TrackerSymbols)
1322 for (
auto &KV : Symbols) {
1323 auto &Sym = KV.first;
1324 if (!CurrentlyTrackedSymbols.count(Sym))
1325 SymbolsToTrack.push_back(Sym);
1328 TrackerSymbols[&DstRT] = std::move(SymbolsToTrack);
1332 auto &DstTrackedSymbols = TrackerSymbols[&DstRT];
1336 auto SI = TrackerSymbols.find(&SrcRT);
1337 if (SI == TrackerSymbols.end())
1340 DstTrackedSymbols.reserve(DstTrackedSymbols.size() +
SI->second.size());
1341 for (
auto &Sym :
SI->second)
1342 DstTrackedSymbols.push_back(std::move(Sym));
1343 TrackerSymbols.erase(SI);
1350 std::vector<SymbolStringPtr> ExistingDefsOverridden;
1351 std::vector<SymbolStringPtr> MUDefsOverridden;
1353 for (
const auto &KV : MU.getSymbols()) {
1354 auto I = Symbols.find(KV.first);
1356 if (
I != Symbols.end()) {
1357 if (KV.second.isStrong()) {
1358 if (
I->second.getFlags().isStrong() ||
1360 Duplicates.insert(KV.first);
1363 "Overridden existing def should be in the never-searched "
1365 ExistingDefsOverridden.push_back(KV.first);
1368 MUDefsOverridden.push_back(KV.first);
1373 if (!Duplicates.empty()) {
1375 {
dbgs() <<
" Error: Duplicate symbols " << Duplicates <<
"\n"; });
1377 MU.getName().str());
1382 if (!MUDefsOverridden.empty())
1383 dbgs() <<
" Defs in this MU overridden: " << MUDefsOverridden <<
"\n";
1385 for (
auto &S : MUDefsOverridden)
1386 MU.doDiscard(*
this, S);
1390 if (!ExistingDefsOverridden.empty())
1391 dbgs() <<
" Existing defs overridden by this MU: " << MUDefsOverridden
1394 for (
auto &S : ExistingDefsOverridden) {
1396 auto UMII = UnmaterializedInfos.find(S);
1397 assert(UMII != UnmaterializedInfos.end() &&
1398 "Overridden existing def should have an UnmaterializedInfo");
1399 UMII->second->MU->doDiscard(*
this, S);
1403 for (
auto &KV : MU.getSymbols()) {
1404 auto &SymEntry = Symbols[KV.first];
1405 SymEntry.setFlags(KV.second);
1407 SymEntry.setMaterializerAttached(
true);
1413void JITDylib::installMaterializationUnit(
1417 if (&RT != DefaultTracker.get()) {
1418 auto &TS = TrackerSymbols[&RT];
1419 TS.reserve(TS.size() + MU->getSymbols().size());
1420 for (
auto &KV : MU->getSymbols())
1421 TS.push_back(KV.first);
1424 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU), &RT);
1425 for (
auto &KV : UMI->MU->getSymbols())
1426 UnmaterializedInfos[KV.first] = UMI;
1431 for (
auto &QuerySymbol : QuerySymbols) {
1432 auto MII = MaterializingInfos.find(QuerySymbol);
1433 if (MII != MaterializingInfos.end())
1434 MII->second.removeQuery(Q);
1446 std::mutex LookupMutex;
1447 std::condition_variable CV;
1451 dbgs() <<
"Issuing init-symbol lookup:\n";
1452 for (
auto &KV : InitSyms)
1453 dbgs() <<
" " << KV.first->getName() <<
": " << KV.second <<
"\n";
1456 for (
auto &KV : InitSyms) {
1457 auto *JD = KV.first;
1458 auto Names = std::move(KV.second);
1465 std::lock_guard<std::mutex> Lock(LookupMutex);
1469 "Duplicate JITDylib in lookup?");
1470 CompoundResult[JD] = std::move(*
Result);
1480 std::unique_lock<std::mutex> Lock(LookupMutex);
1481 CV.wait(Lock, [&] {
return Count == 0; });
1484 return std::move(CompoundErr);
1486 return std::move(CompoundResult);
1493 class TriggerOnComplete {
1496 TriggerOnComplete(OnCompleteFn OnComplete)
1497 : OnComplete(std::move(OnComplete)) {}
1498 ~TriggerOnComplete() { OnComplete(std::move(LookupResult)); }
1499 void reportResult(
Error Err) {
1500 std::lock_guard<std::mutex> Lock(ResultMutex);
1501 LookupResult =
joinErrors(std::move(LookupResult), std::move(Err));
1505 std::mutex ResultMutex;
1507 OnCompleteFn OnComplete;
1511 dbgs() <<
"Issuing init-symbol lookup:\n";
1512 for (
auto &KV : InitSyms)
1513 dbgs() <<
" " << KV.first->getName() <<
": " << KV.second <<
"\n";
1516 auto TOC = std::make_shared<TriggerOnComplete>(std::move(OnComplete));
1518 for (
auto &KV : InitSyms) {
1519 auto *JD = KV.first;
1520 auto Names = std::move(KV.second);
1526 TOC->reportResult(
Result.takeError());
1535 MR->failMaterialization();
1539 OS <<
"Materialization task: " << MU->getName() <<
" in "
1540 << MR->getTargetJITDylib().getName();
1544 assert(MU &&
"MU should not be null");
1545 assert(MR &&
"MR should not be null");
1546 MU->materialize(std::move(MR));
1556 this->EPC->ES =
this;
1558 for (
auto &[Name, Ptr] : this->EPC->getBootstrapSymbolsMap())
1559 BootstrapSymbols[
intern(Name)] =
1569 "Session still open. Did you forget to call endSession?");
1573 LLVM_DEBUG(
dbgs() <<
"Ending ExecutionSession " <<
this <<
"\n");
1575 WaitingOnGraph::OpRecorder *GOpRecorderToEnd =
nullptr;
1578#ifdef EXPENSIVE_CHECKS
1579 verifySessionState(
"Entering ExecutionSession::endSession");
1583 GOpRecorderToEnd = GOpRecorder;
1584 SessionOpen =
false;
1588 std::reverse(JDsToRemove.begin(), JDsToRemove.end());
1592 Err =
joinErrors(std::move(Err), EPC->disconnect());
1594 if (GOpRecorderToEnd)
1595 GOpRecorderToEnd->recordEnd();
1606 assert(!ResourceManagers.empty() &&
"No managers registered");
1607 if (ResourceManagers.back() == &RM)
1608 ResourceManagers.pop_back();
1611 assert(
I != ResourceManagers.end() &&
"RM not registered");
1612 ResourceManagers.erase(
I);
1619 for (
auto &JD : JDs)
1620 if (JD->getName() == Name)
1629 assert(SessionOpen &&
"Cannot create JITDylib after session is closed");
1630 JDs.push_back(
new JITDylib(*
this, std::move(Name)));
1638 if (
auto Err = P->setupJITDylib(JD))
1639 return std::move(Err);
1646 for (
auto &JD : JDsToRemove) {
1647 assert(JD->State == JITDylib::Open &&
"JD already closed");
1648 JD->State = JITDylib::Closing;
1650 assert(
I != JDs.end() &&
"JD does not appear in session JDs");
1657 for (
auto JD : JDsToRemove) {
1658 Err =
joinErrors(std::move(Err), JD->clear());
1660 Err =
joinErrors(std::move(Err), P->teardownJITDylib(*JD));
1665 for (
auto &JD : JDsToRemove) {
1666 assert(JD->State == JITDylib::Closing &&
"JD should be closing");
1667 JD->State = JITDylib::Closed;
1668 assert(JD->Symbols.empty() &&
"JD.Symbols is not empty after clear");
1669 assert(JD->UnmaterializedInfos.empty() &&
1670 "JD.UnmaterializedInfos is not empty after clear");
1671 assert(JD->MaterializingInfos.empty() &&
1672 "JD.MaterializingInfos is not empty after clear");
1673 assert(JD->TrackerSymbols.empty() &&
1674 "TrackerSymbols is not empty after clear");
1675 JD->DefGenerators.clear();
1676 JD->LinkOrder.clear();
1686 return std::vector<JITDylibSP>();
1688 auto &ES = JDs.
front()->getExecutionSession();
1689 return ES.runSessionLocked([&]() ->
Expected<std::vector<JITDylibSP>> {
1691 std::vector<JITDylibSP>
Result;
1693 for (
auto &JD : JDs) {
1695 if (JD->State != Open)
1697 "Error building link order: " + JD->getName() +
" is defunct",
1699 if (Visited.
count(JD.get()))
1704 Visited.
insert(JD.get());
1706 while (!WorkStack.
empty()) {
1707 Result.push_back(std::move(WorkStack.
back()));
1711 auto &JD = *KV.first;
1712 if (!Visited.
insert(&JD).second)
1742 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
1743 K, std::move(SearchOrder), std::move(LookupSet),
1744 std::move(OnComplete)),
1752 std::promise<MSVCPExpected<SymbolFlagsMap>> ResultP;
1753 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
1754 K, std::move(SearchOrder), std::move(LookupSet),
1756 ResultP.set_value(std::move(
Result));
1760 auto ResultF = ResultP.get_future();
1761 return ResultF.
get();
1772 dbgs() <<
"Looking up " << Symbols <<
" in " << SearchOrder
1773 <<
" (required state: " << RequiredState <<
")\n";
1780 dispatchOutstandingMUs();
1782 auto Unresolved = std::move(Symbols);
1783 auto Q = std::make_shared<AsynchronousSymbolQuery>(Unresolved, RequiredState,
1784 std::move(NotifyComplete));
1786 auto IPLS = std::make_unique<InProgressFullLookupState>(
1787 K, SearchOrder, std::move(Unresolved), RequiredState, std::move(Q),
1788 std::move(RegisterDependencies));
1798#if LLVM_ENABLE_THREADS
1800 std::promise<MSVCPExpected<SymbolMap>> PromisedResult;
1803 PromisedResult.set_value(std::move(R));
1815 ResolutionError = R.takeError();
1820 lookup(K, SearchOrder, std::move(Symbols), RequiredState,
1821 std::move(NotifyComplete), RegisterDependencies);
1823#if LLVM_ENABLE_THREADS
1824 return PromisedResult.get_future().get();
1826 if (ResolutionError)
1827 return std::move(ResolutionError);
1840 assert(ResultMap->size() == 1 &&
"Unexpected number of results");
1841 assert(ResultMap->count(Name) &&
"Missing result for symbol");
1842 return std::move(ResultMap->begin()->second);
1844 return ResultMap.takeError();
1856 return lookup(SearchOrder,
intern(Name), RequiredState);
1866 return TagSyms.takeError();
1869 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
1872 for (
auto &[TagName, TagSym] : *TagSyms) {
1873 auto TagAddr = TagSym.getAddress();
1874 if (JITDispatchHandlers.count(TagAddr))
1876 " (for " + *TagName +
1877 ") already registered",
1882 for (
auto &[TagName, TagSym] : *TagSyms) {
1883 auto TagAddr = TagSym.getAddress();
1884 auto I = WFs.
find(TagName);
1886 "JITDispatchHandler implementation missing");
1887 JITDispatchHandlers[TagAddr] =
1888 std::make_shared<JITDispatchHandlerFunction>(std::move(
I->second));
1890 dbgs() <<
"Associated function tag \"" << *TagName <<
"\" ("
1891 <<
formatv(
"{0:x}", TagAddr) <<
") with handler\n";
1902 std::shared_ptr<JITDispatchHandlerFunction>
F;
1904 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
1905 auto I = JITDispatchHandlers.find(HandlerFnTagAddr);
1906 if (
I != JITDispatchHandlers.end())
1911 (*F)(std::move(SendResult), ArgBytes.
data(), ArgBytes.
size());
1914 (
"No function registered for tag " +
1915 formatv(
"{0:x16}", HandlerFnTagAddr))
1921 for (
auto &JD : JDs)
1926#ifdef EXPENSIVE_CHECKS
1927bool ExecutionSession::verifySessionState(
Twine Phase) {
1931 for (
auto &JD : JDs) {
1934 auto &Stream =
errs();
1936 Stream <<
"ERROR: Bad ExecutionSession state detected " <<
Phase
1938 Stream <<
" In JITDylib " << JD->getName() <<
", ";
1943 if (JD->State != JITDylib::Open) {
1945 <<
"state is not Open, but JD is in ExecutionSession list.";
1953 for (
auto &[Sym, Entry] : JD->Symbols) {
1956 if (Entry.getAddress()) {
1957 LogFailure() <<
"symbol " << Sym <<
" has state "
1959 <<
" (not-yet-resolved) but non-null address "
1960 << Entry.getAddress() <<
".\n";
1965 auto UMIItr = JD->UnmaterializedInfos.find(Sym);
1966 if (
Entry.hasMaterializerAttached()) {
1967 if (UMIItr == JD->UnmaterializedInfos.end()) {
1968 LogFailure() <<
"symbol " << Sym
1969 <<
" entry claims materializer attached, but "
1970 "UnmaterializedInfos has no corresponding entry.\n";
1972 }
else if (UMIItr != JD->UnmaterializedInfos.end()) {
1975 <<
" entry claims no materializer attached, but "
1976 "UnmaterializedInfos has an unexpected entry for it.\n";
1982 for (
auto &[Sym, UMI] : JD->UnmaterializedInfos) {
1983 auto SymItr = JD->Symbols.find(Sym);
1984 if (SymItr == JD->Symbols.end()) {
1987 <<
" has UnmaterializedInfos entry, but no Symbols entry.\n";
1992 for (
auto &[Sym, MII] : JD->MaterializingInfos) {
1994 auto SymItr = JD->Symbols.find(Sym);
1995 if (SymItr == JD->Symbols.end()) {
2000 <<
" has MaterializingInfos entry, but no Symbols entry.\n";
2008 <<
" is in Ready state, should not have MaterializingInfo.\n";
2013 static_cast<std::underlying_type_t<SymbolState>
>(
2014 SymItr->second.getState()) + 1);
2015 for (
auto &Q : MII.PendingQueries) {
2016 if (Q->getRequiredState() != CurState) {
2017 if (Q->getRequiredState() > CurState)
2018 CurState = Q->getRequiredState();
2020 LogFailure() <<
"symbol " << Sym
2021 <<
" has stale or misordered queries.\n";
2033void ExecutionSession::dispatchOutstandingMUs() {
2036 std::optional<std::pair<std::unique_ptr<MaterializationUnit>,
2037 std::unique_ptr<MaterializationResponsibility>>>
2041 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2042 if (!OutstandingMUs.empty()) {
2043 JMU.emplace(std::move(OutstandingMUs.back()));
2044 OutstandingMUs.pop_back();
2051 assert(JMU->first &&
"No MU?");
2052 LLVM_DEBUG(
dbgs() <<
" Dispatching \"" << JMU->first->getName() <<
"\"\n");
2053 dispatchTask(std::make_unique<MaterializationTask>(std::move(JMU->first),
2054 std::move(JMU->second)));
2056 LLVM_DEBUG(
dbgs() <<
"Done dispatching MaterializationUnits.\n");
2061 dbgs() <<
"In " << RT.getJITDylib().getName() <<
" removing tracker "
2062 <<
formatv(
"{0:x}", RT.getKeyUnsafe()) <<
"\n";
2064 std::vector<ResourceManager *> CurrentResourceManagers;
2066 JITDylib::RemoveTrackerResult
R;
2069 CurrentResourceManagers = ResourceManagers;
2071 R = RT.getJITDylib().IL_removeTracker(RT);
2075 R.DefunctMUs.clear();
2079 auto &JD = RT.getJITDylib();
2080 for (
auto *L :
reverse(CurrentResourceManagers))
2082 L->handleRemoveResources(JD, RT.getKeyUnsafe()));
2084 for (
auto &Q :
R.QueriesToFail)
2094 dbgs() <<
"In " << SrcRT.getJITDylib().getName()
2095 <<
" transfering resources from tracker "
2096 <<
formatv(
"{0:x}", SrcRT.getKeyUnsafe()) <<
" to tracker "
2097 <<
formatv(
"{0:x}", DstRT.getKeyUnsafe()) <<
"\n";
2101 if (&DstRT == &SrcRT)
2104 assert(&DstRT.getJITDylib() == &SrcRT.getJITDylib() &&
2105 "Can't transfer resources between JITDylibs");
2107 SrcRT.makeDefunct();
2108 auto &JD = DstRT.getJITDylib();
2109 JD.transferTracker(DstRT, SrcRT);
2110 for (
auto *L :
reverse(ResourceManagers))
2111 L->handleTransferResources(JD, DstRT.getKeyUnsafe(),
2112 SrcRT.getKeyUnsafe());
2119 dbgs() <<
"In " << RT.getJITDylib().getName() <<
" destroying tracker "
2120 <<
formatv(
"{0:x}", RT.getKeyUnsafe()) <<
"\n";
2122 if (!RT.isDefunct())
2123 transferResourceTracker(*RT.getJITDylib().getDefaultResourceTracker(),
2128Error ExecutionSession::IL_updateCandidatesFor(
2131 return Candidates.forEachWithRemoval(
2132 [&](
const SymbolStringPtr &Name,
2136 auto SymI = JD.Symbols.find(Name);
2137 if (SymI == JD.Symbols.end())
2145 if (!SymI->second.getFlags().isExported() &&
2148 NonCandidates->add(Name, SymLookupFlags);
2157 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2164 if (SymI->second.getFlags().hasError()) {
2165 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2166 (*FailedSymbolsMap)[&JD] = {
Name};
2168 std::move(FailedSymbolsMap));
2176void ExecutionSession::OL_resumeLookupAfterGeneration(
2180 "Should not be called for not-in-generator lookups");
2185 if (
auto DG = IPLS.CurDefGeneratorStack.back().lock()) {
2186 IPLS.CurDefGeneratorStack.pop_back();
2187 std::lock_guard<std::mutex> Lock(DG->M);
2191 if (DG->PendingLookups.empty()) {
2197 LS = std::move(DG->PendingLookups.front());
2198 DG->PendingLookups.pop_front();
2203 dispatchTask(std::make_unique<LookupTask>(std::move(LS)));
2207void ExecutionSession::OL_applyQueryPhase1(
2208 std::unique_ptr<InProgressLookupState> IPLS,
Error Err) {
2211 dbgs() <<
"Entering OL_applyQueryPhase1:\n"
2212 <<
" Lookup kind: " << IPLS->K <<
"\n"
2213 <<
" Search order: " << IPLS->SearchOrder
2214 <<
", Current index = " << IPLS->CurSearchOrderIndex
2215 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2216 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2217 <<
" Definition generator candidates: "
2218 << IPLS->DefGeneratorCandidates <<
"\n"
2219 <<
" Definition generator non-candidates: "
2220 << IPLS->DefGeneratorNonCandidates <<
"\n";
2224 OL_resumeLookupAfterGeneration(*IPLS);
2227 "Lookup should not be in InGenerator state here");
2234 while (IPLS->CurSearchOrderIndex != IPLS->SearchOrder.size()) {
2240 return IPLS->fail(std::move(Err));
2243 auto &KV = IPLS->SearchOrder[IPLS->CurSearchOrderIndex];
2244 auto &JD = *KV.first;
2245 auto JDLookupFlags = KV.second;
2248 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2249 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2253 if (IPLS->NewJITDylib) {
2257 SymbolLookupSet Tmp;
2258 std::swap(IPLS->DefGeneratorNonCandidates, Tmp);
2259 IPLS->DefGeneratorCandidates.append(std::move(Tmp));
2262 dbgs() <<
" First time visiting " << JD.getName()
2263 <<
", resetting candidate sets and building generator stack\n";
2268 IPLS->CurDefGeneratorStack.reserve(JD.DefGenerators.size());
2274 IPLS->NewJITDylib =
false;
2283 Err = IL_updateCandidatesFor(
2284 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2285 JD.DefGenerators.empty() ?
nullptr
2286 : &IPLS->DefGeneratorNonCandidates);
2288 dbgs() <<
" Remaining candidates = " << IPLS->DefGeneratorCandidates
2296 IPLS->DefGeneratorCandidates.empty())
2297 OL_resumeLookupAfterGeneration(*IPLS);
2303 return IPLS->fail(std::move(Err));
2307 if (IPLS->CurDefGeneratorStack.empty())
2308 LLVM_DEBUG(
dbgs() <<
" No generators to run for this JITDylib.\n");
2309 else if (IPLS->DefGeneratorCandidates.empty())
2312 dbgs() <<
" Running " << IPLS->CurDefGeneratorStack.size()
2313 <<
" remaining generators for "
2314 << IPLS->DefGeneratorCandidates.size() <<
" candidates\n";
2316 while (!IPLS->CurDefGeneratorStack.empty() &&
2317 !IPLS->DefGeneratorCandidates.empty()) {
2318 auto DG = IPLS->CurDefGeneratorStack.back().lock();
2322 "DefinitionGenerator removed while lookup in progress",
2335 std::lock_guard<std::mutex> Lock(DG->M);
2337 DG->PendingLookups.push_back(std::move(IPLS));
2346 auto &LookupSet = IPLS->DefGeneratorCandidates;
2351 LLVM_DEBUG(
dbgs() <<
" Attempting to generate " << LookupSet <<
"\n");
2353 Err = DG->tryToGenerate(LS, K, JD, JDLookupFlags, LookupSet);
2354 IPLS = std::move(
LS.IPLS);
2360 OL_resumeLookupAfterGeneration(*IPLS);
2365 dbgs() <<
" Error attempting to generate " << LookupSet <<
"\n";
2367 assert(IPLS &&
"LS cannot be retained if error is returned");
2368 return IPLS->fail(std::move(Err));
2374 {
dbgs() <<
" LookupState captured. Exiting phase1 for now.\n"; });
2381 LLVM_DEBUG(
dbgs() <<
" Updating candidate set post-generation\n");
2382 Err = IL_updateCandidatesFor(
2383 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2384 JD.DefGenerators.empty() ?
nullptr
2385 : &IPLS->DefGeneratorNonCandidates);
2390 LLVM_DEBUG(
dbgs() <<
" Error encountered while updating candidates\n");
2391 return IPLS->fail(std::move(Err));
2395 if (IPLS->DefGeneratorCandidates.empty() &&
2396 IPLS->DefGeneratorNonCandidates.empty()) {
2399 IPLS->CurSearchOrderIndex = IPLS->SearchOrder.size();
2405 ++IPLS->CurSearchOrderIndex;
2406 IPLS->NewJITDylib =
true;
2411 IPLS->DefGeneratorCandidates.remove_if(
2419 if (IPLS->DefGeneratorCandidates.empty()) {
2421 IPLS->complete(std::move(IPLS));
2423 LLVM_DEBUG(
dbgs() <<
"Phase 1 failed with unresolved symbols.\n");
2429void ExecutionSession::OL_completeLookup(
2430 std::unique_ptr<InProgressLookupState> IPLS,
2431 std::shared_ptr<AsynchronousSymbolQuery> Q,
2435 dbgs() <<
"Entering OL_completeLookup:\n"
2436 <<
" Lookup kind: " << IPLS->K <<
"\n"
2437 <<
" Search order: " << IPLS->SearchOrder
2438 <<
", Current index = " << IPLS->CurSearchOrderIndex
2439 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2440 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2441 <<
" Definition generator candidates: "
2442 << IPLS->DefGeneratorCandidates <<
"\n"
2443 <<
" Definition generator non-candidates: "
2444 << IPLS->DefGeneratorNonCandidates <<
"\n";
2447 bool QueryComplete =
false;
2448 DenseMap<JITDylib *, JITDylib::UnmaterializedInfosList> CollectedUMIs;
2451 for (
auto &KV : IPLS->SearchOrder) {
2452 auto &JD = *KV.first;
2453 auto JDLookupFlags = KV.second;
2455 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2456 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2459 auto Err = IPLS->LookupSet.forEachWithRemoval(
2460 [&](
const SymbolStringPtr &Name,
2463 dbgs() <<
" Attempting to match \"" <<
Name <<
"\" ("
2464 << SymLookupFlags <<
")... ";
2469 auto SymI = JD.Symbols.find(Name);
2470 if (SymI == JD.Symbols.end()) {
2477 if (!SymI->second.getFlags().isExported() &&
2489 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2493 "required, but symbol is has-side-effects-only\n";
2501 if (SymI->second.getFlags().hasError()) {
2503 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2504 (*FailedSymbolsMap)[&JD] = {
Name};
2513 if (SymI->second.getState() >= Q->getRequiredState()) {
2515 <<
"matched, symbol already in required state\n");
2516 Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
2521 Q->addQueryDependence(JD, Name);
2529 if (SymI->second.hasMaterializerAttached()) {
2530 assert(SymI->second.getAddress() == ExecutorAddr() &&
2531 "Symbol not resolved but already has address?");
2532 auto UMII = JD.UnmaterializedInfos.find(Name);
2533 assert(UMII != JD.UnmaterializedInfos.end() &&
2534 "Lazy symbol should have UnmaterializedInfo");
2536 auto UMI = UMII->second;
2537 assert(UMI->MU &&
"Materializer should not be null");
2538 assert(UMI->RT &&
"Tracker should not be null");
2540 dbgs() <<
"matched, preparing to dispatch MU@" << UMI->MU.get()
2541 <<
" (" << UMI->MU->getName() <<
")\n";
2546 for (
auto &KV : UMI->MU->getSymbols()) {
2547 auto SymK = JD.Symbols.find(KV.first);
2548 assert(SymK != JD.Symbols.end() &&
2549 "No entry for symbol covered by MaterializationUnit");
2550 SymK->second.setMaterializerAttached(
false);
2552 JD.UnmaterializedInfos.erase(KV.first);
2556 CollectedUMIs[&JD].push_back(std::move(UMI));
2564 "By this line the symbol should be materializing");
2565 auto &
MI = JD.MaterializingInfos[
Name];
2567 Q->addQueryDependence(JD, Name);
2572 JD.shrinkMaterializationInfoMemory();
2578 dbgs() <<
"Lookup failed. Detaching query and replacing MUs.\n";
2585 for (
auto &KV : CollectedUMIs) {
2586 auto &JD = *KV.first;
2587 for (
auto &UMI : KV.second)
2588 for (
auto &KV2 : UMI->MU->getSymbols()) {
2589 assert(!JD.UnmaterializedInfos.count(KV2.first) &&
2590 "Unexpected materializer in map");
2591 auto SymI = JD.Symbols.find(KV2.first);
2592 assert(SymI != JD.Symbols.end() &&
"Missing symbol entry");
2594 "Can not replace symbol that is not materializing");
2595 assert(!SymI->second.hasMaterializerAttached() &&
2596 "MaterializerAttached flag should not be set");
2597 SymI->second.setMaterializerAttached(
true);
2598 JD.UnmaterializedInfos[KV2.first] = UMI;
2606 LLVM_DEBUG(
dbgs() <<
"Stripping unmatched weakly-referenced symbols\n");
2607 IPLS->LookupSet.forEachWithRemoval(
2610 Q->dropSymbol(Name);
2616 if (!IPLS->LookupSet.empty()) {
2619 IPLS->LookupSet.getSymbolNames());
2623 QueryComplete = Q->isComplete();
2626 dbgs() <<
"Query successfully "
2627 << (QueryComplete ?
"completed" :
"lodged") <<
"\n";
2631 if (!CollectedUMIs.empty()) {
2632 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2635 for (
auto &KV : CollectedUMIs) {
2637 auto &JD = *KV.first;
2638 dbgs() <<
" For " << JD.getName() <<
": Adding " << KV.second.size()
2641 for (
auto &UMI : KV.second) {
2642 auto MR = createMaterializationResponsibility(
2643 *UMI->RT, std::move(UMI->MU->SymbolFlags),
2644 std::move(UMI->MU->InitSymbol));
2645 OutstandingMUs.push_back(
2646 std::make_pair(std::move(UMI->MU), std::move(MR)));
2652 if (RegisterDependencies && !Q->QueryRegistrations.empty()) {
2654 RegisterDependencies(Q->QueryRegistrations);
2664 Q->handleFailed(std::move(LodgingErr));
2668 if (QueryComplete) {
2670 Q->handleComplete(*
this);
2673 dispatchOutstandingMUs();
2676void ExecutionSession::OL_completeLookupFlags(
2677 std::unique_ptr<InProgressLookupState> IPLS,
2678 unique_function<
void(Expected<SymbolFlagsMap>)> OnComplete) {
2682 dbgs() <<
"Entering OL_completeLookupFlags:\n"
2683 <<
" Lookup kind: " << IPLS->K <<
"\n"
2684 <<
" Search order: " << IPLS->SearchOrder
2685 <<
", Current index = " << IPLS->CurSearchOrderIndex
2686 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2687 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2688 <<
" Definition generator candidates: "
2689 << IPLS->DefGeneratorCandidates <<
"\n"
2690 <<
" Definition generator non-candidates: "
2691 << IPLS->DefGeneratorNonCandidates <<
"\n";
2697 for (
auto &KV : IPLS->SearchOrder) {
2698 auto &JD = *KV.first;
2699 auto JDLookupFlags = KV.second;
2701 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2702 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2705 IPLS->LookupSet.forEachWithRemoval([&](
const SymbolStringPtr &Name,
2708 dbgs() <<
" Attempting to match \"" <<
Name <<
"\" ("
2709 << SymLookupFlags <<
")... ";
2714 auto SymI = JD.Symbols.find(Name);
2715 if (SymI == JD.Symbols.end()) {
2721 if (!SymI->second.getFlags().isExported() &&
2728 dbgs() <<
"matched, \"" <<
Name <<
"\" -> " << SymI->second.getFlags()
2742 if (!IPLS->LookupSet.empty()) {
2745 IPLS->LookupSet.getSymbolNames());
2754 OnComplete(std::move(
Result));
2757void ExecutionSession::OL_destroyMaterializationResponsibility(
2760 assert(MR.SymbolFlags.empty() &&
2761 "All symbols should have been explicitly materialized or failed");
2762 MR.JD.unlinkMaterializationResponsibility(MR);
2767 return MR.JD.getRequestedSymbols(MR.SymbolFlags);
2773 dbgs() <<
"In " << MR.JD.getName() <<
" resolving " <<
Symbols <<
"\n";
2776 for (
auto &KV : Symbols) {
2777 auto I = MR.SymbolFlags.find(KV.first);
2778 assert(
I != MR.SymbolFlags.end() &&
2779 "Resolving symbol outside this responsibility set");
2780 assert(!
I->second.hasMaterializationSideEffectsOnly() &&
2781 "Can't resolve materialization-side-effects-only symbol");
2784 assert((KV.second.getFlags() & WeakOrCommon) &&
2785 "Common symbols must be resolved as common or weak");
2786 assert((KV.second.getFlags() & ~WeakOrCommon) ==
2788 "Resolving symbol with incorrect flags");
2790 assert(KV.second.getFlags() ==
I->second &&
2791 "Resolving symbol with incorrect flags");
2795 return MR.JD.resolve(MR, Symbols);
2799ExecutionSession::IL_getSymbolState(
JITDylib *JD,
2801 if (JD->State != JITDylib::Open)
2802 return WaitingOnGraph::ExternalState::Failed;
2804 auto I = JD->Symbols.find_as(Name);
2807 if (
I == JD->Symbols.end())
2808 return WaitingOnGraph::ExternalState::Failed;
2810 if (
I->second.getFlags().hasError())
2811 return WaitingOnGraph::ExternalState::Failed;
2814 return WaitingOnGraph::ExternalState::Ready;
2816 return WaitingOnGraph::ExternalState::None;
2819template <
typename UpdateSymbolFn,
typename UpdateQueryFn>
2820void ExecutionSession::IL_collectQueries(
2821 JITDylib::AsynchronousSymbolQuerySet &Qs,
2822 WaitingOnGraph::ContainerElementsMap &QualifiedSymbols,
2823 UpdateSymbolFn &&UpdateSymbol, UpdateQueryFn &&UpdateQuery) {
2825 for (
auto &[JD, Symbols] : QualifiedSymbols) {
2830 assert(JD->State == JITDylib::Open &&
2831 "WaitingOnGraph includes definition in defunct JITDylib");
2832 for (
auto &Symbol : Symbols) {
2834 auto I = JD->Symbols.find_as(Symbol);
2835 assert(
I != JD->Symbols.end() &&
2836 "Failed Symbol missing from JD symbol table");
2838 UpdateSymbol(Entry);
2841 auto J = JD->MaterializingInfos.find_as(Symbol);
2842 if (J != JD->MaterializingInfos.end()) {
2843 for (
auto &Q : J->second.takeAllPendingQueries()) {
2844 UpdateQuery(*Q, *JD, Symbol, Entry);
2845 Qs.insert(std::move(Q));
2847 JD->MaterializingInfos.erase(J);
2853Expected<ExecutionSession::EmitQueries>
2855 WaitingOnGraph::SimplifyResult SR) {
2857 if (MR.RT->isDefunct())
2860 auto &TargetJD = MR.getTargetJITDylib();
2861 if (TargetJD.State != JITDylib::Open)
2866#ifdef EXPENSIVE_CHECKS
2867 verifySessionState(
"entering ExecutionSession::IL_emit");
2870 auto ER = G.emit(std::move(SR),
2871 [
this](
JITDylib *JD, NonOwningSymbolStringPtr Name) {
2872 return IL_getSymbolState(JD, Name);
2878 for (
auto &SN : ER.Failed)
2880 EQ.Failed, SN->defs(),
2881 [](JITDylib::SymbolTableEntry &
E) {
2882 E.setFlags(E.getFlags() = JITSymbolFlags::HasError);
2884 [&](AsynchronousSymbolQuery &Q,
JITDylib &JD,
2885 NonOwningSymbolStringPtr Name, JITDylib::SymbolTableEntry &
E) {
2886 auto &FS = EQ.FailedSymsForQuery[&Q];
2888 FS = std::make_shared<SymbolDependenceMap>();
2889 (*FS)[&JD].insert(SymbolStringPtr(Name));
2892 for (
auto &FQ :
EQ.Failed)
2895 for (
auto &SN : ER.Ready)
2897 EQ.Completed, SN->defs(),
2898 [](JITDylib::SymbolTableEntry &
E) { E.setState(SymbolState::Ready); },
2899 [](AsynchronousSymbolQuery &Q,
JITDylib &JD,
2900 NonOwningSymbolStringPtr Name, JITDylib::SymbolTableEntry &
E) {
2901 Q.notifySymbolMetRequiredState(SymbolStringPtr(Name), E.getSymbol());
2906 for (
auto it =
EQ.Completed.begin(), end =
EQ.Completed.end(); it != end;) {
2907 if ((*it)->isComplete()) {
2910 it =
EQ.Completed.erase(it);
2914#ifdef EXPENSIVE_CHECKS
2915 verifySessionState(
"exiting ExecutionSession::IL_emit");
2918 return std::move(
EQ);
2921Error ExecutionSession::OL_notifyEmitted(
2925 dbgs() <<
"In " << MR.JD.getName() <<
" emitting " << MR.SymbolFlags
2927 if (!DepGroups.empty()) {
2928 dbgs() <<
" Initial dependencies:\n";
2929 for (
auto &SDG : DepGroups) {
2930 dbgs() <<
" Symbols: " << SDG.Symbols
2931 <<
", Dependencies: " << SDG.Dependencies <<
"\n";
2938 for (
auto &DG : DepGroups) {
2939 for (
auto &Sym : DG.Symbols) {
2940 assert(MR.SymbolFlags.count(Sym) &&
2941 "DG contains dependence for symbol outside this MR");
2942 assert(Visited.insert(Sym).second &&
2943 "DG contains duplicate entries for Name");
2948 std::vector<std::unique_ptr<WaitingOnGraph::SuperNode>> SNs;
2949 WaitingOnGraph::ContainerElementsMap Residual;
2951 auto &JDResidual = Residual[&MR.getTargetJITDylib()];
2952 for (
auto &[Name, Flags] : MR.getSymbols())
2953 JDResidual.insert(NonOwningSymbolStringPtr(Name));
2955 for (
auto &SDG : DepGroups) {
2956 WaitingOnGraph::ContainerElementsMap Defs;
2957 assert(!SDG.Symbols.empty());
2958 auto &JDDefs = Defs[&MR.getTargetJITDylib()];
2959 for (
auto &Def : SDG.Symbols) {
2960 JDDefs.insert(NonOwningSymbolStringPtr(Def));
2961 JDResidual.erase(NonOwningSymbolStringPtr(Def));
2963 WaitingOnGraph::ContainerElementsMap Deps;
2964 if (!SDG.Dependencies.empty()) {
2965 for (
auto &[JD, Syms] : SDG.Dependencies) {
2966 auto &JDDeps = Deps[JD];
2967 for (
auto &Dep : Syms)
2968 JDDeps.insert(NonOwningSymbolStringPtr(Dep));
2971 SNs.push_back(std::make_unique<WaitingOnGraph::SuperNode>(
2972 std::move(Defs), std::move(Deps)));
2974 if (!JDResidual.empty())
2975 SNs.push_back(std::make_unique<WaitingOnGraph::SuperNode>(
2976 std::move(Residual), WaitingOnGraph::ContainerElementsMap()));
2982 dbgs() <<
" Simplified dependencies:\n";
2983 for (
auto &SN : SR.superNodes()) {
2985 auto SortedLibs = [](WaitingOnGraph::ContainerElementsMap &
C) {
2986 std::vector<JITDylib *> JDs;
2987 for (
auto &[JD,
_] :
C)
2990 return LHS->getName() <
RHS->getName();
2995 auto SortedNames = [](WaitingOnGraph::ElementSet &Elems) {
2996 std::vector<NonOwningSymbolStringPtr> Names(Elems.begin(), Elems.end());
2998 const NonOwningSymbolStringPtr &
RHS) {
3004 dbgs() <<
" Defs: {";
3005 for (
auto *JD : SortedLibs(SN->defs())) {
3006 dbgs() <<
" (" << JD->getName() <<
", [";
3007 for (
auto &Sym : SortedNames(SN->defs()[JD]))
3008 dbgs() <<
" " << Sym;
3011 dbgs() <<
" }, Deps: {";
3012 for (
auto *JD : SortedLibs(SN->deps())) {
3013 dbgs() <<
" (" << JD->getName() <<
", [";
3014 for (
auto &Sym : SortedNames(SN->deps()[JD]))
3015 dbgs() <<
" " << Sym;
3026 return EmitQueries.takeError();
3034 for (
auto &FQ : EmitQueries->Failed) {
3036 assert(EmitQueries->FailedSymsForQuery.count(FQ.get()) &&
3037 "Missing failed symbols for query");
3038 auto FailedSyms = std::move(EmitQueries->FailedSymsForQuery[FQ.get()]);
3039 for (
auto &[JD, Syms] : *FailedSyms) {
3040 auto &BadDepsForJD = BadDeps[JD];
3041 for (
auto &Sym : Syms)
3042 BadDepsForJD.insert(Sym);
3045 std::move(FailedSyms)));
3049 for (
auto &UQ : EmitQueries->Completed)
3050 UQ->handleComplete(*
this);
3053 if (!BadDeps.empty()) {
3059 for (
auto &[Name, Flags] : MR.getSymbols())
3061 MR.SymbolFlags.clear();
3064 std::move(BadDeps),
"dependencies removed or in error state");
3067 MR.SymbolFlags.
clear();
3071Error ExecutionSession::OL_defineMaterializing(
3075 dbgs() <<
"In " << MR.JD.getName() <<
" defining materializing symbols "
3076 << NewSymbolFlags <<
"\n";
3078 if (
auto AcceptedDefs =
3079 MR.JD.defineMaterializing(MR, std::move(NewSymbolFlags))) {
3081 for (
auto &KV : *AcceptedDefs)
3082 MR.SymbolFlags.insert(KV);
3085 return AcceptedDefs.takeError();
3088std::pair<JITDylib::AsynchronousSymbolQuerySet,
3089 std::shared_ptr<SymbolDependenceMap>>
3090ExecutionSession::IL_failSymbols(
JITDylib &JD,
3093#ifdef EXPENSIVE_CHECKS
3094 verifySessionState(
"entering ExecutionSession::IL_failSymbols");
3098 if (SymbolsToFail.empty())
3101 JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3102 auto Fail = [&](
JITDylib *FailJD, NonOwningSymbolStringPtr FailSym) {
3103 auto I = FailJD->Symbols.find_as(FailSym);
3104 assert(
I != FailJD->Symbols.end());
3106 auto J = FailJD->MaterializingInfos.find_as(FailSym);
3107 if (J != FailJD->MaterializingInfos.end()) {
3108 for (
auto &Q : J->second.takeAllPendingQueries())
3109 FailedQueries.insert(std::move(Q));
3110 FailJD->MaterializingInfos.erase(J);
3114 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
3117 auto &FailedSymsForJD = (*FailedSymbolsMap)[&JD];
3118 for (
auto &Sym : SymbolsToFail) {
3119 FailedSymsForJD.insert(Sym);
3120 Fail(&JD, NonOwningSymbolStringPtr(Sym));
3124 WaitingOnGraph::ContainerElementsMap ToFail;
3125 auto &JDToFail = ToFail[&JD];
3126 for (
auto &Sym : SymbolsToFail)
3127 JDToFail.insert(NonOwningSymbolStringPtr(Sym));
3129 auto FailedSNs = G.fail(ToFail, GOpRecorder);
3131 for (
auto &SN : FailedSNs) {
3132 for (
auto &[FailJD, Defs] : SN->defs()) {
3133 auto &FailedSymsForFailJD = (*FailedSymbolsMap)[FailJD];
3134 for (
auto &Def : Defs) {
3135 FailedSymsForFailJD.insert(SymbolStringPtr(Def));
3142 for (
auto &Q : FailedQueries)
3145#ifdef EXPENSIVE_CHECKS
3146 verifySessionState(
"exiting ExecutionSession::IL_failSymbols");
3149 return std::make_pair(std::move(FailedQueries), std::move(FailedSymbolsMap));
3155 dbgs() <<
"In " << MR.JD.getName() <<
" failing materialization for "
3156 << MR.SymbolFlags <<
"\n";
3159 if (MR.SymbolFlags.empty())
3163 for (
auto &[Name, Flags] : MR.SymbolFlags)
3164 SymbolsToFail.push_back(Name);
3165 MR.SymbolFlags.clear();
3167 JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3168 std::shared_ptr<SymbolDependenceMap> FailedSymbols;
3172 if (MR.RT->isDefunct())
3173 return std::pair<JITDylib::AsynchronousSymbolQuerySet,
3174 std::shared_ptr<SymbolDependenceMap>>();
3175 return IL_failSymbols(MR.getTargetJITDylib(), SymbolsToFail);
3178 for (
auto &Q : FailedQueries) {
3186 std::unique_ptr<MaterializationUnit> MU) {
3187 for (
auto &KV : MU->getSymbols()) {
3188 assert(MR.SymbolFlags.count(KV.first) &&
3189 "Replacing definition outside this responsibility set");
3190 MR.SymbolFlags.erase(KV.first);
3193 if (MU->getInitializerSymbol() == MR.InitSymbol)
3194 MR.InitSymbol =
nullptr;
3196 LLVM_DEBUG(MR.JD.getExecutionSession().runSessionLocked([&]() {
3197 dbgs() <<
"In " << MR.JD.getName() <<
" replacing symbols with " << *MU
3201 return MR.JD.replace(MR, std::move(MU));
3204Expected<std::unique_ptr<MaterializationResponsibility>>
3208 SymbolStringPtr DelegatedInitSymbol;
3211 for (
auto &Name : Symbols) {
3212 auto I = MR.SymbolFlags.find(Name);
3213 assert(
I != MR.SymbolFlags.end() &&
3214 "Symbol is not tracked by this MaterializationResponsibility "
3217 DelegatedFlags[
Name] = std::move(
I->second);
3218 if (Name == MR.InitSymbol)
3219 std::swap(MR.InitSymbol, DelegatedInitSymbol);
3221 MR.SymbolFlags.erase(
I);
3224 return MR.JD.delegate(MR, std::move(DelegatedFlags),
3225 std::move(DelegatedInitSymbol));
3229void ExecutionSession::dumpDispatchInfo(
Task &
T) {
3231 dbgs() <<
"Dispatching: ";
3232 T.printDescription(
dbgs());
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
aarch64 falkor hwpf fix Falkor HW Prefetch Fix Late Phase
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static StringRef getName(Value *V)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
const T & front() const
Get the first element.
bool empty() const
Check if the array is empty.
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
bool remove_if(Predicate Pred)
Remove entries that match the given predicate.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Implements a dense probed hash-table based set.
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.
reference get()
Returns a reference to the stored T value.
bool hasMaterializationSideEffectsOnly() const
Returns true if this symbol is a materialization-side-effects-only symbol.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
std::pair< iterator, bool > insert(const ValueT &V)
void insert_range(Range &&R)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
void reserve(size_t Size)
Grow the DenseSet so that it can contain at least NumEntries items before resizing again.
const std::string & getName() const
Get the name for this JITLinkDylib.
A symbol query that returns results via a callback when results are ready.
LLVM_ABI AsynchronousSymbolQuery(const SymbolLookupSet &Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete)
Create a query for the given symbols.
LLVM_ABI 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.
LLVM_ABI void runJITDispatchHandler(SendResultFunction SendResult, ExecutorAddr HandlerFnTagAddr, shared::WrapperFunctionBuffer ArgBytes)
Run a registered jit-side wrapper function.
LLVM_ABI Error endSession()
End the session.
void reportError(Error Err)
Report a error for this execution session.
LLVM_ABI 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.
LLVM_ABI JITDylib * getJITDylibByName(StringRef Name)
Return a pointer to the "name" JITDylib.
LLVM_ABI JITDylib & createBareJITDylib(std::string Name)
Add a new bare JITDylib to this ExecutionSession.
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
LLVM_ABI void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete, RegisterDependenciesFunction RegisterDependencies)
Search the given JITDylibs for the given symbols.
LLVM_ABI Error registerJITDispatchHandlers(JITDylib &JD, JITDispatchHandlerAssociationMap WFs)
For each tag symbol name, associate the corresponding AsyncHandlerWrapperFunction with the address of...
LLVM_ABI void registerResourceManager(ResourceManager &RM)
Register the given ResourceManager with this ExecutionSession.
LLVM_ABI ~ExecutionSession()
Destroy an ExecutionSession.
LLVM_ABI void deregisterResourceManager(ResourceManager &RM)
Deregister the given ResourceManager with this ExecutionSession.
LLVM_ABI 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.
LLVM_ABI void dump(raw_ostream &OS)
Dump the state of all the JITDylibs in this session.
unique_function< void(shared::WrapperFunctionBuffer)> SendResultFunction
Send a result to the remote.
LLVM_ABI Error removeJITDylibs(std::vector< JITDylibSP > JDsToRemove)
Removes the given JITDylibs from the ExecutionSession.
LLVM_ABI Expected< JITDylib & > createJITDylib(std::string Name)
Add a new JITDylib to this ExecutionSession.
void dispatchTask(std::unique_ptr< Task > T)
Materialize the given unit.
DenseMap< SymbolStringPtr, JITDispatchHandlerFunction > JITDispatchHandlerAssociationMap
A map associating tag names with asynchronous wrapper function implementations in the JIT.
Represents an address in the executor process.
Represents a defining location for a JIT symbol.
const JITSymbolFlags & getFlags() const
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.
~FailedToMaterialize() override
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::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.
Represents a JIT'd dynamic library.
LLVM_ABI Error remove(const SymbolNameSet &Names)
Tries to remove the given symbols.
LLVM_ABI Error clear()
Calls remove on all trackers currently associated with this JITDylib.
LLVM_ABI void dump(raw_ostream &OS)
Dump current JITDylib state to OS.
LLVM_ABI void replaceInLinkOrder(JITDylib &OldJD, JITDylib &NewJD, JITDylibLookupFlags JDLookupFlags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Replace OldJD with NewJD in the link order if OldJD is present.
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.
LLVM_ABI void addToLinkOrder(const JITDylibSearchOrder &NewLinks)
Append the given JITDylibSearchOrder to the link order for this JITDylib (discarding any elements alr...
LLVM_ABI ResourceTrackerSP createResourceTracker()
Create a resource tracker for this JITDylib.
LLVM_ABI void removeFromLinkOrder(JITDylib &JD)
Remove the given JITDylib from the link order for this JITDylib if it is present.
LLVM_ABI void setLinkOrder(JITDylibSearchOrder NewSearchOrder, bool LinkAgainstThisJITDylibFirst=true)
Set the link order to be used when fixing up definitions in JITDylib.
LLVM_ABI Expected< std::vector< JITDylibSP > > getReverseDFSLinkOrder()
Rteurn this JITDylib and its transitive dependencies in reverse DFS order based on linkage relationsh...
LLVM_ABI ResourceTrackerSP getDefaultResourceTracker()
Get the default resource tracker for this JITDylib.
JITDylib(const JITDylib &)=delete
LLVM_ABI void removeGenerator(DefinitionGenerator &G)
Remove a definition generator from this JITDylib.
LLVM_ABI 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.
LLVM_ABI void continueLookup(Error Err)
Continue the lookup.
LLVM_ABI LookupState & operator=(LookupState &&)
void printDescription(raw_ostream &OS) override
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
void printDescription(raw_ostream &OS) override
~MaterializationTask() override
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
MaterializationUnit(Interface I)
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.
LLVM_ABI void transferTo(ResourceTracker &DstRT)
Transfer all resources associated with this key to the given tracker, which must target the same JITD...
LLVM_ABI ~ResourceTracker()
ResourceTracker(const ResourceTracker &)=delete
LLVM_ABI 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, ValT > &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.
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.
UnsatisfiedSymbolDependencies(std::shared_ptr< SymbolStringPool > SSP, JITDylibSP JD, SymbolNameSet FailedSymbols, SymbolDependenceMap BadDeps, std::string Explanation)
static SimplifyResult simplify(std::vector< std::unique_ptr< SuperNode > > SNs, OpRecorder *Rec=nullptr)
C++ wrapper function buffer: Same as CWrapperFunctionBuffer but auto-releases memory.
size_t size() const
Returns the size of the data contained in this instance.
static WrapperFunctionBuffer createOutOfBandError(const char *Msg)
Create an out-of-band error by copying the given string.
char * data()
Get a pointer to the data contained in this instance.
A raw_ostream that writes to a file descriptor.
This class implements an extremely fast bulk output stream that can only output to a stream.
unique_function is a type-erasing functor similar to std::function.
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.
IntrusiveRefCntPtr< JITDylib > JITDylibSP
IntrusiveRefCntPtr< ResourceTracker > ResourceTrackerSP
@ MissingSymbolDefinitions
@ UnexpectedSymbolDefinitions
std::unique_ptr< ReExportsMaterializationUnit > symbolAliases(SymbolAliasMap Aliases)
Create a ReExportsMaterializationUnit with the given aliases.
std::unique_ptr< AbsoluteSymbolsMaterializationUnit > absoluteSymbols(SymbolMap Symbols)
Create an AbsoluteSymbolsMaterializationUnit with the given symbols.
std::function< void(const SymbolDependenceMap &)> RegisterDependenciesFunction
Callback to register the dependencies for a given query.
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...
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).
LookupKind
Describes the kind of lookup being performed.
LLVM_ABI 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.
DenseMap< JITDylib *, SymbolNameSet > SymbolDependenceMap
A map from JITDylibs to sets of symbols.
DenseSet< SymbolStringPtr > SymbolNameSet
A set of symbol names (represented by SymbolStringPtrs for.
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.
DenseMap< SymbolStringPtr, SymbolAliasMapEntry > SymbolAliasMap
A map of Symbols to (Symbol, Flags) pairs.
LLVM_ABI std::error_code orcError(OrcErrorCode ErrCode)
unique_function< void(Expected< SymbolMap >)> SymbolsResolvedCallback
Callback to notify client that symbols have been resolved.
LLVM_ABI 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 ...
DenseMap< SymbolStringPtr, JITSymbolFlags > SymbolFlagsMap
A map from symbol names (as SymbolStringPtrs) to JITSymbolFlags.
This is an optimization pass for GlobalISel generic memory operations.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
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.
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
auto reverse(ContainerTy &&C)
Error joinErrors(Error E1, Error E2)
Concatenate errors.
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI 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.
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
ArrayRef(const T &OneElt) -> ArrayRef< T >
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.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Implement std::hash so that hash_code can be used in STL containers.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.