12#include "llvm/Config/llvm-config.h"
20#include <condition_variable>
24#define DEBUG_TYPE "orc"
43void MaterializationUnit::anchor() {}
46 assert((
reinterpret_cast<uintptr_t
>(JD.get()) & 0x1) == 0 &&
47 "JITDylib must be two byte aligned");
49 JDAndFlag.store(
reinterpret_cast<uintptr_t
>(JD.get()));
65void ResourceTracker::makeDefunct() {
66 uintptr_t Val = JDAndFlag.load();
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
192 JD->getExecutionSession().lookup(
195 [OnComplete = std::move(OnComplete)
202 assert(
Result->size() == 1 &&
"Unexpected number of results");
204 "Result does not contain expected symbol");
205 OnComplete(
Result->begin()->second);
207 OnComplete(
Result.takeError());
215 : NotifyComplete(
std::
move(NotifyComplete)), RequiredState(RequiredState) {
217 "Cannot query for a symbols that have not reached the resolve state "
220 OutstandingSymbolsCount = Symbols.size();
222 for (
auto &[Name, Flags] : Symbols)
228 auto I = ResolvedSymbols.find(Name);
229 assert(
I != ResolvedSymbols.end() &&
230 "Resolving symbol outside the requested set");
232 "Redundantly resolving symbol Name");
237 ResolvedSymbols.erase(
I);
239 I->second = std::move(Sym);
240 --OutstandingSymbolsCount;
244 assert(OutstandingSymbolsCount == 0 &&
245 "Symbols remain, handleComplete called prematurely");
247 class RunQueryCompleteTask :
public Task {
249 RunQueryCompleteTask(
SymbolMap ResolvedSymbols,
251 : ResolvedSymbols(
std::
move(ResolvedSymbols)),
252 NotifyComplete(
std::
move(NotifyComplete)) {}
254 OS <<
"Execute query complete callback for " << ResolvedSymbols;
256 void run()
override { NotifyComplete(std::move(ResolvedSymbols)); }
263 auto T = std::make_unique<RunQueryCompleteTask>(std::move(ResolvedSymbols),
264 std::move(NotifyComplete));
269void AsynchronousSymbolQuery::handleFailed(
Error Err) {
270 assert(QueryRegistrations.empty() && ResolvedSymbols.empty() &&
271 OutstandingSymbolsCount == 0 &&
272 "Query should already have been abandoned");
273 NotifyComplete(std::move(Err));
277void AsynchronousSymbolQuery::addQueryDependence(
JITDylib &JD,
279 bool Added = QueryRegistrations[&JD].insert(std::move(Name)).second;
281 assert(Added &&
"Duplicate dependence notification?");
284void AsynchronousSymbolQuery::removeQueryDependence(
286 auto QRI = QueryRegistrations.find(&JD);
287 assert(QRI != QueryRegistrations.end() &&
288 "No dependencies registered for JD");
289 assert(QRI->second.count(Name) &&
"No dependency on Name in JD");
290 QRI->second.erase(Name);
291 if (QRI->second.empty())
292 QueryRegistrations.erase(QRI);
296 auto I = ResolvedSymbols.find(Name);
297 assert(
I != ResolvedSymbols.end() &&
298 "Redundant removal of weakly-referenced symbol");
299 ResolvedSymbols.erase(
I);
300 --OutstandingSymbolsCount;
303void AsynchronousSymbolQuery::detach() {
304 ResolvedSymbols.clear();
305 OutstandingSymbolsCount = 0;
306 for (
auto &[JD, Syms] : QueryRegistrations)
307 JD->detachQueryHelper(*
this, Syms);
308 QueryRegistrations.clear();
315 SourceJDLookupFlags(SourceJDLookupFlags), Aliases(
std::
move(Aliases)) {}
318 return "<Reexports>";
321void ReExportsMaterializationUnit::materialize(
322 std::unique_ptr<MaterializationResponsibility> R) {
324 auto &ES = R->getTargetJITDylib().getExecutionSession();
325 JITDylib &TgtJD = R->getTargetJITDylib();
326 JITDylib &SrcJD = SourceJD ? *SourceJD : TgtJD;
331 auto RequestedSymbols = R->getRequestedSymbols();
334 for (
auto &Name : RequestedSymbols) {
335 auto I = Aliases.
find(Name);
336 assert(
I != Aliases.
end() &&
"Symbol not found in aliases map?");
337 RequestedAliases[Name] = std::move(
I->second);
343 dbgs() <<
"materializing reexports: target = " << TgtJD.
getName()
344 <<
", source = " << SrcJD.
getName() <<
" " << RequestedAliases
349 if (!Aliases.empty()) {
350 auto Err = SourceJD ?
R->replace(
reexports(*SourceJD, std::move(Aliases),
351 SourceJDLookupFlags))
358 R->failMaterialization();
365 struct OnResolveInfo {
366 OnResolveInfo(std::unique_ptr<MaterializationResponsibility> R,
367 SymbolAliasMap Aliases)
368 :
R(std::
move(
R)), Aliases(std::
move(Aliases)) {}
370 std::unique_ptr<MaterializationResponsibility>
R;
372 std::vector<SymbolDependenceGroup> SDGs;
383 std::vector<std::pair<SymbolLookupSet, std::shared_ptr<OnResolveInfo>>>
385 while (!RequestedAliases.
empty()) {
386 SymbolNameSet ResponsibilitySymbols;
387 SymbolLookupSet QuerySymbols;
388 SymbolAliasMap QueryAliases;
391 for (auto &[Alias, AliasInfo] : RequestedAliases) {
393 if (&SrcJD == &TgtJD && (QueryAliases.count(AliasInfo.Aliasee) ||
394 RequestedAliases.count(AliasInfo.Aliasee)))
397 ResponsibilitySymbols.insert(Alias);
398 QuerySymbols.add(AliasInfo.Aliasee,
399 AliasInfo.AliasFlags.hasMaterializationSideEffectsOnly()
400 ? SymbolLookupFlags::WeaklyReferencedSymbol
401 : SymbolLookupFlags::RequiredSymbol);
402 QueryAliases[Alias] = std::move(AliasInfo);
406 for (
auto &KV : QueryAliases)
407 RequestedAliases.
erase(KV.first);
409 assert(!QuerySymbols.empty() &&
"Alias cycle detected!");
411 auto NewR =
R->delegate(ResponsibilitySymbols);
414 R->failMaterialization();
418 auto QueryInfo = std::make_shared<OnResolveInfo>(std::move(*NewR),
419 std::move(QueryAliases));
420 QueryInfos.push_back(
421 make_pair(std::move(QuerySymbols), std::move(QueryInfo)));
425 while (!QueryInfos.empty()) {
426 auto QuerySymbols = std::move(QueryInfos.back().first);
427 auto QueryInfo = std::move(QueryInfos.back().second);
429 QueryInfos.pop_back();
431 auto RegisterDependencies = [QueryInfo,
438 assert(Deps.size() == 1 && Deps.count(&SrcJD) &&
439 "Unexpected dependencies for reexports");
441 auto &SrcJDDeps = Deps.find(&SrcJD)->second;
443 for (
auto &[Alias, AliasInfo] : QueryInfo->Aliases)
444 if (SrcJDDeps.count(AliasInfo.Aliasee))
445 QueryInfo->SDGs.push_back({{Alias}, {{&SrcJD, {AliasInfo.Aliasee}}}});
448 auto OnComplete = [QueryInfo](Expected<SymbolMap>
Result) {
449 auto &ES = QueryInfo->R->getTargetJITDylib().getExecutionSession();
452 for (
auto &KV : QueryInfo->Aliases) {
453 assert((KV.second.AliasFlags.hasMaterializationSideEffectsOnly() ||
454 Result->count(KV.second.Aliasee)) &&
455 "Result map missing entry?");
457 if (KV.second.AliasFlags.hasMaterializationSideEffectsOnly())
460 ResolutionMap[KV.first] = {(*Result)[KV.second.Aliasee].getAddress(),
461 KV.second.AliasFlags};
463 if (
auto Err = QueryInfo->R->notifyResolved(ResolutionMap)) {
465 QueryInfo->R->failMaterialization();
468 if (
auto Err = QueryInfo->R->notifyEmitted(QueryInfo->SDGs)) {
470 QueryInfo->R->failMaterialization();
475 QueryInfo->R->failMaterialization();
482 std::move(RegisterDependencies));
486void ReExportsMaterializationUnit::discard(
const JITDylib &JD,
487 const SymbolStringPtr &Name) {
488 assert(Aliases.count(Name) &&
489 "Symbol not covered by this MaterializationUnit");
493MaterializationUnit::Interface
494ReExportsMaterializationUnit::extractFlags(
const SymbolAliasMap &Aliases) {
496 for (
auto &KV : Aliases)
499 return MaterializationUnit::Interface(std::move(SymbolFlags),
nullptr);
510 return Flags.takeError();
513 for (
auto &Name : Symbols) {
514 assert(Flags->count(Name) &&
"Missing entry in flags map");
533 virtual void complete(std::unique_ptr<InProgressLookupState> IPLS) = 0;
550 } GenState = NotInGenerator;
561 OnComplete(
std::
move(OnComplete)) {}
563 void complete(std::unique_ptr<InProgressLookupState> IPLS)
override {
564 auto &ES =
SearchOrder.front().first->getExecutionSession();
565 ES.OL_completeLookupFlags(std::move(IPLS), std::move(OnComplete));
568 void fail(
Error Err)
override { OnComplete(std::move(Err)); }
579 std::shared_ptr<AsynchronousSymbolQuery> Q,
583 Q(
std::
move(Q)), RegisterDependencies(
std::
move(RegisterDependencies)) {
586 void complete(std::unique_ptr<InProgressLookupState> IPLS)
override {
587 auto &ES =
SearchOrder.front().first->getExecutionSession();
588 ES.OL_completeLookup(std::move(IPLS), std::move(Q),
589 std::move(RegisterDependencies));
594 Q->handleFailed(std::move(Err));
598 std::shared_ptr<AsynchronousSymbolQuery> Q;
605 : SourceJD(SourceJD), SourceJDLookupFlags(SourceJDLookupFlags),
612 assert(&JD != &SourceJD &&
"Cannot re-export from the same dylib");
616 K, {{&SourceJD, JDLookupFlags}}, LookupSet);
618 return Flags.takeError();
622 for (
auto &KV : *Flags)
623 if (!Allow || Allow(KV.first))
626 if (AliasMap.empty())
636void LookupState::reset(InProgressLookupState *IPLS) { this->IPLS.reset(IPLS); }
644 assert(IPLS &&
"Cannot call continueLookup on empty LookupState");
645 auto &ES = IPLS->SearchOrder.begin()->first->getExecutionSession();
646 ES.OL_applyQueryPhase1(std::move(IPLS), std::move(Err));
650 std::deque<LookupState> LookupsToFail;
652 std::lock_guard<std::mutex> Lock(M);
653 std::swap(PendingLookups, LookupsToFail);
657 for (
auto &LS : LookupsToFail)
659 "Query waiting on DefinitionGenerator that was destroyed",
668 std::vector<ResourceTrackerSP> TrackersToRemove;
669 ES.runSessionLocked([&]() {
670 assert(State != Closed &&
"JD is defunct");
671 for (
auto &KV : TrackerSymbols)
672 TrackersToRemove.push_back(KV.first);
677 for (
auto &RT : TrackersToRemove)
678 Err =
joinErrors(std::move(Err), RT->remove());
683 return ES.runSessionLocked([
this] {
684 assert(State != Closed &&
"JD is defunct");
687 return DefaultTracker;
692 return ES.runSessionLocked([
this] {
693 assert(State == Open &&
"JD is defunct");
702 std::shared_ptr<DefinitionGenerator> TmpDG;
704 ES.runSessionLocked([&] {
705 assert(State == Open &&
"JD is defunct");
707 [&](
const std::shared_ptr<DefinitionGenerator> &
H) {
708 return H.get() == &
G;
710 assert(
I != DefGenerators.end() &&
"Generator not found");
711 TmpDG = std::move(*
I);
712 DefGenerators.erase(
I);
721 if (FromMR.RT->isDefunct())
724 std::vector<NonOwningSymbolStringPtr> AddedSyms;
725 std::vector<NonOwningSymbolStringPtr> RejectedWeakDefs;
727 for (
auto &[Name, Flags] : SymbolFlags) {
728 auto EntryItr = Symbols.
find(Name);
731 if (EntryItr != Symbols.
end()) {
734 if (!Flags.isWeak()) {
736 for (
auto &S : AddedSyms)
741 std::string(*Name),
"defineMaterializing operation");
745 RejectedWeakDefs.push_back(NonOwningSymbolStringPtr(Name));
749 Symbols.
insert(std::make_pair(Name, SymbolTableEntry(Flags))).first;
751 AddedSyms.push_back(NonOwningSymbolStringPtr(Name));
756 while (!RejectedWeakDefs.empty()) {
758 RejectedWeakDefs.pop_back();
766 std::unique_ptr<MaterializationUnit> MU) {
767 assert(MU !=
nullptr &&
"Can not replace with a null MaterializationUnit");
768 std::unique_ptr<MaterializationUnit> MustRunMU;
769 std::unique_ptr<MaterializationResponsibility> MustRunMR;
772 ES.runSessionLocked([&,
this]() ->
Error {
773 if (FromMR.RT->isDefunct())
777 for (
auto &KV : MU->getSymbols()) {
778 auto SymI = Symbols.find(KV.first);
779 assert(SymI != Symbols.end() &&
"Replacing unknown symbol");
781 "Can not replace a symbol that ha is not materializing");
782 assert(!SymI->second.hasMaterializerAttached() &&
783 "Symbol should not have materializer attached already");
784 assert(UnmaterializedInfos.count(KV.first) == 0 &&
785 "Symbol being replaced should have no UnmaterializedInfo");
793 for (
auto &KV : MU->getSymbols()) {
794 auto MII = MaterializingInfos.find(KV.first);
795 if (MII != MaterializingInfos.end()) {
796 if (MII->second.hasQueriesPending()) {
797 MustRunMR = ES.createMaterializationResponsibility(
798 *FromMR.RT, std::move(MU->SymbolFlags),
799 std::move(MU->InitSymbol));
800 MustRunMU = std::move(MU);
807 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU),
809 for (
auto &KV : UMI->MU->getSymbols()) {
810 auto SymI = Symbols.find(KV.first);
812 "Can not replace a symbol that is not materializing");
813 assert(!SymI->second.hasMaterializerAttached() &&
814 "Can not replace a symbol that has a materializer attached");
815 assert(UnmaterializedInfos.count(KV.first) == 0 &&
816 "Unexpected materializer entry in map");
817 SymI->second.setAddress(SymI->second.getAddress());
818 SymI->second.setMaterializerAttached(
true);
820 auto &UMIEntry = UnmaterializedInfos[KV.first];
821 assert((!UMIEntry || !UMIEntry->MU) &&
822 "Replacing symbol with materializer still attached");
833 assert(MustRunMR &&
"MustRunMU set implies MustRunMR set");
834 ES.dispatchTask(std::make_unique<MaterializationTask>(
835 std::move(MustRunMU), std::move(MustRunMR)));
837 assert(!MustRunMR &&
"MustRunMU unset implies MustRunMR unset");
843Expected<std::unique_ptr<MaterializationResponsibility>>
847 return ES.runSessionLocked(
848 [&]() -> Expected<std::unique_ptr<MaterializationResponsibility>> {
849 if (FromMR.RT->isDefunct())
852 return ES.createMaterializationResponsibility(
853 *FromMR.RT, std::move(SymbolFlags), std::move(InitSymbol));
858JITDylib::getRequestedSymbols(
const SymbolFlagsMap &SymbolFlags)
const {
859 return ES.runSessionLocked([&]() {
862 for (
auto &KV : SymbolFlags) {
863 assert(Symbols.count(KV.first) &&
"JITDylib does not cover this symbol?");
864 assert(Symbols.find(KV.first)->second.getState() !=
867 "getRequestedSymbols can only be called for symbols that have "
868 "started materializing");
869 auto I = MaterializingInfos.find(KV.first);
870 if (
I == MaterializingInfos.end())
873 if (
I->second.hasQueriesPending())
874 RequestedSymbols.insert(KV.first);
877 return RequestedSymbols;
883 AsynchronousSymbolQuerySet CompletedQueries;
885 if (
auto Err = ES.runSessionLocked([&,
this]() ->
Error {
886 if (MR.RT->isDefunct())
887 return make_error<ResourceTrackerDefunct>(MR.RT);
890 return make_error<StringError>(
"JITDylib " + getName() +
892 inconvertibleErrorCode());
894 struct WorklistEntry {
895 SymbolTable::iterator SymI;
896 ExecutorSymbolDef ResolvedSym;
900 std::vector<WorklistEntry> Worklist;
906 assert(!KV.second.getFlags().hasError() &&
907 "Resolution result can not have error flag set");
909 auto SymI = Symbols.find(KV.first);
911 assert(SymI != Symbols.end() &&
"Symbol not found");
912 assert(!SymI->second.hasMaterializerAttached() &&
913 "Resolving symbol with materializer attached?");
915 "Symbol should be materializing");
916 assert(SymI->second.getAddress() == ExecutorAddr() &&
917 "Symbol has already been resolved");
919 if (SymI->second.getFlags().hasError())
920 SymbolsInErrorState.insert(KV.first);
923 [[maybe_unused]]
auto WeakOrCommon =
925 assert((KV.second.getFlags() & WeakOrCommon) &&
926 "Common symbols must be resolved as common or weak");
927 assert((KV.second.getFlags() & ~WeakOrCommon) ==
929 "Resolving symbol with incorrect flags");
932 assert(KV.second.getFlags() == SymI->second.getFlags() &&
933 "Resolved flags should match the declared flags");
936 {SymI, {KV.second.getAddress(), SymI->second.getFlags()}});
941 if (!SymbolsInErrorState.empty()) {
942 auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
943 (*FailedSymbolsDepMap)[this] = std::move(SymbolsInErrorState);
944 return make_error<FailedToMaterialize>(
945 getExecutionSession().getSymbolStringPool(),
946 std::move(FailedSymbolsDepMap));
949 while (!Worklist.empty()) {
950 auto SymI = Worklist.back().SymI;
951 auto ResolvedSym = Worklist.back().ResolvedSym;
954 auto &Name = SymI->first;
957 JITSymbolFlags ResolvedFlags = ResolvedSym.getFlags();
958 SymI->second.setAddress(ResolvedSym.getAddress());
959 SymI->second.setFlags(ResolvedFlags);
960 SymI->second.setState(SymbolState::Resolved);
962 auto MII = MaterializingInfos.find(Name);
963 if (MII == MaterializingInfos.end())
966 auto &MI = MII->second;
967 for (auto &Q : MI.takeQueriesMeeting(SymbolState::Resolved)) {
968 Q->notifySymbolMetRequiredState(Name, ResolvedSym);
970 CompletedQueries.insert(std::move(Q));
979 for (
auto &Q : CompletedQueries) {
980 assert(Q->isComplete() &&
"Q not completed");
981 Q->handleComplete(ES);
987void JITDylib::unlinkMaterializationResponsibility(
988 MaterializationResponsibility &MR) {
990 auto I = TrackerMRs.find(MR.RT.get());
991 assert(
I != TrackerMRs.end() &&
"No MRs in TrackerMRs list for RT");
992 assert(
I->second.count(&MR) &&
"MR not in TrackerMRs list for RT");
993 I->second.erase(&MR);
994 if (
I->second.empty())
995 TrackerMRs.erase(MR.RT.get());
999void JITDylib::shrinkMaterializationInfoMemory() {
1003 if (UnmaterializedInfos.empty())
1004 UnmaterializedInfos.clear();
1006 if (MaterializingInfos.empty())
1007 MaterializingInfos.clear();
1011 bool LinkAgainstThisJITDylibFirst) {
1012 ES.runSessionLocked([&]() {
1013 assert(State == Open &&
"JD is defunct");
1014 if (LinkAgainstThisJITDylibFirst) {
1016 if (NewLinkOrder.empty() || NewLinkOrder.front().first !=
this)
1017 LinkOrder.push_back(
1021 LinkOrder = std::move(NewLinkOrder);
1026 ES.runSessionLocked([&]() {
1027 for (
auto &KV : NewLinks) {
1032 LinkOrder.push_back(std::move(KV));
1038 ES.runSessionLocked([&]() { LinkOrder.push_back({&JD, JDLookupFlags}); });
1043 ES.runSessionLocked([&]() {
1044 assert(State == Open &&
"JD is defunct");
1045 for (
auto &KV : LinkOrder)
1046 if (KV.first == &OldJD) {
1047 KV = {&NewJD, JDLookupFlags};
1054 ES.runSessionLocked([&]() {
1055 assert(State == Open &&
"JD is defunct");
1057 [&](
const JITDylibSearchOrder::value_type &KV) {
1058 return KV.first == &JD;
1060 if (
I != LinkOrder.end())
1066 return ES.runSessionLocked([&]() ->
Error {
1067 assert(State == Open &&
"JD is defunct");
1072 for (
auto &Name : Names) {
1073 auto I = Symbols.find(Name);
1076 if (
I == Symbols.end()) {
1077 Missing.insert(Name);
1092 if (!Missing.empty())
1094 std::move(Missing));
1106 auto UMII = UnmaterializedInfos.find(Name);
1107 if (UMII != UnmaterializedInfos.end()) {
1108 UMII->second->MU->doDiscard(*
this, UMII->first);
1109 UnmaterializedInfos.erase(UMII);
1112 Symbols.erase(Name);
1115 shrinkMaterializationInfoMemory();
1122 ES.runSessionLocked([&,
this]() {
1123 OS <<
"JITDylib \"" <<
getName() <<
"\" (ES: "
1124 <<
format(
"0x%016" PRIx64,
reinterpret_cast<uintptr_t
>(&ES))
1138 if (State == Closed)
1140 OS <<
"Link order: " << LinkOrder <<
"\n"
1141 <<
"Symbol table:\n";
1144 std::vector<std::pair<SymbolStringPtr, SymbolTableEntry *>> SymbolsSorted;
1145 for (
auto &KV : Symbols)
1146 SymbolsSorted.emplace_back(KV.first, &KV.second);
1147 std::sort(SymbolsSorted.begin(), SymbolsSorted.end(),
1148 [](
const auto &L,
const auto &R) { return *L.first < *R.first; });
1150 for (
auto &KV : SymbolsSorted) {
1151 OS <<
" \"" << *KV.first <<
"\": ";
1152 if (
auto Addr = KV.second->getAddress())
1155 OS <<
"<not resolved> ";
1157 OS <<
" " << KV.second->getFlags() <<
" " << KV.second->getState();
1159 if (KV.second->hasMaterializerAttached()) {
1160 OS <<
" (Materializer ";
1161 auto I = UnmaterializedInfos.find(KV.first);
1162 assert(
I != UnmaterializedInfos.end() &&
1163 "Lazy symbol should have UnmaterializedInfo");
1164 OS <<
I->second->MU.get() <<
", " <<
I->second->MU->getName() <<
")\n";
1169 if (!MaterializingInfos.empty())
1170 OS <<
" MaterializingInfos entries:\n";
1171 for (
auto &KV : MaterializingInfos) {
1172 OS <<
" \"" << *KV.first <<
"\":\n"
1173 <<
" " << KV.second.pendingQueries().size()
1174 <<
" pending queries: { ";
1175 for (
const auto &Q : KV.second.pendingQueries())
1176 OS << Q.get() <<
" (" << Q->getRequiredState() <<
") ";
1182void JITDylib::MaterializingInfo::addQuery(
1183 std::shared_ptr<AsynchronousSymbolQuery> Q) {
1187 [](
const std::shared_ptr<AsynchronousSymbolQuery> &V,
SymbolState S) {
1188 return V->getRequiredState() <= S;
1190 PendingQueries.insert(
I.base(), std::move(Q));
1193void JITDylib::MaterializingInfo::removeQuery(
1194 const AsynchronousSymbolQuery &Q) {
1197 PendingQueries, [&Q](
const std::shared_ptr<AsynchronousSymbolQuery> &V) {
1198 return V.get() == &Q;
1200 if (
I != PendingQueries.end())
1201 PendingQueries.erase(
I);
1204JITDylib::AsynchronousSymbolQueryList
1205JITDylib::MaterializingInfo::takeQueriesMeeting(SymbolState RequiredState) {
1206 AsynchronousSymbolQueryList
Result;
1207 while (!PendingQueries.empty()) {
1208 if (PendingQueries.back()->getRequiredState() > RequiredState)
1211 Result.push_back(std::move(PendingQueries.back()));
1212 PendingQueries.pop_back();
1218JITDylib::JITDylib(ExecutionSession &ES, std::string Name)
1219 : JITLinkDylib(std::
move(
Name)), ES(ES) {
1223JITDylib::RemoveTrackerResult JITDylib::IL_removeTracker(
ResourceTracker &RT) {
1225 assert(State != Closed &&
"JD is defunct");
1230 if (&RT == DefaultTracker.get()) {
1232 for (
auto &KV : TrackerSymbols)
1235 for (
auto &KV : Symbols) {
1236 auto &Sym = KV.first;
1237 if (!TrackedSymbols.count(Sym))
1238 SymbolsToRemove.push_back(Sym);
1241 DefaultTracker.reset();
1244 auto I = TrackerSymbols.find(&RT);
1245 if (
I != TrackerSymbols.end()) {
1246 SymbolsToRemove = std::move(
I->second);
1247 TrackerSymbols.erase(
I);
1252 for (
auto &Sym : SymbolsToRemove) {
1253 assert(Symbols.count(Sym) &&
"Symbol not in symbol table");
1256 auto MII = MaterializingInfos.find(Sym);
1257 if (MII != MaterializingInfos.end())
1258 SymbolsToFail.push_back(Sym);
1261 auto [QueriesToFail, FailedSymbols] =
1262 ES.IL_failSymbols(*
this, std::move(SymbolsToFail));
1264 std::vector<std::unique_ptr<MaterializationUnit>> DefunctMUs;
1267 for (
auto &Sym : SymbolsToRemove) {
1268 auto I = Symbols.find(Sym);
1269 assert(
I != Symbols.end() &&
"Symbol not present in table");
1272 if (
I->second.hasMaterializerAttached()) {
1274 auto J = UnmaterializedInfos.find(Sym);
1275 assert(J != UnmaterializedInfos.end() &&
1276 "Symbol table indicates MU present, but no UMI record");
1278 DefunctMUs.push_back(std::move(J->second->MU));
1279 UnmaterializedInfos.erase(J);
1281 assert(!UnmaterializedInfos.count(Sym) &&
1282 "Symbol has materializer attached");
1288 shrinkMaterializationInfoMemory();
1290 return {std::move(QueriesToFail), std::move(FailedSymbols),
1291 std::move(DefunctMUs)};
1295 assert(State != Closed &&
"JD is defunct");
1296 assert(&DstRT != &SrcRT &&
"No-op transfers shouldn't call transferTracker");
1297 assert(&DstRT.getJITDylib() ==
this &&
"DstRT is not for this JITDylib");
1298 assert(&SrcRT.getJITDylib() ==
this &&
"SrcRT is not for this JITDylib");
1301 for (
auto &KV : UnmaterializedInfos) {
1302 if (KV.second->RT == &SrcRT)
1303 KV.second->RT = &DstRT;
1308 auto I = TrackerMRs.find(&SrcRT);
1309 if (
I != TrackerMRs.end()) {
1310 auto &SrcMRs =
I->second;
1311 auto &DstMRs = TrackerMRs[&DstRT];
1312 for (
auto *MR : SrcMRs)
1315 DstMRs = std::move(SrcMRs);
1317 DstMRs.insert_range(SrcMRs);
1320 TrackerMRs.erase(&SrcRT);
1326 if (&DstRT == DefaultTracker.get()) {
1327 TrackerSymbols.erase(&SrcRT);
1333 if (&SrcRT == DefaultTracker.get()) {
1334 assert(!TrackerSymbols.count(&SrcRT) &&
1335 "Default tracker should not appear in TrackerSymbols");
1340 for (
auto &KV : TrackerSymbols)
1343 for (
auto &KV : Symbols) {
1344 auto &Sym = KV.first;
1345 if (!CurrentlyTrackedSymbols.count(Sym))
1346 SymbolsToTrack.push_back(Sym);
1349 TrackerSymbols[&DstRT] = std::move(SymbolsToTrack);
1353 auto &DstTrackedSymbols = TrackerSymbols[&DstRT];
1357 auto SI = TrackerSymbols.find(&SrcRT);
1358 if (SI == TrackerSymbols.end())
1361 DstTrackedSymbols.reserve(DstTrackedSymbols.size() +
SI->second.size());
1362 for (
auto &Sym :
SI->second)
1363 DstTrackedSymbols.push_back(std::move(Sym));
1364 TrackerSymbols.erase(SI);
1371 std::vector<SymbolStringPtr> ExistingDefsOverridden;
1372 std::vector<SymbolStringPtr> MUDefsOverridden;
1374 for (
const auto &KV : MU.getSymbols()) {
1375 auto I = Symbols.find(KV.first);
1377 if (
I != Symbols.end()) {
1378 if (KV.second.isStrong()) {
1379 if (
I->second.getFlags().isStrong() ||
1381 Duplicates.insert(KV.first);
1384 "Overridden existing def should be in the never-searched "
1386 ExistingDefsOverridden.push_back(KV.first);
1389 MUDefsOverridden.push_back(KV.first);
1394 if (!Duplicates.empty()) {
1396 {
dbgs() <<
" Error: Duplicate symbols " << Duplicates <<
"\n"; });
1398 MU.getName().str());
1403 if (!MUDefsOverridden.empty())
1404 dbgs() <<
" Defs in this MU overridden: " << MUDefsOverridden <<
"\n";
1406 for (
auto &S : MUDefsOverridden)
1407 MU.doDiscard(*
this, S);
1411 if (!ExistingDefsOverridden.empty())
1412 dbgs() <<
" Existing defs overridden by this MU: " << MUDefsOverridden
1415 for (
auto &S : ExistingDefsOverridden) {
1417 auto UMII = UnmaterializedInfos.find(S);
1418 assert(UMII != UnmaterializedInfos.end() &&
1419 "Overridden existing def should have an UnmaterializedInfo");
1420 UMII->second->MU->doDiscard(*
this, S);
1424 for (
auto &KV : MU.getSymbols()) {
1425 auto &SymEntry = Symbols[KV.first];
1426 SymEntry.setFlags(KV.second);
1428 SymEntry.setMaterializerAttached(
true);
1434void JITDylib::installMaterializationUnit(
1438 if (&RT != DefaultTracker.get()) {
1439 auto &TS = TrackerSymbols[&RT];
1440 TS.reserve(TS.size() + MU->getSymbols().size());
1441 for (
auto &KV : MU->getSymbols())
1442 TS.push_back(KV.first);
1445 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU), &RT);
1446 for (
auto &KV : UMI->MU->getSymbols())
1447 UnmaterializedInfos[KV.first] = UMI;
1452 for (
auto &QuerySymbol : QuerySymbols) {
1453 auto MII = MaterializingInfos.find(QuerySymbol);
1454 if (MII != MaterializingInfos.end())
1455 MII->second.removeQuery(Q);
1467 std::mutex LookupMutex;
1468 std::condition_variable CV;
1472 dbgs() <<
"Issuing init-symbol lookup:\n";
1473 for (
auto &KV : InitSyms)
1474 dbgs() <<
" " << KV.first->getName() <<
": " << KV.second <<
"\n";
1477 for (
auto &KV : InitSyms) {
1478 auto *JD = KV.first;
1479 auto Names = std::move(KV.second);
1486 std::lock_guard<std::mutex> Lock(LookupMutex);
1490 "Duplicate JITDylib in lookup?");
1491 CompoundResult[JD] = std::move(*
Result);
1501 std::unique_lock<std::mutex> Lock(LookupMutex);
1502 CV.wait(Lock, [&] {
return Count == 0; });
1505 return std::move(CompoundErr);
1507 return std::move(CompoundResult);
1514 class TriggerOnComplete {
1517 TriggerOnComplete(OnCompleteFn OnComplete)
1518 : OnComplete(std::move(OnComplete)) {}
1519 ~TriggerOnComplete() { OnComplete(std::move(LookupResult)); }
1520 void reportResult(
Error Err) {
1521 std::lock_guard<std::mutex> Lock(ResultMutex);
1522 LookupResult =
joinErrors(std::move(LookupResult), std::move(Err));
1526 std::mutex ResultMutex;
1528 OnCompleteFn OnComplete;
1532 dbgs() <<
"Issuing init-symbol lookup:\n";
1533 for (
auto &KV : InitSyms)
1534 dbgs() <<
" " << KV.first->getName() <<
": " << KV.second <<
"\n";
1537 auto TOC = std::make_shared<TriggerOnComplete>(std::move(OnComplete));
1539 for (
auto &KV : InitSyms) {
1540 auto *JD = KV.first;
1541 auto Names = std::move(KV.second);
1547 TOC->reportResult(
Result.takeError());
1556 MR->failMaterialization();
1560 OS <<
"Materialization task: " << MU->getName() <<
" in "
1561 << MR->getTargetJITDylib().getName();
1565 assert(MU &&
"MU should not be null");
1566 assert(MR &&
"MR should not be null");
1567 MU->materialize(std::move(MR));
1577 this->EPC->ES =
this;
1579 for (
auto &[Name, Ptr] : this->EPC->getBootstrapSymbolsMap())
1580 BootstrapSymbols[
intern(Name)] =
1590 "Session still open. Did you forget to call endSession?");
1594 LLVM_DEBUG(
dbgs() <<
"Ending ExecutionSession " <<
this <<
"\n");
1596 WaitingOnGraph::OpRecorder *GOpRecorderToEnd =
nullptr;
1599#ifdef EXPENSIVE_CHECKS
1600 verifySessionState(
"Entering ExecutionSession::endSession");
1604 GOpRecorderToEnd = GOpRecorder;
1605 SessionOpen =
false;
1609 std::reverse(JDsToRemove.begin(), JDsToRemove.end());
1613 Err =
joinErrors(std::move(Err), EPC->disconnect());
1615 if (GOpRecorderToEnd)
1616 GOpRecorderToEnd->recordEnd();
1627 assert(!ResourceManagers.empty() &&
"No managers registered");
1628 if (ResourceManagers.back() == &RM)
1629 ResourceManagers.pop_back();
1632 assert(
I != ResourceManagers.end() &&
"RM not registered");
1633 ResourceManagers.erase(
I);
1640 for (
auto &JD : JDs)
1641 if (JD->getName() == Name)
1650 assert(SessionOpen &&
"Cannot create JITDylib after session is closed");
1651 JDs.push_back(
new JITDylib(*
this, std::move(Name)));
1659 if (
auto Err = P->setupJITDylib(JD))
1660 return std::move(Err);
1667 for (
auto &JD : JDsToRemove) {
1668 assert(JD->State == JITDylib::Open &&
"JD already closed");
1669 JD->State = JITDylib::Closing;
1671 assert(
I != JDs.end() &&
"JD does not appear in session JDs");
1678 for (
auto JD : JDsToRemove) {
1679 Err =
joinErrors(std::move(Err), JD->clear());
1681 Err =
joinErrors(std::move(Err), P->teardownJITDylib(*JD));
1686 for (
auto &JD : JDsToRemove) {
1687 assert(JD->State == JITDylib::Closing &&
"JD should be closing");
1688 JD->State = JITDylib::Closed;
1689 assert(JD->Symbols.empty() &&
"JD.Symbols is not empty after clear");
1690 assert(JD->UnmaterializedInfos.empty() &&
1691 "JD.UnmaterializedInfos is not empty after clear");
1692 assert(JD->MaterializingInfos.empty() &&
1693 "JD.MaterializingInfos is not empty after clear");
1694 assert(JD->TrackerSymbols.empty() &&
1695 "TrackerSymbols is not empty after clear");
1696 JD->DefGenerators.clear();
1697 JD->LinkOrder.clear();
1707 return std::vector<JITDylibSP>();
1709 auto &ES = JDs.
front()->getExecutionSession();
1710 return ES.runSessionLocked([&]() ->
Expected<std::vector<JITDylibSP>> {
1712 std::vector<JITDylibSP>
Result;
1714 for (
auto &JD : JDs) {
1716 if (JD->State != Open)
1718 "Error building link order: " + JD->getName() +
" is defunct",
1720 if (Visited.
count(JD.get()))
1725 Visited.
insert(JD.get());
1727 while (!WorkStack.
empty()) {
1728 Result.push_back(std::move(WorkStack.
back()));
1732 auto &JD = *KV.first;
1733 if (!Visited.
insert(&JD).second)
1763 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
1764 K, std::move(SearchOrder), std::move(LookupSet),
1765 std::move(OnComplete)),
1773 std::promise<MSVCPExpected<SymbolFlagsMap>> ResultP;
1774 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
1775 K, std::move(SearchOrder), std::move(LookupSet),
1777 ResultP.set_value(std::move(
Result));
1781 auto ResultF = ResultP.get_future();
1782 return ResultF.
get();
1793 dbgs() <<
"Looking up " << Symbols <<
" in " << SearchOrder
1794 <<
" (required state: " << RequiredState <<
")\n";
1801 dispatchOutstandingMUs();
1803 auto Unresolved = std::move(Symbols);
1804 auto Q = std::make_shared<AsynchronousSymbolQuery>(Unresolved, RequiredState,
1805 std::move(NotifyComplete));
1807 auto IPLS = std::make_unique<InProgressFullLookupState>(
1808 K, SearchOrder, std::move(Unresolved), RequiredState, std::move(Q),
1809 std::move(RegisterDependencies));
1819#if LLVM_ENABLE_THREADS
1821 std::promise<MSVCPExpected<SymbolMap>> PromisedResult;
1824 PromisedResult.set_value(std::move(R));
1836 ResolutionError = R.takeError();
1841 lookup(K, SearchOrder, std::move(Symbols), RequiredState,
1842 std::move(NotifyComplete), RegisterDependencies);
1844#if LLVM_ENABLE_THREADS
1845 return PromisedResult.get_future().get();
1847 if (ResolutionError)
1848 return std::move(ResolutionError);
1861 assert(ResultMap->size() == 1 &&
"Unexpected number of results");
1862 assert(ResultMap->count(Name) &&
"Missing result for symbol");
1863 return std::move(ResultMap->begin()->second);
1865 return ResultMap.takeError();
1877 return lookup(SearchOrder,
intern(Name), RequiredState);
1887 return TagSyms.takeError();
1890 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
1893 for (
auto &[TagName, TagSym] : *TagSyms) {
1894 auto TagAddr = TagSym.getAddress();
1895 if (JITDispatchHandlers.count(TagAddr))
1897 " (for " + *TagName +
1898 ") already registered",
1903 for (
auto &[TagName, TagSym] : *TagSyms) {
1904 auto TagAddr = TagSym.getAddress();
1905 auto I = WFs.
find(TagName);
1907 "JITDispatchHandler implementation missing");
1908 JITDispatchHandlers[TagAddr] =
1909 std::make_shared<JITDispatchHandlerFunction>(std::move(
I->second));
1911 dbgs() <<
"Associated function tag \"" << *TagName <<
"\" ("
1912 <<
formatv(
"{0:x}", TagAddr) <<
") with handler\n";
1923 std::shared_ptr<JITDispatchHandlerFunction>
F;
1925 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
1926 auto I = JITDispatchHandlers.find(HandlerFnTagAddr);
1927 if (
I != JITDispatchHandlers.end())
1932 (*F)(std::move(SendResult), ArgBytes.
data(), ArgBytes.
size());
1935 (
"No function registered for tag " +
1936 formatv(
"{0:x16}", HandlerFnTagAddr))
1942 for (
auto &JD : JDs)
1947#ifdef EXPENSIVE_CHECKS
1948bool ExecutionSession::verifySessionState(
Twine Phase) {
1952 for (
auto &JD : JDs) {
1955 auto &Stream =
errs();
1957 Stream <<
"ERROR: Bad ExecutionSession state detected " <<
Phase
1959 Stream <<
" In JITDylib " << JD->getName() <<
", ";
1964 if (JD->State != JITDylib::Open) {
1966 <<
"state is not Open, but JD is in ExecutionSession list.";
1974 for (
auto &[Sym, Entry] : JD->Symbols) {
1977 if (Entry.getAddress()) {
1978 LogFailure() <<
"symbol " << Sym <<
" has state "
1980 <<
" (not-yet-resolved) but non-null address "
1981 << Entry.getAddress() <<
".\n";
1986 auto UMIItr = JD->UnmaterializedInfos.find(Sym);
1987 if (
Entry.hasMaterializerAttached()) {
1988 if (UMIItr == JD->UnmaterializedInfos.end()) {
1989 LogFailure() <<
"symbol " << Sym
1990 <<
" entry claims materializer attached, but "
1991 "UnmaterializedInfos has no corresponding entry.\n";
1993 }
else if (UMIItr != JD->UnmaterializedInfos.end()) {
1996 <<
" entry claims no materializer attached, but "
1997 "UnmaterializedInfos has an unexpected entry for it.\n";
2003 for (
auto &[Sym, UMI] : JD->UnmaterializedInfos) {
2004 auto SymItr = JD->Symbols.find(Sym);
2005 if (SymItr == JD->Symbols.end()) {
2008 <<
" has UnmaterializedInfos entry, but no Symbols entry.\n";
2013 for (
auto &[Sym, MII] : JD->MaterializingInfos) {
2015 auto SymItr = JD->Symbols.find(Sym);
2016 if (SymItr == JD->Symbols.end()) {
2021 <<
" has MaterializingInfos entry, but no Symbols entry.\n";
2029 <<
" is in Ready state, should not have MaterializingInfo.\n";
2034 static_cast<std::underlying_type_t<SymbolState>
>(
2035 SymItr->second.getState()) + 1);
2036 for (
auto &Q : MII.PendingQueries) {
2037 if (Q->getRequiredState() != CurState) {
2038 if (Q->getRequiredState() > CurState)
2039 CurState = Q->getRequiredState();
2041 LogFailure() <<
"symbol " << Sym
2042 <<
" has stale or misordered queries.\n";
2054void ExecutionSession::dispatchOutstandingMUs() {
2057 std::optional<std::pair<std::unique_ptr<MaterializationUnit>,
2058 std::unique_ptr<MaterializationResponsibility>>>
2062 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2063 if (!OutstandingMUs.empty()) {
2064 JMU.emplace(std::move(OutstandingMUs.back()));
2065 OutstandingMUs.pop_back();
2072 assert(JMU->first &&
"No MU?");
2073 LLVM_DEBUG(
dbgs() <<
" Dispatching \"" << JMU->first->getName() <<
"\"\n");
2074 dispatchTask(std::make_unique<MaterializationTask>(std::move(JMU->first),
2075 std::move(JMU->second)));
2077 LLVM_DEBUG(
dbgs() <<
"Done dispatching MaterializationUnits.\n");
2082 dbgs() <<
"In " << RT.getJITDylib().getName() <<
" removing tracker "
2083 <<
formatv(
"{0:x}", RT.getKeyUnsafe()) <<
"\n";
2085 std::vector<ResourceManager *> CurrentResourceManagers;
2087 JITDylib::RemoveTrackerResult
R;
2090 CurrentResourceManagers = ResourceManagers;
2092 R = RT.getJITDylib().IL_removeTracker(RT);
2096 R.DefunctMUs.clear();
2100 auto &JD = RT.getJITDylib();
2101 for (
auto *L :
reverse(CurrentResourceManagers))
2103 L->handleRemoveResources(JD, RT.getKeyUnsafe()));
2105 for (
auto &Q :
R.QueriesToFail)
2115 dbgs() <<
"In " << SrcRT.getJITDylib().getName()
2116 <<
" transfering resources from tracker "
2117 <<
formatv(
"{0:x}", SrcRT.getKeyUnsafe()) <<
" to tracker "
2118 <<
formatv(
"{0:x}", DstRT.getKeyUnsafe()) <<
"\n";
2122 if (&DstRT == &SrcRT)
2125 assert(&DstRT.getJITDylib() == &SrcRT.getJITDylib() &&
2126 "Can't transfer resources between JITDylibs");
2128 SrcRT.makeDefunct();
2129 auto &JD = DstRT.getJITDylib();
2130 JD.transferTracker(DstRT, SrcRT);
2131 for (
auto *L :
reverse(ResourceManagers))
2132 L->handleTransferResources(JD, DstRT.getKeyUnsafe(),
2133 SrcRT.getKeyUnsafe());
2140 dbgs() <<
"In " << RT.getJITDylib().getName() <<
" destroying tracker "
2141 <<
formatv(
"{0:x}", RT.getKeyUnsafe()) <<
"\n";
2143 if (!RT.isDefunct())
2144 transferResourceTracker(*RT.getJITDylib().getDefaultResourceTracker(),
2149Error ExecutionSession::IL_updateCandidatesFor(
2152 return Candidates.forEachWithRemoval(
2153 [&](
const SymbolStringPtr &Name,
2157 auto SymI = JD.Symbols.find(Name);
2158 if (SymI == JD.Symbols.end())
2166 if (!SymI->second.getFlags().isExported() &&
2169 NonCandidates->add(Name, SymLookupFlags);
2178 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2185 if (SymI->second.getFlags().hasError()) {
2186 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2187 (*FailedSymbolsMap)[&JD] = {
Name};
2189 std::move(FailedSymbolsMap));
2197void ExecutionSession::OL_resumeLookupAfterGeneration(
2201 "Should not be called for not-in-generator lookups");
2206 if (
auto DG = IPLS.CurDefGeneratorStack.back().lock()) {
2207 IPLS.CurDefGeneratorStack.pop_back();
2208 std::lock_guard<std::mutex> Lock(DG->M);
2212 if (DG->PendingLookups.empty()) {
2218 LS = std::move(DG->PendingLookups.front());
2219 DG->PendingLookups.pop_front();
2224 dispatchTask(std::make_unique<LookupTask>(std::move(LS)));
2228void ExecutionSession::OL_applyQueryPhase1(
2229 std::unique_ptr<InProgressLookupState> IPLS,
Error Err) {
2232 dbgs() <<
"Entering OL_applyQueryPhase1:\n"
2233 <<
" Lookup kind: " << IPLS->K <<
"\n"
2234 <<
" Search order: " << IPLS->SearchOrder
2235 <<
", Current index = " << IPLS->CurSearchOrderIndex
2236 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2237 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2238 <<
" Definition generator candidates: "
2239 << IPLS->DefGeneratorCandidates <<
"\n"
2240 <<
" Definition generator non-candidates: "
2241 << IPLS->DefGeneratorNonCandidates <<
"\n";
2245 OL_resumeLookupAfterGeneration(*IPLS);
2248 "Lookup should not be in InGenerator state here");
2255 while (IPLS->CurSearchOrderIndex != IPLS->SearchOrder.size()) {
2261 return IPLS->fail(std::move(Err));
2264 auto &KV = IPLS->SearchOrder[IPLS->CurSearchOrderIndex];
2265 auto &JD = *KV.first;
2266 auto JDLookupFlags = KV.second;
2269 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2270 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2274 if (IPLS->NewJITDylib) {
2278 SymbolLookupSet Tmp;
2279 std::swap(IPLS->DefGeneratorNonCandidates, Tmp);
2280 IPLS->DefGeneratorCandidates.append(std::move(Tmp));
2283 dbgs() <<
" First time visiting " << JD.getName()
2284 <<
", resetting candidate sets and building generator stack\n";
2289 IPLS->CurDefGeneratorStack.reserve(JD.DefGenerators.size());
2295 IPLS->NewJITDylib =
false;
2304 Err = IL_updateCandidatesFor(
2305 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2306 JD.DefGenerators.empty() ?
nullptr
2307 : &IPLS->DefGeneratorNonCandidates);
2309 dbgs() <<
" Remaining candidates = " << IPLS->DefGeneratorCandidates
2317 IPLS->DefGeneratorCandidates.empty())
2318 OL_resumeLookupAfterGeneration(*IPLS);
2324 return IPLS->fail(std::move(Err));
2328 if (IPLS->CurDefGeneratorStack.empty())
2329 LLVM_DEBUG(
dbgs() <<
" No generators to run for this JITDylib.\n");
2330 else if (IPLS->DefGeneratorCandidates.empty())
2333 dbgs() <<
" Running " << IPLS->CurDefGeneratorStack.size()
2334 <<
" remaining generators for "
2335 << IPLS->DefGeneratorCandidates.size() <<
" candidates\n";
2337 while (!IPLS->CurDefGeneratorStack.empty() &&
2338 !IPLS->DefGeneratorCandidates.empty()) {
2339 auto DG = IPLS->CurDefGeneratorStack.back().lock();
2343 "DefinitionGenerator removed while lookup in progress",
2356 std::lock_guard<std::mutex> Lock(DG->M);
2358 DG->PendingLookups.push_back(std::move(IPLS));
2367 auto &LookupSet = IPLS->DefGeneratorCandidates;
2372 LLVM_DEBUG(
dbgs() <<
" Attempting to generate " << LookupSet <<
"\n");
2374 Err = DG->tryToGenerate(LS, K, JD, JDLookupFlags, LookupSet);
2375 IPLS = std::move(
LS.IPLS);
2381 OL_resumeLookupAfterGeneration(*IPLS);
2386 dbgs() <<
" Error attempting to generate " << LookupSet <<
"\n";
2388 assert(IPLS &&
"LS cannot be retained if error is returned");
2389 return IPLS->fail(std::move(Err));
2395 {
dbgs() <<
" LookupState captured. Exiting phase1 for now.\n"; });
2402 LLVM_DEBUG(
dbgs() <<
" Updating candidate set post-generation\n");
2403 Err = IL_updateCandidatesFor(
2404 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2405 JD.DefGenerators.empty() ?
nullptr
2406 : &IPLS->DefGeneratorNonCandidates);
2411 LLVM_DEBUG(
dbgs() <<
" Error encountered while updating candidates\n");
2412 return IPLS->fail(std::move(Err));
2416 if (IPLS->DefGeneratorCandidates.empty() &&
2417 IPLS->DefGeneratorNonCandidates.empty()) {
2420 IPLS->CurSearchOrderIndex = IPLS->SearchOrder.size();
2426 ++IPLS->CurSearchOrderIndex;
2427 IPLS->NewJITDylib =
true;
2432 IPLS->DefGeneratorCandidates.remove_if(
2440 if (IPLS->DefGeneratorCandidates.empty()) {
2442 IPLS->complete(std::move(IPLS));
2444 LLVM_DEBUG(
dbgs() <<
"Phase 1 failed with unresolved symbols.\n");
2450void ExecutionSession::OL_completeLookup(
2451 std::unique_ptr<InProgressLookupState> IPLS,
2452 std::shared_ptr<AsynchronousSymbolQuery> Q,
2456 dbgs() <<
"Entering OL_completeLookup:\n"
2457 <<
" Lookup kind: " << IPLS->K <<
"\n"
2458 <<
" Search order: " << IPLS->SearchOrder
2459 <<
", Current index = " << IPLS->CurSearchOrderIndex
2460 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2461 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2462 <<
" Definition generator candidates: "
2463 << IPLS->DefGeneratorCandidates <<
"\n"
2464 <<
" Definition generator non-candidates: "
2465 << IPLS->DefGeneratorNonCandidates <<
"\n";
2468 bool QueryComplete =
false;
2469 DenseMap<JITDylib *, JITDylib::UnmaterializedInfosList> CollectedUMIs;
2472 for (
auto &KV : IPLS->SearchOrder) {
2473 auto &JD = *KV.first;
2474 auto JDLookupFlags = KV.second;
2476 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2477 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2480 auto Err = IPLS->LookupSet.forEachWithRemoval(
2481 [&](
const SymbolStringPtr &Name,
2484 dbgs() <<
" Attempting to match \"" <<
Name <<
"\" ("
2485 << SymLookupFlags <<
")... ";
2490 auto SymI = JD.Symbols.find(Name);
2491 if (SymI == JD.Symbols.end()) {
2498 if (!SymI->second.getFlags().isExported() &&
2510 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2514 "required, but symbol is has-side-effects-only\n";
2522 if (SymI->second.getFlags().hasError()) {
2524 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2525 (*FailedSymbolsMap)[&JD] = {
Name};
2534 if (SymI->second.getState() >= Q->getRequiredState()) {
2536 <<
"matched, symbol already in required state\n");
2537 Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
2542 Q->addQueryDependence(JD, Name);
2550 if (SymI->second.hasMaterializerAttached()) {
2551 assert(SymI->second.getAddress() == ExecutorAddr() &&
2552 "Symbol not resolved but already has address?");
2553 auto UMII = JD.UnmaterializedInfos.find(Name);
2554 assert(UMII != JD.UnmaterializedInfos.end() &&
2555 "Lazy symbol should have UnmaterializedInfo");
2557 auto UMI = UMII->second;
2558 assert(UMI->MU &&
"Materializer should not be null");
2559 assert(UMI->RT &&
"Tracker should not be null");
2561 dbgs() <<
"matched, preparing to dispatch MU@" << UMI->MU.get()
2562 <<
" (" << UMI->MU->getName() <<
")\n";
2567 for (
auto &KV : UMI->MU->getSymbols()) {
2568 auto SymK = JD.Symbols.find(KV.first);
2569 assert(SymK != JD.Symbols.end() &&
2570 "No entry for symbol covered by MaterializationUnit");
2571 SymK->second.setMaterializerAttached(
false);
2573 JD.UnmaterializedInfos.erase(KV.first);
2577 CollectedUMIs[&JD].push_back(std::move(UMI));
2585 "By this line the symbol should be materializing");
2586 auto &
MI = JD.MaterializingInfos[
Name];
2588 Q->addQueryDependence(JD, Name);
2593 JD.shrinkMaterializationInfoMemory();
2599 dbgs() <<
"Lookup failed. Detaching query and replacing MUs.\n";
2606 for (
auto &KV : CollectedUMIs) {
2607 auto &JD = *KV.first;
2608 for (
auto &UMI : KV.second)
2609 for (
auto &KV2 : UMI->MU->getSymbols()) {
2610 assert(!JD.UnmaterializedInfos.count(KV2.first) &&
2611 "Unexpected materializer in map");
2612 auto SymI = JD.Symbols.find(KV2.first);
2613 assert(SymI != JD.Symbols.end() &&
"Missing symbol entry");
2615 "Can not replace symbol that is not materializing");
2616 assert(!SymI->second.hasMaterializerAttached() &&
2617 "MaterializerAttached flag should not be set");
2618 SymI->second.setMaterializerAttached(
true);
2619 JD.UnmaterializedInfos[KV2.first] = UMI;
2627 LLVM_DEBUG(
dbgs() <<
"Stripping unmatched weakly-referenced symbols\n");
2628 IPLS->LookupSet.forEachWithRemoval(
2631 Q->dropSymbol(Name);
2637 if (!IPLS->LookupSet.empty()) {
2640 IPLS->LookupSet.getSymbolNames());
2644 QueryComplete = Q->isComplete();
2647 dbgs() <<
"Query successfully "
2648 << (QueryComplete ?
"completed" :
"lodged") <<
"\n";
2652 if (!CollectedUMIs.empty()) {
2653 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2656 for (
auto &KV : CollectedUMIs) {
2658 auto &JD = *KV.first;
2659 dbgs() <<
" For " << JD.getName() <<
": Adding " << KV.second.size()
2662 for (
auto &UMI : KV.second) {
2663 auto MR = createMaterializationResponsibility(
2664 *UMI->RT, std::move(UMI->MU->SymbolFlags),
2665 std::move(UMI->MU->InitSymbol));
2666 OutstandingMUs.push_back(
2667 std::make_pair(std::move(UMI->MU), std::move(MR)));
2673 if (RegisterDependencies && !Q->QueryRegistrations.empty()) {
2675 RegisterDependencies(Q->QueryRegistrations);
2685 Q->handleFailed(std::move(LodgingErr));
2689 if (QueryComplete) {
2691 Q->handleComplete(*
this);
2694 dispatchOutstandingMUs();
2697void ExecutionSession::OL_completeLookupFlags(
2698 std::unique_ptr<InProgressLookupState> IPLS,
2699 unique_function<
void(Expected<SymbolFlagsMap>)> OnComplete) {
2703 dbgs() <<
"Entering OL_completeLookupFlags:\n"
2704 <<
" Lookup kind: " << IPLS->K <<
"\n"
2705 <<
" Search order: " << IPLS->SearchOrder
2706 <<
", Current index = " << IPLS->CurSearchOrderIndex
2707 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2708 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2709 <<
" Definition generator candidates: "
2710 << IPLS->DefGeneratorCandidates <<
"\n"
2711 <<
" Definition generator non-candidates: "
2712 << IPLS->DefGeneratorNonCandidates <<
"\n";
2718 for (
auto &KV : IPLS->SearchOrder) {
2719 auto &JD = *KV.first;
2720 auto JDLookupFlags = KV.second;
2722 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2723 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2726 IPLS->LookupSet.forEachWithRemoval([&](
const SymbolStringPtr &Name,
2729 dbgs() <<
" Attempting to match \"" <<
Name <<
"\" ("
2730 << SymLookupFlags <<
")... ";
2735 auto SymI = JD.Symbols.find(Name);
2736 if (SymI == JD.Symbols.end()) {
2742 if (!SymI->second.getFlags().isExported() &&
2749 dbgs() <<
"matched, \"" <<
Name <<
"\" -> " << SymI->second.getFlags()
2763 if (!IPLS->LookupSet.empty()) {
2766 IPLS->LookupSet.getSymbolNames());
2775 OnComplete(std::move(
Result));
2778void ExecutionSession::OL_destroyMaterializationResponsibility(
2781 assert(MR.SymbolFlags.empty() &&
2782 "All symbols should have been explicitly materialized or failed");
2783 MR.JD.unlinkMaterializationResponsibility(MR);
2788 return MR.JD.getRequestedSymbols(MR.SymbolFlags);
2794 dbgs() <<
"In " << MR.JD.getName() <<
" resolving " <<
Symbols <<
"\n";
2797 for (
auto &KV : Symbols) {
2798 auto I = MR.SymbolFlags.find(KV.first);
2799 assert(
I != MR.SymbolFlags.end() &&
2800 "Resolving symbol outside this responsibility set");
2801 assert(!
I->second.hasMaterializationSideEffectsOnly() &&
2802 "Can't resolve materialization-side-effects-only symbol");
2805 assert((KV.second.getFlags() & WeakOrCommon) &&
2806 "Common symbols must be resolved as common or weak");
2807 assert((KV.second.getFlags() & ~WeakOrCommon) ==
2809 "Resolving symbol with incorrect flags");
2811 assert(KV.second.getFlags() ==
I->second &&
2812 "Resolving symbol with incorrect flags");
2816 return MR.JD.resolve(MR, Symbols);
2820ExecutionSession::IL_getSymbolState(
JITDylib *JD,
2822 if (JD->State != JITDylib::Open)
2823 return WaitingOnGraph::ExternalState::Failed;
2825 auto I = JD->Symbols.find_as(Name);
2828 if (
I == JD->Symbols.end())
2829 return WaitingOnGraph::ExternalState::Failed;
2831 if (
I->second.getFlags().hasError())
2832 return WaitingOnGraph::ExternalState::Failed;
2835 return WaitingOnGraph::ExternalState::Ready;
2837 return WaitingOnGraph::ExternalState::None;
2840template <
typename UpdateSymbolFn,
typename UpdateQueryFn>
2841void ExecutionSession::IL_collectQueries(
2842 JITDylib::AsynchronousSymbolQuerySet &Qs,
2843 WaitingOnGraph::ContainerElementsMap &QualifiedSymbols,
2844 UpdateSymbolFn &&UpdateSymbol, UpdateQueryFn &&UpdateQuery) {
2846 for (
auto &[JD, Symbols] : QualifiedSymbols) {
2851 assert(JD->State == JITDylib::Open &&
2852 "WaitingOnGraph includes definition in defunct JITDylib");
2853 for (
auto &Symbol : Symbols) {
2855 auto I = JD->Symbols.find_as(Symbol);
2856 assert(
I != JD->Symbols.end() &&
2857 "Failed Symbol missing from JD symbol table");
2859 UpdateSymbol(Entry);
2862 auto J = JD->MaterializingInfos.find_as(Symbol);
2863 if (J != JD->MaterializingInfos.end()) {
2864 for (
auto &Q : J->second.takeAllPendingQueries()) {
2865 UpdateQuery(*Q, *JD, Symbol, Entry);
2866 Qs.insert(std::move(Q));
2868 JD->MaterializingInfos.erase(J);
2874Expected<ExecutionSession::EmitQueries>
2876 WaitingOnGraph::SimplifyResult SR) {
2878 if (MR.RT->isDefunct())
2881 auto &TargetJD = MR.getTargetJITDylib();
2882 if (TargetJD.State != JITDylib::Open)
2887#ifdef EXPENSIVE_CHECKS
2888 verifySessionState(
"entering ExecutionSession::IL_emit");
2891 auto ER = G.emit(std::move(SR),
2892 [
this](
JITDylib *JD, NonOwningSymbolStringPtr Name) {
2893 return IL_getSymbolState(JD, Name);
2899 for (
auto &SN : ER.Failed)
2901 EQ.Failed, SN->defs(),
2902 [](JITDylib::SymbolTableEntry &
E) {
2903 E.setFlags(E.getFlags() = JITSymbolFlags::HasError);
2905 [&](AsynchronousSymbolQuery &Q,
JITDylib &JD,
2906 NonOwningSymbolStringPtr Name, JITDylib::SymbolTableEntry &
E) {
2907 auto &FS = EQ.FailedSymsForQuery[&Q];
2909 FS = std::make_shared<SymbolDependenceMap>();
2910 (*FS)[&JD].insert(SymbolStringPtr(Name));
2913 for (
auto &FQ :
EQ.Failed)
2916 for (
auto &SN : ER.Ready)
2918 EQ.Completed, SN->defs(),
2919 [](JITDylib::SymbolTableEntry &
E) { E.setState(SymbolState::Ready); },
2920 [](AsynchronousSymbolQuery &Q,
JITDylib &JD,
2921 NonOwningSymbolStringPtr Name, JITDylib::SymbolTableEntry &
E) {
2922 Q.notifySymbolMetRequiredState(SymbolStringPtr(Name), E.getSymbol());
2927 for (
auto it =
EQ.Completed.begin(), end =
EQ.Completed.end(); it != end;) {
2928 if ((*it)->isComplete()) {
2931 it =
EQ.Completed.erase(it);
2935#ifdef EXPENSIVE_CHECKS
2936 verifySessionState(
"exiting ExecutionSession::IL_emit");
2939 return std::move(
EQ);
2942Error ExecutionSession::OL_notifyEmitted(
2946 dbgs() <<
"In " << MR.JD.getName() <<
" emitting " << MR.SymbolFlags
2948 if (!DepGroups.empty()) {
2949 dbgs() <<
" Initial dependencies:\n";
2950 for (
auto &SDG : DepGroups) {
2951 dbgs() <<
" Symbols: " << SDG.Symbols
2952 <<
", Dependencies: " << SDG.Dependencies <<
"\n";
2959 for (
auto &DG : DepGroups) {
2960 for (
auto &Sym : DG.Symbols) {
2961 assert(MR.SymbolFlags.count(Sym) &&
2962 "DG contains dependence for symbol outside this MR");
2963 assert(Visited.insert(Sym).second &&
2964 "DG contains duplicate entries for Name");
2969 std::vector<std::unique_ptr<WaitingOnGraph::SuperNode>> SNs;
2970 WaitingOnGraph::ContainerElementsMap Residual;
2972 auto &JDResidual = Residual[&MR.getTargetJITDylib()];
2973 for (
auto &[Name, Flags] : MR.getSymbols())
2974 JDResidual.insert(NonOwningSymbolStringPtr(Name));
2976 for (
auto &SDG : DepGroups) {
2977 WaitingOnGraph::ContainerElementsMap Defs;
2978 assert(!SDG.Symbols.empty());
2979 auto &JDDefs = Defs[&MR.getTargetJITDylib()];
2980 for (
auto &Def : SDG.Symbols) {
2981 JDDefs.insert(NonOwningSymbolStringPtr(Def));
2982 JDResidual.erase(NonOwningSymbolStringPtr(Def));
2984 WaitingOnGraph::ContainerElementsMap Deps;
2985 if (!SDG.Dependencies.empty()) {
2986 for (
auto &[JD, Syms] : SDG.Dependencies) {
2987 auto &JDDeps = Deps[JD];
2988 for (
auto &Dep : Syms)
2989 JDDeps.insert(NonOwningSymbolStringPtr(Dep));
2992 SNs.push_back(std::make_unique<WaitingOnGraph::SuperNode>(
2993 std::move(Defs), std::move(Deps)));
2995 if (!JDResidual.empty())
2996 SNs.push_back(std::make_unique<WaitingOnGraph::SuperNode>(
2997 std::move(Residual), WaitingOnGraph::ContainerElementsMap()));
3003 dbgs() <<
" Simplified dependencies:\n";
3004 for (
auto &SN : SR.superNodes()) {
3006 auto SortedLibs = [](WaitingOnGraph::ContainerElementsMap &
C) {
3007 std::vector<JITDylib *> JDs;
3008 for (
auto &[JD,
_] :
C)
3011 return LHS->getName() <
RHS->getName();
3016 auto SortedNames = [](WaitingOnGraph::ElementSet &Elems) {
3017 std::vector<NonOwningSymbolStringPtr> Names(Elems.begin(), Elems.end());
3019 const NonOwningSymbolStringPtr &
RHS) {
3025 dbgs() <<
" Defs: {";
3026 for (
auto *JD : SortedLibs(SN->defs())) {
3027 dbgs() <<
" (" << JD->getName() <<
", [";
3028 for (
auto &Sym : SortedNames(SN->defs()[JD]))
3029 dbgs() <<
" " << Sym;
3032 dbgs() <<
" }, Deps: {";
3033 for (
auto *JD : SortedLibs(SN->deps())) {
3034 dbgs() <<
" (" << JD->getName() <<
", [";
3035 for (
auto &Sym : SortedNames(SN->deps()[JD]))
3036 dbgs() <<
" " << Sym;
3047 return EmitQueries.takeError();
3055 for (
auto &FQ : EmitQueries->Failed) {
3057 assert(EmitQueries->FailedSymsForQuery.count(FQ.get()) &&
3058 "Missing failed symbols for query");
3059 auto FailedSyms = std::move(EmitQueries->FailedSymsForQuery[FQ.get()]);
3060 for (
auto &[JD, Syms] : *FailedSyms) {
3061 auto &BadDepsForJD = BadDeps[JD];
3062 for (
auto &Sym : Syms)
3063 BadDepsForJD.insert(Sym);
3066 std::move(FailedSyms)));
3070 for (
auto &UQ : EmitQueries->Completed)
3071 UQ->handleComplete(*
this);
3074 if (!BadDeps.empty()) {
3080 for (
auto &[Name, Flags] : MR.getSymbols())
3082 MR.SymbolFlags.clear();
3085 std::move(BadDeps),
"dependencies removed or in error state");
3088 MR.SymbolFlags.
clear();
3092Error ExecutionSession::OL_defineMaterializing(
3096 dbgs() <<
"In " << MR.JD.getName() <<
" defining materializing symbols "
3097 << NewSymbolFlags <<
"\n";
3099 if (
auto AcceptedDefs =
3100 MR.JD.defineMaterializing(MR, std::move(NewSymbolFlags))) {
3102 for (
auto &KV : *AcceptedDefs)
3103 MR.SymbolFlags.insert(KV);
3106 return AcceptedDefs.takeError();
3109std::pair<JITDylib::AsynchronousSymbolQuerySet,
3110 std::shared_ptr<SymbolDependenceMap>>
3111ExecutionSession::IL_failSymbols(
JITDylib &JD,
3114#ifdef EXPENSIVE_CHECKS
3115 verifySessionState(
"entering ExecutionSession::IL_failSymbols");
3119 if (SymbolsToFail.empty())
3122 JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3123 auto Fail = [&](
JITDylib *FailJD, NonOwningSymbolStringPtr FailSym) {
3124 auto I = FailJD->Symbols.find_as(FailSym);
3125 assert(
I != FailJD->Symbols.end());
3127 auto J = FailJD->MaterializingInfos.find_as(FailSym);
3128 if (J != FailJD->MaterializingInfos.end()) {
3129 for (
auto &Q : J->second.takeAllPendingQueries())
3130 FailedQueries.insert(std::move(Q));
3131 FailJD->MaterializingInfos.erase(J);
3135 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
3138 auto &FailedSymsForJD = (*FailedSymbolsMap)[&JD];
3139 for (
auto &Sym : SymbolsToFail) {
3140 FailedSymsForJD.insert(Sym);
3141 Fail(&JD, NonOwningSymbolStringPtr(Sym));
3145 WaitingOnGraph::ContainerElementsMap ToFail;
3146 auto &JDToFail = ToFail[&JD];
3147 for (
auto &Sym : SymbolsToFail)
3148 JDToFail.insert(NonOwningSymbolStringPtr(Sym));
3150 auto FailedSNs = G.fail(ToFail, GOpRecorder);
3152 for (
auto &SN : FailedSNs) {
3153 for (
auto &[FailJD, Defs] : SN->defs()) {
3154 auto &FailedSymsForFailJD = (*FailedSymbolsMap)[FailJD];
3155 for (
auto &Def : Defs) {
3156 FailedSymsForFailJD.insert(SymbolStringPtr(Def));
3163 for (
auto &Q : FailedQueries)
3166#ifdef EXPENSIVE_CHECKS
3167 verifySessionState(
"exiting ExecutionSession::IL_failSymbols");
3170 return std::make_pair(std::move(FailedQueries), std::move(FailedSymbolsMap));
3176 dbgs() <<
"In " << MR.JD.getName() <<
" failing materialization for "
3177 << MR.SymbolFlags <<
"\n";
3180 if (MR.SymbolFlags.empty())
3184 for (
auto &[Name, Flags] : MR.SymbolFlags)
3185 SymbolsToFail.push_back(Name);
3186 MR.SymbolFlags.clear();
3188 JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3189 std::shared_ptr<SymbolDependenceMap> FailedSymbols;
3193 if (MR.RT->isDefunct())
3194 return std::pair<JITDylib::AsynchronousSymbolQuerySet,
3195 std::shared_ptr<SymbolDependenceMap>>();
3196 return IL_failSymbols(MR.getTargetJITDylib(), SymbolsToFail);
3199 for (
auto &Q : FailedQueries) {
3207 std::unique_ptr<MaterializationUnit> MU) {
3208 for (
auto &KV : MU->getSymbols()) {
3209 assert(MR.SymbolFlags.count(KV.first) &&
3210 "Replacing definition outside this responsibility set");
3211 MR.SymbolFlags.erase(KV.first);
3214 if (MU->getInitializerSymbol() == MR.InitSymbol)
3215 MR.InitSymbol =
nullptr;
3217 LLVM_DEBUG(MR.JD.getExecutionSession().runSessionLocked([&]() {
3218 dbgs() <<
"In " << MR.JD.getName() <<
" replacing symbols with " << *MU
3222 return MR.JD.replace(MR, std::move(MU));
3225Expected<std::unique_ptr<MaterializationResponsibility>>
3229 SymbolStringPtr DelegatedInitSymbol;
3232 for (
auto &Name : Symbols) {
3233 auto I = MR.SymbolFlags.find(Name);
3234 assert(
I != MR.SymbolFlags.end() &&
3235 "Symbol is not tracked by this MaterializationResponsibility "
3238 DelegatedFlags[
Name] = std::move(
I->second);
3239 if (Name == MR.InitSymbol)
3240 std::swap(MR.InitSymbol, DelegatedInitSymbol);
3242 MR.SymbolFlags.erase(
I);
3245 return MR.JD.delegate(MR, std::move(DelegatedFlags),
3246 std::move(DelegatedInitSymbol));
3250void ExecutionSession::dumpDispatchInfo(
Task &
T) {
3252 dbgs() <<
"Dispatching: ";
3253 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< 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 reserve(size_t Size)
Grow the DenseSet so that it can contain at least NumEntries items before resizing again.
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.
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.
LLVM_ABI void lookupAsync(LookupAsyncOnCompleteFn OnComplete) const
unique_function< void(Expected< ExecutorSymbolDef >)> LookupAsyncOnCompleteFn
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.
@ C
The default llvm calling convention, compatible with C.
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...
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 ...
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.
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.
FunctionAddr VTableAddr Count
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...
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.