12#include "llvm/Config/llvm-config.h"
18#include <condition_variable>
22#define DEBUG_TYPE "orc"
40void MaterializationUnit::anchor() {}
43 assert((
reinterpret_cast<uintptr_t
>(JD.get()) & 0x1) == 0 &&
44 "JITDylib must be two byte aligned");
46 JDAndFlag.store(
reinterpret_cast<uintptr_t
>(JD.get()));
62void ResourceTracker::makeDefunct() {
63 uintptr_t Val = JDAndFlag.load();
78 OS <<
"Resource tracker " << (
void *)RT.
get() <<
" became defunct";
82 std::shared_ptr<SymbolStringPool> SSP,
83 std::shared_ptr<SymbolDependenceMap> Symbols)
85 assert(this->SSP &&
"String pool cannot be null");
86 assert(!this->Symbols->empty() &&
"Can not fail to resolve an empty set");
90 for (
auto &[JD, Syms] : *this->Symbols)
95 for (
auto &[JD, Syms] : *Symbols)
104 OS <<
"Failed to materialize symbols: " << *Symbols;
108 std::shared_ptr<SymbolStringPool> SSP,
JITDylibSP JD,
110 std::string Explanation)
112 FailedSymbols(
std::
move(FailedSymbols)), BadDeps(
std::
move(BadDeps)),
113 Explanation(
std::
move(Explanation)) {}
120 OS <<
"In " << JD->getName() <<
", failed to materialize " << FailedSymbols
121 <<
", due to unsatisfied dependencies " << BadDeps;
122 if (!Explanation.empty())
123 OS <<
" (" << Explanation <<
")";
129 for (
auto &
Sym : Symbols)
130 this->Symbols.push_back(
Sym);
131 assert(!this->Symbols.
empty() &&
"Can not fail to resolve an empty set");
137 assert(!this->Symbols.empty() &&
"Can not fail to resolve an empty set");
145 OS <<
"Symbols not found: " << Symbols;
149 std::shared_ptr<SymbolStringPool> SSP,
SymbolNameSet Symbols)
151 assert(!this->Symbols.
empty() &&
"Can not fail to resolve an empty set");
159 OS <<
"Symbols could not be removed: " << Symbols;
183 : NotifyComplete(
std::
move(NotifyComplete)), RequiredState(RequiredState) {
185 "Cannot query for a symbols that have not reached the resolve state "
188 OutstandingSymbolsCount = Symbols.size();
190 for (
auto &[
Name, Flags] : Symbols)
198 "Resolving symbol outside the requested set");
200 "Redundantly resolving symbol Name");
204 if (
Sym.getFlags().hasMaterializationSideEffectsOnly())
207 I->second = std::move(
Sym);
208 --OutstandingSymbolsCount;
212 assert(OutstandingSymbolsCount == 0 &&
213 "Symbols remain, handleComplete called prematurely");
215 class RunQueryCompleteTask :
public Task {
217 RunQueryCompleteTask(
SymbolMap ResolvedSymbols,
219 : ResolvedSymbols(
std::
move(ResolvedSymbols)),
220 NotifyComplete(
std::
move(NotifyComplete)) {}
222 OS <<
"Execute query complete callback for " << ResolvedSymbols;
224 void run()
override { NotifyComplete(std::move(ResolvedSymbols)); }
231 auto T = std::make_unique<RunQueryCompleteTask>(std::move(ResolvedSymbols),
232 std::move(NotifyComplete));
237void AsynchronousSymbolQuery::handleFailed(Error Err) {
239 OutstandingSymbolsCount == 0 &&
240 "Query should already have been abandoned");
241 NotifyComplete(std::move(Err));
245void AsynchronousSymbolQuery::addQueryDependence(JITDylib &JD,
246 SymbolStringPtr
Name) {
249 assert(Added &&
"Duplicate dependence notification?");
252void AsynchronousSymbolQuery::removeQueryDependence(
253 JITDylib &JD,
const SymbolStringPtr &
Name) {
254 auto QRI = QueryRegistrations.
find(&JD);
255 assert(QRI != QueryRegistrations.
end() &&
256 "No dependencies registered for JD");
257 assert(QRI->second.count(
Name) &&
"No dependency on Name in JD");
258 QRI->second.erase(
Name);
259 if (QRI->second.empty())
260 QueryRegistrations.
erase(QRI);
263void AsynchronousSymbolQuery::dropSymbol(
const SymbolStringPtr &
Name) {
266 "Redundant removal of weakly-referenced symbol");
268 --OutstandingSymbolsCount;
271void AsynchronousSymbolQuery::detach() {
272 ResolvedSymbols.
clear();
273 OutstandingSymbolsCount = 0;
274 for (
auto &[JD, Syms] : QueryRegistrations)
275 JD->detachQueryHelper(*
this, Syms);
276 QueryRegistrations.clear();
284 return "<Absolute Symbols>";
287void AbsoluteSymbolsMaterializationUnit::materialize(
288 std::unique_ptr<MaterializationResponsibility> R) {
294 if (
auto Err = R->notifyResolved(Symbols)) {
295 R->getExecutionSession().reportError(std::move(Err));
296 R->failMaterialization();
299 if (
auto Err = R->notifyEmitted({})) {
300 R->getExecutionSession().reportError(std::move(Err));
301 R->failMaterialization();
306void AbsoluteSymbolsMaterializationUnit::discard(
const JITDylib &JD,
307 const SymbolStringPtr &
Name) {
312MaterializationUnit::Interface
313AbsoluteSymbolsMaterializationUnit::extractFlags(
const SymbolMap &Symbols) {
315 for (
const auto &[
Name, Def] : Symbols)
317 return MaterializationUnit::Interface(std::move(Flags),
nullptr);
324 SourceJDLookupFlags(SourceJDLookupFlags), Aliases(
std::
move(Aliases)) {}
327 return "<Reexports>";
330void ReExportsMaterializationUnit::materialize(
331 std::unique_ptr<MaterializationResponsibility> R) {
333 auto &ES = R->getTargetJITDylib().getExecutionSession();
334 JITDylib &TgtJD = R->getTargetJITDylib();
335 JITDylib &SrcJD = SourceJD ? *SourceJD : TgtJD;
340 auto RequestedSymbols = R->getRequestedSymbols();
343 for (
auto &
Name : RequestedSymbols) {
345 assert(
I != Aliases.
end() &&
"Symbol not found in aliases map?");
346 RequestedAliases[
Name] = std::move(
I->second);
352 dbgs() <<
"materializing reexports: target = " << TgtJD.
getName()
353 <<
", source = " << SrcJD.
getName() <<
" " << RequestedAliases
358 if (!Aliases.
empty()) {
359 auto Err = SourceJD ?
R->replace(
reexports(*SourceJD, std::move(Aliases),
360 SourceJDLookupFlags))
367 R->failMaterialization();
374 struct OnResolveInfo {
375 OnResolveInfo(std::unique_ptr<MaterializationResponsibility> R,
376 SymbolAliasMap Aliases)
379 std::unique_ptr<MaterializationResponsibility>
R;
381 std::vector<SymbolDependenceGroup> SDGs;
392 std::vector<std::pair<SymbolLookupSet, std::shared_ptr<OnResolveInfo>>>
394 while (!RequestedAliases.
empty()) {
396 SymbolLookupSet QuerySymbols;
400 for (
auto &KV : RequestedAliases) {
402 if (&SrcJD == &TgtJD && (QueryAliases.count(KV.second.Aliasee) ||
403 RequestedAliases.count(KV.second.Aliasee)))
406 ResponsibilitySymbols.
insert(KV.first);
407 QuerySymbols.add(KV.second.Aliasee,
408 KV.second.AliasFlags.hasMaterializationSideEffectsOnly()
411 QueryAliases[KV.first] = std::move(KV.second);
415 for (
auto &KV : QueryAliases)
416 RequestedAliases.erase(KV.first);
418 assert(!QuerySymbols.empty() &&
"Alias cycle detected!");
420 auto NewR =
R->delegate(ResponsibilitySymbols);
423 R->failMaterialization();
427 auto QueryInfo = std::make_shared<OnResolveInfo>(std::move(*NewR),
428 std::move(QueryAliases));
429 QueryInfos.push_back(
430 make_pair(std::move(QuerySymbols), std::move(QueryInfo)));
434 while (!QueryInfos.empty()) {
435 auto QuerySymbols = std::move(QueryInfos.back().first);
436 auto QueryInfo = std::move(QueryInfos.back().second);
438 QueryInfos.pop_back();
440 auto RegisterDependencies = [QueryInfo,
447 assert(Deps.size() == 1 && Deps.count(&SrcJD) &&
448 "Unexpected dependencies for reexports");
450 auto &SrcJDDeps = Deps.find(&SrcJD)->second;
452 for (
auto &[Alias, AliasInfo] : QueryInfo->Aliases)
453 if (SrcJDDeps.count(AliasInfo.Aliasee))
454 QueryInfo->SDGs.push_back({{Alias}, {{&SrcJD, {AliasInfo.Aliasee}}}});
457 auto OnComplete = [QueryInfo](Expected<SymbolMap>
Result) {
458 auto &ES = QueryInfo->R->getTargetJITDylib().getExecutionSession();
461 for (
auto &KV : QueryInfo->Aliases) {
462 assert((KV.second.AliasFlags.hasMaterializationSideEffectsOnly() ||
463 Result->count(KV.second.Aliasee)) &&
464 "Result map missing entry?");
466 if (KV.second.AliasFlags.hasMaterializationSideEffectsOnly())
469 ResolutionMap[KV.first] = {(*Result)[KV.second.Aliasee].getAddress(),
470 KV.second.AliasFlags};
472 if (
auto Err = QueryInfo->R->notifyResolved(ResolutionMap)) {
474 QueryInfo->R->failMaterialization();
477 if (
auto Err = QueryInfo->R->notifyEmitted(QueryInfo->SDGs)) {
479 QueryInfo->R->failMaterialization();
484 QueryInfo->R->failMaterialization();
491 std::move(RegisterDependencies));
495void ReExportsMaterializationUnit::discard(
const JITDylib &JD,
496 const SymbolStringPtr &
Name) {
498 "Symbol not covered by this MaterializationUnit");
502MaterializationUnit::Interface
503ReExportsMaterializationUnit::extractFlags(
const SymbolAliasMap &Aliases) {
505 for (
auto &KV : Aliases)
508 return MaterializationUnit::Interface(std::move(
SymbolFlags),
nullptr);
519 return Flags.takeError();
522 for (
auto &
Name : Symbols) {
523 assert(Flags->count(
Name) &&
"Missing entry in flags map");
542 virtual void complete(std::unique_ptr<InProgressLookupState> IPLS) = 0;
570 OnComplete(
std::
move(OnComplete)) {}
572 void complete(std::unique_ptr<InProgressLookupState> IPLS)
override {
573 auto &ES =
SearchOrder.front().first->getExecutionSession();
574 ES.OL_completeLookupFlags(std::move(IPLS), std::move(OnComplete));
577 void fail(
Error Err)
override { OnComplete(std::move(Err)); }
588 std::shared_ptr<AsynchronousSymbolQuery> Q,
592 Q(
std::
move(Q)), RegisterDependencies(
std::
move(RegisterDependencies)) {
595 void complete(std::unique_ptr<InProgressLookupState> IPLS)
override {
596 auto &ES =
SearchOrder.front().first->getExecutionSession();
597 ES.OL_completeLookup(std::move(IPLS), std::move(Q),
598 std::move(RegisterDependencies));
603 Q->handleFailed(std::move(Err));
607 std::shared_ptr<AsynchronousSymbolQuery> Q;
614 : SourceJD(SourceJD), SourceJDLookupFlags(SourceJDLookupFlags),
621 assert(&JD != &SourceJD &&
"Cannot re-export from the same dylib");
625 K, {{&SourceJD, JDLookupFlags}}, LookupSet);
627 return Flags.takeError();
631 for (
auto &KV : *Flags)
632 if (!Allow || Allow(KV.first))
635 if (AliasMap.empty())
645void LookupState::reset(InProgressLookupState *IPLS) { this->IPLS.reset(IPLS); }
653 assert(IPLS &&
"Cannot call continueLookup on empty LookupState");
654 auto &ES = IPLS->SearchOrder.begin()->first->getExecutionSession();
655 ES.OL_applyQueryPhase1(std::move(IPLS), std::move(Err));
659 std::deque<LookupState> LookupsToFail;
661 std::lock_guard<std::mutex> Lock(M);
662 std::swap(PendingLookups, LookupsToFail);
666 for (
auto &LS : LookupsToFail)
667 LS.continueLookup(make_error<StringError>(
668 "Query waiting on DefinitionGenerator that was destroyed",
677 std::vector<ResourceTrackerSP> TrackersToRemove;
679 assert(State != Closed &&
"JD is defunct");
680 for (
auto &KV : TrackerSymbols)
681 TrackersToRemove.push_back(KV.first);
686 for (
auto &RT : TrackersToRemove)
687 Err =
joinErrors(std::move(Err), RT->remove());
693 assert(State != Closed &&
"JD is defunct");
696 return DefaultTracker;
702 assert(State == Open &&
"JD is defunct");
711 std::shared_ptr<DefinitionGenerator> TmpDG;
714 assert(State == Open &&
"JD is defunct");
716 [&](
const std::shared_ptr<DefinitionGenerator> &
H) {
717 return H.get() == &
G;
719 assert(
I != DefGenerators.end() &&
"Generator not found");
720 TmpDG = std::move(*
I);
721 DefGenerators.erase(
I);
730 if (FromMR.RT->isDefunct())
731 return make_error<ResourceTrackerDefunct>(FromMR.RT);
733 std::vector<NonOwningSymbolStringPtr> AddedSyms;
734 std::vector<NonOwningSymbolStringPtr> RejectedWeakDefs;
736 for (
auto SFItr = SymbolFlags.begin(), SFEnd = SymbolFlags.end();
737 SFItr != SFEnd; ++SFItr) {
739 auto &Name = SFItr->first;
740 auto &Flags = SFItr->second;
742 auto EntryItr = Symbols.find(Name);
745 if (EntryItr != Symbols.end()) {
748 if (!Flags.isWeak()) {
750 for (auto &S : AddedSyms)
751 Symbols.erase(Symbols.find_as(S));
754 return make_error<DuplicateDefinition>(std::string(*Name));
758 RejectedWeakDefs.push_back(NonOwningSymbolStringPtr(Name));
769 while (!RejectedWeakDefs.empty()) {
770 SymbolFlags.erase(SymbolFlags.find_as(RejectedWeakDefs.back()));
771 RejectedWeakDefs.pop_back();
778Error JITDylib::replace(MaterializationResponsibility &FromMR,
779 std::unique_ptr<MaterializationUnit> MU) {
780 assert(MU !=
nullptr &&
"Can not replace with a null MaterializationUnit");
781 std::unique_ptr<MaterializationUnit> MustRunMU;
782 std::unique_ptr<MaterializationResponsibility> MustRunMR;
786 if (FromMR.RT->isDefunct())
787 return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
790 for (
auto &KV : MU->getSymbols()) {
791 auto SymI = Symbols.find(KV.first);
792 assert(SymI != Symbols.end() &&
"Replacing unknown symbol");
793 assert(SymI->second.getState() == SymbolState::Materializing &&
794 "Can not replace a symbol that ha is not materializing");
795 assert(!SymI->second.hasMaterializerAttached() &&
796 "Symbol should not have materializer attached already");
797 assert(UnmaterializedInfos.count(KV.first) == 0 &&
798 "Symbol being replaced should have no UnmaterializedInfo");
806 for (
auto &KV : MU->getSymbols()) {
807 auto MII = MaterializingInfos.find(KV.first);
808 if (MII != MaterializingInfos.end()) {
809 if (MII->second.hasQueriesPending()) {
810 MustRunMR = ES.createMaterializationResponsibility(
811 *FromMR.RT, std::move(MU->SymbolFlags),
812 std::move(MU->InitSymbol));
813 MustRunMU = std::move(MU);
814 return Error::success();
820 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU),
822 for (
auto &KV : UMI->MU->getSymbols()) {
823 auto SymI = Symbols.find(KV.first);
824 assert(SymI->second.getState() == SymbolState::Materializing &&
825 "Can not replace a symbol that is not materializing");
826 assert(!SymI->second.hasMaterializerAttached() &&
827 "Can not replace a symbol that has a materializer attached");
828 assert(UnmaterializedInfos.count(KV.first) == 0 &&
829 "Unexpected materializer entry in map");
830 SymI->second.setAddress(SymI->second.getAddress());
831 SymI->second.setMaterializerAttached(
true);
833 auto &UMIEntry = UnmaterializedInfos[KV.first];
834 assert((!UMIEntry || !UMIEntry->MU) &&
835 "Replacing symbol with materializer still attached");
846 assert(MustRunMR &&
"MustRunMU set implies MustRunMR set");
848 std::move(MustRunMU), std::move(MustRunMR)));
850 assert(!MustRunMR &&
"MustRunMU unset implies MustRunMR unset");
856Expected<std::unique_ptr<MaterializationResponsibility>>
857JITDylib::delegate(MaterializationResponsibility &FromMR,
858 SymbolFlagsMap SymbolFlags, SymbolStringPtr InitSymbol) {
861 [&]() -> Expected<std::unique_ptr<MaterializationResponsibility>> {
862 if (FromMR.RT->isDefunct())
863 return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
865 return ES.createMaterializationResponsibility(
866 *FromMR.RT, std::move(SymbolFlags), std::move(InitSymbol));
871JITDylib::getRequestedSymbols(
const SymbolFlagsMap &SymbolFlags)
const {
875 for (
auto &KV : SymbolFlags) {
876 assert(Symbols.count(KV.first) &&
"JITDylib does not cover this symbol?");
877 assert(Symbols.find(KV.first)->second.getState() !=
878 SymbolState::NeverSearched &&
879 Symbols.find(KV.first)->second.getState() != SymbolState::Ready &&
880 "getRequestedSymbols can only be called for symbols that have "
881 "started materializing");
882 auto I = MaterializingInfos.find(KV.first);
883 if (
I == MaterializingInfos.end())
886 if (
I->second.hasQueriesPending())
887 RequestedSymbols.insert(KV.first);
890 return RequestedSymbols;
894Error JITDylib::resolve(MaterializationResponsibility &MR,
895 const SymbolMap &Resolved) {
896 AsynchronousSymbolQuerySet CompletedQueries;
899 if (MR.RT->isDefunct())
900 return make_error<ResourceTrackerDefunct>(MR.RT);
903 return make_error<StringError>(
"JITDylib " + getName() +
905 inconvertibleErrorCode());
907 struct WorklistEntry {
908 SymbolTable::iterator SymI;
909 ExecutorSymbolDef ResolvedSym;
912 SymbolNameSet SymbolsInErrorState;
913 std::vector<WorklistEntry> Worklist;
917 for (
const auto &KV : Resolved) {
919 assert(!KV.second.getFlags().hasError() &&
920 "Resolution result can not have error flag set");
922 auto SymI = Symbols.find(KV.first);
924 assert(SymI != Symbols.end() &&
"Symbol not found");
925 assert(!SymI->second.hasMaterializerAttached() &&
926 "Resolving symbol with materializer attached?");
927 assert(SymI->second.getState() == SymbolState::Materializing &&
928 "Symbol should be materializing");
929 assert(SymI->second.getAddress() == ExecutorAddr() &&
930 "Symbol has already been resolved");
932 if (SymI->second.getFlags().hasError())
933 SymbolsInErrorState.insert(KV.first);
935 if (SymI->second.getFlags() & JITSymbolFlags::Common) {
936 [[maybe_unused]]
auto WeakOrCommon =
937 JITSymbolFlags::Weak | JITSymbolFlags::Common;
938 assert((KV.second.getFlags() & WeakOrCommon) &&
939 "Common symbols must be resolved as common or weak");
940 assert((KV.second.getFlags() & ~WeakOrCommon) ==
941 (SymI->second.getFlags() & ~JITSymbolFlags::Common) &&
942 "Resolving symbol with incorrect flags");
945 assert(KV.second.getFlags() == SymI->second.getFlags() &&
946 "Resolved flags should match the declared flags");
949 {SymI, {KV.second.getAddress(), SymI->second.getFlags()}});
954 if (!SymbolsInErrorState.empty()) {
955 auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
956 (*FailedSymbolsDepMap)[
this] = std::move(SymbolsInErrorState);
957 return make_error<FailedToMaterialize>(
958 getExecutionSession().getSymbolStringPool(),
959 std::move(FailedSymbolsDepMap));
962 while (!Worklist.empty()) {
963 auto SymI = Worklist.back().SymI;
964 auto ResolvedSym = Worklist.back().ResolvedSym;
967 auto &
Name = SymI->first;
970 JITSymbolFlags ResolvedFlags = ResolvedSym.getFlags();
971 SymI->second.setAddress(ResolvedSym.getAddress());
972 SymI->second.setFlags(ResolvedFlags);
973 SymI->second.setState(SymbolState::Resolved);
975 auto MII = MaterializingInfos.find(
Name);
976 if (MII == MaterializingInfos.end())
979 auto &
MI = MII->second;
980 for (
auto &Q :
MI.takeQueriesMeeting(SymbolState::Resolved)) {
981 Q->notifySymbolMetRequiredState(
Name, ResolvedSym);
982 Q->removeQueryDependence(*
this,
Name);
984 CompletedQueries.insert(std::move(Q));
988 return Error::success();
993 for (
auto &Q : CompletedQueries) {
994 assert(Q->isComplete() &&
"Q not completed");
995 Q->handleComplete(ES);
998 return Error::success();
1001void JITDylib::unlinkMaterializationResponsibility(
1002 MaterializationResponsibility &MR) {
1004 auto I = TrackerMRs.find(MR.RT.get());
1005 assert(
I != TrackerMRs.end() &&
"No MRs in TrackerMRs list for RT");
1006 assert(
I->second.count(&MR) &&
"MR not in TrackerMRs list for RT");
1007 I->second.erase(&MR);
1008 if (
I->second.empty())
1009 TrackerMRs.erase(MR.RT.get());
1013void JITDylib::shrinkMaterializationInfoMemory() {
1017 if (UnmaterializedInfos.empty())
1018 UnmaterializedInfos.clear();
1020 if (MaterializingInfos.empty())
1021 MaterializingInfos.clear();
1025 bool LinkAgainstThisJITDylibFirst) {
1027 assert(State == Open &&
"JD is defunct");
1028 if (LinkAgainstThisJITDylibFirst) {
1030 if (NewLinkOrder.empty() || NewLinkOrder.front().first !=
this)
1031 LinkOrder.push_back(
1032 std::make_pair(
this, JITDylibLookupFlags::MatchAllSymbols));
1035 LinkOrder = std::move(NewLinkOrder);
1041 for (
auto &KV : NewLinks) {
1046 LinkOrder.push_back(std::move(KV));
1058 assert(State == Open &&
"JD is defunct");
1059 for (
auto &KV : LinkOrder)
1060 if (KV.first == &OldJD) {
1061 KV = {&NewJD, JDLookupFlags};
1069 assert(State == Open &&
"JD is defunct");
1071 [&](
const JITDylibSearchOrder::value_type &KV) {
1072 return KV.first == &JD;
1074 if (
I != LinkOrder.end())
1081 assert(State == Open &&
"JD is defunct");
1082 using SymbolMaterializerItrPair =
1083 std::pair<SymbolTable::iterator, UnmaterializedInfosMap::iterator>;
1084 std::vector<SymbolMaterializerItrPair> SymbolsToRemove;
1088 for (
auto &
Name : Names) {
1089 auto I = Symbols.find(
Name);
1092 if (
I == Symbols.end()) {
1093 Missing.insert(
Name);
1098 if (
I->second.getState() != SymbolState::NeverSearched &&
1099 I->second.getState() != SymbolState::Ready) {
1104 auto UMII =
I->second.hasMaterializerAttached()
1105 ? UnmaterializedInfos.find(
Name)
1106 : UnmaterializedInfos.end();
1107 SymbolsToRemove.push_back(std::make_pair(
I, UMII));
1111 if (!Missing.empty())
1113 std::move(Missing));
1121 for (
auto &SymbolMaterializerItrPair : SymbolsToRemove) {
1122 auto UMII = SymbolMaterializerItrPair.second;
1125 if (UMII != UnmaterializedInfos.end()) {
1126 UMII->second->MU->doDiscard(*
this, UMII->first);
1127 UnmaterializedInfos.erase(UMII);
1130 auto SymI = SymbolMaterializerItrPair.first;
1131 Symbols.erase(SymI);
1134 shrinkMaterializationInfoMemory();
1136 return Error::success();
1142 OS <<
"JITDylib \"" <<
getName() <<
"\" (ES: "
1143 <<
format(
"0x%016" PRIx64,
reinterpret_cast<uintptr_t
>(&ES))
1157 if (State == Closed)
1159 OS <<
"Link order: " << LinkOrder <<
"\n"
1160 <<
"Symbol table:\n";
1163 std::vector<std::pair<SymbolStringPtr, SymbolTableEntry *>> SymbolsSorted;
1164 for (
auto &KV : Symbols)
1165 SymbolsSorted.emplace_back(KV.first, &KV.second);
1166 std::sort(SymbolsSorted.begin(), SymbolsSorted.end(),
1167 [](
const auto &L,
const auto &R) { return *L.first < *R.first; });
1169 for (
auto &KV : SymbolsSorted) {
1170 OS <<
" \"" << *KV.first <<
"\": ";
1171 if (
auto Addr = KV.second->getAddress())
1174 OS <<
"<not resolved> ";
1176 OS <<
" " << KV.second->getFlags() <<
" " << KV.second->getState();
1178 if (KV.second->hasMaterializerAttached()) {
1179 OS <<
" (Materializer ";
1180 auto I = UnmaterializedInfos.find(KV.first);
1181 assert(
I != UnmaterializedInfos.end() &&
1182 "Lazy symbol should have UnmaterializedInfo");
1183 OS <<
I->second->MU.get() <<
", " <<
I->second->MU->getName() <<
")\n";
1188 if (!MaterializingInfos.empty())
1189 OS <<
" MaterializingInfos entries:\n";
1190 for (
auto &KV : MaterializingInfos) {
1191 OS <<
" \"" << *KV.first <<
"\":\n"
1192 <<
" " << KV.second.pendingQueries().size()
1193 <<
" pending queries: { ";
1194 for (
const auto &Q : KV.second.pendingQueries())
1195 OS << Q.get() <<
" (" << Q->getRequiredState() <<
") ";
1196 OS <<
"}\n Defining EDU: ";
1197 if (KV.second.DefiningEDU) {
1198 OS << KV.second.DefiningEDU.get() <<
" { ";
1199 for (
auto &[
Name, Flags] : KV.second.DefiningEDU->Symbols)
1202 OS <<
" Dependencies:\n";
1203 if (!KV.second.DefiningEDU->Dependencies.empty()) {
1204 for (
auto &[DepJD, Deps] : KV.second.DefiningEDU->Dependencies) {
1205 OS <<
" " << DepJD->getName() <<
": [ ";
1206 for (
auto &Dep : Deps)
1214 OS <<
" Dependant EDUs:\n";
1215 if (!KV.second.DependantEDUs.empty()) {
1216 for (
auto &DependantEDU : KV.second.DependantEDUs) {
1217 OS <<
" " << DependantEDU <<
": "
1218 << DependantEDU->JD->getName() <<
" { ";
1219 for (
auto &[
Name, Flags] : DependantEDU->Symbols)
1225 assert((Symbols[KV.first].getState() != SymbolState::Ready ||
1226 (KV.second.pendingQueries().empty() && !KV.second.DefiningEDU &&
1227 !KV.second.DependantEDUs.empty())) &&
1228 "Stale materializing info entry");
1233void JITDylib::MaterializingInfo::addQuery(
1234 std::shared_ptr<AsynchronousSymbolQuery> Q) {
1238 [](
const std::shared_ptr<AsynchronousSymbolQuery> &V,
SymbolState S) {
1239 return V->getRequiredState() <= S;
1241 PendingQueries.insert(
I.base(), std::move(Q));
1244void JITDylib::MaterializingInfo::removeQuery(
1245 const AsynchronousSymbolQuery &Q) {
1248 PendingQueries, [&Q](
const std::shared_ptr<AsynchronousSymbolQuery> &V) {
1249 return V.get() == &Q;
1251 assert(
I != PendingQueries.end() &&
1252 "Query is not attached to this MaterializingInfo");
1253 PendingQueries.erase(
I);
1256JITDylib::AsynchronousSymbolQueryList
1257JITDylib::MaterializingInfo::takeQueriesMeeting(SymbolState RequiredState) {
1258 AsynchronousSymbolQueryList
Result;
1259 while (!PendingQueries.empty()) {
1260 if (PendingQueries.back()->getRequiredState() > RequiredState)
1263 Result.push_back(std::move(PendingQueries.back()));
1264 PendingQueries.pop_back();
1270JITDylib::JITDylib(ExecutionSession &ES, std::string
Name)
1275std::pair<JITDylib::AsynchronousSymbolQuerySet,
1276 std::shared_ptr<SymbolDependenceMap>>
1277JITDylib::IL_removeTracker(ResourceTracker &RT) {
1279 assert(State != Closed &&
"JD is defunct");
1284 if (&RT == DefaultTracker.
get()) {
1286 for (
auto &KV : TrackerSymbols)
1287 for (
auto &
Sym : KV.second)
1290 for (
auto &KV : Symbols) {
1291 auto &
Sym = KV.first;
1292 if (!TrackedSymbols.count(
Sym))
1293 SymbolsToRemove.push_back(
Sym);
1296 DefaultTracker.
reset();
1299 auto I = TrackerSymbols.find(&RT);
1300 if (
I != TrackerSymbols.end()) {
1301 SymbolsToRemove = std::move(
I->second);
1302 TrackerSymbols.erase(
I);
1307 for (
auto &
Sym : SymbolsToRemove) {
1308 assert(Symbols.count(
Sym) &&
"Symbol not in symbol table");
1311 auto MII = MaterializingInfos.
find(
Sym);
1312 if (MII != MaterializingInfos.
end())
1313 SymbolsToFail.push_back(
Sym);
1316 auto Result = ES.IL_failSymbols(*
this, std::move(SymbolsToFail));
1319 for (
auto &
Sym : SymbolsToRemove) {
1320 auto I = Symbols.find(
Sym);
1321 assert(
I != Symbols.end() &&
"Symbol not present in table");
1324 if (
I->second.hasMaterializerAttached()) {
1329 "Symbol has materializer attached");
1335 shrinkMaterializationInfoMemory();
1340void JITDylib::transferTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT) {
1341 assert(State != Closed &&
"JD is defunct");
1342 assert(&DstRT != &SrcRT &&
"No-op transfers shouldn't call transferTracker");
1343 assert(&DstRT.getJITDylib() ==
this &&
"DstRT is not for this JITDylib");
1344 assert(&SrcRT.getJITDylib() ==
this &&
"SrcRT is not for this JITDylib");
1347 for (
auto &KV : UnmaterializedInfos) {
1348 if (KV.second->RT == &SrcRT)
1349 KV.second->RT = &DstRT;
1354 auto I = TrackerMRs.find(&SrcRT);
1355 if (
I != TrackerMRs.end()) {
1356 auto &SrcMRs =
I->second;
1357 auto &DstMRs = TrackerMRs[&DstRT];
1358 for (
auto *MR : SrcMRs)
1361 DstMRs = std::move(SrcMRs);
1363 for (
auto *MR : SrcMRs)
1367 TrackerMRs.erase(&SrcRT);
1373 if (&DstRT == DefaultTracker.
get()) {
1374 TrackerSymbols.erase(&SrcRT);
1380 if (&SrcRT == DefaultTracker.
get()) {
1381 assert(!TrackerSymbols.count(&SrcRT) &&
1382 "Default tracker should not appear in TrackerSymbols");
1387 for (
auto &KV : TrackerSymbols)
1388 for (
auto &
Sym : KV.second)
1391 for (
auto &KV : Symbols) {
1392 auto &
Sym = KV.first;
1393 if (!CurrentlyTrackedSymbols.count(
Sym))
1394 SymbolsToTrack.push_back(
Sym);
1397 TrackerSymbols[&DstRT] = std::move(SymbolsToTrack);
1401 auto &DstTrackedSymbols = TrackerSymbols[&DstRT];
1405 auto SI = TrackerSymbols.find(&SrcRT);
1406 if (SI == TrackerSymbols.end())
1409 DstTrackedSymbols.reserve(DstTrackedSymbols.size() +
SI->second.size());
1410 for (
auto &
Sym :
SI->second)
1411 DstTrackedSymbols.push_back(std::move(
Sym));
1412 TrackerSymbols.erase(SI);
1415Error JITDylib::defineImpl(MaterializationUnit &MU) {
1419 std::vector<SymbolStringPtr> ExistingDefsOverridden;
1420 std::vector<SymbolStringPtr> MUDefsOverridden;
1422 for (
const auto &KV : MU.getSymbols()) {
1423 auto I = Symbols.find(KV.first);
1425 if (
I != Symbols.end()) {
1426 if (KV.second.isStrong()) {
1427 if (
I->second.getFlags().isStrong() ||
1429 Duplicates.insert(KV.first);
1432 "Overridden existing def should be in the never-searched "
1434 ExistingDefsOverridden.push_back(KV.first);
1437 MUDefsOverridden.push_back(KV.first);
1442 if (!Duplicates.empty()) {
1444 {
dbgs() <<
" Error: Duplicate symbols " << Duplicates <<
"\n"; });
1445 return make_error<DuplicateDefinition>(std::string(**Duplicates.begin()));
1450 if (!MUDefsOverridden.empty())
1451 dbgs() <<
" Defs in this MU overridden: " << MUDefsOverridden <<
"\n";
1453 for (
auto &S : MUDefsOverridden)
1454 MU.doDiscard(*
this, S);
1458 if (!ExistingDefsOverridden.empty())
1459 dbgs() <<
" Existing defs overridden by this MU: " << MUDefsOverridden
1462 for (
auto &S : ExistingDefsOverridden) {
1464 auto UMII = UnmaterializedInfos.find(S);
1465 assert(UMII != UnmaterializedInfos.end() &&
1466 "Overridden existing def should have an UnmaterializedInfo");
1467 UMII->second->MU->doDiscard(*
this, S);
1471 for (
auto &KV : MU.getSymbols()) {
1472 auto &SymEntry = Symbols[KV.first];
1473 SymEntry.setFlags(KV.second);
1475 SymEntry.setMaterializerAttached(
true);
1481void JITDylib::installMaterializationUnit(
1482 std::unique_ptr<MaterializationUnit> MU, ResourceTracker &RT) {
1485 if (&RT != DefaultTracker.
get()) {
1486 auto &TS = TrackerSymbols[&RT];
1487 TS.reserve(TS.size() + MU->getSymbols().size());
1488 for (
auto &KV : MU->getSymbols())
1489 TS.push_back(KV.first);
1492 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU), &RT);
1493 for (
auto &KV : UMI->MU->getSymbols())
1494 UnmaterializedInfos[KV.first] = UMI;
1497void JITDylib::detachQueryHelper(AsynchronousSymbolQuery &Q,
1499 for (
auto &QuerySymbol : QuerySymbols) {
1501 "QuerySymbol does not have MaterializingInfo");
1502 auto &
MI = MaterializingInfos[QuerySymbol];
1515 std::mutex LookupMutex;
1516 std::condition_variable CV;
1520 dbgs() <<
"Issuing init-symbol lookup:\n";
1521 for (
auto &KV : InitSyms)
1522 dbgs() <<
" " << KV.first->getName() <<
": " << KV.second <<
"\n";
1525 for (
auto &KV : InitSyms) {
1526 auto *JD = KV.first;
1527 auto Names = std::move(KV.second);
1534 std::lock_guard<std::mutex> Lock(LookupMutex);
1538 "Duplicate JITDylib in lookup?");
1539 CompoundResult[JD] = std::move(*
Result);
1549 std::unique_lock<std::mutex> Lock(LookupMutex);
1550 CV.wait(Lock, [&] {
return Count == 0 || CompoundErr; });
1553 return std::move(CompoundErr);
1555 return std::move(CompoundResult);
1562 class TriggerOnComplete {
1565 TriggerOnComplete(OnCompleteFn OnComplete)
1566 : OnComplete(std::move(OnComplete)) {}
1567 ~TriggerOnComplete() { OnComplete(std::move(LookupResult)); }
1568 void reportResult(
Error Err) {
1569 std::lock_guard<std::mutex> Lock(ResultMutex);
1570 LookupResult =
joinErrors(std::move(LookupResult), std::move(Err));
1574 std::mutex ResultMutex;
1575 Error LookupResult{Error::success()};
1576 OnCompleteFn OnComplete;
1580 dbgs() <<
"Issuing init-symbol lookup:\n";
1581 for (
auto &KV : InitSyms)
1582 dbgs() <<
" " << KV.first->getName() <<
": " << KV.second <<
"\n";
1585 auto TOC = std::make_shared<TriggerOnComplete>(std::move(OnComplete));
1587 for (
auto &KV : InitSyms) {
1588 auto *JD = KV.first;
1589 auto Names = std::move(KV.second);
1595 TOC->reportResult(
Result.takeError());
1602 OS <<
"Materialization task: " << MU->getName() <<
" in "
1603 << MR->getTargetJITDylib().getName();
1615 this->EPC->ES =
this;
1621 "Session still open. Did you forget to call endSession?");
1625 LLVM_DEBUG(
dbgs() <<
"Ending ExecutionSession " <<
this <<
"\n");
1629#ifdef EXPENSIVE_CHECKS
1630 verifySessionState(
"Entering ExecutionSession::endSession");
1633 SessionOpen =
false;
1637 std::reverse(JDsToRemove.begin(), JDsToRemove.end());
1641 Err =
joinErrors(std::move(Err), EPC->disconnect());
1652 assert(!ResourceManagers.empty() &&
"No managers registered");
1653 if (ResourceManagers.back() == &RM)
1654 ResourceManagers.pop_back();
1657 assert(
I != ResourceManagers.end() &&
"RM not registered");
1658 ResourceManagers.erase(
I);
1665 for (
auto &JD : JDs)
1666 if (JD->getName() ==
Name)
1675 assert(SessionOpen &&
"Cannot create JITDylib after session is closed");
1684 if (
auto Err = P->setupJITDylib(JD))
1685 return std::move(Err);
1692 for (
auto &JD : JDsToRemove) {
1693 assert(JD->State == JITDylib::Open &&
"JD already closed");
1694 JD->State = JITDylib::Closing;
1696 assert(
I != JDs.end() &&
"JD does not appear in session JDs");
1703 for (
auto JD : JDsToRemove) {
1704 Err =
joinErrors(std::move(Err), JD->clear());
1706 Err =
joinErrors(std::move(Err), P->teardownJITDylib(*JD));
1711 for (
auto &JD : JDsToRemove) {
1712 assert(JD->State == JITDylib::Closing &&
"JD should be closing");
1713 JD->State = JITDylib::Closed;
1714 assert(JD->Symbols.empty() &&
"JD.Symbols is not empty after clear");
1715 assert(JD->UnmaterializedInfos.empty() &&
1716 "JD.UnmaterializedInfos is not empty after clear");
1717 assert(JD->MaterializingInfos.empty() &&
1718 "JD.MaterializingInfos is not empty after clear");
1719 assert(JD->TrackerSymbols.empty() &&
1720 "TrackerSymbols is not empty after clear");
1721 JD->DefGenerators.clear();
1722 JD->LinkOrder.clear();
1732 return std::vector<JITDylibSP>();
1734 auto &ES = JDs.
front()->getExecutionSession();
1735 return ES.runSessionLocked([&]() ->
Expected<std::vector<JITDylibSP>> {
1737 std::vector<JITDylibSP>
Result;
1739 for (
auto &JD : JDs) {
1741 if (JD->State != Open)
1742 return make_error<StringError>(
1743 "Error building link order: " + JD->getName() +
" is defunct",
1745 if (Visited.
count(JD.get()))
1750 Visited.
insert(JD.get());
1752 while (!WorkStack.empty()) {
1753 Result.push_back(std::move(WorkStack.back()));
1754 WorkStack.pop_back();
1756 for (auto &KV : llvm::reverse(Result.back()->LinkOrder)) {
1757 auto &JD = *KV.first;
1758 if (!Visited.insert(&JD).second)
1760 WorkStack.push_back(&JD);
1788 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
1789 K, std::move(SearchOrder), std::move(LookupSet),
1790 std::move(OnComplete)),
1798 std::promise<MSVCPExpected<SymbolFlagsMap>> ResultP;
1799 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
1800 K, std::move(SearchOrder), std::move(LookupSet),
1802 ResultP.set_value(std::move(
Result));
1806 auto ResultF = ResultP.get_future();
1807 return ResultF.get();
1818 dbgs() <<
"Looking up " << Symbols <<
" in " << SearchOrder
1819 <<
" (required state: " << RequiredState <<
")\n";
1826 dispatchOutstandingMUs();
1828 auto Unresolved = std::move(Symbols);
1829 auto Q = std::make_shared<AsynchronousSymbolQuery>(Unresolved, RequiredState,
1830 std::move(NotifyComplete));
1832 auto IPLS = std::make_unique<InProgressFullLookupState>(
1833 K, SearchOrder, std::move(Unresolved), RequiredState, std::move(Q),
1834 std::move(RegisterDependencies));
1844#if LLVM_ENABLE_THREADS
1846 std::promise<SymbolMap> PromisedResult;
1851 PromisedResult.set_value(std::move(*R));
1854 ResolutionError = R.takeError();
1868 ResolutionError = R.takeError();
1873 lookup(K, SearchOrder, std::move(Symbols), RequiredState, NotifyComplete,
1874 RegisterDependencies);
1876#if LLVM_ENABLE_THREADS
1877 auto ResultFuture = PromisedResult.get_future();
1878 auto Result = ResultFuture.get();
1880 if (ResolutionError)
1881 return std::move(ResolutionError);
1883 return std::move(
Result);
1886 if (ResolutionError)
1887 return std::move(ResolutionError);
1900 assert(ResultMap->size() == 1 &&
"Unexpected number of results");
1901 assert(ResultMap->count(
Name) &&
"Missing result for symbol");
1902 return std::move(ResultMap->begin()->second);
1904 return ResultMap.takeError();
1926 return TagAddrs.takeError();
1929 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
1930 for (
auto &KV : *TagAddrs) {
1931 auto TagAddr = KV.second.getAddress();
1932 if (JITDispatchHandlers.count(TagAddr))
1933 return make_error<StringError>(
"Tag " +
formatv(
"{0:x16}", TagAddr) +
1934 " (for " + *KV.first +
1935 ") already registered",
1937 auto I = WFs.
find(KV.first);
1939 "JITDispatchHandler implementation missing");
1940 JITDispatchHandlers[KV.second.getAddress()] =
1941 std::make_shared<JITDispatchHandlerFunction>(std::move(
I->second));
1943 dbgs() <<
"Associated function tag \"" << *KV.first <<
"\" ("
1944 <<
formatv(
"{0:x}", KV.second.getAddress()) <<
") with handler\n";
1954 std::shared_ptr<JITDispatchHandlerFunction>
F;
1956 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
1957 auto I = JITDispatchHandlers.find(HandlerFnTagAddr);
1958 if (
I != JITDispatchHandlers.end())
1963 (*F)(std::move(SendResult), ArgBuffer.
data(), ArgBuffer.
size());
1966 (
"No function registered for tag " +
1967 formatv(
"{0:x16}", HandlerFnTagAddr))
1973 for (
auto &JD : JDs)
1978#ifdef EXPENSIVE_CHECKS
1979bool ExecutionSession::verifySessionState(
Twine Phase) {
1986 for (
auto &JD : JDs) {
1989 auto &Stream =
errs();
1991 Stream <<
"ERROR: Bad ExecutionSession state detected " <<
Phase
1993 Stream <<
" In JITDylib " << JD->getName() <<
", ";
1998 if (JD->State != JITDylib::Open) {
2000 <<
"state is not Open, but JD is in ExecutionSession list.";
2008 for (
auto &[
Sym, Entry] : JD->Symbols) {
2011 if (Entry.getAddress()) {
2012 LogFailure() <<
"symbol " <<
Sym <<
" has state "
2014 <<
" (not-yet-resolved) but non-null address "
2015 << Entry.getAddress() <<
".\n";
2020 auto UMIItr = JD->UnmaterializedInfos.find(
Sym);
2021 if (
Entry.hasMaterializerAttached()) {
2022 if (UMIItr == JD->UnmaterializedInfos.end()) {
2023 LogFailure() <<
"symbol " <<
Sym
2024 <<
" entry claims materializer attached, but "
2025 "UnmaterializedInfos has no corresponding entry.\n";
2027 }
else if (UMIItr != JD->UnmaterializedInfos.end()) {
2030 <<
" entry claims no materializer attached, but "
2031 "UnmaterializedInfos has an unexpected entry for it.\n";
2037 for (
auto &[
Sym, UMI] : JD->UnmaterializedInfos) {
2038 auto SymItr = JD->Symbols.find(
Sym);
2039 if (SymItr == JD->Symbols.end()) {
2042 <<
" has UnmaterializedInfos entry, but no Symbols entry.\n";
2047 for (
auto &[
Sym, MII] : JD->MaterializingInfos) {
2049 auto SymItr = JD->Symbols.find(
Sym);
2050 if (SymItr == JD->Symbols.end()) {
2055 <<
" has MaterializingInfos entry, but no Symbols entry.\n";
2063 <<
" is in Ready state, should not have MaterializingInfo.\n";
2068 static_cast<std::underlying_type_t<SymbolState>
>(
2069 SymItr->second.getState()) + 1);
2070 for (
auto &Q : MII.PendingQueries) {
2071 if (Q->getRequiredState() != CurState) {
2072 if (Q->getRequiredState() > CurState)
2073 CurState = Q->getRequiredState();
2075 LogFailure() <<
"symbol " <<
Sym
2076 <<
" has stale or misordered queries.\n";
2084 if (MII.DefiningEDU) {
2086 EDUsToCheck.
insert(MII.DefiningEDU.get());
2088 if (MII.DefiningEDU->JD != JD.get()) {
2089 LogFailure() <<
"symbol " <<
Sym
2090 <<
" has DefiningEDU with incorrect JD"
2092 ?
" (JD not currently in ExecutionSession"
2100 <<
" has DefiningEDU, but is not in Emitted state.\n";
2106 for (
auto &DepEDU : MII.DependantEDUs) {
2108 LogFailure() <<
"symbol " <<
Sym <<
" has DependantEDU "
2109 << (
void *)DepEDU <<
" with JD (" << DepEDU->JD
2110 <<
") that isn't in ExecutionSession.\n";
2118 for (
auto *EDU : EDUsToCheck) {
2119 assert(EDU->JD->State == JITDylib::Open &&
"EDU->JD is not Open");
2121 auto LogFailure = [&]() -> raw_fd_ostream & {
2123 auto &Stream =
errs();
2124 Stream <<
"In EDU defining " << EDU->JD->getName() <<
": { ";
2125 for (
auto &[
Sym, Flags] : EDU->Symbols)
2126 Stream <<
Sym <<
" ";
2131 if (EDU->Symbols.empty())
2132 LogFailure() <<
"no symbols defined.\n";
2134 for (
auto &[
Sym, Flags] : EDU->Symbols) {
2136 LogFailure() <<
"null symbol defined.\n";
2138 if (!EDU->JD->Symbols.count(SymbolStringPtr(
Sym))) {
2139 LogFailure() <<
"symbol " <<
Sym
2140 <<
" isn't present in JD's symbol table.\n";
2146 for (
auto &[DepJD, Symbols] : EDU->Dependencies) {
2148 LogFailure() <<
"dependant symbols listed for JD that isn't in "
2149 "ExecutionSession.\n";
2151 for (
auto &DepSym : Symbols) {
2152 if (!DepJD->Symbols.count(SymbolStringPtr(DepSym))) {
2154 <<
"dependant symbol " << DepSym
2155 <<
" does not appear in symbol table for dependant JD "
2156 << DepJD->getName() <<
".\n";
2168void ExecutionSession::dispatchOutstandingMUs() {
2171 std::optional<std::pair<std::unique_ptr<MaterializationUnit>,
2172 std::unique_ptr<MaterializationResponsibility>>>
2176 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2177 if (!OutstandingMUs.empty()) {
2178 JMU.emplace(std::move(OutstandingMUs.back()));
2179 OutstandingMUs.pop_back();
2186 assert(JMU->first &&
"No MU?");
2187 LLVM_DEBUG(
dbgs() <<
" Dispatching \"" << JMU->first->getName() <<
"\"\n");
2188 dispatchTask(std::make_unique<MaterializationTask>(std::move(JMU->first),
2189 std::move(JMU->second)));
2191 LLVM_DEBUG(
dbgs() <<
"Done dispatching MaterializationUnits.\n");
2194Error ExecutionSession::removeResourceTracker(ResourceTracker &RT) {
2196 dbgs() <<
"In " << RT.getJITDylib().getName() <<
" removing tracker "
2197 <<
formatv(
"{0:x}", RT.getKeyUnsafe()) <<
"\n";
2199 std::vector<ResourceManager *> CurrentResourceManagers;
2201 JITDylib::AsynchronousSymbolQuerySet QueriesToFail;
2202 std::shared_ptr<SymbolDependenceMap> FailedSymbols;
2205 CurrentResourceManagers = ResourceManagers;
2207 std::tie(QueriesToFail, FailedSymbols) =
2208 RT.getJITDylib().IL_removeTracker(RT);
2213 auto &JD = RT.getJITDylib();
2214 for (
auto *L :
reverse(CurrentResourceManagers))
2216 L->handleRemoveResources(JD, RT.getKeyUnsafe()));
2218 for (
auto &Q : QueriesToFail)
2225void ExecutionSession::transferResourceTracker(ResourceTracker &DstRT,
2226 ResourceTracker &SrcRT) {
2228 dbgs() <<
"In " << SrcRT.getJITDylib().getName()
2229 <<
" transfering resources from tracker "
2230 <<
formatv(
"{0:x}", SrcRT.getKeyUnsafe()) <<
" to tracker "
2231 <<
formatv(
"{0:x}", DstRT.getKeyUnsafe()) <<
"\n";
2235 if (&DstRT == &SrcRT)
2238 assert(&DstRT.getJITDylib() == &SrcRT.getJITDylib() &&
2239 "Can't transfer resources between JITDylibs");
2241 SrcRT.makeDefunct();
2242 auto &JD = DstRT.getJITDylib();
2243 JD.transferTracker(DstRT, SrcRT);
2244 for (
auto *L :
reverse(ResourceManagers))
2245 L->handleTransferResources(JD, DstRT.getKeyUnsafe(),
2246 SrcRT.getKeyUnsafe());
2250void ExecutionSession::destroyResourceTracker(ResourceTracker &RT) {
2253 dbgs() <<
"In " << RT.getJITDylib().getName() <<
" destroying tracker "
2254 <<
formatv(
"{0:x}", RT.getKeyUnsafe()) <<
"\n";
2256 if (!RT.isDefunct())
2257 transferResourceTracker(*RT.getJITDylib().getDefaultResourceTracker(),
2262Error ExecutionSession::IL_updateCandidatesFor(
2264 SymbolLookupSet &Candidates, SymbolLookupSet *NonCandidates) {
2265 return Candidates.forEachWithRemoval(
2266 [&](
const SymbolStringPtr &
Name,
2270 auto SymI = JD.Symbols.find(
Name);
2271 if (SymI == JD.Symbols.end())
2279 if (!SymI->second.getFlags().isExported() &&
2282 NonCandidates->add(Name, SymLookupFlags);
2291 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2298 if (SymI->second.getFlags().hasError()) {
2299 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2300 (*FailedSymbolsMap)[&JD] = {Name};
2302 std::move(FailedSymbolsMap));
2310void ExecutionSession::OL_resumeLookupAfterGeneration(
2311 InProgressLookupState &IPLS) {
2314 "Should not be called for not-in-generator lookups");
2319 if (
auto DG = IPLS.CurDefGeneratorStack.back().lock()) {
2320 IPLS.CurDefGeneratorStack.pop_back();
2321 std::lock_guard<std::mutex> Lock(DG->M);
2325 if (DG->PendingLookups.empty()) {
2331 LS = std::move(DG->PendingLookups.front());
2332 DG->PendingLookups.pop_front();
2337 dispatchTask(std::make_unique<LookupTask>(std::move(LS)));
2341void ExecutionSession::OL_applyQueryPhase1(
2342 std::unique_ptr<InProgressLookupState> IPLS, Error Err) {
2345 dbgs() <<
"Entering OL_applyQueryPhase1:\n"
2346 <<
" Lookup kind: " << IPLS->K <<
"\n"
2347 <<
" Search order: " << IPLS->SearchOrder
2348 <<
", Current index = " << IPLS->CurSearchOrderIndex
2349 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2350 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2351 <<
" Definition generator candidates: "
2352 << IPLS->DefGeneratorCandidates <<
"\n"
2353 <<
" Definition generator non-candidates: "
2354 << IPLS->DefGeneratorNonCandidates <<
"\n";
2358 OL_resumeLookupAfterGeneration(*IPLS);
2361 "Lookup should not be in InGenerator state here");
2368 while (IPLS->CurSearchOrderIndex != IPLS->SearchOrder.size()) {
2374 return IPLS->fail(std::move(Err));
2377 auto &KV = IPLS->SearchOrder[IPLS->CurSearchOrderIndex];
2378 auto &JD = *KV.first;
2379 auto JDLookupFlags = KV.second;
2382 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2383 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2387 if (IPLS->NewJITDylib) {
2391 SymbolLookupSet Tmp;
2392 std::swap(IPLS->DefGeneratorNonCandidates, Tmp);
2393 IPLS->DefGeneratorCandidates.append(std::move(Tmp));
2396 dbgs() <<
" First time visiting " << JD.getName()
2397 <<
", resetting candidate sets and building generator stack\n";
2402 IPLS->CurDefGeneratorStack.reserve(JD.DefGenerators.size());
2404 IPLS->CurDefGeneratorStack.push_back(DG);
2408 IPLS->NewJITDylib =
false;
2417 Err = IL_updateCandidatesFor(
2418 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2419 JD.DefGenerators.empty() ?
nullptr
2420 : &IPLS->DefGeneratorNonCandidates);
2422 dbgs() <<
" Remaining candidates = " << IPLS->DefGeneratorCandidates
2430 IPLS->DefGeneratorCandidates.empty())
2431 OL_resumeLookupAfterGeneration(*IPLS);
2437 return IPLS->fail(std::move(Err));
2441 if (IPLS->CurDefGeneratorStack.empty())
2442 LLVM_DEBUG(
dbgs() <<
" No generators to run for this JITDylib.\n");
2443 else if (IPLS->DefGeneratorCandidates.empty())
2446 dbgs() <<
" Running " << IPLS->CurDefGeneratorStack.size()
2447 <<
" remaining generators for "
2448 << IPLS->DefGeneratorCandidates.size() <<
" candidates\n";
2450 while (!IPLS->CurDefGeneratorStack.empty() &&
2451 !IPLS->DefGeneratorCandidates.empty()) {
2452 auto DG = IPLS->CurDefGeneratorStack.back().lock();
2455 return IPLS->fail(make_error<StringError>(
2456 "DefinitionGenerator removed while lookup in progress",
2469 std::lock_guard<std::mutex> Lock(DG->M);
2471 DG->PendingLookups.push_back(std::move(IPLS));
2480 auto &LookupSet = IPLS->DefGeneratorCandidates;
2485 LLVM_DEBUG(
dbgs() <<
" Attempting to generate " << LookupSet <<
"\n");
2487 Err = DG->tryToGenerate(LS, K, JD, JDLookupFlags, LookupSet);
2488 IPLS = std::move(
LS.IPLS);
2494 OL_resumeLookupAfterGeneration(*IPLS);
2499 dbgs() <<
" Error attempting to generate " << LookupSet <<
"\n";
2501 assert(IPLS &&
"LS cannot be retained if error is returned");
2502 return IPLS->fail(std::move(Err));
2508 {
dbgs() <<
" LookupState captured. Exiting phase1 for now.\n"; });
2515 LLVM_DEBUG(
dbgs() <<
" Updating candidate set post-generation\n");
2516 Err = IL_updateCandidatesFor(
2517 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2518 JD.DefGenerators.empty() ?
nullptr
2519 : &IPLS->DefGeneratorNonCandidates);
2524 LLVM_DEBUG(
dbgs() <<
" Error encountered while updating candidates\n");
2525 return IPLS->fail(std::move(Err));
2529 if (IPLS->DefGeneratorCandidates.empty() &&
2530 IPLS->DefGeneratorNonCandidates.empty()) {
2533 IPLS->CurSearchOrderIndex = IPLS->SearchOrder.size();
2539 ++IPLS->CurSearchOrderIndex;
2540 IPLS->NewJITDylib =
true;
2545 IPLS->DefGeneratorCandidates.remove_if(
2553 if (IPLS->DefGeneratorCandidates.empty()) {
2555 IPLS->complete(std::move(IPLS));
2557 LLVM_DEBUG(
dbgs() <<
"Phase 1 failed with unresolved symbols.\n");
2558 IPLS->fail(make_error<SymbolsNotFound>(
2563void ExecutionSession::OL_completeLookup(
2564 std::unique_ptr<InProgressLookupState> IPLS,
2565 std::shared_ptr<AsynchronousSymbolQuery> Q,
2569 dbgs() <<
"Entering OL_completeLookup:\n"
2570 <<
" Lookup kind: " << IPLS->K <<
"\n"
2571 <<
" Search order: " << IPLS->SearchOrder
2572 <<
", Current index = " << IPLS->CurSearchOrderIndex
2573 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2574 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2575 <<
" Definition generator candidates: "
2576 << IPLS->DefGeneratorCandidates <<
"\n"
2577 <<
" Definition generator non-candidates: "
2578 << IPLS->DefGeneratorNonCandidates <<
"\n";
2581 bool QueryComplete =
false;
2582 DenseMap<JITDylib *, JITDylib::UnmaterializedInfosList> CollectedUMIs;
2585 for (
auto &KV : IPLS->SearchOrder) {
2586 auto &JD = *KV.first;
2587 auto JDLookupFlags = KV.second;
2589 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2590 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2593 auto Err = IPLS->LookupSet.forEachWithRemoval(
2594 [&](
const SymbolStringPtr &
Name,
2597 dbgs() <<
" Attempting to match \"" <<
Name <<
"\" ("
2598 << SymLookupFlags <<
")... ";
2603 auto SymI = JD.Symbols.find(
Name);
2604 if (SymI == JD.Symbols.end()) {
2611 if (!SymI->second.getFlags().isExported() &&
2623 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2627 "required, but symbol is has-side-effects-only\n";
2635 if (SymI->second.getFlags().hasError()) {
2637 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2638 (*FailedSymbolsMap)[&JD] = {
Name};
2639 return make_error<FailedToMaterialize>(
2647 if (SymI->second.getState() >= Q->getRequiredState()) {
2649 <<
"matched, symbol already in required state\n");
2650 Q->notifySymbolMetRequiredState(
Name, SymI->second.getSymbol());
2657 if (SymI->second.hasMaterializerAttached()) {
2658 assert(SymI->second.getAddress() == ExecutorAddr() &&
2659 "Symbol not resolved but already has address?");
2660 auto UMII = JD.UnmaterializedInfos.find(
Name);
2661 assert(UMII != JD.UnmaterializedInfos.end() &&
2662 "Lazy symbol should have UnmaterializedInfo");
2664 auto UMI = UMII->second;
2665 assert(UMI->MU &&
"Materializer should not be null");
2666 assert(UMI->RT &&
"Tracker should not be null");
2668 dbgs() <<
"matched, preparing to dispatch MU@" << UMI->MU.get()
2669 <<
" (" << UMI->MU->getName() <<
")\n";
2674 for (
auto &KV : UMI->MU->getSymbols()) {
2675 auto SymK = JD.Symbols.find(KV.first);
2676 assert(SymK != JD.Symbols.end() &&
2677 "No entry for symbol covered by MaterializationUnit");
2678 SymK->second.setMaterializerAttached(
false);
2680 JD.UnmaterializedInfos.erase(KV.first);
2684 CollectedUMIs[&JD].push_back(std::move(UMI));
2692 "By this line the symbol should be materializing");
2693 auto &
MI = JD.MaterializingInfos[
Name];
2695 Q->addQueryDependence(JD,
Name);
2700 JD.shrinkMaterializationInfoMemory();
2706 dbgs() <<
"Lookup failed. Detaching query and replacing MUs.\n";
2713 for (
auto &KV : CollectedUMIs) {
2714 auto &JD = *KV.first;
2715 for (
auto &UMI : KV.second)
2716 for (
auto &KV2 : UMI->MU->getSymbols()) {
2717 assert(!JD.UnmaterializedInfos.count(KV2.first) &&
2718 "Unexpected materializer in map");
2719 auto SymI = JD.Symbols.find(KV2.first);
2720 assert(SymI != JD.Symbols.end() &&
"Missing symbol entry");
2722 "Can not replace symbol that is not materializing");
2723 assert(!SymI->second.hasMaterializerAttached() &&
2724 "MaterializerAttached flag should not be set");
2725 SymI->second.setMaterializerAttached(
true);
2726 JD.UnmaterializedInfos[KV2.first] = UMI;
2734 LLVM_DEBUG(
dbgs() <<
"Stripping unmatched weakly-referenced symbols\n");
2735 IPLS->LookupSet.forEachWithRemoval(
2738 Q->dropSymbol(
Name);
2744 if (!IPLS->LookupSet.empty()) {
2747 IPLS->LookupSet.getSymbolNames());
2751 QueryComplete = Q->isComplete();
2754 dbgs() <<
"Query successfully "
2755 << (QueryComplete ?
"completed" :
"lodged") <<
"\n";
2759 if (!CollectedUMIs.empty()) {
2760 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2763 for (
auto &KV : CollectedUMIs) {
2765 auto &JD = *KV.first;
2766 dbgs() <<
" For " << JD.getName() <<
": Adding " << KV.second.size()
2769 for (
auto &UMI : KV.second) {
2770 auto MR = createMaterializationResponsibility(
2771 *UMI->RT, std::move(UMI->MU->SymbolFlags),
2772 std::move(UMI->MU->InitSymbol));
2773 OutstandingMUs.push_back(
2774 std::make_pair(std::move(UMI->MU), std::move(MR)));
2780 if (RegisterDependencies && !Q->QueryRegistrations.empty()) {
2782 RegisterDependencies(Q->QueryRegistrations);
2792 Q->handleFailed(std::move(LodgingErr));
2796 if (QueryComplete) {
2798 Q->handleComplete(*
this);
2801 dispatchOutstandingMUs();
2804void ExecutionSession::OL_completeLookupFlags(
2805 std::unique_ptr<InProgressLookupState> IPLS,
2806 unique_function<
void(Expected<SymbolFlagsMap>)> OnComplete) {
2810 dbgs() <<
"Entering OL_completeLookupFlags:\n"
2811 <<
" Lookup kind: " << IPLS->K <<
"\n"
2812 <<
" Search order: " << IPLS->SearchOrder
2813 <<
", Current index = " << IPLS->CurSearchOrderIndex
2814 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2815 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2816 <<
" Definition generator candidates: "
2817 << IPLS->DefGeneratorCandidates <<
"\n"
2818 <<
" Definition generator non-candidates: "
2819 << IPLS->DefGeneratorNonCandidates <<
"\n";
2825 for (
auto &KV : IPLS->SearchOrder) {
2826 auto &JD = *KV.first;
2827 auto JDLookupFlags = KV.second;
2829 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2830 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2833 IPLS->LookupSet.forEachWithRemoval([&](
const SymbolStringPtr &
Name,
2836 dbgs() <<
" Attempting to match \"" <<
Name <<
"\" ("
2837 << SymLookupFlags <<
")... ";
2842 auto SymI = JD.Symbols.find(
Name);
2843 if (SymI == JD.Symbols.end()) {
2849 if (!SymI->second.getFlags().isExported() &&
2856 dbgs() <<
"matched, \"" <<
Name <<
"\" -> " << SymI->second.getFlags()
2865 IPLS->LookupSet.remove_if(
2870 if (!IPLS->LookupSet.empty()) {
2873 IPLS->LookupSet.getSymbolNames());
2882 OnComplete(std::move(
Result));
2885void ExecutionSession::OL_destroyMaterializationResponsibility(
2886 MaterializationResponsibility &MR) {
2888 assert(MR.SymbolFlags.empty() &&
2889 "All symbols should have been explicitly materialized or failed");
2890 MR.JD.unlinkMaterializationResponsibility(MR);
2894 const MaterializationResponsibility &MR) {
2895 return MR.JD.getRequestedSymbols(MR.SymbolFlags);
2898Error ExecutionSession::OL_notifyResolved(MaterializationResponsibility &MR,
2901 dbgs() <<
"In " << MR.JD.getName() <<
" resolving " << Symbols <<
"\n";
2904 for (
auto &KV : Symbols) {
2905 auto I = MR.SymbolFlags.find(KV.first);
2906 assert(
I != MR.SymbolFlags.end() &&
2907 "Resolving symbol outside this responsibility set");
2908 assert(!
I->second.hasMaterializationSideEffectsOnly() &&
2909 "Can't resolve materialization-side-effects-only symbol");
2912 assert((KV.second.getFlags() & WeakOrCommon) &&
2913 "Common symbols must be resolved as common or weak");
2914 assert((KV.second.getFlags() & ~WeakOrCommon) ==
2916 "Resolving symbol with incorrect flags");
2918 assert(KV.second.getFlags() ==
I->second &&
2919 "Resolving symbol with incorrect flags");
2923 return MR.JD.resolve(MR, Symbols);
2926template <
typename HandleNewDepFn>
2927void ExecutionSession::propagateExtraEmitDeps(
2928 std::deque<JITDylib::EmissionDepUnit *> Worklist, EDUInfosMap &EDUInfos,
2929 HandleNewDepFn HandleNewDep) {
2933 while (!Worklist.empty()) {
2934 auto &EDU = *Worklist.front();
2935 Worklist.pop_front();
2937 assert(EDUInfos.count(&EDU) &&
"No info entry for EDU");
2938 auto &EDUInfo = EDUInfos[&EDU];
2941 for (
auto *UserEDU : EDUInfo.IntraEmitUsers) {
2944 JITDylib::EmissionDepUnitInfo *UserEDUInfo =
nullptr;
2946 auto UserEDUInfoItr = EDUInfos.find(UserEDU);
2947 if (UserEDUInfoItr != EDUInfos.end())
2948 UserEDUInfo = &UserEDUInfoItr->second;
2951 for (
auto &[DepJD, Deps] : EDUInfo.NewDeps) {
2952 auto &UserEDUDepsForJD = UserEDU->Dependencies[DepJD];
2953 DenseSet<NonOwningSymbolStringPtr> *UserEDUNewDepsForJD =
nullptr;
2954 for (
auto Dep : Deps) {
2955 if (UserEDUDepsForJD.insert(Dep).second) {
2956 HandleNewDep(*UserEDU, *DepJD, Dep);
2958 if (!UserEDUNewDepsForJD) {
2961 if (UserEDUInfo->NewDeps.empty())
2962 Worklist.push_back(UserEDU);
2963 UserEDUNewDepsForJD = &UserEDUInfo->NewDeps[DepJD];
2966 UserEDUNewDepsForJD->insert(Dep);
2973 EDUInfo.NewDeps.clear();
2978ExecutionSession::EDUInfosMap ExecutionSession::simplifyDepGroups(
2979 MaterializationResponsibility &MR,
2980 ArrayRef<SymbolDependenceGroup> EmittedDeps) {
2982 auto &TargetJD = MR.getTargetJITDylib();
2986 DenseMap<JITDylib::EmissionDepUnit *, JITDylib::EmissionDepUnitInfo> EDUInfos;
2987 EDUInfos.reserve(EmittedDeps.size());
2988 DenseMap<NonOwningSymbolStringPtr, JITDylib::EmissionDepUnit *> EDUForSymbol;
2989 for (
auto &DG : EmittedDeps) {
2990 assert(!DG.Symbols.empty() &&
"DepGroup does not cover any symbols");
2993 if (DG.Dependencies.empty())
2996 auto TmpEDU = std::make_shared<JITDylib::EmissionDepUnit>(TargetJD);
2997 auto &EDUInfo = EDUInfos[TmpEDU.get()];
2998 EDUInfo.EDU = std::move(TmpEDU);
2999 for (
const auto &Symbol : DG.Symbols) {
3000 NonOwningSymbolStringPtr NonOwningSymbol(Symbol);
3001 assert(!EDUForSymbol.count(NonOwningSymbol) &&
3002 "Symbol should not appear in more than one SymbolDependenceGroup");
3003 assert(MR.getSymbols().count(Symbol) &&
3004 "Symbol in DepGroups not in the emitted set");
3005 auto NewlyEmittedItr = MR.getSymbols().find(Symbol);
3006 EDUInfo.EDU->Symbols[NonOwningSymbol] = NewlyEmittedItr->second;
3007 EDUForSymbol[NonOwningSymbol] = EDUInfo.EDU.get();
3013 DenseMap<NonOwningSymbolStringPtr, JITSymbolFlags> ResidualSymbolFlags;
3014 for (
auto &[
Sym, Flags] : MR.getSymbols()) {
3015 if (!EDUForSymbol.count(NonOwningSymbolStringPtr(
Sym)))
3016 ResidualSymbolFlags[NonOwningSymbolStringPtr(
Sym)] =
Flags;
3018 if (!ResidualSymbolFlags.empty()) {
3019 auto ResidualEDU = std::make_shared<JITDylib::EmissionDepUnit>(TargetJD);
3020 ResidualEDU->Symbols = std::move(ResidualSymbolFlags);
3021 auto &ResidualEDUInfo = EDUInfos[ResidualEDU.get()];
3022 ResidualEDUInfo.EDU = std::move(ResidualEDU);
3025 if (EDUInfos.size() == 1)
3029 for (
auto &[
Sym, Flags] : ResidualEDUInfo.EDU->Symbols)
3030 EDUForSymbol[
Sym] = ResidualEDUInfo.EDU.get();
3035 assert(EDUForSymbol.size() == MR.getSymbols().size() &&
3036 "MR symbols not fully covered by EDUs?");
3037 for (
auto &[
Sym, Flags] : MR.getSymbols()) {
3038 assert(EDUForSymbol.count(NonOwningSymbolStringPtr(
Sym)) &&
3039 "Sym in MR not covered by EDU");
3047 for (
auto &DG : EmittedDeps) {
3050 if (DG.Dependencies.empty())
3053 assert(EDUForSymbol.count(NonOwningSymbolStringPtr(*DG.Symbols.begin())) &&
3056 *EDUForSymbol.find(NonOwningSymbolStringPtr(*DG.Symbols.begin()))
3059 for (
auto &[DepJD, Deps] : DG.Dependencies) {
3060 DenseSet<NonOwningSymbolStringPtr> NewDepsForJD;
3062 assert(!Deps.empty() &&
"Dependence set for DepJD is empty");
3064 if (DepJD != &TargetJD) {
3067 for (
auto &Dep : Deps)
3068 NewDepsForJD.insert(NonOwningSymbolStringPtr(Dep));
3072 for (
auto &Dep : Deps) {
3073 NonOwningSymbolStringPtr NonOwningDep(Dep);
3074 auto I = EDUForSymbol.find(NonOwningDep);
3075 if (
I == EDUForSymbol.end()) {
3076 if (!MR.getSymbols().count(Dep))
3077 NewDepsForJD.insert(NonOwningDep);
3081 if (
I->second != &EDU)
3082 EDUInfos[
I->second].IntraEmitUsers.insert(&EDU);
3086 if (!NewDepsForJD.empty())
3087 EDU.Dependencies[DepJD] = std::move(NewDepsForJD);
3092 std::deque<JITDylib::EmissionDepUnit *> Worklist;
3093 for (
auto &[EDU, EDUInfo] : EDUInfos) {
3096 if (!EDU->Dependencies.empty()) {
3097 auto I = EDUInfos.find(EDU);
3098 if (
I != EDUInfos.end()) {
3099 auto &EDUInfo =
I->second;
3100 if (!EDUInfo.IntraEmitUsers.empty()) {
3101 EDUInfo.NewDeps = EDU->Dependencies;
3102 Worklist.push_back(EDU);
3109 propagateExtraEmitDeps(
3111 [](JITDylib::EmissionDepUnit &,
JITDylib &, NonOwningSymbolStringPtr) {});
3116void ExecutionSession::IL_makeEDUReady(
3117 std::shared_ptr<JITDylib::EmissionDepUnit> EDU,
3118 JITDylib::AsynchronousSymbolQuerySet &Queries) {
3121 auto &JD = *EDU->JD;
3123 for (
auto &[
Sym, Flags] : EDU->Symbols) {
3124 assert(JD.Symbols.count(SymbolStringPtr(
Sym)) &&
3125 "JD does not have an entry for Sym");
3126 auto &
Entry = JD.Symbols[SymbolStringPtr(
Sym)];
3128 assert(((
Entry.getFlags().hasMaterializationSideEffectsOnly() &&
3132 "Emitting from state other than Resolved");
3136 auto MII = JD.MaterializingInfos.find(SymbolStringPtr(
Sym));
3139 if (MII == JD.MaterializingInfos.end())
3141 auto &
MI = MII->second;
3144 Q->notifySymbolMetRequiredState(SymbolStringPtr(
Sym),
Entry.getSymbol());
3145 if (Q->isComplete())
3147 Q->removeQueryDependence(JD, SymbolStringPtr(
Sym));
3150 JD.MaterializingInfos.erase(MII);
3153 JD.shrinkMaterializationInfoMemory();
3156void ExecutionSession::IL_makeEDUEmitted(
3157 std::shared_ptr<JITDylib::EmissionDepUnit> EDU,
3158 JITDylib::AsynchronousSymbolQuerySet &Queries) {
3161 auto &JD = *EDU->JD;
3163 for (
auto &[
Sym, Flags] : EDU->Symbols) {
3164 assert(JD.Symbols.count(SymbolStringPtr(
Sym)) &&
3165 "JD does not have an entry for Sym");
3166 auto &
Entry = JD.Symbols[SymbolStringPtr(
Sym)];
3168 assert(((
Entry.getFlags().hasMaterializationSideEffectsOnly() &&
3172 "Emitting from state other than Resolved");
3177 for (
auto &[
Sym, Flags] : EDU->Symbols) {
3178 assert(JD.Symbols.count(SymbolStringPtr(
Sym)) &&
3179 "JD does not have an entry for Sym");
3180 auto &
Entry = JD.Symbols[SymbolStringPtr(
Sym)];
3182 "Symbols for EDU in inconsistent state");
3183 assert(JD.MaterializingInfos.count(SymbolStringPtr(
Sym)) &&
3184 "Emitted symbol has no MI");
3185 auto MI = JD.MaterializingInfos[SymbolStringPtr(
Sym)];
3187 "Already-emitted symbol has waiting-on-emitted queries");
3194 auto &
MI = JD.MaterializingInfos[SymbolStringPtr(
Sym)];
3195 MI.DefiningEDU = EDU;
3198 Q->notifySymbolMetRequiredState(SymbolStringPtr(
Sym),
Entry.getSymbol());
3199 if (Q->isComplete())
3201 Q->removeQueryDependence(JD, SymbolStringPtr(
Sym));
3205 for (
auto &[DepJD, Deps] : EDU->Dependencies) {
3206 for (
auto &Dep : Deps)
3207 DepJD->MaterializingInfos[SymbolStringPtr(Dep)].DependantEDUs.insert(
3215bool ExecutionSession::IL_removeEDUDependence(JITDylib::EmissionDepUnit &EDU,
3217 NonOwningSymbolStringPtr DepSym,
3218 EDUInfosMap &EDUInfos) {
3219 assert(EDU.Dependencies.count(&DepJD) &&
3220 "JD does not appear in Dependencies of DependantEDU");
3221 assert(EDU.Dependencies[&DepJD].count(DepSym) &&
3222 "Symbol does not appear in Dependencies of DependantEDU");
3223 auto &JDDeps = EDU.Dependencies[&DepJD];
3224 JDDeps.erase(DepSym);
3225 if (JDDeps.empty()) {
3226 EDU.Dependencies.erase(&DepJD);
3227 if (EDU.Dependencies.empty()) {
3232 auto &DepEDUInfo = EDUInfos[&EDU];
3233 if (!DepEDUInfo.EDU) {
3234 assert(EDU.JD->Symbols.count(
3235 SymbolStringPtr(EDU.Symbols.begin()->first)) &&
3236 "Missing symbol entry for first symbol in EDU");
3237 auto DepEDUFirstMI = EDU.JD->MaterializingInfos.find(
3238 SymbolStringPtr(EDU.Symbols.begin()->first));
3239 assert(DepEDUFirstMI != EDU.JD->MaterializingInfos.end() &&
3240 "Missing MI for first symbol in DependantEDU");
3241 DepEDUInfo.EDU = DepEDUFirstMI->second.DefiningEDU;
3249Error ExecutionSession::makeJDClosedError(JITDylib::EmissionDepUnit &EDU,
3250 JITDylib &ClosedJD) {
3252 for (
auto &[
Sym, Flags] : EDU.Symbols)
3253 FailedSymbols.
insert(SymbolStringPtr(
Sym));
3255 for (
auto &Dep : EDU.Dependencies[&ClosedJD])
3256 BadDeps[&ClosedJD].
insert(SymbolStringPtr(Dep));
3257 return make_error<UnsatisfiedSymbolDependencies>(
3258 ClosedJD.getExecutionSession().getSymbolStringPool(), EDU.JD,
3259 std::move(FailedSymbols), std::move(BadDeps),
3260 ClosedJD.getName() +
" is closed");
3263Error ExecutionSession::makeUnsatisfiedDepsError(JITDylib::EmissionDepUnit &EDU,
3267 for (
auto &[
Sym, Flags] : EDU.Symbols)
3268 FailedSymbols.
insert(SymbolStringPtr(
Sym));
3270 BadDepsMap[&BadJD] = std::move(BadDeps);
3271 return make_error<UnsatisfiedSymbolDependencies>(
3272 BadJD.getExecutionSession().getSymbolStringPool(), &BadJD,
3273 std::move(FailedSymbols), std::move(BadDepsMap),
3274 "dependencies removed or in error state");
3277Expected<JITDylib::AsynchronousSymbolQuerySet>
3278ExecutionSession::IL_emit(MaterializationResponsibility &MR,
3279 EDUInfosMap EDUInfos) {
3281 if (MR.RT->isDefunct())
3282 return make_error<ResourceTrackerDefunct>(MR.RT);
3284 auto &TargetJD = MR.getTargetJITDylib();
3285 if (TargetJD.State != JITDylib::Open)
3286 return make_error<StringError>(
"JITDylib " + TargetJD.getName() +
3289#ifdef EXPENSIVE_CHECKS
3290 verifySessionState(
"entering ExecutionSession::IL_emit");
3299 std::deque<JITDylib::EmissionDepUnit *> Worklist;
3300 for (
auto &[EDU,
_] : EDUInfos)
3301 Worklist.push_back(EDU);
3303 for (
auto *EDU : Worklist) {
3304 auto *EDUInfo = &EDUInfos[EDU];
3306 SmallVector<JITDylib *> DepJDsToRemove;
3307 for (
auto &[DepJD, Deps] : EDU->Dependencies) {
3308 if (DepJD->State != JITDylib::Open)
3309 return makeJDClosedError(*EDU, *DepJD);
3312 SmallVector<NonOwningSymbolStringPtr> DepsToRemove;
3313 for (
auto &Dep : Deps) {
3314 auto DepEntryItr = DepJD->Symbols.
find(SymbolStringPtr(Dep));
3319 if (DepEntryItr == DepJD->Symbols.end() ||
3320 DepEntryItr->second.getFlags().hasError()) {
3321 BadDeps.insert(SymbolStringPtr(Dep));
3327 auto &DepEntry = DepEntryItr->second;
3329 EDUInfo->NewDeps[DepJD].insert(Dep);
3335 DepsToRemove.push_back(Dep);
3339 assert(!DepJD->MaterializingInfos.count(SymbolStringPtr(Dep)) &&
3340 "Unexpected MaterializationInfo attached to ready symbol");
3348 assert(DepJD->MaterializingInfos.count(SymbolStringPtr(Dep)) &&
3349 "Expected MaterializationInfo for emitted dependency");
3350 auto &DepMI = DepJD->MaterializingInfos[SymbolStringPtr(Dep)];
3351 assert(DepMI.DefiningEDU &&
3352 "Emitted symbol does not have a defining EDU");
3353 assert(!DepMI.DefiningEDU->Dependencies.empty() &&
3354 "Emitted symbol has empty dependencies (should be ready)");
3355 assert(DepMI.DependantEDUs.empty() &&
3356 "Already-emitted symbol has dependant EDUs?");
3357 auto &DepEDUInfo = EDUInfos[DepMI.DefiningEDU.get()];
3358 if (!DepEDUInfo.EDU) {
3361 EDUInfo = &EDUInfos[EDU];
3362 DepEDUInfo.EDU = DepMI.DefiningEDU;
3363 for (
auto &[DepDepJD, DepDeps] : DepEDUInfo.EDU->Dependencies) {
3364 if (DepDepJD == &TargetJD) {
3365 for (
auto &DepDep : DepDeps)
3366 if (!MR.getSymbols().count(SymbolStringPtr(DepDep)))
3367 DepEDUInfo.NewDeps[DepDepJD].insert(DepDep);
3369 DepEDUInfo.NewDeps[DepDepJD] = DepDeps;
3372 DepEDUInfo.IntraEmitUsers.insert(EDU);
3376 if (!BadDeps.empty())
3377 return makeUnsatisfiedDepsError(*EDU, *DepJD, std::move(BadDeps));
3380 for (
auto &Dep : DepsToRemove)
3385 DepJDsToRemove.push_back(DepJD);
3389 for (
auto &DepJD : DepJDsToRemove) {
3390 assert(EDU->Dependencies.count(DepJD) &&
3391 "Trying to remove non-existent dep entries");
3392 EDU->Dependencies.erase(DepJD);
3396 for (
auto &[
Sym, Flags] : EDU->Symbols) {
3397 assert(TargetJD.Symbols.count(SymbolStringPtr(
Sym)) &&
3398 "Sym not present in symbol table");
3399 assert((TargetJD.Symbols[SymbolStringPtr(
Sym)].getState() ==
3401 TargetJD.Symbols[SymbolStringPtr(
Sym)]
3403 .hasMaterializationSideEffectsOnly()) &&
3404 "Emitting symbol not in the resolved state");
3406 "Symbol is already in an error state");
3408 auto MII = TargetJD.MaterializingInfos.find(SymbolStringPtr(
Sym));
3409 if (MII == TargetJD.MaterializingInfos.end() ||
3410 MII->second.DependantEDUs.empty())
3413 for (
auto &DependantEDU : MII->second.DependantEDUs) {
3414 if (IL_removeEDUDependence(*DependantEDU, TargetJD,
Sym, EDUInfos))
3415 EDUInfo = &EDUInfos[EDU];
3416 EDUInfo->IntraEmitUsers.insert(DependantEDU);
3418 MII->second.DependantEDUs.clear();
3423 for (
auto &[EDU, EDUInfo] : EDUInfos) {
3424 if (!EDUInfo.IntraEmitUsers.empty() && !EDU->Dependencies.empty()) {
3425 if (EDUInfo.NewDeps.empty())
3426 EDUInfo.NewDeps = EDU->Dependencies;
3427 Worklist.push_back(EDU);
3431 propagateExtraEmitDeps(
3433 [](JITDylib::EmissionDepUnit &EDU,
JITDylib &JD,
3434 NonOwningSymbolStringPtr
Sym) {
3435 JD.MaterializingInfos[SymbolStringPtr(
Sym)].DependantEDUs.insert(&EDU);
3438 JITDylib::AsynchronousSymbolQuerySet CompletedQueries;
3442 for (
auto &[EDU, EDUInfo] : EDUInfos) {
3443 if (EDU->Dependencies.empty())
3444 IL_makeEDUReady(std::move(EDUInfo.EDU), CompletedQueries);
3446 IL_makeEDUEmitted(std::move(EDUInfo.EDU), CompletedQueries);
3449#ifdef EXPENSIVE_CHECKS
3450 verifySessionState(
"exiting ExecutionSession::IL_emit");
3453 return std::move(CompletedQueries);
3456Error ExecutionSession::OL_notifyEmitted(
3457 MaterializationResponsibility &MR,
3458 ArrayRef<SymbolDependenceGroup> DepGroups) {
3460 dbgs() <<
"In " << MR.JD.getName() <<
" emitting " << MR.SymbolFlags
3462 if (!DepGroups.empty()) {
3463 dbgs() <<
" Initial dependencies:\n";
3464 for (
auto &SDG : DepGroups) {
3465 dbgs() <<
" Symbols: " << SDG.Symbols
3466 <<
", Dependencies: " << SDG.Dependencies <<
"\n";
3473 for (
auto &DG : DepGroups) {
3474 for (
auto &
Sym : DG.Symbols) {
3476 "DG contains dependence for symbol outside this MR");
3478 "DG contains duplicate entries for Name");
3483 auto EDUInfos = simplifyDepGroups(MR, DepGroups);
3486 dbgs() <<
" Simplified dependencies:\n";
3487 for (
auto &[EDU, EDUInfo] : EDUInfos) {
3488 dbgs() <<
" Symbols: { ";
3489 for (
auto &[
Sym, Flags] : EDU->Symbols)
3491 dbgs() <<
"}, Dependencies: { ";
3492 for (
auto &[DepJD, Deps] : EDU->Dependencies) {
3493 dbgs() <<
"(" << DepJD->getName() <<
", { ";
3494 for (
auto &Dep : Deps)
3495 dbgs() << Dep <<
" ";
3502 auto CompletedQueries =
3506 if (!CompletedQueries)
3507 return CompletedQueries.takeError();
3509 MR.SymbolFlags.clear();
3512 for (
auto &Q : *CompletedQueries) {
3513 assert(Q->isComplete() &&
"Q is not complete");
3514 Q->handleComplete(*
this);
3520Error ExecutionSession::OL_defineMaterializing(
3521 MaterializationResponsibility &MR,
SymbolFlagsMap NewSymbolFlags) {
3524 dbgs() <<
"In " << MR.JD.getName() <<
" defining materializing symbols "
3525 << NewSymbolFlags <<
"\n";
3527 if (
auto AcceptedDefs =
3528 MR.JD.defineMaterializing(MR, std::move(NewSymbolFlags))) {
3530 for (
auto &KV : *AcceptedDefs)
3531 MR.SymbolFlags.insert(KV);
3534 return AcceptedDefs.takeError();
3537std::pair<JITDylib::AsynchronousSymbolQuerySet,
3538 std::shared_ptr<SymbolDependenceMap>>
3539ExecutionSession::IL_failSymbols(JITDylib &JD,
3542#ifdef EXPENSIVE_CHECKS
3543 verifySessionState(
"entering ExecutionSession::IL_failSymbols");
3546 JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3547 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
3548 auto ExtractFailedQueries = [&](JITDylib::MaterializingInfo &
MI) {
3549 JITDylib::AsynchronousSymbolQueryList ToDetach;
3550 for (
auto &Q :
MI.pendingQueries()) {
3552 FailedQueries.insert(Q);
3553 ToDetach.push_back(Q);
3555 for (
auto &Q : ToDetach)
3557 assert(!
MI.hasQueriesPending() &&
"Queries still pending after detach");
3560 for (
auto &
Name : SymbolsToFail) {
3561 (*FailedSymbolsMap)[&JD].insert(
Name);
3564 auto SymI = JD.Symbols.find(
Name);
3573 if (SymI == JD.Symbols.end())
3575 auto &
Sym = SymI->second;
3579 if (
Sym.getFlags().hasError()) {
3581 "Symbol in error state still has MaterializingInfo");
3591 auto MII = JD.MaterializingInfos.find(
Name);
3592 if (MII == JD.MaterializingInfos.end())
3595 auto &
MI = MII->second;
3598 ExtractFailedQueries(
MI);
3600 if (
MI.DefiningEDU) {
3604 "Symbol with DefiningEDU should not have DependantEDUs");
3606 "Symbol has EDU, should have been emitted");
3607 assert(
MI.DefiningEDU->Symbols.count(NonOwningSymbolStringPtr(
Name)) &&
3608 "Symbol does not appear in its DefiningEDU");
3609 MI.DefiningEDU->Symbols.erase(NonOwningSymbolStringPtr(
Name));
3610 MI.DefiningEDU =
nullptr;
3617 for (
auto &DependantEDU :
MI.DependantEDUs) {
3620 for (
auto &[DepJD, DepSyms] : DependantEDU->Dependencies) {
3621 for (
auto DepSym : DepSyms) {
3624 if (DepJD == &JD && DepSym ==
Name)
3626 assert(DepJD->Symbols.count(SymbolStringPtr(DepSym)) &&
3627 "DepSym not in DepJD?");
3628 assert(DepJD->MaterializingInfos.count(SymbolStringPtr(DepSym)) &&
3629 "DependantEDU not registered with symbol it depends on");
3630 auto &SymMI = DepJD->MaterializingInfos[SymbolStringPtr(DepSym)];
3631 assert(SymMI.DependantEDUs.count(DependantEDU) &&
3632 "DependantEDU missing from DependantEDUs list");
3633 SymMI.DependantEDUs.erase(DependantEDU);
3639 auto &DepJD = *DependantEDU->JD;
3640 auto DepEDUSymbols = std::move(DependantEDU->Symbols);
3641 for (
auto &[DepName, Flags] : DepEDUSymbols) {
3642 auto DepSymItr = DepJD.Symbols.find(SymbolStringPtr(DepName));
3643 assert(DepSymItr != DepJD.Symbols.end() &&
3644 "Symbol not present in table");
3645 auto &DepSym = DepSymItr->second;
3648 "Symbol has EDU, should have been emitted");
3649 assert(!DepSym.getFlags().hasError() &&
3650 "Symbol is already in the error state?");
3652 (*FailedSymbolsMap)[&DepJD].insert(SymbolStringPtr(DepName));
3657 DepJD.MaterializingInfos.find(SymbolStringPtr(DepName));
3658 assert(DepMIItr != DepJD.MaterializingInfos.end() &&
3659 "Symbol has defining EDU but not MaterializingInfo");
3660 auto &DepMI = DepMIItr->second;
3661 assert(DepMI.DefiningEDU.get() == DependantEDU &&
3662 "Bad EDU dependence edge");
3663 assert(DepMI.DependantEDUs.empty() &&
3664 "Symbol was emitted, should not have any DependantEDUs");
3665 ExtractFailedQueries(DepMI);
3666 DepJD.MaterializingInfos.erase(SymbolStringPtr(DepName));
3669 DepJD.shrinkMaterializationInfoMemory();
3672 MI.DependantEDUs.clear();
3675 assert(!
MI.DefiningEDU &&
"DefiningEDU should have been reset");
3677 "DependantEDUs should have been removed above");
3679 "Can not delete MaterializingInfo with queries pending");
3680 JD.MaterializingInfos.erase(
Name);
3683 JD.shrinkMaterializationInfoMemory();
3685#ifdef EXPENSIVE_CHECKS
3686 verifySessionState(
"exiting ExecutionSession::IL_failSymbols");
3689 return std::make_pair(std::move(FailedQueries), std::move(FailedSymbolsMap));
3692void ExecutionSession::OL_notifyFailed(MaterializationResponsibility &MR) {
3695 dbgs() <<
"In " << MR.JD.getName() <<
" failing materialization for "
3696 << MR.SymbolFlags <<
"\n";
3699 if (MR.SymbolFlags.empty())
3703 for (
auto &[
Name, Flags] : MR.SymbolFlags)
3704 SymbolsToFail.push_back(
Name);
3705 MR.SymbolFlags.clear();
3707 JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3708 std::shared_ptr<SymbolDependenceMap> FailedSymbols;
3712 if (MR.RT->isDefunct())
3713 return std::pair<JITDylib::AsynchronousSymbolQuerySet,
3714 std::shared_ptr<SymbolDependenceMap>>();
3715 return IL_failSymbols(MR.getTargetJITDylib(), SymbolsToFail);
3718 for (
auto &Q : FailedQueries)
3723Error ExecutionSession::OL_replace(MaterializationResponsibility &MR,
3724 std::unique_ptr<MaterializationUnit> MU) {
3725 for (
auto &KV : MU->getSymbols()) {
3726 assert(MR.SymbolFlags.count(KV.first) &&
3727 "Replacing definition outside this responsibility set");
3728 MR.SymbolFlags.erase(KV.first);
3731 if (MU->getInitializerSymbol() == MR.InitSymbol)
3732 MR.InitSymbol =
nullptr;
3734 LLVM_DEBUG(MR.JD.getExecutionSession().runSessionLocked([&]() {
3735 dbgs() <<
"In " << MR.JD.getName() <<
" replacing symbols with " << *MU
3739 return MR.JD.replace(MR, std::move(MU));
3742Expected<std::unique_ptr<MaterializationResponsibility>>
3743ExecutionSession::OL_delegate(MaterializationResponsibility &MR,
3746 SymbolStringPtr DelegatedInitSymbol;
3749 for (
auto &
Name : Symbols) {
3750 auto I = MR.SymbolFlags.find(
Name);
3751 assert(
I != MR.SymbolFlags.end() &&
3752 "Symbol is not tracked by this MaterializationResponsibility "
3755 DelegatedFlags[
Name] = std::move(
I->second);
3756 if (
Name == MR.InitSymbol)
3757 std::swap(MR.InitSymbol, DelegatedInitSymbol);
3759 MR.SymbolFlags.erase(
I);
3762 return MR.JD.delegate(MR, std::move(DelegatedFlags),
3763 std::move(DelegatedInitSymbol));
3767void ExecutionSession::dumpDispatchInfo(Task &
T) {
3769 dbgs() <<
"Dispatching: ";
3770 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.
StringRef getName() const override
Return the name of this materialization unit.
AbsoluteSymbolsMaterializationUnit(SymbolMap Symbols)
AsynchronousSymbolQuery(const SymbolLookupSet &Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete)
Create a query for the given symbols.
void notifySymbolMetRequiredState(const SymbolStringPtr &Name, ExecutorSymbolDef Sym)
Notify the query that a requested symbol has reached the required state.
Definition generators can be attached to JITDylibs to generate new definitions for otherwise unresolv...
virtual ~DefinitionGenerator()
An ExecutionSession represents a running JIT program.
Error endSession()
End the session.
void reportError(Error Err)
Report a error for this execution session.
void lookupFlags(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet Symbols, unique_function< void(Expected< SymbolFlagsMap >)> OnComplete)
Search the given JITDylibs to find the flags associated with each of the given symbols.
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
JITDylib * getJITDylibByName(StringRef Name)
Return a pointer to the "name" JITDylib.
JITDylib & createBareJITDylib(std::string Name)
Add a new bare JITDylib to this ExecutionSession.
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete, RegisterDependenciesFunction RegisterDependencies)
Search the given JITDylibs for the given symbols.
Error registerJITDispatchHandlers(JITDylib &JD, JITDispatchHandlerAssociationMap WFs)
For each tag symbol name, associate the corresponding AsyncHandlerWrapperFunction with the address of...
void registerResourceManager(ResourceManager &RM)
Register the given ResourceManager with this ExecutionSession.
~ExecutionSession()
Destroy an ExecutionSession.
void runJITDispatchHandler(SendResultFunction SendResult, ExecutorAddr HandlerFnTagAddr, ArrayRef< char > ArgBuffer)
Run a registered jit-side wrapper function.
void deregisterResourceManager(ResourceManager &RM)
Deregister the given ResourceManager with this ExecutionSession.
ExecutionSession(std::unique_ptr< ExecutorProcessControl > EPC)
Construct an ExecutionSession with the given ExecutorProcessControl object.
decltype(auto) runSessionLocked(Func &&F)
Run the given lambda with the session mutex locked.
void dump(raw_ostream &OS)
Dump the state of all the JITDylibs in this session.
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
enum llvm::orc::InProgressLookupState::@480 GenState
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
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.
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.
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 ...
NodeAddr< DefNode * > Def
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...
auto formatv(const char *Fmt, Ts &&...Vals) -> formatv_object< decltype(std::make_tuple(support::detail::build_format_adapter(std::forward< Ts >(Vals))...))>
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
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.