LLVM 20.0.0git
Core.cpp
Go to the documentation of this file.
1//===--- Core.cpp - Core ORC APIs (MaterializationUnit, JITDylib, etc.) ---===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
11#include "llvm/ADT/STLExtras.h"
12#include "llvm/Config/llvm-config.h"
18
19#include <condition_variable>
20#include <future>
21#include <optional>
22
23#define DEBUG_TYPE "orc"
24
25namespace llvm {
26namespace orc {
27
30char SymbolsNotFound::ID = 0;
36char LookupTask::ID = 0;
37
40
41void MaterializationUnit::anchor() {}
42
44 assert((reinterpret_cast<uintptr_t>(JD.get()) & 0x1) == 0 &&
45 "JITDylib must be two byte aligned");
46 JD->Retain();
47 JDAndFlag.store(reinterpret_cast<uintptr_t>(JD.get()));
48}
49
51 getJITDylib().getExecutionSession().destroyResourceTracker(*this);
53}
54
56 return getJITDylib().getExecutionSession().removeResourceTracker(*this);
57}
58
60 getJITDylib().getExecutionSession().transferResourceTracker(DstRT, *this);
61}
62
63void ResourceTracker::makeDefunct() {
64 uintptr_t Val = JDAndFlag.load();
65 Val |= 0x1U;
66 JDAndFlag.store(Val);
67}
68
70
72 : RT(std::move(RT)) {}
73
76}
77
79 OS << "Resource tracker " << (void *)RT.get() << " became defunct";
80}
81
83 std::shared_ptr<SymbolStringPool> SSP,
84 std::shared_ptr<SymbolDependenceMap> Symbols)
85 : SSP(std::move(SSP)), Symbols(std::move(Symbols)) {
86 assert(this->SSP && "String pool cannot be null");
87 assert(!this->Symbols->empty() && "Can not fail to resolve an empty set");
88
89 // FIXME: Use a new dep-map type for FailedToMaterialize errors so that we
90 // don't have to manually retain/release.
91 for (auto &[JD, Syms] : *this->Symbols)
92 JD->Retain();
93}
94
96 for (auto &[JD, Syms] : *Symbols)
97 JD->Release();
98}
99
102}
103
105 OS << "Failed to materialize symbols: " << *Symbols;
106}
107
109 std::shared_ptr<SymbolStringPool> SSP, JITDylibSP JD,
110 SymbolNameSet FailedSymbols, SymbolDependenceMap BadDeps,
111 std::string Explanation)
112 : SSP(std::move(SSP)), JD(std::move(JD)),
113 FailedSymbols(std::move(FailedSymbols)), BadDeps(std::move(BadDeps)),
114 Explanation(std::move(Explanation)) {}
115
118}
119
121 OS << "In " << JD->getName() << ", failed to materialize " << FailedSymbols
122 << ", due to unsatisfied dependencies " << BadDeps;
123 if (!Explanation.empty())
124 OS << " (" << Explanation << ")";
125}
126
127SymbolsNotFound::SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP,
128 SymbolNameSet Symbols)
129 : SSP(std::move(SSP)) {
130 for (auto &Sym : Symbols)
131 this->Symbols.push_back(Sym);
132 assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
133}
134
135SymbolsNotFound::SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP,
136 SymbolNameVector Symbols)
137 : SSP(std::move(SSP)), Symbols(std::move(Symbols)) {
138 assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
139}
140
141std::error_code SymbolsNotFound::convertToErrorCode() const {
143}
144
146 OS << "Symbols not found: " << Symbols;
147}
148
150 std::shared_ptr<SymbolStringPool> SSP, SymbolNameSet Symbols)
151 : SSP(std::move(SSP)), Symbols(std::move(Symbols)) {
152 assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
153}
154
157}
158
160 OS << "Symbols could not be removed: " << Symbols;
161}
162
165}
166
168 OS << "Missing definitions in module " << ModuleName
169 << ": " << Symbols;
170}
171
174}
175
177 OS << "Unexpected definitions in module " << ModuleName
178 << ": " << Symbols;
179}
180
182 JD->getExecutionSession().lookup(
185 [OnComplete = std::move(OnComplete)
186#ifndef NDEBUG
187 ,
188 Name = this->Name // Captured for the assert below only.
189#endif // NDEBUG
190 ](Expected<SymbolMap> Result) mutable {
191 if (Result) {
192 assert(Result->size() == 1 && "Unexpected number of results");
193 assert(Result->count(Name) &&
194 "Result does not contain expected symbol");
195 OnComplete(Result->begin()->second);
196 } else
197 OnComplete(Result.takeError());
198 },
200}
201
203 const SymbolLookupSet &Symbols, SymbolState RequiredState,
204 SymbolsResolvedCallback NotifyComplete)
205 : NotifyComplete(std::move(NotifyComplete)), RequiredState(RequiredState) {
206 assert(RequiredState >= SymbolState::Resolved &&
207 "Cannot query for a symbols that have not reached the resolve state "
208 "yet");
209
210 OutstandingSymbolsCount = Symbols.size();
211
212 for (auto &[Name, Flags] : Symbols)
213 ResolvedSymbols[Name] = ExecutorSymbolDef();
214}
215
218 auto I = ResolvedSymbols.find(Name);
219 assert(I != ResolvedSymbols.end() &&
220 "Resolving symbol outside the requested set");
221 assert(I->second == ExecutorSymbolDef() &&
222 "Redundantly resolving symbol Name");
223
224 // If this is a materialization-side-effects-only symbol then drop it,
225 // otherwise update its map entry with its resolved address.
226 if (Sym.getFlags().hasMaterializationSideEffectsOnly())
227 ResolvedSymbols.erase(I);
228 else
229 I->second = std::move(Sym);
230 --OutstandingSymbolsCount;
231}
232
233void AsynchronousSymbolQuery::handleComplete(ExecutionSession &ES) {
234 assert(OutstandingSymbolsCount == 0 &&
235 "Symbols remain, handleComplete called prematurely");
236
237 class RunQueryCompleteTask : public Task {
238 public:
239 RunQueryCompleteTask(SymbolMap ResolvedSymbols,
240 SymbolsResolvedCallback NotifyComplete)
241 : ResolvedSymbols(std::move(ResolvedSymbols)),
242 NotifyComplete(std::move(NotifyComplete)) {}
243 void printDescription(raw_ostream &OS) override {
244 OS << "Execute query complete callback for " << ResolvedSymbols;
245 }
246 void run() override { NotifyComplete(std::move(ResolvedSymbols)); }
247
248 private:
249 SymbolMap ResolvedSymbols;
250 SymbolsResolvedCallback NotifyComplete;
251 };
252
253 auto T = std::make_unique<RunQueryCompleteTask>(std::move(ResolvedSymbols),
254 std::move(NotifyComplete));
255 NotifyComplete = SymbolsResolvedCallback();
256 ES.dispatchTask(std::move(T));
257}
258
259void AsynchronousSymbolQuery::handleFailed(Error Err) {
260 assert(QueryRegistrations.empty() && ResolvedSymbols.empty() &&
261 OutstandingSymbolsCount == 0 &&
262 "Query should already have been abandoned");
263 NotifyComplete(std::move(Err));
264 NotifyComplete = SymbolsResolvedCallback();
265}
266
267void AsynchronousSymbolQuery::addQueryDependence(JITDylib &JD,
268 SymbolStringPtr Name) {
269 bool Added = QueryRegistrations[&JD].insert(std::move(Name)).second;
270 (void)Added;
271 assert(Added && "Duplicate dependence notification?");
272}
273
274void AsynchronousSymbolQuery::removeQueryDependence(
275 JITDylib &JD, const SymbolStringPtr &Name) {
276 auto QRI = QueryRegistrations.find(&JD);
277 assert(QRI != QueryRegistrations.end() &&
278 "No dependencies registered for JD");
279 assert(QRI->second.count(Name) && "No dependency on Name in JD");
280 QRI->second.erase(Name);
281 if (QRI->second.empty())
282 QueryRegistrations.erase(QRI);
283}
284
285void AsynchronousSymbolQuery::dropSymbol(const SymbolStringPtr &Name) {
286 auto I = ResolvedSymbols.find(Name);
287 assert(I != ResolvedSymbols.end() &&
288 "Redundant removal of weakly-referenced symbol");
289 ResolvedSymbols.erase(I);
290 --OutstandingSymbolsCount;
291}
292
293void AsynchronousSymbolQuery::detach() {
294 ResolvedSymbols.clear();
295 OutstandingSymbolsCount = 0;
296 for (auto &[JD, Syms] : QueryRegistrations)
297 JD->detachQueryHelper(*this, Syms);
298 QueryRegistrations.clear();
299}
300
302 JITDylib *SourceJD, JITDylibLookupFlags SourceJDLookupFlags,
303 SymbolAliasMap Aliases)
304 : MaterializationUnit(extractFlags(Aliases)), SourceJD(SourceJD),
305 SourceJDLookupFlags(SourceJDLookupFlags), Aliases(std::move(Aliases)) {}
306
308 return "<Reexports>";
309}
310
311void ReExportsMaterializationUnit::materialize(
312 std::unique_ptr<MaterializationResponsibility> R) {
313
314 auto &ES = R->getTargetJITDylib().getExecutionSession();
315 JITDylib &TgtJD = R->getTargetJITDylib();
316 JITDylib &SrcJD = SourceJD ? *SourceJD : TgtJD;
317
318 // Find the set of requested aliases and aliasees. Return any unrequested
319 // aliases back to the JITDylib so as to not prematurely materialize any
320 // aliasees.
321 auto RequestedSymbols = R->getRequestedSymbols();
322 SymbolAliasMap RequestedAliases;
323
324 for (auto &Name : RequestedSymbols) {
325 auto I = Aliases.find(Name);
326 assert(I != Aliases.end() && "Symbol not found in aliases map?");
327 RequestedAliases[Name] = std::move(I->second);
328 Aliases.erase(I);
329 }
330
331 LLVM_DEBUG({
332 ES.runSessionLocked([&]() {
333 dbgs() << "materializing reexports: target = " << TgtJD.getName()
334 << ", source = " << SrcJD.getName() << " " << RequestedAliases
335 << "\n";
336 });
337 });
338
339 if (!Aliases.empty()) {
340 auto Err = SourceJD ? R->replace(reexports(*SourceJD, std::move(Aliases),
341 SourceJDLookupFlags))
342 : R->replace(symbolAliases(std::move(Aliases)));
343
344 if (Err) {
345 // FIXME: Should this be reported / treated as failure to materialize?
346 // Or should this be treated as a sanctioned bailing-out?
347 ES.reportError(std::move(Err));
348 R->failMaterialization();
349 return;
350 }
351 }
352
353 // The OnResolveInfo struct will hold the aliases and responsibility for each
354 // query in the list.
355 struct OnResolveInfo {
356 OnResolveInfo(std::unique_ptr<MaterializationResponsibility> R,
357 SymbolAliasMap Aliases)
358 : R(std::move(R)), Aliases(std::move(Aliases)) {}
359
360 std::unique_ptr<MaterializationResponsibility> R;
361 SymbolAliasMap Aliases;
362 std::vector<SymbolDependenceGroup> SDGs;
363 };
364
365 // Build a list of queries to issue. In each round we build a query for the
366 // largest set of aliases that we can resolve without encountering a chain of
367 // aliases (e.g. Foo -> Bar, Bar -> Baz). Such a chain would deadlock as the
368 // query would be waiting on a symbol that it itself had to resolve. Creating
369 // a new query for each link in such a chain eliminates the possibility of
370 // deadlock. In practice chains are likely to be rare, and this algorithm will
371 // usually result in a single query to issue.
372
373 std::vector<std::pair<SymbolLookupSet, std::shared_ptr<OnResolveInfo>>>
374 QueryInfos;
375 while (!RequestedAliases.empty()) {
376 SymbolNameSet ResponsibilitySymbols;
377 SymbolLookupSet QuerySymbols;
378 SymbolAliasMap QueryAliases;
379
380 // Collect as many aliases as we can without including a chain.
381 for (auto &KV : RequestedAliases) {
382 // Chain detected. Skip this symbol for this round.
383 if (&SrcJD == &TgtJD && (QueryAliases.count(KV.second.Aliasee) ||
384 RequestedAliases.count(KV.second.Aliasee)))
385 continue;
386
387 ResponsibilitySymbols.insert(KV.first);
388 QuerySymbols.add(KV.second.Aliasee,
389 KV.second.AliasFlags.hasMaterializationSideEffectsOnly()
392 QueryAliases[KV.first] = std::move(KV.second);
393 }
394
395 // Remove the aliases collected this round from the RequestedAliases map.
396 for (auto &KV : QueryAliases)
397 RequestedAliases.erase(KV.first);
398
399 assert(!QuerySymbols.empty() && "Alias cycle detected!");
400
401 auto NewR = R->delegate(ResponsibilitySymbols);
402 if (!NewR) {
403 ES.reportError(NewR.takeError());
404 R->failMaterialization();
405 return;
406 }
407
408 auto QueryInfo = std::make_shared<OnResolveInfo>(std::move(*NewR),
409 std::move(QueryAliases));
410 QueryInfos.push_back(
411 make_pair(std::move(QuerySymbols), std::move(QueryInfo)));
412 }
413
414 // Issue the queries.
415 while (!QueryInfos.empty()) {
416 auto QuerySymbols = std::move(QueryInfos.back().first);
417 auto QueryInfo = std::move(QueryInfos.back().second);
418
419 QueryInfos.pop_back();
420
421 auto RegisterDependencies = [QueryInfo,
422 &SrcJD](const SymbolDependenceMap &Deps) {
423 // If there were no materializing symbols, just bail out.
424 if (Deps.empty())
425 return;
426
427 // Otherwise the only deps should be on SrcJD.
428 assert(Deps.size() == 1 && Deps.count(&SrcJD) &&
429 "Unexpected dependencies for reexports");
430
431 auto &SrcJDDeps = Deps.find(&SrcJD)->second;
432
433 for (auto &[Alias, AliasInfo] : QueryInfo->Aliases)
434 if (SrcJDDeps.count(AliasInfo.Aliasee))
435 QueryInfo->SDGs.push_back({{Alias}, {{&SrcJD, {AliasInfo.Aliasee}}}});
436 };
437
438 auto OnComplete = [QueryInfo](Expected<SymbolMap> Result) {
439 auto &ES = QueryInfo->R->getTargetJITDylib().getExecutionSession();
440 if (Result) {
441 SymbolMap ResolutionMap;
442 for (auto &KV : QueryInfo->Aliases) {
443 assert((KV.second.AliasFlags.hasMaterializationSideEffectsOnly() ||
444 Result->count(KV.second.Aliasee)) &&
445 "Result map missing entry?");
446 // Don't try to resolve materialization-side-effects-only symbols.
447 if (KV.second.AliasFlags.hasMaterializationSideEffectsOnly())
448 continue;
449
450 ResolutionMap[KV.first] = {(*Result)[KV.second.Aliasee].getAddress(),
451 KV.second.AliasFlags};
452 }
453 if (auto Err = QueryInfo->R->notifyResolved(ResolutionMap)) {
454 ES.reportError(std::move(Err));
455 QueryInfo->R->failMaterialization();
456 return;
457 }
458 if (auto Err = QueryInfo->R->notifyEmitted(QueryInfo->SDGs)) {
459 ES.reportError(std::move(Err));
460 QueryInfo->R->failMaterialization();
461 return;
462 }
463 } else {
464 ES.reportError(Result.takeError());
465 QueryInfo->R->failMaterialization();
466 }
467 };
468
470 JITDylibSearchOrder({{&SrcJD, SourceJDLookupFlags}}),
471 QuerySymbols, SymbolState::Resolved, std::move(OnComplete),
472 std::move(RegisterDependencies));
473 }
474}
475
476void ReExportsMaterializationUnit::discard(const JITDylib &JD,
477 const SymbolStringPtr &Name) {
478 assert(Aliases.count(Name) &&
479 "Symbol not covered by this MaterializationUnit");
480 Aliases.erase(Name);
481}
482
483MaterializationUnit::Interface
484ReExportsMaterializationUnit::extractFlags(const SymbolAliasMap &Aliases) {
486 for (auto &KV : Aliases)
487 SymbolFlags[KV.first] = KV.second.AliasFlags;
488
489 return MaterializationUnit::Interface(std::move(SymbolFlags), nullptr);
490}
491
493 SymbolNameSet Symbols) {
494 SymbolLookupSet LookupSet(Symbols);
495 auto Flags = SourceJD.getExecutionSession().lookupFlags(
497 SymbolLookupSet(std::move(Symbols)));
498
499 if (!Flags)
500 return Flags.takeError();
501
503 for (auto &Name : Symbols) {
504 assert(Flags->count(Name) && "Missing entry in flags map");
505 Result[Name] = SymbolAliasMapEntry(Name, (*Flags)[Name]);
506 }
507
508 return Result;
509}
510
512public:
513 // FIXME: Reduce the number of SymbolStringPtrs here. See
514 // https://github.com/llvm/llvm-project/issues/55576.
515
521 }
522 virtual ~InProgressLookupState() = default;
523 virtual void complete(std::unique_ptr<InProgressLookupState> IPLS) = 0;
524 virtual void fail(Error Err) = 0;
525
530
532 bool NewJITDylib = true;
535
536 enum {
537 NotInGenerator, // Not currently using a generator.
538 ResumedForGenerator, // Resumed after being auto-suspended before generator.
539 InGenerator // Currently using generator.
541 std::vector<std::weak_ptr<DefinitionGenerator>> CurDefGeneratorStack;
542};
543
545public:
551 OnComplete(std::move(OnComplete)) {}
552
553 void complete(std::unique_ptr<InProgressLookupState> IPLS) override {
554 auto &ES = SearchOrder.front().first->getExecutionSession();
555 ES.OL_completeLookupFlags(std::move(IPLS), std::move(OnComplete));
556 }
557
558 void fail(Error Err) override { OnComplete(std::move(Err)); }
559
560private:
562};
563
565public:
569 std::shared_ptr<AsynchronousSymbolQuery> Q,
570 RegisterDependenciesFunction RegisterDependencies)
573 Q(std::move(Q)), RegisterDependencies(std::move(RegisterDependencies)) {
574 }
575
576 void complete(std::unique_ptr<InProgressLookupState> IPLS) override {
577 auto &ES = SearchOrder.front().first->getExecutionSession();
578 ES.OL_completeLookup(std::move(IPLS), std::move(Q),
579 std::move(RegisterDependencies));
580 }
581
582 void fail(Error Err) override {
583 Q->detach();
584 Q->handleFailed(std::move(Err));
585 }
586
587private:
588 std::shared_ptr<AsynchronousSymbolQuery> Q;
589 RegisterDependenciesFunction RegisterDependencies;
590};
591
593 JITDylibLookupFlags SourceJDLookupFlags,
594 SymbolPredicate Allow)
595 : SourceJD(SourceJD), SourceJDLookupFlags(SourceJDLookupFlags),
596 Allow(std::move(Allow)) {}
597
599 JITDylib &JD,
600 JITDylibLookupFlags JDLookupFlags,
601 const SymbolLookupSet &LookupSet) {
602 assert(&JD != &SourceJD && "Cannot re-export from the same dylib");
603
604 // Use lookupFlags to find the subset of symbols that match our lookup.
605 auto Flags = JD.getExecutionSession().lookupFlags(
606 K, {{&SourceJD, JDLookupFlags}}, LookupSet);
607 if (!Flags)
608 return Flags.takeError();
609
610 // Create an alias map.
611 orc::SymbolAliasMap AliasMap;
612 for (auto &KV : *Flags)
613 if (!Allow || Allow(KV.first))
614 AliasMap[KV.first] = SymbolAliasMapEntry(KV.first, KV.second);
615
616 if (AliasMap.empty())
617 return Error::success();
618
619 // Define the re-exports.
620 return JD.define(reexports(SourceJD, AliasMap, SourceJDLookupFlags));
621}
622
623LookupState::LookupState(std::unique_ptr<InProgressLookupState> IPLS)
624 : IPLS(std::move(IPLS)) {}
625
626void LookupState::reset(InProgressLookupState *IPLS) { this->IPLS.reset(IPLS); }
627
628LookupState::LookupState() = default;
629LookupState::LookupState(LookupState &&) = default;
630LookupState &LookupState::operator=(LookupState &&) = default;
631LookupState::~LookupState() = default;
632
634 assert(IPLS && "Cannot call continueLookup on empty LookupState");
635 auto &ES = IPLS->SearchOrder.begin()->first->getExecutionSession();
636 ES.OL_applyQueryPhase1(std::move(IPLS), std::move(Err));
637}
638
640 std::deque<LookupState> LookupsToFail;
641 {
642 std::lock_guard<std::mutex> Lock(M);
643 std::swap(PendingLookups, LookupsToFail);
644 InUse = false;
645 }
646
647 for (auto &LS : LookupsToFail)
648 LS.continueLookup(make_error<StringError>(
649 "Query waiting on DefinitionGenerator that was destroyed",
651}
652
654 LLVM_DEBUG(dbgs() << "Destroying JITDylib " << getName() << "\n");
655}
656
658 std::vector<ResourceTrackerSP> TrackersToRemove;
659 ES.runSessionLocked([&]() {
660 assert(State != Closed && "JD is defunct");
661 for (auto &KV : TrackerSymbols)
662 TrackersToRemove.push_back(KV.first);
663 TrackersToRemove.push_back(getDefaultResourceTracker());
664 });
665
666 Error Err = Error::success();
667 for (auto &RT : TrackersToRemove)
668 Err = joinErrors(std::move(Err), RT->remove());
669 return Err;
670}
671
673 return ES.runSessionLocked([this] {
674 assert(State != Closed && "JD is defunct");
675 if (!DefaultTracker)
676 DefaultTracker = new ResourceTracker(this);
677 return DefaultTracker;
678 });
679}
680
682 return ES.runSessionLocked([this] {
683 assert(State == Open && "JD is defunct");
684 ResourceTrackerSP RT = new ResourceTracker(this);
685 return RT;
686 });
687}
688
690 // DefGenerator moved into TmpDG to ensure that it's destroyed outside the
691 // session lock (since it may have to send errors to pending queries).
692 std::shared_ptr<DefinitionGenerator> TmpDG;
693
694 ES.runSessionLocked([&] {
695 assert(State == Open && "JD is defunct");
696 auto I = llvm::find_if(DefGenerators,
697 [&](const std::shared_ptr<DefinitionGenerator> &H) {
698 return H.get() == &G;
699 });
700 assert(I != DefGenerators.end() && "Generator not found");
701 TmpDG = std::move(*I);
702 DefGenerators.erase(I);
703 });
704}
705
707JITDylib::defineMaterializing(MaterializationResponsibility &FromMR,
708 SymbolFlagsMap SymbolFlags) {
709
710 return ES.runSessionLocked([&]() -> Expected<SymbolFlagsMap> {
711 if (FromMR.RT->isDefunct())
712 return make_error<ResourceTrackerDefunct>(FromMR.RT);
713
714 std::vector<NonOwningSymbolStringPtr> AddedSyms;
715 std::vector<NonOwningSymbolStringPtr> RejectedWeakDefs;
716
717 for (auto SFItr = SymbolFlags.begin(), SFEnd = SymbolFlags.end();
718 SFItr != SFEnd; ++SFItr) {
719
720 auto &Name = SFItr->first;
721 auto &Flags = SFItr->second;
722
723 auto EntryItr = Symbols.find(Name);
724
725 // If the entry already exists...
726 if (EntryItr != Symbols.end()) {
727
728 // If this is a strong definition then error out.
729 if (!Flags.isWeak()) {
730 // Remove any symbols already added.
731 for (auto &S : AddedSyms)
732 Symbols.erase(Symbols.find_as(S));
733
734 // FIXME: Return all duplicates.
735 return make_error<DuplicateDefinition>(std::string(*Name));
736 }
737
738 // Otherwise just make a note to discard this symbol after the loop.
739 RejectedWeakDefs.push_back(NonOwningSymbolStringPtr(Name));
740 continue;
741 } else
742 EntryItr =
743 Symbols.insert(std::make_pair(Name, SymbolTableEntry(Flags))).first;
744
745 AddedSyms.push_back(NonOwningSymbolStringPtr(Name));
746 EntryItr->second.setState(SymbolState::Materializing);
747 }
748
749 // Remove any rejected weak definitions from the SymbolFlags map.
750 while (!RejectedWeakDefs.empty()) {
751 SymbolFlags.erase(SymbolFlags.find_as(RejectedWeakDefs.back()));
752 RejectedWeakDefs.pop_back();
753 }
754
755 return SymbolFlags;
756 });
757}
758
759Error JITDylib::replace(MaterializationResponsibility &FromMR,
760 std::unique_ptr<MaterializationUnit> MU) {
761 assert(MU != nullptr && "Can not replace with a null MaterializationUnit");
762 std::unique_ptr<MaterializationUnit> MustRunMU;
763 std::unique_ptr<MaterializationResponsibility> MustRunMR;
764
765 auto Err =
766 ES.runSessionLocked([&, this]() -> Error {
767 if (FromMR.RT->isDefunct())
768 return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
769
770#ifndef NDEBUG
771 for (auto &KV : MU->getSymbols()) {
772 auto SymI = Symbols.find(KV.first);
773 assert(SymI != Symbols.end() && "Replacing unknown symbol");
774 assert(SymI->second.getState() == SymbolState::Materializing &&
775 "Can not replace a symbol that ha is not materializing");
776 assert(!SymI->second.hasMaterializerAttached() &&
777 "Symbol should not have materializer attached already");
778 assert(UnmaterializedInfos.count(KV.first) == 0 &&
779 "Symbol being replaced should have no UnmaterializedInfo");
780 }
781#endif // NDEBUG
782
783 // If the tracker is defunct we need to bail out immediately.
784
785 // If any symbol has pending queries against it then we need to
786 // materialize MU immediately.
787 for (auto &KV : MU->getSymbols()) {
788 auto MII = MaterializingInfos.find(KV.first);
789 if (MII != MaterializingInfos.end()) {
790 if (MII->second.hasQueriesPending()) {
791 MustRunMR = ES.createMaterializationResponsibility(
792 *FromMR.RT, std::move(MU->SymbolFlags),
793 std::move(MU->InitSymbol));
794 MustRunMU = std::move(MU);
795 return Error::success();
796 }
797 }
798 }
799
800 // Otherwise, make MU responsible for all the symbols.
801 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU),
802 FromMR.RT.get());
803 for (auto &KV : UMI->MU->getSymbols()) {
804 auto SymI = Symbols.find(KV.first);
805 assert(SymI->second.getState() == SymbolState::Materializing &&
806 "Can not replace a symbol that is not materializing");
807 assert(!SymI->second.hasMaterializerAttached() &&
808 "Can not replace a symbol that has a materializer attached");
809 assert(UnmaterializedInfos.count(KV.first) == 0 &&
810 "Unexpected materializer entry in map");
811 SymI->second.setAddress(SymI->second.getAddress());
812 SymI->second.setMaterializerAttached(true);
813
814 auto &UMIEntry = UnmaterializedInfos[KV.first];
815 assert((!UMIEntry || !UMIEntry->MU) &&
816 "Replacing symbol with materializer still attached");
817 UMIEntry = UMI;
818 }
819
820 return Error::success();
821 });
822
823 if (Err)
824 return Err;
825
826 if (MustRunMU) {
827 assert(MustRunMR && "MustRunMU set implies MustRunMR set");
828 ES.dispatchTask(std::make_unique<MaterializationTask>(
829 std::move(MustRunMU), std::move(MustRunMR)));
830 } else {
831 assert(!MustRunMR && "MustRunMU unset implies MustRunMR unset");
832 }
833
834 return Error::success();
835}
836
837Expected<std::unique_ptr<MaterializationResponsibility>>
838JITDylib::delegate(MaterializationResponsibility &FromMR,
839 SymbolFlagsMap SymbolFlags, SymbolStringPtr InitSymbol) {
840
841 return ES.runSessionLocked(
842 [&]() -> Expected<std::unique_ptr<MaterializationResponsibility>> {
843 if (FromMR.RT->isDefunct())
844 return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
845
846 return ES.createMaterializationResponsibility(
847 *FromMR.RT, std::move(SymbolFlags), std::move(InitSymbol));
848 });
849}
850
852JITDylib::getRequestedSymbols(const SymbolFlagsMap &SymbolFlags) const {
853 return ES.runSessionLocked([&]() {
854 SymbolNameSet RequestedSymbols;
855
856 for (auto &KV : SymbolFlags) {
857 assert(Symbols.count(KV.first) && "JITDylib does not cover this symbol?");
858 assert(Symbols.find(KV.first)->second.getState() !=
859 SymbolState::NeverSearched &&
860 Symbols.find(KV.first)->second.getState() != SymbolState::Ready &&
861 "getRequestedSymbols can only be called for symbols that have "
862 "started materializing");
863 auto I = MaterializingInfos.find(KV.first);
864 if (I == MaterializingInfos.end())
865 continue;
866
867 if (I->second.hasQueriesPending())
868 RequestedSymbols.insert(KV.first);
869 }
870
871 return RequestedSymbols;
872 });
873}
874
875Error JITDylib::resolve(MaterializationResponsibility &MR,
876 const SymbolMap &Resolved) {
877 AsynchronousSymbolQuerySet CompletedQueries;
878
879 if (auto Err = ES.runSessionLocked([&, this]() -> Error {
880 if (MR.RT->isDefunct())
881 return make_error<ResourceTrackerDefunct>(MR.RT);
882
883 if (State != Open)
884 return make_error<StringError>("JITDylib " + getName() +
885 " is defunct",
886 inconvertibleErrorCode());
887
888 struct WorklistEntry {
889 SymbolTable::iterator SymI;
890 ExecutorSymbolDef ResolvedSym;
891 };
892
893 SymbolNameSet SymbolsInErrorState;
894 std::vector<WorklistEntry> Worklist;
895 Worklist.reserve(Resolved.size());
896
897 // Build worklist and check for any symbols in the error state.
898 for (const auto &KV : Resolved) {
899
900 assert(!KV.second.getFlags().hasError() &&
901 "Resolution result can not have error flag set");
902
903 auto SymI = Symbols.find(KV.first);
904
905 assert(SymI != Symbols.end() && "Symbol not found");
906 assert(!SymI->second.hasMaterializerAttached() &&
907 "Resolving symbol with materializer attached?");
908 assert(SymI->second.getState() == SymbolState::Materializing &&
909 "Symbol should be materializing");
910 assert(SymI->second.getAddress() == ExecutorAddr() &&
911 "Symbol has already been resolved");
912
913 if (SymI->second.getFlags().hasError())
914 SymbolsInErrorState.insert(KV.first);
915 else {
916 if (SymI->second.getFlags() & JITSymbolFlags::Common) {
917 [[maybe_unused]] auto WeakOrCommon =
918 JITSymbolFlags::Weak | JITSymbolFlags::Common;
919 assert((KV.second.getFlags() & WeakOrCommon) &&
920 "Common symbols must be resolved as common or weak");
921 assert((KV.second.getFlags() & ~WeakOrCommon) ==
922 (SymI->second.getFlags() & ~JITSymbolFlags::Common) &&
923 "Resolving symbol with incorrect flags");
924
925 } else
926 assert(KV.second.getFlags() == SymI->second.getFlags() &&
927 "Resolved flags should match the declared flags");
928
929 Worklist.push_back(
930 {SymI, {KV.second.getAddress(), SymI->second.getFlags()}});
931 }
932 }
933
934 // If any symbols were in the error state then bail out.
935 if (!SymbolsInErrorState.empty()) {
936 auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
937 (*FailedSymbolsDepMap)[this] = std::move(SymbolsInErrorState);
938 return make_error<FailedToMaterialize>(
939 getExecutionSession().getSymbolStringPool(),
940 std::move(FailedSymbolsDepMap));
941 }
942
943 while (!Worklist.empty()) {
944 auto SymI = Worklist.back().SymI;
945 auto ResolvedSym = Worklist.back().ResolvedSym;
946 Worklist.pop_back();
947
948 auto &Name = SymI->first;
949
950 // Resolved symbols can not be weak: discard the weak flag.
951 JITSymbolFlags ResolvedFlags = ResolvedSym.getFlags();
952 SymI->second.setAddress(ResolvedSym.getAddress());
953 SymI->second.setFlags(ResolvedFlags);
954 SymI->second.setState(SymbolState::Resolved);
955
956 auto MII = MaterializingInfos.find(Name);
957 if (MII == MaterializingInfos.end())
958 continue;
959
960 auto &MI = MII->second;
961 for (auto &Q : MI.takeQueriesMeeting(SymbolState::Resolved)) {
962 Q->notifySymbolMetRequiredState(Name, ResolvedSym);
963 if (Q->isComplete())
964 CompletedQueries.insert(std::move(Q));
965 }
966 }
967
968 return Error::success();
969 }))
970 return Err;
971
972 // Otherwise notify all the completed queries.
973 for (auto &Q : CompletedQueries) {
974 assert(Q->isComplete() && "Q not completed");
975 Q->handleComplete(ES);
976 }
977
978 return Error::success();
979}
980
981void JITDylib::unlinkMaterializationResponsibility(
982 MaterializationResponsibility &MR) {
983 ES.runSessionLocked([&]() {
984 auto I = TrackerMRs.find(MR.RT.get());
985 assert(I != TrackerMRs.end() && "No MRs in TrackerMRs list for RT");
986 assert(I->second.count(&MR) && "MR not in TrackerMRs list for RT");
987 I->second.erase(&MR);
988 if (I->second.empty())
989 TrackerMRs.erase(MR.RT.get());
990 });
991}
992
993void JITDylib::shrinkMaterializationInfoMemory() {
994 // DenseMap::erase never shrinks its storage; use clear to heuristically free
995 // memory since we may have long-lived JDs after linking is done.
996
997 if (UnmaterializedInfos.empty())
998 UnmaterializedInfos.clear();
999
1000 if (MaterializingInfos.empty())
1001 MaterializingInfos.clear();
1002}
1003
1004void JITDylib::setLinkOrder(JITDylibSearchOrder NewLinkOrder,
1005 bool LinkAgainstThisJITDylibFirst) {
1006 ES.runSessionLocked([&]() {
1007 assert(State == Open && "JD is defunct");
1008 if (LinkAgainstThisJITDylibFirst) {
1009 LinkOrder.clear();
1010 if (NewLinkOrder.empty() || NewLinkOrder.front().first != this)
1011 LinkOrder.push_back(
1012 std::make_pair(this, JITDylibLookupFlags::MatchAllSymbols));
1013 llvm::append_range(LinkOrder, NewLinkOrder);
1014 } else
1015 LinkOrder = std::move(NewLinkOrder);
1016 });
1017}
1018
1019void JITDylib::addToLinkOrder(const JITDylibSearchOrder &NewLinks) {
1020 ES.runSessionLocked([&]() {
1021 for (auto &KV : NewLinks) {
1022 // Skip elements of NewLinks that are already in the link order.
1023 if (llvm::is_contained(LinkOrder, KV))
1024 continue;
1025
1026 LinkOrder.push_back(std::move(KV));
1027 }
1028 });
1029}
1030
1031void JITDylib::addToLinkOrder(JITDylib &JD, JITDylibLookupFlags JDLookupFlags) {
1032 ES.runSessionLocked([&]() { LinkOrder.push_back({&JD, JDLookupFlags}); });
1033}
1034
1035void JITDylib::replaceInLinkOrder(JITDylib &OldJD, JITDylib &NewJD,
1036 JITDylibLookupFlags JDLookupFlags) {
1037 ES.runSessionLocked([&]() {
1038 assert(State == Open && "JD is defunct");
1039 for (auto &KV : LinkOrder)
1040 if (KV.first == &OldJD) {
1041 KV = {&NewJD, JDLookupFlags};
1042 break;
1043 }
1044 });
1045}
1046
1047void JITDylib::removeFromLinkOrder(JITDylib &JD) {
1048 ES.runSessionLocked([&]() {
1049 assert(State == Open && "JD is defunct");
1050 auto I = llvm::find_if(LinkOrder,
1051 [&](const JITDylibSearchOrder::value_type &KV) {
1052 return KV.first == &JD;
1053 });
1054 if (I != LinkOrder.end())
1055 LinkOrder.erase(I);
1056 });
1057}
1058
1059Error JITDylib::remove(const SymbolNameSet &Names) {
1060 return ES.runSessionLocked([&]() -> Error {
1061 assert(State == Open && "JD is defunct");
1062 using SymbolMaterializerItrPair =
1063 std::pair<SymbolTable::iterator, UnmaterializedInfosMap::iterator>;
1064 std::vector<SymbolMaterializerItrPair> SymbolsToRemove;
1065 SymbolNameSet Missing;
1067
1068 for (auto &Name : Names) {
1069 auto I = Symbols.find(Name);
1070
1071 // Note symbol missing.
1072 if (I == Symbols.end()) {
1073 Missing.insert(Name);
1074 continue;
1075 }
1076
1077 // Note symbol materializing.
1078 if (I->second.getState() != SymbolState::NeverSearched &&
1079 I->second.getState() != SymbolState::Ready) {
1080 Materializing.insert(Name);
1081 continue;
1082 }
1083
1084 auto UMII = I->second.hasMaterializerAttached()
1085 ? UnmaterializedInfos.find(Name)
1086 : UnmaterializedInfos.end();
1087 SymbolsToRemove.push_back(std::make_pair(I, UMII));
1088 }
1089
1090 // If any of the symbols are not defined, return an error.
1091 if (!Missing.empty())
1092 return make_error<SymbolsNotFound>(ES.getSymbolStringPool(),
1093 std::move(Missing));
1094
1095 // If any of the symbols are currently materializing, return an error.
1096 if (!Materializing.empty())
1097 return make_error<SymbolsCouldNotBeRemoved>(ES.getSymbolStringPool(),
1098 std::move(Materializing));
1099
1100 // Remove the symbols.
1101 for (auto &SymbolMaterializerItrPair : SymbolsToRemove) {
1102 auto UMII = SymbolMaterializerItrPair.second;
1103
1104 // If there is a materializer attached, call discard.
1105 if (UMII != UnmaterializedInfos.end()) {
1106 UMII->second->MU->doDiscard(*this, UMII->first);
1107 UnmaterializedInfos.erase(UMII);
1108 }
1109
1110 auto SymI = SymbolMaterializerItrPair.first;
1111 Symbols.erase(SymI);
1112 }
1113
1114 shrinkMaterializationInfoMemory();
1115
1116 return Error::success();
1117 });
1118}
1119
1120void JITDylib::dump(raw_ostream &OS) {
1121 ES.runSessionLocked([&, this]() {
1122 OS << "JITDylib \"" << getName() << "\" (ES: "
1123 << format("0x%016" PRIx64, reinterpret_cast<uintptr_t>(&ES))
1124 << ", State = ";
1125 switch (State) {
1126 case Open:
1127 OS << "Open";
1128 break;
1129 case Closing:
1130 OS << "Closing";
1131 break;
1132 case Closed:
1133 OS << "Closed";
1134 break;
1135 }
1136 OS << ")\n";
1137 if (State == Closed)
1138 return;
1139 OS << "Link order: " << LinkOrder << "\n"
1140 << "Symbol table:\n";
1141
1142 // Sort symbols so we get a deterministic order and can check them in tests.
1143 std::vector<std::pair<SymbolStringPtr, SymbolTableEntry *>> SymbolsSorted;
1144 for (auto &KV : Symbols)
1145 SymbolsSorted.emplace_back(KV.first, &KV.second);
1146 std::sort(SymbolsSorted.begin(), SymbolsSorted.end(),
1147 [](const auto &L, const auto &R) { return *L.first < *R.first; });
1148
1149 for (auto &KV : SymbolsSorted) {
1150 OS << " \"" << *KV.first << "\": ";
1151 if (auto Addr = KV.second->getAddress())
1152 OS << Addr;
1153 else
1154 OS << "<not resolved> ";
1155
1156 OS << " " << KV.second->getFlags() << " " << KV.second->getState();
1157
1158 if (KV.second->hasMaterializerAttached()) {
1159 OS << " (Materializer ";
1160 auto I = UnmaterializedInfos.find(KV.first);
1161 assert(I != UnmaterializedInfos.end() &&
1162 "Lazy symbol should have UnmaterializedInfo");
1163 OS << I->second->MU.get() << ", " << I->second->MU->getName() << ")\n";
1164 } else
1165 OS << "\n";
1166 }
1167
1168 if (!MaterializingInfos.empty())
1169 OS << " MaterializingInfos entries:\n";
1170 for (auto &KV : MaterializingInfos) {
1171 OS << " \"" << *KV.first << "\":\n"
1172 << " " << KV.second.pendingQueries().size()
1173 << " pending queries: { ";
1174 for (const auto &Q : KV.second.pendingQueries())
1175 OS << Q.get() << " (" << Q->getRequiredState() << ") ";
1176 OS << "}\n Defining EDU: ";
1177 if (KV.second.DefiningEDU) {
1178 OS << KV.second.DefiningEDU.get() << " { ";
1179 for (auto &[Name, Flags] : KV.second.DefiningEDU->Symbols)
1180 OS << Name << " ";
1181 OS << "}\n";
1182 OS << " Dependencies:\n";
1183 if (!KV.second.DefiningEDU->Dependencies.empty()) {
1184 for (auto &[DepJD, Deps] : KV.second.DefiningEDU->Dependencies) {
1185 OS << " " << DepJD->getName() << ": [ ";
1186 for (auto &Dep : Deps)
1187 OS << Dep << " ";
1188 OS << "]\n";
1189 }
1190 } else
1191 OS << " none\n";
1192 } else
1193 OS << "none\n";
1194 OS << " Dependant EDUs:\n";
1195 if (!KV.second.DependantEDUs.empty()) {
1196 for (auto &DependantEDU : KV.second.DependantEDUs) {
1197 OS << " " << DependantEDU << ": "
1198 << DependantEDU->JD->getName() << " { ";
1199 for (auto &[Name, Flags] : DependantEDU->Symbols)
1200 OS << Name << " ";
1201 OS << "}\n";
1202 }
1203 } else
1204 OS << " none\n";
1205 assert((Symbols[KV.first].getState() != SymbolState::Ready ||
1206 (KV.second.pendingQueries().empty() && !KV.second.DefiningEDU &&
1207 !KV.second.DependantEDUs.empty())) &&
1208 "Stale materializing info entry");
1209 }
1210 });
1211}
1212
1213void JITDylib::MaterializingInfo::addQuery(
1214 std::shared_ptr<AsynchronousSymbolQuery> Q) {
1215
1216 auto I = llvm::lower_bound(
1217 llvm::reverse(PendingQueries), Q->getRequiredState(),
1218 [](const std::shared_ptr<AsynchronousSymbolQuery> &V, SymbolState S) {
1219 return V->getRequiredState() <= S;
1220 });
1221 PendingQueries.insert(I.base(), std::move(Q));
1222}
1223
1224void JITDylib::MaterializingInfo::removeQuery(
1225 const AsynchronousSymbolQuery &Q) {
1226 // FIXME: Implement 'find_as' for shared_ptr<T>/T*.
1227 auto I = llvm::find_if(
1228 PendingQueries, [&Q](const std::shared_ptr<AsynchronousSymbolQuery> &V) {
1229 return V.get() == &Q;
1230 });
1231 if (I != PendingQueries.end())
1232 PendingQueries.erase(I);
1233}
1234
1235JITDylib::AsynchronousSymbolQueryList
1236JITDylib::MaterializingInfo::takeQueriesMeeting(SymbolState RequiredState) {
1237 AsynchronousSymbolQueryList Result;
1238 while (!PendingQueries.empty()) {
1239 if (PendingQueries.back()->getRequiredState() > RequiredState)
1240 break;
1241
1242 Result.push_back(std::move(PendingQueries.back()));
1243 PendingQueries.pop_back();
1244 }
1245
1246 return Result;
1247}
1248
1249JITDylib::JITDylib(ExecutionSession &ES, std::string Name)
1250 : JITLinkDylib(std::move(Name)), ES(ES) {
1251 LinkOrder.push_back({this, JITDylibLookupFlags::MatchAllSymbols});
1252}
1253
1254std::pair<JITDylib::AsynchronousSymbolQuerySet,
1255 std::shared_ptr<SymbolDependenceMap>>
1256JITDylib::IL_removeTracker(ResourceTracker &RT) {
1257 // Note: Should be called under the session lock.
1258 assert(State != Closed && "JD is defunct");
1259
1260 SymbolNameVector SymbolsToRemove;
1261 SymbolNameVector SymbolsToFail;
1262
1263 if (&RT == DefaultTracker.get()) {
1264 SymbolNameSet TrackedSymbols;
1265 for (auto &KV : TrackerSymbols)
1266 for (auto &Sym : KV.second)
1267 TrackedSymbols.insert(Sym);
1268
1269 for (auto &KV : Symbols) {
1270 auto &Sym = KV.first;
1271 if (!TrackedSymbols.count(Sym))
1272 SymbolsToRemove.push_back(Sym);
1273 }
1274
1275 DefaultTracker.reset();
1276 } else {
1277 /// Check for a non-default tracker.
1278 auto I = TrackerSymbols.find(&RT);
1279 if (I != TrackerSymbols.end()) {
1280 SymbolsToRemove = std::move(I->second);
1281 TrackerSymbols.erase(I);
1282 }
1283 // ... if not found this tracker was already defunct. Nothing to do.
1284 }
1285
1286 for (auto &Sym : SymbolsToRemove) {
1287 assert(Symbols.count(Sym) && "Symbol not in symbol table");
1288
1289 // If there is a MaterializingInfo then collect any queries to fail.
1290 auto MII = MaterializingInfos.find(Sym);
1291 if (MII != MaterializingInfos.end())
1292 SymbolsToFail.push_back(Sym);
1293 }
1294
1295 auto Result = ES.IL_failSymbols(*this, std::move(SymbolsToFail));
1296
1297 // Removed symbols should be taken out of the table altogether.
1298 for (auto &Sym : SymbolsToRemove) {
1299 auto I = Symbols.find(Sym);
1300 assert(I != Symbols.end() && "Symbol not present in table");
1301
1302 // Remove Materializer if present.
1303 if (I->second.hasMaterializerAttached()) {
1304 // FIXME: Should this discard the symbols?
1305 UnmaterializedInfos.erase(Sym);
1306 } else {
1307 assert(!UnmaterializedInfos.count(Sym) &&
1308 "Symbol has materializer attached");
1309 }
1310
1311 Symbols.erase(I);
1312 }
1313
1314 shrinkMaterializationInfoMemory();
1315
1316 return Result;
1317}
1318
1319void JITDylib::transferTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT) {
1320 assert(State != Closed && "JD is defunct");
1321 assert(&DstRT != &SrcRT && "No-op transfers shouldn't call transferTracker");
1322 assert(&DstRT.getJITDylib() == this && "DstRT is not for this JITDylib");
1323 assert(&SrcRT.getJITDylib() == this && "SrcRT is not for this JITDylib");
1324
1325 // Update trackers for any not-yet materialized units.
1326 for (auto &KV : UnmaterializedInfos) {
1327 if (KV.second->RT == &SrcRT)
1328 KV.second->RT = &DstRT;
1329 }
1330
1331 // Update trackers for any active materialization responsibilities.
1332 {
1333 auto I = TrackerMRs.find(&SrcRT);
1334 if (I != TrackerMRs.end()) {
1335 auto &SrcMRs = I->second;
1336 auto &DstMRs = TrackerMRs[&DstRT];
1337 for (auto *MR : SrcMRs)
1338 MR->RT = &DstRT;
1339 if (DstMRs.empty())
1340 DstMRs = std::move(SrcMRs);
1341 else
1342 for (auto *MR : SrcMRs)
1343 DstMRs.insert(MR);
1344 // Erase SrcRT entry in TrackerMRs. Use &SrcRT key rather than iterator I
1345 // for this, since I may have been invalidated by 'TrackerMRs[&DstRT]'.
1346 TrackerMRs.erase(&SrcRT);
1347 }
1348 }
1349
1350 // If we're transfering to the default tracker we just need to delete the
1351 // tracked symbols for the source tracker.
1352 if (&DstRT == DefaultTracker.get()) {
1353 TrackerSymbols.erase(&SrcRT);
1354 return;
1355 }
1356
1357 // If we're transferring from the default tracker we need to find all
1358 // currently untracked symbols.
1359 if (&SrcRT == DefaultTracker.get()) {
1360 assert(!TrackerSymbols.count(&SrcRT) &&
1361 "Default tracker should not appear in TrackerSymbols");
1362
1363 SymbolNameVector SymbolsToTrack;
1364
1365 SymbolNameSet CurrentlyTrackedSymbols;
1366 for (auto &KV : TrackerSymbols)
1367 for (auto &Sym : KV.second)
1368 CurrentlyTrackedSymbols.insert(Sym);
1369
1370 for (auto &KV : Symbols) {
1371 auto &Sym = KV.first;
1372 if (!CurrentlyTrackedSymbols.count(Sym))
1373 SymbolsToTrack.push_back(Sym);
1374 }
1375
1376 TrackerSymbols[&DstRT] = std::move(SymbolsToTrack);
1377 return;
1378 }
1379
1380 auto &DstTrackedSymbols = TrackerSymbols[&DstRT];
1381
1382 // Finally if neither SrtRT or DstRT are the default tracker then
1383 // just append DstRT's tracked symbols to SrtRT's.
1384 auto SI = TrackerSymbols.find(&SrcRT);
1385 if (SI == TrackerSymbols.end())
1386 return;
1387
1388 DstTrackedSymbols.reserve(DstTrackedSymbols.size() + SI->second.size());
1389 for (auto &Sym : SI->second)
1390 DstTrackedSymbols.push_back(std::move(Sym));
1391 TrackerSymbols.erase(SI);
1392}
1393
1394Error JITDylib::defineImpl(MaterializationUnit &MU) {
1395 LLVM_DEBUG({ dbgs() << " " << MU.getSymbols() << "\n"; });
1396
1397 SymbolNameSet Duplicates;
1398 std::vector<SymbolStringPtr> ExistingDefsOverridden;
1399 std::vector<SymbolStringPtr> MUDefsOverridden;
1400
1401 for (const auto &KV : MU.getSymbols()) {
1402 auto I = Symbols.find(KV.first);
1403
1404 if (I != Symbols.end()) {
1405 if (KV.second.isStrong()) {
1406 if (I->second.getFlags().isStrong() ||
1407 I->second.getState() > SymbolState::NeverSearched)
1408 Duplicates.insert(KV.first);
1409 else {
1410 assert(I->second.getState() == SymbolState::NeverSearched &&
1411 "Overridden existing def should be in the never-searched "
1412 "state");
1413 ExistingDefsOverridden.push_back(KV.first);
1414 }
1415 } else
1416 MUDefsOverridden.push_back(KV.first);
1417 }
1418 }
1419
1420 // If there were any duplicate definitions then bail out.
1421 if (!Duplicates.empty()) {
1422 LLVM_DEBUG(
1423 { dbgs() << " Error: Duplicate symbols " << Duplicates << "\n"; });
1424 return make_error<DuplicateDefinition>(std::string(**Duplicates.begin()));
1425 }
1426
1427 // Discard any overridden defs in this MU.
1428 LLVM_DEBUG({
1429 if (!MUDefsOverridden.empty())
1430 dbgs() << " Defs in this MU overridden: " << MUDefsOverridden << "\n";
1431 });
1432 for (auto &S : MUDefsOverridden)
1433 MU.doDiscard(*this, S);
1434
1435 // Discard existing overridden defs.
1436 LLVM_DEBUG({
1437 if (!ExistingDefsOverridden.empty())
1438 dbgs() << " Existing defs overridden by this MU: " << MUDefsOverridden
1439 << "\n";
1440 });
1441 for (auto &S : ExistingDefsOverridden) {
1442
1443 auto UMII = UnmaterializedInfos.find(S);
1444 assert(UMII != UnmaterializedInfos.end() &&
1445 "Overridden existing def should have an UnmaterializedInfo");
1446 UMII->second->MU->doDiscard(*this, S);
1447 }
1448
1449 // Finally, add the defs from this MU.
1450 for (auto &KV : MU.getSymbols()) {
1451 auto &SymEntry = Symbols[KV.first];
1452 SymEntry.setFlags(KV.second);
1453 SymEntry.setState(SymbolState::NeverSearched);
1454 SymEntry.setMaterializerAttached(true);
1455 }
1456
1457 return Error::success();
1458}
1459
1460void JITDylib::installMaterializationUnit(
1461 std::unique_ptr<MaterializationUnit> MU, ResourceTracker &RT) {
1462
1463 /// defineImpl succeeded.
1464 if (&RT != DefaultTracker.get()) {
1465 auto &TS = TrackerSymbols[&RT];
1466 TS.reserve(TS.size() + MU->getSymbols().size());
1467 for (auto &KV : MU->getSymbols())
1468 TS.push_back(KV.first);
1469 }
1470
1471 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU), &RT);
1472 for (auto &KV : UMI->MU->getSymbols())
1473 UnmaterializedInfos[KV.first] = UMI;
1474}
1475
1476void JITDylib::detachQueryHelper(AsynchronousSymbolQuery &Q,
1477 const SymbolNameSet &QuerySymbols) {
1478 for (auto &QuerySymbol : QuerySymbols) {
1479 auto MII = MaterializingInfos.find(QuerySymbol);
1480 if (MII != MaterializingInfos.end())
1481 MII->second.removeQuery(Q);
1482 }
1483}
1484
1485Platform::~Platform() = default;
1486
1488 ExecutionSession &ES,
1489 const DenseMap<JITDylib *, SymbolLookupSet> &InitSyms) {
1490
1491 DenseMap<JITDylib *, SymbolMap> CompoundResult;
1492 Error CompoundErr = Error::success();
1493 std::mutex LookupMutex;
1494 std::condition_variable CV;
1495 uint64_t Count = InitSyms.size();
1496
1497 LLVM_DEBUG({
1498 dbgs() << "Issuing init-symbol lookup:\n";
1499 for (auto &KV : InitSyms)
1500 dbgs() << " " << KV.first->getName() << ": " << KV.second << "\n";
1501 });
1502
1503 for (auto &KV : InitSyms) {
1504 auto *JD = KV.first;
1505 auto Names = std::move(KV.second);
1506 ES.lookup(
1509 std::move(Names), SymbolState::Ready,
1510 [&, JD](Expected<SymbolMap> Result) {
1511 {
1512 std::lock_guard<std::mutex> Lock(LookupMutex);
1513 --Count;
1514 if (Result) {
1515 assert(!CompoundResult.count(JD) &&
1516 "Duplicate JITDylib in lookup?");
1517 CompoundResult[JD] = std::move(*Result);
1518 } else
1519 CompoundErr =
1520 joinErrors(std::move(CompoundErr), Result.takeError());
1521 }
1522 CV.notify_one();
1523 },
1525 }
1526
1527 std::unique_lock<std::mutex> Lock(LookupMutex);
1528 CV.wait(Lock, [&] { return Count == 0 || CompoundErr; });
1529
1530 if (CompoundErr)
1531 return std::move(CompoundErr);
1532
1533 return std::move(CompoundResult);
1534}
1535
1537 unique_function<void(Error)> OnComplete, ExecutionSession &ES,
1538 const DenseMap<JITDylib *, SymbolLookupSet> &InitSyms) {
1539
1540 class TriggerOnComplete {
1541 public:
1542 using OnCompleteFn = unique_function<void(Error)>;
1543 TriggerOnComplete(OnCompleteFn OnComplete)
1544 : OnComplete(std::move(OnComplete)) {}
1545 ~TriggerOnComplete() { OnComplete(std::move(LookupResult)); }
1546 void reportResult(Error Err) {
1547 std::lock_guard<std::mutex> Lock(ResultMutex);
1548 LookupResult = joinErrors(std::move(LookupResult), std::move(Err));
1549 }
1550
1551 private:
1552 std::mutex ResultMutex;
1553 Error LookupResult{Error::success()};
1554 OnCompleteFn OnComplete;
1555 };
1556
1557 LLVM_DEBUG({
1558 dbgs() << "Issuing init-symbol lookup:\n";
1559 for (auto &KV : InitSyms)
1560 dbgs() << " " << KV.first->getName() << ": " << KV.second << "\n";
1561 });
1562
1563 auto TOC = std::make_shared<TriggerOnComplete>(std::move(OnComplete));
1564
1565 for (auto &KV : InitSyms) {
1566 auto *JD = KV.first;
1567 auto Names = std::move(KV.second);
1568 ES.lookup(
1571 std::move(Names), SymbolState::Ready,
1573 TOC->reportResult(Result.takeError());
1574 },
1576 }
1577}
1578
1580 OS << "Materialization task: " << MU->getName() << " in "
1581 << MR->getTargetJITDylib().getName();
1582}
1583
1584void MaterializationTask::run() { MU->materialize(std::move(MR)); }
1585
1586void LookupTask::printDescription(raw_ostream &OS) { OS << "Lookup task"; }
1587
1589
1590ExecutionSession::ExecutionSession(std::unique_ptr<ExecutorProcessControl> EPC)
1591 : EPC(std::move(EPC)) {
1592 // Associated EPC and this.
1593 this->EPC->ES = this;
1594}
1595
1597 // You must call endSession prior to destroying the session.
1598 assert(!SessionOpen &&
1599 "Session still open. Did you forget to call endSession?");
1600}
1601
1603 LLVM_DEBUG(dbgs() << "Ending ExecutionSession " << this << "\n");
1604
1605 auto JDsToRemove = runSessionLocked([&] {
1606
1607#ifdef EXPENSIVE_CHECKS
1608 verifySessionState("Entering ExecutionSession::endSession");
1609#endif
1610
1611 SessionOpen = false;
1612 return JDs;
1613 });
1614
1615 std::reverse(JDsToRemove.begin(), JDsToRemove.end());
1616
1617 auto Err = removeJITDylibs(std::move(JDsToRemove));
1618
1619 Err = joinErrors(std::move(Err), EPC->disconnect());
1620
1621 return Err;
1622}
1623
1625 runSessionLocked([&] { ResourceManagers.push_back(&RM); });
1626}
1627
1629 runSessionLocked([&] {
1630 assert(!ResourceManagers.empty() && "No managers registered");
1631 if (ResourceManagers.back() == &RM)
1632 ResourceManagers.pop_back();
1633 else {
1634 auto I = llvm::find(ResourceManagers, &RM);
1635 assert(I != ResourceManagers.end() && "RM not registered");
1636 ResourceManagers.erase(I);
1637 }
1638 });
1639}
1640
1642 return runSessionLocked([&, this]() -> JITDylib * {
1643 for (auto &JD : JDs)
1644 if (JD->getName() == Name)
1645 return JD.get();
1646 return nullptr;
1647 });
1648}
1649
1651 assert(!getJITDylibByName(Name) && "JITDylib with that name already exists");
1652 return runSessionLocked([&, this]() -> JITDylib & {
1653 assert(SessionOpen && "Cannot create JITDylib after session is closed");
1654 JDs.push_back(new JITDylib(*this, std::move(Name)));
1655 return *JDs.back();
1656 });
1657}
1658
1660 auto &JD = createBareJITDylib(Name);
1661 if (P)
1662 if (auto Err = P->setupJITDylib(JD))
1663 return std::move(Err);
1664 return JD;
1665}
1666
1667Error ExecutionSession::removeJITDylibs(std::vector<JITDylibSP> JDsToRemove) {
1668 // Set JD to 'Closing' state and remove JD from the ExecutionSession.
1669 runSessionLocked([&] {
1670 for (auto &JD : JDsToRemove) {
1671 assert(JD->State == JITDylib::Open && "JD already closed");
1672 JD->State = JITDylib::Closing;
1673 auto I = llvm::find(JDs, JD);
1674 assert(I != JDs.end() && "JD does not appear in session JDs");
1675 JDs.erase(I);
1676 }
1677 });
1678
1679 // Clear JITDylibs and notify the platform.
1680 Error Err = Error::success();
1681 for (auto JD : JDsToRemove) {
1682 Err = joinErrors(std::move(Err), JD->clear());
1683 if (P)
1684 Err = joinErrors(std::move(Err), P->teardownJITDylib(*JD));
1685 }
1686
1687 // Set JD to closed state. Clear remaining data structures.
1688 runSessionLocked([&] {
1689 for (auto &JD : JDsToRemove) {
1690 assert(JD->State == JITDylib::Closing && "JD should be closing");
1691 JD->State = JITDylib::Closed;
1692 assert(JD->Symbols.empty() && "JD.Symbols is not empty after clear");
1693 assert(JD->UnmaterializedInfos.empty() &&
1694 "JD.UnmaterializedInfos is not empty after clear");
1695 assert(JD->MaterializingInfos.empty() &&
1696 "JD.MaterializingInfos is not empty after clear");
1697 assert(JD->TrackerSymbols.empty() &&
1698 "TrackerSymbols is not empty after clear");
1699 JD->DefGenerators.clear();
1700 JD->LinkOrder.clear();
1701 }
1702 });
1703
1704 return Err;
1705}
1706
1709 if (JDs.empty())
1710 return std::vector<JITDylibSP>();
1711
1712 auto &ES = JDs.front()->getExecutionSession();
1713 return ES.runSessionLocked([&]() -> Expected<std::vector<JITDylibSP>> {
1714 DenseSet<JITDylib *> Visited;
1715 std::vector<JITDylibSP> Result;
1716
1717 for (auto &JD : JDs) {
1718
1719 if (JD->State != Open)
1720 return make_error<StringError>(
1721 "Error building link order: " + JD->getName() + " is defunct",
1723 if (Visited.count(JD.get()))
1724 continue;
1725
1727 WorkStack.push_back(JD);
1728 Visited.insert(JD.get());
1729
1730 while (!WorkStack.empty()) {
1731 Result.push_back(std::move(WorkStack.back()));
1732 WorkStack.pop_back();
1733
1734 for (auto &KV : llvm::reverse(Result.back()->LinkOrder)) {
1735 auto &JD = *KV.first;
1736 if (!Visited.insert(&JD).second)
1737 continue;
1738 WorkStack.push_back(&JD);
1739 }
1740 }
1741 }
1742 return Result;
1743 });
1744}
1745
1748 auto Result = getDFSLinkOrder(JDs);
1749 if (Result)
1750 std::reverse(Result->begin(), Result->end());
1751 return Result;
1752}
1753
1755 return getDFSLinkOrder({this});
1756}
1757
1759 return getReverseDFSLinkOrder({this});
1760}
1761
1763 LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet,
1764 unique_function<void(Expected<SymbolFlagsMap>)> OnComplete) {
1765
1766 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
1767 K, std::move(SearchOrder), std::move(LookupSet),
1768 std::move(OnComplete)),
1769 Error::success());
1770}
1771
1774 SymbolLookupSet LookupSet) {
1775
1776 std::promise<MSVCPExpected<SymbolFlagsMap>> ResultP;
1777 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
1778 K, std::move(SearchOrder), std::move(LookupSet),
1779 [&ResultP](Expected<SymbolFlagsMap> Result) {
1780 ResultP.set_value(std::move(Result));
1781 }),
1782 Error::success());
1783
1784 auto ResultF = ResultP.get_future();
1785 return ResultF.get();
1786}
1787
1789 LookupKind K, const JITDylibSearchOrder &SearchOrder,
1790 SymbolLookupSet Symbols, SymbolState RequiredState,
1791 SymbolsResolvedCallback NotifyComplete,
1792 RegisterDependenciesFunction RegisterDependencies) {
1793
1794 LLVM_DEBUG({
1795 runSessionLocked([&]() {
1796 dbgs() << "Looking up " << Symbols << " in " << SearchOrder
1797 << " (required state: " << RequiredState << ")\n";
1798 });
1799 });
1800
1801 // lookup can be re-entered recursively if running on a single thread. Run any
1802 // outstanding MUs in case this query depends on them, otherwise this lookup
1803 // will starve waiting for a result from an MU that is stuck in the queue.
1804 dispatchOutstandingMUs();
1805
1806 auto Unresolved = std::move(Symbols);
1807 auto Q = std::make_shared<AsynchronousSymbolQuery>(Unresolved, RequiredState,
1808 std::move(NotifyComplete));
1809
1810 auto IPLS = std::make_unique<InProgressFullLookupState>(
1811 K, SearchOrder, std::move(Unresolved), RequiredState, std::move(Q),
1812 std::move(RegisterDependencies));
1813
1814 OL_applyQueryPhase1(std::move(IPLS), Error::success());
1815}
1816
1819 SymbolLookupSet Symbols, LookupKind K,
1820 SymbolState RequiredState,
1821 RegisterDependenciesFunction RegisterDependencies) {
1822#if LLVM_ENABLE_THREADS
1823 // In the threaded case we use promises to return the results.
1824 std::promise<SymbolMap> PromisedResult;
1825 Error ResolutionError = Error::success();
1826
1827 auto NotifyComplete = [&](Expected<SymbolMap> R) {
1828 if (R)
1829 PromisedResult.set_value(std::move(*R));
1830 else {
1831 ErrorAsOutParameter _(ResolutionError);
1832 ResolutionError = R.takeError();
1833 PromisedResult.set_value(SymbolMap());
1834 }
1835 };
1836
1837#else
1839 Error ResolutionError = Error::success();
1840
1841 auto NotifyComplete = [&](Expected<SymbolMap> R) {
1842 ErrorAsOutParameter _(ResolutionError);
1843 if (R)
1844 Result = std::move(*R);
1845 else
1846 ResolutionError = R.takeError();
1847 };
1848#endif
1849
1850 // Perform the asynchronous lookup.
1851 lookup(K, SearchOrder, std::move(Symbols), RequiredState, NotifyComplete,
1852 RegisterDependencies);
1853
1854#if LLVM_ENABLE_THREADS
1855 auto ResultFuture = PromisedResult.get_future();
1856 auto Result = ResultFuture.get();
1857
1858 if (ResolutionError)
1859 return std::move(ResolutionError);
1860
1861 return std::move(Result);
1862
1863#else
1864 if (ResolutionError)
1865 return std::move(ResolutionError);
1866
1867 return Result;
1868#endif
1869}
1870
1873 SymbolStringPtr Name, SymbolState RequiredState) {
1874 SymbolLookupSet Names({Name});
1875
1876 if (auto ResultMap = lookup(SearchOrder, std::move(Names), LookupKind::Static,
1877 RequiredState, NoDependenciesToRegister)) {
1878 assert(ResultMap->size() == 1 && "Unexpected number of results");
1879 assert(ResultMap->count(Name) && "Missing result for symbol");
1880 return std::move(ResultMap->begin()->second);
1881 } else
1882 return ResultMap.takeError();
1883}
1884
1887 SymbolState RequiredState) {
1888 return lookup(makeJITDylibSearchOrder(SearchOrder), Name, RequiredState);
1889}
1890
1893 SymbolState RequiredState) {
1894 return lookup(SearchOrder, intern(Name), RequiredState);
1895}
1896
1899
1900 auto TagSyms = lookup({{&JD, JITDylibLookupFlags::MatchAllSymbols}},
1903 if (!TagSyms)
1904 return TagSyms.takeError();
1905
1906 // Associate tag addresses with implementations.
1907 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
1908
1909 // Check that no tags are being overwritten.
1910 for (auto &[TagName, TagSym] : *TagSyms) {
1911 auto TagAddr = TagSym.getAddress();
1912 if (JITDispatchHandlers.count(TagAddr))
1913 return make_error<StringError>("Tag " + formatv("{0:x}", TagAddr) +
1914 " (for " + *TagName +
1915 ") already registered",
1917 }
1918
1919 // At this point we're guaranteed to succeed. Install the handlers.
1920 for (auto &[TagName, TagSym] : *TagSyms) {
1921 auto TagAddr = TagSym.getAddress();
1922 auto I = WFs.find(TagName);
1923 assert(I != WFs.end() && I->second &&
1924 "JITDispatchHandler implementation missing");
1925 JITDispatchHandlers[TagAddr] =
1926 std::make_shared<JITDispatchHandlerFunction>(std::move(I->second));
1927 LLVM_DEBUG({
1928 dbgs() << "Associated function tag \"" << *TagName << "\" ("
1929 << formatv("{0:x}", TagAddr) << ") with handler\n";
1930 });
1931 }
1932
1933 return Error::success();
1934}
1935
1937 ExecutorAddr HandlerFnTagAddr,
1938 ArrayRef<char> ArgBuffer) {
1939
1940 std::shared_ptr<JITDispatchHandlerFunction> F;
1941 {
1942 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
1943 auto I = JITDispatchHandlers.find(HandlerFnTagAddr);
1944 if (I != JITDispatchHandlers.end())
1945 F = I->second;
1946 }
1947
1948 if (F)
1949 (*F)(std::move(SendResult), ArgBuffer.data(), ArgBuffer.size());
1950 else
1952 ("No function registered for tag " +
1953 formatv("{0:x16}", HandlerFnTagAddr))
1954 .str()));
1955}
1956
1958 runSessionLocked([this, &OS]() {
1959 for (auto &JD : JDs)
1960 JD->dump(OS);
1961 });
1962}
1963
1964#ifdef EXPENSIVE_CHECKS
1965bool ExecutionSession::verifySessionState(Twine Phase) {
1966 return runSessionLocked([&]() {
1967 bool AllOk = true;
1968
1969 // We'll collect these and verify them later to avoid redundant checks.
1971
1972 for (auto &JD : JDs) {
1973
1974 auto LogFailure = [&]() -> raw_fd_ostream & {
1975 auto &Stream = errs();
1976 if (AllOk)
1977 Stream << "ERROR: Bad ExecutionSession state detected " << Phase
1978 << "\n";
1979 Stream << " In JITDylib " << JD->getName() << ", ";
1980 AllOk = false;
1981 return Stream;
1982 };
1983
1984 if (JD->State != JITDylib::Open) {
1985 LogFailure()
1986 << "state is not Open, but JD is in ExecutionSession list.";
1987 }
1988
1989 // Check symbol table.
1990 // 1. If the entry state isn't resolved then check that no address has
1991 // been set.
1992 // 2. Check that if the hasMaterializerAttached flag is set then there is
1993 // an UnmaterializedInfo entry, and vice-versa.
1994 for (auto &[Sym, Entry] : JD->Symbols) {
1995 // Check that unresolved symbols have null addresses.
1996 if (Entry.getState() < SymbolState::Resolved) {
1997 if (Entry.getAddress()) {
1998 LogFailure() << "symbol " << Sym << " has state "
1999 << Entry.getState()
2000 << " (not-yet-resolved) but non-null address "
2001 << Entry.getAddress() << ".\n";
2002 }
2003 }
2004
2005 // Check that the hasMaterializerAttached flag is correct.
2006 auto UMIItr = JD->UnmaterializedInfos.find(Sym);
2007 if (Entry.hasMaterializerAttached()) {
2008 if (UMIItr == JD->UnmaterializedInfos.end()) {
2009 LogFailure() << "symbol " << Sym
2010 << " entry claims materializer attached, but "
2011 "UnmaterializedInfos has no corresponding entry.\n";
2012 }
2013 } else if (UMIItr != JD->UnmaterializedInfos.end()) {
2014 LogFailure()
2015 << "symbol " << Sym
2016 << " entry claims no materializer attached, but "
2017 "UnmaterializedInfos has an unexpected entry for it.\n";
2018 }
2019 }
2020
2021 // Check that every UnmaterializedInfo entry has a corresponding entry
2022 // in the Symbols table.
2023 for (auto &[Sym, UMI] : JD->UnmaterializedInfos) {
2024 auto SymItr = JD->Symbols.find(Sym);
2025 if (SymItr == JD->Symbols.end()) {
2026 LogFailure()
2027 << "symbol " << Sym
2028 << " has UnmaterializedInfos entry, but no Symbols entry.\n";
2029 }
2030 }
2031
2032 // Check consistency of the MaterializingInfos table.
2033 for (auto &[Sym, MII] : JD->MaterializingInfos) {
2034
2035 auto SymItr = JD->Symbols.find(Sym);
2036 if (SymItr == JD->Symbols.end()) {
2037 // If there's no Symbols entry for this MaterializingInfos entry then
2038 // report that.
2039 LogFailure()
2040 << "symbol " << Sym
2041 << " has MaterializingInfos entry, but no Symbols entry.\n";
2042 } else {
2043 // Otherwise check consistency between Symbols and MaterializingInfos.
2044
2045 // Ready symbols should not have MaterializingInfos.
2046 if (SymItr->second.getState() == SymbolState::Ready) {
2047 LogFailure()
2048 << "symbol " << Sym
2049 << " is in Ready state, should not have MaterializingInfo.\n";
2050 }
2051
2052 // Pending queries should be for subsequent states.
2053 auto CurState = static_cast<SymbolState>(
2054 static_cast<std::underlying_type_t<SymbolState>>(
2055 SymItr->second.getState()) + 1);
2056 for (auto &Q : MII.PendingQueries) {
2057 if (Q->getRequiredState() != CurState) {
2058 if (Q->getRequiredState() > CurState)
2059 CurState = Q->getRequiredState();
2060 else
2061 LogFailure() << "symbol " << Sym
2062 << " has stale or misordered queries.\n";
2063 }
2064 }
2065
2066 // If there's a DefiningEDU then check that...
2067 // 1. The JD matches.
2068 // 2. The symbol is in the EDU's Symbols map.
2069 // 3. The symbol table entry is in the Emitted state.
2070 if (MII.DefiningEDU) {
2071
2072 EDUsToCheck.insert(MII.DefiningEDU.get());
2073
2074 if (MII.DefiningEDU->JD != JD.get()) {
2075 LogFailure() << "symbol " << Sym
2076 << " has DefiningEDU with incorrect JD"
2077 << (llvm::is_contained(JDs, MII.DefiningEDU->JD)
2078 ? " (JD not currently in ExecutionSession"
2079 : "")
2080 << "\n";
2081 }
2082
2083 if (SymItr->second.getState() != SymbolState::Emitted) {
2084 LogFailure()
2085 << "symbol " << Sym
2086 << " has DefiningEDU, but is not in Emitted state.\n";
2087 }
2088 }
2089
2090 // Check that JDs for any DependantEDUs are also in the session --
2091 // that guarantees that we'll also visit them during this loop.
2092 for (auto &DepEDU : MII.DependantEDUs) {
2093 if (!llvm::is_contained(JDs, DepEDU->JD)) {
2094 LogFailure() << "symbol " << Sym << " has DependantEDU "
2095 << (void *)DepEDU << " with JD (" << DepEDU->JD
2096 << ") that isn't in ExecutionSession.\n";
2097 }
2098 }
2099 }
2100 }
2101 }
2102
2103 // Check EDUs.
2104 for (auto *EDU : EDUsToCheck) {
2105 assert(EDU->JD->State == JITDylib::Open && "EDU->JD is not Open");
2106
2107 auto LogFailure = [&]() -> raw_fd_ostream & {
2108 AllOk = false;
2109 auto &Stream = errs();
2110 Stream << "In EDU defining " << EDU->JD->getName() << ": { ";
2111 for (auto &[Sym, Flags] : EDU->Symbols)
2112 Stream << Sym << " ";
2113 Stream << "}, ";
2114 return Stream;
2115 };
2116
2117 if (EDU->Symbols.empty())
2118 LogFailure() << "no symbols defined.\n";
2119 else {
2120 for (auto &[Sym, Flags] : EDU->Symbols) {
2121 if (!Sym)
2122 LogFailure() << "null symbol defined.\n";
2123 else {
2124 if (!EDU->JD->Symbols.count(SymbolStringPtr(Sym))) {
2125 LogFailure() << "symbol " << Sym
2126 << " isn't present in JD's symbol table.\n";
2127 }
2128 }
2129 }
2130 }
2131
2132 for (auto &[DepJD, Symbols] : EDU->Dependencies) {
2133 if (!llvm::is_contained(JDs, DepJD)) {
2134 LogFailure() << "dependant symbols listed for JD that isn't in "
2135 "ExecutionSession.\n";
2136 } else {
2137 for (auto &DepSym : Symbols) {
2138 if (!DepJD->Symbols.count(SymbolStringPtr(DepSym))) {
2139 LogFailure()
2140 << "dependant symbol " << DepSym
2141 << " does not appear in symbol table for dependant JD "
2142 << DepJD->getName() << ".\n";
2143 }
2144 }
2145 }
2146 }
2147 }
2148
2149 return AllOk;
2150 });
2151}
2152#endif // EXPENSIVE_CHECKS
2153
2154void ExecutionSession::dispatchOutstandingMUs() {
2155 LLVM_DEBUG(dbgs() << "Dispatching MaterializationUnits...\n");
2156 while (true) {
2157 std::optional<std::pair<std::unique_ptr<MaterializationUnit>,
2158 std::unique_ptr<MaterializationResponsibility>>>
2159 JMU;
2160
2161 {
2162 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2163 if (!OutstandingMUs.empty()) {
2164 JMU.emplace(std::move(OutstandingMUs.back()));
2165 OutstandingMUs.pop_back();
2166 }
2167 }
2168
2169 if (!JMU)
2170 break;
2171
2172 assert(JMU->first && "No MU?");
2173 LLVM_DEBUG(dbgs() << " Dispatching \"" << JMU->first->getName() << "\"\n");
2174 dispatchTask(std::make_unique<MaterializationTask>(std::move(JMU->first),
2175 std::move(JMU->second)));
2176 }
2177 LLVM_DEBUG(dbgs() << "Done dispatching MaterializationUnits.\n");
2178}
2179
2180Error ExecutionSession::removeResourceTracker(ResourceTracker &RT) {
2181 LLVM_DEBUG({
2182 dbgs() << "In " << RT.getJITDylib().getName() << " removing tracker "
2183 << formatv("{0:x}", RT.getKeyUnsafe()) << "\n";
2184 });
2185 std::vector<ResourceManager *> CurrentResourceManagers;
2186
2187 JITDylib::AsynchronousSymbolQuerySet QueriesToFail;
2188 std::shared_ptr<SymbolDependenceMap> FailedSymbols;
2189
2190 runSessionLocked([&] {
2191 CurrentResourceManagers = ResourceManagers;
2192 RT.makeDefunct();
2193 std::tie(QueriesToFail, FailedSymbols) =
2194 RT.getJITDylib().IL_removeTracker(RT);
2195 });
2196
2197 Error Err = Error::success();
2198
2199 auto &JD = RT.getJITDylib();
2200 for (auto *L : reverse(CurrentResourceManagers))
2201 Err = joinErrors(std::move(Err),
2202 L->handleRemoveResources(JD, RT.getKeyUnsafe()));
2203
2204 for (auto &Q : QueriesToFail)
2205 Q->handleFailed(
2206 make_error<FailedToMaterialize>(getSymbolStringPool(), FailedSymbols));
2207
2208 return Err;
2209}
2210
2211void ExecutionSession::transferResourceTracker(ResourceTracker &DstRT,
2212 ResourceTracker &SrcRT) {
2213 LLVM_DEBUG({
2214 dbgs() << "In " << SrcRT.getJITDylib().getName()
2215 << " transfering resources from tracker "
2216 << formatv("{0:x}", SrcRT.getKeyUnsafe()) << " to tracker "
2217 << formatv("{0:x}", DstRT.getKeyUnsafe()) << "\n";
2218 });
2219
2220 // No-op transfers are allowed and do not invalidate the source.
2221 if (&DstRT == &SrcRT)
2222 return;
2223
2224 assert(&DstRT.getJITDylib() == &SrcRT.getJITDylib() &&
2225 "Can't transfer resources between JITDylibs");
2226 runSessionLocked([&]() {
2227 SrcRT.makeDefunct();
2228 auto &JD = DstRT.getJITDylib();
2229 JD.transferTracker(DstRT, SrcRT);
2230 for (auto *L : reverse(ResourceManagers))
2231 L->handleTransferResources(JD, DstRT.getKeyUnsafe(),
2232 SrcRT.getKeyUnsafe());
2233 });
2234}
2235
2236void ExecutionSession::destroyResourceTracker(ResourceTracker &RT) {
2237 runSessionLocked([&]() {
2238 LLVM_DEBUG({
2239 dbgs() << "In " << RT.getJITDylib().getName() << " destroying tracker "
2240 << formatv("{0:x}", RT.getKeyUnsafe()) << "\n";
2241 });
2242 if (!RT.isDefunct())
2243 transferResourceTracker(*RT.getJITDylib().getDefaultResourceTracker(),
2244 RT);
2245 });
2246}
2247
2248Error ExecutionSession::IL_updateCandidatesFor(
2249 JITDylib &JD, JITDylibLookupFlags JDLookupFlags,
2250 SymbolLookupSet &Candidates, SymbolLookupSet *NonCandidates) {
2251 return Candidates.forEachWithRemoval(
2252 [&](const SymbolStringPtr &Name,
2253 SymbolLookupFlags SymLookupFlags) -> Expected<bool> {
2254 /// Search for the symbol. If not found then continue without
2255 /// removal.
2256 auto SymI = JD.Symbols.find(Name);
2257 if (SymI == JD.Symbols.end())
2258 return false;
2259
2260 // If this is a non-exported symbol and we're matching exported
2261 // symbols only then remove this symbol from the candidates list.
2262 //
2263 // If we're tracking non-candidates then add this to the non-candidate
2264 // list.
2265 if (!SymI->second.getFlags().isExported() &&
2267 if (NonCandidates)
2268 NonCandidates->add(Name, SymLookupFlags);
2269 return true;
2270 }
2271
2272 // If we match against a materialization-side-effects only symbol
2273 // then make sure it is weakly-referenced. Otherwise bail out with
2274 // an error.
2275 // FIXME: Use a "materialization-side-effects-only symbols must be
2276 // weakly referenced" specific error here to reduce confusion.
2277 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2279 return make_error<SymbolsNotFound>(getSymbolStringPool(),
2281
2282 // If we matched against this symbol but it is in the error state
2283 // then bail out and treat it as a failure to materialize.
2284 if (SymI->second.getFlags().hasError()) {
2285 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2286 (*FailedSymbolsMap)[&JD] = {Name};
2287 return make_error<FailedToMaterialize>(getSymbolStringPool(),
2288 std::move(FailedSymbolsMap));
2289 }
2290
2291 // Otherwise this is a match. Remove it from the candidate set.
2292 return true;
2293 });
2294}
2295
2296void ExecutionSession::OL_resumeLookupAfterGeneration(
2297 InProgressLookupState &IPLS) {
2298
2300 "Should not be called for not-in-generator lookups");
2302
2304
2305 if (auto DG = IPLS.CurDefGeneratorStack.back().lock()) {
2306 IPLS.CurDefGeneratorStack.pop_back();
2307 std::lock_guard<std::mutex> Lock(DG->M);
2308
2309 // If there are no pending lookups then mark the generator as free and
2310 // return.
2311 if (DG->PendingLookups.empty()) {
2312 DG->InUse = false;
2313 return;
2314 }
2315
2316 // Otherwise resume the next lookup.
2317 LS = std::move(DG->PendingLookups.front());
2318 DG->PendingLookups.pop_front();
2319 }
2320
2321 if (LS.IPLS) {
2323 dispatchTask(std::make_unique<LookupTask>(std::move(LS)));
2324 }
2325}
2326
2327void ExecutionSession::OL_applyQueryPhase1(
2328 std::unique_ptr<InProgressLookupState> IPLS, Error Err) {
2329
2330 LLVM_DEBUG({
2331 dbgs() << "Entering OL_applyQueryPhase1:\n"
2332 << " Lookup kind: " << IPLS->K << "\n"
2333 << " Search order: " << IPLS->SearchOrder
2334 << ", Current index = " << IPLS->CurSearchOrderIndex
2335 << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2336 << " Lookup set: " << IPLS->LookupSet << "\n"
2337 << " Definition generator candidates: "
2338 << IPLS->DefGeneratorCandidates << "\n"
2339 << " Definition generator non-candidates: "
2340 << IPLS->DefGeneratorNonCandidates << "\n";
2341 });
2342
2343 if (IPLS->GenState == InProgressLookupState::InGenerator)
2344 OL_resumeLookupAfterGeneration(*IPLS);
2345
2346 assert(IPLS->GenState != InProgressLookupState::InGenerator &&
2347 "Lookup should not be in InGenerator state here");
2348
2349 // FIXME: We should attach the query as we go: This provides a result in a
2350 // single pass in the common case where all symbols have already reached the
2351 // required state. The query could be detached again in the 'fail' method on
2352 // IPLS. Phase 2 would be reduced to collecting and dispatching the MUs.
2353
2354 while (IPLS->CurSearchOrderIndex != IPLS->SearchOrder.size()) {
2355
2356 // If we've been handed an error or received one back from a generator then
2357 // fail the query. We don't need to unlink: At this stage the query hasn't
2358 // actually been lodged.
2359 if (Err)
2360 return IPLS->fail(std::move(Err));
2361
2362 // Get the next JITDylib and lookup flags.
2363 auto &KV = IPLS->SearchOrder[IPLS->CurSearchOrderIndex];
2364 auto &JD = *KV.first;
2365 auto JDLookupFlags = KV.second;
2366
2367 LLVM_DEBUG({
2368 dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2369 << ") with lookup set " << IPLS->LookupSet << ":\n";
2370 });
2371
2372 // If we've just reached a new JITDylib then perform some setup.
2373 if (IPLS->NewJITDylib) {
2374 // Add any non-candidates from the last JITDylib (if any) back on to the
2375 // list of definition candidates for this JITDylib, reset definition
2376 // non-candidates to the empty set.
2377 SymbolLookupSet Tmp;
2378 std::swap(IPLS->DefGeneratorNonCandidates, Tmp);
2379 IPLS->DefGeneratorCandidates.append(std::move(Tmp));
2380
2381 LLVM_DEBUG({
2382 dbgs() << " First time visiting " << JD.getName()
2383 << ", resetting candidate sets and building generator stack\n";
2384 });
2385
2386 // Build the definition generator stack for this JITDylib.
2387 runSessionLocked([&] {
2388 IPLS->CurDefGeneratorStack.reserve(JD.DefGenerators.size());
2389 for (auto &DG : reverse(JD.DefGenerators))
2390 IPLS->CurDefGeneratorStack.push_back(DG);
2391 });
2392
2393 // Flag that we've done our initialization.
2394 IPLS->NewJITDylib = false;
2395 }
2396
2397 // Remove any generation candidates that are already defined (and match) in
2398 // this JITDylib.
2399 runSessionLocked([&] {
2400 // Update the list of candidates (and non-candidates) for definition
2401 // generation.
2402 LLVM_DEBUG(dbgs() << " Updating candidate set...\n");
2403 Err = IL_updateCandidatesFor(
2404 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2405 JD.DefGenerators.empty() ? nullptr
2406 : &IPLS->DefGeneratorNonCandidates);
2407 LLVM_DEBUG({
2408 dbgs() << " Remaining candidates = " << IPLS->DefGeneratorCandidates
2409 << "\n";
2410 });
2411
2412 // If this lookup was resumed after auto-suspension but all candidates
2413 // have already been generated (by some previous call to the generator)
2414 // treat the lookup as if it had completed generation.
2415 if (IPLS->GenState == InProgressLookupState::ResumedForGenerator &&
2416 IPLS->DefGeneratorCandidates.empty())
2417 OL_resumeLookupAfterGeneration(*IPLS);
2418 });
2419
2420 // If we encountered an error while filtering generation candidates then
2421 // bail out.
2422 if (Err)
2423 return IPLS->fail(std::move(Err));
2424
2425 /// Apply any definition generators on the stack.
2426 LLVM_DEBUG({
2427 if (IPLS->CurDefGeneratorStack.empty())
2428 LLVM_DEBUG(dbgs() << " No generators to run for this JITDylib.\n");
2429 else if (IPLS->DefGeneratorCandidates.empty())
2430 LLVM_DEBUG(dbgs() << " No candidates to generate.\n");
2431 else
2432 dbgs() << " Running " << IPLS->CurDefGeneratorStack.size()
2433 << " remaining generators for "
2434 << IPLS->DefGeneratorCandidates.size() << " candidates\n";
2435 });
2436 while (!IPLS->CurDefGeneratorStack.empty() &&
2437 !IPLS->DefGeneratorCandidates.empty()) {
2438 auto DG = IPLS->CurDefGeneratorStack.back().lock();
2439
2440 if (!DG)
2441 return IPLS->fail(make_error<StringError>(
2442 "DefinitionGenerator removed while lookup in progress",
2444
2445 // At this point the lookup is in either the NotInGenerator state, or in
2446 // the ResumedForGenerator state.
2447 // If this lookup is in the NotInGenerator state then check whether the
2448 // generator is in use. If the generator is not in use then move the
2449 // lookup to the InGenerator state and continue. If the generator is
2450 // already in use then just add this lookup to the pending lookups list
2451 // and bail out.
2452 // If this lookup is in the ResumedForGenerator state then just move it
2453 // to InGenerator and continue.
2454 if (IPLS->GenState == InProgressLookupState::NotInGenerator) {
2455 std::lock_guard<std::mutex> Lock(DG->M);
2456 if (DG->InUse) {
2457 DG->PendingLookups.push_back(std::move(IPLS));
2458 return;
2459 }
2460 DG->InUse = true;
2461 }
2462
2463 IPLS->GenState = InProgressLookupState::InGenerator;
2464
2465 auto K = IPLS->K;
2466 auto &LookupSet = IPLS->DefGeneratorCandidates;
2467
2468 // Run the generator. If the generator takes ownership of QA then this
2469 // will break the loop.
2470 {
2471 LLVM_DEBUG(dbgs() << " Attempting to generate " << LookupSet << "\n");
2472 LookupState LS(std::move(IPLS));
2473 Err = DG->tryToGenerate(LS, K, JD, JDLookupFlags, LookupSet);
2474 IPLS = std::move(LS.IPLS);
2475 }
2476
2477 // If the lookup returned then pop the generator stack and unblock the
2478 // next lookup on this generator (if any).
2479 if (IPLS)
2480 OL_resumeLookupAfterGeneration(*IPLS);
2481
2482 // If there was an error then fail the query.
2483 if (Err) {
2484 LLVM_DEBUG({
2485 dbgs() << " Error attempting to generate " << LookupSet << "\n";
2486 });
2487 assert(IPLS && "LS cannot be retained if error is returned");
2488 return IPLS->fail(std::move(Err));
2489 }
2490
2491 // Otherwise if QA was captured then break the loop.
2492 if (!IPLS) {
2493 LLVM_DEBUG(
2494 { dbgs() << " LookupState captured. Exiting phase1 for now.\n"; });
2495 return;
2496 }
2497
2498 // Otherwise if we're continuing around the loop then update candidates
2499 // for the next round.
2500 runSessionLocked([&] {
2501 LLVM_DEBUG(dbgs() << " Updating candidate set post-generation\n");
2502 Err = IL_updateCandidatesFor(
2503 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2504 JD.DefGenerators.empty() ? nullptr
2505 : &IPLS->DefGeneratorNonCandidates);
2506 });
2507
2508 // If updating candidates failed then fail the query.
2509 if (Err) {
2510 LLVM_DEBUG(dbgs() << " Error encountered while updating candidates\n");
2511 return IPLS->fail(std::move(Err));
2512 }
2513 }
2514
2515 if (IPLS->DefGeneratorCandidates.empty() &&
2516 IPLS->DefGeneratorNonCandidates.empty()) {
2517 // Early out if there are no remaining symbols.
2518 LLVM_DEBUG(dbgs() << "All symbols matched.\n");
2519 IPLS->CurSearchOrderIndex = IPLS->SearchOrder.size();
2520 break;
2521 } else {
2522 // If we get here then we've moved on to the next JITDylib with candidates
2523 // remaining.
2524 LLVM_DEBUG(dbgs() << "Phase 1 moving to next JITDylib.\n");
2525 ++IPLS->CurSearchOrderIndex;
2526 IPLS->NewJITDylib = true;
2527 }
2528 }
2529
2530 // Remove any weakly referenced candidates that could not be found/generated.
2531 IPLS->DefGeneratorCandidates.remove_if(
2532 [](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2533 return SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol;
2534 });
2535
2536 // If we get here then we've finished searching all JITDylibs.
2537 // If we matched all symbols then move to phase 2, otherwise fail the query
2538 // with a SymbolsNotFound error.
2539 if (IPLS->DefGeneratorCandidates.empty()) {
2540 LLVM_DEBUG(dbgs() << "Phase 1 succeeded.\n");
2541 IPLS->complete(std::move(IPLS));
2542 } else {
2543 LLVM_DEBUG(dbgs() << "Phase 1 failed with unresolved symbols.\n");
2544 IPLS->fail(make_error<SymbolsNotFound>(
2545 getSymbolStringPool(), IPLS->DefGeneratorCandidates.getSymbolNames()));
2546 }
2547}
2548
2549void ExecutionSession::OL_completeLookup(
2550 std::unique_ptr<InProgressLookupState> IPLS,
2551 std::shared_ptr<AsynchronousSymbolQuery> Q,
2552 RegisterDependenciesFunction RegisterDependencies) {
2553
2554 LLVM_DEBUG({
2555 dbgs() << "Entering OL_completeLookup:\n"
2556 << " Lookup kind: " << IPLS->K << "\n"
2557 << " Search order: " << IPLS->SearchOrder
2558 << ", Current index = " << IPLS->CurSearchOrderIndex
2559 << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2560 << " Lookup set: " << IPLS->LookupSet << "\n"
2561 << " Definition generator candidates: "
2562 << IPLS->DefGeneratorCandidates << "\n"
2563 << " Definition generator non-candidates: "
2564 << IPLS->DefGeneratorNonCandidates << "\n";
2565 });
2566
2567 bool QueryComplete = false;
2568 DenseMap<JITDylib *, JITDylib::UnmaterializedInfosList> CollectedUMIs;
2569
2570 auto LodgingErr = runSessionLocked([&]() -> Error {
2571 for (auto &KV : IPLS->SearchOrder) {
2572 auto &JD = *KV.first;
2573 auto JDLookupFlags = KV.second;
2574 LLVM_DEBUG({
2575 dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2576 << ") with lookup set " << IPLS->LookupSet << ":\n";
2577 });
2578
2579 auto Err = IPLS->LookupSet.forEachWithRemoval(
2580 [&](const SymbolStringPtr &Name,
2581 SymbolLookupFlags SymLookupFlags) -> Expected<bool> {
2582 LLVM_DEBUG({
2583 dbgs() << " Attempting to match \"" << Name << "\" ("
2584 << SymLookupFlags << ")... ";
2585 });
2586
2587 /// Search for the symbol. If not found then continue without
2588 /// removal.
2589 auto SymI = JD.Symbols.find(Name);
2590 if (SymI == JD.Symbols.end()) {
2591 LLVM_DEBUG(dbgs() << "skipping: not present\n");
2592 return false;
2593 }
2594
2595 // If this is a non-exported symbol and we're matching exported
2596 // symbols only then skip this symbol without removal.
2597 if (!SymI->second.getFlags().isExported() &&
2598 JDLookupFlags ==
2600 LLVM_DEBUG(dbgs() << "skipping: not exported\n");
2601 return false;
2602 }
2603
2604 // If we match against a materialization-side-effects only symbol
2605 // then make sure it is weakly-referenced. Otherwise bail out with
2606 // an error.
2607 // FIXME: Use a "materialization-side-effects-only symbols must be
2608 // weakly referenced" specific error here to reduce confusion.
2609 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2611 LLVM_DEBUG({
2612 dbgs() << "error: "
2613 "required, but symbol is has-side-effects-only\n";
2614 });
2615 return make_error<SymbolsNotFound>(getSymbolStringPool(),
2617 }
2618
2619 // If we matched against this symbol but it is in the error state
2620 // then bail out and treat it as a failure to materialize.
2621 if (SymI->second.getFlags().hasError()) {
2622 LLVM_DEBUG(dbgs() << "error: symbol is in error state\n");
2623 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2624 (*FailedSymbolsMap)[&JD] = {Name};
2625 return make_error<FailedToMaterialize>(
2626 getSymbolStringPool(), std::move(FailedSymbolsMap));
2627 }
2628
2629 // Otherwise this is a match.
2630
2631 // If this symbol is already in the required state then notify the
2632 // query, remove the symbol and continue.
2633 if (SymI->second.getState() >= Q->getRequiredState()) {
2635 << "matched, symbol already in required state\n");
2636 Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
2637
2638 // If this symbol is in anything other than the Ready state then
2639 // we need to track the dependence.
2640 if (SymI->second.getState() != SymbolState::Ready)
2641 Q->addQueryDependence(JD, Name);
2642
2643 return true;
2644 }
2645
2646 // Otherwise this symbol does not yet meet the required state. Check
2647 // whether it has a materializer attached, and if so prepare to run
2648 // it.
2649 if (SymI->second.hasMaterializerAttached()) {
2650 assert(SymI->second.getAddress() == ExecutorAddr() &&
2651 "Symbol not resolved but already has address?");
2652 auto UMII = JD.UnmaterializedInfos.find(Name);
2653 assert(UMII != JD.UnmaterializedInfos.end() &&
2654 "Lazy symbol should have UnmaterializedInfo");
2655
2656 auto UMI = UMII->second;
2657 assert(UMI->MU && "Materializer should not be null");
2658 assert(UMI->RT && "Tracker should not be null");
2659 LLVM_DEBUG({
2660 dbgs() << "matched, preparing to dispatch MU@" << UMI->MU.get()
2661 << " (" << UMI->MU->getName() << ")\n";
2662 });
2663
2664 // Move all symbols associated with this MaterializationUnit into
2665 // materializing state.
2666 for (auto &KV : UMI->MU->getSymbols()) {
2667 auto SymK = JD.Symbols.find(KV.first);
2668 assert(SymK != JD.Symbols.end() &&
2669 "No entry for symbol covered by MaterializationUnit");
2670 SymK->second.setMaterializerAttached(false);
2671 SymK->second.setState(SymbolState::Materializing);
2672 JD.UnmaterializedInfos.erase(KV.first);
2673 }
2674
2675 // Add MU to the list of MaterializationUnits to be materialized.
2676 CollectedUMIs[&JD].push_back(std::move(UMI));
2677 } else
2678 LLVM_DEBUG(dbgs() << "matched, registering query");
2679
2680 // Add the query to the PendingQueries list and continue, deleting
2681 // the element from the lookup set.
2682 assert(SymI->second.getState() != SymbolState::NeverSearched &&
2683 SymI->second.getState() != SymbolState::Ready &&
2684 "By this line the symbol should be materializing");
2685 auto &MI = JD.MaterializingInfos[Name];
2686 MI.addQuery(Q);
2687 Q->addQueryDependence(JD, Name);
2688
2689 return true;
2690 });
2691
2692 JD.shrinkMaterializationInfoMemory();
2693
2694 // Handle failure.
2695 if (Err) {
2696
2697 LLVM_DEBUG({
2698 dbgs() << "Lookup failed. Detaching query and replacing MUs.\n";
2699 });
2700
2701 // Detach the query.
2702 Q->detach();
2703
2704 // Replace the MUs.
2705 for (auto &KV : CollectedUMIs) {
2706 auto &JD = *KV.first;
2707 for (auto &UMI : KV.second)
2708 for (auto &KV2 : UMI->MU->getSymbols()) {
2709 assert(!JD.UnmaterializedInfos.count(KV2.first) &&
2710 "Unexpected materializer in map");
2711 auto SymI = JD.Symbols.find(KV2.first);
2712 assert(SymI != JD.Symbols.end() && "Missing symbol entry");
2713 assert(SymI->second.getState() == SymbolState::Materializing &&
2714 "Can not replace symbol that is not materializing");
2715 assert(!SymI->second.hasMaterializerAttached() &&
2716 "MaterializerAttached flag should not be set");
2717 SymI->second.setMaterializerAttached(true);
2718 JD.UnmaterializedInfos[KV2.first] = UMI;
2719 }
2720 }
2721
2722 return Err;
2723 }
2724 }
2725
2726 LLVM_DEBUG(dbgs() << "Stripping unmatched weakly-referenced symbols\n");
2727 IPLS->LookupSet.forEachWithRemoval(
2728 [&](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2729 if (SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol) {
2730 Q->dropSymbol(Name);
2731 return true;
2732 } else
2733 return false;
2734 });
2735
2736 if (!IPLS->LookupSet.empty()) {
2737 LLVM_DEBUG(dbgs() << "Failing due to unresolved symbols\n");
2738 return make_error<SymbolsNotFound>(getSymbolStringPool(),
2739 IPLS->LookupSet.getSymbolNames());
2740 }
2741
2742 // Record whether the query completed.
2743 QueryComplete = Q->isComplete();
2744
2745 LLVM_DEBUG({
2746 dbgs() << "Query successfully "
2747 << (QueryComplete ? "completed" : "lodged") << "\n";
2748 });
2749
2750 // Move the collected MUs to the OutstandingMUs list.
2751 if (!CollectedUMIs.empty()) {
2752 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2753
2754 LLVM_DEBUG(dbgs() << "Adding MUs to dispatch:\n");
2755 for (auto &KV : CollectedUMIs) {
2756 LLVM_DEBUG({
2757 auto &JD = *KV.first;
2758 dbgs() << " For " << JD.getName() << ": Adding " << KV.second.size()
2759 << " MUs.\n";
2760 });
2761 for (auto &UMI : KV.second) {
2762 auto MR = createMaterializationResponsibility(
2763 *UMI->RT, std::move(UMI->MU->SymbolFlags),
2764 std::move(UMI->MU->InitSymbol));
2765 OutstandingMUs.push_back(
2766 std::make_pair(std::move(UMI->MU), std::move(MR)));
2767 }
2768 }
2769 } else
2770 LLVM_DEBUG(dbgs() << "No MUs to dispatch.\n");
2771
2772 if (RegisterDependencies && !Q->QueryRegistrations.empty()) {
2773 LLVM_DEBUG(dbgs() << "Registering dependencies\n");
2774 RegisterDependencies(Q->QueryRegistrations);
2775 } else
2776 LLVM_DEBUG(dbgs() << "No dependencies to register\n");
2777
2778 return Error::success();
2779 });
2780
2781 if (LodgingErr) {
2782 LLVM_DEBUG(dbgs() << "Failing query\n");
2783 Q->detach();
2784 Q->handleFailed(std::move(LodgingErr));
2785 return;
2786 }
2787
2788 if (QueryComplete) {
2789 LLVM_DEBUG(dbgs() << "Completing query\n");
2790 Q->handleComplete(*this);
2791 }
2792
2793 dispatchOutstandingMUs();
2794}
2795
2796void ExecutionSession::OL_completeLookupFlags(
2797 std::unique_ptr<InProgressLookupState> IPLS,
2798 unique_function<void(Expected<SymbolFlagsMap>)> OnComplete) {
2799
2800 auto Result = runSessionLocked([&]() -> Expected<SymbolFlagsMap> {
2801 LLVM_DEBUG({
2802 dbgs() << "Entering OL_completeLookupFlags:\n"
2803 << " Lookup kind: " << IPLS->K << "\n"
2804 << " Search order: " << IPLS->SearchOrder
2805 << ", Current index = " << IPLS->CurSearchOrderIndex
2806 << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2807 << " Lookup set: " << IPLS->LookupSet << "\n"
2808 << " Definition generator candidates: "
2809 << IPLS->DefGeneratorCandidates << "\n"
2810 << " Definition generator non-candidates: "
2811 << IPLS->DefGeneratorNonCandidates << "\n";
2812 });
2813
2815
2816 // Attempt to find flags for each symbol.
2817 for (auto &KV : IPLS->SearchOrder) {
2818 auto &JD = *KV.first;
2819 auto JDLookupFlags = KV.second;
2820 LLVM_DEBUG({
2821 dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2822 << ") with lookup set " << IPLS->LookupSet << ":\n";
2823 });
2824
2825 IPLS->LookupSet.forEachWithRemoval([&](const SymbolStringPtr &Name,
2826 SymbolLookupFlags SymLookupFlags) {
2827 LLVM_DEBUG({
2828 dbgs() << " Attempting to match \"" << Name << "\" ("
2829 << SymLookupFlags << ")... ";
2830 });
2831
2832 // Search for the symbol. If not found then continue without removing
2833 // from the lookup set.
2834 auto SymI = JD.Symbols.find(Name);
2835 if (SymI == JD.Symbols.end()) {
2836 LLVM_DEBUG(dbgs() << "skipping: not present\n");
2837 return false;
2838 }
2839
2840 // If this is a non-exported symbol then it doesn't match. Skip it.
2841 if (!SymI->second.getFlags().isExported() &&
2843 LLVM_DEBUG(dbgs() << "skipping: not exported\n");
2844 return false;
2845 }
2846
2847 LLVM_DEBUG({
2848 dbgs() << "matched, \"" << Name << "\" -> " << SymI->second.getFlags()
2849 << "\n";
2850 });
2851 Result[Name] = SymI->second.getFlags();
2852 return true;
2853 });
2854 }
2855
2856 // Remove any weakly referenced symbols that haven't been resolved.
2857 IPLS->LookupSet.remove_if(
2858 [](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2859 return SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol;
2860 });
2861
2862 if (!IPLS->LookupSet.empty()) {
2863 LLVM_DEBUG(dbgs() << "Failing due to unresolved symbols\n");
2864 return make_error<SymbolsNotFound>(getSymbolStringPool(),
2865 IPLS->LookupSet.getSymbolNames());
2866 }
2867
2868 LLVM_DEBUG(dbgs() << "Succeded, result = " << Result << "\n");
2869 return Result;
2870 });
2871
2872 // Run the callback on the result.
2873 LLVM_DEBUG(dbgs() << "Sending result to handler.\n");
2874 OnComplete(std::move(Result));
2875}
2876
2877void ExecutionSession::OL_destroyMaterializationResponsibility(
2878 MaterializationResponsibility &MR) {
2879
2880 assert(MR.SymbolFlags.empty() &&
2881 "All symbols should have been explicitly materialized or failed");
2882 MR.JD.unlinkMaterializationResponsibility(MR);
2883}
2884
2885SymbolNameSet ExecutionSession::OL_getRequestedSymbols(
2886 const MaterializationResponsibility &MR) {
2887 return MR.JD.getRequestedSymbols(MR.SymbolFlags);
2888}
2889
2890Error ExecutionSession::OL_notifyResolved(MaterializationResponsibility &MR,
2891 const SymbolMap &Symbols) {
2892 LLVM_DEBUG({
2893 dbgs() << "In " << MR.JD.getName() << " resolving " << Symbols << "\n";
2894 });
2895#ifndef NDEBUG
2896 for (auto &KV : Symbols) {
2897 auto I = MR.SymbolFlags.find(KV.first);
2898 assert(I != MR.SymbolFlags.end() &&
2899 "Resolving symbol outside this responsibility set");
2900 assert(!I->second.hasMaterializationSideEffectsOnly() &&
2901 "Can't resolve materialization-side-effects-only symbol");
2902 if (I->second & JITSymbolFlags::Common) {
2903 auto WeakOrCommon = JITSymbolFlags::Weak | JITSymbolFlags::Common;
2904 assert((KV.second.getFlags() & WeakOrCommon) &&
2905 "Common symbols must be resolved as common or weak");
2906 assert((KV.second.getFlags() & ~WeakOrCommon) ==
2907 (I->second & ~JITSymbolFlags::Common) &&
2908 "Resolving symbol with incorrect flags");
2909 } else
2910 assert(KV.second.getFlags() == I->second &&
2911 "Resolving symbol with incorrect flags");
2912 }
2913#endif
2914
2915 return MR.JD.resolve(MR, Symbols);
2916}
2917
2918template <typename HandleNewDepFn>
2919void ExecutionSession::propagateExtraEmitDeps(
2920 std::deque<JITDylib::EmissionDepUnit *> Worklist, EDUInfosMap &EDUInfos,
2921 HandleNewDepFn HandleNewDep) {
2922
2923 // Iterate to a fixed-point to propagate extra-emit dependencies through the
2924 // EDU graph.
2925 while (!Worklist.empty()) {
2926 auto &EDU = *Worklist.front();
2927 Worklist.pop_front();
2928
2929 assert(EDUInfos.count(&EDU) && "No info entry for EDU");
2930 auto &EDUInfo = EDUInfos[&EDU];
2931
2932 // Propagate new dependencies to users.
2933 for (auto *UserEDU : EDUInfo.IntraEmitUsers) {
2934
2935 // UserEDUInfo only present if UserEDU has its own users.
2936 JITDylib::EmissionDepUnitInfo *UserEDUInfo = nullptr;
2937 {
2938 auto UserEDUInfoItr = EDUInfos.find(UserEDU);
2939 if (UserEDUInfoItr != EDUInfos.end())
2940 UserEDUInfo = &UserEDUInfoItr->second;
2941 }
2942
2943 for (auto &[DepJD, Deps] : EDUInfo.NewDeps) {
2944 auto &UserEDUDepsForJD = UserEDU->Dependencies[DepJD];
2945 DenseSet<NonOwningSymbolStringPtr> *UserEDUNewDepsForJD = nullptr;
2946 for (auto Dep : Deps) {
2947 if (UserEDUDepsForJD.insert(Dep).second) {
2948 HandleNewDep(*UserEDU, *DepJD, Dep);
2949 if (UserEDUInfo) {
2950 if (!UserEDUNewDepsForJD) {
2951 // If UserEDU has no new deps then it's not in the worklist
2952 // yet, so add it.
2953 if (UserEDUInfo->NewDeps.empty())
2954 Worklist.push_back(UserEDU);
2955 UserEDUNewDepsForJD = &UserEDUInfo->NewDeps[DepJD];
2956 }
2957 // Add (DepJD, Dep) to NewDeps.
2958 UserEDUNewDepsForJD->insert(Dep);
2959 }
2960 }
2961 }
2962 }
2963 }
2964
2965 EDUInfo.NewDeps.clear();
2966 }
2967}
2968
2969// Note: This method modifies the emitted set.
2970ExecutionSession::EDUInfosMap ExecutionSession::simplifyDepGroups(
2971 MaterializationResponsibility &MR,
2972 ArrayRef<SymbolDependenceGroup> EmittedDeps) {
2973
2974 auto &TargetJD = MR.getTargetJITDylib();
2975
2976 // 1. Build initial EmissionDepUnit -> EmissionDepUnitInfo and
2977 // Symbol -> EmissionDepUnit mappings.
2978 DenseMap<JITDylib::EmissionDepUnit *, JITDylib::EmissionDepUnitInfo> EDUInfos;
2979 EDUInfos.reserve(EmittedDeps.size());
2980 DenseMap<NonOwningSymbolStringPtr, JITDylib::EmissionDepUnit *> EDUForSymbol;
2981 for (auto &DG : EmittedDeps) {
2982 assert(!DG.Symbols.empty() && "DepGroup does not cover any symbols");
2983
2984 // Skip empty EDUs.
2985 if (DG.Dependencies.empty())
2986 continue;
2987
2988 auto TmpEDU = std::make_shared<JITDylib::EmissionDepUnit>(TargetJD);
2989 auto &EDUInfo = EDUInfos[TmpEDU.get()];
2990 EDUInfo.EDU = std::move(TmpEDU);
2991 for (const auto &Symbol : DG.Symbols) {
2992 NonOwningSymbolStringPtr NonOwningSymbol(Symbol);
2993 assert(!EDUForSymbol.count(NonOwningSymbol) &&
2994 "Symbol should not appear in more than one SymbolDependenceGroup");
2995 assert(MR.getSymbols().count(Symbol) &&
2996 "Symbol in DepGroups not in the emitted set");
2997 auto NewlyEmittedItr = MR.getSymbols().find(Symbol);
2998 EDUInfo.EDU->Symbols[NonOwningSymbol] = NewlyEmittedItr->second;
2999 EDUForSymbol[NonOwningSymbol] = EDUInfo.EDU.get();
3000 }
3001 }
3002
3003 // 2. Build a "residual" EDU to cover all symbols that have no dependencies.
3004 {
3005 DenseMap<NonOwningSymbolStringPtr, JITSymbolFlags> ResidualSymbolFlags;
3006 for (auto &[Sym, Flags] : MR.getSymbols()) {
3007 if (!EDUForSymbol.count(NonOwningSymbolStringPtr(Sym)))
3008 ResidualSymbolFlags[NonOwningSymbolStringPtr(Sym)] = Flags;
3009 }
3010 if (!ResidualSymbolFlags.empty()) {
3011 auto ResidualEDU = std::make_shared<JITDylib::EmissionDepUnit>(TargetJD);
3012 ResidualEDU->Symbols = std::move(ResidualSymbolFlags);
3013 auto &ResidualEDUInfo = EDUInfos[ResidualEDU.get()];
3014 ResidualEDUInfo.EDU = std::move(ResidualEDU);
3015
3016 // If the residual EDU is the only one then bail out early.
3017 if (EDUInfos.size() == 1)
3018 return EDUInfos;
3019
3020 // Otherwise add the residual EDU to the EDUForSymbol map.
3021 for (auto &[Sym, Flags] : ResidualEDUInfo.EDU->Symbols)
3022 EDUForSymbol[Sym] = ResidualEDUInfo.EDU.get();
3023 }
3024 }
3025
3026#ifndef NDEBUG
3027 assert(EDUForSymbol.size() == MR.getSymbols().size() &&
3028 "MR symbols not fully covered by EDUs?");
3029 for (auto &[Sym, Flags] : MR.getSymbols()) {
3030 assert(EDUForSymbol.count(NonOwningSymbolStringPtr(Sym)) &&
3031 "Sym in MR not covered by EDU");
3032 }
3033#endif // NDEBUG
3034
3035 // 3. Use the DepGroups array to build a graph of dependencies between
3036 // EmissionDepUnits in this finalization. We want to remove these
3037 // intra-finalization uses, propagating dependencies on symbols outside
3038 // this finalization. Add EDUs to the worklist.
3039 for (auto &DG : EmittedDeps) {
3040
3041 // Skip SymbolDependenceGroups with no dependencies.
3042 if (DG.Dependencies.empty())
3043 continue;
3044
3045 assert(EDUForSymbol.count(NonOwningSymbolStringPtr(*DG.Symbols.begin())) &&
3046 "No EDU for DG");
3047 auto &EDU =
3048 *EDUForSymbol.find(NonOwningSymbolStringPtr(*DG.Symbols.begin()))
3049 ->second;
3050
3051 for (auto &[DepJD, Deps] : DG.Dependencies) {
3052 DenseSet<NonOwningSymbolStringPtr> NewDepsForJD;
3053
3054 assert(!Deps.empty() && "Dependence set for DepJD is empty");
3055
3056 if (DepJD != &TargetJD) {
3057 // DepJD is some other JITDylib.There can't be any intra-finalization
3058 // edges here, so just skip.
3059 for (auto &Dep : Deps)
3060 NewDepsForJD.insert(NonOwningSymbolStringPtr(Dep));
3061 } else {
3062 // DepJD is the Target JITDylib. Check for intra-finaliztaion edges,
3063 // skipping any and recording the intra-finalization use instead.
3064 for (auto &Dep : Deps) {
3065 NonOwningSymbolStringPtr NonOwningDep(Dep);
3066 auto I = EDUForSymbol.find(NonOwningDep);
3067 if (I == EDUForSymbol.end()) {
3068 if (!MR.getSymbols().count(Dep))
3069 NewDepsForJD.insert(NonOwningDep);
3070 continue;
3071 }
3072
3073 if (I->second != &EDU)
3074 EDUInfos[I->second].IntraEmitUsers.insert(&EDU);
3075 }
3076 }
3077
3078 if (!NewDepsForJD.empty())
3079 EDU.Dependencies[DepJD] = std::move(NewDepsForJD);
3080 }
3081 }
3082
3083 // 4. Build the worklist.
3084 std::deque<JITDylib::EmissionDepUnit *> Worklist;
3085 for (auto &[EDU, EDUInfo] : EDUInfos) {
3086 // If this EDU has extra-finalization dependencies and intra-finalization
3087 // users then add it to the worklist.
3088 if (!EDU->Dependencies.empty()) {
3089 auto I = EDUInfos.find(EDU);
3090 if (I != EDUInfos.end()) {
3091 auto &EDUInfo = I->second;
3092 if (!EDUInfo.IntraEmitUsers.empty()) {
3093 EDUInfo.NewDeps = EDU->Dependencies;
3094 Worklist.push_back(EDU);
3095 }
3096 }
3097 }
3098 }
3099
3100 // 4. Propagate dependencies through the EDU graph.
3101 propagateExtraEmitDeps(
3102 Worklist, EDUInfos,
3103 [](JITDylib::EmissionDepUnit &, JITDylib &, NonOwningSymbolStringPtr) {});
3104
3105 return EDUInfos;
3106}
3107
3108void ExecutionSession::IL_makeEDUReady(
3109 std::shared_ptr<JITDylib::EmissionDepUnit> EDU,
3110 JITDylib::AsynchronousSymbolQuerySet &Queries) {
3111
3112 // The symbols for this EDU are ready.
3113 auto &JD = *EDU->JD;
3114
3115 for (auto &[Sym, Flags] : EDU->Symbols) {
3116 assert(JD.Symbols.count(SymbolStringPtr(Sym)) &&
3117 "JD does not have an entry for Sym");
3118 auto &Entry = JD.Symbols[SymbolStringPtr(Sym)];
3119
3120 assert(((Entry.getFlags().hasMaterializationSideEffectsOnly() &&
3121 Entry.getState() == SymbolState::Materializing) ||
3122 Entry.getState() == SymbolState::Resolved ||
3123 Entry.getState() == SymbolState::Emitted) &&
3124 "Emitting from state other than Resolved");
3125
3126 Entry.setState(SymbolState::Ready);
3127
3128 auto MII = JD.MaterializingInfos.find(SymbolStringPtr(Sym));
3129
3130 // Check for pending queries.
3131 if (MII == JD.MaterializingInfos.end())
3132 continue;
3133 auto &MI = MII->second;
3134
3135 for (auto &Q : MI.takeQueriesMeeting(SymbolState::Ready)) {
3136 Q->notifySymbolMetRequiredState(SymbolStringPtr(Sym), Entry.getSymbol());
3137 if (Q->isComplete())
3138 Queries.insert(Q);
3139 Q->removeQueryDependence(JD, SymbolStringPtr(Sym));
3140 }
3141
3142 JD.MaterializingInfos.erase(MII);
3143 }
3144
3145 JD.shrinkMaterializationInfoMemory();
3146}
3147
3148void ExecutionSession::IL_makeEDUEmitted(
3149 std::shared_ptr<JITDylib::EmissionDepUnit> EDU,
3150 JITDylib::AsynchronousSymbolQuerySet &Queries) {
3151
3152 // The symbols for this EDU are emitted, but not ready.
3153 auto &JD = *EDU->JD;
3154
3155 for (auto &[Sym, Flags] : EDU->Symbols) {
3156 assert(JD.Symbols.count(SymbolStringPtr(Sym)) &&
3157 "JD does not have an entry for Sym");
3158 auto &Entry = JD.Symbols[SymbolStringPtr(Sym)];
3159
3160 assert(((Entry.getFlags().hasMaterializationSideEffectsOnly() &&
3161 Entry.getState() == SymbolState::Materializing) ||
3162 Entry.getState() == SymbolState::Resolved ||
3163 Entry.getState() == SymbolState::Emitted) &&
3164 "Emitting from state other than Resolved");
3165
3166 if (Entry.getState() == SymbolState::Emitted) {
3167 // This was already emitted, so we can skip the rest of this loop.
3168#ifndef NDEBUG
3169 for (auto &[Sym, Flags] : EDU->Symbols) {
3170 assert(JD.Symbols.count(SymbolStringPtr(Sym)) &&
3171 "JD does not have an entry for Sym");
3172 auto &Entry = JD.Symbols[SymbolStringPtr(Sym)];
3173 assert(Entry.getState() == SymbolState::Emitted &&
3174 "Symbols for EDU in inconsistent state");
3175 assert(JD.MaterializingInfos.count(SymbolStringPtr(Sym)) &&
3176 "Emitted symbol has no MI");
3177 auto MI = JD.MaterializingInfos[SymbolStringPtr(Sym)];
3178 assert(MI.takeQueriesMeeting(SymbolState::Emitted).empty() &&
3179 "Already-emitted symbol has waiting-on-emitted queries");
3180 }
3181#endif // NDEBUG
3182 break;
3183 }
3184
3185 Entry.setState(SymbolState::Emitted);
3186 auto &MI = JD.MaterializingInfos[SymbolStringPtr(Sym)];
3187 MI.DefiningEDU = EDU;
3188
3189 for (auto &Q : MI.takeQueriesMeeting(SymbolState::Emitted)) {
3190 Q->notifySymbolMetRequiredState(SymbolStringPtr(Sym), Entry.getSymbol());
3191 if (Q->isComplete())
3192 Queries.insert(Q);
3193 }
3194 }
3195
3196 for (auto &[DepJD, Deps] : EDU->Dependencies) {
3197 for (auto &Dep : Deps)
3198 DepJD->MaterializingInfos[SymbolStringPtr(Dep)].DependantEDUs.insert(
3199 EDU.get());
3200 }
3201}
3202
3203/// Removes the given dependence from EDU. If EDU's dependence set becomes
3204/// empty then this function adds an entry for it to the EDUInfos map.
3205/// Returns true if a new EDUInfosMap entry is added.
3206bool ExecutionSession::IL_removeEDUDependence(JITDylib::EmissionDepUnit &EDU,
3207 JITDylib &DepJD,
3208 NonOwningSymbolStringPtr DepSym,
3209 EDUInfosMap &EDUInfos) {
3210 assert(EDU.Dependencies.count(&DepJD) &&
3211 "JD does not appear in Dependencies of DependantEDU");
3212 assert(EDU.Dependencies[&DepJD].count(DepSym) &&
3213 "Symbol does not appear in Dependencies of DependantEDU");
3214 auto &JDDeps = EDU.Dependencies[&DepJD];
3215 JDDeps.erase(DepSym);
3216 if (JDDeps.empty()) {
3217 EDU.Dependencies.erase(&DepJD);
3218 if (EDU.Dependencies.empty()) {
3219 // If the dependencies set has become empty then EDU _may_ be ready
3220 // (we won't know for sure until we've propagated the extra-emit deps).
3221 // Create an EDUInfo for it (if it doesn't have one already) so that
3222 // it'll be visited after propagation.
3223 auto &DepEDUInfo = EDUInfos[&EDU];
3224 if (!DepEDUInfo.EDU) {
3225 assert(EDU.JD->Symbols.count(
3226 SymbolStringPtr(EDU.Symbols.begin()->first)) &&
3227 "Missing symbol entry for first symbol in EDU");
3228 auto DepEDUFirstMI = EDU.JD->MaterializingInfos.find(
3229 SymbolStringPtr(EDU.Symbols.begin()->first));
3230 assert(DepEDUFirstMI != EDU.JD->MaterializingInfos.end() &&
3231 "Missing MI for first symbol in DependantEDU");
3232 DepEDUInfo.EDU = DepEDUFirstMI->second.DefiningEDU;
3233 return true;
3234 }
3235 }
3236 }
3237 return false;
3238}
3239
3240Error ExecutionSession::makeJDClosedError(JITDylib::EmissionDepUnit &EDU,
3241 JITDylib &ClosedJD) {
3242 SymbolNameSet FailedSymbols;
3243 for (auto &[Sym, Flags] : EDU.Symbols)
3244 FailedSymbols.insert(SymbolStringPtr(Sym));
3245 SymbolDependenceMap BadDeps;
3246 for (auto &Dep : EDU.Dependencies[&ClosedJD])
3247 BadDeps[&ClosedJD].insert(SymbolStringPtr(Dep));
3248 return make_error<UnsatisfiedSymbolDependencies>(
3249 ClosedJD.getExecutionSession().getSymbolStringPool(), EDU.JD,
3250 std::move(FailedSymbols), std::move(BadDeps),
3251 ClosedJD.getName() + " is closed");
3252}
3253
3254Error ExecutionSession::makeUnsatisfiedDepsError(JITDylib::EmissionDepUnit &EDU,
3255 JITDylib &BadJD,
3256 SymbolNameSet BadDeps) {
3257 SymbolNameSet FailedSymbols;
3258 for (auto &[Sym, Flags] : EDU.Symbols)
3259 FailedSymbols.insert(SymbolStringPtr(Sym));
3260 SymbolDependenceMap BadDepsMap;
3261 BadDepsMap[&BadJD] = std::move(BadDeps);
3262 return make_error<UnsatisfiedSymbolDependencies>(
3263 BadJD.getExecutionSession().getSymbolStringPool(), &BadJD,
3264 std::move(FailedSymbols), std::move(BadDepsMap),
3265 "dependencies removed or in error state");
3266}
3267
3268Expected<JITDylib::AsynchronousSymbolQuerySet>
3269ExecutionSession::IL_emit(MaterializationResponsibility &MR,
3270 EDUInfosMap EDUInfos) {
3271
3272 if (MR.RT->isDefunct())
3273 return make_error<ResourceTrackerDefunct>(MR.RT);
3274
3275 auto &TargetJD = MR.getTargetJITDylib();
3276 if (TargetJD.State != JITDylib::Open)
3277 return make_error<StringError>("JITDylib " + TargetJD.getName() +
3278 " is defunct",
3280#ifdef EXPENSIVE_CHECKS
3281 verifySessionState("entering ExecutionSession::IL_emit");
3282#endif
3283
3284 // Walk all EDUs:
3285 // 1. Verifying that dependencies are available (not removed or in the error
3286 // state.
3287 // 2. Removing any dependencies that are already Ready.
3288 // 3. Lifting any EDUs for Emitted symbols into the EDUInfos map.
3289 // 4. Finding any dependant EDUs and lifting them into the EDUInfos map.
3290 std::deque<JITDylib::EmissionDepUnit *> Worklist;
3291 for (auto &[EDU, _] : EDUInfos)
3292 Worklist.push_back(EDU);
3293
3294 for (auto *EDU : Worklist) {
3295 auto *EDUInfo = &EDUInfos[EDU];
3296
3297 SmallVector<JITDylib *> DepJDsToRemove;
3298 for (auto &[DepJD, Deps] : EDU->Dependencies) {
3299 if (DepJD->State != JITDylib::Open)
3300 return makeJDClosedError(*EDU, *DepJD);
3301
3302 SymbolNameSet BadDeps;
3303 SmallVector<NonOwningSymbolStringPtr> DepsToRemove;
3304 for (auto &Dep : Deps) {
3305 auto DepEntryItr = DepJD->Symbols.find(SymbolStringPtr(Dep));
3306
3307 // If this dep has been removed or moved to the error state then add it
3308 // to the bad deps set. We aggregate these bad deps for more
3309 // comprehensive error messages.
3310 if (DepEntryItr == DepJD->Symbols.end() ||
3311 DepEntryItr->second.getFlags().hasError()) {
3312 BadDeps.insert(SymbolStringPtr(Dep));
3313 continue;
3314 }
3315
3316 // If this dep isn't emitted yet then just add it to the NewDeps set to
3317 // be propagated.
3318 auto &DepEntry = DepEntryItr->second;
3319 if (DepEntry.getState() < SymbolState::Emitted) {
3320 EDUInfo->NewDeps[DepJD].insert(Dep);
3321 continue;
3322 }
3323
3324 // This dep has been emitted, so add it to the list to be removed from
3325 // EDU.
3326 DepsToRemove.push_back(Dep);
3327
3328 // If Dep is Ready then there's nothing further to do.
3329 if (DepEntry.getState() == SymbolState::Ready) {
3330 assert(!DepJD->MaterializingInfos.count(SymbolStringPtr(Dep)) &&
3331 "Unexpected MaterializationInfo attached to ready symbol");
3332 continue;
3333 }
3334
3335 // If we get here then Dep is Emitted. We need to look up its defining
3336 // EDU and add this EDU to the defining EDU's list of users (this means
3337 // creating an EDUInfos entry if the defining EDU doesn't have one
3338 // already).
3339 assert(DepJD->MaterializingInfos.count(SymbolStringPtr(Dep)) &&
3340 "Expected MaterializationInfo for emitted dependency");
3341 auto &DepMI = DepJD->MaterializingInfos[SymbolStringPtr(Dep)];
3342 assert(DepMI.DefiningEDU &&
3343 "Emitted symbol does not have a defining EDU");
3344 assert(DepMI.DependantEDUs.empty() &&
3345 "Already-emitted symbol has dependant EDUs?");
3346 auto &DepEDUInfo = EDUInfos[DepMI.DefiningEDU.get()];
3347 if (!DepEDUInfo.EDU) {
3348 // No EDUInfo yet -- build initial entry, and reset the EDUInfo
3349 // pointer, which we will have invalidated.
3350 EDUInfo = &EDUInfos[EDU];
3351 DepEDUInfo.EDU = DepMI.DefiningEDU;
3352 for (auto &[DepDepJD, DepDeps] : DepEDUInfo.EDU->Dependencies) {
3353 if (DepDepJD == &TargetJD) {
3354 for (auto &DepDep : DepDeps)
3355 if (!MR.getSymbols().count(SymbolStringPtr(DepDep)))
3356 DepEDUInfo.NewDeps[DepDepJD].insert(DepDep);
3357 } else
3358 DepEDUInfo.NewDeps[DepDepJD] = DepDeps;
3359 }
3360 }
3361 DepEDUInfo.IntraEmitUsers.insert(EDU);
3362 }
3363
3364 // Some dependencies were removed or in an error state -- error out.
3365 if (!BadDeps.empty())
3366 return makeUnsatisfiedDepsError(*EDU, *DepJD, std::move(BadDeps));
3367
3368 // Remove the emitted / ready deps from DepJD.
3369 for (auto &Dep : DepsToRemove)
3370 Deps.erase(Dep);
3371
3372 // If there are no further deps in DepJD then flag it for removal too.
3373 if (Deps.empty())
3374 DepJDsToRemove.push_back(DepJD);
3375 }
3376
3377 // Remove any JDs whose dependence sets have become empty.
3378 for (auto &DepJD : DepJDsToRemove) {
3379 assert(EDU->Dependencies.count(DepJD) &&
3380 "Trying to remove non-existent dep entries");
3381 EDU->Dependencies.erase(DepJD);
3382 }
3383
3384 // Now look for users of this EDU.
3385 for (auto &[Sym, Flags] : EDU->Symbols) {
3386 assert(TargetJD.Symbols.count(SymbolStringPtr(Sym)) &&
3387 "Sym not present in symbol table");
3388 assert((TargetJD.Symbols[SymbolStringPtr(Sym)].getState() ==
3390 TargetJD.Symbols[SymbolStringPtr(Sym)]
3391 .getFlags()
3392 .hasMaterializationSideEffectsOnly()) &&
3393 "Emitting symbol not in the resolved state");
3394 assert(!TargetJD.Symbols[SymbolStringPtr(Sym)].getFlags().hasError() &&
3395 "Symbol is already in an error state");
3396
3397 auto MII = TargetJD.MaterializingInfos.find(SymbolStringPtr(Sym));
3398 if (MII == TargetJD.MaterializingInfos.end() ||
3399 MII->second.DependantEDUs.empty())
3400 continue;
3401
3402 for (auto &DependantEDU : MII->second.DependantEDUs) {
3403 if (IL_removeEDUDependence(*DependantEDU, TargetJD, Sym, EDUInfos))
3404 EDUInfo = &EDUInfos[EDU];
3405 EDUInfo->IntraEmitUsers.insert(DependantEDU);
3406 }
3407 MII->second.DependantEDUs.clear();
3408 }
3409 }
3410
3411 Worklist.clear();
3412 for (auto &[EDU, EDUInfo] : EDUInfos) {
3413 if (!EDUInfo.IntraEmitUsers.empty() && !EDU->Dependencies.empty()) {
3414 if (EDUInfo.NewDeps.empty())
3415 EDUInfo.NewDeps = EDU->Dependencies;
3416 Worklist.push_back(EDU);
3417 }
3418 }
3419
3420 propagateExtraEmitDeps(
3421 Worklist, EDUInfos,
3422 [](JITDylib::EmissionDepUnit &EDU, JITDylib &JD,
3423 NonOwningSymbolStringPtr Sym) {
3424 JD.MaterializingInfos[SymbolStringPtr(Sym)].DependantEDUs.insert(&EDU);
3425 });
3426
3427 JITDylib::AsynchronousSymbolQuerySet CompletedQueries;
3428
3429 // Extract completed queries and lodge not-yet-ready EDUs in the
3430 // session.
3431 for (auto &[EDU, EDUInfo] : EDUInfos) {
3432 if (EDU->Dependencies.empty())
3433 IL_makeEDUReady(std::move(EDUInfo.EDU), CompletedQueries);
3434 else
3435 IL_makeEDUEmitted(std::move(EDUInfo.EDU), CompletedQueries);
3436 }
3437
3438#ifdef EXPENSIVE_CHECKS
3439 verifySessionState("exiting ExecutionSession::IL_emit");
3440#endif
3441
3442 return std::move(CompletedQueries);
3443}
3444
3445Error ExecutionSession::OL_notifyEmitted(
3446 MaterializationResponsibility &MR,
3447 ArrayRef<SymbolDependenceGroup> DepGroups) {
3448 LLVM_DEBUG({
3449 dbgs() << "In " << MR.JD.getName() << " emitting " << MR.SymbolFlags
3450 << "\n";
3451 if (!DepGroups.empty()) {
3452 dbgs() << " Initial dependencies:\n";
3453 for (auto &SDG : DepGroups) {
3454 dbgs() << " Symbols: " << SDG.Symbols
3455 << ", Dependencies: " << SDG.Dependencies << "\n";
3456 }
3457 }
3458 });
3459
3460#ifndef NDEBUG
3461 SymbolNameSet Visited;
3462 for (auto &DG : DepGroups) {
3463 for (auto &Sym : DG.Symbols) {
3464 assert(MR.SymbolFlags.count(Sym) &&
3465 "DG contains dependence for symbol outside this MR");
3466 assert(Visited.insert(Sym).second &&
3467 "DG contains duplicate entries for Name");
3468 }
3469 }
3470#endif // NDEBUG
3471
3472 auto EDUInfos = simplifyDepGroups(MR, DepGroups);
3473
3474 LLVM_DEBUG({
3475 dbgs() << " Simplified dependencies:\n";
3476 for (auto &[EDU, EDUInfo] : EDUInfos) {
3477 dbgs() << " Symbols: { ";
3478 for (auto &[Sym, Flags] : EDU->Symbols)
3479 dbgs() << Sym << " ";
3480 dbgs() << "}, Dependencies: { ";
3481 for (auto &[DepJD, Deps] : EDU->Dependencies) {
3482 dbgs() << "(" << DepJD->getName() << ", { ";
3483 for (auto &Dep : Deps)
3484 dbgs() << Dep << " ";
3485 dbgs() << "}) ";
3486 }
3487 dbgs() << "}\n";
3488 }
3489 });
3490
3491 auto CompletedQueries =
3492 runSessionLocked([&]() { return IL_emit(MR, EDUInfos); });
3493
3494 // On error bail out.
3495 if (!CompletedQueries)
3496 return CompletedQueries.takeError();
3497
3498 MR.SymbolFlags.clear();
3499
3500 // Otherwise notify all the completed queries.
3501 for (auto &Q : *CompletedQueries) {
3502 assert(Q->isComplete() && "Q is not complete");
3503 Q->handleComplete(*this);
3504 }
3505
3506 return Error::success();
3507}
3508
3509Error ExecutionSession::OL_defineMaterializing(
3510 MaterializationResponsibility &MR, SymbolFlagsMap NewSymbolFlags) {
3511
3512 LLVM_DEBUG({
3513 dbgs() << "In " << MR.JD.getName() << " defining materializing symbols "
3514 << NewSymbolFlags << "\n";
3515 });
3516 if (auto AcceptedDefs =
3517 MR.JD.defineMaterializing(MR, std::move(NewSymbolFlags))) {
3518 // Add all newly accepted symbols to this responsibility object.
3519 for (auto &KV : *AcceptedDefs)
3520 MR.SymbolFlags.insert(KV);
3521 return Error::success();
3522 } else
3523 return AcceptedDefs.takeError();
3524}
3525
3526std::pair<JITDylib::AsynchronousSymbolQuerySet,
3527 std::shared_ptr<SymbolDependenceMap>>
3528ExecutionSession::IL_failSymbols(JITDylib &JD,
3529 const SymbolNameVector &SymbolsToFail) {
3530
3531#ifdef EXPENSIVE_CHECKS
3532 verifySessionState("entering ExecutionSession::IL_failSymbols");
3533#endif
3534
3535 JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3536 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
3537 auto ExtractFailedQueries = [&](JITDylib::MaterializingInfo &MI) {
3538 JITDylib::AsynchronousSymbolQueryList ToDetach;
3539 for (auto &Q : MI.pendingQueries()) {
3540 // Add the query to the list to be failed and detach it.
3541 FailedQueries.insert(Q);
3542 ToDetach.push_back(Q);
3543 }
3544 for (auto &Q : ToDetach)
3545 Q->detach();
3546 assert(!MI.hasQueriesPending() && "Queries still pending after detach");
3547 };
3548
3549 for (auto &Name : SymbolsToFail) {
3550 (*FailedSymbolsMap)[&JD].insert(Name);
3551
3552 // Look up the symbol to fail.
3553 auto SymI = JD.Symbols.find(Name);
3554
3555 // FIXME: Revisit this. We should be able to assert sequencing between
3556 // ResourceTracker removal and symbol failure.
3557 //
3558 // It's possible that this symbol has already been removed, e.g. if a
3559 // materialization failure happens concurrently with a ResourceTracker or
3560 // JITDylib removal. In that case we can safely skip this symbol and
3561 // continue.
3562 if (SymI == JD.Symbols.end())
3563 continue;
3564 auto &Sym = SymI->second;
3565
3566 // If the symbol is already in the error state then we must have visited
3567 // it earlier.
3568 if (Sym.getFlags().hasError()) {
3569 assert(!JD.MaterializingInfos.count(Name) &&
3570 "Symbol in error state still has MaterializingInfo");
3571 continue;
3572 }
3573
3574 // Move the symbol into the error state.
3575 Sym.setFlags(Sym.getFlags() | JITSymbolFlags::HasError);
3576
3577 // FIXME: Come up with a sane mapping of state to
3578 // presence-of-MaterializingInfo so that we can assert presence / absence
3579 // here, rather than testing it.
3580 auto MII = JD.MaterializingInfos.find(Name);
3581 if (MII == JD.MaterializingInfos.end())
3582 continue;
3583
3584 auto &MI = MII->second;
3585
3586 // Collect queries to be failed for this MII.
3587 ExtractFailedQueries(MI);
3588
3589 if (MI.DefiningEDU) {
3590 // If there is a DefiningEDU for this symbol then remove this
3591 // symbol from it.
3592 assert(MI.DependantEDUs.empty() &&
3593 "Symbol with DefiningEDU should not have DependantEDUs");
3594 assert(Sym.getState() >= SymbolState::Emitted &&
3595 "Symbol has EDU, should have been emitted");
3596 assert(MI.DefiningEDU->Symbols.count(NonOwningSymbolStringPtr(Name)) &&
3597 "Symbol does not appear in its DefiningEDU");
3598 MI.DefiningEDU->Symbols.erase(NonOwningSymbolStringPtr(Name));
3599
3600 // Remove this EDU from the dependants lists of its dependencies.
3601 for (auto &[DepJD, DepSyms] : MI.DefiningEDU->Dependencies) {
3602 for (auto DepSym : DepSyms) {
3603 assert(DepJD->Symbols.count(SymbolStringPtr(DepSym)) &&
3604 "DepSym not in DepJD");
3605 assert(DepJD->MaterializingInfos.count(SymbolStringPtr(DepSym)) &&
3606 "DepSym has not MaterializingInfo");
3607 auto &SymMI = DepJD->MaterializingInfos[SymbolStringPtr(DepSym)];
3608 assert(SymMI.DependantEDUs.count(MI.DefiningEDU.get()) &&
3609 "DefiningEDU missing from DependantEDUs list of dependency");
3610 SymMI.DependantEDUs.erase(MI.DefiningEDU.get());
3611 }
3612 }
3613
3614 MI.DefiningEDU = nullptr;
3615 } else {
3616 // Otherwise if there are any EDUs waiting on this symbol then move
3617 // those symbols to the error state too, and deregister them from the
3618 // symbols that they depend on.
3619 // Note: We use a copy of DependantEDUs here since we'll be removing
3620 // from the original set as we go.
3621 for (auto &DependantEDU : MI.DependantEDUs) {
3622
3623 // Remove DependantEDU from all of its users DependantEDUs lists.
3624 for (auto &[DepJD, DepSyms] : DependantEDU->Dependencies) {
3625 for (auto DepSym : DepSyms) {
3626 // Skip self-reference to avoid invalidating the MI.DependantEDUs
3627 // map. We'll clear this later.
3628 if (DepJD == &JD && DepSym == Name)
3629 continue;
3630 assert(DepJD->Symbols.count(SymbolStringPtr(DepSym)) &&
3631 "DepSym not in DepJD?");
3632 assert(DepJD->MaterializingInfos.count(SymbolStringPtr(DepSym)) &&
3633 "DependantEDU not registered with symbol it depends on");
3634 auto &SymMI = DepJD->MaterializingInfos[SymbolStringPtr(DepSym)];
3635 assert(SymMI.DependantEDUs.count(DependantEDU) &&
3636 "DependantEDU missing from DependantEDUs list");
3637 SymMI.DependantEDUs.erase(DependantEDU);
3638 }
3639 }
3640
3641 // Move any symbols defined by DependantEDU into the error state and
3642 // fail any queries waiting on them.
3643 auto &DepJD = *DependantEDU->JD;
3644 auto DepEDUSymbols = std::move(DependantEDU->Symbols);
3645 for (auto &[DepName, Flags] : DepEDUSymbols) {
3646 auto DepSymItr = DepJD.Symbols.find(SymbolStringPtr(DepName));
3647 assert(DepSymItr != DepJD.Symbols.end() &&
3648 "Symbol not present in table");
3649 auto &DepSym = DepSymItr->second;
3650
3651 assert(DepSym.getState() >= SymbolState::Emitted &&
3652 "Symbol has EDU, should have been emitted");
3653 assert(!DepSym.getFlags().hasError() &&
3654 "Symbol is already in the error state?");
3655 DepSym.setFlags(DepSym.getFlags() | JITSymbolFlags::HasError);
3656 (*FailedSymbolsMap)[&DepJD].insert(SymbolStringPtr(DepName));
3657
3658 // This symbol has a defining EDU so its MaterializingInfo object must
3659 // exist.
3660 auto DepMIItr =
3661 DepJD.MaterializingInfos.find(SymbolStringPtr(DepName));
3662 assert(DepMIItr != DepJD.MaterializingInfos.end() &&
3663 "Symbol has defining EDU but not MaterializingInfo");
3664 auto &DepMI = DepMIItr->second;
3665 assert(DepMI.DefiningEDU.get() == DependantEDU &&
3666 "Bad EDU dependence edge");
3667 assert(DepMI.DependantEDUs.empty() &&
3668 "Symbol was emitted, should not have any DependantEDUs");
3669 ExtractFailedQueries(DepMI);
3670 DepJD.MaterializingInfos.erase(SymbolStringPtr(DepName));
3671 }
3672
3673 DepJD.shrinkMaterializationInfoMemory();
3674 }
3675
3676 MI.DependantEDUs.clear();
3677 }
3678
3679 assert(!MI.DefiningEDU && "DefiningEDU should have been reset");
3680 assert(MI.DependantEDUs.empty() &&
3681 "DependantEDUs should have been removed above");
3682 assert(!MI.hasQueriesPending() &&
3683 "Can not delete MaterializingInfo with queries pending");
3684 JD.MaterializingInfos.erase(Name);
3685 }
3686
3687 JD.shrinkMaterializationInfoMemory();
3688
3689#ifdef EXPENSIVE_CHECKS
3690 verifySessionState("exiting ExecutionSession::IL_failSymbols");
3691#endif
3692
3693 return std::make_pair(std::move(FailedQueries), std::move(FailedSymbolsMap));
3694}
3695
3696void ExecutionSession::OL_notifyFailed(MaterializationResponsibility &MR) {
3697
3698 LLVM_DEBUG({
3699 dbgs() << "In " << MR.JD.getName() << " failing materialization for "
3700 << MR.SymbolFlags << "\n";
3701 });
3702
3703 if (MR.SymbolFlags.empty())
3704 return;
3705
3706 SymbolNameVector SymbolsToFail;
3707 for (auto &[Name, Flags] : MR.SymbolFlags)
3708 SymbolsToFail.push_back(Name);
3709 MR.SymbolFlags.clear();
3710
3711 JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3712 std::shared_ptr<SymbolDependenceMap> FailedSymbols;
3713
3714 std::tie(FailedQueries, FailedSymbols) = runSessionLocked([&]() {
3715 // If the tracker is defunct then there's nothing to do here.
3716 if (MR.RT->isDefunct())
3717 return std::pair<JITDylib::AsynchronousSymbolQuerySet,
3718 std::shared_ptr<SymbolDependenceMap>>();
3719 return IL_failSymbols(MR.getTargetJITDylib(), SymbolsToFail);
3720 });
3721
3722 for (auto &Q : FailedQueries)
3723 Q->handleFailed(
3724 make_error<FailedToMaterialize>(getSymbolStringPool(), FailedSymbols));
3725}
3726
3727Error ExecutionSession::OL_replace(MaterializationResponsibility &MR,
3728 std::unique_ptr<MaterializationUnit> MU) {
3729 for (auto &KV : MU->getSymbols()) {
3730 assert(MR.SymbolFlags.count(KV.first) &&
3731 "Replacing definition outside this responsibility set");
3732 MR.SymbolFlags.erase(KV.first);
3733 }
3734
3735 if (MU->getInitializerSymbol() == MR.InitSymbol)
3736 MR.InitSymbol = nullptr;
3737
3738 LLVM_DEBUG(MR.JD.getExecutionSession().runSessionLocked([&]() {
3739 dbgs() << "In " << MR.JD.getName() << " replacing symbols with " << *MU
3740 << "\n";
3741 }););
3742
3743 return MR.JD.replace(MR, std::move(MU));
3744}
3745
3746Expected<std::unique_ptr<MaterializationResponsibility>>
3747ExecutionSession::OL_delegate(MaterializationResponsibility &MR,
3748 const SymbolNameSet &Symbols) {
3749
3750 SymbolStringPtr DelegatedInitSymbol;
3751 SymbolFlagsMap DelegatedFlags;
3752
3753 for (auto &Name : Symbols) {
3754 auto I = MR.SymbolFlags.find(Name);
3755 assert(I != MR.SymbolFlags.end() &&
3756 "Symbol is not tracked by this MaterializationResponsibility "
3757 "instance");
3758
3759 DelegatedFlags[Name] = std::move(I->second);
3760 if (Name == MR.InitSymbol)
3761 std::swap(MR.InitSymbol, DelegatedInitSymbol);
3762
3763 MR.SymbolFlags.erase(I);
3764 }
3765
3766 return MR.JD.delegate(MR, std::move(DelegatedFlags),
3767 std::move(DelegatedInitSymbol));
3768}
3769
3770#ifndef NDEBUG
3771void ExecutionSession::dumpDispatchInfo(Task &T) {
3772 runSessionLocked([&]() {
3773 dbgs() << "Dispatching: ";
3774 T.printDescription(dbgs());
3775 dbgs() << "\n";
3776 });
3777}
3778#endif // NDEBUG
3779
3780} // End namespace orc.
3781} // End namespace llvm.
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
aarch64 falkor hwpf fix Falkor HW Prefetch Fix Late Phase
#define LLVM_DEBUG(...)
Definition: Debug.h:106
uint64_t Addr
std::string Name
Symbol * Sym
Definition: ELF_riscv.cpp:479
#define _
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
#define H(x, y, z)
Definition: MD5.cpp:57
while(!ToSimplify.empty())
if(PassOpts->AAPipeline)
static StringRef getName(Value *V)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
static uint32_t getFlags(const Symbol *Sym)
Definition: TapiFile.cpp:26
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
const T & front() const
front - Get the first element.
Definition: ArrayRef.h:171
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:168
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:163
const T * data() const
Definition: ArrayRef.h:165
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:156
bool erase(const KeyT &Val)
Definition: DenseMap.h:321
unsigned size() const
Definition: DenseMap.h:99
bool empty() const
Definition: DenseMap.h:98
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:152
iterator end()
Definition: DenseMap.h:84
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:211
Helper for Errors used as out-parameters.
Definition: Error.h:1130
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
Symbol info for RuntimeDyld.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:213
iterator find(const_arg_type_t< ValueT > V)
Definition: DenseSet.h:187
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:95
AsynchronousSymbolQuery(const SymbolLookupSet &Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete)
Create a query for the given symbols.
Definition: Core.cpp:202
void notifySymbolMetRequiredState(const SymbolStringPtr &Name, ExecutorSymbolDef Sym)
Notify the query that a requested symbol has reached the required state.
Definition: Core.cpp:216
Definition generators can be attached to JITDylibs to generate new definitions for otherwise unresolv...
Definition: Core.h:854
An ExecutionSession represents a running JIT program.
Definition: Core.h:1339
Error endSession()
End the session.
Definition: Core.cpp:1602
void reportError(Error Err)
Report a error for this execution session.
Definition: Core.h:1474
friend class JITDylib
Definition: Core.h:1342
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.
Definition: Core.cpp:1762
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition: Core.h:1393
JITDylib * getJITDylibByName(StringRef Name)
Return a pointer to the "name" JITDylib.
Definition: Core.cpp:1641
friend class LookupState
Definition: Core.h:1343
JITDylib & createBareJITDylib(std::string Name)
Add a new bare JITDylib to this ExecutionSession.
Definition: Core.cpp:1650
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
Definition: Core.h:1388
void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete, RegisterDependenciesFunction RegisterDependencies)
Search the given JITDylibs for the given symbols.
Definition: Core.cpp:1788
Error registerJITDispatchHandlers(JITDylib &JD, JITDispatchHandlerAssociationMap WFs)
For each tag symbol name, associate the corresponding AsyncHandlerWrapperFunction with the address of...
Definition: Core.cpp:1897
void registerResourceManager(ResourceManager &RM)
Register the given ResourceManager with this ExecutionSession.
Definition: Core.cpp:1624
~ExecutionSession()
Destroy an ExecutionSession.
Definition: Core.cpp:1596
void runJITDispatchHandler(SendResultFunction SendResult, ExecutorAddr HandlerFnTagAddr, ArrayRef< char > ArgBuffer)
Run a registered jit-side wrapper function.
Definition: Core.cpp:1936
void deregisterResourceManager(ResourceManager &RM)
Deregister the given ResourceManager with this ExecutionSession.
Definition: Core.cpp:1628
ExecutionSession(std::unique_ptr< ExecutorProcessControl > EPC)
Construct an ExecutionSession with the given ExecutorProcessControl object.
Definition: Core.cpp:1590
decltype(auto) runSessionLocked(Func &&F)
Run the given lambda with the session mutex locked.
Definition: Core.h:1403
void dump(raw_ostream &OS)
Dump the state of all the JITDylibs in this session.
Definition: Core.cpp:1957
Error removeJITDylibs(std::vector< JITDylibSP > JDsToRemove)
Removes the given JITDylibs from the ExecutionSession.
Definition: Core.cpp:1667
Expected< JITDylib & > createJITDylib(std::string Name)
Add a new JITDylib to this ExecutionSession.
Definition: Core.cpp:1659
void dispatchTask(std::unique_ptr< Task > T)
Materialize the given unit.
Definition: Core.h:1547
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)
Definition: Core.cpp:82
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Core.cpp:100
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Core.cpp:104
InProgressFullLookupState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, SymbolState RequiredState, std::shared_ptr< AsynchronousSymbolQuery > Q, RegisterDependenciesFunction RegisterDependencies)
Definition: Core.cpp:566
void complete(std::unique_ptr< InProgressLookupState > IPLS) override
Definition: Core.cpp:576
void fail(Error Err) override
Definition: Core.cpp:582
void complete(std::unique_ptr< InProgressLookupState > IPLS) override
Definition: Core.cpp:553
void fail(Error Err) override
Definition: Core.cpp:558
InProgressLookupFlagsState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, unique_function< void(Expected< SymbolFlagsMap >)> OnComplete)
Definition: Core.cpp:546
virtual ~InProgressLookupState()=default
SymbolLookupSet DefGeneratorCandidates
Definition: Core.cpp:533
JITDylibSearchOrder SearchOrder
Definition: Core.cpp:527
std::vector< std::weak_ptr< DefinitionGenerator > > CurDefGeneratorStack
Definition: Core.cpp:541
SymbolLookupSet LookupSet
Definition: Core.cpp:528
virtual void complete(std::unique_ptr< InProgressLookupState > IPLS)=0
InProgressLookupState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, SymbolState RequiredState)
Definition: Core.cpp:516
SymbolLookupSet DefGeneratorNonCandidates
Definition: Core.cpp:534
virtual void fail(Error Err)=0
enum llvm::orc::InProgressLookupState::@503 GenState
Represents a JIT'd dynamic library.
Definition: Core.h:897
Error clear()
Calls remove on all trackers currently associated with this JITDylib.
Definition: Core.cpp:657
Error define(std::unique_ptr< MaterializationUnitType > &&MU, ResourceTrackerSP RT=nullptr)
Define all symbols provided by the materialization unit to be part of this JITDylib.
Definition: Core.h:1822
ExecutionSession & getExecutionSession() const
Get a reference to the ExecutionSession for this JITDylib.
Definition: Core.h:916
ResourceTrackerSP createResourceTracker()
Create a resource tracker for this JITDylib.
Definition: Core.cpp:681
Expected< std::vector< JITDylibSP > > getReverseDFSLinkOrder()
Rteurn this JITDylib and its transitive dependencies in reverse DFS order based on linkage relationsh...
Definition: Core.cpp:1758
ResourceTrackerSP getDefaultResourceTracker()
Get the default resource tracker for this JITDylib.
Definition: Core.cpp:672
void removeGenerator(DefinitionGenerator &G)
Remove a definition generator from this JITDylib.
Definition: Core.cpp:689
Expected< std::vector< JITDylibSP > > getDFSLinkOrder()
Return this JITDylib and its transitive dependencies in DFS order based on linkage relationships.
Definition: Core.cpp:1754
Wraps state for a lookup-in-progress.
Definition: Core.h:829
void continueLookup(Error Err)
Continue the lookup.
Definition: Core.cpp:633
LookupState & operator=(LookupState &&)
void run() override
Definition: Core.cpp:1588
static char ID
Definition: Core.h:1328
void printDescription(raw_ostream &OS) override
Definition: Core.cpp:1586
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
Definition: Core.h:571
void printDescription(raw_ostream &OS) override
Definition: Core.cpp:1579
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Core.cpp:163
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Core.cpp:167
Non-owning SymbolStringPool entry pointer.
static void lookupInitSymbolsAsync(unique_function< void(Error)> OnComplete, ExecutionSession &ES, const DenseMap< JITDylib *, SymbolLookupSet > &InitSyms)
Performs an async lookup for the given symbols in each of the given JITDylibs, calling the given hand...
Definition: Core.cpp:1536
static Expected< DenseMap< JITDylib *, SymbolMap > > lookupInitSymbols(ExecutionSession &ES, const DenseMap< JITDylib *, SymbolLookupSet > &InitSyms)
A utility function for looking up initializer symbols.
Definition: Core.cpp:1487
StringRef getName() const override
Return the name of this materialization unit.
Definition: Core.cpp:307
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...
Definition: Core.cpp:301
std::function< bool(SymbolStringPtr)> SymbolPredicate
Definition: Core.h:1911
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.
Definition: Core.cpp:598
ReexportsGenerator(JITDylib &SourceJD, JITDylibLookupFlags SourceJDLookupFlags, SymbolPredicate Allow=SymbolPredicate())
Create a reexports generator.
Definition: Core.cpp:592
Listens for ResourceTracker operations.
Definition: Core.h:125
ResourceTrackerDefunct(ResourceTrackerSP RT)
Definition: Core.cpp:71
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Core.cpp:78
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Core.cpp:74
API to remove / transfer ownership of JIT resources.
Definition: Core.h:77
JITDylib & getJITDylib() const
Return the JITDylib targeted by this tracker.
Definition: Core.h:92
void transferTo(ResourceTracker &DstRT)
Transfer all resources associated with this key to the given tracker, which must target the same JITD...
Definition: Core.cpp:59
ResourceTracker(const ResourceTracker &)=delete
Error remove()
Remove all resources associated with this key.
Definition: Core.cpp:55
void lookupAsync(LookupAsyncOnCompleteFn OnComplete) const
Definition: Core.cpp:181
A set of symbols to look up, each associated with a SymbolLookupFlags value.
Definition: Core.h:194
static SymbolLookupSet fromMapKeys(const DenseMap< SymbolStringPtr, ValT > &M, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Construct a SymbolLookupSet from DenseMap keys.
Definition: Core.h:248
Pointer to a pooled string representing a symbol name.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Core.cpp:155
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Core.cpp:159
SymbolsCouldNotBeRemoved(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
Definition: Core.cpp:149
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Core.cpp:145
SymbolsNotFound(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
Definition: Core.cpp:127
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Core.cpp:141
Represents an abstract task for ORC to run.
Definition: TaskDispatch.h:35
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Core.cpp:172
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Core.cpp:176
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Core.cpp:120
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Core.cpp:116
UnsatisfiedSymbolDependencies(std::shared_ptr< SymbolStringPool > SSP, JITDylibSP JD, SymbolNameSet FailedSymbols, SymbolDependenceMap BadDeps, std::string Explanation)
Definition: Core.cpp:108
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.
Definition: raw_ostream.h:460
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
unique_function is a type-erasing functor similar to std::function.
@ Entry
Definition: COFF.h:844
IntrusiveRefCntPtr< JITDylib > JITDylibSP
Definition: Core.h:52
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...
Definition: Core.h:177
std::vector< std::pair< JITDylib *, JITDylibLookupFlags > > JITDylibSearchOrder
A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search order during symbol lookup.
Definition: Core.h:173
std::function< void(const SymbolDependenceMap &)> RegisterDependenciesFunction
Callback to register the dependencies for a given query.
Definition: Core.h:419
std::unique_ptr< ReExportsMaterializationUnit > symbolAliases(SymbolAliasMap Aliases)
Create a ReExportsMaterializationUnit with the given aliases.
Definition: Core.h:745
SymbolLookupFlags
Lookup flags that apply to each symbol in a lookup.
Definition: Core.h:156
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...
Definition: Core.h:754
DenseMap< SymbolStringPtr, SymbolAliasMapEntry > SymbolAliasMap
A map of Symbols to (Symbol, Flags) pairs.
Definition: Core.h:412
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
Definition: Core.h:146
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.
Definition: Core.h:415
DenseSet< SymbolStringPtr > SymbolNameSet
A set of symbol names (represented by SymbolStringPtrs for.
LookupKind
Describes the kind of lookup being performed.
Definition: Core.h:168
RegisterDependenciesFunction NoDependenciesToRegister
This can be used as the value for a RegisterDependenciesFunction if there are no dependants to regist...
Definition: Core.cpp:38
std::vector< SymbolStringPtr > SymbolNameVector
A vector of symbol names.
SymbolState
Represents the state that a symbol has reached during materialization.
Definition: Core.h:767
@ 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)
Definition: OrcError.cpp:84
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.
Definition: AddressRanges.h:18
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1759
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2115
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:420
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition: Error.h:438
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:125
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...
Definition: STLExtras.h:1978
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1873
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1766
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1903
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
#define NDEBUG
Definition: regutils.h:48