12#include "llvm/Config/llvm-config.h"
19#include <condition_variable>
23#define DEBUG_TYPE "orc"
41void MaterializationUnit::anchor() {}
44 assert((
reinterpret_cast<uintptr_t
>(JD.get()) & 0x1) == 0 &&
45 "JITDylib must be two byte aligned");
47 JDAndFlag.store(
reinterpret_cast<uintptr_t
>(JD.get()));
63void ResourceTracker::makeDefunct() {
64 uintptr_t Val = JDAndFlag.load();
79 OS <<
"Resource tracker " << (
void *)RT.
get() <<
" became defunct";
83 std::shared_ptr<SymbolStringPool> SSP,
84 std::shared_ptr<SymbolDependenceMap> Symbols)
86 assert(this->SSP &&
"String pool cannot be null");
87 assert(!this->Symbols->empty() &&
"Can not fail to resolve an empty set");
91 for (
auto &[JD, Syms] : *this->Symbols)
96 for (
auto &[JD, Syms] : *Symbols)
105 OS <<
"Failed to materialize symbols: " << *Symbols;
109 std::shared_ptr<SymbolStringPool> SSP,
JITDylibSP JD,
111 std::string Explanation)
113 FailedSymbols(
std::
move(FailedSymbols)), BadDeps(
std::
move(BadDeps)),
114 Explanation(
std::
move(Explanation)) {}
121 OS <<
"In " << JD->getName() <<
", failed to materialize " << FailedSymbols
122 <<
", due to unsatisfied dependencies " << BadDeps;
123 if (!Explanation.empty())
124 OS <<
" (" << Explanation <<
")";
130 for (
auto &
Sym : Symbols)
131 this->Symbols.push_back(
Sym);
132 assert(!this->Symbols.
empty() &&
"Can not fail to resolve an empty set");
138 assert(!this->Symbols.empty() &&
"Can not fail to resolve an empty set");
146 OS <<
"Symbols not found: " << Symbols;
150 std::shared_ptr<SymbolStringPool> SSP,
SymbolNameSet Symbols)
152 assert(!this->Symbols.
empty() &&
"Can not fail to resolve an empty set");
160 OS <<
"Symbols could not be removed: " << Symbols;
182 JD->getExecutionSession().lookup(
185 [OnComplete = std::move(OnComplete)
192 assert(
Result->size() == 1 &&
"Unexpected number of results");
194 "Result does not contain expected symbol");
195 OnComplete(
Result->begin()->second);
197 OnComplete(
Result.takeError());
205 : NotifyComplete(
std::
move(NotifyComplete)), RequiredState(RequiredState) {
207 "Cannot query for a symbols that have not reached the resolve state "
210 OutstandingSymbolsCount = Symbols.size();
212 for (
auto &[
Name, Flags] : Symbols)
220 "Resolving symbol outside the requested set");
222 "Redundantly resolving symbol Name");
226 if (
Sym.getFlags().hasMaterializationSideEffectsOnly())
229 I->second = std::move(
Sym);
230 --OutstandingSymbolsCount;
234 assert(OutstandingSymbolsCount == 0 &&
235 "Symbols remain, handleComplete called prematurely");
237 class RunQueryCompleteTask :
public Task {
239 RunQueryCompleteTask(
SymbolMap ResolvedSymbols,
241 : ResolvedSymbols(
std::
move(ResolvedSymbols)),
242 NotifyComplete(
std::
move(NotifyComplete)) {}
244 OS <<
"Execute query complete callback for " << ResolvedSymbols;
246 void run()
override { NotifyComplete(std::move(ResolvedSymbols)); }
253 auto T = std::make_unique<RunQueryCompleteTask>(std::move(ResolvedSymbols),
254 std::move(NotifyComplete));
259void AsynchronousSymbolQuery::handleFailed(Error Err) {
261 OutstandingSymbolsCount == 0 &&
262 "Query should already have been abandoned");
263 NotifyComplete(std::move(Err));
267void AsynchronousSymbolQuery::addQueryDependence(JITDylib &JD,
268 SymbolStringPtr
Name) {
271 assert(Added &&
"Duplicate dependence notification?");
274void AsynchronousSymbolQuery::removeQueryDependence(
275 JITDylib &JD,
const SymbolStringPtr &
Name) {
276 auto QRI = QueryRegistrations.
find(&JD);
277 assert(QRI != QueryRegistrations.
end() &&
278 "No dependencies registered for JD");
279 assert(QRI->second.count(
Name) &&
"No dependency on Name in JD");
280 QRI->second.erase(
Name);
281 if (QRI->second.empty())
282 QueryRegistrations.
erase(QRI);
285void AsynchronousSymbolQuery::dropSymbol(
const SymbolStringPtr &
Name) {
288 "Redundant removal of weakly-referenced symbol");
290 --OutstandingSymbolsCount;
293void AsynchronousSymbolQuery::detach() {
294 ResolvedSymbols.
clear();
295 OutstandingSymbolsCount = 0;
296 for (
auto &[JD, Syms] : QueryRegistrations)
297 JD->detachQueryHelper(*
this, Syms);
298 QueryRegistrations.clear();
305 SourceJDLookupFlags(SourceJDLookupFlags), Aliases(
std::
move(Aliases)) {}
308 return "<Reexports>";
311void ReExportsMaterializationUnit::materialize(
312 std::unique_ptr<MaterializationResponsibility> R) {
314 auto &ES = R->getTargetJITDylib().getExecutionSession();
315 JITDylib &TgtJD = R->getTargetJITDylib();
316 JITDylib &SrcJD = SourceJD ? *SourceJD : TgtJD;
321 auto RequestedSymbols = R->getRequestedSymbols();
324 for (
auto &
Name : RequestedSymbols) {
326 assert(
I != Aliases.
end() &&
"Symbol not found in aliases map?");
327 RequestedAliases[
Name] = std::move(
I->second);
333 dbgs() <<
"materializing reexports: target = " << TgtJD.
getName()
334 <<
", source = " << SrcJD.
getName() <<
" " << RequestedAliases
339 if (!Aliases.
empty()) {
340 auto Err = SourceJD ?
R->replace(
reexports(*SourceJD, std::move(Aliases),
341 SourceJDLookupFlags))
348 R->failMaterialization();
355 struct OnResolveInfo {
356 OnResolveInfo(std::unique_ptr<MaterializationResponsibility> R,
357 SymbolAliasMap Aliases)
360 std::unique_ptr<MaterializationResponsibility>
R;
362 std::vector<SymbolDependenceGroup> SDGs;
373 std::vector<std::pair<SymbolLookupSet, std::shared_ptr<OnResolveInfo>>>
375 while (!RequestedAliases.
empty()) {
377 SymbolLookupSet QuerySymbols;
381 for (
auto &KV : RequestedAliases) {
383 if (&SrcJD == &TgtJD && (QueryAliases.count(KV.second.Aliasee) ||
384 RequestedAliases.count(KV.second.Aliasee)))
387 ResponsibilitySymbols.
insert(KV.first);
388 QuerySymbols.add(KV.second.Aliasee,
389 KV.second.AliasFlags.hasMaterializationSideEffectsOnly()
392 QueryAliases[KV.first] = std::move(KV.second);
396 for (
auto &KV : QueryAliases)
397 RequestedAliases.erase(KV.first);
399 assert(!QuerySymbols.empty() &&
"Alias cycle detected!");
401 auto NewR =
R->delegate(ResponsibilitySymbols);
404 R->failMaterialization();
408 auto QueryInfo = std::make_shared<OnResolveInfo>(std::move(*NewR),
409 std::move(QueryAliases));
410 QueryInfos.push_back(
411 make_pair(std::move(QuerySymbols), std::move(QueryInfo)));
415 while (!QueryInfos.empty()) {
416 auto QuerySymbols = std::move(QueryInfos.back().first);
417 auto QueryInfo = std::move(QueryInfos.back().second);
419 QueryInfos.pop_back();
421 auto RegisterDependencies = [QueryInfo,
428 assert(Deps.size() == 1 && Deps.count(&SrcJD) &&
429 "Unexpected dependencies for reexports");
431 auto &SrcJDDeps = Deps.find(&SrcJD)->second;
433 for (
auto &[Alias, AliasInfo] : QueryInfo->Aliases)
434 if (SrcJDDeps.count(AliasInfo.Aliasee))
435 QueryInfo->SDGs.push_back({{Alias}, {{&SrcJD, {AliasInfo.Aliasee}}}});
438 auto OnComplete = [QueryInfo](Expected<SymbolMap>
Result) {
439 auto &ES = QueryInfo->R->getTargetJITDylib().getExecutionSession();
442 for (
auto &KV : QueryInfo->Aliases) {
443 assert((KV.second.AliasFlags.hasMaterializationSideEffectsOnly() ||
444 Result->count(KV.second.Aliasee)) &&
445 "Result map missing entry?");
447 if (KV.second.AliasFlags.hasMaterializationSideEffectsOnly())
450 ResolutionMap[KV.first] = {(*Result)[KV.second.Aliasee].getAddress(),
451 KV.second.AliasFlags};
453 if (
auto Err = QueryInfo->R->notifyResolved(ResolutionMap)) {
455 QueryInfo->R->failMaterialization();
458 if (
auto Err = QueryInfo->R->notifyEmitted(QueryInfo->SDGs)) {
460 QueryInfo->R->failMaterialization();
465 QueryInfo->R->failMaterialization();
472 std::move(RegisterDependencies));
476void ReExportsMaterializationUnit::discard(
const JITDylib &JD,
477 const SymbolStringPtr &
Name) {
479 "Symbol not covered by this MaterializationUnit");
483MaterializationUnit::Interface
484ReExportsMaterializationUnit::extractFlags(
const SymbolAliasMap &Aliases) {
486 for (
auto &KV : Aliases)
489 return MaterializationUnit::Interface(std::move(
SymbolFlags),
nullptr);
500 return Flags.takeError();
503 for (
auto &
Name : Symbols) {
504 assert(Flags->count(
Name) &&
"Missing entry in flags map");
523 virtual void complete(std::unique_ptr<InProgressLookupState> IPLS) = 0;
551 OnComplete(
std::
move(OnComplete)) {}
553 void complete(std::unique_ptr<InProgressLookupState> IPLS)
override {
554 auto &ES =
SearchOrder.front().first->getExecutionSession();
555 ES.OL_completeLookupFlags(std::move(IPLS), std::move(OnComplete));
558 void fail(
Error Err)
override { OnComplete(std::move(Err)); }
569 std::shared_ptr<AsynchronousSymbolQuery> Q,
573 Q(
std::
move(Q)), RegisterDependencies(
std::
move(RegisterDependencies)) {
576 void complete(std::unique_ptr<InProgressLookupState> IPLS)
override {
577 auto &ES =
SearchOrder.front().first->getExecutionSession();
578 ES.OL_completeLookup(std::move(IPLS), std::move(Q),
579 std::move(RegisterDependencies));
584 Q->handleFailed(std::move(Err));
588 std::shared_ptr<AsynchronousSymbolQuery> Q;
595 : SourceJD(SourceJD), SourceJDLookupFlags(SourceJDLookupFlags),
602 assert(&JD != &SourceJD &&
"Cannot re-export from the same dylib");
606 K, {{&SourceJD, JDLookupFlags}}, LookupSet);
608 return Flags.takeError();
612 for (
auto &KV : *Flags)
613 if (!Allow || Allow(KV.first))
616 if (AliasMap.empty())
626void LookupState::reset(InProgressLookupState *IPLS) { this->IPLS.reset(IPLS); }
634 assert(IPLS &&
"Cannot call continueLookup on empty LookupState");
635 auto &ES = IPLS->SearchOrder.begin()->first->getExecutionSession();
636 ES.OL_applyQueryPhase1(std::move(IPLS), std::move(Err));
640 std::deque<LookupState> LookupsToFail;
642 std::lock_guard<std::mutex> Lock(M);
643 std::swap(PendingLookups, LookupsToFail);
647 for (
auto &LS : LookupsToFail)
648 LS.continueLookup(make_error<StringError>(
649 "Query waiting on DefinitionGenerator that was destroyed",
658 std::vector<ResourceTrackerSP> TrackersToRemove;
660 assert(State != Closed &&
"JD is defunct");
661 for (
auto &KV : TrackerSymbols)
662 TrackersToRemove.push_back(KV.first);
667 for (
auto &RT : TrackersToRemove)
668 Err =
joinErrors(std::move(Err), RT->remove());
674 assert(State != Closed &&
"JD is defunct");
677 return DefaultTracker;
683 assert(State == Open &&
"JD is defunct");
692 std::shared_ptr<DefinitionGenerator> TmpDG;
695 assert(State == Open &&
"JD is defunct");
697 [&](
const std::shared_ptr<DefinitionGenerator> &
H) {
698 return H.get() == &
G;
700 assert(
I != DefGenerators.end() &&
"Generator not found");
701 TmpDG = std::move(*
I);
702 DefGenerators.erase(
I);
711 if (FromMR.RT->isDefunct())
712 return make_error<ResourceTrackerDefunct>(FromMR.RT);
714 std::vector<NonOwningSymbolStringPtr> AddedSyms;
715 std::vector<NonOwningSymbolStringPtr> RejectedWeakDefs;
717 for (
auto SFItr = SymbolFlags.begin(), SFEnd = SymbolFlags.end();
718 SFItr != SFEnd; ++SFItr) {
720 auto &Name = SFItr->first;
721 auto &Flags = SFItr->second;
723 auto EntryItr = Symbols.find(Name);
726 if (EntryItr != Symbols.end()) {
729 if (!Flags.isWeak()) {
731 for (auto &S : AddedSyms)
732 Symbols.erase(Symbols.find_as(S));
735 return make_error<DuplicateDefinition>(std::string(*Name));
739 RejectedWeakDefs.push_back(NonOwningSymbolStringPtr(Name));
750 while (!RejectedWeakDefs.empty()) {
751 SymbolFlags.erase(SymbolFlags.find_as(RejectedWeakDefs.back()));
752 RejectedWeakDefs.pop_back();
759Error JITDylib::replace(MaterializationResponsibility &FromMR,
760 std::unique_ptr<MaterializationUnit> MU) {
761 assert(MU !=
nullptr &&
"Can not replace with a null MaterializationUnit");
762 std::unique_ptr<MaterializationUnit> MustRunMU;
763 std::unique_ptr<MaterializationResponsibility> MustRunMR;
767 if (FromMR.RT->isDefunct())
768 return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
771 for (
auto &KV : MU->getSymbols()) {
772 auto SymI = Symbols.find(KV.first);
773 assert(SymI != Symbols.end() &&
"Replacing unknown symbol");
774 assert(SymI->second.getState() == SymbolState::Materializing &&
775 "Can not replace a symbol that ha is not materializing");
776 assert(!SymI->second.hasMaterializerAttached() &&
777 "Symbol should not have materializer attached already");
778 assert(UnmaterializedInfos.count(KV.first) == 0 &&
779 "Symbol being replaced should have no UnmaterializedInfo");
787 for (
auto &KV : MU->getSymbols()) {
788 auto MII = MaterializingInfos.find(KV.first);
789 if (MII != MaterializingInfos.end()) {
790 if (MII->second.hasQueriesPending()) {
791 MustRunMR = ES.createMaterializationResponsibility(
792 *FromMR.RT, std::move(MU->SymbolFlags),
793 std::move(MU->InitSymbol));
794 MustRunMU = std::move(MU);
795 return Error::success();
801 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU),
803 for (
auto &KV : UMI->MU->getSymbols()) {
804 auto SymI = Symbols.find(KV.first);
805 assert(SymI->second.getState() == SymbolState::Materializing &&
806 "Can not replace a symbol that is not materializing");
807 assert(!SymI->second.hasMaterializerAttached() &&
808 "Can not replace a symbol that has a materializer attached");
809 assert(UnmaterializedInfos.count(KV.first) == 0 &&
810 "Unexpected materializer entry in map");
811 SymI->second.setAddress(SymI->second.getAddress());
812 SymI->second.setMaterializerAttached(
true);
814 auto &UMIEntry = UnmaterializedInfos[KV.first];
815 assert((!UMIEntry || !UMIEntry->MU) &&
816 "Replacing symbol with materializer still attached");
827 assert(MustRunMR &&
"MustRunMU set implies MustRunMR set");
829 std::move(MustRunMU), std::move(MustRunMR)));
831 assert(!MustRunMR &&
"MustRunMU unset implies MustRunMR unset");
837Expected<std::unique_ptr<MaterializationResponsibility>>
838JITDylib::delegate(MaterializationResponsibility &FromMR,
839 SymbolFlagsMap SymbolFlags, SymbolStringPtr InitSymbol) {
842 [&]() -> Expected<std::unique_ptr<MaterializationResponsibility>> {
843 if (FromMR.RT->isDefunct())
844 return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
846 return ES.createMaterializationResponsibility(
847 *FromMR.RT, std::move(SymbolFlags), std::move(InitSymbol));
852JITDylib::getRequestedSymbols(
const SymbolFlagsMap &SymbolFlags)
const {
856 for (
auto &KV : SymbolFlags) {
857 assert(Symbols.count(KV.first) &&
"JITDylib does not cover this symbol?");
858 assert(Symbols.find(KV.first)->second.getState() !=
859 SymbolState::NeverSearched &&
860 Symbols.find(KV.first)->second.getState() != SymbolState::Ready &&
861 "getRequestedSymbols can only be called for symbols that have "
862 "started materializing");
863 auto I = MaterializingInfos.find(KV.first);
864 if (
I == MaterializingInfos.end())
867 if (
I->second.hasQueriesPending())
868 RequestedSymbols.insert(KV.first);
871 return RequestedSymbols;
875Error JITDylib::resolve(MaterializationResponsibility &MR,
876 const SymbolMap &Resolved) {
877 AsynchronousSymbolQuerySet CompletedQueries;
880 if (MR.RT->isDefunct())
881 return make_error<ResourceTrackerDefunct>(MR.RT);
884 return make_error<StringError>(
"JITDylib " + getName() +
886 inconvertibleErrorCode());
888 struct WorklistEntry {
889 SymbolTable::iterator SymI;
890 ExecutorSymbolDef ResolvedSym;
893 SymbolNameSet SymbolsInErrorState;
894 std::vector<WorklistEntry> Worklist;
898 for (
const auto &KV : Resolved) {
900 assert(!KV.second.getFlags().hasError() &&
901 "Resolution result can not have error flag set");
903 auto SymI = Symbols.find(KV.first);
905 assert(SymI != Symbols.end() &&
"Symbol not found");
906 assert(!SymI->second.hasMaterializerAttached() &&
907 "Resolving symbol with materializer attached?");
908 assert(SymI->second.getState() == SymbolState::Materializing &&
909 "Symbol should be materializing");
910 assert(SymI->second.getAddress() == ExecutorAddr() &&
911 "Symbol has already been resolved");
913 if (SymI->second.getFlags().hasError())
914 SymbolsInErrorState.insert(KV.first);
916 if (SymI->second.getFlags() & JITSymbolFlags::Common) {
917 [[maybe_unused]]
auto WeakOrCommon =
918 JITSymbolFlags::Weak | JITSymbolFlags::Common;
919 assert((KV.second.getFlags() & WeakOrCommon) &&
920 "Common symbols must be resolved as common or weak");
921 assert((KV.second.getFlags() & ~WeakOrCommon) ==
922 (SymI->second.getFlags() & ~JITSymbolFlags::Common) &&
923 "Resolving symbol with incorrect flags");
926 assert(KV.second.getFlags() == SymI->second.getFlags() &&
927 "Resolved flags should match the declared flags");
930 {SymI, {KV.second.getAddress(), SymI->second.getFlags()}});
935 if (!SymbolsInErrorState.empty()) {
936 auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
937 (*FailedSymbolsDepMap)[
this] = std::move(SymbolsInErrorState);
938 return make_error<FailedToMaterialize>(
939 getExecutionSession().getSymbolStringPool(),
940 std::move(FailedSymbolsDepMap));
943 while (!Worklist.empty()) {
944 auto SymI = Worklist.back().SymI;
945 auto ResolvedSym = Worklist.back().ResolvedSym;
948 auto &
Name = SymI->first;
951 JITSymbolFlags ResolvedFlags = ResolvedSym.getFlags();
952 SymI->second.setAddress(ResolvedSym.getAddress());
953 SymI->second.setFlags(ResolvedFlags);
954 SymI->second.setState(SymbolState::Resolved);
956 auto MII = MaterializingInfos.find(
Name);
957 if (MII == MaterializingInfos.end())
960 auto &
MI = MII->second;
961 for (
auto &Q :
MI.takeQueriesMeeting(SymbolState::Resolved)) {
962 Q->notifySymbolMetRequiredState(
Name, ResolvedSym);
964 CompletedQueries.insert(std::move(Q));
968 return Error::success();
973 for (
auto &Q : CompletedQueries) {
974 assert(Q->isComplete() &&
"Q not completed");
975 Q->handleComplete(ES);
978 return Error::success();
981void JITDylib::unlinkMaterializationResponsibility(
982 MaterializationResponsibility &MR) {
984 auto I = TrackerMRs.find(MR.RT.get());
985 assert(
I != TrackerMRs.end() &&
"No MRs in TrackerMRs list for RT");
986 assert(
I->second.count(&MR) &&
"MR not in TrackerMRs list for RT");
987 I->second.erase(&MR);
988 if (
I->second.empty())
989 TrackerMRs.erase(MR.RT.get());
993void JITDylib::shrinkMaterializationInfoMemory() {
997 if (UnmaterializedInfos.empty())
998 UnmaterializedInfos.clear();
1000 if (MaterializingInfos.empty())
1001 MaterializingInfos.clear();
1005 bool LinkAgainstThisJITDylibFirst) {
1007 assert(State == Open &&
"JD is defunct");
1008 if (LinkAgainstThisJITDylibFirst) {
1010 if (NewLinkOrder.empty() || NewLinkOrder.front().first !=
this)
1011 LinkOrder.push_back(
1012 std::make_pair(
this, JITDylibLookupFlags::MatchAllSymbols));
1015 LinkOrder = std::move(NewLinkOrder);
1021 for (
auto &KV : NewLinks) {
1026 LinkOrder.push_back(std::move(KV));
1038 assert(State == Open &&
"JD is defunct");
1039 for (
auto &KV : LinkOrder)
1040 if (KV.first == &OldJD) {
1041 KV = {&NewJD, JDLookupFlags};
1049 assert(State == Open &&
"JD is defunct");
1051 [&](
const JITDylibSearchOrder::value_type &KV) {
1052 return KV.first == &JD;
1054 if (
I != LinkOrder.end())
1061 assert(State == Open &&
"JD is defunct");
1062 using SymbolMaterializerItrPair =
1063 std::pair<SymbolTable::iterator, UnmaterializedInfosMap::iterator>;
1064 std::vector<SymbolMaterializerItrPair> SymbolsToRemove;
1068 for (
auto &
Name : Names) {
1069 auto I = Symbols.find(
Name);
1072 if (
I == Symbols.end()) {
1073 Missing.insert(
Name);
1078 if (
I->second.getState() != SymbolState::NeverSearched &&
1079 I->second.getState() != SymbolState::Ready) {
1084 auto UMII =
I->second.hasMaterializerAttached()
1085 ? UnmaterializedInfos.find(
Name)
1086 : UnmaterializedInfos.end();
1087 SymbolsToRemove.push_back(std::make_pair(
I, UMII));
1091 if (!Missing.empty())
1093 std::move(Missing));
1101 for (
auto &SymbolMaterializerItrPair : SymbolsToRemove) {
1102 auto UMII = SymbolMaterializerItrPair.second;
1105 if (UMII != UnmaterializedInfos.end()) {
1106 UMII->second->MU->doDiscard(*
this, UMII->first);
1107 UnmaterializedInfos.erase(UMII);
1110 auto SymI = SymbolMaterializerItrPair.first;
1111 Symbols.erase(SymI);
1114 shrinkMaterializationInfoMemory();
1116 return Error::success();
1122 OS <<
"JITDylib \"" <<
getName() <<
"\" (ES: "
1123 <<
format(
"0x%016" PRIx64,
reinterpret_cast<uintptr_t
>(&ES))
1137 if (State == Closed)
1139 OS <<
"Link order: " << LinkOrder <<
"\n"
1140 <<
"Symbol table:\n";
1143 std::vector<std::pair<SymbolStringPtr, SymbolTableEntry *>> SymbolsSorted;
1144 for (
auto &KV : Symbols)
1145 SymbolsSorted.emplace_back(KV.first, &KV.second);
1146 std::sort(SymbolsSorted.begin(), SymbolsSorted.end(),
1147 [](
const auto &L,
const auto &R) { return *L.first < *R.first; });
1149 for (
auto &KV : SymbolsSorted) {
1150 OS <<
" \"" << *KV.first <<
"\": ";
1151 if (
auto Addr = KV.second->getAddress())
1154 OS <<
"<not resolved> ";
1156 OS <<
" " << KV.second->getFlags() <<
" " << KV.second->getState();
1158 if (KV.second->hasMaterializerAttached()) {
1159 OS <<
" (Materializer ";
1160 auto I = UnmaterializedInfos.find(KV.first);
1161 assert(
I != UnmaterializedInfos.end() &&
1162 "Lazy symbol should have UnmaterializedInfo");
1163 OS <<
I->second->MU.get() <<
", " <<
I->second->MU->getName() <<
")\n";
1168 if (!MaterializingInfos.empty())
1169 OS <<
" MaterializingInfos entries:\n";
1170 for (
auto &KV : MaterializingInfos) {
1171 OS <<
" \"" << *KV.first <<
"\":\n"
1172 <<
" " << KV.second.pendingQueries().size()
1173 <<
" pending queries: { ";
1174 for (
const auto &Q : KV.second.pendingQueries())
1175 OS << Q.get() <<
" (" << Q->getRequiredState() <<
") ";
1176 OS <<
"}\n Defining EDU: ";
1177 if (KV.second.DefiningEDU) {
1178 OS << KV.second.DefiningEDU.get() <<
" { ";
1179 for (
auto &[
Name, Flags] : KV.second.DefiningEDU->Symbols)
1182 OS <<
" Dependencies:\n";
1183 if (!KV.second.DefiningEDU->Dependencies.empty()) {
1184 for (
auto &[DepJD, Deps] : KV.second.DefiningEDU->Dependencies) {
1185 OS <<
" " << DepJD->getName() <<
": [ ";
1186 for (
auto &Dep : Deps)
1194 OS <<
" Dependant EDUs:\n";
1195 if (!KV.second.DependantEDUs.empty()) {
1196 for (
auto &DependantEDU : KV.second.DependantEDUs) {
1197 OS <<
" " << DependantEDU <<
": "
1198 << DependantEDU->JD->getName() <<
" { ";
1199 for (
auto &[
Name, Flags] : DependantEDU->Symbols)
1205 assert((Symbols[KV.first].getState() != SymbolState::Ready ||
1206 (KV.second.pendingQueries().empty() && !KV.second.DefiningEDU &&
1207 !KV.second.DependantEDUs.empty())) &&
1208 "Stale materializing info entry");
1213void JITDylib::MaterializingInfo::addQuery(
1214 std::shared_ptr<AsynchronousSymbolQuery> Q) {
1218 [](
const std::shared_ptr<AsynchronousSymbolQuery> &V,
SymbolState S) {
1219 return V->getRequiredState() <= S;
1221 PendingQueries.insert(
I.base(), std::move(Q));
1224void JITDylib::MaterializingInfo::removeQuery(
1225 const AsynchronousSymbolQuery &Q) {
1228 PendingQueries, [&Q](
const std::shared_ptr<AsynchronousSymbolQuery> &V) {
1229 return V.get() == &Q;
1231 if (
I != PendingQueries.end())
1232 PendingQueries.erase(
I);
1235JITDylib::AsynchronousSymbolQueryList
1236JITDylib::MaterializingInfo::takeQueriesMeeting(SymbolState RequiredState) {
1237 AsynchronousSymbolQueryList
Result;
1238 while (!PendingQueries.empty()) {
1239 if (PendingQueries.back()->getRequiredState() > RequiredState)
1242 Result.push_back(std::move(PendingQueries.back()));
1243 PendingQueries.pop_back();
1249JITDylib::JITDylib(ExecutionSession &ES, std::string
Name)
1254std::pair<JITDylib::AsynchronousSymbolQuerySet,
1255 std::shared_ptr<SymbolDependenceMap>>
1256JITDylib::IL_removeTracker(ResourceTracker &RT) {
1258 assert(State != Closed &&
"JD is defunct");
1263 if (&RT == DefaultTracker.
get()) {
1265 for (
auto &KV : TrackerSymbols)
1266 for (
auto &
Sym : KV.second)
1269 for (
auto &KV : Symbols) {
1270 auto &
Sym = KV.first;
1271 if (!TrackedSymbols.count(
Sym))
1272 SymbolsToRemove.push_back(
Sym);
1275 DefaultTracker.
reset();
1278 auto I = TrackerSymbols.find(&RT);
1279 if (
I != TrackerSymbols.end()) {
1280 SymbolsToRemove = std::move(
I->second);
1281 TrackerSymbols.erase(
I);
1286 for (
auto &
Sym : SymbolsToRemove) {
1287 assert(Symbols.count(
Sym) &&
"Symbol not in symbol table");
1290 auto MII = MaterializingInfos.
find(
Sym);
1291 if (MII != MaterializingInfos.
end())
1292 SymbolsToFail.push_back(
Sym);
1295 auto Result = ES.IL_failSymbols(*
this, std::move(SymbolsToFail));
1298 for (
auto &
Sym : SymbolsToRemove) {
1299 auto I = Symbols.find(
Sym);
1300 assert(
I != Symbols.end() &&
"Symbol not present in table");
1303 if (
I->second.hasMaterializerAttached()) {
1308 "Symbol has materializer attached");
1314 shrinkMaterializationInfoMemory();
1319void JITDylib::transferTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT) {
1320 assert(State != Closed &&
"JD is defunct");
1321 assert(&DstRT != &SrcRT &&
"No-op transfers shouldn't call transferTracker");
1322 assert(&DstRT.getJITDylib() ==
this &&
"DstRT is not for this JITDylib");
1323 assert(&SrcRT.getJITDylib() ==
this &&
"SrcRT is not for this JITDylib");
1326 for (
auto &KV : UnmaterializedInfos) {
1327 if (KV.second->RT == &SrcRT)
1328 KV.second->RT = &DstRT;
1333 auto I = TrackerMRs.find(&SrcRT);
1334 if (
I != TrackerMRs.end()) {
1335 auto &SrcMRs =
I->second;
1336 auto &DstMRs = TrackerMRs[&DstRT];
1337 for (
auto *MR : SrcMRs)
1340 DstMRs = std::move(SrcMRs);
1342 for (
auto *MR : SrcMRs)
1346 TrackerMRs.erase(&SrcRT);
1352 if (&DstRT == DefaultTracker.
get()) {
1353 TrackerSymbols.erase(&SrcRT);
1359 if (&SrcRT == DefaultTracker.
get()) {
1360 assert(!TrackerSymbols.count(&SrcRT) &&
1361 "Default tracker should not appear in TrackerSymbols");
1366 for (
auto &KV : TrackerSymbols)
1367 for (
auto &
Sym : KV.second)
1370 for (
auto &KV : Symbols) {
1371 auto &
Sym = KV.first;
1372 if (!CurrentlyTrackedSymbols.count(
Sym))
1373 SymbolsToTrack.push_back(
Sym);
1376 TrackerSymbols[&DstRT] = std::move(SymbolsToTrack);
1380 auto &DstTrackedSymbols = TrackerSymbols[&DstRT];
1384 auto SI = TrackerSymbols.find(&SrcRT);
1385 if (SI == TrackerSymbols.end())
1388 DstTrackedSymbols.reserve(DstTrackedSymbols.size() +
SI->second.size());
1389 for (
auto &
Sym :
SI->second)
1390 DstTrackedSymbols.push_back(std::move(
Sym));
1391 TrackerSymbols.erase(SI);
1394Error JITDylib::defineImpl(MaterializationUnit &MU) {
1398 std::vector<SymbolStringPtr> ExistingDefsOverridden;
1399 std::vector<SymbolStringPtr> MUDefsOverridden;
1401 for (
const auto &KV : MU.getSymbols()) {
1402 auto I = Symbols.find(KV.first);
1404 if (
I != Symbols.end()) {
1405 if (KV.second.isStrong()) {
1406 if (
I->second.getFlags().isStrong() ||
1408 Duplicates.insert(KV.first);
1411 "Overridden existing def should be in the never-searched "
1413 ExistingDefsOverridden.push_back(KV.first);
1416 MUDefsOverridden.push_back(KV.first);
1421 if (!Duplicates.empty()) {
1423 {
dbgs() <<
" Error: Duplicate symbols " << Duplicates <<
"\n"; });
1424 return make_error<DuplicateDefinition>(std::string(**Duplicates.begin()));
1429 if (!MUDefsOverridden.empty())
1430 dbgs() <<
" Defs in this MU overridden: " << MUDefsOverridden <<
"\n";
1432 for (
auto &S : MUDefsOverridden)
1433 MU.doDiscard(*
this, S);
1437 if (!ExistingDefsOverridden.empty())
1438 dbgs() <<
" Existing defs overridden by this MU: " << MUDefsOverridden
1441 for (
auto &S : ExistingDefsOverridden) {
1443 auto UMII = UnmaterializedInfos.find(S);
1444 assert(UMII != UnmaterializedInfos.end() &&
1445 "Overridden existing def should have an UnmaterializedInfo");
1446 UMII->second->MU->doDiscard(*
this, S);
1450 for (
auto &KV : MU.getSymbols()) {
1451 auto &SymEntry = Symbols[KV.first];
1452 SymEntry.setFlags(KV.second);
1454 SymEntry.setMaterializerAttached(
true);
1460void JITDylib::installMaterializationUnit(
1461 std::unique_ptr<MaterializationUnit> MU, ResourceTracker &RT) {
1464 if (&RT != DefaultTracker.
get()) {
1465 auto &TS = TrackerSymbols[&RT];
1466 TS.reserve(TS.size() + MU->getSymbols().size());
1467 for (
auto &KV : MU->getSymbols())
1468 TS.push_back(KV.first);
1471 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU), &RT);
1472 for (
auto &KV : UMI->MU->getSymbols())
1473 UnmaterializedInfos[KV.first] = UMI;
1476void JITDylib::detachQueryHelper(AsynchronousSymbolQuery &Q,
1478 for (
auto &QuerySymbol : QuerySymbols) {
1479 auto MII = MaterializingInfos.
find(QuerySymbol);
1480 if (MII != MaterializingInfos.
end())
1481 MII->second.removeQuery(Q);
1493 std::mutex LookupMutex;
1494 std::condition_variable CV;
1498 dbgs() <<
"Issuing init-symbol lookup:\n";
1499 for (
auto &KV : InitSyms)
1500 dbgs() <<
" " << KV.first->getName() <<
": " << KV.second <<
"\n";
1503 for (
auto &KV : InitSyms) {
1504 auto *JD = KV.first;
1505 auto Names = std::move(KV.second);
1512 std::lock_guard<std::mutex> Lock(LookupMutex);
1516 "Duplicate JITDylib in lookup?");
1517 CompoundResult[JD] = std::move(*
Result);
1527 std::unique_lock<std::mutex> Lock(LookupMutex);
1528 CV.wait(Lock, [&] {
return Count == 0 || CompoundErr; });
1531 return std::move(CompoundErr);
1533 return std::move(CompoundResult);
1540 class TriggerOnComplete {
1543 TriggerOnComplete(OnCompleteFn OnComplete)
1544 : OnComplete(std::move(OnComplete)) {}
1545 ~TriggerOnComplete() { OnComplete(std::move(LookupResult)); }
1546 void reportResult(
Error Err) {
1547 std::lock_guard<std::mutex> Lock(ResultMutex);
1548 LookupResult =
joinErrors(std::move(LookupResult), std::move(Err));
1552 std::mutex ResultMutex;
1553 Error LookupResult{Error::success()};
1554 OnCompleteFn OnComplete;
1558 dbgs() <<
"Issuing init-symbol lookup:\n";
1559 for (
auto &KV : InitSyms)
1560 dbgs() <<
" " << KV.first->getName() <<
": " << KV.second <<
"\n";
1563 auto TOC = std::make_shared<TriggerOnComplete>(std::move(OnComplete));
1565 for (
auto &KV : InitSyms) {
1566 auto *JD = KV.first;
1567 auto Names = std::move(KV.second);
1573 TOC->reportResult(
Result.takeError());
1580 OS <<
"Materialization task: " << MU->getName() <<
" in "
1581 << MR->getTargetJITDylib().getName();
1593 this->EPC->ES =
this;
1599 "Session still open. Did you forget to call endSession?");
1603 LLVM_DEBUG(
dbgs() <<
"Ending ExecutionSession " <<
this <<
"\n");
1607#ifdef EXPENSIVE_CHECKS
1608 verifySessionState(
"Entering ExecutionSession::endSession");
1611 SessionOpen =
false;
1615 std::reverse(JDsToRemove.begin(), JDsToRemove.end());
1619 Err =
joinErrors(std::move(Err), EPC->disconnect());
1630 assert(!ResourceManagers.empty() &&
"No managers registered");
1631 if (ResourceManagers.back() == &RM)
1632 ResourceManagers.pop_back();
1635 assert(
I != ResourceManagers.end() &&
"RM not registered");
1636 ResourceManagers.erase(
I);
1643 for (
auto &JD : JDs)
1644 if (JD->getName() ==
Name)
1653 assert(SessionOpen &&
"Cannot create JITDylib after session is closed");
1662 if (
auto Err = P->setupJITDylib(JD))
1663 return std::move(Err);
1670 for (
auto &JD : JDsToRemove) {
1671 assert(JD->State == JITDylib::Open &&
"JD already closed");
1672 JD->State = JITDylib::Closing;
1674 assert(
I != JDs.end() &&
"JD does not appear in session JDs");
1681 for (
auto JD : JDsToRemove) {
1682 Err =
joinErrors(std::move(Err), JD->clear());
1684 Err =
joinErrors(std::move(Err), P->teardownJITDylib(*JD));
1689 for (
auto &JD : JDsToRemove) {
1690 assert(JD->State == JITDylib::Closing &&
"JD should be closing");
1691 JD->State = JITDylib::Closed;
1692 assert(JD->Symbols.empty() &&
"JD.Symbols is not empty after clear");
1693 assert(JD->UnmaterializedInfos.empty() &&
1694 "JD.UnmaterializedInfos is not empty after clear");
1695 assert(JD->MaterializingInfos.empty() &&
1696 "JD.MaterializingInfos is not empty after clear");
1697 assert(JD->TrackerSymbols.empty() &&
1698 "TrackerSymbols is not empty after clear");
1699 JD->DefGenerators.clear();
1700 JD->LinkOrder.clear();
1710 return std::vector<JITDylibSP>();
1712 auto &ES = JDs.
front()->getExecutionSession();
1713 return ES.runSessionLocked([&]() ->
Expected<std::vector<JITDylibSP>> {
1715 std::vector<JITDylibSP>
Result;
1717 for (
auto &JD : JDs) {
1719 if (JD->State != Open)
1720 return make_error<StringError>(
1721 "Error building link order: " + JD->getName() +
" is defunct",
1723 if (Visited.
count(JD.get()))
1728 Visited.
insert(JD.get());
1730 while (!WorkStack.empty()) {
1731 Result.push_back(std::move(WorkStack.back()));
1732 WorkStack.pop_back();
1734 for (auto &KV : llvm::reverse(Result.back()->LinkOrder)) {
1735 auto &JD = *KV.first;
1736 if (!Visited.insert(&JD).second)
1738 WorkStack.push_back(&JD);
1766 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
1767 K, std::move(SearchOrder), std::move(LookupSet),
1768 std::move(OnComplete)),
1776 std::promise<MSVCPExpected<SymbolFlagsMap>> ResultP;
1777 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
1778 K, std::move(SearchOrder), std::move(LookupSet),
1780 ResultP.set_value(std::move(
Result));
1784 auto ResultF = ResultP.get_future();
1785 return ResultF.get();
1796 dbgs() <<
"Looking up " << Symbols <<
" in " << SearchOrder
1797 <<
" (required state: " << RequiredState <<
")\n";
1804 dispatchOutstandingMUs();
1806 auto Unresolved = std::move(Symbols);
1807 auto Q = std::make_shared<AsynchronousSymbolQuery>(Unresolved, RequiredState,
1808 std::move(NotifyComplete));
1810 auto IPLS = std::make_unique<InProgressFullLookupState>(
1811 K, SearchOrder, std::move(Unresolved), RequiredState, std::move(Q),
1812 std::move(RegisterDependencies));
1822#if LLVM_ENABLE_THREADS
1824 std::promise<SymbolMap> PromisedResult;
1829 PromisedResult.set_value(std::move(*R));
1832 ResolutionError = R.takeError();
1846 ResolutionError = R.takeError();
1851 lookup(K, SearchOrder, std::move(Symbols), RequiredState, NotifyComplete,
1852 RegisterDependencies);
1854#if LLVM_ENABLE_THREADS
1855 auto ResultFuture = PromisedResult.get_future();
1856 auto Result = ResultFuture.get();
1858 if (ResolutionError)
1859 return std::move(ResolutionError);
1861 return std::move(
Result);
1864 if (ResolutionError)
1865 return std::move(ResolutionError);
1878 assert(ResultMap->size() == 1 &&
"Unexpected number of results");
1879 assert(ResultMap->count(
Name) &&
"Missing result for symbol");
1880 return std::move(ResultMap->begin()->second);
1882 return ResultMap.takeError();
1904 return TagSyms.takeError();
1907 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
1910 for (
auto &[TagName, TagSym] : *TagSyms) {
1911 auto TagAddr = TagSym.getAddress();
1912 if (JITDispatchHandlers.count(TagAddr))
1913 return make_error<StringError>(
"Tag " +
formatv(
"{0:x}", TagAddr) +
1914 " (for " + *TagName +
1915 ") already registered",
1920 for (
auto &[TagName, TagSym] : *TagSyms) {
1921 auto TagAddr = TagSym.getAddress();
1922 auto I = WFs.
find(TagName);
1924 "JITDispatchHandler implementation missing");
1925 JITDispatchHandlers[TagAddr] =
1926 std::make_shared<JITDispatchHandlerFunction>(std::move(
I->second));
1928 dbgs() <<
"Associated function tag \"" << *TagName <<
"\" ("
1929 <<
formatv(
"{0:x}", TagAddr) <<
") with handler\n";
1940 std::shared_ptr<JITDispatchHandlerFunction>
F;
1942 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
1943 auto I = JITDispatchHandlers.find(HandlerFnTagAddr);
1944 if (
I != JITDispatchHandlers.end())
1949 (*F)(std::move(SendResult), ArgBuffer.
data(), ArgBuffer.
size());
1952 (
"No function registered for tag " +
1953 formatv(
"{0:x16}", HandlerFnTagAddr))
1959 for (
auto &JD : JDs)
1964#ifdef EXPENSIVE_CHECKS
1965bool ExecutionSession::verifySessionState(
Twine Phase) {
1972 for (
auto &JD : JDs) {
1975 auto &Stream =
errs();
1977 Stream <<
"ERROR: Bad ExecutionSession state detected " <<
Phase
1979 Stream <<
" In JITDylib " << JD->getName() <<
", ";
1984 if (JD->State != JITDylib::Open) {
1986 <<
"state is not Open, but JD is in ExecutionSession list.";
1994 for (
auto &[
Sym, Entry] : JD->Symbols) {
1997 if (Entry.getAddress()) {
1998 LogFailure() <<
"symbol " <<
Sym <<
" has state "
2000 <<
" (not-yet-resolved) but non-null address "
2001 << Entry.getAddress() <<
".\n";
2006 auto UMIItr = JD->UnmaterializedInfos.find(
Sym);
2007 if (
Entry.hasMaterializerAttached()) {
2008 if (UMIItr == JD->UnmaterializedInfos.end()) {
2009 LogFailure() <<
"symbol " <<
Sym
2010 <<
" entry claims materializer attached, but "
2011 "UnmaterializedInfos has no corresponding entry.\n";
2013 }
else if (UMIItr != JD->UnmaterializedInfos.end()) {
2016 <<
" entry claims no materializer attached, but "
2017 "UnmaterializedInfos has an unexpected entry for it.\n";
2023 for (
auto &[
Sym, UMI] : JD->UnmaterializedInfos) {
2024 auto SymItr = JD->Symbols.find(
Sym);
2025 if (SymItr == JD->Symbols.end()) {
2028 <<
" has UnmaterializedInfos entry, but no Symbols entry.\n";
2033 for (
auto &[
Sym, MII] : JD->MaterializingInfos) {
2035 auto SymItr = JD->Symbols.find(
Sym);
2036 if (SymItr == JD->Symbols.end()) {
2041 <<
" has MaterializingInfos entry, but no Symbols entry.\n";
2049 <<
" is in Ready state, should not have MaterializingInfo.\n";
2054 static_cast<std::underlying_type_t<SymbolState>
>(
2055 SymItr->second.getState()) + 1);
2056 for (
auto &Q : MII.PendingQueries) {
2057 if (Q->getRequiredState() != CurState) {
2058 if (Q->getRequiredState() > CurState)
2059 CurState = Q->getRequiredState();
2061 LogFailure() <<
"symbol " <<
Sym
2062 <<
" has stale or misordered queries.\n";
2070 if (MII.DefiningEDU) {
2072 EDUsToCheck.
insert(MII.DefiningEDU.get());
2074 if (MII.DefiningEDU->JD != JD.get()) {
2075 LogFailure() <<
"symbol " <<
Sym
2076 <<
" has DefiningEDU with incorrect JD"
2078 ?
" (JD not currently in ExecutionSession"
2086 <<
" has DefiningEDU, but is not in Emitted state.\n";
2092 for (
auto &DepEDU : MII.DependantEDUs) {
2094 LogFailure() <<
"symbol " <<
Sym <<
" has DependantEDU "
2095 << (
void *)DepEDU <<
" with JD (" << DepEDU->JD
2096 <<
") that isn't in ExecutionSession.\n";
2104 for (
auto *EDU : EDUsToCheck) {
2105 assert(EDU->JD->State == JITDylib::Open &&
"EDU->JD is not Open");
2107 auto LogFailure = [&]() -> raw_fd_ostream & {
2109 auto &Stream =
errs();
2110 Stream <<
"In EDU defining " << EDU->JD->getName() <<
": { ";
2111 for (
auto &[
Sym, Flags] : EDU->Symbols)
2112 Stream <<
Sym <<
" ";
2117 if (EDU->Symbols.empty())
2118 LogFailure() <<
"no symbols defined.\n";
2120 for (
auto &[
Sym, Flags] : EDU->Symbols) {
2122 LogFailure() <<
"null symbol defined.\n";
2124 if (!EDU->JD->Symbols.count(SymbolStringPtr(
Sym))) {
2125 LogFailure() <<
"symbol " <<
Sym
2126 <<
" isn't present in JD's symbol table.\n";
2132 for (
auto &[DepJD, Symbols] : EDU->Dependencies) {
2134 LogFailure() <<
"dependant symbols listed for JD that isn't in "
2135 "ExecutionSession.\n";
2137 for (
auto &DepSym : Symbols) {
2138 if (!DepJD->Symbols.count(SymbolStringPtr(DepSym))) {
2140 <<
"dependant symbol " << DepSym
2141 <<
" does not appear in symbol table for dependant JD "
2142 << DepJD->getName() <<
".\n";
2154void ExecutionSession::dispatchOutstandingMUs() {
2157 std::optional<std::pair<std::unique_ptr<MaterializationUnit>,
2158 std::unique_ptr<MaterializationResponsibility>>>
2162 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2163 if (!OutstandingMUs.empty()) {
2164 JMU.emplace(std::move(OutstandingMUs.back()));
2165 OutstandingMUs.pop_back();
2172 assert(JMU->first &&
"No MU?");
2173 LLVM_DEBUG(
dbgs() <<
" Dispatching \"" << JMU->first->getName() <<
"\"\n");
2174 dispatchTask(std::make_unique<MaterializationTask>(std::move(JMU->first),
2175 std::move(JMU->second)));
2177 LLVM_DEBUG(
dbgs() <<
"Done dispatching MaterializationUnits.\n");
2180Error ExecutionSession::removeResourceTracker(ResourceTracker &RT) {
2182 dbgs() <<
"In " << RT.getJITDylib().getName() <<
" removing tracker "
2183 <<
formatv(
"{0:x}", RT.getKeyUnsafe()) <<
"\n";
2185 std::vector<ResourceManager *> CurrentResourceManagers;
2187 JITDylib::AsynchronousSymbolQuerySet QueriesToFail;
2188 std::shared_ptr<SymbolDependenceMap> FailedSymbols;
2191 CurrentResourceManagers = ResourceManagers;
2193 std::tie(QueriesToFail, FailedSymbols) =
2194 RT.getJITDylib().IL_removeTracker(RT);
2199 auto &JD = RT.getJITDylib();
2200 for (
auto *L :
reverse(CurrentResourceManagers))
2202 L->handleRemoveResources(JD, RT.getKeyUnsafe()));
2204 for (
auto &Q : QueriesToFail)
2211void ExecutionSession::transferResourceTracker(ResourceTracker &DstRT,
2212 ResourceTracker &SrcRT) {
2214 dbgs() <<
"In " << SrcRT.getJITDylib().getName()
2215 <<
" transfering resources from tracker "
2216 <<
formatv(
"{0:x}", SrcRT.getKeyUnsafe()) <<
" to tracker "
2217 <<
formatv(
"{0:x}", DstRT.getKeyUnsafe()) <<
"\n";
2221 if (&DstRT == &SrcRT)
2224 assert(&DstRT.getJITDylib() == &SrcRT.getJITDylib() &&
2225 "Can't transfer resources between JITDylibs");
2227 SrcRT.makeDefunct();
2228 auto &JD = DstRT.getJITDylib();
2229 JD.transferTracker(DstRT, SrcRT);
2230 for (
auto *L :
reverse(ResourceManagers))
2231 L->handleTransferResources(JD, DstRT.getKeyUnsafe(),
2232 SrcRT.getKeyUnsafe());
2236void ExecutionSession::destroyResourceTracker(ResourceTracker &RT) {
2239 dbgs() <<
"In " << RT.getJITDylib().getName() <<
" destroying tracker "
2240 <<
formatv(
"{0:x}", RT.getKeyUnsafe()) <<
"\n";
2242 if (!RT.isDefunct())
2243 transferResourceTracker(*RT.getJITDylib().getDefaultResourceTracker(),
2248Error ExecutionSession::IL_updateCandidatesFor(
2250 SymbolLookupSet &Candidates, SymbolLookupSet *NonCandidates) {
2251 return Candidates.forEachWithRemoval(
2252 [&](
const SymbolStringPtr &
Name,
2256 auto SymI = JD.Symbols.find(
Name);
2257 if (SymI == JD.Symbols.end())
2265 if (!SymI->second.getFlags().isExported() &&
2268 NonCandidates->add(Name, SymLookupFlags);
2277 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2284 if (SymI->second.getFlags().hasError()) {
2285 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2286 (*FailedSymbolsMap)[&JD] = {Name};
2288 std::move(FailedSymbolsMap));
2296void ExecutionSession::OL_resumeLookupAfterGeneration(
2297 InProgressLookupState &IPLS) {
2300 "Should not be called for not-in-generator lookups");
2305 if (
auto DG = IPLS.CurDefGeneratorStack.back().lock()) {
2306 IPLS.CurDefGeneratorStack.pop_back();
2307 std::lock_guard<std::mutex> Lock(DG->M);
2311 if (DG->PendingLookups.empty()) {
2317 LS = std::move(DG->PendingLookups.front());
2318 DG->PendingLookups.pop_front();
2323 dispatchTask(std::make_unique<LookupTask>(std::move(LS)));
2327void ExecutionSession::OL_applyQueryPhase1(
2328 std::unique_ptr<InProgressLookupState> IPLS, Error Err) {
2331 dbgs() <<
"Entering OL_applyQueryPhase1:\n"
2332 <<
" Lookup kind: " << IPLS->K <<
"\n"
2333 <<
" Search order: " << IPLS->SearchOrder
2334 <<
", Current index = " << IPLS->CurSearchOrderIndex
2335 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2336 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2337 <<
" Definition generator candidates: "
2338 << IPLS->DefGeneratorCandidates <<
"\n"
2339 <<
" Definition generator non-candidates: "
2340 << IPLS->DefGeneratorNonCandidates <<
"\n";
2344 OL_resumeLookupAfterGeneration(*IPLS);
2347 "Lookup should not be in InGenerator state here");
2354 while (IPLS->CurSearchOrderIndex != IPLS->SearchOrder.size()) {
2360 return IPLS->fail(std::move(Err));
2363 auto &KV = IPLS->SearchOrder[IPLS->CurSearchOrderIndex];
2364 auto &JD = *KV.first;
2365 auto JDLookupFlags = KV.second;
2368 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2369 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2373 if (IPLS->NewJITDylib) {
2377 SymbolLookupSet Tmp;
2378 std::swap(IPLS->DefGeneratorNonCandidates, Tmp);
2379 IPLS->DefGeneratorCandidates.append(std::move(Tmp));
2382 dbgs() <<
" First time visiting " << JD.getName()
2383 <<
", resetting candidate sets and building generator stack\n";
2388 IPLS->CurDefGeneratorStack.reserve(JD.DefGenerators.size());
2390 IPLS->CurDefGeneratorStack.push_back(DG);
2394 IPLS->NewJITDylib =
false;
2403 Err = IL_updateCandidatesFor(
2404 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2405 JD.DefGenerators.empty() ?
nullptr
2406 : &IPLS->DefGeneratorNonCandidates);
2408 dbgs() <<
" Remaining candidates = " << IPLS->DefGeneratorCandidates
2416 IPLS->DefGeneratorCandidates.empty())
2417 OL_resumeLookupAfterGeneration(*IPLS);
2423 return IPLS->fail(std::move(Err));
2427 if (IPLS->CurDefGeneratorStack.empty())
2428 LLVM_DEBUG(
dbgs() <<
" No generators to run for this JITDylib.\n");
2429 else if (IPLS->DefGeneratorCandidates.empty())
2432 dbgs() <<
" Running " << IPLS->CurDefGeneratorStack.size()
2433 <<
" remaining generators for "
2434 << IPLS->DefGeneratorCandidates.size() <<
" candidates\n";
2436 while (!IPLS->CurDefGeneratorStack.empty() &&
2437 !IPLS->DefGeneratorCandidates.empty()) {
2438 auto DG = IPLS->CurDefGeneratorStack.back().lock();
2441 return IPLS->fail(make_error<StringError>(
2442 "DefinitionGenerator removed while lookup in progress",
2455 std::lock_guard<std::mutex> Lock(DG->M);
2457 DG->PendingLookups.push_back(std::move(IPLS));
2466 auto &LookupSet = IPLS->DefGeneratorCandidates;
2471 LLVM_DEBUG(
dbgs() <<
" Attempting to generate " << LookupSet <<
"\n");
2473 Err = DG->tryToGenerate(LS, K, JD, JDLookupFlags, LookupSet);
2474 IPLS = std::move(
LS.IPLS);
2480 OL_resumeLookupAfterGeneration(*IPLS);
2485 dbgs() <<
" Error attempting to generate " << LookupSet <<
"\n";
2487 assert(IPLS &&
"LS cannot be retained if error is returned");
2488 return IPLS->fail(std::move(Err));
2494 {
dbgs() <<
" LookupState captured. Exiting phase1 for now.\n"; });
2501 LLVM_DEBUG(
dbgs() <<
" Updating candidate set post-generation\n");
2502 Err = IL_updateCandidatesFor(
2503 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2504 JD.DefGenerators.empty() ?
nullptr
2505 : &IPLS->DefGeneratorNonCandidates);
2510 LLVM_DEBUG(
dbgs() <<
" Error encountered while updating candidates\n");
2511 return IPLS->fail(std::move(Err));
2515 if (IPLS->DefGeneratorCandidates.empty() &&
2516 IPLS->DefGeneratorNonCandidates.empty()) {
2519 IPLS->CurSearchOrderIndex = IPLS->SearchOrder.size();
2525 ++IPLS->CurSearchOrderIndex;
2526 IPLS->NewJITDylib =
true;
2531 IPLS->DefGeneratorCandidates.remove_if(
2539 if (IPLS->DefGeneratorCandidates.empty()) {
2541 IPLS->complete(std::move(IPLS));
2543 LLVM_DEBUG(
dbgs() <<
"Phase 1 failed with unresolved symbols.\n");
2544 IPLS->fail(make_error<SymbolsNotFound>(
2549void ExecutionSession::OL_completeLookup(
2550 std::unique_ptr<InProgressLookupState> IPLS,
2551 std::shared_ptr<AsynchronousSymbolQuery> Q,
2555 dbgs() <<
"Entering OL_completeLookup:\n"
2556 <<
" Lookup kind: " << IPLS->K <<
"\n"
2557 <<
" Search order: " << IPLS->SearchOrder
2558 <<
", Current index = " << IPLS->CurSearchOrderIndex
2559 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2560 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2561 <<
" Definition generator candidates: "
2562 << IPLS->DefGeneratorCandidates <<
"\n"
2563 <<
" Definition generator non-candidates: "
2564 << IPLS->DefGeneratorNonCandidates <<
"\n";
2567 bool QueryComplete =
false;
2568 DenseMap<JITDylib *, JITDylib::UnmaterializedInfosList> CollectedUMIs;
2571 for (
auto &KV : IPLS->SearchOrder) {
2572 auto &JD = *KV.first;
2573 auto JDLookupFlags = KV.second;
2575 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2576 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2579 auto Err = IPLS->LookupSet.forEachWithRemoval(
2580 [&](
const SymbolStringPtr &
Name,
2583 dbgs() <<
" Attempting to match \"" <<
Name <<
"\" ("
2584 << SymLookupFlags <<
")... ";
2589 auto SymI = JD.Symbols.find(
Name);
2590 if (SymI == JD.Symbols.end()) {
2597 if (!SymI->second.getFlags().isExported() &&
2609 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2613 "required, but symbol is has-side-effects-only\n";
2621 if (SymI->second.getFlags().hasError()) {
2623 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2624 (*FailedSymbolsMap)[&JD] = {
Name};
2625 return make_error<FailedToMaterialize>(
2633 if (SymI->second.getState() >= Q->getRequiredState()) {
2635 <<
"matched, symbol already in required state\n");
2636 Q->notifySymbolMetRequiredState(
Name, SymI->second.getSymbol());
2641 Q->addQueryDependence(JD,
Name);
2649 if (SymI->second.hasMaterializerAttached()) {
2650 assert(SymI->second.getAddress() == ExecutorAddr() &&
2651 "Symbol not resolved but already has address?");
2652 auto UMII = JD.UnmaterializedInfos.find(
Name);
2653 assert(UMII != JD.UnmaterializedInfos.end() &&
2654 "Lazy symbol should have UnmaterializedInfo");
2656 auto UMI = UMII->second;
2657 assert(UMI->MU &&
"Materializer should not be null");
2658 assert(UMI->RT &&
"Tracker should not be null");
2660 dbgs() <<
"matched, preparing to dispatch MU@" << UMI->MU.get()
2661 <<
" (" << UMI->MU->getName() <<
")\n";
2666 for (
auto &KV : UMI->MU->getSymbols()) {
2667 auto SymK = JD.Symbols.find(KV.first);
2668 assert(SymK != JD.Symbols.end() &&
2669 "No entry for symbol covered by MaterializationUnit");
2670 SymK->second.setMaterializerAttached(
false);
2672 JD.UnmaterializedInfos.erase(KV.first);
2676 CollectedUMIs[&JD].push_back(std::move(UMI));
2684 "By this line the symbol should be materializing");
2685 auto &
MI = JD.MaterializingInfos[
Name];
2687 Q->addQueryDependence(JD,
Name);
2692 JD.shrinkMaterializationInfoMemory();
2698 dbgs() <<
"Lookup failed. Detaching query and replacing MUs.\n";
2705 for (
auto &KV : CollectedUMIs) {
2706 auto &JD = *KV.first;
2707 for (
auto &UMI : KV.second)
2708 for (
auto &KV2 : UMI->MU->getSymbols()) {
2709 assert(!JD.UnmaterializedInfos.count(KV2.first) &&
2710 "Unexpected materializer in map");
2711 auto SymI = JD.Symbols.find(KV2.first);
2712 assert(SymI != JD.Symbols.end() &&
"Missing symbol entry");
2714 "Can not replace symbol that is not materializing");
2715 assert(!SymI->second.hasMaterializerAttached() &&
2716 "MaterializerAttached flag should not be set");
2717 SymI->second.setMaterializerAttached(
true);
2718 JD.UnmaterializedInfos[KV2.first] = UMI;
2726 LLVM_DEBUG(
dbgs() <<
"Stripping unmatched weakly-referenced symbols\n");
2727 IPLS->LookupSet.forEachWithRemoval(
2730 Q->dropSymbol(
Name);
2736 if (!IPLS->LookupSet.empty()) {
2739 IPLS->LookupSet.getSymbolNames());
2743 QueryComplete = Q->isComplete();
2746 dbgs() <<
"Query successfully "
2747 << (QueryComplete ?
"completed" :
"lodged") <<
"\n";
2751 if (!CollectedUMIs.empty()) {
2752 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2755 for (
auto &KV : CollectedUMIs) {
2757 auto &JD = *KV.first;
2758 dbgs() <<
" For " << JD.getName() <<
": Adding " << KV.second.size()
2761 for (
auto &UMI : KV.second) {
2762 auto MR = createMaterializationResponsibility(
2763 *UMI->RT, std::move(UMI->MU->SymbolFlags),
2764 std::move(UMI->MU->InitSymbol));
2765 OutstandingMUs.push_back(
2766 std::make_pair(std::move(UMI->MU), std::move(MR)));
2772 if (RegisterDependencies && !Q->QueryRegistrations.empty()) {
2774 RegisterDependencies(Q->QueryRegistrations);
2784 Q->handleFailed(std::move(LodgingErr));
2788 if (QueryComplete) {
2790 Q->handleComplete(*
this);
2793 dispatchOutstandingMUs();
2796void ExecutionSession::OL_completeLookupFlags(
2797 std::unique_ptr<InProgressLookupState> IPLS,
2798 unique_function<
void(Expected<SymbolFlagsMap>)> OnComplete) {
2802 dbgs() <<
"Entering OL_completeLookupFlags:\n"
2803 <<
" Lookup kind: " << IPLS->K <<
"\n"
2804 <<
" Search order: " << IPLS->SearchOrder
2805 <<
", Current index = " << IPLS->CurSearchOrderIndex
2806 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2807 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2808 <<
" Definition generator candidates: "
2809 << IPLS->DefGeneratorCandidates <<
"\n"
2810 <<
" Definition generator non-candidates: "
2811 << IPLS->DefGeneratorNonCandidates <<
"\n";
2817 for (
auto &KV : IPLS->SearchOrder) {
2818 auto &JD = *KV.first;
2819 auto JDLookupFlags = KV.second;
2821 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2822 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2825 IPLS->LookupSet.forEachWithRemoval([&](
const SymbolStringPtr &
Name,
2828 dbgs() <<
" Attempting to match \"" <<
Name <<
"\" ("
2829 << SymLookupFlags <<
")... ";
2834 auto SymI = JD.Symbols.find(
Name);
2835 if (SymI == JD.Symbols.end()) {
2841 if (!SymI->second.getFlags().isExported() &&
2848 dbgs() <<
"matched, \"" <<
Name <<
"\" -> " << SymI->second.getFlags()
2857 IPLS->LookupSet.remove_if(
2862 if (!IPLS->LookupSet.empty()) {
2865 IPLS->LookupSet.getSymbolNames());
2874 OnComplete(std::move(
Result));
2877void ExecutionSession::OL_destroyMaterializationResponsibility(
2878 MaterializationResponsibility &MR) {
2880 assert(MR.SymbolFlags.empty() &&
2881 "All symbols should have been explicitly materialized or failed");
2882 MR.JD.unlinkMaterializationResponsibility(MR);
2886 const MaterializationResponsibility &MR) {
2887 return MR.JD.getRequestedSymbols(MR.SymbolFlags);
2890Error ExecutionSession::OL_notifyResolved(MaterializationResponsibility &MR,
2893 dbgs() <<
"In " << MR.JD.getName() <<
" resolving " << Symbols <<
"\n";
2896 for (
auto &KV : Symbols) {
2897 auto I = MR.SymbolFlags.find(KV.first);
2898 assert(
I != MR.SymbolFlags.end() &&
2899 "Resolving symbol outside this responsibility set");
2900 assert(!
I->second.hasMaterializationSideEffectsOnly() &&
2901 "Can't resolve materialization-side-effects-only symbol");
2904 assert((KV.second.getFlags() & WeakOrCommon) &&
2905 "Common symbols must be resolved as common or weak");
2906 assert((KV.second.getFlags() & ~WeakOrCommon) ==
2908 "Resolving symbol with incorrect flags");
2910 assert(KV.second.getFlags() ==
I->second &&
2911 "Resolving symbol with incorrect flags");
2915 return MR.JD.resolve(MR, Symbols);
2918template <
typename HandleNewDepFn>
2919void ExecutionSession::propagateExtraEmitDeps(
2920 std::deque<JITDylib::EmissionDepUnit *> Worklist, EDUInfosMap &EDUInfos,
2921 HandleNewDepFn HandleNewDep) {
2925 while (!Worklist.empty()) {
2926 auto &EDU = *Worklist.front();
2927 Worklist.pop_front();
2929 assert(EDUInfos.count(&EDU) &&
"No info entry for EDU");
2930 auto &EDUInfo = EDUInfos[&EDU];
2933 for (
auto *UserEDU : EDUInfo.IntraEmitUsers) {
2936 JITDylib::EmissionDepUnitInfo *UserEDUInfo =
nullptr;
2938 auto UserEDUInfoItr = EDUInfos.find(UserEDU);
2939 if (UserEDUInfoItr != EDUInfos.end())
2940 UserEDUInfo = &UserEDUInfoItr->second;
2943 for (
auto &[DepJD, Deps] : EDUInfo.NewDeps) {
2944 auto &UserEDUDepsForJD = UserEDU->Dependencies[DepJD];
2945 DenseSet<NonOwningSymbolStringPtr> *UserEDUNewDepsForJD =
nullptr;
2946 for (
auto Dep : Deps) {
2947 if (UserEDUDepsForJD.insert(Dep).second) {
2948 HandleNewDep(*UserEDU, *DepJD, Dep);
2950 if (!UserEDUNewDepsForJD) {
2953 if (UserEDUInfo->NewDeps.empty())
2954 Worklist.push_back(UserEDU);
2955 UserEDUNewDepsForJD = &UserEDUInfo->NewDeps[DepJD];
2958 UserEDUNewDepsForJD->insert(Dep);
2965 EDUInfo.NewDeps.clear();
2970ExecutionSession::EDUInfosMap ExecutionSession::simplifyDepGroups(
2971 MaterializationResponsibility &MR,
2972 ArrayRef<SymbolDependenceGroup> EmittedDeps) {
2974 auto &TargetJD = MR.getTargetJITDylib();
2978 DenseMap<JITDylib::EmissionDepUnit *, JITDylib::EmissionDepUnitInfo> EDUInfos;
2979 EDUInfos.reserve(EmittedDeps.size());
2980 DenseMap<NonOwningSymbolStringPtr, JITDylib::EmissionDepUnit *> EDUForSymbol;
2981 for (
auto &DG : EmittedDeps) {
2982 assert(!DG.Symbols.empty() &&
"DepGroup does not cover any symbols");
2985 if (DG.Dependencies.empty())
2988 auto TmpEDU = std::make_shared<JITDylib::EmissionDepUnit>(TargetJD);
2989 auto &EDUInfo = EDUInfos[TmpEDU.get()];
2990 EDUInfo.EDU = std::move(TmpEDU);
2991 for (
const auto &Symbol : DG.Symbols) {
2992 NonOwningSymbolStringPtr NonOwningSymbol(Symbol);
2993 assert(!EDUForSymbol.count(NonOwningSymbol) &&
2994 "Symbol should not appear in more than one SymbolDependenceGroup");
2995 assert(MR.getSymbols().count(Symbol) &&
2996 "Symbol in DepGroups not in the emitted set");
2997 auto NewlyEmittedItr = MR.getSymbols().find(Symbol);
2998 EDUInfo.EDU->Symbols[NonOwningSymbol] = NewlyEmittedItr->second;
2999 EDUForSymbol[NonOwningSymbol] = EDUInfo.EDU.get();
3005 DenseMap<NonOwningSymbolStringPtr, JITSymbolFlags> ResidualSymbolFlags;
3006 for (
auto &[
Sym, Flags] : MR.getSymbols()) {
3007 if (!EDUForSymbol.count(NonOwningSymbolStringPtr(
Sym)))
3008 ResidualSymbolFlags[NonOwningSymbolStringPtr(
Sym)] =
Flags;
3010 if (!ResidualSymbolFlags.empty()) {
3011 auto ResidualEDU = std::make_shared<JITDylib::EmissionDepUnit>(TargetJD);
3012 ResidualEDU->Symbols = std::move(ResidualSymbolFlags);
3013 auto &ResidualEDUInfo = EDUInfos[ResidualEDU.get()];
3014 ResidualEDUInfo.EDU = std::move(ResidualEDU);
3017 if (EDUInfos.size() == 1)
3021 for (
auto &[
Sym, Flags] : ResidualEDUInfo.EDU->Symbols)
3022 EDUForSymbol[
Sym] = ResidualEDUInfo.EDU.get();
3027 assert(EDUForSymbol.size() == MR.getSymbols().size() &&
3028 "MR symbols not fully covered by EDUs?");
3029 for (
auto &[
Sym, Flags] : MR.getSymbols()) {
3030 assert(EDUForSymbol.count(NonOwningSymbolStringPtr(
Sym)) &&
3031 "Sym in MR not covered by EDU");
3039 for (
auto &DG : EmittedDeps) {
3042 if (DG.Dependencies.empty())
3045 assert(EDUForSymbol.count(NonOwningSymbolStringPtr(*DG.Symbols.begin())) &&
3048 *EDUForSymbol.find(NonOwningSymbolStringPtr(*DG.Symbols.begin()))
3051 for (
auto &[DepJD, Deps] : DG.Dependencies) {
3052 DenseSet<NonOwningSymbolStringPtr> NewDepsForJD;
3054 assert(!Deps.empty() &&
"Dependence set for DepJD is empty");
3056 if (DepJD != &TargetJD) {
3059 for (
auto &Dep : Deps)
3060 NewDepsForJD.insert(NonOwningSymbolStringPtr(Dep));
3064 for (
auto &Dep : Deps) {
3065 NonOwningSymbolStringPtr NonOwningDep(Dep);
3066 auto I = EDUForSymbol.find(NonOwningDep);
3067 if (
I == EDUForSymbol.end()) {
3068 if (!MR.getSymbols().count(Dep))
3069 NewDepsForJD.insert(NonOwningDep);
3073 if (
I->second != &EDU)
3074 EDUInfos[
I->second].IntraEmitUsers.insert(&EDU);
3078 if (!NewDepsForJD.empty())
3079 EDU.Dependencies[DepJD] = std::move(NewDepsForJD);
3084 std::deque<JITDylib::EmissionDepUnit *> Worklist;
3085 for (
auto &[EDU, EDUInfo] : EDUInfos) {
3088 if (!EDU->Dependencies.empty()) {
3089 auto I = EDUInfos.find(EDU);
3090 if (
I != EDUInfos.end()) {
3091 auto &EDUInfo =
I->second;
3092 if (!EDUInfo.IntraEmitUsers.empty()) {
3093 EDUInfo.NewDeps = EDU->Dependencies;
3094 Worklist.push_back(EDU);
3101 propagateExtraEmitDeps(
3103 [](JITDylib::EmissionDepUnit &,
JITDylib &, NonOwningSymbolStringPtr) {});
3108void ExecutionSession::IL_makeEDUReady(
3109 std::shared_ptr<JITDylib::EmissionDepUnit> EDU,
3110 JITDylib::AsynchronousSymbolQuerySet &Queries) {
3113 auto &JD = *EDU->JD;
3115 for (
auto &[
Sym, Flags] : EDU->Symbols) {
3116 assert(JD.Symbols.count(SymbolStringPtr(
Sym)) &&
3117 "JD does not have an entry for Sym");
3118 auto &
Entry = JD.Symbols[SymbolStringPtr(
Sym)];
3120 assert(((
Entry.getFlags().hasMaterializationSideEffectsOnly() &&
3124 "Emitting from state other than Resolved");
3128 auto MII = JD.MaterializingInfos.find(SymbolStringPtr(
Sym));
3131 if (MII == JD.MaterializingInfos.end())
3133 auto &
MI = MII->second;
3136 Q->notifySymbolMetRequiredState(SymbolStringPtr(
Sym),
Entry.getSymbol());
3137 if (Q->isComplete())
3139 Q->removeQueryDependence(JD, SymbolStringPtr(
Sym));
3142 JD.MaterializingInfos.erase(MII);
3145 JD.shrinkMaterializationInfoMemory();
3148void ExecutionSession::IL_makeEDUEmitted(
3149 std::shared_ptr<JITDylib::EmissionDepUnit> EDU,
3150 JITDylib::AsynchronousSymbolQuerySet &Queries) {
3153 auto &JD = *EDU->JD;
3155 for (
auto &[
Sym, Flags] : EDU->Symbols) {
3156 assert(JD.Symbols.count(SymbolStringPtr(
Sym)) &&
3157 "JD does not have an entry for Sym");
3158 auto &
Entry = JD.Symbols[SymbolStringPtr(
Sym)];
3160 assert(((
Entry.getFlags().hasMaterializationSideEffectsOnly() &&
3164 "Emitting from state other than Resolved");
3169 for (
auto &[
Sym, Flags] : EDU->Symbols) {
3170 assert(JD.Symbols.count(SymbolStringPtr(
Sym)) &&
3171 "JD does not have an entry for Sym");
3172 auto &
Entry = JD.Symbols[SymbolStringPtr(
Sym)];
3174 "Symbols for EDU in inconsistent state");
3175 assert(JD.MaterializingInfos.count(SymbolStringPtr(
Sym)) &&
3176 "Emitted symbol has no MI");
3177 auto MI = JD.MaterializingInfos[SymbolStringPtr(
Sym)];
3179 "Already-emitted symbol has waiting-on-emitted queries");
3186 auto &
MI = JD.MaterializingInfos[SymbolStringPtr(
Sym)];
3187 MI.DefiningEDU = EDU;
3190 Q->notifySymbolMetRequiredState(SymbolStringPtr(
Sym),
Entry.getSymbol());
3191 if (Q->isComplete())
3196 for (
auto &[DepJD, Deps] : EDU->Dependencies) {
3197 for (
auto &Dep : Deps)
3198 DepJD->MaterializingInfos[SymbolStringPtr(Dep)].DependantEDUs.insert(
3206bool ExecutionSession::IL_removeEDUDependence(JITDylib::EmissionDepUnit &EDU,
3208 NonOwningSymbolStringPtr DepSym,
3209 EDUInfosMap &EDUInfos) {
3210 assert(EDU.Dependencies.count(&DepJD) &&
3211 "JD does not appear in Dependencies of DependantEDU");
3212 assert(EDU.Dependencies[&DepJD].count(DepSym) &&
3213 "Symbol does not appear in Dependencies of DependantEDU");
3214 auto &JDDeps = EDU.Dependencies[&DepJD];
3215 JDDeps.erase(DepSym);
3216 if (JDDeps.empty()) {
3217 EDU.Dependencies.erase(&DepJD);
3218 if (EDU.Dependencies.empty()) {
3223 auto &DepEDUInfo = EDUInfos[&EDU];
3224 if (!DepEDUInfo.EDU) {
3225 assert(EDU.JD->Symbols.count(
3226 SymbolStringPtr(EDU.Symbols.begin()->first)) &&
3227 "Missing symbol entry for first symbol in EDU");
3228 auto DepEDUFirstMI = EDU.JD->MaterializingInfos.find(
3229 SymbolStringPtr(EDU.Symbols.begin()->first));
3230 assert(DepEDUFirstMI != EDU.JD->MaterializingInfos.end() &&
3231 "Missing MI for first symbol in DependantEDU");
3232 DepEDUInfo.EDU = DepEDUFirstMI->second.DefiningEDU;
3240Error ExecutionSession::makeJDClosedError(JITDylib::EmissionDepUnit &EDU,
3241 JITDylib &ClosedJD) {
3243 for (
auto &[
Sym, Flags] : EDU.Symbols)
3244 FailedSymbols.
insert(SymbolStringPtr(
Sym));
3246 for (
auto &Dep : EDU.Dependencies[&ClosedJD])
3247 BadDeps[&ClosedJD].
insert(SymbolStringPtr(Dep));
3248 return make_error<UnsatisfiedSymbolDependencies>(
3249 ClosedJD.getExecutionSession().getSymbolStringPool(), EDU.JD,
3250 std::move(FailedSymbols), std::move(BadDeps),
3251 ClosedJD.getName() +
" is closed");
3254Error ExecutionSession::makeUnsatisfiedDepsError(JITDylib::EmissionDepUnit &EDU,
3258 for (
auto &[
Sym, Flags] : EDU.Symbols)
3259 FailedSymbols.
insert(SymbolStringPtr(
Sym));
3261 BadDepsMap[&BadJD] = std::move(BadDeps);
3262 return make_error<UnsatisfiedSymbolDependencies>(
3263 BadJD.getExecutionSession().getSymbolStringPool(), &BadJD,
3264 std::move(FailedSymbols), std::move(BadDepsMap),
3265 "dependencies removed or in error state");
3268Expected<JITDylib::AsynchronousSymbolQuerySet>
3269ExecutionSession::IL_emit(MaterializationResponsibility &MR,
3270 EDUInfosMap EDUInfos) {
3272 if (MR.RT->isDefunct())
3273 return make_error<ResourceTrackerDefunct>(MR.RT);
3275 auto &TargetJD = MR.getTargetJITDylib();
3276 if (TargetJD.State != JITDylib::Open)
3277 return make_error<StringError>(
"JITDylib " + TargetJD.getName() +
3280#ifdef EXPENSIVE_CHECKS
3281 verifySessionState(
"entering ExecutionSession::IL_emit");
3290 std::deque<JITDylib::EmissionDepUnit *> Worklist;
3291 for (
auto &[EDU,
_] : EDUInfos)
3292 Worklist.push_back(EDU);
3294 for (
auto *EDU : Worklist) {
3295 auto *EDUInfo = &EDUInfos[EDU];
3297 SmallVector<JITDylib *> DepJDsToRemove;
3298 for (
auto &[DepJD, Deps] : EDU->Dependencies) {
3299 if (DepJD->State != JITDylib::Open)
3300 return makeJDClosedError(*EDU, *DepJD);
3303 SmallVector<NonOwningSymbolStringPtr> DepsToRemove;
3304 for (
auto &Dep : Deps) {
3305 auto DepEntryItr = DepJD->Symbols.
find(SymbolStringPtr(Dep));
3310 if (DepEntryItr == DepJD->Symbols.end() ||
3311 DepEntryItr->second.getFlags().hasError()) {
3312 BadDeps.insert(SymbolStringPtr(Dep));
3318 auto &DepEntry = DepEntryItr->second;
3320 EDUInfo->NewDeps[DepJD].insert(Dep);
3326 DepsToRemove.push_back(Dep);
3330 assert(!DepJD->MaterializingInfos.count(SymbolStringPtr(Dep)) &&
3331 "Unexpected MaterializationInfo attached to ready symbol");
3339 assert(DepJD->MaterializingInfos.count(SymbolStringPtr(Dep)) &&
3340 "Expected MaterializationInfo for emitted dependency");
3341 auto &DepMI = DepJD->MaterializingInfos[SymbolStringPtr(Dep)];
3342 assert(DepMI.DefiningEDU &&
3343 "Emitted symbol does not have a defining EDU");
3344 assert(DepMI.DependantEDUs.empty() &&
3345 "Already-emitted symbol has dependant EDUs?");
3346 auto &DepEDUInfo = EDUInfos[DepMI.DefiningEDU.get()];
3347 if (!DepEDUInfo.EDU) {
3350 EDUInfo = &EDUInfos[EDU];
3351 DepEDUInfo.EDU = DepMI.DefiningEDU;
3352 for (
auto &[DepDepJD, DepDeps] : DepEDUInfo.EDU->Dependencies) {
3353 if (DepDepJD == &TargetJD) {
3354 for (
auto &DepDep : DepDeps)
3355 if (!MR.getSymbols().count(SymbolStringPtr(DepDep)))
3356 DepEDUInfo.NewDeps[DepDepJD].insert(DepDep);
3358 DepEDUInfo.NewDeps[DepDepJD] = DepDeps;
3361 DepEDUInfo.IntraEmitUsers.insert(EDU);
3365 if (!BadDeps.empty())
3366 return makeUnsatisfiedDepsError(*EDU, *DepJD, std::move(BadDeps));
3369 for (
auto &Dep : DepsToRemove)
3374 DepJDsToRemove.push_back(DepJD);
3378 for (
auto &DepJD : DepJDsToRemove) {
3379 assert(EDU->Dependencies.count(DepJD) &&
3380 "Trying to remove non-existent dep entries");
3381 EDU->Dependencies.erase(DepJD);
3385 for (
auto &[
Sym, Flags] : EDU->Symbols) {
3386 assert(TargetJD.Symbols.count(SymbolStringPtr(
Sym)) &&
3387 "Sym not present in symbol table");
3388 assert((TargetJD.Symbols[SymbolStringPtr(
Sym)].getState() ==
3390 TargetJD.Symbols[SymbolStringPtr(
Sym)]
3392 .hasMaterializationSideEffectsOnly()) &&
3393 "Emitting symbol not in the resolved state");
3395 "Symbol is already in an error state");
3397 auto MII = TargetJD.MaterializingInfos.find(SymbolStringPtr(
Sym));
3398 if (MII == TargetJD.MaterializingInfos.end() ||
3399 MII->second.DependantEDUs.empty())
3402 for (
auto &DependantEDU : MII->second.DependantEDUs) {
3403 if (IL_removeEDUDependence(*DependantEDU, TargetJD,
Sym, EDUInfos))
3404 EDUInfo = &EDUInfos[EDU];
3405 EDUInfo->IntraEmitUsers.insert(DependantEDU);
3407 MII->second.DependantEDUs.clear();
3412 for (
auto &[EDU, EDUInfo] : EDUInfos) {
3413 if (!EDUInfo.IntraEmitUsers.empty() && !EDU->Dependencies.empty()) {
3414 if (EDUInfo.NewDeps.empty())
3415 EDUInfo.NewDeps = EDU->Dependencies;
3416 Worklist.push_back(EDU);
3420 propagateExtraEmitDeps(
3422 [](JITDylib::EmissionDepUnit &EDU,
JITDylib &JD,
3423 NonOwningSymbolStringPtr
Sym) {
3424 JD.MaterializingInfos[SymbolStringPtr(
Sym)].DependantEDUs.insert(&EDU);
3427 JITDylib::AsynchronousSymbolQuerySet CompletedQueries;
3431 for (
auto &[EDU, EDUInfo] : EDUInfos) {
3432 if (EDU->Dependencies.empty())
3433 IL_makeEDUReady(std::move(EDUInfo.EDU), CompletedQueries);
3435 IL_makeEDUEmitted(std::move(EDUInfo.EDU), CompletedQueries);
3438#ifdef EXPENSIVE_CHECKS
3439 verifySessionState(
"exiting ExecutionSession::IL_emit");
3442 return std::move(CompletedQueries);
3445Error ExecutionSession::OL_notifyEmitted(
3446 MaterializationResponsibility &MR,
3447 ArrayRef<SymbolDependenceGroup> DepGroups) {
3449 dbgs() <<
"In " << MR.JD.getName() <<
" emitting " << MR.SymbolFlags
3451 if (!DepGroups.empty()) {
3452 dbgs() <<
" Initial dependencies:\n";
3453 for (
auto &SDG : DepGroups) {
3454 dbgs() <<
" Symbols: " << SDG.Symbols
3455 <<
", Dependencies: " << SDG.Dependencies <<
"\n";
3462 for (
auto &DG : DepGroups) {
3463 for (
auto &
Sym : DG.Symbols) {
3465 "DG contains dependence for symbol outside this MR");
3467 "DG contains duplicate entries for Name");
3472 auto EDUInfos = simplifyDepGroups(MR, DepGroups);
3475 dbgs() <<
" Simplified dependencies:\n";
3476 for (
auto &[EDU, EDUInfo] : EDUInfos) {
3477 dbgs() <<
" Symbols: { ";
3478 for (
auto &[
Sym, Flags] : EDU->Symbols)
3480 dbgs() <<
"}, Dependencies: { ";
3481 for (
auto &[DepJD, Deps] : EDU->Dependencies) {
3482 dbgs() <<
"(" << DepJD->getName() <<
", { ";
3483 for (
auto &Dep : Deps)
3484 dbgs() << Dep <<
" ";
3491 auto CompletedQueries =
3495 if (!CompletedQueries)
3496 return CompletedQueries.takeError();
3498 MR.SymbolFlags.clear();
3501 for (
auto &Q : *CompletedQueries) {
3502 assert(Q->isComplete() &&
"Q is not complete");
3503 Q->handleComplete(*
this);
3509Error ExecutionSession::OL_defineMaterializing(
3510 MaterializationResponsibility &MR,
SymbolFlagsMap NewSymbolFlags) {
3513 dbgs() <<
"In " << MR.JD.getName() <<
" defining materializing symbols "
3514 << NewSymbolFlags <<
"\n";
3516 if (
auto AcceptedDefs =
3517 MR.JD.defineMaterializing(MR, std::move(NewSymbolFlags))) {
3519 for (
auto &KV : *AcceptedDefs)
3520 MR.SymbolFlags.insert(KV);
3523 return AcceptedDefs.takeError();
3526std::pair<JITDylib::AsynchronousSymbolQuerySet,
3527 std::shared_ptr<SymbolDependenceMap>>
3528ExecutionSession::IL_failSymbols(JITDylib &JD,
3531#ifdef EXPENSIVE_CHECKS
3532 verifySessionState(
"entering ExecutionSession::IL_failSymbols");
3535 JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3536 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
3537 auto ExtractFailedQueries = [&](JITDylib::MaterializingInfo &
MI) {
3538 JITDylib::AsynchronousSymbolQueryList ToDetach;
3539 for (
auto &Q :
MI.pendingQueries()) {
3541 FailedQueries.insert(Q);
3542 ToDetach.push_back(Q);
3544 for (
auto &Q : ToDetach)
3546 assert(!
MI.hasQueriesPending() &&
"Queries still pending after detach");
3549 for (
auto &
Name : SymbolsToFail) {
3550 (*FailedSymbolsMap)[&JD].insert(
Name);
3553 auto SymI = JD.Symbols.find(
Name);
3562 if (SymI == JD.Symbols.end())
3564 auto &
Sym = SymI->second;
3568 if (
Sym.getFlags().hasError()) {
3570 "Symbol in error state still has MaterializingInfo");
3580 auto MII = JD.MaterializingInfos.find(
Name);
3581 if (MII == JD.MaterializingInfos.end())
3584 auto &
MI = MII->second;
3587 ExtractFailedQueries(
MI);
3589 if (
MI.DefiningEDU) {
3593 "Symbol with DefiningEDU should not have DependantEDUs");
3595 "Symbol has EDU, should have been emitted");
3596 assert(
MI.DefiningEDU->Symbols.count(NonOwningSymbolStringPtr(
Name)) &&
3597 "Symbol does not appear in its DefiningEDU");
3598 MI.DefiningEDU->Symbols.erase(NonOwningSymbolStringPtr(
Name));
3601 for (
auto &[DepJD, DepSyms] :
MI.DefiningEDU->Dependencies) {
3602 for (
auto DepSym : DepSyms) {
3603 assert(DepJD->Symbols.count(SymbolStringPtr(DepSym)) &&
3604 "DepSym not in DepJD");
3605 assert(DepJD->MaterializingInfos.count(SymbolStringPtr(DepSym)) &&
3606 "DepSym has not MaterializingInfo");
3607 auto &SymMI = DepJD->MaterializingInfos[SymbolStringPtr(DepSym)];
3608 assert(SymMI.DependantEDUs.count(
MI.DefiningEDU.get()) &&
3609 "DefiningEDU missing from DependantEDUs list of dependency");
3610 SymMI.DependantEDUs.erase(
MI.DefiningEDU.get());
3614 MI.DefiningEDU =
nullptr;
3621 for (
auto &DependantEDU :
MI.DependantEDUs) {
3624 for (
auto &[DepJD, DepSyms] : DependantEDU->Dependencies) {
3625 for (
auto DepSym : DepSyms) {
3628 if (DepJD == &JD && DepSym ==
Name)
3630 assert(DepJD->Symbols.count(SymbolStringPtr(DepSym)) &&
3631 "DepSym not in DepJD?");
3632 assert(DepJD->MaterializingInfos.count(SymbolStringPtr(DepSym)) &&
3633 "DependantEDU not registered with symbol it depends on");
3634 auto &SymMI = DepJD->MaterializingInfos[SymbolStringPtr(DepSym)];
3635 assert(SymMI.DependantEDUs.count(DependantEDU) &&
3636 "DependantEDU missing from DependantEDUs list");
3637 SymMI.DependantEDUs.erase(DependantEDU);
3643 auto &DepJD = *DependantEDU->JD;
3644 auto DepEDUSymbols = std::move(DependantEDU->Symbols);
3645 for (
auto &[DepName, Flags] : DepEDUSymbols) {
3646 auto DepSymItr = DepJD.Symbols.find(SymbolStringPtr(DepName));
3647 assert(DepSymItr != DepJD.Symbols.end() &&
3648 "Symbol not present in table");
3649 auto &DepSym = DepSymItr->second;
3652 "Symbol has EDU, should have been emitted");
3653 assert(!DepSym.getFlags().hasError() &&
3654 "Symbol is already in the error state?");
3656 (*FailedSymbolsMap)[&DepJD].insert(SymbolStringPtr(DepName));
3661 DepJD.MaterializingInfos.find(SymbolStringPtr(DepName));
3662 assert(DepMIItr != DepJD.MaterializingInfos.end() &&
3663 "Symbol has defining EDU but not MaterializingInfo");
3664 auto &DepMI = DepMIItr->second;
3665 assert(DepMI.DefiningEDU.get() == DependantEDU &&
3666 "Bad EDU dependence edge");
3667 assert(DepMI.DependantEDUs.empty() &&
3668 "Symbol was emitted, should not have any DependantEDUs");
3669 ExtractFailedQueries(DepMI);
3670 DepJD.MaterializingInfos.erase(SymbolStringPtr(DepName));
3673 DepJD.shrinkMaterializationInfoMemory();
3676 MI.DependantEDUs.clear();
3679 assert(!
MI.DefiningEDU &&
"DefiningEDU should have been reset");
3681 "DependantEDUs should have been removed above");
3683 "Can not delete MaterializingInfo with queries pending");
3684 JD.MaterializingInfos.erase(
Name);
3687 JD.shrinkMaterializationInfoMemory();
3689#ifdef EXPENSIVE_CHECKS
3690 verifySessionState(
"exiting ExecutionSession::IL_failSymbols");
3693 return std::make_pair(std::move(FailedQueries), std::move(FailedSymbolsMap));
3696void ExecutionSession::OL_notifyFailed(MaterializationResponsibility &MR) {
3699 dbgs() <<
"In " << MR.JD.getName() <<
" failing materialization for "
3700 << MR.SymbolFlags <<
"\n";
3703 if (MR.SymbolFlags.empty())
3707 for (
auto &[
Name, Flags] : MR.SymbolFlags)
3708 SymbolsToFail.push_back(
Name);
3709 MR.SymbolFlags.clear();
3711 JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3712 std::shared_ptr<SymbolDependenceMap> FailedSymbols;
3716 if (MR.RT->isDefunct())
3717 return std::pair<JITDylib::AsynchronousSymbolQuerySet,
3718 std::shared_ptr<SymbolDependenceMap>>();
3719 return IL_failSymbols(MR.getTargetJITDylib(), SymbolsToFail);
3722 for (
auto &Q : FailedQueries)
3727Error ExecutionSession::OL_replace(MaterializationResponsibility &MR,
3728 std::unique_ptr<MaterializationUnit> MU) {
3729 for (
auto &KV : MU->getSymbols()) {
3730 assert(MR.SymbolFlags.count(KV.first) &&
3731 "Replacing definition outside this responsibility set");
3732 MR.SymbolFlags.erase(KV.first);
3735 if (MU->getInitializerSymbol() == MR.InitSymbol)
3736 MR.InitSymbol =
nullptr;
3738 LLVM_DEBUG(MR.JD.getExecutionSession().runSessionLocked([&]() {
3739 dbgs() <<
"In " << MR.JD.getName() <<
" replacing symbols with " << *MU
3743 return MR.JD.replace(MR, std::move(MU));
3746Expected<std::unique_ptr<MaterializationResponsibility>>
3747ExecutionSession::OL_delegate(MaterializationResponsibility &MR,
3750 SymbolStringPtr DelegatedInitSymbol;
3753 for (
auto &
Name : Symbols) {
3754 auto I = MR.SymbolFlags.find(
Name);
3755 assert(
I != MR.SymbolFlags.end() &&
3756 "Symbol is not tracked by this MaterializationResponsibility "
3759 DelegatedFlags[
Name] = std::move(
I->second);
3760 if (
Name == MR.InitSymbol)
3761 std::swap(MR.InitSymbol, DelegatedInitSymbol);
3763 MR.SymbolFlags.erase(
I);
3766 return MR.JD.delegate(MR, std::move(DelegatedFlags),
3767 std::move(DelegatedInitSymbol));
3771void ExecutionSession::dumpDispatchInfo(Task &
T) {
3773 dbgs() <<
"Dispatching: ";
3774 T.printDescription(
dbgs());
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
aarch64 falkor hwpf fix Falkor HW Prefetch Fix Late Phase
while(!ToSimplify.empty())
static StringRef getName(Value *V)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static uint32_t getFlags(const Symbol *Sym)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
const T & front() const
front - Get the first element.
size_t size() const
size - Get the array size.
bool empty() const
empty - Check if the array is empty.
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Helper for Errors used as out-parameters.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Symbol info for RuntimeDyld.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
std::pair< iterator, bool > insert(const ValueT &V)
iterator find(const_arg_type_t< ValueT > V)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
const std::string & getName() const
Get the name for this JITLinkDylib.
AsynchronousSymbolQuery(const SymbolLookupSet &Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete)
Create a query for the given symbols.
void notifySymbolMetRequiredState(const SymbolStringPtr &Name, ExecutorSymbolDef Sym)
Notify the query that a requested symbol has reached the required state.
Definition generators can be attached to JITDylibs to generate new definitions for otherwise unresolv...
virtual ~DefinitionGenerator()
An ExecutionSession represents a running JIT program.
Error endSession()
End the session.
void reportError(Error Err)
Report a error for this execution session.
void lookupFlags(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet Symbols, unique_function< void(Expected< SymbolFlagsMap >)> OnComplete)
Search the given JITDylibs to find the flags associated with each of the given symbols.
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
JITDylib * getJITDylibByName(StringRef Name)
Return a pointer to the "name" JITDylib.
JITDylib & createBareJITDylib(std::string Name)
Add a new bare JITDylib to this ExecutionSession.
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete, RegisterDependenciesFunction RegisterDependencies)
Search the given JITDylibs for the given symbols.
Error registerJITDispatchHandlers(JITDylib &JD, JITDispatchHandlerAssociationMap WFs)
For each tag symbol name, associate the corresponding AsyncHandlerWrapperFunction with the address of...
void registerResourceManager(ResourceManager &RM)
Register the given ResourceManager with this ExecutionSession.
~ExecutionSession()
Destroy an ExecutionSession.
void runJITDispatchHandler(SendResultFunction SendResult, ExecutorAddr HandlerFnTagAddr, ArrayRef< char > ArgBuffer)
Run a registered jit-side wrapper function.
void deregisterResourceManager(ResourceManager &RM)
Deregister the given ResourceManager with this ExecutionSession.
ExecutionSession(std::unique_ptr< ExecutorProcessControl > EPC)
Construct an ExecutionSession with the given ExecutorProcessControl object.
decltype(auto) runSessionLocked(Func &&F)
Run the given lambda with the session mutex locked.
void dump(raw_ostream &OS)
Dump the state of all the JITDylibs in this session.
Error removeJITDylibs(std::vector< JITDylibSP > JDsToRemove)
Removes the given JITDylibs from the ExecutionSession.
Expected< JITDylib & > createJITDylib(std::string Name)
Add a new JITDylib to this ExecutionSession.
void dispatchTask(std::unique_ptr< Task > T)
Materialize the given unit.
Represents an address in the executor process.
Represents a defining location for a JIT symbol.
FailedToMaterialize(std::shared_ptr< SymbolStringPool > SSP, std::shared_ptr< SymbolDependenceMap > Symbols)
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
void log(raw_ostream &OS) const override
Print an error message to an output stream.
InProgressFullLookupState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, SymbolState RequiredState, std::shared_ptr< AsynchronousSymbolQuery > Q, RegisterDependenciesFunction RegisterDependencies)
void complete(std::unique_ptr< InProgressLookupState > IPLS) override
void fail(Error Err) override
void complete(std::unique_ptr< InProgressLookupState > IPLS) override
void fail(Error Err) override
InProgressLookupFlagsState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, unique_function< void(Expected< SymbolFlagsMap >)> OnComplete)
virtual ~InProgressLookupState()=default
SymbolLookupSet DefGeneratorCandidates
JITDylibSearchOrder SearchOrder
std::vector< std::weak_ptr< DefinitionGenerator > > CurDefGeneratorStack
size_t CurSearchOrderIndex
SymbolLookupSet LookupSet
virtual void complete(std::unique_ptr< InProgressLookupState > IPLS)=0
InProgressLookupState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, SymbolState RequiredState)
SymbolState RequiredState
SymbolLookupSet DefGeneratorNonCandidates
virtual void fail(Error Err)=0
enum llvm::orc::InProgressLookupState::@503 GenState
Represents a JIT'd dynamic library.
Error clear()
Calls remove on all trackers currently associated with this JITDylib.
Error define(std::unique_ptr< MaterializationUnitType > &&MU, ResourceTrackerSP RT=nullptr)
Define all symbols provided by the materialization unit to be part of this JITDylib.
ExecutionSession & getExecutionSession() const
Get a reference to the ExecutionSession for this JITDylib.
ResourceTrackerSP createResourceTracker()
Create a resource tracker for this JITDylib.
Expected< std::vector< JITDylibSP > > getReverseDFSLinkOrder()
Rteurn this JITDylib and its transitive dependencies in reverse DFS order based on linkage relationsh...
ResourceTrackerSP getDefaultResourceTracker()
Get the default resource tracker for this JITDylib.
void removeGenerator(DefinitionGenerator &G)
Remove a definition generator from this JITDylib.
Expected< std::vector< JITDylibSP > > getDFSLinkOrder()
Return this JITDylib and its transitive dependencies in DFS order based on linkage relationships.
Wraps state for a lookup-in-progress.
void continueLookup(Error Err)
Continue the lookup.
LookupState & operator=(LookupState &&)
void printDescription(raw_ostream &OS) override
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
void printDescription(raw_ostream &OS) override
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
SymbolFlagsMap SymbolFlags
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Non-owning SymbolStringPool entry pointer.
StringRef getName() const override
Return the name of this materialization unit.
ReExportsMaterializationUnit(JITDylib *SourceJD, JITDylibLookupFlags SourceJDLookupFlags, SymbolAliasMap Aliases)
SourceJD is allowed to be nullptr, in which case the source JITDylib is taken to be whatever JITDylib...
std::function< bool(SymbolStringPtr)> SymbolPredicate
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &LookupSet) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
ReexportsGenerator(JITDylib &SourceJD, JITDylibLookupFlags SourceJDLookupFlags, SymbolPredicate Allow=SymbolPredicate())
Create a reexports generator.
Listens for ResourceTracker operations.
virtual ~ResourceManager()
ResourceTrackerDefunct(ResourceTrackerSP RT)
void log(raw_ostream &OS) const override
Print an error message to an output stream.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
API to remove / transfer ownership of JIT resources.
JITDylib & getJITDylib() const
Return the JITDylib targeted by this tracker.
void transferTo(ResourceTracker &DstRT)
Transfer all resources associated with this key to the given tracker, which must target the same JITD...
ResourceTracker(const ResourceTracker &)=delete
Error remove()
Remove all resources associated with this key.
void lookupAsync(LookupAsyncOnCompleteFn OnComplete) const
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 WrapperFunctionResult createOutOfBandError(const char *Msg)
Create an out-of-band error by copying the given string.
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.
IntrusiveRefCntPtr< JITDylib > JITDylibSP
JITDylibSearchOrder makeJITDylibSearchOrder(ArrayRef< JITDylib * > JDs, JITDylibLookupFlags Flags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Convenience function for creating a search order from an ArrayRef of JITDylib*, all with the same fla...
std::vector< std::pair< JITDylib *, JITDylibLookupFlags > > JITDylibSearchOrder
A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search order during symbol lookup.
std::function< void(const SymbolDependenceMap &)> RegisterDependenciesFunction
Callback to register the dependencies for a given query.
@ MissingSymbolDefinitions
@ UnexpectedSymbolDefinitions
std::unique_ptr< ReExportsMaterializationUnit > symbolAliases(SymbolAliasMap Aliases)
Create a ReExportsMaterializationUnit with the given aliases.
SymbolLookupFlags
Lookup flags that apply to each symbol in a lookup.
std::unique_ptr< ReExportsMaterializationUnit > reexports(JITDylib &SourceJD, SymbolAliasMap Aliases, JITDylibLookupFlags SourceJDLookupFlags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Create a materialization unit for re-exporting symbols from another JITDylib with alternative names/f...
DenseMap< SymbolStringPtr, SymbolAliasMapEntry > SymbolAliasMap
A map of Symbols to (Symbol, Flags) pairs.
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
@ MatchExportedSymbolsOnly
DenseMap< SymbolStringPtr, ExecutorSymbolDef > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
DenseMap< SymbolStringPtr, JITSymbolFlags > SymbolFlagsMap
A map from symbol names (as SymbolStringPtrs) to JITSymbolFlags.
unique_function< void(Expected< SymbolMap >)> SymbolsResolvedCallback
Callback to notify client that symbols have been resolved.
DenseSet< SymbolStringPtr > SymbolNameSet
A set of symbol names (represented by SymbolStringPtrs for.
LookupKind
Describes the kind of lookup being performed.
RegisterDependenciesFunction NoDependenciesToRegister
This can be used as the value for a RegisterDependenciesFunction if there are no dependants to regist...
std::vector< SymbolStringPtr > SymbolNameVector
A vector of symbol names.
SymbolState
Represents the state that a symbol has reached during materialization.
@ Materializing
Added to the symbol table, never queried.
@ NeverSearched
No symbol should be in this state.
@ Ready
Emitted to memory, but waiting on transitive dependencies.
@ Emitted
Assigned address, still materializing.
@ Resolved
Queried, materialization begun.
std::error_code orcError(OrcErrorCode ErrCode)
DenseMap< JITDylib *, SymbolNameSet > SymbolDependenceMap
A map from JITDylibs to sets of symbols.
Expected< SymbolAliasMap > buildSimpleReexportsAliasMap(JITDylib &SourceJD, const SymbolNameSet &Symbols)
Build a SymbolAliasMap for the common case where you want to re-export symbols from another JITDylib ...
This is an optimization pass for GlobalISel generic memory operations.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
void append_range(Container &C, Range &&R)
Wrapper function to append 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.
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.
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
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.