12#include "llvm/Config/llvm-config.h"
18#include <condition_variable>
22#define DEBUG_TYPE "orc"
39void MaterializationUnit::anchor() {}
42 assert((
reinterpret_cast<uintptr_t
>(JD.get()) & 0x1) == 0 &&
43 "JITDylib must be two byte aligned");
45 JDAndFlag.store(
reinterpret_cast<uintptr_t
>(JD.get()));
61void ResourceTracker::makeDefunct() {
62 uintptr_t Val = JDAndFlag.load();
77 OS <<
"Resource tracker " << (
void *)RT.
get() <<
" became defunct";
81 std::shared_ptr<SymbolStringPool> SSP,
82 std::shared_ptr<SymbolDependenceMap> Symbols)
84 assert(this->SSP &&
"String pool cannot be null");
85 assert(!this->Symbols->empty() &&
"Can not fail to resolve an empty set");
89 for (
auto &KV : *this->Symbols)
94 for (
auto &KV : *Symbols)
103 OS <<
"Failed to materialize symbols: " << *Symbols;
109 for (
auto &
Sym : Symbols)
110 this->Symbols.push_back(
Sym);
111 assert(!this->Symbols.
empty() &&
"Can not fail to resolve an empty set");
117 assert(!this->Symbols.empty() &&
"Can not fail to resolve an empty set");
125 OS <<
"Symbols not found: " << Symbols;
129 std::shared_ptr<SymbolStringPool> SSP,
SymbolNameSet Symbols)
131 assert(!this->Symbols.
empty() &&
"Can not fail to resolve an empty set");
139 OS <<
"Symbols could not be removed: " << Symbols;
163 : NotifyComplete(
std::
move(NotifyComplete)), RequiredState(RequiredState) {
165 "Cannot query for a symbols that have not reached the resolve state "
168 OutstandingSymbolsCount = Symbols.size();
170 for (
auto &KV : Symbols)
178 "Resolving symbol outside the requested set");
180 "Redundantly resolving symbol Name");
184 if (
Sym.getFlags().hasMaterializationSideEffectsOnly())
187 I->second = std::move(
Sym);
188 --OutstandingSymbolsCount;
192 assert(OutstandingSymbolsCount == 0 &&
193 "Symbols remain, handleComplete called prematurely");
195 class RunQueryCompleteTask :
public Task {
197 RunQueryCompleteTask(
SymbolMap ResolvedSymbols,
199 : ResolvedSymbols(
std::
move(ResolvedSymbols)),
200 NotifyComplete(
std::
move(NotifyComplete)) {}
202 OS <<
"Execute query complete callback for " << ResolvedSymbols;
204 void run()
override { NotifyComplete(std::move(ResolvedSymbols)); }
211 auto T = std::make_unique<RunQueryCompleteTask>(std::move(ResolvedSymbols),
212 std::move(NotifyComplete));
217void AsynchronousSymbolQuery::handleFailed(Error Err) {
219 OutstandingSymbolsCount == 0 &&
220 "Query should already have been abandoned");
221 NotifyComplete(std::move(Err));
225void AsynchronousSymbolQuery::addQueryDependence(JITDylib &JD,
226 SymbolStringPtr
Name) {
229 assert(Added &&
"Duplicate dependence notification?");
232void AsynchronousSymbolQuery::removeQueryDependence(
233 JITDylib &JD,
const SymbolStringPtr &
Name) {
234 auto QRI = QueryRegistrations.
find(&JD);
235 assert(QRI != QueryRegistrations.
end() &&
236 "No dependencies registered for JD");
237 assert(QRI->second.count(
Name) &&
"No dependency on Name in JD");
238 QRI->second.erase(
Name);
239 if (QRI->second.empty())
240 QueryRegistrations.
erase(QRI);
243void AsynchronousSymbolQuery::dropSymbol(
const SymbolStringPtr &
Name) {
246 "Redundant removal of weakly-referenced symbol");
248 --OutstandingSymbolsCount;
251void AsynchronousSymbolQuery::detach() {
252 ResolvedSymbols.
clear();
253 OutstandingSymbolsCount = 0;
254 for (
auto &KV : QueryRegistrations)
255 KV.first->detachQueryHelper(*
this, KV.second);
256 QueryRegistrations.clear();
264 return "<Absolute Symbols>";
267void AbsoluteSymbolsMaterializationUnit::materialize(
268 std::unique_ptr<MaterializationResponsibility> R) {
274 if (
auto Err = R->notifyResolved(Symbols)) {
275 R->getExecutionSession().reportError(std::move(Err));
276 R->failMaterialization();
279 if (
auto Err = R->notifyEmitted()) {
280 R->getExecutionSession().reportError(std::move(Err));
281 R->failMaterialization();
286void AbsoluteSymbolsMaterializationUnit::discard(
const JITDylib &JD,
287 const SymbolStringPtr &
Name) {
292MaterializationUnit::Interface
293AbsoluteSymbolsMaterializationUnit::extractFlags(
const SymbolMap &Symbols) {
295 for (
const auto &KV : Symbols)
296 Flags[KV.first] = KV.second.getFlags();
297 return MaterializationUnit::Interface(std::move(Flags),
nullptr);
304 SourceJDLookupFlags(SourceJDLookupFlags), Aliases(
std::
move(Aliases)) {}
307 return "<Reexports>";
310void ReExportsMaterializationUnit::materialize(
311 std::unique_ptr<MaterializationResponsibility> R) {
313 auto &ES = R->getTargetJITDylib().getExecutionSession();
314 JITDylib &TgtJD = R->getTargetJITDylib();
315 JITDylib &SrcJD = SourceJD ? *SourceJD : TgtJD;
320 auto RequestedSymbols = R->getRequestedSymbols();
323 for (
auto &
Name : RequestedSymbols) {
325 assert(
I != Aliases.
end() &&
"Symbol not found in aliases map?");
326 RequestedAliases[
Name] = std::move(
I->second);
332 dbgs() <<
"materializing reexports: target = " << TgtJD.
getName()
333 <<
", source = " << SrcJD.
getName() <<
" " << RequestedAliases
338 if (!Aliases.
empty()) {
339 auto Err = SourceJD ?
R->replace(
reexports(*SourceJD, std::move(Aliases),
340 SourceJDLookupFlags))
347 R->failMaterialization();
354 struct OnResolveInfo {
355 OnResolveInfo(std::unique_ptr<MaterializationResponsibility> R,
356 SymbolAliasMap Aliases)
359 std::unique_ptr<MaterializationResponsibility>
R;
371 std::vector<std::pair<SymbolLookupSet, std::shared_ptr<OnResolveInfo>>>
373 while (!RequestedAliases.
empty()) {
375 SymbolLookupSet QuerySymbols;
379 for (
auto &KV : RequestedAliases) {
381 if (&SrcJD == &TgtJD && (QueryAliases.count(KV.second.Aliasee) ||
382 RequestedAliases.count(KV.second.Aliasee)))
385 ResponsibilitySymbols.
insert(KV.first);
386 QuerySymbols.add(KV.second.Aliasee,
387 KV.second.AliasFlags.hasMaterializationSideEffectsOnly()
390 QueryAliases[KV.first] = std::move(KV.second);
394 for (
auto &KV : QueryAliases)
395 RequestedAliases.erase(KV.first);
397 assert(!QuerySymbols.empty() &&
"Alias cycle detected!");
399 auto NewR =
R->delegate(ResponsibilitySymbols);
402 R->failMaterialization();
406 auto QueryInfo = std::make_shared<OnResolveInfo>(std::move(*NewR),
407 std::move(QueryAliases));
408 QueryInfos.push_back(
409 make_pair(std::move(QuerySymbols), std::move(QueryInfo)));
413 while (!QueryInfos.empty()) {
414 auto QuerySymbols = std::move(QueryInfos.back().first);
415 auto QueryInfo = std::move(QueryInfos.back().second);
417 QueryInfos.pop_back();
419 auto RegisterDependencies = [QueryInfo,
426 assert(Deps.size() == 1 && Deps.count(&SrcJD) &&
427 "Unexpected dependencies for reexports");
429 auto &SrcJDDeps = Deps.find(&SrcJD)->second;
431 auto &PerAliasDeps = PerAliasDepsMap[&SrcJD];
433 for (
auto &KV : QueryInfo->Aliases)
434 if (SrcJDDeps.count(KV.second.Aliasee)) {
435 PerAliasDeps = {KV.second.Aliasee};
436 QueryInfo->R->addDependencies(KV.first, PerAliasDepsMap);
440 auto OnComplete = [QueryInfo](Expected<SymbolMap>
Result) {
441 auto &ES = QueryInfo->R->getTargetJITDylib().getExecutionSession();
444 for (
auto &KV : QueryInfo->Aliases) {
445 assert((KV.second.AliasFlags.hasMaterializationSideEffectsOnly() ||
446 Result->count(KV.second.Aliasee)) &&
447 "Result map missing entry?");
449 if (KV.second.AliasFlags.hasMaterializationSideEffectsOnly())
452 ResolutionMap[KV.first] = {(*Result)[KV.second.Aliasee].getAddress(),
453 KV.second.AliasFlags};
455 if (
auto Err = QueryInfo->R->notifyResolved(ResolutionMap)) {
457 QueryInfo->R->failMaterialization();
460 if (
auto Err = QueryInfo->R->notifyEmitted()) {
462 QueryInfo->R->failMaterialization();
467 QueryInfo->R->failMaterialization();
474 std::move(RegisterDependencies));
478void ReExportsMaterializationUnit::discard(
const JITDylib &JD,
479 const SymbolStringPtr &
Name) {
481 "Symbol not covered by this MaterializationUnit");
485MaterializationUnit::Interface
486ReExportsMaterializationUnit::extractFlags(
const SymbolAliasMap &Aliases) {
488 for (
auto &KV : Aliases)
491 return MaterializationUnit::Interface(std::move(
SymbolFlags),
nullptr);
502 return Flags.takeError();
505 for (
auto &
Name : Symbols) {
506 assert(Flags->count(
Name) &&
"Missing entry in flags map");
525 virtual void complete(std::unique_ptr<InProgressLookupState> IPLS) = 0;
553 OnComplete(
std::
move(OnComplete)) {}
555 void complete(std::unique_ptr<InProgressLookupState> IPLS)
override {
556 auto &ES =
SearchOrder.front().first->getExecutionSession();
557 ES.OL_completeLookupFlags(std::move(IPLS), std::move(OnComplete));
560 void fail(
Error Err)
override { OnComplete(std::move(Err)); }
571 std::shared_ptr<AsynchronousSymbolQuery> Q,
575 Q(
std::
move(Q)), RegisterDependencies(
std::
move(RegisterDependencies)) {
578 void complete(std::unique_ptr<InProgressLookupState> IPLS)
override {
579 auto &ES =
SearchOrder.front().first->getExecutionSession();
580 ES.OL_completeLookup(std::move(IPLS), std::move(Q),
581 std::move(RegisterDependencies));
586 Q->handleFailed(std::move(Err));
590 std::shared_ptr<AsynchronousSymbolQuery> Q;
597 : SourceJD(SourceJD), SourceJDLookupFlags(SourceJDLookupFlags),
604 assert(&JD != &SourceJD &&
"Cannot re-export from the same dylib");
608 K, {{&SourceJD, JDLookupFlags}}, LookupSet);
610 return Flags.takeError();
614 for (
auto &KV : *Flags)
615 if (!Allow || Allow(KV.first))
618 if (AliasMap.
empty())
628void LookupState::reset(InProgressLookupState *IPLS) { this->IPLS.reset(IPLS); }
636 assert(IPLS &&
"Cannot call continueLookup on empty LookupState");
637 auto &ES = IPLS->SearchOrder.begin()->first->getExecutionSession();
638 ES.OL_applyQueryPhase1(std::move(IPLS), std::move(Err));
642 std::deque<LookupState> LookupsToFail;
644 std::lock_guard<std::mutex> Lock(M);
645 std::swap(PendingLookups, LookupsToFail);
649 for (
auto &LS : LookupsToFail)
650 LS.continueLookup(make_error<StringError>(
651 "Query waiting on DefinitionGenerator that was destroyed",
660 std::vector<ResourceTrackerSP> TrackersToRemove;
662 assert(State != Closed &&
"JD is defunct");
663 for (
auto &KV : TrackerSymbols)
664 TrackersToRemove.push_back(KV.first);
669 for (
auto &RT : TrackersToRemove)
670 Err =
joinErrors(std::move(Err), RT->remove());
676 assert(State != Closed &&
"JD is defunct");
679 return DefaultTracker;
685 assert(State == Open &&
"JD is defunct");
694 std::shared_ptr<DefinitionGenerator> TmpDG;
697 assert(State == Open &&
"JD is defunct");
699 [&](
const std::shared_ptr<DefinitionGenerator> &
H) {
700 return H.get() == &
G;
702 assert(
I != DefGenerators.end() &&
"Generator not found");
703 TmpDG = std::move(*
I);
704 DefGenerators.erase(
I);
713 if (FromMR.RT->isDefunct())
714 return make_error<ResourceTrackerDefunct>(FromMR.RT);
716 std::vector<NonOwningSymbolStringPtr> AddedSyms;
717 std::vector<NonOwningSymbolStringPtr> RejectedWeakDefs;
719 for (
auto SFItr = SymbolFlags.begin(), SFEnd = SymbolFlags.end();
720 SFItr != SFEnd; ++SFItr) {
722 auto &Name = SFItr->first;
723 auto &Flags = SFItr->second;
725 auto EntryItr = Symbols.find(Name);
728 if (EntryItr != Symbols.end()) {
731 if (!Flags.isWeak()) {
733 for (auto &S : AddedSyms)
734 Symbols.erase(Symbols.find_as(S));
737 return make_error<DuplicateDefinition>(std::string(*Name));
741 RejectedWeakDefs.push_back(NonOwningSymbolStringPtr(Name));
752 while (!RejectedWeakDefs.empty()) {
753 SymbolFlags.erase(SymbolFlags.find_as(RejectedWeakDefs.back()));
754 RejectedWeakDefs.pop_back();
761Error JITDylib::replace(MaterializationResponsibility &FromMR,
762 std::unique_ptr<MaterializationUnit> MU) {
763 assert(MU !=
nullptr &&
"Can not replace with a null MaterializationUnit");
764 std::unique_ptr<MaterializationUnit> MustRunMU;
765 std::unique_ptr<MaterializationResponsibility> MustRunMR;
769 if (FromMR.RT->isDefunct())
770 return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
773 for (
auto &KV : MU->getSymbols()) {
774 auto SymI = Symbols.find(KV.first);
775 assert(SymI != Symbols.end() &&
"Replacing unknown symbol");
776 assert(SymI->second.getState() == SymbolState::Materializing &&
777 "Can not replace a symbol that ha is not materializing");
778 assert(!SymI->second.hasMaterializerAttached() &&
779 "Symbol should not have materializer attached already");
780 assert(UnmaterializedInfos.count(KV.first) == 0 &&
781 "Symbol being replaced should have no UnmaterializedInfo");
789 for (
auto &KV : MU->getSymbols()) {
790 auto MII = MaterializingInfos.find(KV.first);
791 if (MII != MaterializingInfos.end()) {
792 if (MII->second.hasQueriesPending()) {
793 MustRunMR = ES.createMaterializationResponsibility(
794 *FromMR.RT, std::move(MU->SymbolFlags),
795 std::move(MU->InitSymbol));
796 MustRunMU = std::move(MU);
797 return Error::success();
803 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU),
805 for (
auto &KV : UMI->MU->getSymbols()) {
806 auto SymI = Symbols.find(KV.first);
807 assert(SymI->second.getState() == SymbolState::Materializing &&
808 "Can not replace a symbol that is not materializing");
809 assert(!SymI->second.hasMaterializerAttached() &&
810 "Can not replace a symbol that has a materializer attached");
811 assert(UnmaterializedInfos.count(KV.first) == 0 &&
812 "Unexpected materializer entry in map");
813 SymI->second.setAddress(SymI->second.getAddress());
814 SymI->second.setMaterializerAttached(
true);
816 auto &UMIEntry = UnmaterializedInfos[KV.first];
817 assert((!UMIEntry || !UMIEntry->MU) &&
818 "Replacing symbol with materializer still attached");
829 assert(MustRunMR &&
"MustRunMU set implies MustRunMR set");
831 std::move(MustRunMU), std::move(MustRunMR)));
833 assert(!MustRunMR &&
"MustRunMU unset implies MustRunMR unset");
839Expected<std::unique_ptr<MaterializationResponsibility>>
840JITDylib::delegate(MaterializationResponsibility &FromMR,
841 SymbolFlagsMap SymbolFlags, SymbolStringPtr InitSymbol) {
844 [&]() -> Expected<std::unique_ptr<MaterializationResponsibility>> {
845 if (FromMR.RT->isDefunct())
846 return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
848 return ES.createMaterializationResponsibility(
849 *FromMR.RT, std::move(SymbolFlags), std::move(InitSymbol));
854JITDylib::getRequestedSymbols(
const SymbolFlagsMap &SymbolFlags)
const {
858 for (
auto &KV : SymbolFlags) {
859 assert(Symbols.count(KV.first) &&
"JITDylib does not cover this symbol?");
860 assert(Symbols.find(KV.first)->second.getState() !=
861 SymbolState::NeverSearched &&
862 Symbols.find(KV.first)->second.getState() != SymbolState::Ready &&
863 "getRequestedSymbols can only be called for symbols that have "
864 "started materializing");
865 auto I = MaterializingInfos.find(KV.first);
866 if (
I == MaterializingInfos.end())
869 if (
I->second.hasQueriesPending())
870 RequestedSymbols.insert(KV.first);
873 return RequestedSymbols;
877void JITDylib::addDependencies(
const SymbolStringPtr &
Name,
878 const SymbolDependenceMap &Dependencies) {
880 assert(Symbols.count(
Name) &&
"Name not in symbol table");
881 assert(Symbols[
Name].getState() < SymbolState::Emitted &&
882 "Can not add dependencies for a symbol that is not materializing");
886 <<
": " << Dependencies <<
"\n";
893 auto &
MI = MaterializingInfos[
Name];
894 assert(Symbols[
Name].getState() != SymbolState::Emitted &&
895 "Can not add dependencies to an emitted symbol");
897 bool DependsOnSymbolInErrorState =
false;
901 for (
auto &KV : Dependencies) {
902 assert(KV.first &&
"Null JITDylib in dependency?");
903 auto &OtherJITDylib = *KV.first;
904 auto &DepsOnOtherJITDylib =
MI.UnemittedDependencies[&OtherJITDylib];
906 for (
auto &OtherSymbol : KV.second) {
909 auto OtherSymI = OtherJITDylib.Symbols.find(OtherSymbol);
913 assert(OtherSymI != OtherJITDylib.Symbols.end() &&
914 "Dependency on unknown symbol");
916 auto &OtherSymEntry = OtherSymI->second;
920 if (OtherSymEntry.getState() == SymbolState::Ready)
925 if (OtherSymEntry.getFlags().hasError()) {
926 DependsOnSymbolInErrorState =
true;
932 auto &OtherMI = OtherJITDylib.MaterializingInfos[OtherSymbol];
934 if (OtherSymEntry.getState() == SymbolState::Emitted)
935 transferEmittedNodeDependencies(
MI,
Name, OtherMI);
936 else if (&OtherJITDylib !=
this || OtherSymbol !=
Name) {
937 OtherMI.Dependants[
this].insert(
Name);
938 DepsOnOtherJITDylib.insert(OtherSymbol);
942 if (DepsOnOtherJITDylib.empty())
943 MI.UnemittedDependencies.erase(&OtherJITDylib);
948 if (DependsOnSymbolInErrorState)
950 JITSymbolFlags::HasError);
954Error JITDylib::resolve(MaterializationResponsibility &MR,
955 const SymbolMap &Resolved) {
956 AsynchronousSymbolQuerySet CompletedQueries;
959 if (MR.RT->isDefunct())
960 return make_error<ResourceTrackerDefunct>(MR.RT);
963 return make_error<StringError>(
"JITDylib " + getName() +
965 inconvertibleErrorCode());
967 struct WorklistEntry {
968 SymbolTable::iterator SymI;
969 ExecutorSymbolDef ResolvedSym;
972 SymbolNameSet SymbolsInErrorState;
973 std::vector<WorklistEntry> Worklist;
977 for (
const auto &KV : Resolved) {
979 assert(!KV.second.getFlags().hasError() &&
980 "Resolution result can not have error flag set");
982 auto SymI = Symbols.find(KV.first);
984 assert(SymI != Symbols.end() &&
"Symbol not found");
985 assert(!SymI->second.hasMaterializerAttached() &&
986 "Resolving symbol with materializer attached?");
987 assert(SymI->second.getState() == SymbolState::Materializing &&
988 "Symbol should be materializing");
989 assert(SymI->second.getAddress() == ExecutorAddr() &&
990 "Symbol has already been resolved");
992 if (SymI->second.getFlags().hasError())
993 SymbolsInErrorState.insert(KV.first);
995 auto Flags = KV.second.getFlags();
996 Flags &= ~JITSymbolFlags::Common;
998 (SymI->second.getFlags() & ~JITSymbolFlags::Common) &&
999 "Resolved flags should match the declared flags");
1001 Worklist.push_back({SymI, {KV.second.getAddress(), Flags}});
1006 if (!SymbolsInErrorState.empty()) {
1007 auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
1008 (*FailedSymbolsDepMap)[
this] = std::move(SymbolsInErrorState);
1009 return make_error<FailedToMaterialize>(
1010 getExecutionSession().getSymbolStringPool(),
1011 std::move(FailedSymbolsDepMap));
1014 while (!Worklist.empty()) {
1015 auto SymI = Worklist.back().SymI;
1016 auto ResolvedSym = Worklist.back().ResolvedSym;
1017 Worklist.pop_back();
1019 auto &
Name = SymI->first;
1022 JITSymbolFlags ResolvedFlags = ResolvedSym.getFlags();
1023 SymI->second.setAddress(ResolvedSym.getAddress());
1024 SymI->second.setFlags(ResolvedFlags);
1025 SymI->second.setState(SymbolState::Resolved);
1027 auto MII = MaterializingInfos.find(
Name);
1028 if (MII == MaterializingInfos.end())
1031 auto &
MI = MII->second;
1032 for (
auto &Q :
MI.takeQueriesMeeting(SymbolState::Resolved)) {
1033 Q->notifySymbolMetRequiredState(
Name, ResolvedSym);
1034 Q->removeQueryDependence(*
this,
Name);
1035 if (Q->isComplete())
1036 CompletedQueries.insert(std::move(Q));
1040 return Error::success();
1045 for (
auto &Q : CompletedQueries) {
1046 assert(Q->isComplete() &&
"Q not completed");
1047 Q->handleComplete(ES);
1050 return Error::success();
1053Error JITDylib::emit(MaterializationResponsibility &MR,
1054 const SymbolFlagsMap &Emitted) {
1055 AsynchronousSymbolQuerySet CompletedQueries;
1056 DenseMap<JITDylib *, SymbolNameVector> ReadySymbols;
1059 if (MR.RT->isDefunct())
1060 return make_error<ResourceTrackerDefunct>(MR.RT);
1063 return make_error<StringError>(
"JITDylib " + getName() +
1065 inconvertibleErrorCode());
1067 SymbolNameSet SymbolsInErrorState;
1068 std::vector<SymbolTable::iterator> Worklist;
1071 for (const auto &KV : Emitted) {
1072 auto &Name = KV.first;
1074 auto SymI = Symbols.find(Name);
1075 assert(SymI != Symbols.end() &&
"No symbol table entry for Name");
1077 if (SymI->second.getFlags().hasError())
1078 SymbolsInErrorState.insert(Name);
1080 Worklist.push_back(SymI);
1084 if (!SymbolsInErrorState.empty()) {
1085 auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
1086 (*FailedSymbolsDepMap)[this] = std::move(SymbolsInErrorState);
1087 return make_error<FailedToMaterialize>(
1088 getExecutionSession().getSymbolStringPool(),
1089 std::move(FailedSymbolsDepMap));
1093 while (!Worklist.empty()) {
1094 auto SymI = Worklist.back();
1095 Worklist.pop_back();
1097 auto &Name = SymI->first;
1098 auto &SymEntry = SymI->second;
1101 assert(((SymEntry.getFlags().hasMaterializationSideEffectsOnly() &&
1102 SymEntry.getState() == SymbolState::Materializing) ||
1103 SymEntry.getState() == SymbolState::Resolved) &&
1104 "Emitting from state other than Resolved");
1105 SymEntry.setState(SymbolState::Emitted);
1107 auto MII = MaterializingInfos.find(Name);
1111 if (MII == MaterializingInfos.end()) {
1112 SymEntry.setState(SymbolState::Ready);
1116 auto &
MI = MII->second;
1121 for (
auto &KV :
MI.Dependants) {
1122 auto &DependantJD = *KV.first;
1123 auto &DependantJDReadySymbols = ReadySymbols[&DependantJD];
1124 for (auto &DependantName : KV.second) {
1126 DependantJD.MaterializingInfos.find(DependantName);
1127 assert(DependantMII != DependantJD.MaterializingInfos.end() &&
1128 "Dependant should have MaterializingInfo");
1130 auto &DependantMI = DependantMII->second;
1133 assert(DependantMI.UnemittedDependencies.count(this) &&
1134 "Dependant does not have an unemitted dependencies record "
1137 assert(DependantMI.UnemittedDependencies[this].count(Name) &&
1138 "Dependant does not count this symbol as a dependency?");
1140 DependantMI.UnemittedDependencies[this].erase(Name);
1141 if (DependantMI.UnemittedDependencies[this].empty())
1142 DependantMI.UnemittedDependencies.erase(this);
1146 DependantJD.transferEmittedNodeDependencies(DependantMI,
1149 auto DependantSymI = DependantJD.Symbols.find(DependantName);
1150 assert(DependantSymI != DependantJD.Symbols.end() &&
1151 "Dependant has no entry in the Symbols table");
1152 auto &DependantSymEntry = DependantSymI->second;
1157 if (DependantSymEntry.getState() == SymbolState::Emitted &&
1158 DependantMI.UnemittedDependencies.empty()) {
1159 assert(DependantMI.Dependants.empty() &&
1160 "Dependants should be empty by now");
1164 DependantSymEntry.setState(SymbolState::Ready);
1165 DependantJDReadySymbols.push_back(DependantName);
1168 DependantMI.takeQueriesMeeting(SymbolState::Ready)) {
1169 Q->notifySymbolMetRequiredState(
1170 DependantName, DependantSymI->second.getSymbol());
1171 if (Q->isComplete())
1172 CompletedQueries.insert(Q);
1173 Q->removeQueryDependence(DependantJD, DependantName);
1175 DependantJD.MaterializingInfos.erase(DependantMII);
1180 auto &ThisJDReadySymbols = ReadySymbols[
this];
1181 MI.Dependants.clear();
1182 if (
MI.UnemittedDependencies.empty()) {
1183 SymI->second.setState(SymbolState::Ready);
1184 ThisJDReadySymbols.push_back(Name);
1185 for (auto &Q : MI.takeQueriesMeeting(SymbolState::Ready)) {
1186 Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
1187 if (Q->isComplete())
1188 CompletedQueries.insert(Q);
1189 Q->removeQueryDependence(*this, Name);
1191 MaterializingInfos.erase(MII);
1195 return Error::success();
1200 for (
auto &Q : CompletedQueries) {
1201 assert(Q->isComplete() &&
"Q is not complete");
1202 Q->handleComplete(ES);
1205 return Error::success();
1208void JITDylib::unlinkMaterializationResponsibility(
1209 MaterializationResponsibility &MR) {
1211 auto I = TrackerMRs.find(MR.RT.get());
1212 assert(
I != TrackerMRs.end() &&
"No MRs in TrackerMRs list for RT");
1213 assert(
I->second.count(&MR) &&
"MR not in TrackerMRs list for RT");
1214 I->second.erase(&MR);
1215 if (
I->second.empty())
1216 TrackerMRs.erase(MR.RT.get());
1220std::pair<JITDylib::AsynchronousSymbolQuerySet,
1221 std::shared_ptr<SymbolDependenceMap>>
1222JITDylib::failSymbols(FailedSymbolsWorklist Worklist) {
1223 AsynchronousSymbolQuerySet FailedQueries;
1224 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
1226 while (!Worklist.empty()) {
1227 assert(Worklist.back().first &&
"Failed JITDylib can not be null");
1228 auto &JD = *Worklist.back().first;
1229 auto Name = std::move(Worklist.back().second);
1230 Worklist.pop_back();
1232 (*FailedSymbolsMap)[&JD].insert(
Name);
1235 auto SymI = JD.Symbols.find(
Name);
1241 if (SymI == JD.Symbols.end())
1243 auto &
Sym = SymI->second;
1248 Sym.setFlags(
Sym.getFlags() | JITSymbolFlags::HasError);
1253 auto MII = JD.MaterializingInfos.find(
Name);
1255 if (MII == JD.MaterializingInfos.end())
1258 auto &
MI = MII->second;
1261 for (
auto &KV :
MI.Dependants) {
1262 auto &DependantJD = *KV.first;
1263 for (
auto &DependantName : KV.second) {
1264 assert(DependantJD.Symbols.count(DependantName) &&
1265 "No symbol table entry for DependantName");
1266 auto &DependantSym = DependantJD.Symbols[DependantName];
1267 DependantSym.setFlags(DependantSym.getFlags() |
1268 JITSymbolFlags::HasError);
1270 assert(DependantJD.MaterializingInfos.count(DependantName) &&
1271 "No MaterializingInfo for dependant");
1272 auto &DependantMI = DependantJD.MaterializingInfos[DependantName];
1274 auto UnemittedDepI = DependantMI.UnemittedDependencies.find(&JD);
1275 assert(UnemittedDepI != DependantMI.UnemittedDependencies.end() &&
1276 "No UnemittedDependencies entry for this JITDylib");
1278 "No UnemittedDependencies entry for this symbol");
1279 UnemittedDepI->second.erase(
Name);
1280 if (UnemittedDepI->second.empty())
1281 DependantMI.UnemittedDependencies.erase(UnemittedDepI);
1286 if (DependantSym.getState() == SymbolState::Emitted) {
1287 assert(DependantMI.Dependants.empty() &&
1288 "Emitted symbol should not have dependants");
1289 Worklist.push_back(std::make_pair(&DependantJD, DependantName));
1293 MI.Dependants.clear();
1296 for (
auto &KV :
MI.UnemittedDependencies) {
1297 auto &UnemittedDepJD = *KV.first;
1298 for (
auto &UnemittedDepName : KV.second) {
1299 auto UnemittedDepMII =
1300 UnemittedDepJD.MaterializingInfos.find(UnemittedDepName);
1301 assert(UnemittedDepMII != UnemittedDepJD.MaterializingInfos.end() &&
1302 "Missing MII for unemitted dependency");
1303 assert(UnemittedDepMII->second.Dependants.count(&JD) &&
1304 "JD not listed as a dependant of unemitted dependency");
1305 assert(UnemittedDepMII->second.Dependants[&JD].count(
Name) &&
1306 "Name is not listed as a dependant of unemitted dependency");
1307 UnemittedDepMII->second.Dependants[&JD].erase(
Name);
1308 if (UnemittedDepMII->second.Dependants[&JD].empty())
1309 UnemittedDepMII->second.Dependants.erase(&JD);
1312 MI.UnemittedDependencies.clear();
1315 AsynchronousSymbolQueryList ToDetach;
1316 for (
auto &Q : MII->second.pendingQueries()) {
1318 FailedQueries.insert(Q);
1319 ToDetach.push_back(Q);
1321 for (
auto &Q : ToDetach)
1325 "Can not delete MaterializingInfo with dependants still attached");
1326 assert(
MI.UnemittedDependencies.empty() &&
1327 "Can not delete MaterializingInfo with unemitted dependencies "
1330 "Can not delete MaterializingInfo with queries pending");
1331 JD.MaterializingInfos.erase(MII);
1334 return std::make_pair(std::move(FailedQueries), std::move(FailedSymbolsMap));
1338 bool LinkAgainstThisJITDylibFirst) {
1340 assert(State == Open &&
"JD is defunct");
1341 if (LinkAgainstThisJITDylibFirst) {
1343 if (NewLinkOrder.empty() || NewLinkOrder.front().first !=
this)
1344 LinkOrder.push_back(
1345 std::make_pair(
this, JITDylibLookupFlags::MatchAllSymbols));
1348 LinkOrder = std::move(NewLinkOrder);
1354 for (
auto &KV : NewLinks) {
1359 LinkOrder.push_back(std::move(KV));
1371 assert(State == Open &&
"JD is defunct");
1372 for (
auto &KV : LinkOrder)
1373 if (KV.first == &OldJD) {
1374 KV = {&NewJD, JDLookupFlags};
1382 assert(State == Open &&
"JD is defunct");
1384 [&](
const JITDylibSearchOrder::value_type &KV) {
1385 return KV.first == &JD;
1387 if (
I != LinkOrder.end())
1394 assert(State == Open &&
"JD is defunct");
1395 using SymbolMaterializerItrPair =
1396 std::pair<SymbolTable::iterator, UnmaterializedInfosMap::iterator>;
1397 std::vector<SymbolMaterializerItrPair> SymbolsToRemove;
1401 for (
auto &
Name : Names) {
1402 auto I = Symbols.find(
Name);
1405 if (
I == Symbols.end()) {
1406 Missing.insert(
Name);
1411 if (
I->second.getState() != SymbolState::NeverSearched &&
1412 I->second.getState() != SymbolState::Ready) {
1417 auto UMII =
I->second.hasMaterializerAttached()
1418 ? UnmaterializedInfos.find(
Name)
1419 : UnmaterializedInfos.end();
1420 SymbolsToRemove.push_back(std::make_pair(
I, UMII));
1424 if (!Missing.empty())
1426 std::move(Missing));
1434 for (
auto &SymbolMaterializerItrPair : SymbolsToRemove) {
1435 auto UMII = SymbolMaterializerItrPair.second;
1438 if (UMII != UnmaterializedInfos.end()) {
1439 UMII->second->MU->doDiscard(*
this, UMII->first);
1440 UnmaterializedInfos.erase(UMII);
1443 auto SymI = SymbolMaterializerItrPair.first;
1444 Symbols.erase(SymI);
1447 return Error::success();
1453 OS <<
"JITDylib \"" <<
getName() <<
"\" (ES: "
1454 <<
format(
"0x%016" PRIx64,
reinterpret_cast<uintptr_t
>(&ES))
1468 if (State == Closed)
1470 OS <<
"Link order: " << LinkOrder <<
"\n"
1471 <<
"Symbol table:\n";
1474 std::vector<std::pair<SymbolStringPtr, SymbolTableEntry *>> SymbolsSorted;
1475 for (
auto &KV : Symbols)
1476 SymbolsSorted.emplace_back(KV.first, &KV.second);
1477 std::sort(SymbolsSorted.begin(), SymbolsSorted.end(),
1478 [](
const auto &L,
const auto &R) { return *L.first < *R.first; });
1480 for (
auto &KV : SymbolsSorted) {
1481 OS <<
" \"" << *KV.first <<
"\": ";
1482 if (
auto Addr = KV.second->getAddress())
1485 OS <<
"<not resolved> ";
1487 OS <<
" " << KV.second->getFlags() <<
" " << KV.second->getState();
1489 if (KV.second->hasMaterializerAttached()) {
1490 OS <<
" (Materializer ";
1491 auto I = UnmaterializedInfos.find(KV.first);
1492 assert(
I != UnmaterializedInfos.end() &&
1493 "Lazy symbol should have UnmaterializedInfo");
1494 OS <<
I->second->MU.get() <<
", " <<
I->second->MU->getName() <<
")\n";
1499 if (!MaterializingInfos.empty())
1500 OS <<
" MaterializingInfos entries:\n";
1501 for (
auto &KV : MaterializingInfos) {
1502 OS <<
" \"" << *KV.first <<
"\":\n"
1503 <<
" " << KV.second.pendingQueries().size()
1504 <<
" pending queries: { ";
1505 for (
const auto &Q : KV.second.pendingQueries())
1506 OS << Q.get() <<
" (" << Q->getRequiredState() <<
") ";
1507 OS <<
"}\n Dependants:\n";
1508 for (
auto &KV2 : KV.second.Dependants)
1509 OS <<
" " << KV2.first->getName() <<
": " << KV2.second <<
"\n";
1510 OS <<
" Unemitted Dependencies:\n";
1511 for (
auto &KV2 : KV.second.UnemittedDependencies)
1512 OS <<
" " << KV2.first->getName() <<
": " << KV2.second <<
"\n";
1513 assert((Symbols[KV.first].getState() != SymbolState::Ready ||
1514 !KV.second.pendingQueries().empty() ||
1515 !KV.second.Dependants.empty() ||
1516 !KV.second.UnemittedDependencies.empty()) &&
1517 "Stale materializing info entry");
1522void JITDylib::MaterializingInfo::addQuery(
1523 std::shared_ptr<AsynchronousSymbolQuery> Q) {
1527 [](
const std::shared_ptr<AsynchronousSymbolQuery> &V,
SymbolState S) {
1528 return V->getRequiredState() <= S;
1530 PendingQueries.insert(
I.base(), std::move(Q));
1533void JITDylib::MaterializingInfo::removeQuery(
1534 const AsynchronousSymbolQuery &Q) {
1537 PendingQueries, [&Q](
const std::shared_ptr<AsynchronousSymbolQuery> &V) {
1538 return V.get() == &Q;
1540 assert(
I != PendingQueries.end() &&
1541 "Query is not attached to this MaterializingInfo");
1542 PendingQueries.erase(
I);
1545JITDylib::AsynchronousSymbolQueryList
1546JITDylib::MaterializingInfo::takeQueriesMeeting(SymbolState RequiredState) {
1547 AsynchronousSymbolQueryList
Result;
1548 while (!PendingQueries.empty()) {
1549 if (PendingQueries.back()->getRequiredState() > RequiredState)
1552 Result.push_back(std::move(PendingQueries.back()));
1553 PendingQueries.pop_back();
1559JITDylib::JITDylib(ExecutionSession &ES, std::string
Name)
1564std::pair<JITDylib::AsynchronousSymbolQuerySet,
1565 std::shared_ptr<SymbolDependenceMap>>
1566JITDylib::removeTracker(ResourceTracker &RT) {
1568 assert(State != Closed &&
"JD is defunct");
1571 std::vector<std::pair<JITDylib *, SymbolStringPtr>> SymbolsToFail;
1573 if (&RT == DefaultTracker.
get()) {
1575 for (
auto &KV : TrackerSymbols)
1576 for (
auto &
Sym : KV.second)
1579 for (
auto &KV : Symbols) {
1580 auto &
Sym = KV.first;
1581 if (!TrackedSymbols.count(
Sym))
1582 SymbolsToRemove.push_back(
Sym);
1585 DefaultTracker.
reset();
1588 auto I = TrackerSymbols.find(&RT);
1589 if (
I != TrackerSymbols.end()) {
1590 SymbolsToRemove = std::move(
I->second);
1591 TrackerSymbols.erase(
I);
1596 for (
auto &
Sym : SymbolsToRemove) {
1597 assert(Symbols.count(
Sym) &&
"Symbol not in symbol table");
1600 auto MII = MaterializingInfos.
find(
Sym);
1601 if (MII != MaterializingInfos.
end())
1602 SymbolsToFail.push_back({
this,
Sym});
1605 AsynchronousSymbolQuerySet QueriesToFail;
1606 auto Result = failSymbols(std::move(SymbolsToFail));
1609 for (
auto &
Sym : SymbolsToRemove) {
1610 auto I = Symbols.find(
Sym);
1611 assert(
I != Symbols.end() &&
"Symbol not present in table");
1614 if (
I->second.hasMaterializerAttached()) {
1619 "Symbol has materializer attached");
1628void JITDylib::transferTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT) {
1629 assert(State != Closed &&
"JD is defunct");
1630 assert(&DstRT != &SrcRT &&
"No-op transfers shouldn't call transferTracker");
1631 assert(&DstRT.getJITDylib() ==
this &&
"DstRT is not for this JITDylib");
1632 assert(&SrcRT.getJITDylib() ==
this &&
"SrcRT is not for this JITDylib");
1635 for (
auto &KV : UnmaterializedInfos) {
1636 if (KV.second->RT == &SrcRT)
1637 KV.second->RT = &DstRT;
1642 auto I = TrackerMRs.find(&SrcRT);
1643 if (
I != TrackerMRs.end()) {
1644 auto &SrcMRs =
I->second;
1645 auto &DstMRs = TrackerMRs[&DstRT];
1646 for (
auto *MR : SrcMRs)
1649 DstMRs = std::move(SrcMRs);
1651 for (
auto *MR : SrcMRs)
1655 TrackerMRs.erase(&SrcRT);
1661 if (&DstRT == DefaultTracker.
get()) {
1662 TrackerSymbols.erase(&SrcRT);
1668 if (&SrcRT == DefaultTracker.
get()) {
1669 assert(!TrackerSymbols.count(&SrcRT) &&
1670 "Default tracker should not appear in TrackerSymbols");
1675 for (
auto &KV : TrackerSymbols)
1676 for (
auto &
Sym : KV.second)
1679 for (
auto &KV : Symbols) {
1680 auto &
Sym = KV.first;
1681 if (!CurrentlyTrackedSymbols.count(
Sym))
1682 SymbolsToTrack.push_back(
Sym);
1685 TrackerSymbols[&DstRT] = std::move(SymbolsToTrack);
1689 auto &DstTrackedSymbols = TrackerSymbols[&DstRT];
1693 auto SI = TrackerSymbols.find(&SrcRT);
1694 if (SI == TrackerSymbols.end())
1697 DstTrackedSymbols.reserve(DstTrackedSymbols.size() +
SI->second.size());
1698 for (
auto &
Sym :
SI->second)
1699 DstTrackedSymbols.push_back(std::move(
Sym));
1700 TrackerSymbols.erase(SI);
1703Error JITDylib::defineImpl(MaterializationUnit &MU) {
1708 std::vector<SymbolStringPtr> ExistingDefsOverridden;
1709 std::vector<SymbolStringPtr> MUDefsOverridden;
1711 for (
const auto &KV : MU.getSymbols()) {
1712 auto I = Symbols.find(KV.first);
1714 if (
I != Symbols.end()) {
1715 if (KV.second.isStrong()) {
1716 if (
I->second.getFlags().isStrong() ||
1718 Duplicates.insert(KV.first);
1721 "Overridden existing def should be in the never-searched "
1723 ExistingDefsOverridden.push_back(KV.first);
1726 MUDefsOverridden.push_back(KV.first);
1731 if (!Duplicates.empty()) {
1733 {
dbgs() <<
" Error: Duplicate symbols " << Duplicates <<
"\n"; });
1734 return make_error<DuplicateDefinition>(std::string(**Duplicates.begin()));
1739 if (!MUDefsOverridden.empty())
1740 dbgs() <<
" Defs in this MU overridden: " << MUDefsOverridden <<
"\n";
1742 for (
auto &S : MUDefsOverridden)
1743 MU.doDiscard(*
this, S);
1747 if (!ExistingDefsOverridden.empty())
1748 dbgs() <<
" Existing defs overridden by this MU: " << MUDefsOverridden
1751 for (
auto &S : ExistingDefsOverridden) {
1753 auto UMII = UnmaterializedInfos.find(S);
1754 assert(UMII != UnmaterializedInfos.end() &&
1755 "Overridden existing def should have an UnmaterializedInfo");
1756 UMII->second->MU->doDiscard(*
this, S);
1760 for (
auto &KV : MU.getSymbols()) {
1761 auto &SymEntry = Symbols[KV.first];
1762 SymEntry.setFlags(KV.second);
1764 SymEntry.setMaterializerAttached(
true);
1770void JITDylib::installMaterializationUnit(
1771 std::unique_ptr<MaterializationUnit> MU, ResourceTracker &RT) {
1774 if (&RT != DefaultTracker.
get()) {
1775 auto &TS = TrackerSymbols[&RT];
1776 TS.reserve(TS.size() + MU->getSymbols().size());
1777 for (
auto &KV : MU->getSymbols())
1778 TS.push_back(KV.first);
1781 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU), &RT);
1782 for (
auto &KV : UMI->MU->getSymbols())
1783 UnmaterializedInfos[KV.first] = UMI;
1786void JITDylib::detachQueryHelper(AsynchronousSymbolQuery &Q,
1788 for (
auto &QuerySymbol : QuerySymbols) {
1790 "QuerySymbol does not have MaterializingInfo");
1791 auto &
MI = MaterializingInfos[QuerySymbol];
1796void JITDylib::transferEmittedNodeDependencies(
1797 MaterializingInfo &DependantMI,
const SymbolStringPtr &DependantName,
1798 MaterializingInfo &EmittedMI) {
1799 for (
auto &KV : EmittedMI.UnemittedDependencies) {
1800 auto &DependencyJD = *KV.first;
1801 SymbolNameSet *UnemittedDependenciesOnDependencyJD =
nullptr;
1803 for (
auto &DependencyName : KV.second) {
1804 auto &DependencyMI = DependencyJD.MaterializingInfos[DependencyName];
1807 if (&DependencyMI == &DependantMI)
1812 if (!UnemittedDependenciesOnDependencyJD)
1813 UnemittedDependenciesOnDependencyJD =
1814 &DependantMI.UnemittedDependencies[&DependencyJD];
1816 DependencyMI.Dependants[
this].
insert(DependantName);
1817 UnemittedDependenciesOnDependencyJD->insert(DependencyName);
1830 std::mutex LookupMutex;
1831 std::condition_variable CV;
1835 dbgs() <<
"Issuing init-symbol lookup:\n";
1836 for (
auto &KV : InitSyms)
1837 dbgs() <<
" " << KV.first->getName() <<
": " << KV.second <<
"\n";
1840 for (
auto &KV : InitSyms) {
1841 auto *JD = KV.first;
1842 auto Names = std::move(KV.second);
1849 std::lock_guard<std::mutex> Lock(LookupMutex);
1853 "Duplicate JITDylib in lookup?");
1854 CompoundResult[JD] = std::move(*
Result);
1864 std::unique_lock<std::mutex> Lock(LookupMutex);
1865 CV.wait(Lock, [&] {
return Count == 0 || CompoundErr; });
1868 return std::move(CompoundErr);
1870 return std::move(CompoundResult);
1877 class TriggerOnComplete {
1880 TriggerOnComplete(OnCompleteFn OnComplete)
1881 : OnComplete(std::move(OnComplete)) {}
1882 ~TriggerOnComplete() { OnComplete(std::move(LookupResult)); }
1883 void reportResult(
Error Err) {
1884 std::lock_guard<std::mutex> Lock(ResultMutex);
1885 LookupResult =
joinErrors(std::move(LookupResult), std::move(Err));
1889 std::mutex ResultMutex;
1890 Error LookupResult{Error::success()};
1891 OnCompleteFn OnComplete;
1895 dbgs() <<
"Issuing init-symbol lookup:\n";
1896 for (
auto &KV : InitSyms)
1897 dbgs() <<
" " << KV.first->getName() <<
": " << KV.second <<
"\n";
1900 auto TOC = std::make_shared<TriggerOnComplete>(std::move(OnComplete));
1902 for (
auto &KV : InitSyms) {
1903 auto *JD = KV.first;
1904 auto Names = std::move(KV.second);
1910 TOC->reportResult(
Result.takeError());
1917 OS <<
"Materialization task: " << MU->getName() <<
" in "
1918 << MR->getTargetJITDylib().getName();
1930 this->EPC->ES =
this;
1936 "Session still open. Did you forget to call endSession?");
1940 LLVM_DEBUG(
dbgs() <<
"Ending ExecutionSession " <<
this <<
"\n");
1943 SessionOpen =
false;
1947 std::reverse(JDsToRemove.begin(), JDsToRemove.end());
1951 Err =
joinErrors(std::move(Err), EPC->disconnect());
1962 assert(!ResourceManagers.empty() &&
"No managers registered");
1963 if (ResourceManagers.back() == &RM)
1964 ResourceManagers.pop_back();
1967 assert(
I != ResourceManagers.end() &&
"RM not registered");
1968 ResourceManagers.erase(
I);
1975 for (
auto &JD : JDs)
1976 if (JD->getName() ==
Name)
1985 assert(SessionOpen &&
"Cannot create JITDylib after session is closed");
1994 if (
auto Err = P->setupJITDylib(JD))
1995 return std::move(Err);
2003 for (
auto &JD : JDsToRemove) {
2004 assert(JD->State == JITDylib::Open &&
"JD already closed");
2005 JD->State = JITDylib::Closing;
2007 assert(
I != JDs.end() &&
"JD does not appear in session JDs");
2014 for (
auto JD : JDsToRemove) {
2015 Err =
joinErrors(std::move(Err), JD->clear());
2017 Err =
joinErrors(std::move(Err), P->teardownJITDylib(*JD));
2022 for (
auto &JD : JDsToRemove) {
2023 assert(JD->State == JITDylib::Closing &&
"JD should be closing");
2024 JD->State = JITDylib::Closed;
2025 assert(JD->Symbols.empty() &&
"JD.Symbols is not empty after clear");
2026 assert(JD->UnmaterializedInfos.empty() &&
2027 "JD.UnmaterializedInfos is not empty after clear");
2028 assert(JD->MaterializingInfos.empty() &&
2029 "JD.MaterializingInfos is not empty after clear");
2030 assert(JD->TrackerSymbols.empty() &&
2031 "TrackerSymbols is not empty after clear");
2032 JD->DefGenerators.clear();
2033 JD->LinkOrder.clear();
2043 return std::vector<JITDylibSP>();
2045 auto &ES = JDs.
front()->getExecutionSession();
2046 return ES.runSessionLocked([&]() ->
Expected<std::vector<JITDylibSP>> {
2048 std::vector<JITDylibSP>
Result;
2050 for (
auto &JD : JDs) {
2052 if (JD->State != Open)
2053 return make_error<StringError>(
2054 "Error building link order: " + JD->getName() +
" is defunct",
2056 if (Visited.
count(JD.get()))
2061 Visited.
insert(JD.get());
2063 while (!WorkStack.empty()) {
2064 Result.push_back(std::move(WorkStack.back()));
2065 WorkStack.pop_back();
2067 for (auto &KV : llvm::reverse(Result.back()->LinkOrder)) {
2068 auto &JD = *KV.first;
2069 if (!Visited.insert(&JD).second)
2071 WorkStack.push_back(&JD);
2099 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
2100 K, std::move(SearchOrder), std::move(LookupSet),
2101 std::move(OnComplete)),
2109 std::promise<MSVCPExpected<SymbolFlagsMap>> ResultP;
2110 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
2111 K, std::move(SearchOrder), std::move(LookupSet),
2113 ResultP.set_value(std::move(
Result));
2117 auto ResultF = ResultP.get_future();
2118 return ResultF.get();
2129 dbgs() <<
"Looking up " << Symbols <<
" in " << SearchOrder
2130 <<
" (required state: " << RequiredState <<
")\n";
2137 dispatchOutstandingMUs();
2139 auto Unresolved = std::move(Symbols);
2140 auto Q = std::make_shared<AsynchronousSymbolQuery>(Unresolved, RequiredState,
2141 std::move(NotifyComplete));
2143 auto IPLS = std::make_unique<InProgressFullLookupState>(
2144 K, SearchOrder, std::move(Unresolved), RequiredState, std::move(Q),
2145 std::move(RegisterDependencies));
2155#if LLVM_ENABLE_THREADS
2157 std::promise<SymbolMap> PromisedResult;
2162 PromisedResult.set_value(std::move(*R));
2165 ResolutionError = R.takeError();
2179 ResolutionError = R.takeError();
2184 lookup(K, SearchOrder, std::move(Symbols), RequiredState, NotifyComplete,
2185 RegisterDependencies);
2187#if LLVM_ENABLE_THREADS
2188 auto ResultFuture = PromisedResult.get_future();
2189 auto Result = ResultFuture.get();
2191 if (ResolutionError)
2192 return std::move(ResolutionError);
2194 return std::move(
Result);
2197 if (ResolutionError)
2198 return std::move(ResolutionError);
2211 assert(ResultMap->size() == 1 &&
"Unexpected number of results");
2212 assert(ResultMap->count(
Name) &&
"Missing result for symbol");
2213 return std::move(ResultMap->begin()->second);
2215 return ResultMap.takeError();
2237 return TagAddrs.takeError();
2240 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
2241 for (
auto &KV : *TagAddrs) {
2242 auto TagAddr = KV.second.getAddress();
2243 if (JITDispatchHandlers.count(TagAddr))
2244 return make_error<StringError>(
"Tag " +
formatv(
"{0:x16}", TagAddr) +
2245 " (for " + *KV.first +
2246 ") already registered",
2248 auto I = WFs.
find(KV.first);
2250 "JITDispatchHandler implementation missing");
2251 JITDispatchHandlers[KV.second.getAddress()] =
2252 std::make_shared<JITDispatchHandlerFunction>(std::move(
I->second));
2254 dbgs() <<
"Associated function tag \"" << *KV.first <<
"\" ("
2255 <<
formatv(
"{0:x}", KV.second.getAddress()) <<
") with handler\n";
2265 std::shared_ptr<JITDispatchHandlerFunction>
F;
2267 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
2268 auto I = JITDispatchHandlers.find(HandlerFnTagAddr);
2269 if (
I != JITDispatchHandlers.end())
2274 (*F)(std::move(SendResult), ArgBuffer.
data(), ArgBuffer.
size());
2277 (
"No function registered for tag " +
2278 formatv(
"{0:x16}", HandlerFnTagAddr))
2284 for (
auto &JD : JDs)
2289void ExecutionSession::dispatchOutstandingMUs() {
2292 std::optional<std::pair<std::unique_ptr<MaterializationUnit>,
2293 std::unique_ptr<MaterializationResponsibility>>>
2297 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2298 if (!OutstandingMUs.empty()) {
2299 JMU.emplace(std::move(OutstandingMUs.back()));
2300 OutstandingMUs.pop_back();
2307 assert(JMU->first &&
"No MU?");
2308 LLVM_DEBUG(
dbgs() <<
" Dispatching \"" << JMU->first->getName() <<
"\"\n");
2309 dispatchTask(std::make_unique<MaterializationTask>(std::move(JMU->first),
2310 std::move(JMU->second)));
2312 LLVM_DEBUG(
dbgs() <<
"Done dispatching MaterializationUnits.\n");
2315Error ExecutionSession::removeResourceTracker(ResourceTracker &RT) {
2317 dbgs() <<
"In " << RT.getJITDylib().getName() <<
" removing tracker "
2318 <<
formatv(
"{0:x}", RT.getKeyUnsafe()) <<
"\n";
2320 std::vector<ResourceManager *> CurrentResourceManagers;
2322 JITDylib::AsynchronousSymbolQuerySet QueriesToFail;
2323 std::shared_ptr<SymbolDependenceMap> FailedSymbols;
2326 CurrentResourceManagers = ResourceManagers;
2328 std::tie(QueriesToFail, FailedSymbols) = RT.getJITDylib().removeTracker(RT);
2333 auto &JD = RT.getJITDylib();
2334 for (
auto *L :
reverse(CurrentResourceManagers))
2336 L->handleRemoveResources(JD, RT.getKeyUnsafe()));
2338 for (
auto &Q : QueriesToFail)
2345void ExecutionSession::transferResourceTracker(ResourceTracker &DstRT,
2346 ResourceTracker &SrcRT) {
2348 dbgs() <<
"In " << SrcRT.getJITDylib().getName()
2349 <<
" transfering resources from tracker "
2350 <<
formatv(
"{0:x}", SrcRT.getKeyUnsafe()) <<
" to tracker "
2351 <<
formatv(
"{0:x}", DstRT.getKeyUnsafe()) <<
"\n";
2355 if (&DstRT == &SrcRT)
2358 assert(&DstRT.getJITDylib() == &SrcRT.getJITDylib() &&
2359 "Can't transfer resources between JITDylibs");
2361 SrcRT.makeDefunct();
2362 auto &JD = DstRT.getJITDylib();
2363 JD.transferTracker(DstRT, SrcRT);
2364 for (
auto *L :
reverse(ResourceManagers))
2365 L->handleTransferResources(JD, DstRT.getKeyUnsafe(),
2366 SrcRT.getKeyUnsafe());
2370void ExecutionSession::destroyResourceTracker(ResourceTracker &RT) {
2373 dbgs() <<
"In " << RT.getJITDylib().getName() <<
" destroying tracker "
2374 <<
formatv(
"{0:x}", RT.getKeyUnsafe()) <<
"\n";
2376 if (!RT.isDefunct())
2377 transferResourceTracker(*RT.getJITDylib().getDefaultResourceTracker(),
2382Error ExecutionSession::IL_updateCandidatesFor(
2384 SymbolLookupSet &Candidates, SymbolLookupSet *NonCandidates) {
2385 return Candidates.forEachWithRemoval(
2386 [&](
const SymbolStringPtr &
Name,
2390 auto SymI = JD.Symbols.find(
Name);
2391 if (SymI == JD.Symbols.end())
2399 if (!SymI->second.getFlags().isExported() &&
2402 NonCandidates->add(Name, SymLookupFlags);
2411 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2418 if (SymI->second.getFlags().hasError()) {
2419 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2420 (*FailedSymbolsMap)[&JD] = {Name};
2422 std::move(FailedSymbolsMap));
2430void ExecutionSession::OL_resumeLookupAfterGeneration(
2431 InProgressLookupState &IPLS) {
2434 "Should not be called for not-in-generator lookups");
2439 if (
auto DG = IPLS.CurDefGeneratorStack.back().lock()) {
2440 IPLS.CurDefGeneratorStack.pop_back();
2441 std::lock_guard<std::mutex> Lock(DG->M);
2445 if (DG->PendingLookups.empty()) {
2451 LS = std::move(DG->PendingLookups.front());
2452 DG->PendingLookups.pop_front();
2457 dispatchTask(std::make_unique<LookupTask>(std::move(LS)));
2461void ExecutionSession::OL_applyQueryPhase1(
2462 std::unique_ptr<InProgressLookupState> IPLS, Error Err) {
2465 dbgs() <<
"Entering OL_applyQueryPhase1:\n"
2466 <<
" Lookup kind: " << IPLS->K <<
"\n"
2467 <<
" Search order: " << IPLS->SearchOrder
2468 <<
", Current index = " << IPLS->CurSearchOrderIndex
2469 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2470 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2471 <<
" Definition generator candidates: "
2472 << IPLS->DefGeneratorCandidates <<
"\n"
2473 <<
" Definition generator non-candidates: "
2474 << IPLS->DefGeneratorNonCandidates <<
"\n";
2478 OL_resumeLookupAfterGeneration(*IPLS);
2481 "Lookup should not be in InGenerator state here");
2488 while (IPLS->CurSearchOrderIndex != IPLS->SearchOrder.size()) {
2494 return IPLS->fail(std::move(Err));
2497 auto &KV = IPLS->SearchOrder[IPLS->CurSearchOrderIndex];
2498 auto &JD = *KV.first;
2499 auto JDLookupFlags = KV.second;
2502 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2503 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2507 if (IPLS->NewJITDylib) {
2511 SymbolLookupSet Tmp;
2512 std::swap(IPLS->DefGeneratorNonCandidates, Tmp);
2513 IPLS->DefGeneratorCandidates.append(std::move(Tmp));
2516 dbgs() <<
" First time visiting " << JD.getName()
2517 <<
", resetting candidate sets and building generator stack\n";
2522 IPLS->CurDefGeneratorStack.reserve(JD.DefGenerators.size());
2524 IPLS->CurDefGeneratorStack.push_back(DG);
2528 IPLS->NewJITDylib =
false;
2537 Err = IL_updateCandidatesFor(
2538 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2539 JD.DefGenerators.empty() ?
nullptr
2540 : &IPLS->DefGeneratorNonCandidates);
2542 dbgs() <<
" Remaining candidates = " << IPLS->DefGeneratorCandidates
2550 IPLS->DefGeneratorCandidates.empty())
2551 OL_resumeLookupAfterGeneration(*IPLS);
2557 return IPLS->fail(std::move(Err));
2561 if (IPLS->CurDefGeneratorStack.empty())
2562 LLVM_DEBUG(
dbgs() <<
" No generators to run for this JITDylib.\n");
2563 else if (IPLS->DefGeneratorCandidates.empty())
2566 dbgs() <<
" Running " << IPLS->CurDefGeneratorStack.size()
2567 <<
" remaining generators for "
2568 << IPLS->DefGeneratorCandidates.size() <<
" candidates\n";
2570 while (!IPLS->CurDefGeneratorStack.empty() &&
2571 !IPLS->DefGeneratorCandidates.empty()) {
2572 auto DG = IPLS->CurDefGeneratorStack.back().lock();
2575 return IPLS->fail(make_error<StringError>(
2576 "DefinitionGenerator removed while lookup in progress",
2589 std::lock_guard<std::mutex> Lock(DG->M);
2591 DG->PendingLookups.push_back(std::move(IPLS));
2600 auto &LookupSet = IPLS->DefGeneratorCandidates;
2605 LLVM_DEBUG(
dbgs() <<
" Attempting to generate " << LookupSet <<
"\n");
2607 Err = DG->tryToGenerate(LS, K, JD, JDLookupFlags, LookupSet);
2608 IPLS = std::move(
LS.IPLS);
2614 OL_resumeLookupAfterGeneration(*IPLS);
2619 dbgs() <<
" Error attempting to generate " << LookupSet <<
"\n";
2621 assert(IPLS &&
"LS cannot be retained if error is returned");
2622 return IPLS->fail(std::move(Err));
2628 {
dbgs() <<
" LookupState captured. Exiting phase1 for now.\n"; });
2635 LLVM_DEBUG(
dbgs() <<
" Updating candidate set post-generation\n");
2636 Err = IL_updateCandidatesFor(
2637 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2638 JD.DefGenerators.empty() ?
nullptr
2639 : &IPLS->DefGeneratorNonCandidates);
2644 LLVM_DEBUG(
dbgs() <<
" Error encountered while updating candidates\n");
2645 return IPLS->fail(std::move(Err));
2649 if (IPLS->DefGeneratorCandidates.empty() &&
2650 IPLS->DefGeneratorNonCandidates.empty()) {
2653 IPLS->CurSearchOrderIndex = IPLS->SearchOrder.size();
2659 ++IPLS->CurSearchOrderIndex;
2660 IPLS->NewJITDylib =
true;
2665 IPLS->DefGeneratorCandidates.remove_if(
2673 if (IPLS->DefGeneratorCandidates.empty()) {
2675 IPLS->complete(std::move(IPLS));
2677 LLVM_DEBUG(
dbgs() <<
"Phase 1 failed with unresolved symbols.\n");
2678 IPLS->fail(make_error<SymbolsNotFound>(
2683void ExecutionSession::OL_completeLookup(
2684 std::unique_ptr<InProgressLookupState> IPLS,
2685 std::shared_ptr<AsynchronousSymbolQuery> Q,
2689 dbgs() <<
"Entering OL_completeLookup:\n"
2690 <<
" Lookup kind: " << IPLS->K <<
"\n"
2691 <<
" Search order: " << IPLS->SearchOrder
2692 <<
", Current index = " << IPLS->CurSearchOrderIndex
2693 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2694 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2695 <<
" Definition generator candidates: "
2696 << IPLS->DefGeneratorCandidates <<
"\n"
2697 <<
" Definition generator non-candidates: "
2698 << IPLS->DefGeneratorNonCandidates <<
"\n";
2701 bool QueryComplete =
false;
2702 DenseMap<JITDylib *, JITDylib::UnmaterializedInfosList> CollectedUMIs;
2705 for (
auto &KV : IPLS->SearchOrder) {
2706 auto &JD = *KV.first;
2707 auto JDLookupFlags = KV.second;
2709 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2710 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2713 auto Err = IPLS->LookupSet.forEachWithRemoval(
2714 [&](
const SymbolStringPtr &
Name,
2717 dbgs() <<
" Attempting to match \"" <<
Name <<
"\" ("
2718 << SymLookupFlags <<
")... ";
2723 auto SymI = JD.Symbols.find(
Name);
2724 if (SymI == JD.Symbols.end()) {
2731 if (!SymI->second.getFlags().isExported() &&
2743 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2747 "required, but symbol is has-side-effects-only\n";
2755 if (SymI->second.getFlags().hasError()) {
2757 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2758 (*FailedSymbolsMap)[&JD] = {
Name};
2759 return make_error<FailedToMaterialize>(
2767 if (SymI->second.getState() >= Q->getRequiredState()) {
2769 <<
"matched, symbol already in required state\n");
2770 Q->notifySymbolMetRequiredState(
Name, SymI->second.getSymbol());
2777 if (SymI->second.hasMaterializerAttached()) {
2778 assert(SymI->second.getAddress() == ExecutorAddr() &&
2779 "Symbol not resolved but already has address?");
2780 auto UMII = JD.UnmaterializedInfos.find(
Name);
2781 assert(UMII != JD.UnmaterializedInfos.end() &&
2782 "Lazy symbol should have UnmaterializedInfo");
2784 auto UMI = UMII->second;
2785 assert(UMI->MU &&
"Materializer should not be null");
2786 assert(UMI->RT &&
"Tracker should not be null");
2788 dbgs() <<
"matched, preparing to dispatch MU@" << UMI->MU.get()
2789 <<
" (" << UMI->MU->getName() <<
")\n";
2794 for (
auto &KV : UMI->MU->getSymbols()) {
2795 auto SymK = JD.Symbols.find(KV.first);
2796 assert(SymK != JD.Symbols.end() &&
2797 "No entry for symbol covered by MaterializationUnit");
2798 SymK->second.setMaterializerAttached(
false);
2800 JD.UnmaterializedInfos.erase(KV.first);
2804 CollectedUMIs[&JD].push_back(std::move(UMI));
2812 "By this line the symbol should be materializing");
2813 auto &
MI = JD.MaterializingInfos[
Name];
2815 Q->addQueryDependence(JD,
Name);
2824 dbgs() <<
"Lookup failed. Detaching query and replacing MUs.\n";
2831 for (
auto &KV : CollectedUMIs) {
2832 auto &JD = *KV.first;
2833 for (
auto &UMI : KV.second)
2834 for (
auto &KV2 : UMI->MU->getSymbols()) {
2835 assert(!JD.UnmaterializedInfos.count(KV2.first) &&
2836 "Unexpected materializer in map");
2837 auto SymI = JD.Symbols.find(KV2.first);
2838 assert(SymI != JD.Symbols.end() &&
"Missing symbol entry");
2840 "Can not replace symbol that is not materializing");
2841 assert(!SymI->second.hasMaterializerAttached() &&
2842 "MaterializerAttached flag should not be set");
2843 SymI->second.setMaterializerAttached(
true);
2844 JD.UnmaterializedInfos[KV2.first] = UMI;
2852 LLVM_DEBUG(
dbgs() <<
"Stripping unmatched weakly-referenced symbols\n");
2853 IPLS->LookupSet.forEachWithRemoval(
2856 Q->dropSymbol(
Name);
2862 if (!IPLS->LookupSet.empty()) {
2865 IPLS->LookupSet.getSymbolNames());
2869 QueryComplete = Q->isComplete();
2872 dbgs() <<
"Query successfully "
2873 << (QueryComplete ?
"completed" :
"lodged") <<
"\n";
2877 if (!CollectedUMIs.empty()) {
2878 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2881 for (
auto &KV : CollectedUMIs) {
2883 auto &JD = *KV.first;
2884 dbgs() <<
" For " << JD.getName() <<
": Adding " << KV.second.size()
2887 for (
auto &UMI : KV.second) {
2888 auto MR = createMaterializationResponsibility(
2889 *UMI->RT, std::move(UMI->MU->SymbolFlags),
2890 std::move(UMI->MU->InitSymbol));
2891 OutstandingMUs.push_back(
2892 std::make_pair(std::move(UMI->MU), std::move(MR)));
2898 if (RegisterDependencies && !Q->QueryRegistrations.empty()) {
2900 RegisterDependencies(Q->QueryRegistrations);
2910 Q->handleFailed(std::move(LodgingErr));
2914 if (QueryComplete) {
2916 Q->handleComplete(*
this);
2919 dispatchOutstandingMUs();
2922void ExecutionSession::OL_completeLookupFlags(
2923 std::unique_ptr<InProgressLookupState> IPLS,
2924 unique_function<
void(Expected<SymbolFlagsMap>)> OnComplete) {
2928 dbgs() <<
"Entering OL_completeLookupFlags:\n"
2929 <<
" Lookup kind: " << IPLS->K <<
"\n"
2930 <<
" Search order: " << IPLS->SearchOrder
2931 <<
", Current index = " << IPLS->CurSearchOrderIndex
2932 << (IPLS->NewJITDylib ?
" (entering new JITDylib)" :
"") <<
"\n"
2933 <<
" Lookup set: " << IPLS->LookupSet <<
"\n"
2934 <<
" Definition generator candidates: "
2935 << IPLS->DefGeneratorCandidates <<
"\n"
2936 <<
" Definition generator non-candidates: "
2937 << IPLS->DefGeneratorNonCandidates <<
"\n";
2943 for (
auto &KV : IPLS->SearchOrder) {
2944 auto &JD = *KV.first;
2945 auto JDLookupFlags = KV.second;
2947 dbgs() <<
"Visiting \"" << JD.getName() <<
"\" (" << JDLookupFlags
2948 <<
") with lookup set " << IPLS->LookupSet <<
":\n";
2951 IPLS->LookupSet.forEachWithRemoval([&](
const SymbolStringPtr &
Name,
2954 dbgs() <<
" Attempting to match \"" <<
Name <<
"\" ("
2955 << SymLookupFlags <<
")... ";
2960 auto SymI = JD.Symbols.find(
Name);
2961 if (SymI == JD.Symbols.end()) {
2967 if (!SymI->second.getFlags().isExported() &&
2974 dbgs() <<
"matched, \"" <<
Name <<
"\" -> " << SymI->second.getFlags()
2983 IPLS->LookupSet.remove_if(
2988 if (!IPLS->LookupSet.empty()) {
2991 IPLS->LookupSet.getSymbolNames());
3000 OnComplete(std::move(
Result));
3003void ExecutionSession::OL_destroyMaterializationResponsibility(
3004 MaterializationResponsibility &MR) {
3006 assert(MR.SymbolFlags.empty() &&
3007 "All symbols should have been explicitly materialized or failed");
3008 MR.JD.unlinkMaterializationResponsibility(MR);
3012 const MaterializationResponsibility &MR) {
3013 return MR.JD.getRequestedSymbols(MR.SymbolFlags);
3016Error ExecutionSession::OL_notifyResolved(MaterializationResponsibility &MR,
3019 dbgs() <<
"In " << MR.JD.getName() <<
" resolving " << Symbols <<
"\n";
3022 for (
auto &KV : Symbols) {
3023 auto I = MR.SymbolFlags.find(KV.first);
3024 assert(
I != MR.SymbolFlags.end() &&
3025 "Resolving symbol outside this responsibility set");
3026 assert(!
I->second.hasMaterializationSideEffectsOnly() &&
3027 "Can't resolve materialization-side-effects-only symbol");
3030 "Resolving symbol with incorrect flags");
3034 return MR.JD.resolve(MR, Symbols);
3037Error ExecutionSession::OL_notifyEmitted(MaterializationResponsibility &MR) {
3039 dbgs() <<
"In " << MR.JD.getName() <<
" emitting " << MR.SymbolFlags
3043 if (
auto Err = MR.JD.emit(MR, MR.SymbolFlags))
3046 MR.SymbolFlags.clear();
3050Error ExecutionSession::OL_defineMaterializing(
3051 MaterializationResponsibility &MR,
SymbolFlagsMap NewSymbolFlags) {
3054 dbgs() <<
"In " << MR.JD.getName() <<
" defining materializing symbols "
3055 << NewSymbolFlags <<
"\n";
3057 if (
auto AcceptedDefs =
3058 MR.JD.defineMaterializing(MR, std::move(NewSymbolFlags))) {
3060 for (
auto &KV : *AcceptedDefs)
3061 MR.SymbolFlags.insert(KV);
3064 return AcceptedDefs.takeError();
3067void ExecutionSession::OL_notifyFailed(MaterializationResponsibility &MR) {
3070 dbgs() <<
"In " << MR.JD.getName() <<
" failing materialization for "
3071 << MR.SymbolFlags <<
"\n";
3074 JITDylib::FailedSymbolsWorklist Worklist;
3076 for (
auto &KV : MR.SymbolFlags)
3077 Worklist.push_back(std::make_pair(&MR.JD, KV.first));
3078 MR.SymbolFlags.clear();
3080 if (Worklist.empty())
3083 JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3084 std::shared_ptr<SymbolDependenceMap> FailedSymbols;
3088 if (MR.RT->isDefunct())
3091 std::tie(FailedQueries, FailedSymbols) =
3092 JITDylib::failSymbols(std::move(Worklist));
3095 for (
auto &Q : FailedQueries)
3100Error ExecutionSession::OL_replace(MaterializationResponsibility &MR,
3101 std::unique_ptr<MaterializationUnit> MU) {
3102 for (
auto &KV : MU->getSymbols()) {
3103 assert(MR.SymbolFlags.count(KV.first) &&
3104 "Replacing definition outside this responsibility set");
3105 MR.SymbolFlags.erase(KV.first);
3108 if (MU->getInitializerSymbol() == MR.InitSymbol)
3109 MR.InitSymbol =
nullptr;
3111 LLVM_DEBUG(MR.JD.getExecutionSession().runSessionLocked([&]() {
3112 dbgs() <<
"In " << MR.JD.getName() <<
" replacing symbols with " << *MU
3116 return MR.JD.replace(MR, std::move(MU));
3119Expected<std::unique_ptr<MaterializationResponsibility>>
3120ExecutionSession::OL_delegate(MaterializationResponsibility &MR,
3123 SymbolStringPtr DelegatedInitSymbol;
3126 for (
auto &
Name : Symbols) {
3127 auto I = MR.SymbolFlags.find(
Name);
3128 assert(
I != MR.SymbolFlags.end() &&
3129 "Symbol is not tracked by this MaterializationResponsibility "
3132 DelegatedFlags[
Name] = std::move(
I->second);
3133 if (
Name == MR.InitSymbol)
3134 std::swap(MR.InitSymbol, DelegatedInitSymbol);
3136 MR.SymbolFlags.erase(
I);
3139 return MR.JD.delegate(MR, std::move(DelegatedFlags),
3140 std::move(DelegatedInitSymbol));
3143void ExecutionSession::OL_addDependencies(
3144 MaterializationResponsibility &MR,
const SymbolStringPtr &
Name,
3147 dbgs() <<
"Adding dependencies for " <<
Name <<
": " << Dependencies
3151 "Symbol not covered by this MaterializationResponsibility instance");
3152 MR.JD.addDependencies(
Name, Dependencies);
3155void ExecutionSession::OL_addDependenciesForAll(
3156 MaterializationResponsibility &MR,
3159 dbgs() <<
"Adding dependencies for all symbols in " << MR.SymbolFlags <<
": "
3160 << Dependencies <<
"\n";
3162 for (
auto &KV : MR.SymbolFlags)
3163 MR.JD.addDependencies(KV.first, Dependencies);
3167void ExecutionSession::dumpDispatchInfo(Task &
T) {
3169 dbgs() <<
"Dispatching: ";
3170 T.printDescription(
dbgs());
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
static StringRef getName(Value *V)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static uint32_t getFlags(const Symbol *Sym)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
const T & front() const
front - Get the first element.
size_t size() const
size - Get the array size.
bool empty() const
empty - Check if the array is empty.
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Helper for Errors used as out-parameters.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Symbol info for RuntimeDyld.
std::pair< iterator, bool > insert(const ValueT &V)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
const std::string & getName() const
Get the name for this JITLinkDylib.
StringRef getName() const override
Return the name of this materialization unit.
AbsoluteSymbolsMaterializationUnit(SymbolMap Symbols)
AsynchronousSymbolQuery(const SymbolLookupSet &Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete)
Create a query for the given symbols.
void notifySymbolMetRequiredState(const SymbolStringPtr &Name, ExecutorSymbolDef Sym)
Notify the query that a requested symbol has reached the required state.
Definition generators can be attached to JITDylibs to generate new definitions for otherwise unresolv...
virtual ~DefinitionGenerator()
An ExecutionSession represents a running JIT program.
Error endSession()
End the session.
void reportError(Error Err)
Report a error for this execution session.
void lookupFlags(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet Symbols, unique_function< void(Expected< SymbolFlagsMap >)> OnComplete)
Search the given JITDylibs to find the flags associated with each of the given symbols.
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
JITDylib * getJITDylibByName(StringRef Name)
Return a pointer to the "name" JITDylib.
JITDylib & createBareJITDylib(std::string Name)
Add a new bare JITDylib to this ExecutionSession.
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete, RegisterDependenciesFunction RegisterDependencies)
Search the given JITDylibs for the given symbols.
Error registerJITDispatchHandlers(JITDylib &JD, JITDispatchHandlerAssociationMap WFs)
For each tag symbol name, associate the corresponding AsyncHandlerWrapperFunction with the address of...
void registerResourceManager(ResourceManager &RM)
Register the given ResourceManager with this ExecutionSession.
~ExecutionSession()
Destroy an ExecutionSession.
void runJITDispatchHandler(SendResultFunction SendResult, ExecutorAddr HandlerFnTagAddr, ArrayRef< char > ArgBuffer)
Run a registered jit-side wrapper function.
void deregisterResourceManager(ResourceManager &RM)
Deregister the given ResourceManager with this ExecutionSession.
ExecutionSession(std::unique_ptr< ExecutorProcessControl > EPC)
Construct an ExecutionSession with the given ExecutorProcessControl object.
decltype(auto) runSessionLocked(Func &&F)
Run the given lambda with the session mutex locked.
void dump(raw_ostream &OS)
Dump the state of all the JITDylibs in this session.
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
enum llvm::orc::InProgressLookupState::@462 GenState
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, KeyT > &M, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Construct a SymbolLookupSet from DenseMap keys.
Pointer to a pooled string representing a symbol name.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
void log(raw_ostream &OS) const override
Print an error message to an output stream.
SymbolsCouldNotBeRemoved(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
void log(raw_ostream &OS) const override
Print an error message to an output stream.
SymbolsNotFound(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Represents an abstract task for ORC to run.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
void log(raw_ostream &OS) const override
Print an error message to an output stream.
static WrapperFunctionResult createOutOfBandError(const char *Msg)
Create an out-of-band error by copying the given string.
This class implements an extremely fast bulk output stream that can only output to a stream.
IntrusiveRefCntPtr< JITDylib > JITDylibSP
JITDylibSearchOrder makeJITDylibSearchOrder(ArrayRef< JITDylib * > JDs, JITDylibLookupFlags Flags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Convenience function for creating a search order from an ArrayRef of JITDylib*, all with the same fla...
std::vector< std::pair< JITDylib *, JITDylibLookupFlags > > JITDylibSearchOrder
A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search order during symbol lookup.
std::function< void(const SymbolDependenceMap &)> RegisterDependenciesFunction
Callback to register the dependencies for a given query.
@ MissingSymbolDefinitions
@ UnexpectedSymbolDefinitions
std::unique_ptr< ReExportsMaterializationUnit > symbolAliases(SymbolAliasMap Aliases)
Create a ReExportsMaterializationUnit with the given aliases.
SymbolLookupFlags
Lookup flags that apply to each symbol in a lookup.
std::unique_ptr< ReExportsMaterializationUnit > reexports(JITDylib &SourceJD, SymbolAliasMap Aliases, JITDylibLookupFlags SourceJDLookupFlags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Create a materialization unit for re-exporting symbols from another JITDylib with alternative names/f...
DenseMap< SymbolStringPtr, SymbolAliasMapEntry > SymbolAliasMap
A map of Symbols to (Symbol, Flags) pairs.
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
@ MatchExportedSymbolsOnly
DenseMap< SymbolStringPtr, ExecutorSymbolDef > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
DenseMap< SymbolStringPtr, JITSymbolFlags > SymbolFlagsMap
A map from symbol names (as SymbolStringPtrs) to JITSymbolFlags.
unique_function< void(Expected< SymbolMap >)> SymbolsResolvedCallback
Callback to notify client that symbols have been resolved.
DenseSet< SymbolStringPtr > SymbolNameSet
A set of symbol names (represented by SymbolStringPtrs for.
LookupKind
Describes the kind of lookup being performed.
RegisterDependenciesFunction NoDependenciesToRegister
This can be used as the value for a RegisterDependenciesFunction if there are no dependants to regist...
std::vector< SymbolStringPtr > SymbolNameVector
A vector of symbol names.
SymbolState
Represents the state that a symbol has reached during materialization.
@ Materializing
Added to the symbol table, never queried.
@ NeverSearched
No symbol should be in this state.
@ Ready
Emitted to memory, but waiting on transitive dependencies.
@ Resolved
Queried, materialization begun.
std::error_code orcError(OrcErrorCode ErrCode)
DenseMap< JITDylib *, SymbolNameSet > SymbolDependenceMap
A map from JITDylibs to sets of symbols.
Expected< SymbolAliasMap > buildSimpleReexportsAliasMap(JITDylib &SourceJD, const SymbolNameSet &Symbols)
Build a SymbolAliasMap for the common case where you want to re-export symbols from another JITDylib ...
This is an optimization pass for GlobalISel generic memory operations.
auto formatv(const char *Fmt, Ts &&... Vals) -> formatv_object< decltype(std::make_tuple(detail::build_format_adapter(std::forward< Ts >(Vals))...))>
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
void append_range(Container &C, Range &&R)
Wrapper function to append 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.
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.