xref: /llvm-project/llvm/lib/ExecutionEngine/Orc/Core.cpp (revision 212cdc9a377a1b3ac96be0da20212592ebd2c818)
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 
9 #include "llvm/ExecutionEngine/Orc/Core.h"
10 
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/Config/llvm-config.h"
13 #include "llvm/ExecutionEngine/Orc/DebugUtils.h"
14 #include "llvm/ExecutionEngine/Orc/Shared/OrcError.h"
15 #include "llvm/Support/FormatVariadic.h"
16 #include "llvm/Support/MSVCErrorWorkarounds.h"
17 #include "llvm/Support/raw_ostream.h"
18 
19 #include <condition_variable>
20 #include <future>
21 #include <optional>
22 
23 #define DEBUG_TYPE "orc"
24 
25 namespace llvm {
26 namespace orc {
27 
28 char ResourceTrackerDefunct::ID = 0;
29 char FailedToMaterialize::ID = 0;
30 char SymbolsNotFound::ID = 0;
31 char SymbolsCouldNotBeRemoved::ID = 0;
32 char MissingSymbolDefinitions::ID = 0;
33 char UnexpectedSymbolDefinitions::ID = 0;
34 char UnsatisfiedSymbolDependencies::ID = 0;
35 char MaterializationTask::ID = 0;
36 char LookupTask::ID = 0;
37 
38 RegisterDependenciesFunction NoDependenciesToRegister =
39     RegisterDependenciesFunction();
40 
41 void MaterializationUnit::anchor() {}
42 
43 ResourceTracker::ResourceTracker(JITDylibSP JD) {
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 
50 ResourceTracker::~ResourceTracker() {
51   getJITDylib().getExecutionSession().destroyResourceTracker(*this);
52   getJITDylib().Release();
53 }
54 
55 Error ResourceTracker::remove() {
56   return getJITDylib().getExecutionSession().removeResourceTracker(*this);
57 }
58 
59 void ResourceTracker::transferTo(ResourceTracker &DstRT) {
60   getJITDylib().getExecutionSession().transferResourceTracker(DstRT, *this);
61 }
62 
63 void ResourceTracker::makeDefunct() {
64   uintptr_t Val = JDAndFlag.load();
65   Val |= 0x1U;
66   JDAndFlag.store(Val);
67 }
68 
69 ResourceManager::~ResourceManager() = default;
70 
71 ResourceTrackerDefunct::ResourceTrackerDefunct(ResourceTrackerSP RT)
72     : RT(std::move(RT)) {}
73 
74 std::error_code ResourceTrackerDefunct::convertToErrorCode() const {
75   return orcError(OrcErrorCode::UnknownORCError);
76 }
77 
78 void ResourceTrackerDefunct::log(raw_ostream &OS) const {
79   OS << "Resource tracker " << (void *)RT.get() << " became defunct";
80 }
81 
82 FailedToMaterialize::FailedToMaterialize(
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 
95 FailedToMaterialize::~FailedToMaterialize() {
96   for (auto &[JD, Syms] : *Symbols)
97     JD->Release();
98 }
99 
100 std::error_code FailedToMaterialize::convertToErrorCode() const {
101   return orcError(OrcErrorCode::UnknownORCError);
102 }
103 
104 void FailedToMaterialize::log(raw_ostream &OS) const {
105   OS << "Failed to materialize symbols: " << *Symbols;
106 }
107 
108 UnsatisfiedSymbolDependencies::UnsatisfiedSymbolDependencies(
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 
116 std::error_code UnsatisfiedSymbolDependencies::convertToErrorCode() const {
117   return orcError(OrcErrorCode::UnknownORCError);
118 }
119 
120 void UnsatisfiedSymbolDependencies::log(raw_ostream &OS) const {
121   OS << "In " << JD->getName() << ", failed to materialize " << FailedSymbols
122      << ", due to unsatisfied dependencies " << BadDeps;
123   if (!Explanation.empty())
124     OS << " (" << Explanation << ")";
125 }
126 
127 SymbolsNotFound::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 
135 SymbolsNotFound::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 
141 std::error_code SymbolsNotFound::convertToErrorCode() const {
142   return orcError(OrcErrorCode::UnknownORCError);
143 }
144 
145 void SymbolsNotFound::log(raw_ostream &OS) const {
146   OS << "Symbols not found: " << Symbols;
147 }
148 
149 SymbolsCouldNotBeRemoved::SymbolsCouldNotBeRemoved(
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 
155 std::error_code SymbolsCouldNotBeRemoved::convertToErrorCode() const {
156   return orcError(OrcErrorCode::UnknownORCError);
157 }
158 
159 void SymbolsCouldNotBeRemoved::log(raw_ostream &OS) const {
160   OS << "Symbols could not be removed: " << Symbols;
161 }
162 
163 std::error_code MissingSymbolDefinitions::convertToErrorCode() const {
164   return orcError(OrcErrorCode::MissingSymbolDefinitions);
165 }
166 
167 void MissingSymbolDefinitions::log(raw_ostream &OS) const {
168   OS << "Missing definitions in module " << ModuleName
169      << ": " << Symbols;
170 }
171 
172 std::error_code UnexpectedSymbolDefinitions::convertToErrorCode() const {
173   return orcError(OrcErrorCode::UnexpectedSymbolDefinitions);
174 }
175 
176 void UnexpectedSymbolDefinitions::log(raw_ostream &OS) const {
177   OS << "Unexpected definitions in module " << ModuleName
178      << ": " << Symbols;
179 }
180 
181 void SymbolInstance::lookupAsync(LookupAsyncOnCompleteFn OnComplete) const {
182   JD->getExecutionSession().lookup(
183       LookupKind::Static, {{JD.get(), JITDylibLookupFlags::MatchAllSymbols}},
184       SymbolLookupSet(Name), SymbolState::Ready,
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       },
199       NoDependenciesToRegister);
200 }
201 
202 AsynchronousSymbolQuery::AsynchronousSymbolQuery(
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 
216 void AsynchronousSymbolQuery::notifySymbolMetRequiredState(
217     const SymbolStringPtr &Name, ExecutorSymbolDef Sym) {
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 
233 void 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 
259 void 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 
267 void 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 
274 void 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 
285 void 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 
293 void AsynchronousSymbolQuery::detach() {
294   ResolvedSymbols.clear();
295   OutstandingSymbolsCount = 0;
296   for (auto &[JD, Syms] : QueryRegistrations)
297     JD->detachQueryHelper(*this, Syms);
298   QueryRegistrations.clear();
299 }
300 
301 ReExportsMaterializationUnit::ReExportsMaterializationUnit(
302     JITDylib *SourceJD, JITDylibLookupFlags SourceJDLookupFlags,
303     SymbolAliasMap Aliases)
304     : MaterializationUnit(extractFlags(Aliases)), SourceJD(SourceJD),
305       SourceJDLookupFlags(SourceJDLookupFlags), Aliases(std::move(Aliases)) {}
306 
307 StringRef ReExportsMaterializationUnit::getName() const {
308   return "<Reexports>";
309 }
310 
311 void 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()
390                            ? SymbolLookupFlags::WeaklyReferencedSymbol
391                            : SymbolLookupFlags::RequiredSymbol);
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 
469     ES.lookup(LookupKind::Static,
470               JITDylibSearchOrder({{&SrcJD, SourceJDLookupFlags}}),
471               QuerySymbols, SymbolState::Resolved, std::move(OnComplete),
472               std::move(RegisterDependencies));
473   }
474 }
475 
476 void 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 
483 MaterializationUnit::Interface
484 ReExportsMaterializationUnit::extractFlags(const SymbolAliasMap &Aliases) {
485   SymbolFlagsMap SymbolFlags;
486   for (auto &KV : Aliases)
487     SymbolFlags[KV.first] = KV.second.AliasFlags;
488 
489   return MaterializationUnit::Interface(std::move(SymbolFlags), nullptr);
490 }
491 
492 Expected<SymbolAliasMap> buildSimpleReexportsAliasMap(JITDylib &SourceJD,
493                                                       SymbolNameSet Symbols) {
494   SymbolLookupSet LookupSet(Symbols);
495   auto Flags = SourceJD.getExecutionSession().lookupFlags(
496       LookupKind::Static, {{&SourceJD, JITDylibLookupFlags::MatchAllSymbols}},
497       SymbolLookupSet(std::move(Symbols)));
498 
499   if (!Flags)
500     return Flags.takeError();
501 
502   SymbolAliasMap Result;
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 
511 class InProgressLookupState {
512 public:
513   // FIXME: Reduce the number of SymbolStringPtrs here. See
514   //        https://github.com/llvm/llvm-project/issues/55576.
515 
516   InProgressLookupState(LookupKind K, JITDylibSearchOrder SearchOrder,
517                         SymbolLookupSet LookupSet, SymbolState RequiredState)
518       : K(K), SearchOrder(std::move(SearchOrder)),
519         LookupSet(std::move(LookupSet)), RequiredState(RequiredState) {
520     DefGeneratorCandidates = this->LookupSet;
521   }
522   virtual ~InProgressLookupState() = default;
523   virtual void complete(std::unique_ptr<InProgressLookupState> IPLS) = 0;
524   virtual void fail(Error Err) = 0;
525 
526   LookupKind K;
527   JITDylibSearchOrder SearchOrder;
528   SymbolLookupSet LookupSet;
529   SymbolState RequiredState;
530 
531   size_t CurSearchOrderIndex = 0;
532   bool NewJITDylib = true;
533   SymbolLookupSet DefGeneratorCandidates;
534   SymbolLookupSet DefGeneratorNonCandidates;
535 
536   enum {
537     NotInGenerator,      // Not currently using a generator.
538     ResumedForGenerator, // Resumed after being auto-suspended before generator.
539     InGenerator          // Currently using generator.
540   } GenState = NotInGenerator;
541   std::vector<std::weak_ptr<DefinitionGenerator>> CurDefGeneratorStack;
542 };
543 
544 class InProgressLookupFlagsState : public InProgressLookupState {
545 public:
546   InProgressLookupFlagsState(
547       LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet,
548       unique_function<void(Expected<SymbolFlagsMap>)> OnComplete)
549       : InProgressLookupState(K, std::move(SearchOrder), std::move(LookupSet),
550                               SymbolState::NeverSearched),
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 
560 private:
561   unique_function<void(Expected<SymbolFlagsMap>)> OnComplete;
562 };
563 
564 class InProgressFullLookupState : public InProgressLookupState {
565 public:
566   InProgressFullLookupState(LookupKind K, JITDylibSearchOrder SearchOrder,
567                             SymbolLookupSet LookupSet,
568                             SymbolState RequiredState,
569                             std::shared_ptr<AsynchronousSymbolQuery> Q,
570                             RegisterDependenciesFunction RegisterDependencies)
571       : InProgressLookupState(K, std::move(SearchOrder), std::move(LookupSet),
572                               RequiredState),
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 
587 private:
588   std::shared_ptr<AsynchronousSymbolQuery> Q;
589   RegisterDependenciesFunction RegisterDependencies;
590 };
591 
592 ReexportsGenerator::ReexportsGenerator(JITDylib &SourceJD,
593                                        JITDylibLookupFlags SourceJDLookupFlags,
594                                        SymbolPredicate Allow)
595     : SourceJD(SourceJD), SourceJDLookupFlags(SourceJDLookupFlags),
596       Allow(std::move(Allow)) {}
597 
598 Error ReexportsGenerator::tryToGenerate(LookupState &LS, LookupKind K,
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 
623 LookupState::LookupState(std::unique_ptr<InProgressLookupState> IPLS)
624     : IPLS(std::move(IPLS)) {}
625 
626 void LookupState::reset(InProgressLookupState *IPLS) { this->IPLS.reset(IPLS); }
627 
628 LookupState::LookupState() = default;
629 LookupState::LookupState(LookupState &&) = default;
630 LookupState &LookupState::operator=(LookupState &&) = default;
631 LookupState::~LookupState() = default;
632 
633 void LookupState::continueLookup(Error Err) {
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 
639 DefinitionGenerator::~DefinitionGenerator() {
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",
650         inconvertibleErrorCode()));
651 }
652 
653 JITDylib::~JITDylib() {
654   LLVM_DEBUG(dbgs() << "Destroying JITDylib " << getName() << "\n");
655 }
656 
657 Error JITDylib::clear() {
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 
672 ResourceTrackerSP JITDylib::getDefaultResourceTracker() {
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 
681 ResourceTrackerSP JITDylib::createResourceTracker() {
682   return ES.runSessionLocked([this] {
683     assert(State == Open && "JD is defunct");
684     ResourceTrackerSP RT = new ResourceTracker(this);
685     return RT;
686   });
687 }
688 
689 void JITDylib::removeGenerator(DefinitionGenerator &G) {
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 
706 Expected<SymbolFlagsMap>
707 JITDylib::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 
759 Error 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 
837 Expected<std::unique_ptr<MaterializationResponsibility>>
838 JITDylib::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 
851 SymbolNameSet
852 JITDylib::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 
875 Error 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 
981 void 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 
993 void 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 
1004 void 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 
1019 void 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 
1031 void JITDylib::addToLinkOrder(JITDylib &JD, JITDylibLookupFlags JDLookupFlags) {
1032   ES.runSessionLocked([&]() { LinkOrder.push_back({&JD, JDLookupFlags}); });
1033 }
1034 
1035 void 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 
1047 void 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 
1059 Error 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;
1066     SymbolNameSet Materializing;
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 
1120 void 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 
1213 void 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 
1224 void 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 
1235 JITDylib::AsynchronousSymbolQueryList
1236 JITDylib::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 
1249 JITDylib::JITDylib(ExecutionSession &ES, std::string Name)
1250     : JITLinkDylib(std::move(Name)), ES(ES) {
1251   LinkOrder.push_back({this, JITDylibLookupFlags::MatchAllSymbols});
1252 }
1253 
1254 std::pair<JITDylib::AsynchronousSymbolQuerySet,
1255           std::shared_ptr<SymbolDependenceMap>>
1256 JITDylib::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 
1319 void 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 
1394 Error 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 
1460 void 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 
1476 void 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 
1485 Platform::~Platform() = default;
1486 
1487 Expected<DenseMap<JITDylib *, SymbolMap>> Platform::lookupInitSymbols(
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(
1507         LookupKind::Static,
1508         JITDylibSearchOrder({{JD, JITDylibLookupFlags::MatchAllSymbols}}),
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         },
1524         NoDependenciesToRegister);
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 
1536 void Platform::lookupInitSymbolsAsync(
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(
1569         LookupKind::Static,
1570         JITDylibSearchOrder({{JD, JITDylibLookupFlags::MatchAllSymbols}}),
1571         std::move(Names), SymbolState::Ready,
1572         [TOC](Expected<SymbolMap> Result) {
1573           TOC->reportResult(Result.takeError());
1574         },
1575         NoDependenciesToRegister);
1576   }
1577 }
1578 
1579 MaterializationTask::~MaterializationTask() {
1580   // If this task wasn't run then fail materialization.
1581   if (MR)
1582     MR->failMaterialization();
1583 }
1584 
1585 void MaterializationTask::printDescription(raw_ostream &OS) {
1586   OS << "Materialization task: " << MU->getName() << " in "
1587      << MR->getTargetJITDylib().getName();
1588 }
1589 
1590 void MaterializationTask::run() {
1591   assert(MU && "MU should not be null");
1592   assert(MR && "MR should not be null");
1593   MU->materialize(std::move(MR));
1594 }
1595 
1596 void LookupTask::printDescription(raw_ostream &OS) { OS << "Lookup task"; }
1597 
1598 void LookupTask::run() { LS.continueLookup(Error::success()); }
1599 
1600 ExecutionSession::ExecutionSession(std::unique_ptr<ExecutorProcessControl> EPC)
1601     : EPC(std::move(EPC)) {
1602   // Associated EPC and this.
1603   this->EPC->ES = this;
1604 }
1605 
1606 ExecutionSession::~ExecutionSession() {
1607   // You must call endSession prior to destroying the session.
1608   assert(!SessionOpen &&
1609          "Session still open. Did you forget to call endSession?");
1610 }
1611 
1612 Error ExecutionSession::endSession() {
1613   LLVM_DEBUG(dbgs() << "Ending ExecutionSession " << this << "\n");
1614 
1615   auto JDsToRemove = runSessionLocked([&] {
1616 
1617 #ifdef EXPENSIVE_CHECKS
1618     verifySessionState("Entering ExecutionSession::endSession");
1619 #endif
1620 
1621     SessionOpen = false;
1622     return JDs;
1623   });
1624 
1625   std::reverse(JDsToRemove.begin(), JDsToRemove.end());
1626 
1627   auto Err = removeJITDylibs(std::move(JDsToRemove));
1628 
1629   Err = joinErrors(std::move(Err), EPC->disconnect());
1630 
1631   return Err;
1632 }
1633 
1634 void ExecutionSession::registerResourceManager(ResourceManager &RM) {
1635   runSessionLocked([&] { ResourceManagers.push_back(&RM); });
1636 }
1637 
1638 void ExecutionSession::deregisterResourceManager(ResourceManager &RM) {
1639   runSessionLocked([&] {
1640     assert(!ResourceManagers.empty() && "No managers registered");
1641     if (ResourceManagers.back() == &RM)
1642       ResourceManagers.pop_back();
1643     else {
1644       auto I = llvm::find(ResourceManagers, &RM);
1645       assert(I != ResourceManagers.end() && "RM not registered");
1646       ResourceManagers.erase(I);
1647     }
1648   });
1649 }
1650 
1651 JITDylib *ExecutionSession::getJITDylibByName(StringRef Name) {
1652   return runSessionLocked([&, this]() -> JITDylib * {
1653     for (auto &JD : JDs)
1654       if (JD->getName() == Name)
1655         return JD.get();
1656     return nullptr;
1657   });
1658 }
1659 
1660 JITDylib &ExecutionSession::createBareJITDylib(std::string Name) {
1661   assert(!getJITDylibByName(Name) && "JITDylib with that name already exists");
1662   return runSessionLocked([&, this]() -> JITDylib & {
1663     assert(SessionOpen && "Cannot create JITDylib after session is closed");
1664     JDs.push_back(new JITDylib(*this, std::move(Name)));
1665     return *JDs.back();
1666   });
1667 }
1668 
1669 Expected<JITDylib &> ExecutionSession::createJITDylib(std::string Name) {
1670   auto &JD = createBareJITDylib(Name);
1671   if (P)
1672     if (auto Err = P->setupJITDylib(JD))
1673       return std::move(Err);
1674   return JD;
1675 }
1676 
1677 Error ExecutionSession::removeJITDylibs(std::vector<JITDylibSP> JDsToRemove) {
1678   // Set JD to 'Closing' state and remove JD from the ExecutionSession.
1679   runSessionLocked([&] {
1680     for (auto &JD : JDsToRemove) {
1681       assert(JD->State == JITDylib::Open && "JD already closed");
1682       JD->State = JITDylib::Closing;
1683       auto I = llvm::find(JDs, JD);
1684       assert(I != JDs.end() && "JD does not appear in session JDs");
1685       JDs.erase(I);
1686     }
1687   });
1688 
1689   // Clear JITDylibs and notify the platform.
1690   Error Err = Error::success();
1691   for (auto JD : JDsToRemove) {
1692     Err = joinErrors(std::move(Err), JD->clear());
1693     if (P)
1694       Err = joinErrors(std::move(Err), P->teardownJITDylib(*JD));
1695   }
1696 
1697   // Set JD to closed state. Clear remaining data structures.
1698   runSessionLocked([&] {
1699     for (auto &JD : JDsToRemove) {
1700       assert(JD->State == JITDylib::Closing && "JD should be closing");
1701       JD->State = JITDylib::Closed;
1702       assert(JD->Symbols.empty() && "JD.Symbols is not empty after clear");
1703       assert(JD->UnmaterializedInfos.empty() &&
1704              "JD.UnmaterializedInfos is not empty after clear");
1705       assert(JD->MaterializingInfos.empty() &&
1706              "JD.MaterializingInfos is not empty after clear");
1707       assert(JD->TrackerSymbols.empty() &&
1708              "TrackerSymbols is not empty after clear");
1709       JD->DefGenerators.clear();
1710       JD->LinkOrder.clear();
1711     }
1712   });
1713 
1714   return Err;
1715 }
1716 
1717 Expected<std::vector<JITDylibSP>>
1718 JITDylib::getDFSLinkOrder(ArrayRef<JITDylibSP> JDs) {
1719   if (JDs.empty())
1720     return std::vector<JITDylibSP>();
1721 
1722   auto &ES = JDs.front()->getExecutionSession();
1723   return ES.runSessionLocked([&]() -> Expected<std::vector<JITDylibSP>> {
1724     DenseSet<JITDylib *> Visited;
1725     std::vector<JITDylibSP> Result;
1726 
1727     for (auto &JD : JDs) {
1728 
1729       if (JD->State != Open)
1730         return make_error<StringError>(
1731             "Error building link order: " + JD->getName() + " is defunct",
1732             inconvertibleErrorCode());
1733       if (Visited.count(JD.get()))
1734         continue;
1735 
1736       SmallVector<JITDylibSP, 64> WorkStack;
1737       WorkStack.push_back(JD);
1738       Visited.insert(JD.get());
1739 
1740       while (!WorkStack.empty()) {
1741         Result.push_back(std::move(WorkStack.back()));
1742         WorkStack.pop_back();
1743 
1744         for (auto &KV : llvm::reverse(Result.back()->LinkOrder)) {
1745           auto &JD = *KV.first;
1746           if (!Visited.insert(&JD).second)
1747             continue;
1748           WorkStack.push_back(&JD);
1749         }
1750       }
1751     }
1752     return Result;
1753   });
1754 }
1755 
1756 Expected<std::vector<JITDylibSP>>
1757 JITDylib::getReverseDFSLinkOrder(ArrayRef<JITDylibSP> JDs) {
1758   auto Result = getDFSLinkOrder(JDs);
1759   if (Result)
1760     std::reverse(Result->begin(), Result->end());
1761   return Result;
1762 }
1763 
1764 Expected<std::vector<JITDylibSP>> JITDylib::getDFSLinkOrder() {
1765   return getDFSLinkOrder({this});
1766 }
1767 
1768 Expected<std::vector<JITDylibSP>> JITDylib::getReverseDFSLinkOrder() {
1769   return getReverseDFSLinkOrder({this});
1770 }
1771 
1772 void ExecutionSession::lookupFlags(
1773     LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet,
1774     unique_function<void(Expected<SymbolFlagsMap>)> OnComplete) {
1775 
1776   OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
1777                           K, std::move(SearchOrder), std::move(LookupSet),
1778                           std::move(OnComplete)),
1779                       Error::success());
1780 }
1781 
1782 Expected<SymbolFlagsMap>
1783 ExecutionSession::lookupFlags(LookupKind K, JITDylibSearchOrder SearchOrder,
1784                               SymbolLookupSet LookupSet) {
1785 
1786   std::promise<MSVCPExpected<SymbolFlagsMap>> ResultP;
1787   OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
1788                           K, std::move(SearchOrder), std::move(LookupSet),
1789                           [&ResultP](Expected<SymbolFlagsMap> Result) {
1790                             ResultP.set_value(std::move(Result));
1791                           }),
1792                       Error::success());
1793 
1794   auto ResultF = ResultP.get_future();
1795   return ResultF.get();
1796 }
1797 
1798 void ExecutionSession::lookup(
1799     LookupKind K, const JITDylibSearchOrder &SearchOrder,
1800     SymbolLookupSet Symbols, SymbolState RequiredState,
1801     SymbolsResolvedCallback NotifyComplete,
1802     RegisterDependenciesFunction RegisterDependencies) {
1803 
1804   LLVM_DEBUG({
1805     runSessionLocked([&]() {
1806       dbgs() << "Looking up " << Symbols << " in " << SearchOrder
1807              << " (required state: " << RequiredState << ")\n";
1808     });
1809   });
1810 
1811   // lookup can be re-entered recursively if running on a single thread. Run any
1812   // outstanding MUs in case this query depends on them, otherwise this lookup
1813   // will starve waiting for a result from an MU that is stuck in the queue.
1814   dispatchOutstandingMUs();
1815 
1816   auto Unresolved = std::move(Symbols);
1817   auto Q = std::make_shared<AsynchronousSymbolQuery>(Unresolved, RequiredState,
1818                                                      std::move(NotifyComplete));
1819 
1820   auto IPLS = std::make_unique<InProgressFullLookupState>(
1821       K, SearchOrder, std::move(Unresolved), RequiredState, std::move(Q),
1822       std::move(RegisterDependencies));
1823 
1824   OL_applyQueryPhase1(std::move(IPLS), Error::success());
1825 }
1826 
1827 Expected<SymbolMap>
1828 ExecutionSession::lookup(const JITDylibSearchOrder &SearchOrder,
1829                          SymbolLookupSet Symbols, LookupKind K,
1830                          SymbolState RequiredState,
1831                          RegisterDependenciesFunction RegisterDependencies) {
1832 #if LLVM_ENABLE_THREADS
1833   // In the threaded case we use promises to return the results.
1834   std::promise<MSVCPExpected<SymbolMap>> PromisedResult;
1835 
1836   auto NotifyComplete = [&](Expected<SymbolMap> R) {
1837     PromisedResult.set_value(std::move(R));
1838   };
1839 
1840 #else
1841   SymbolMap Result;
1842   Error ResolutionError = Error::success();
1843 
1844   auto NotifyComplete = [&](Expected<SymbolMap> R) {
1845     ErrorAsOutParameter _(ResolutionError);
1846     if (R)
1847       Result = std::move(*R);
1848     else
1849       ResolutionError = R.takeError();
1850   };
1851 #endif
1852 
1853   // Perform the asynchronous lookup.
1854   lookup(K, SearchOrder, std::move(Symbols), RequiredState,
1855          std::move(NotifyComplete), RegisterDependencies);
1856 
1857 #if LLVM_ENABLE_THREADS
1858   return PromisedResult.get_future().get();
1859 #else
1860   if (ResolutionError)
1861     return std::move(ResolutionError);
1862 
1863   return Result;
1864 #endif
1865 }
1866 
1867 Expected<ExecutorSymbolDef>
1868 ExecutionSession::lookup(const JITDylibSearchOrder &SearchOrder,
1869                          SymbolStringPtr Name, SymbolState RequiredState) {
1870   SymbolLookupSet Names({Name});
1871 
1872   if (auto ResultMap = lookup(SearchOrder, std::move(Names), LookupKind::Static,
1873                               RequiredState, NoDependenciesToRegister)) {
1874     assert(ResultMap->size() == 1 && "Unexpected number of results");
1875     assert(ResultMap->count(Name) && "Missing result for symbol");
1876     return std::move(ResultMap->begin()->second);
1877   } else
1878     return ResultMap.takeError();
1879 }
1880 
1881 Expected<ExecutorSymbolDef>
1882 ExecutionSession::lookup(ArrayRef<JITDylib *> SearchOrder, SymbolStringPtr Name,
1883                          SymbolState RequiredState) {
1884   return lookup(makeJITDylibSearchOrder(SearchOrder), Name, RequiredState);
1885 }
1886 
1887 Expected<ExecutorSymbolDef>
1888 ExecutionSession::lookup(ArrayRef<JITDylib *> SearchOrder, StringRef Name,
1889                          SymbolState RequiredState) {
1890   return lookup(SearchOrder, intern(Name), RequiredState);
1891 }
1892 
1893 Error ExecutionSession::registerJITDispatchHandlers(
1894     JITDylib &JD, JITDispatchHandlerAssociationMap WFs) {
1895 
1896   auto TagSyms = lookup({{&JD, JITDylibLookupFlags::MatchAllSymbols}},
1897                         SymbolLookupSet::fromMapKeys(
1898                             WFs, SymbolLookupFlags::WeaklyReferencedSymbol));
1899   if (!TagSyms)
1900     return TagSyms.takeError();
1901 
1902   // Associate tag addresses with implementations.
1903   std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
1904 
1905   // Check that no tags are being overwritten.
1906   for (auto &[TagName, TagSym] : *TagSyms) {
1907     auto TagAddr = TagSym.getAddress();
1908     if (JITDispatchHandlers.count(TagAddr))
1909       return make_error<StringError>("Tag " + formatv("{0:x}", TagAddr) +
1910                                          " (for " + *TagName +
1911                                          ") already registered",
1912                                      inconvertibleErrorCode());
1913   }
1914 
1915   // At this point we're guaranteed to succeed. Install the handlers.
1916   for (auto &[TagName, TagSym] : *TagSyms) {
1917     auto TagAddr = TagSym.getAddress();
1918     auto I = WFs.find(TagName);
1919     assert(I != WFs.end() && I->second &&
1920            "JITDispatchHandler implementation missing");
1921     JITDispatchHandlers[TagAddr] =
1922         std::make_shared<JITDispatchHandlerFunction>(std::move(I->second));
1923     LLVM_DEBUG({
1924       dbgs() << "Associated function tag \"" << *TagName << "\" ("
1925              << formatv("{0:x}", TagAddr) << ") with handler\n";
1926     });
1927   }
1928 
1929   return Error::success();
1930 }
1931 
1932 void ExecutionSession::runJITDispatchHandler(SendResultFunction SendResult,
1933                                              ExecutorAddr HandlerFnTagAddr,
1934                                              ArrayRef<char> ArgBuffer) {
1935 
1936   std::shared_ptr<JITDispatchHandlerFunction> F;
1937   {
1938     std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
1939     auto I = JITDispatchHandlers.find(HandlerFnTagAddr);
1940     if (I != JITDispatchHandlers.end())
1941       F = I->second;
1942   }
1943 
1944   if (F)
1945     (*F)(std::move(SendResult), ArgBuffer.data(), ArgBuffer.size());
1946   else
1947     SendResult(shared::WrapperFunctionResult::createOutOfBandError(
1948         ("No function registered for tag " +
1949          formatv("{0:x16}", HandlerFnTagAddr))
1950             .str()));
1951 }
1952 
1953 void ExecutionSession::dump(raw_ostream &OS) {
1954   runSessionLocked([this, &OS]() {
1955     for (auto &JD : JDs)
1956       JD->dump(OS);
1957   });
1958 }
1959 
1960 #ifdef EXPENSIVE_CHECKS
1961 bool ExecutionSession::verifySessionState(Twine Phase) {
1962   return runSessionLocked([&]() {
1963     bool AllOk = true;
1964 
1965     // We'll collect these and verify them later to avoid redundant checks.
1966     DenseSet<JITDylib::EmissionDepUnit *> EDUsToCheck;
1967 
1968     for (auto &JD : JDs) {
1969 
1970       auto LogFailure = [&]() -> raw_fd_ostream & {
1971         auto &Stream = errs();
1972         if (AllOk)
1973           Stream << "ERROR: Bad ExecutionSession state detected " << Phase
1974                  << "\n";
1975         Stream << "  In JITDylib " << JD->getName() << ", ";
1976         AllOk = false;
1977         return Stream;
1978       };
1979 
1980       if (JD->State != JITDylib::Open) {
1981         LogFailure()
1982             << "state is not Open, but JD is in ExecutionSession list.";
1983       }
1984 
1985       // Check symbol table.
1986       // 1. If the entry state isn't resolved then check that no address has
1987       //    been set.
1988       // 2. Check that if the hasMaterializerAttached flag is set then there is
1989       //    an UnmaterializedInfo entry, and vice-versa.
1990       for (auto &[Sym, Entry] : JD->Symbols) {
1991         // Check that unresolved symbols have null addresses.
1992         if (Entry.getState() < SymbolState::Resolved) {
1993           if (Entry.getAddress()) {
1994             LogFailure() << "symbol " << Sym << " has state "
1995                          << Entry.getState()
1996                          << " (not-yet-resolved) but non-null address "
1997                          << Entry.getAddress() << ".\n";
1998           }
1999         }
2000 
2001         // Check that the hasMaterializerAttached flag is correct.
2002         auto UMIItr = JD->UnmaterializedInfos.find(Sym);
2003         if (Entry.hasMaterializerAttached()) {
2004           if (UMIItr == JD->UnmaterializedInfos.end()) {
2005             LogFailure() << "symbol " << Sym
2006                          << " entry claims materializer attached, but "
2007                             "UnmaterializedInfos has no corresponding entry.\n";
2008           }
2009         } else if (UMIItr != JD->UnmaterializedInfos.end()) {
2010           LogFailure()
2011               << "symbol " << Sym
2012               << " entry claims no materializer attached, but "
2013                  "UnmaterializedInfos has an unexpected entry for it.\n";
2014         }
2015       }
2016 
2017       // Check that every UnmaterializedInfo entry has a corresponding entry
2018       // in the Symbols table.
2019       for (auto &[Sym, UMI] : JD->UnmaterializedInfos) {
2020         auto SymItr = JD->Symbols.find(Sym);
2021         if (SymItr == JD->Symbols.end()) {
2022           LogFailure()
2023               << "symbol " << Sym
2024               << " has UnmaterializedInfos entry, but no Symbols entry.\n";
2025         }
2026       }
2027 
2028       // Check consistency of the MaterializingInfos table.
2029       for (auto &[Sym, MII] : JD->MaterializingInfos) {
2030 
2031         auto SymItr = JD->Symbols.find(Sym);
2032         if (SymItr == JD->Symbols.end()) {
2033           // If there's no Symbols entry for this MaterializingInfos entry then
2034           // report that.
2035           LogFailure()
2036               << "symbol " << Sym
2037               << " has MaterializingInfos entry, but no Symbols entry.\n";
2038         } else {
2039           // Otherwise check consistency between Symbols and MaterializingInfos.
2040 
2041           // Ready symbols should not have MaterializingInfos.
2042           if (SymItr->second.getState() == SymbolState::Ready) {
2043             LogFailure()
2044                 << "symbol " << Sym
2045                 << " is in Ready state, should not have MaterializingInfo.\n";
2046           }
2047 
2048           // Pending queries should be for subsequent states.
2049           auto CurState = static_cast<SymbolState>(
2050               static_cast<std::underlying_type_t<SymbolState>>(
2051                   SymItr->second.getState()) + 1);
2052           for (auto &Q : MII.PendingQueries) {
2053             if (Q->getRequiredState() != CurState) {
2054               if (Q->getRequiredState() > CurState)
2055                 CurState = Q->getRequiredState();
2056               else
2057                 LogFailure() << "symbol " << Sym
2058                              << " has stale or misordered queries.\n";
2059             }
2060           }
2061 
2062           // If there's a DefiningEDU then check that...
2063           // 1. The JD matches.
2064           // 2. The symbol is in the EDU's Symbols map.
2065           // 3. The symbol table entry is in the Emitted state.
2066           if (MII.DefiningEDU) {
2067 
2068             EDUsToCheck.insert(MII.DefiningEDU.get());
2069 
2070             if (MII.DefiningEDU->JD != JD.get()) {
2071               LogFailure() << "symbol " << Sym
2072                            << " has DefiningEDU with incorrect JD"
2073                            << (llvm::is_contained(JDs, MII.DefiningEDU->JD)
2074                                    ? " (JD not currently in ExecutionSession"
2075                                    : "")
2076                            << "\n";
2077             }
2078 
2079             if (SymItr->second.getState() != SymbolState::Emitted) {
2080               LogFailure()
2081                   << "symbol " << Sym
2082                   << " has DefiningEDU, but is not in Emitted state.\n";
2083             }
2084           }
2085 
2086           // Check that JDs for any DependantEDUs are also in the session --
2087           // that guarantees that we'll also visit them during this loop.
2088           for (auto &DepEDU : MII.DependantEDUs) {
2089             if (!llvm::is_contained(JDs, DepEDU->JD)) {
2090               LogFailure() << "symbol " << Sym << " has DependantEDU "
2091                            << (void *)DepEDU << " with JD (" << DepEDU->JD
2092                            << ") that isn't in ExecutionSession.\n";
2093             }
2094           }
2095         }
2096       }
2097     }
2098 
2099     // Check EDUs.
2100     for (auto *EDU : EDUsToCheck) {
2101       assert(EDU->JD->State == JITDylib::Open && "EDU->JD is not Open");
2102 
2103       auto LogFailure = [&]() -> raw_fd_ostream & {
2104         AllOk = false;
2105         auto &Stream = errs();
2106         Stream << "In EDU defining " << EDU->JD->getName() << ": { ";
2107         for (auto &[Sym, Flags] : EDU->Symbols)
2108           Stream << Sym << " ";
2109         Stream << "}, ";
2110         return Stream;
2111       };
2112 
2113       if (EDU->Symbols.empty())
2114         LogFailure() << "no symbols defined.\n";
2115       else {
2116         for (auto &[Sym, Flags] : EDU->Symbols) {
2117           if (!Sym)
2118             LogFailure() << "null symbol defined.\n";
2119           else {
2120             if (!EDU->JD->Symbols.count(SymbolStringPtr(Sym))) {
2121               LogFailure() << "symbol " << Sym
2122                            << " isn't present in JD's symbol table.\n";
2123             }
2124           }
2125         }
2126       }
2127 
2128       for (auto &[DepJD, Symbols] : EDU->Dependencies) {
2129         if (!llvm::is_contained(JDs, DepJD)) {
2130           LogFailure() << "dependant symbols listed for JD that isn't in "
2131                           "ExecutionSession.\n";
2132         } else {
2133           for (auto &DepSym : Symbols) {
2134             if (!DepJD->Symbols.count(SymbolStringPtr(DepSym))) {
2135               LogFailure()
2136                   << "dependant symbol " << DepSym
2137                   << " does not appear in symbol table for dependant JD "
2138                   << DepJD->getName() << ".\n";
2139             }
2140           }
2141         }
2142       }
2143     }
2144 
2145     return AllOk;
2146   });
2147 }
2148 #endif // EXPENSIVE_CHECKS
2149 
2150 void ExecutionSession::dispatchOutstandingMUs() {
2151   LLVM_DEBUG(dbgs() << "Dispatching MaterializationUnits...\n");
2152   while (true) {
2153     std::optional<std::pair<std::unique_ptr<MaterializationUnit>,
2154                             std::unique_ptr<MaterializationResponsibility>>>
2155         JMU;
2156 
2157     {
2158       std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2159       if (!OutstandingMUs.empty()) {
2160         JMU.emplace(std::move(OutstandingMUs.back()));
2161         OutstandingMUs.pop_back();
2162       }
2163     }
2164 
2165     if (!JMU)
2166       break;
2167 
2168     assert(JMU->first && "No MU?");
2169     LLVM_DEBUG(dbgs() << "  Dispatching \"" << JMU->first->getName() << "\"\n");
2170     dispatchTask(std::make_unique<MaterializationTask>(std::move(JMU->first),
2171                                                        std::move(JMU->second)));
2172   }
2173   LLVM_DEBUG(dbgs() << "Done dispatching MaterializationUnits.\n");
2174 }
2175 
2176 Error ExecutionSession::removeResourceTracker(ResourceTracker &RT) {
2177   LLVM_DEBUG({
2178     dbgs() << "In " << RT.getJITDylib().getName() << " removing tracker "
2179            << formatv("{0:x}", RT.getKeyUnsafe()) << "\n";
2180   });
2181   std::vector<ResourceManager *> CurrentResourceManagers;
2182 
2183   JITDylib::AsynchronousSymbolQuerySet QueriesToFail;
2184   std::shared_ptr<SymbolDependenceMap> FailedSymbols;
2185 
2186   runSessionLocked([&] {
2187     CurrentResourceManagers = ResourceManagers;
2188     RT.makeDefunct();
2189     std::tie(QueriesToFail, FailedSymbols) =
2190         RT.getJITDylib().IL_removeTracker(RT);
2191   });
2192 
2193   Error Err = Error::success();
2194 
2195   auto &JD = RT.getJITDylib();
2196   for (auto *L : reverse(CurrentResourceManagers))
2197     Err = joinErrors(std::move(Err),
2198                      L->handleRemoveResources(JD, RT.getKeyUnsafe()));
2199 
2200   for (auto &Q : QueriesToFail)
2201     Q->handleFailed(
2202         make_error<FailedToMaterialize>(getSymbolStringPool(), FailedSymbols));
2203 
2204   return Err;
2205 }
2206 
2207 void ExecutionSession::transferResourceTracker(ResourceTracker &DstRT,
2208                                                ResourceTracker &SrcRT) {
2209   LLVM_DEBUG({
2210     dbgs() << "In " << SrcRT.getJITDylib().getName()
2211            << " transfering resources from tracker "
2212            << formatv("{0:x}", SrcRT.getKeyUnsafe()) << " to tracker "
2213            << formatv("{0:x}", DstRT.getKeyUnsafe()) << "\n";
2214   });
2215 
2216   // No-op transfers are allowed and do not invalidate the source.
2217   if (&DstRT == &SrcRT)
2218     return;
2219 
2220   assert(&DstRT.getJITDylib() == &SrcRT.getJITDylib() &&
2221          "Can't transfer resources between JITDylibs");
2222   runSessionLocked([&]() {
2223     SrcRT.makeDefunct();
2224     auto &JD = DstRT.getJITDylib();
2225     JD.transferTracker(DstRT, SrcRT);
2226     for (auto *L : reverse(ResourceManagers))
2227       L->handleTransferResources(JD, DstRT.getKeyUnsafe(),
2228                                  SrcRT.getKeyUnsafe());
2229   });
2230 }
2231 
2232 void ExecutionSession::destroyResourceTracker(ResourceTracker &RT) {
2233   runSessionLocked([&]() {
2234     LLVM_DEBUG({
2235       dbgs() << "In " << RT.getJITDylib().getName() << " destroying tracker "
2236              << formatv("{0:x}", RT.getKeyUnsafe()) << "\n";
2237     });
2238     if (!RT.isDefunct())
2239       transferResourceTracker(*RT.getJITDylib().getDefaultResourceTracker(),
2240                               RT);
2241   });
2242 }
2243 
2244 Error ExecutionSession::IL_updateCandidatesFor(
2245     JITDylib &JD, JITDylibLookupFlags JDLookupFlags,
2246     SymbolLookupSet &Candidates, SymbolLookupSet *NonCandidates) {
2247   return Candidates.forEachWithRemoval(
2248       [&](const SymbolStringPtr &Name,
2249           SymbolLookupFlags SymLookupFlags) -> Expected<bool> {
2250         /// Search for the symbol. If not found then continue without
2251         /// removal.
2252         auto SymI = JD.Symbols.find(Name);
2253         if (SymI == JD.Symbols.end())
2254           return false;
2255 
2256         // If this is a non-exported symbol and we're matching exported
2257         // symbols only then remove this symbol from the candidates list.
2258         //
2259         // If we're tracking non-candidates then add this to the non-candidate
2260         // list.
2261         if (!SymI->second.getFlags().isExported() &&
2262             JDLookupFlags == JITDylibLookupFlags::MatchExportedSymbolsOnly) {
2263           if (NonCandidates)
2264             NonCandidates->add(Name, SymLookupFlags);
2265           return true;
2266         }
2267 
2268         // If we match against a materialization-side-effects only symbol
2269         // then make sure it is weakly-referenced. Otherwise bail out with
2270         // an error.
2271         // FIXME: Use a "materialization-side-effects-only symbols must be
2272         // weakly referenced" specific error here to reduce confusion.
2273         if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2274             SymLookupFlags != SymbolLookupFlags::WeaklyReferencedSymbol)
2275           return make_error<SymbolsNotFound>(getSymbolStringPool(),
2276                                              SymbolNameVector({Name}));
2277 
2278         // If we matched against this symbol but it is in the error state
2279         // then bail out and treat it as a failure to materialize.
2280         if (SymI->second.getFlags().hasError()) {
2281           auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2282           (*FailedSymbolsMap)[&JD] = {Name};
2283           return make_error<FailedToMaterialize>(getSymbolStringPool(),
2284                                                  std::move(FailedSymbolsMap));
2285         }
2286 
2287         // Otherwise this is a match. Remove it from the candidate set.
2288         return true;
2289       });
2290 }
2291 
2292 void ExecutionSession::OL_resumeLookupAfterGeneration(
2293     InProgressLookupState &IPLS) {
2294 
2295   assert(IPLS.GenState != InProgressLookupState::NotInGenerator &&
2296          "Should not be called for not-in-generator lookups");
2297   IPLS.GenState = InProgressLookupState::NotInGenerator;
2298 
2299   LookupState LS;
2300 
2301   if (auto DG = IPLS.CurDefGeneratorStack.back().lock()) {
2302     IPLS.CurDefGeneratorStack.pop_back();
2303     std::lock_guard<std::mutex> Lock(DG->M);
2304 
2305     // If there are no pending lookups then mark the generator as free and
2306     // return.
2307     if (DG->PendingLookups.empty()) {
2308       DG->InUse = false;
2309       return;
2310     }
2311 
2312     // Otherwise resume the next lookup.
2313     LS = std::move(DG->PendingLookups.front());
2314     DG->PendingLookups.pop_front();
2315   }
2316 
2317   if (LS.IPLS) {
2318     LS.IPLS->GenState = InProgressLookupState::ResumedForGenerator;
2319     dispatchTask(std::make_unique<LookupTask>(std::move(LS)));
2320   }
2321 }
2322 
2323 void ExecutionSession::OL_applyQueryPhase1(
2324     std::unique_ptr<InProgressLookupState> IPLS, Error Err) {
2325 
2326   LLVM_DEBUG({
2327     dbgs() << "Entering OL_applyQueryPhase1:\n"
2328            << "  Lookup kind: " << IPLS->K << "\n"
2329            << "  Search order: " << IPLS->SearchOrder
2330            << ", Current index = " << IPLS->CurSearchOrderIndex
2331            << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2332            << "  Lookup set: " << IPLS->LookupSet << "\n"
2333            << "  Definition generator candidates: "
2334            << IPLS->DefGeneratorCandidates << "\n"
2335            << "  Definition generator non-candidates: "
2336            << IPLS->DefGeneratorNonCandidates << "\n";
2337   });
2338 
2339   if (IPLS->GenState == InProgressLookupState::InGenerator)
2340     OL_resumeLookupAfterGeneration(*IPLS);
2341 
2342   assert(IPLS->GenState != InProgressLookupState::InGenerator &&
2343          "Lookup should not be in InGenerator state here");
2344 
2345   // FIXME: We should attach the query as we go: This provides a result in a
2346   // single pass in the common case where all symbols have already reached the
2347   // required state. The query could be detached again in the 'fail' method on
2348   // IPLS. Phase 2 would be reduced to collecting and dispatching the MUs.
2349 
2350   while (IPLS->CurSearchOrderIndex != IPLS->SearchOrder.size()) {
2351 
2352     // If we've been handed an error or received one back from a generator then
2353     // fail the query. We don't need to unlink: At this stage the query hasn't
2354     // actually been lodged.
2355     if (Err)
2356       return IPLS->fail(std::move(Err));
2357 
2358     // Get the next JITDylib and lookup flags.
2359     auto &KV = IPLS->SearchOrder[IPLS->CurSearchOrderIndex];
2360     auto &JD = *KV.first;
2361     auto JDLookupFlags = KV.second;
2362 
2363     LLVM_DEBUG({
2364       dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2365              << ") with lookup set " << IPLS->LookupSet << ":\n";
2366     });
2367 
2368     // If we've just reached a new JITDylib then perform some setup.
2369     if (IPLS->NewJITDylib) {
2370       // Add any non-candidates from the last JITDylib (if any) back on to the
2371       // list of definition candidates for this JITDylib, reset definition
2372       // non-candidates to the empty set.
2373       SymbolLookupSet Tmp;
2374       std::swap(IPLS->DefGeneratorNonCandidates, Tmp);
2375       IPLS->DefGeneratorCandidates.append(std::move(Tmp));
2376 
2377       LLVM_DEBUG({
2378         dbgs() << "  First time visiting " << JD.getName()
2379                << ", resetting candidate sets and building generator stack\n";
2380       });
2381 
2382       // Build the definition generator stack for this JITDylib.
2383       runSessionLocked([&] {
2384         IPLS->CurDefGeneratorStack.reserve(JD.DefGenerators.size());
2385         for (auto &DG : reverse(JD.DefGenerators))
2386           IPLS->CurDefGeneratorStack.push_back(DG);
2387       });
2388 
2389       // Flag that we've done our initialization.
2390       IPLS->NewJITDylib = false;
2391     }
2392 
2393     // Remove any generation candidates that are already defined (and match) in
2394     // this JITDylib.
2395     runSessionLocked([&] {
2396       // Update the list of candidates (and non-candidates) for definition
2397       // generation.
2398       LLVM_DEBUG(dbgs() << "  Updating candidate set...\n");
2399       Err = IL_updateCandidatesFor(
2400           JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2401           JD.DefGenerators.empty() ? nullptr
2402                                    : &IPLS->DefGeneratorNonCandidates);
2403       LLVM_DEBUG({
2404         dbgs() << "    Remaining candidates = " << IPLS->DefGeneratorCandidates
2405                << "\n";
2406       });
2407 
2408       // If this lookup was resumed after auto-suspension but all candidates
2409       // have already been generated (by some previous call to the generator)
2410       // treat the lookup as if it had completed generation.
2411       if (IPLS->GenState == InProgressLookupState::ResumedForGenerator &&
2412           IPLS->DefGeneratorCandidates.empty())
2413         OL_resumeLookupAfterGeneration(*IPLS);
2414     });
2415 
2416     // If we encountered an error while filtering generation candidates then
2417     // bail out.
2418     if (Err)
2419       return IPLS->fail(std::move(Err));
2420 
2421     /// Apply any definition generators on the stack.
2422     LLVM_DEBUG({
2423       if (IPLS->CurDefGeneratorStack.empty())
2424         LLVM_DEBUG(dbgs() << "  No generators to run for this JITDylib.\n");
2425       else if (IPLS->DefGeneratorCandidates.empty())
2426         LLVM_DEBUG(dbgs() << "  No candidates to generate.\n");
2427       else
2428         dbgs() << "  Running " << IPLS->CurDefGeneratorStack.size()
2429                << " remaining generators for "
2430                << IPLS->DefGeneratorCandidates.size() << " candidates\n";
2431     });
2432     while (!IPLS->CurDefGeneratorStack.empty() &&
2433            !IPLS->DefGeneratorCandidates.empty()) {
2434       auto DG = IPLS->CurDefGeneratorStack.back().lock();
2435 
2436       if (!DG)
2437         return IPLS->fail(make_error<StringError>(
2438             "DefinitionGenerator removed while lookup in progress",
2439             inconvertibleErrorCode()));
2440 
2441       // At this point the lookup is in either the NotInGenerator state, or in
2442       // the ResumedForGenerator state.
2443       // If this lookup is in the NotInGenerator state then check whether the
2444       // generator is in use. If the generator is not in use then move the
2445       // lookup to the InGenerator state and continue. If the generator is
2446       // already in use then just add this lookup to the pending lookups list
2447       // and bail out.
2448       // If this lookup is in the ResumedForGenerator state then just move it
2449       // to InGenerator and continue.
2450       if (IPLS->GenState == InProgressLookupState::NotInGenerator) {
2451         std::lock_guard<std::mutex> Lock(DG->M);
2452         if (DG->InUse) {
2453           DG->PendingLookups.push_back(std::move(IPLS));
2454           return;
2455         }
2456         DG->InUse = true;
2457       }
2458 
2459       IPLS->GenState = InProgressLookupState::InGenerator;
2460 
2461       auto K = IPLS->K;
2462       auto &LookupSet = IPLS->DefGeneratorCandidates;
2463 
2464       // Run the generator. If the generator takes ownership of QA then this
2465       // will break the loop.
2466       {
2467         LLVM_DEBUG(dbgs() << "  Attempting to generate " << LookupSet << "\n");
2468         LookupState LS(std::move(IPLS));
2469         Err = DG->tryToGenerate(LS, K, JD, JDLookupFlags, LookupSet);
2470         IPLS = std::move(LS.IPLS);
2471       }
2472 
2473       // If the lookup returned then pop the generator stack and unblock the
2474       // next lookup on this generator (if any).
2475       if (IPLS)
2476         OL_resumeLookupAfterGeneration(*IPLS);
2477 
2478       // If there was an error then fail the query.
2479       if (Err) {
2480         LLVM_DEBUG({
2481           dbgs() << "  Error attempting to generate " << LookupSet << "\n";
2482         });
2483         assert(IPLS && "LS cannot be retained if error is returned");
2484         return IPLS->fail(std::move(Err));
2485       }
2486 
2487       // Otherwise if QA was captured then break the loop.
2488       if (!IPLS) {
2489         LLVM_DEBUG(
2490             { dbgs() << "  LookupState captured. Exiting phase1 for now.\n"; });
2491         return;
2492       }
2493 
2494       // Otherwise if we're continuing around the loop then update candidates
2495       // for the next round.
2496       runSessionLocked([&] {
2497         LLVM_DEBUG(dbgs() << "  Updating candidate set post-generation\n");
2498         Err = IL_updateCandidatesFor(
2499             JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2500             JD.DefGenerators.empty() ? nullptr
2501                                      : &IPLS->DefGeneratorNonCandidates);
2502       });
2503 
2504       // If updating candidates failed then fail the query.
2505       if (Err) {
2506         LLVM_DEBUG(dbgs() << "  Error encountered while updating candidates\n");
2507         return IPLS->fail(std::move(Err));
2508       }
2509     }
2510 
2511     if (IPLS->DefGeneratorCandidates.empty() &&
2512         IPLS->DefGeneratorNonCandidates.empty()) {
2513       // Early out if there are no remaining symbols.
2514       LLVM_DEBUG(dbgs() << "All symbols matched.\n");
2515       IPLS->CurSearchOrderIndex = IPLS->SearchOrder.size();
2516       break;
2517     } else {
2518       // If we get here then we've moved on to the next JITDylib with candidates
2519       // remaining.
2520       LLVM_DEBUG(dbgs() << "Phase 1 moving to next JITDylib.\n");
2521       ++IPLS->CurSearchOrderIndex;
2522       IPLS->NewJITDylib = true;
2523     }
2524   }
2525 
2526   // Remove any weakly referenced candidates that could not be found/generated.
2527   IPLS->DefGeneratorCandidates.remove_if(
2528       [](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2529         return SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol;
2530       });
2531 
2532   // If we get here then we've finished searching all JITDylibs.
2533   // If we matched all symbols then move to phase 2, otherwise fail the query
2534   // with a SymbolsNotFound error.
2535   if (IPLS->DefGeneratorCandidates.empty()) {
2536     LLVM_DEBUG(dbgs() << "Phase 1 succeeded.\n");
2537     IPLS->complete(std::move(IPLS));
2538   } else {
2539     LLVM_DEBUG(dbgs() << "Phase 1 failed with unresolved symbols.\n");
2540     IPLS->fail(make_error<SymbolsNotFound>(
2541         getSymbolStringPool(), IPLS->DefGeneratorCandidates.getSymbolNames()));
2542   }
2543 }
2544 
2545 void ExecutionSession::OL_completeLookup(
2546     std::unique_ptr<InProgressLookupState> IPLS,
2547     std::shared_ptr<AsynchronousSymbolQuery> Q,
2548     RegisterDependenciesFunction RegisterDependencies) {
2549 
2550   LLVM_DEBUG({
2551     dbgs() << "Entering OL_completeLookup:\n"
2552            << "  Lookup kind: " << IPLS->K << "\n"
2553            << "  Search order: " << IPLS->SearchOrder
2554            << ", Current index = " << IPLS->CurSearchOrderIndex
2555            << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2556            << "  Lookup set: " << IPLS->LookupSet << "\n"
2557            << "  Definition generator candidates: "
2558            << IPLS->DefGeneratorCandidates << "\n"
2559            << "  Definition generator non-candidates: "
2560            << IPLS->DefGeneratorNonCandidates << "\n";
2561   });
2562 
2563   bool QueryComplete = false;
2564   DenseMap<JITDylib *, JITDylib::UnmaterializedInfosList> CollectedUMIs;
2565 
2566   auto LodgingErr = runSessionLocked([&]() -> Error {
2567     for (auto &KV : IPLS->SearchOrder) {
2568       auto &JD = *KV.first;
2569       auto JDLookupFlags = KV.second;
2570       LLVM_DEBUG({
2571         dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2572                << ") with lookup set " << IPLS->LookupSet << ":\n";
2573       });
2574 
2575       auto Err = IPLS->LookupSet.forEachWithRemoval(
2576           [&](const SymbolStringPtr &Name,
2577               SymbolLookupFlags SymLookupFlags) -> Expected<bool> {
2578             LLVM_DEBUG({
2579               dbgs() << "  Attempting to match \"" << Name << "\" ("
2580                      << SymLookupFlags << ")... ";
2581             });
2582 
2583             /// Search for the symbol. If not found then continue without
2584             /// removal.
2585             auto SymI = JD.Symbols.find(Name);
2586             if (SymI == JD.Symbols.end()) {
2587               LLVM_DEBUG(dbgs() << "skipping: not present\n");
2588               return false;
2589             }
2590 
2591             // If this is a non-exported symbol and we're matching exported
2592             // symbols only then skip this symbol without removal.
2593             if (!SymI->second.getFlags().isExported() &&
2594                 JDLookupFlags ==
2595                     JITDylibLookupFlags::MatchExportedSymbolsOnly) {
2596               LLVM_DEBUG(dbgs() << "skipping: not exported\n");
2597               return false;
2598             }
2599 
2600             // If we match against a materialization-side-effects only symbol
2601             // then make sure it is weakly-referenced. Otherwise bail out with
2602             // an error.
2603             // FIXME: Use a "materialization-side-effects-only symbols must be
2604             // weakly referenced" specific error here to reduce confusion.
2605             if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2606                 SymLookupFlags != SymbolLookupFlags::WeaklyReferencedSymbol) {
2607               LLVM_DEBUG({
2608                 dbgs() << "error: "
2609                           "required, but symbol is has-side-effects-only\n";
2610               });
2611               return make_error<SymbolsNotFound>(getSymbolStringPool(),
2612                                                  SymbolNameVector({Name}));
2613             }
2614 
2615             // If we matched against this symbol but it is in the error state
2616             // then bail out and treat it as a failure to materialize.
2617             if (SymI->second.getFlags().hasError()) {
2618               LLVM_DEBUG(dbgs() << "error: symbol is in error state\n");
2619               auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2620               (*FailedSymbolsMap)[&JD] = {Name};
2621               return make_error<FailedToMaterialize>(
2622                   getSymbolStringPool(), std::move(FailedSymbolsMap));
2623             }
2624 
2625             // Otherwise this is a match.
2626 
2627             // If this symbol is already in the required state then notify the
2628             // query, remove the symbol and continue.
2629             if (SymI->second.getState() >= Q->getRequiredState()) {
2630               LLVM_DEBUG(dbgs()
2631                          << "matched, symbol already in required state\n");
2632               Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
2633 
2634               // If this symbol is in anything other than the Ready state then
2635               // we need to track the dependence.
2636               if (SymI->second.getState() != SymbolState::Ready)
2637                 Q->addQueryDependence(JD, Name);
2638 
2639               return true;
2640             }
2641 
2642             // Otherwise this symbol does not yet meet the required state. Check
2643             // whether it has a materializer attached, and if so prepare to run
2644             // it.
2645             if (SymI->second.hasMaterializerAttached()) {
2646               assert(SymI->second.getAddress() == ExecutorAddr() &&
2647                      "Symbol not resolved but already has address?");
2648               auto UMII = JD.UnmaterializedInfos.find(Name);
2649               assert(UMII != JD.UnmaterializedInfos.end() &&
2650                      "Lazy symbol should have UnmaterializedInfo");
2651 
2652               auto UMI = UMII->second;
2653               assert(UMI->MU && "Materializer should not be null");
2654               assert(UMI->RT && "Tracker should not be null");
2655               LLVM_DEBUG({
2656                 dbgs() << "matched, preparing to dispatch MU@" << UMI->MU.get()
2657                        << " (" << UMI->MU->getName() << ")\n";
2658               });
2659 
2660               // Move all symbols associated with this MaterializationUnit into
2661               // materializing state.
2662               for (auto &KV : UMI->MU->getSymbols()) {
2663                 auto SymK = JD.Symbols.find(KV.first);
2664                 assert(SymK != JD.Symbols.end() &&
2665                        "No entry for symbol covered by MaterializationUnit");
2666                 SymK->second.setMaterializerAttached(false);
2667                 SymK->second.setState(SymbolState::Materializing);
2668                 JD.UnmaterializedInfos.erase(KV.first);
2669               }
2670 
2671               // Add MU to the list of MaterializationUnits to be materialized.
2672               CollectedUMIs[&JD].push_back(std::move(UMI));
2673             } else
2674               LLVM_DEBUG(dbgs() << "matched, registering query");
2675 
2676             // Add the query to the PendingQueries list and continue, deleting
2677             // the element from the lookup set.
2678             assert(SymI->second.getState() != SymbolState::NeverSearched &&
2679                    SymI->second.getState() != SymbolState::Ready &&
2680                    "By this line the symbol should be materializing");
2681             auto &MI = JD.MaterializingInfos[Name];
2682             MI.addQuery(Q);
2683             Q->addQueryDependence(JD, Name);
2684 
2685             return true;
2686           });
2687 
2688       JD.shrinkMaterializationInfoMemory();
2689 
2690       // Handle failure.
2691       if (Err) {
2692 
2693         LLVM_DEBUG({
2694           dbgs() << "Lookup failed. Detaching query and replacing MUs.\n";
2695         });
2696 
2697         // Detach the query.
2698         Q->detach();
2699 
2700         // Replace the MUs.
2701         for (auto &KV : CollectedUMIs) {
2702           auto &JD = *KV.first;
2703           for (auto &UMI : KV.second)
2704             for (auto &KV2 : UMI->MU->getSymbols()) {
2705               assert(!JD.UnmaterializedInfos.count(KV2.first) &&
2706                      "Unexpected materializer in map");
2707               auto SymI = JD.Symbols.find(KV2.first);
2708               assert(SymI != JD.Symbols.end() && "Missing symbol entry");
2709               assert(SymI->second.getState() == SymbolState::Materializing &&
2710                      "Can not replace symbol that is not materializing");
2711               assert(!SymI->second.hasMaterializerAttached() &&
2712                      "MaterializerAttached flag should not be set");
2713               SymI->second.setMaterializerAttached(true);
2714               JD.UnmaterializedInfos[KV2.first] = UMI;
2715             }
2716         }
2717 
2718         return Err;
2719       }
2720     }
2721 
2722     LLVM_DEBUG(dbgs() << "Stripping unmatched weakly-referenced symbols\n");
2723     IPLS->LookupSet.forEachWithRemoval(
2724         [&](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2725           if (SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol) {
2726             Q->dropSymbol(Name);
2727             return true;
2728           } else
2729             return false;
2730         });
2731 
2732     if (!IPLS->LookupSet.empty()) {
2733       LLVM_DEBUG(dbgs() << "Failing due to unresolved symbols\n");
2734       return make_error<SymbolsNotFound>(getSymbolStringPool(),
2735                                          IPLS->LookupSet.getSymbolNames());
2736     }
2737 
2738     // Record whether the query completed.
2739     QueryComplete = Q->isComplete();
2740 
2741     LLVM_DEBUG({
2742       dbgs() << "Query successfully "
2743              << (QueryComplete ? "completed" : "lodged") << "\n";
2744     });
2745 
2746     // Move the collected MUs to the OutstandingMUs list.
2747     if (!CollectedUMIs.empty()) {
2748       std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2749 
2750       LLVM_DEBUG(dbgs() << "Adding MUs to dispatch:\n");
2751       for (auto &KV : CollectedUMIs) {
2752         LLVM_DEBUG({
2753           auto &JD = *KV.first;
2754           dbgs() << "  For " << JD.getName() << ": Adding " << KV.second.size()
2755                  << " MUs.\n";
2756         });
2757         for (auto &UMI : KV.second) {
2758           auto MR = createMaterializationResponsibility(
2759               *UMI->RT, std::move(UMI->MU->SymbolFlags),
2760               std::move(UMI->MU->InitSymbol));
2761           OutstandingMUs.push_back(
2762               std::make_pair(std::move(UMI->MU), std::move(MR)));
2763         }
2764       }
2765     } else
2766       LLVM_DEBUG(dbgs() << "No MUs to dispatch.\n");
2767 
2768     if (RegisterDependencies && !Q->QueryRegistrations.empty()) {
2769       LLVM_DEBUG(dbgs() << "Registering dependencies\n");
2770       RegisterDependencies(Q->QueryRegistrations);
2771     } else
2772       LLVM_DEBUG(dbgs() << "No dependencies to register\n");
2773 
2774     return Error::success();
2775   });
2776 
2777   if (LodgingErr) {
2778     LLVM_DEBUG(dbgs() << "Failing query\n");
2779     Q->detach();
2780     Q->handleFailed(std::move(LodgingErr));
2781     return;
2782   }
2783 
2784   if (QueryComplete) {
2785     LLVM_DEBUG(dbgs() << "Completing query\n");
2786     Q->handleComplete(*this);
2787   }
2788 
2789   dispatchOutstandingMUs();
2790 }
2791 
2792 void ExecutionSession::OL_completeLookupFlags(
2793     std::unique_ptr<InProgressLookupState> IPLS,
2794     unique_function<void(Expected<SymbolFlagsMap>)> OnComplete) {
2795 
2796   auto Result = runSessionLocked([&]() -> Expected<SymbolFlagsMap> {
2797     LLVM_DEBUG({
2798       dbgs() << "Entering OL_completeLookupFlags:\n"
2799              << "  Lookup kind: " << IPLS->K << "\n"
2800              << "  Search order: " << IPLS->SearchOrder
2801              << ", Current index = " << IPLS->CurSearchOrderIndex
2802              << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2803              << "  Lookup set: " << IPLS->LookupSet << "\n"
2804              << "  Definition generator candidates: "
2805              << IPLS->DefGeneratorCandidates << "\n"
2806              << "  Definition generator non-candidates: "
2807              << IPLS->DefGeneratorNonCandidates << "\n";
2808     });
2809 
2810     SymbolFlagsMap Result;
2811 
2812     // Attempt to find flags for each symbol.
2813     for (auto &KV : IPLS->SearchOrder) {
2814       auto &JD = *KV.first;
2815       auto JDLookupFlags = KV.second;
2816       LLVM_DEBUG({
2817         dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2818                << ") with lookup set " << IPLS->LookupSet << ":\n";
2819       });
2820 
2821       IPLS->LookupSet.forEachWithRemoval([&](const SymbolStringPtr &Name,
2822                                              SymbolLookupFlags SymLookupFlags) {
2823         LLVM_DEBUG({
2824           dbgs() << "  Attempting to match \"" << Name << "\" ("
2825                  << SymLookupFlags << ")... ";
2826         });
2827 
2828         // Search for the symbol. If not found then continue without removing
2829         // from the lookup set.
2830         auto SymI = JD.Symbols.find(Name);
2831         if (SymI == JD.Symbols.end()) {
2832           LLVM_DEBUG(dbgs() << "skipping: not present\n");
2833           return false;
2834         }
2835 
2836         // If this is a non-exported symbol then it doesn't match. Skip it.
2837         if (!SymI->second.getFlags().isExported() &&
2838             JDLookupFlags == JITDylibLookupFlags::MatchExportedSymbolsOnly) {
2839           LLVM_DEBUG(dbgs() << "skipping: not exported\n");
2840           return false;
2841         }
2842 
2843         LLVM_DEBUG({
2844           dbgs() << "matched, \"" << Name << "\" -> " << SymI->second.getFlags()
2845                  << "\n";
2846         });
2847         Result[Name] = SymI->second.getFlags();
2848         return true;
2849       });
2850     }
2851 
2852     // Remove any weakly referenced symbols that haven't been resolved.
2853     IPLS->LookupSet.remove_if(
2854         [](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2855           return SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol;
2856         });
2857 
2858     if (!IPLS->LookupSet.empty()) {
2859       LLVM_DEBUG(dbgs() << "Failing due to unresolved symbols\n");
2860       return make_error<SymbolsNotFound>(getSymbolStringPool(),
2861                                          IPLS->LookupSet.getSymbolNames());
2862     }
2863 
2864     LLVM_DEBUG(dbgs() << "Succeded, result = " << Result << "\n");
2865     return Result;
2866   });
2867 
2868   // Run the callback on the result.
2869   LLVM_DEBUG(dbgs() << "Sending result to handler.\n");
2870   OnComplete(std::move(Result));
2871 }
2872 
2873 void ExecutionSession::OL_destroyMaterializationResponsibility(
2874     MaterializationResponsibility &MR) {
2875 
2876   assert(MR.SymbolFlags.empty() &&
2877          "All symbols should have been explicitly materialized or failed");
2878   MR.JD.unlinkMaterializationResponsibility(MR);
2879 }
2880 
2881 SymbolNameSet ExecutionSession::OL_getRequestedSymbols(
2882     const MaterializationResponsibility &MR) {
2883   return MR.JD.getRequestedSymbols(MR.SymbolFlags);
2884 }
2885 
2886 Error ExecutionSession::OL_notifyResolved(MaterializationResponsibility &MR,
2887                                           const SymbolMap &Symbols) {
2888   LLVM_DEBUG({
2889     dbgs() << "In " << MR.JD.getName() << " resolving " << Symbols << "\n";
2890   });
2891 #ifndef NDEBUG
2892   for (auto &KV : Symbols) {
2893     auto I = MR.SymbolFlags.find(KV.first);
2894     assert(I != MR.SymbolFlags.end() &&
2895            "Resolving symbol outside this responsibility set");
2896     assert(!I->second.hasMaterializationSideEffectsOnly() &&
2897            "Can't resolve materialization-side-effects-only symbol");
2898     if (I->second & JITSymbolFlags::Common) {
2899       auto WeakOrCommon = JITSymbolFlags::Weak | JITSymbolFlags::Common;
2900       assert((KV.second.getFlags() & WeakOrCommon) &&
2901              "Common symbols must be resolved as common or weak");
2902       assert((KV.second.getFlags() & ~WeakOrCommon) ==
2903                  (I->second & ~JITSymbolFlags::Common) &&
2904              "Resolving symbol with incorrect flags");
2905     } else
2906       assert(KV.second.getFlags() == I->second &&
2907              "Resolving symbol with incorrect flags");
2908   }
2909 #endif
2910 
2911   return MR.JD.resolve(MR, Symbols);
2912 }
2913 
2914 template <typename HandleNewDepFn>
2915 void ExecutionSession::propagateExtraEmitDeps(
2916     std::deque<JITDylib::EmissionDepUnit *> Worklist, EDUInfosMap &EDUInfos,
2917     HandleNewDepFn HandleNewDep) {
2918 
2919   // Iterate to a fixed-point to propagate extra-emit dependencies through the
2920   // EDU graph.
2921   while (!Worklist.empty()) {
2922     auto &EDU = *Worklist.front();
2923     Worklist.pop_front();
2924 
2925     assert(EDUInfos.count(&EDU) && "No info entry for EDU");
2926     auto &EDUInfo = EDUInfos[&EDU];
2927 
2928     // Propagate new dependencies to users.
2929     for (auto *UserEDU : EDUInfo.IntraEmitUsers) {
2930 
2931       // UserEDUInfo only present if UserEDU has its own users.
2932       JITDylib::EmissionDepUnitInfo *UserEDUInfo = nullptr;
2933       {
2934         auto UserEDUInfoItr = EDUInfos.find(UserEDU);
2935         if (UserEDUInfoItr != EDUInfos.end())
2936           UserEDUInfo = &UserEDUInfoItr->second;
2937       }
2938 
2939       for (auto &[DepJD, Deps] : EDUInfo.NewDeps) {
2940         auto &UserEDUDepsForJD = UserEDU->Dependencies[DepJD];
2941         DenseSet<NonOwningSymbolStringPtr> *UserEDUNewDepsForJD = nullptr;
2942         for (auto Dep : Deps) {
2943           if (UserEDUDepsForJD.insert(Dep).second) {
2944             HandleNewDep(*UserEDU, *DepJD, Dep);
2945             if (UserEDUInfo) {
2946               if (!UserEDUNewDepsForJD) {
2947                 // If UserEDU has no new deps then it's not in the worklist
2948                 // yet, so add it.
2949                 if (UserEDUInfo->NewDeps.empty())
2950                   Worklist.push_back(UserEDU);
2951                 UserEDUNewDepsForJD = &UserEDUInfo->NewDeps[DepJD];
2952               }
2953               // Add (DepJD, Dep) to NewDeps.
2954               UserEDUNewDepsForJD->insert(Dep);
2955             }
2956           }
2957         }
2958       }
2959     }
2960 
2961     EDUInfo.NewDeps.clear();
2962   }
2963 }
2964 
2965 // Note: This method modifies the emitted set.
2966 ExecutionSession::EDUInfosMap ExecutionSession::simplifyDepGroups(
2967     MaterializationResponsibility &MR,
2968     ArrayRef<SymbolDependenceGroup> EmittedDeps) {
2969 
2970   auto &TargetJD = MR.getTargetJITDylib();
2971 
2972   // 1. Build initial EmissionDepUnit -> EmissionDepUnitInfo and
2973   //    Symbol -> EmissionDepUnit mappings.
2974   DenseMap<JITDylib::EmissionDepUnit *, JITDylib::EmissionDepUnitInfo> EDUInfos;
2975   EDUInfos.reserve(EmittedDeps.size());
2976   DenseMap<NonOwningSymbolStringPtr, JITDylib::EmissionDepUnit *> EDUForSymbol;
2977   for (auto &DG : EmittedDeps) {
2978     assert(!DG.Symbols.empty() && "DepGroup does not cover any symbols");
2979 
2980     // Skip empty EDUs.
2981     if (DG.Dependencies.empty())
2982       continue;
2983 
2984     auto TmpEDU = std::make_shared<JITDylib::EmissionDepUnit>(TargetJD);
2985     auto &EDUInfo = EDUInfos[TmpEDU.get()];
2986     EDUInfo.EDU = std::move(TmpEDU);
2987     for (const auto &Symbol : DG.Symbols) {
2988       NonOwningSymbolStringPtr NonOwningSymbol(Symbol);
2989       assert(!EDUForSymbol.count(NonOwningSymbol) &&
2990              "Symbol should not appear in more than one SymbolDependenceGroup");
2991       assert(MR.getSymbols().count(Symbol) &&
2992              "Symbol in DepGroups not in the emitted set");
2993       auto NewlyEmittedItr = MR.getSymbols().find(Symbol);
2994       EDUInfo.EDU->Symbols[NonOwningSymbol] = NewlyEmittedItr->second;
2995       EDUForSymbol[NonOwningSymbol] = EDUInfo.EDU.get();
2996     }
2997   }
2998 
2999   // 2. Build a "residual" EDU to cover all symbols that have no dependencies.
3000   {
3001     DenseMap<NonOwningSymbolStringPtr, JITSymbolFlags> ResidualSymbolFlags;
3002     for (auto &[Sym, Flags] : MR.getSymbols()) {
3003       if (!EDUForSymbol.count(NonOwningSymbolStringPtr(Sym)))
3004         ResidualSymbolFlags[NonOwningSymbolStringPtr(Sym)] = Flags;
3005     }
3006     if (!ResidualSymbolFlags.empty()) {
3007       auto ResidualEDU = std::make_shared<JITDylib::EmissionDepUnit>(TargetJD);
3008       ResidualEDU->Symbols = std::move(ResidualSymbolFlags);
3009       auto &ResidualEDUInfo = EDUInfos[ResidualEDU.get()];
3010       ResidualEDUInfo.EDU = std::move(ResidualEDU);
3011 
3012       // If the residual EDU is the only one then bail out early.
3013       if (EDUInfos.size() == 1)
3014         return EDUInfos;
3015 
3016       // Otherwise add the residual EDU to the EDUForSymbol map.
3017       for (auto &[Sym, Flags] : ResidualEDUInfo.EDU->Symbols)
3018         EDUForSymbol[Sym] = ResidualEDUInfo.EDU.get();
3019     }
3020   }
3021 
3022 #ifndef NDEBUG
3023   assert(EDUForSymbol.size() == MR.getSymbols().size() &&
3024          "MR symbols not fully covered by EDUs?");
3025   for (auto &[Sym, Flags] : MR.getSymbols()) {
3026     assert(EDUForSymbol.count(NonOwningSymbolStringPtr(Sym)) &&
3027            "Sym in MR not covered by EDU");
3028   }
3029 #endif // NDEBUG
3030 
3031   // 3. Use the DepGroups array to build a graph of dependencies between
3032   //    EmissionDepUnits in this finalization. We want to remove these
3033   //    intra-finalization uses, propagating dependencies on symbols outside
3034   //    this finalization. Add EDUs to the worklist.
3035   for (auto &DG : EmittedDeps) {
3036 
3037     // Skip SymbolDependenceGroups with no dependencies.
3038     if (DG.Dependencies.empty())
3039       continue;
3040 
3041     assert(EDUForSymbol.count(NonOwningSymbolStringPtr(*DG.Symbols.begin())) &&
3042            "No EDU for DG");
3043     auto &EDU =
3044         *EDUForSymbol.find(NonOwningSymbolStringPtr(*DG.Symbols.begin()))
3045              ->second;
3046 
3047     for (auto &[DepJD, Deps] : DG.Dependencies) {
3048       DenseSet<NonOwningSymbolStringPtr> NewDepsForJD;
3049 
3050       assert(!Deps.empty() && "Dependence set for DepJD is empty");
3051 
3052       if (DepJD != &TargetJD) {
3053         // DepJD is some other JITDylib.There can't be any intra-finalization
3054         // edges here, so just skip.
3055         for (auto &Dep : Deps)
3056           NewDepsForJD.insert(NonOwningSymbolStringPtr(Dep));
3057       } else {
3058         // DepJD is the Target JITDylib. Check for intra-finaliztaion edges,
3059         // skipping any and recording the intra-finalization use instead.
3060         for (auto &Dep : Deps) {
3061           NonOwningSymbolStringPtr NonOwningDep(Dep);
3062           auto I = EDUForSymbol.find(NonOwningDep);
3063           if (I == EDUForSymbol.end()) {
3064             if (!MR.getSymbols().count(Dep))
3065               NewDepsForJD.insert(NonOwningDep);
3066             continue;
3067           }
3068 
3069           if (I->second != &EDU)
3070             EDUInfos[I->second].IntraEmitUsers.insert(&EDU);
3071         }
3072       }
3073 
3074       if (!NewDepsForJD.empty())
3075         EDU.Dependencies[DepJD] = std::move(NewDepsForJD);
3076     }
3077   }
3078 
3079   // 4. Build the worklist.
3080   std::deque<JITDylib::EmissionDepUnit *> Worklist;
3081   for (auto &[EDU, EDUInfo] : EDUInfos) {
3082     // If this EDU has extra-finalization dependencies and intra-finalization
3083     // users then add it to the worklist.
3084     if (!EDU->Dependencies.empty()) {
3085       auto I = EDUInfos.find(EDU);
3086       if (I != EDUInfos.end()) {
3087         auto &EDUInfo = I->second;
3088         if (!EDUInfo.IntraEmitUsers.empty()) {
3089           EDUInfo.NewDeps = EDU->Dependencies;
3090           Worklist.push_back(EDU);
3091         }
3092       }
3093     }
3094   }
3095 
3096   // 4. Propagate dependencies through the EDU graph.
3097   propagateExtraEmitDeps(
3098       Worklist, EDUInfos,
3099       [](JITDylib::EmissionDepUnit &, JITDylib &, NonOwningSymbolStringPtr) {});
3100 
3101   return EDUInfos;
3102 }
3103 
3104 void ExecutionSession::IL_makeEDUReady(
3105     std::shared_ptr<JITDylib::EmissionDepUnit> EDU,
3106     JITDylib::AsynchronousSymbolQuerySet &Queries) {
3107 
3108   // The symbols for this EDU are ready.
3109   auto &JD = *EDU->JD;
3110 
3111   for (auto &[Sym, Flags] : EDU->Symbols) {
3112     assert(JD.Symbols.count(SymbolStringPtr(Sym)) &&
3113            "JD does not have an entry for Sym");
3114     auto &Entry = JD.Symbols[SymbolStringPtr(Sym)];
3115 
3116     assert(((Entry.getFlags().hasMaterializationSideEffectsOnly() &&
3117              Entry.getState() == SymbolState::Materializing) ||
3118             Entry.getState() == SymbolState::Resolved ||
3119             Entry.getState() == SymbolState::Emitted) &&
3120            "Emitting from state other than Resolved");
3121 
3122     Entry.setState(SymbolState::Ready);
3123 
3124     auto MII = JD.MaterializingInfos.find(SymbolStringPtr(Sym));
3125 
3126     // Check for pending queries.
3127     if (MII == JD.MaterializingInfos.end())
3128       continue;
3129     auto &MI = MII->second;
3130 
3131     for (auto &Q : MI.takeQueriesMeeting(SymbolState::Ready)) {
3132       Q->notifySymbolMetRequiredState(SymbolStringPtr(Sym), Entry.getSymbol());
3133       if (Q->isComplete())
3134         Queries.insert(Q);
3135       Q->removeQueryDependence(JD, SymbolStringPtr(Sym));
3136     }
3137 
3138     JD.MaterializingInfos.erase(MII);
3139   }
3140 
3141   JD.shrinkMaterializationInfoMemory();
3142 }
3143 
3144 void ExecutionSession::IL_makeEDUEmitted(
3145     std::shared_ptr<JITDylib::EmissionDepUnit> EDU,
3146     JITDylib::AsynchronousSymbolQuerySet &Queries) {
3147 
3148   // The symbols for this EDU are emitted, but not ready.
3149   auto &JD = *EDU->JD;
3150 
3151   for (auto &[Sym, Flags] : EDU->Symbols) {
3152     assert(JD.Symbols.count(SymbolStringPtr(Sym)) &&
3153            "JD does not have an entry for Sym");
3154     auto &Entry = JD.Symbols[SymbolStringPtr(Sym)];
3155 
3156     assert(((Entry.getFlags().hasMaterializationSideEffectsOnly() &&
3157              Entry.getState() == SymbolState::Materializing) ||
3158             Entry.getState() == SymbolState::Resolved ||
3159             Entry.getState() == SymbolState::Emitted) &&
3160            "Emitting from state other than Resolved");
3161 
3162     if (Entry.getState() == SymbolState::Emitted) {
3163       // This was already emitted, so we can skip the rest of this loop.
3164 #ifndef NDEBUG
3165       for (auto &[Sym, Flags] : EDU->Symbols) {
3166         assert(JD.Symbols.count(SymbolStringPtr(Sym)) &&
3167                "JD does not have an entry for Sym");
3168         auto &Entry = JD.Symbols[SymbolStringPtr(Sym)];
3169         assert(Entry.getState() == SymbolState::Emitted &&
3170                "Symbols for EDU in inconsistent state");
3171         assert(JD.MaterializingInfos.count(SymbolStringPtr(Sym)) &&
3172                "Emitted symbol has no MI");
3173         auto MI = JD.MaterializingInfos[SymbolStringPtr(Sym)];
3174         assert(MI.takeQueriesMeeting(SymbolState::Emitted).empty() &&
3175                "Already-emitted symbol has waiting-on-emitted queries");
3176       }
3177 #endif // NDEBUG
3178       break;
3179     }
3180 
3181     Entry.setState(SymbolState::Emitted);
3182     auto &MI = JD.MaterializingInfos[SymbolStringPtr(Sym)];
3183     MI.DefiningEDU = EDU;
3184 
3185     for (auto &Q : MI.takeQueriesMeeting(SymbolState::Emitted)) {
3186       Q->notifySymbolMetRequiredState(SymbolStringPtr(Sym), Entry.getSymbol());
3187       if (Q->isComplete())
3188         Queries.insert(Q);
3189     }
3190   }
3191 
3192   for (auto &[DepJD, Deps] : EDU->Dependencies) {
3193     for (auto &Dep : Deps)
3194       DepJD->MaterializingInfos[SymbolStringPtr(Dep)].DependantEDUs.insert(
3195           EDU.get());
3196   }
3197 }
3198 
3199 /// Removes the given dependence from EDU. If EDU's dependence set becomes
3200 /// empty then this function adds an entry for it to the EDUInfos map.
3201 /// Returns true if a new EDUInfosMap entry is added.
3202 bool ExecutionSession::IL_removeEDUDependence(JITDylib::EmissionDepUnit &EDU,
3203                                               JITDylib &DepJD,
3204                                               NonOwningSymbolStringPtr DepSym,
3205                                               EDUInfosMap &EDUInfos) {
3206   assert(EDU.Dependencies.count(&DepJD) &&
3207          "JD does not appear in Dependencies of DependantEDU");
3208   assert(EDU.Dependencies[&DepJD].count(DepSym) &&
3209          "Symbol does not appear in Dependencies of DependantEDU");
3210   auto &JDDeps = EDU.Dependencies[&DepJD];
3211   JDDeps.erase(DepSym);
3212   if (JDDeps.empty()) {
3213     EDU.Dependencies.erase(&DepJD);
3214     if (EDU.Dependencies.empty()) {
3215       // If the dependencies set has become empty then EDU _may_ be ready
3216       // (we won't know for sure until we've propagated the extra-emit deps).
3217       // Create an EDUInfo for it (if it doesn't have one already) so that
3218       // it'll be visited after propagation.
3219       auto &DepEDUInfo = EDUInfos[&EDU];
3220       if (!DepEDUInfo.EDU) {
3221         assert(EDU.JD->Symbols.count(
3222                    SymbolStringPtr(EDU.Symbols.begin()->first)) &&
3223                "Missing symbol entry for first symbol in EDU");
3224         auto DepEDUFirstMI = EDU.JD->MaterializingInfos.find(
3225             SymbolStringPtr(EDU.Symbols.begin()->first));
3226         assert(DepEDUFirstMI != EDU.JD->MaterializingInfos.end() &&
3227                "Missing MI for first symbol in DependantEDU");
3228         DepEDUInfo.EDU = DepEDUFirstMI->second.DefiningEDU;
3229         return true;
3230       }
3231     }
3232   }
3233   return false;
3234 }
3235 
3236 Error ExecutionSession::makeJDClosedError(JITDylib::EmissionDepUnit &EDU,
3237                                           JITDylib &ClosedJD) {
3238   SymbolNameSet FailedSymbols;
3239   for (auto &[Sym, Flags] : EDU.Symbols)
3240     FailedSymbols.insert(SymbolStringPtr(Sym));
3241   SymbolDependenceMap BadDeps;
3242   for (auto &Dep : EDU.Dependencies[&ClosedJD])
3243     BadDeps[&ClosedJD].insert(SymbolStringPtr(Dep));
3244   return make_error<UnsatisfiedSymbolDependencies>(
3245       ClosedJD.getExecutionSession().getSymbolStringPool(), EDU.JD,
3246       std::move(FailedSymbols), std::move(BadDeps),
3247       ClosedJD.getName() + " is closed");
3248 }
3249 
3250 Error ExecutionSession::makeUnsatisfiedDepsError(JITDylib::EmissionDepUnit &EDU,
3251                                                  JITDylib &BadJD,
3252                                                  SymbolNameSet BadDeps) {
3253   SymbolNameSet FailedSymbols;
3254   for (auto &[Sym, Flags] : EDU.Symbols)
3255     FailedSymbols.insert(SymbolStringPtr(Sym));
3256   SymbolDependenceMap BadDepsMap;
3257   BadDepsMap[&BadJD] = std::move(BadDeps);
3258   return make_error<UnsatisfiedSymbolDependencies>(
3259       BadJD.getExecutionSession().getSymbolStringPool(), &BadJD,
3260       std::move(FailedSymbols), std::move(BadDepsMap),
3261       "dependencies removed or in error state");
3262 }
3263 
3264 Expected<JITDylib::AsynchronousSymbolQuerySet>
3265 ExecutionSession::IL_emit(MaterializationResponsibility &MR,
3266                           EDUInfosMap EDUInfos) {
3267 
3268   if (MR.RT->isDefunct())
3269     return make_error<ResourceTrackerDefunct>(MR.RT);
3270 
3271   auto &TargetJD = MR.getTargetJITDylib();
3272   if (TargetJD.State != JITDylib::Open)
3273     return make_error<StringError>("JITDylib " + TargetJD.getName() +
3274                                        " is defunct",
3275                                    inconvertibleErrorCode());
3276 #ifdef EXPENSIVE_CHECKS
3277   verifySessionState("entering ExecutionSession::IL_emit");
3278 #endif
3279 
3280   // Walk all EDUs:
3281   // 1. Verifying that dependencies are available (not removed or in the error
3282   //    state.
3283   // 2. Removing any dependencies that are already Ready.
3284   // 3. Lifting any EDUs for Emitted symbols into the EDUInfos map.
3285   // 4. Finding any dependant EDUs and lifting them into the EDUInfos map.
3286   std::deque<JITDylib::EmissionDepUnit *> Worklist;
3287   for (auto &[EDU, _] : EDUInfos)
3288     Worklist.push_back(EDU);
3289 
3290   for (auto *EDU : Worklist) {
3291     auto *EDUInfo = &EDUInfos[EDU];
3292 
3293     SmallVector<JITDylib *> DepJDsToRemove;
3294     for (auto &[DepJD, Deps] : EDU->Dependencies) {
3295       if (DepJD->State != JITDylib::Open)
3296         return makeJDClosedError(*EDU, *DepJD);
3297 
3298       SymbolNameSet BadDeps;
3299       SmallVector<NonOwningSymbolStringPtr> DepsToRemove;
3300       for (auto &Dep : Deps) {
3301         auto DepEntryItr = DepJD->Symbols.find(SymbolStringPtr(Dep));
3302 
3303         // If this dep has been removed or moved to the error state then add it
3304         // to the bad deps set. We aggregate these bad deps for more
3305         // comprehensive error messages.
3306         if (DepEntryItr == DepJD->Symbols.end() ||
3307             DepEntryItr->second.getFlags().hasError()) {
3308           BadDeps.insert(SymbolStringPtr(Dep));
3309           continue;
3310         }
3311 
3312         // If this dep isn't emitted yet then just add it to the NewDeps set to
3313         // be propagated.
3314         auto &DepEntry = DepEntryItr->second;
3315         if (DepEntry.getState() < SymbolState::Emitted) {
3316           EDUInfo->NewDeps[DepJD].insert(Dep);
3317           continue;
3318         }
3319 
3320         // This dep has been emitted, so add it to the list to be removed from
3321         // EDU.
3322         DepsToRemove.push_back(Dep);
3323 
3324         // If Dep is Ready then there's nothing further to do.
3325         if (DepEntry.getState() == SymbolState::Ready) {
3326           assert(!DepJD->MaterializingInfos.count(SymbolStringPtr(Dep)) &&
3327                  "Unexpected MaterializationInfo attached to ready symbol");
3328           continue;
3329         }
3330 
3331         // If we get here then Dep is Emitted. We need to look up its defining
3332         // EDU and add this EDU to the defining EDU's list of users (this means
3333         // creating an EDUInfos entry if the defining EDU doesn't have one
3334         // already).
3335         assert(DepJD->MaterializingInfos.count(SymbolStringPtr(Dep)) &&
3336                "Expected MaterializationInfo for emitted dependency");
3337         auto &DepMI = DepJD->MaterializingInfos[SymbolStringPtr(Dep)];
3338         assert(DepMI.DefiningEDU &&
3339                "Emitted symbol does not have a defining EDU");
3340         assert(DepMI.DependantEDUs.empty() &&
3341                "Already-emitted symbol has dependant EDUs?");
3342         auto &DepEDUInfo = EDUInfos[DepMI.DefiningEDU.get()];
3343         if (!DepEDUInfo.EDU) {
3344           // No EDUInfo yet -- build initial entry, and reset the EDUInfo
3345           // pointer, which we will have invalidated.
3346           EDUInfo = &EDUInfos[EDU];
3347           DepEDUInfo.EDU = DepMI.DefiningEDU;
3348           for (auto &[DepDepJD, DepDeps] : DepEDUInfo.EDU->Dependencies) {
3349             if (DepDepJD == &TargetJD) {
3350               for (auto &DepDep : DepDeps)
3351                 if (!MR.getSymbols().count(SymbolStringPtr(DepDep)))
3352                   DepEDUInfo.NewDeps[DepDepJD].insert(DepDep);
3353             } else
3354               DepEDUInfo.NewDeps[DepDepJD] = DepDeps;
3355           }
3356         }
3357         DepEDUInfo.IntraEmitUsers.insert(EDU);
3358       }
3359 
3360       // Some dependencies were removed or in an error state -- error out.
3361       if (!BadDeps.empty())
3362         return makeUnsatisfiedDepsError(*EDU, *DepJD, std::move(BadDeps));
3363 
3364       // Remove the emitted / ready deps from DepJD.
3365       for (auto &Dep : DepsToRemove)
3366         Deps.erase(Dep);
3367 
3368       // If there are no further deps in DepJD then flag it for removal too.
3369       if (Deps.empty())
3370         DepJDsToRemove.push_back(DepJD);
3371     }
3372 
3373     // Remove any JDs whose dependence sets have become empty.
3374     for (auto &DepJD : DepJDsToRemove) {
3375       assert(EDU->Dependencies.count(DepJD) &&
3376              "Trying to remove non-existent dep entries");
3377       EDU->Dependencies.erase(DepJD);
3378     }
3379 
3380     // Now look for users of this EDU.
3381     for (auto &[Sym, Flags] : EDU->Symbols) {
3382       assert(TargetJD.Symbols.count(SymbolStringPtr(Sym)) &&
3383              "Sym not present in symbol table");
3384       assert((TargetJD.Symbols[SymbolStringPtr(Sym)].getState() ==
3385                   SymbolState::Resolved ||
3386               TargetJD.Symbols[SymbolStringPtr(Sym)]
3387                   .getFlags()
3388                   .hasMaterializationSideEffectsOnly()) &&
3389              "Emitting symbol not in the resolved state");
3390       assert(!TargetJD.Symbols[SymbolStringPtr(Sym)].getFlags().hasError() &&
3391              "Symbol is already in an error state");
3392 
3393       auto MII = TargetJD.MaterializingInfos.find(SymbolStringPtr(Sym));
3394       if (MII == TargetJD.MaterializingInfos.end() ||
3395           MII->second.DependantEDUs.empty())
3396         continue;
3397 
3398       for (auto &DependantEDU : MII->second.DependantEDUs) {
3399         if (IL_removeEDUDependence(*DependantEDU, TargetJD, Sym, EDUInfos))
3400           EDUInfo = &EDUInfos[EDU];
3401         EDUInfo->IntraEmitUsers.insert(DependantEDU);
3402       }
3403       MII->second.DependantEDUs.clear();
3404     }
3405   }
3406 
3407   Worklist.clear();
3408   for (auto &[EDU, EDUInfo] : EDUInfos) {
3409     if (!EDUInfo.IntraEmitUsers.empty() && !EDU->Dependencies.empty()) {
3410       if (EDUInfo.NewDeps.empty())
3411         EDUInfo.NewDeps = EDU->Dependencies;
3412       Worklist.push_back(EDU);
3413     }
3414   }
3415 
3416   propagateExtraEmitDeps(
3417       Worklist, EDUInfos,
3418       [](JITDylib::EmissionDepUnit &EDU, JITDylib &JD,
3419          NonOwningSymbolStringPtr Sym) {
3420         JD.MaterializingInfos[SymbolStringPtr(Sym)].DependantEDUs.insert(&EDU);
3421       });
3422 
3423   JITDylib::AsynchronousSymbolQuerySet CompletedQueries;
3424 
3425   // Extract completed queries and lodge not-yet-ready EDUs in the
3426   // session.
3427   for (auto &[EDU, EDUInfo] : EDUInfos) {
3428     if (EDU->Dependencies.empty())
3429       IL_makeEDUReady(std::move(EDUInfo.EDU), CompletedQueries);
3430     else
3431       IL_makeEDUEmitted(std::move(EDUInfo.EDU), CompletedQueries);
3432   }
3433 
3434 #ifdef EXPENSIVE_CHECKS
3435   verifySessionState("exiting ExecutionSession::IL_emit");
3436 #endif
3437 
3438   return std::move(CompletedQueries);
3439 }
3440 
3441 Error ExecutionSession::OL_notifyEmitted(
3442     MaterializationResponsibility &MR,
3443     ArrayRef<SymbolDependenceGroup> DepGroups) {
3444   LLVM_DEBUG({
3445     dbgs() << "In " << MR.JD.getName() << " emitting " << MR.SymbolFlags
3446            << "\n";
3447     if (!DepGroups.empty()) {
3448       dbgs() << "  Initial dependencies:\n";
3449       for (auto &SDG : DepGroups) {
3450         dbgs() << "    Symbols: " << SDG.Symbols
3451                << ", Dependencies: " << SDG.Dependencies << "\n";
3452       }
3453     }
3454   });
3455 
3456 #ifndef NDEBUG
3457   SymbolNameSet Visited;
3458   for (auto &DG : DepGroups) {
3459     for (auto &Sym : DG.Symbols) {
3460       assert(MR.SymbolFlags.count(Sym) &&
3461              "DG contains dependence for symbol outside this MR");
3462       assert(Visited.insert(Sym).second &&
3463              "DG contains duplicate entries for Name");
3464     }
3465   }
3466 #endif // NDEBUG
3467 
3468   auto EDUInfos = simplifyDepGroups(MR, DepGroups);
3469 
3470   LLVM_DEBUG({
3471     dbgs() << "  Simplified dependencies:\n";
3472     for (auto &[EDU, EDUInfo] : EDUInfos) {
3473       dbgs() << "    Symbols: { ";
3474       for (auto &[Sym, Flags] : EDU->Symbols)
3475         dbgs() << Sym << " ";
3476       dbgs() << "}, Dependencies: { ";
3477       for (auto &[DepJD, Deps] : EDU->Dependencies) {
3478         dbgs() << "(" << DepJD->getName() << ", { ";
3479         for (auto &Dep : Deps)
3480           dbgs() << Dep << " ";
3481         dbgs() << "}) ";
3482       }
3483       dbgs() << "}\n";
3484     }
3485   });
3486 
3487   auto CompletedQueries =
3488       runSessionLocked([&]() { return IL_emit(MR, EDUInfos); });
3489 
3490   // On error bail out.
3491   if (!CompletedQueries)
3492     return CompletedQueries.takeError();
3493 
3494   MR.SymbolFlags.clear();
3495 
3496   // Otherwise notify all the completed queries.
3497   for (auto &Q : *CompletedQueries) {
3498     assert(Q->isComplete() && "Q is not complete");
3499     Q->handleComplete(*this);
3500   }
3501 
3502   return Error::success();
3503 }
3504 
3505 Error ExecutionSession::OL_defineMaterializing(
3506     MaterializationResponsibility &MR, SymbolFlagsMap NewSymbolFlags) {
3507 
3508   LLVM_DEBUG({
3509     dbgs() << "In " << MR.JD.getName() << " defining materializing symbols "
3510            << NewSymbolFlags << "\n";
3511   });
3512   if (auto AcceptedDefs =
3513           MR.JD.defineMaterializing(MR, std::move(NewSymbolFlags))) {
3514     // Add all newly accepted symbols to this responsibility object.
3515     for (auto &KV : *AcceptedDefs)
3516       MR.SymbolFlags.insert(KV);
3517     return Error::success();
3518   } else
3519     return AcceptedDefs.takeError();
3520 }
3521 
3522 std::pair<JITDylib::AsynchronousSymbolQuerySet,
3523           std::shared_ptr<SymbolDependenceMap>>
3524 ExecutionSession::IL_failSymbols(JITDylib &JD,
3525                                  const SymbolNameVector &SymbolsToFail) {
3526 
3527 #ifdef EXPENSIVE_CHECKS
3528   verifySessionState("entering ExecutionSession::IL_failSymbols");
3529 #endif
3530 
3531   JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3532   auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
3533   auto ExtractFailedQueries = [&](JITDylib::MaterializingInfo &MI) {
3534     JITDylib::AsynchronousSymbolQueryList ToDetach;
3535     for (auto &Q : MI.pendingQueries()) {
3536       // Add the query to the list to be failed and detach it.
3537       FailedQueries.insert(Q);
3538       ToDetach.push_back(Q);
3539     }
3540     for (auto &Q : ToDetach)
3541       Q->detach();
3542     assert(!MI.hasQueriesPending() && "Queries still pending after detach");
3543   };
3544 
3545   for (auto &Name : SymbolsToFail) {
3546     (*FailedSymbolsMap)[&JD].insert(Name);
3547 
3548     // Look up the symbol to fail.
3549     auto SymI = JD.Symbols.find(Name);
3550 
3551     // FIXME: Revisit this. We should be able to assert sequencing between
3552     //        ResourceTracker removal and symbol failure.
3553     //
3554     // It's possible that this symbol has already been removed, e.g. if a
3555     // materialization failure happens concurrently with a ResourceTracker or
3556     // JITDylib removal. In that case we can safely skip this symbol and
3557     // continue.
3558     if (SymI == JD.Symbols.end())
3559       continue;
3560     auto &Sym = SymI->second;
3561 
3562     // If the symbol is already in the error state then we must have visited
3563     // it earlier.
3564     if (Sym.getFlags().hasError()) {
3565       assert(!JD.MaterializingInfos.count(Name) &&
3566              "Symbol in error state still has MaterializingInfo");
3567       continue;
3568     }
3569 
3570     // Move the symbol into the error state.
3571     Sym.setFlags(Sym.getFlags() | JITSymbolFlags::HasError);
3572 
3573     // FIXME: Come up with a sane mapping of state to
3574     // presence-of-MaterializingInfo so that we can assert presence / absence
3575     // here, rather than testing it.
3576     auto MII = JD.MaterializingInfos.find(Name);
3577     if (MII == JD.MaterializingInfos.end())
3578       continue;
3579 
3580     auto &MI = MII->second;
3581 
3582     // Collect queries to be failed for this MII.
3583     ExtractFailedQueries(MI);
3584 
3585     if (MI.DefiningEDU) {
3586       // If there is a DefiningEDU for this symbol then remove this
3587       // symbol from it.
3588       assert(MI.DependantEDUs.empty() &&
3589              "Symbol with DefiningEDU should not have DependantEDUs");
3590       assert(Sym.getState() >= SymbolState::Emitted &&
3591              "Symbol has EDU, should have been emitted");
3592       assert(MI.DefiningEDU->Symbols.count(NonOwningSymbolStringPtr(Name)) &&
3593              "Symbol does not appear in its DefiningEDU");
3594       MI.DefiningEDU->Symbols.erase(NonOwningSymbolStringPtr(Name));
3595 
3596       // Remove this EDU from the dependants lists of its dependencies.
3597       for (auto &[DepJD, DepSyms] : MI.DefiningEDU->Dependencies) {
3598         for (auto DepSym : DepSyms) {
3599           assert(DepJD->Symbols.count(SymbolStringPtr(DepSym)) &&
3600                  "DepSym not in DepJD");
3601           assert(DepJD->MaterializingInfos.count(SymbolStringPtr(DepSym)) &&
3602                  "DepSym has not MaterializingInfo");
3603           auto &SymMI = DepJD->MaterializingInfos[SymbolStringPtr(DepSym)];
3604           assert(SymMI.DependantEDUs.count(MI.DefiningEDU.get()) &&
3605                  "DefiningEDU missing from DependantEDUs list of dependency");
3606           SymMI.DependantEDUs.erase(MI.DefiningEDU.get());
3607         }
3608       }
3609 
3610       MI.DefiningEDU = nullptr;
3611     } else {
3612       // Otherwise if there are any EDUs waiting on this symbol then move
3613       // those symbols to the error state too, and deregister them from the
3614       // symbols that they depend on.
3615       // Note: We use a copy of DependantEDUs here since we'll be removing
3616       // from the original set as we go.
3617       for (auto &DependantEDU : MI.DependantEDUs) {
3618 
3619         // Remove DependantEDU from all of its users DependantEDUs lists.
3620         for (auto &[DepJD, DepSyms] : DependantEDU->Dependencies) {
3621           for (auto DepSym : DepSyms) {
3622             // Skip self-reference to avoid invalidating the MI.DependantEDUs
3623             // map. We'll clear this later.
3624             if (DepJD == &JD && DepSym == Name)
3625               continue;
3626             assert(DepJD->Symbols.count(SymbolStringPtr(DepSym)) &&
3627                    "DepSym not in DepJD?");
3628             assert(DepJD->MaterializingInfos.count(SymbolStringPtr(DepSym)) &&
3629                    "DependantEDU not registered with symbol it depends on");
3630             auto &SymMI = DepJD->MaterializingInfos[SymbolStringPtr(DepSym)];
3631             assert(SymMI.DependantEDUs.count(DependantEDU) &&
3632                    "DependantEDU missing from DependantEDUs list");
3633             SymMI.DependantEDUs.erase(DependantEDU);
3634           }
3635         }
3636 
3637         // Move any symbols defined by DependantEDU into the error state and
3638         // fail any queries waiting on them.
3639         auto &DepJD = *DependantEDU->JD;
3640         auto DepEDUSymbols = std::move(DependantEDU->Symbols);
3641         for (auto &[DepName, Flags] : DepEDUSymbols) {
3642           auto DepSymItr = DepJD.Symbols.find(SymbolStringPtr(DepName));
3643           assert(DepSymItr != DepJD.Symbols.end() &&
3644                  "Symbol not present in table");
3645           auto &DepSym = DepSymItr->second;
3646 
3647           assert(DepSym.getState() >= SymbolState::Emitted &&
3648                  "Symbol has EDU, should have been emitted");
3649           assert(!DepSym.getFlags().hasError() &&
3650                  "Symbol is already in the error state?");
3651           DepSym.setFlags(DepSym.getFlags() | JITSymbolFlags::HasError);
3652           (*FailedSymbolsMap)[&DepJD].insert(SymbolStringPtr(DepName));
3653 
3654           // This symbol has a defining EDU so its MaterializingInfo object must
3655           // exist.
3656           auto DepMIItr =
3657               DepJD.MaterializingInfos.find(SymbolStringPtr(DepName));
3658           assert(DepMIItr != DepJD.MaterializingInfos.end() &&
3659                  "Symbol has defining EDU but not MaterializingInfo");
3660           auto &DepMI = DepMIItr->second;
3661           assert(DepMI.DefiningEDU.get() == DependantEDU &&
3662                  "Bad EDU dependence edge");
3663           assert(DepMI.DependantEDUs.empty() &&
3664                  "Symbol was emitted, should not have any DependantEDUs");
3665           ExtractFailedQueries(DepMI);
3666           DepJD.MaterializingInfos.erase(SymbolStringPtr(DepName));
3667         }
3668 
3669         DepJD.shrinkMaterializationInfoMemory();
3670       }
3671 
3672       MI.DependantEDUs.clear();
3673     }
3674 
3675     assert(!MI.DefiningEDU && "DefiningEDU should have been reset");
3676     assert(MI.DependantEDUs.empty() &&
3677            "DependantEDUs should have been removed above");
3678     assert(!MI.hasQueriesPending() &&
3679            "Can not delete MaterializingInfo with queries pending");
3680     JD.MaterializingInfos.erase(Name);
3681   }
3682 
3683   JD.shrinkMaterializationInfoMemory();
3684 
3685 #ifdef EXPENSIVE_CHECKS
3686   verifySessionState("exiting ExecutionSession::IL_failSymbols");
3687 #endif
3688 
3689   return std::make_pair(std::move(FailedQueries), std::move(FailedSymbolsMap));
3690 }
3691 
3692 void ExecutionSession::OL_notifyFailed(MaterializationResponsibility &MR) {
3693 
3694   LLVM_DEBUG({
3695     dbgs() << "In " << MR.JD.getName() << " failing materialization for "
3696            << MR.SymbolFlags << "\n";
3697   });
3698 
3699   if (MR.SymbolFlags.empty())
3700     return;
3701 
3702   SymbolNameVector SymbolsToFail;
3703   for (auto &[Name, Flags] : MR.SymbolFlags)
3704     SymbolsToFail.push_back(Name);
3705   MR.SymbolFlags.clear();
3706 
3707   JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3708   std::shared_ptr<SymbolDependenceMap> FailedSymbols;
3709 
3710   std::tie(FailedQueries, FailedSymbols) = runSessionLocked([&]() {
3711     // If the tracker is defunct then there's nothing to do here.
3712     if (MR.RT->isDefunct())
3713       return std::pair<JITDylib::AsynchronousSymbolQuerySet,
3714                        std::shared_ptr<SymbolDependenceMap>>();
3715     return IL_failSymbols(MR.getTargetJITDylib(), SymbolsToFail);
3716   });
3717 
3718   for (auto &Q : FailedQueries)
3719     Q->handleFailed(
3720         make_error<FailedToMaterialize>(getSymbolStringPool(), FailedSymbols));
3721 }
3722 
3723 Error ExecutionSession::OL_replace(MaterializationResponsibility &MR,
3724                                    std::unique_ptr<MaterializationUnit> MU) {
3725   for (auto &KV : MU->getSymbols()) {
3726     assert(MR.SymbolFlags.count(KV.first) &&
3727            "Replacing definition outside this responsibility set");
3728     MR.SymbolFlags.erase(KV.first);
3729   }
3730 
3731   if (MU->getInitializerSymbol() == MR.InitSymbol)
3732     MR.InitSymbol = nullptr;
3733 
3734   LLVM_DEBUG(MR.JD.getExecutionSession().runSessionLocked([&]() {
3735     dbgs() << "In " << MR.JD.getName() << " replacing symbols with " << *MU
3736            << "\n";
3737   }););
3738 
3739   return MR.JD.replace(MR, std::move(MU));
3740 }
3741 
3742 Expected<std::unique_ptr<MaterializationResponsibility>>
3743 ExecutionSession::OL_delegate(MaterializationResponsibility &MR,
3744                               const SymbolNameSet &Symbols) {
3745 
3746   SymbolStringPtr DelegatedInitSymbol;
3747   SymbolFlagsMap DelegatedFlags;
3748 
3749   for (auto &Name : Symbols) {
3750     auto I = MR.SymbolFlags.find(Name);
3751     assert(I != MR.SymbolFlags.end() &&
3752            "Symbol is not tracked by this MaterializationResponsibility "
3753            "instance");
3754 
3755     DelegatedFlags[Name] = std::move(I->second);
3756     if (Name == MR.InitSymbol)
3757       std::swap(MR.InitSymbol, DelegatedInitSymbol);
3758 
3759     MR.SymbolFlags.erase(I);
3760   }
3761 
3762   return MR.JD.delegate(MR, std::move(DelegatedFlags),
3763                         std::move(DelegatedInitSymbol));
3764 }
3765 
3766 #ifndef NDEBUG
3767 void ExecutionSession::dumpDispatchInfo(Task &T) {
3768   runSessionLocked([&]() {
3769     dbgs() << "Dispatching: ";
3770     T.printDescription(dbgs());
3771     dbgs() << "\n";
3772   });
3773 }
3774 #endif // NDEBUG
3775 
3776 } // End namespace orc.
3777 } // End namespace llvm.
3778