xref: /freebsd-src/contrib/llvm-project/llvm/lib/ExecutionEngine/Orc/Core.cpp (revision 4824e7fd18a1223177218d4aec1b3c6c5c4a444e)
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 
18 #include <condition_variable>
19 #include <future>
20 
21 #define DEBUG_TYPE "orc"
22 
23 namespace llvm {
24 namespace orc {
25 
26 char ResourceTrackerDefunct::ID = 0;
27 char FailedToMaterialize::ID = 0;
28 char SymbolsNotFound::ID = 0;
29 char SymbolsCouldNotBeRemoved::ID = 0;
30 char MissingSymbolDefinitions::ID = 0;
31 char UnexpectedSymbolDefinitions::ID = 0;
32 char MaterializationTask::ID = 0;
33 
34 RegisterDependenciesFunction NoDependenciesToRegister =
35     RegisterDependenciesFunction();
36 
37 void MaterializationUnit::anchor() {}
38 
39 ResourceTracker::ResourceTracker(JITDylibSP JD) {
40   assert((reinterpret_cast<uintptr_t>(JD.get()) & 0x1) == 0 &&
41          "JITDylib must be two byte aligned");
42   JD->Retain();
43   JDAndFlag.store(reinterpret_cast<uintptr_t>(JD.get()));
44 }
45 
46 ResourceTracker::~ResourceTracker() {
47   getJITDylib().getExecutionSession().destroyResourceTracker(*this);
48   getJITDylib().Release();
49 }
50 
51 Error ResourceTracker::remove() {
52   return getJITDylib().getExecutionSession().removeResourceTracker(*this);
53 }
54 
55 void ResourceTracker::transferTo(ResourceTracker &DstRT) {
56   getJITDylib().getExecutionSession().transferResourceTracker(DstRT, *this);
57 }
58 
59 void ResourceTracker::makeDefunct() {
60   uintptr_t Val = JDAndFlag.load();
61   Val |= 0x1U;
62   JDAndFlag.store(Val);
63 }
64 
65 ResourceManager::~ResourceManager() {}
66 
67 ResourceTrackerDefunct::ResourceTrackerDefunct(ResourceTrackerSP RT)
68     : RT(std::move(RT)) {}
69 
70 std::error_code ResourceTrackerDefunct::convertToErrorCode() const {
71   return orcError(OrcErrorCode::UnknownORCError);
72 }
73 
74 void ResourceTrackerDefunct::log(raw_ostream &OS) const {
75   OS << "Resource tracker " << (void *)RT.get() << " became defunct";
76 }
77 
78 FailedToMaterialize::FailedToMaterialize(
79     std::shared_ptr<SymbolDependenceMap> Symbols)
80     : Symbols(std::move(Symbols)) {
81   assert(!this->Symbols->empty() && "Can not fail to resolve an empty set");
82 }
83 
84 std::error_code FailedToMaterialize::convertToErrorCode() const {
85   return orcError(OrcErrorCode::UnknownORCError);
86 }
87 
88 void FailedToMaterialize::log(raw_ostream &OS) const {
89   OS << "Failed to materialize symbols: " << *Symbols;
90 }
91 
92 SymbolsNotFound::SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP,
93                                  SymbolNameSet Symbols)
94     : SSP(std::move(SSP)) {
95   for (auto &Sym : Symbols)
96     this->Symbols.push_back(Sym);
97   assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
98 }
99 
100 SymbolsNotFound::SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP,
101                                  SymbolNameVector Symbols)
102     : SSP(std::move(SSP)), Symbols(std::move(Symbols)) {
103   assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
104 }
105 
106 std::error_code SymbolsNotFound::convertToErrorCode() const {
107   return orcError(OrcErrorCode::UnknownORCError);
108 }
109 
110 void SymbolsNotFound::log(raw_ostream &OS) const {
111   OS << "Symbols not found: " << Symbols;
112 }
113 
114 SymbolsCouldNotBeRemoved::SymbolsCouldNotBeRemoved(
115     std::shared_ptr<SymbolStringPool> SSP, SymbolNameSet Symbols)
116     : SSP(std::move(SSP)), Symbols(std::move(Symbols)) {
117   assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
118 }
119 
120 std::error_code SymbolsCouldNotBeRemoved::convertToErrorCode() const {
121   return orcError(OrcErrorCode::UnknownORCError);
122 }
123 
124 void SymbolsCouldNotBeRemoved::log(raw_ostream &OS) const {
125   OS << "Symbols could not be removed: " << Symbols;
126 }
127 
128 std::error_code MissingSymbolDefinitions::convertToErrorCode() const {
129   return orcError(OrcErrorCode::MissingSymbolDefinitions);
130 }
131 
132 void MissingSymbolDefinitions::log(raw_ostream &OS) const {
133   OS << "Missing definitions in module " << ModuleName
134      << ": " << Symbols;
135 }
136 
137 std::error_code UnexpectedSymbolDefinitions::convertToErrorCode() const {
138   return orcError(OrcErrorCode::UnexpectedSymbolDefinitions);
139 }
140 
141 void UnexpectedSymbolDefinitions::log(raw_ostream &OS) const {
142   OS << "Unexpected definitions in module " << ModuleName
143      << ": " << Symbols;
144 }
145 
146 AsynchronousSymbolQuery::AsynchronousSymbolQuery(
147     const SymbolLookupSet &Symbols, SymbolState RequiredState,
148     SymbolsResolvedCallback NotifyComplete)
149     : NotifyComplete(std::move(NotifyComplete)), RequiredState(RequiredState) {
150   assert(RequiredState >= SymbolState::Resolved &&
151          "Cannot query for a symbols that have not reached the resolve state "
152          "yet");
153 
154   OutstandingSymbolsCount = Symbols.size();
155 
156   for (auto &KV : Symbols)
157     ResolvedSymbols[KV.first] = nullptr;
158 }
159 
160 void AsynchronousSymbolQuery::notifySymbolMetRequiredState(
161     const SymbolStringPtr &Name, JITEvaluatedSymbol Sym) {
162   auto I = ResolvedSymbols.find(Name);
163   assert(I != ResolvedSymbols.end() &&
164          "Resolving symbol outside the requested set");
165   assert(I->second.getAddress() == 0 && "Redundantly resolving symbol Name");
166 
167   // If this is a materialization-side-effects-only symbol then drop it,
168   // otherwise update its map entry with its resolved address.
169   if (Sym.getFlags().hasMaterializationSideEffectsOnly())
170     ResolvedSymbols.erase(I);
171   else
172     I->second = std::move(Sym);
173   --OutstandingSymbolsCount;
174 }
175 
176 void AsynchronousSymbolQuery::handleComplete(ExecutionSession &ES) {
177   assert(OutstandingSymbolsCount == 0 &&
178          "Symbols remain, handleComplete called prematurely");
179 
180   class RunQueryCompleteTask : public Task {
181   public:
182     RunQueryCompleteTask(SymbolMap ResolvedSymbols,
183                          SymbolsResolvedCallback NotifyComplete)
184         : ResolvedSymbols(std::move(ResolvedSymbols)),
185           NotifyComplete(std::move(NotifyComplete)) {}
186     void printDescription(raw_ostream &OS) override {
187       OS << "Execute query complete callback for " << ResolvedSymbols;
188     }
189     void run() override { NotifyComplete(std::move(ResolvedSymbols)); }
190 
191   private:
192     SymbolMap ResolvedSymbols;
193     SymbolsResolvedCallback NotifyComplete;
194   };
195 
196   auto T = std::make_unique<RunQueryCompleteTask>(std::move(ResolvedSymbols),
197                                                   std::move(NotifyComplete));
198   NotifyComplete = SymbolsResolvedCallback();
199   ES.dispatchTask(std::move(T));
200 }
201 
202 void AsynchronousSymbolQuery::handleFailed(Error Err) {
203   assert(QueryRegistrations.empty() && ResolvedSymbols.empty() &&
204          OutstandingSymbolsCount == 0 &&
205          "Query should already have been abandoned");
206   NotifyComplete(std::move(Err));
207   NotifyComplete = SymbolsResolvedCallback();
208 }
209 
210 void AsynchronousSymbolQuery::addQueryDependence(JITDylib &JD,
211                                                  SymbolStringPtr Name) {
212   bool Added = QueryRegistrations[&JD].insert(std::move(Name)).second;
213   (void)Added;
214   assert(Added && "Duplicate dependence notification?");
215 }
216 
217 void AsynchronousSymbolQuery::removeQueryDependence(
218     JITDylib &JD, const SymbolStringPtr &Name) {
219   auto QRI = QueryRegistrations.find(&JD);
220   assert(QRI != QueryRegistrations.end() &&
221          "No dependencies registered for JD");
222   assert(QRI->second.count(Name) && "No dependency on Name in JD");
223   QRI->second.erase(Name);
224   if (QRI->second.empty())
225     QueryRegistrations.erase(QRI);
226 }
227 
228 void AsynchronousSymbolQuery::dropSymbol(const SymbolStringPtr &Name) {
229   auto I = ResolvedSymbols.find(Name);
230   assert(I != ResolvedSymbols.end() &&
231          "Redundant removal of weakly-referenced symbol");
232   ResolvedSymbols.erase(I);
233   --OutstandingSymbolsCount;
234 }
235 
236 void AsynchronousSymbolQuery::detach() {
237   ResolvedSymbols.clear();
238   OutstandingSymbolsCount = 0;
239   for (auto &KV : QueryRegistrations)
240     KV.first->detachQueryHelper(*this, KV.second);
241   QueryRegistrations.clear();
242 }
243 
244 AbsoluteSymbolsMaterializationUnit::AbsoluteSymbolsMaterializationUnit(
245     SymbolMap Symbols)
246     : MaterializationUnit(extractFlags(Symbols), nullptr),
247       Symbols(std::move(Symbols)) {}
248 
249 StringRef AbsoluteSymbolsMaterializationUnit::getName() const {
250   return "<Absolute Symbols>";
251 }
252 
253 void AbsoluteSymbolsMaterializationUnit::materialize(
254     std::unique_ptr<MaterializationResponsibility> R) {
255   // No dependencies, so these calls can't fail.
256   cantFail(R->notifyResolved(Symbols));
257   cantFail(R->notifyEmitted());
258 }
259 
260 void AbsoluteSymbolsMaterializationUnit::discard(const JITDylib &JD,
261                                                  const SymbolStringPtr &Name) {
262   assert(Symbols.count(Name) && "Symbol is not part of this MU");
263   Symbols.erase(Name);
264 }
265 
266 SymbolFlagsMap
267 AbsoluteSymbolsMaterializationUnit::extractFlags(const SymbolMap &Symbols) {
268   SymbolFlagsMap Flags;
269   for (const auto &KV : Symbols)
270     Flags[KV.first] = KV.second.getFlags();
271   return Flags;
272 }
273 
274 ReExportsMaterializationUnit::ReExportsMaterializationUnit(
275     JITDylib *SourceJD, JITDylibLookupFlags SourceJDLookupFlags,
276     SymbolAliasMap Aliases)
277     : MaterializationUnit(extractFlags(Aliases), nullptr), SourceJD(SourceJD),
278       SourceJDLookupFlags(SourceJDLookupFlags), Aliases(std::move(Aliases)) {}
279 
280 StringRef ReExportsMaterializationUnit::getName() const {
281   return "<Reexports>";
282 }
283 
284 void ReExportsMaterializationUnit::materialize(
285     std::unique_ptr<MaterializationResponsibility> R) {
286 
287   auto &ES = R->getTargetJITDylib().getExecutionSession();
288   JITDylib &TgtJD = R->getTargetJITDylib();
289   JITDylib &SrcJD = SourceJD ? *SourceJD : TgtJD;
290 
291   // Find the set of requested aliases and aliasees. Return any unrequested
292   // aliases back to the JITDylib so as to not prematurely materialize any
293   // aliasees.
294   auto RequestedSymbols = R->getRequestedSymbols();
295   SymbolAliasMap RequestedAliases;
296 
297   for (auto &Name : RequestedSymbols) {
298     auto I = Aliases.find(Name);
299     assert(I != Aliases.end() && "Symbol not found in aliases map?");
300     RequestedAliases[Name] = std::move(I->second);
301     Aliases.erase(I);
302   }
303 
304   LLVM_DEBUG({
305     ES.runSessionLocked([&]() {
306       dbgs() << "materializing reexports: target = " << TgtJD.getName()
307              << ", source = " << SrcJD.getName() << " " << RequestedAliases
308              << "\n";
309     });
310   });
311 
312   if (!Aliases.empty()) {
313     auto Err = SourceJD ? R->replace(reexports(*SourceJD, std::move(Aliases),
314                                                SourceJDLookupFlags))
315                         : R->replace(symbolAliases(std::move(Aliases)));
316 
317     if (Err) {
318       // FIXME: Should this be reported / treated as failure to materialize?
319       // Or should this be treated as a sanctioned bailing-out?
320       ES.reportError(std::move(Err));
321       R->failMaterialization();
322       return;
323     }
324   }
325 
326   // The OnResolveInfo struct will hold the aliases and responsibilty for each
327   // query in the list.
328   struct OnResolveInfo {
329     OnResolveInfo(std::unique_ptr<MaterializationResponsibility> R,
330                   SymbolAliasMap Aliases)
331         : R(std::move(R)), Aliases(std::move(Aliases)) {}
332 
333     std::unique_ptr<MaterializationResponsibility> R;
334     SymbolAliasMap Aliases;
335   };
336 
337   // Build a list of queries to issue. In each round we build a query for the
338   // largest set of aliases that we can resolve without encountering a chain of
339   // aliases (e.g. Foo -> Bar, Bar -> Baz). Such a chain would deadlock as the
340   // query would be waiting on a symbol that it itself had to resolve. Creating
341   // a new query for each link in such a chain eliminates the possibility of
342   // deadlock. In practice chains are likely to be rare, and this algorithm will
343   // usually result in a single query to issue.
344 
345   std::vector<std::pair<SymbolLookupSet, std::shared_ptr<OnResolveInfo>>>
346       QueryInfos;
347   while (!RequestedAliases.empty()) {
348     SymbolNameSet ResponsibilitySymbols;
349     SymbolLookupSet QuerySymbols;
350     SymbolAliasMap QueryAliases;
351 
352     // Collect as many aliases as we can without including a chain.
353     for (auto &KV : RequestedAliases) {
354       // Chain detected. Skip this symbol for this round.
355       if (&SrcJD == &TgtJD && (QueryAliases.count(KV.second.Aliasee) ||
356                                RequestedAliases.count(KV.second.Aliasee)))
357         continue;
358 
359       ResponsibilitySymbols.insert(KV.first);
360       QuerySymbols.add(KV.second.Aliasee,
361                        KV.second.AliasFlags.hasMaterializationSideEffectsOnly()
362                            ? SymbolLookupFlags::WeaklyReferencedSymbol
363                            : SymbolLookupFlags::RequiredSymbol);
364       QueryAliases[KV.first] = std::move(KV.second);
365     }
366 
367     // Remove the aliases collected this round from the RequestedAliases map.
368     for (auto &KV : QueryAliases)
369       RequestedAliases.erase(KV.first);
370 
371     assert(!QuerySymbols.empty() && "Alias cycle detected!");
372 
373     auto NewR = R->delegate(ResponsibilitySymbols);
374     if (!NewR) {
375       ES.reportError(NewR.takeError());
376       R->failMaterialization();
377       return;
378     }
379 
380     auto QueryInfo = std::make_shared<OnResolveInfo>(std::move(*NewR),
381                                                      std::move(QueryAliases));
382     QueryInfos.push_back(
383         make_pair(std::move(QuerySymbols), std::move(QueryInfo)));
384   }
385 
386   // Issue the queries.
387   while (!QueryInfos.empty()) {
388     auto QuerySymbols = std::move(QueryInfos.back().first);
389     auto QueryInfo = std::move(QueryInfos.back().second);
390 
391     QueryInfos.pop_back();
392 
393     auto RegisterDependencies = [QueryInfo,
394                                  &SrcJD](const SymbolDependenceMap &Deps) {
395       // If there were no materializing symbols, just bail out.
396       if (Deps.empty())
397         return;
398 
399       // Otherwise the only deps should be on SrcJD.
400       assert(Deps.size() == 1 && Deps.count(&SrcJD) &&
401              "Unexpected dependencies for reexports");
402 
403       auto &SrcJDDeps = Deps.find(&SrcJD)->second;
404       SymbolDependenceMap PerAliasDepsMap;
405       auto &PerAliasDeps = PerAliasDepsMap[&SrcJD];
406 
407       for (auto &KV : QueryInfo->Aliases)
408         if (SrcJDDeps.count(KV.second.Aliasee)) {
409           PerAliasDeps = {KV.second.Aliasee};
410           QueryInfo->R->addDependencies(KV.first, PerAliasDepsMap);
411         }
412     };
413 
414     auto OnComplete = [QueryInfo](Expected<SymbolMap> Result) {
415       auto &ES = QueryInfo->R->getTargetJITDylib().getExecutionSession();
416       if (Result) {
417         SymbolMap ResolutionMap;
418         for (auto &KV : QueryInfo->Aliases) {
419           assert((KV.second.AliasFlags.hasMaterializationSideEffectsOnly() ||
420                   Result->count(KV.second.Aliasee)) &&
421                  "Result map missing entry?");
422           // Don't try to resolve materialization-side-effects-only symbols.
423           if (KV.second.AliasFlags.hasMaterializationSideEffectsOnly())
424             continue;
425 
426           ResolutionMap[KV.first] = JITEvaluatedSymbol(
427               (*Result)[KV.second.Aliasee].getAddress(), KV.second.AliasFlags);
428         }
429         if (auto Err = QueryInfo->R->notifyResolved(ResolutionMap)) {
430           ES.reportError(std::move(Err));
431           QueryInfo->R->failMaterialization();
432           return;
433         }
434         if (auto Err = QueryInfo->R->notifyEmitted()) {
435           ES.reportError(std::move(Err));
436           QueryInfo->R->failMaterialization();
437           return;
438         }
439       } else {
440         ES.reportError(Result.takeError());
441         QueryInfo->R->failMaterialization();
442       }
443     };
444 
445     ES.lookup(LookupKind::Static,
446               JITDylibSearchOrder({{&SrcJD, SourceJDLookupFlags}}),
447               QuerySymbols, SymbolState::Resolved, std::move(OnComplete),
448               std::move(RegisterDependencies));
449   }
450 }
451 
452 void ReExportsMaterializationUnit::discard(const JITDylib &JD,
453                                            const SymbolStringPtr &Name) {
454   assert(Aliases.count(Name) &&
455          "Symbol not covered by this MaterializationUnit");
456   Aliases.erase(Name);
457 }
458 
459 SymbolFlagsMap
460 ReExportsMaterializationUnit::extractFlags(const SymbolAliasMap &Aliases) {
461   SymbolFlagsMap SymbolFlags;
462   for (auto &KV : Aliases)
463     SymbolFlags[KV.first] = KV.second.AliasFlags;
464 
465   return SymbolFlags;
466 }
467 
468 Expected<SymbolAliasMap> buildSimpleReexportsAliasMap(JITDylib &SourceJD,
469                                                       SymbolNameSet Symbols) {
470   SymbolLookupSet LookupSet(Symbols);
471   auto Flags = SourceJD.getExecutionSession().lookupFlags(
472       LookupKind::Static, {{&SourceJD, JITDylibLookupFlags::MatchAllSymbols}},
473       SymbolLookupSet(std::move(Symbols)));
474 
475   if (!Flags)
476     return Flags.takeError();
477 
478   SymbolAliasMap Result;
479   for (auto &Name : Symbols) {
480     assert(Flags->count(Name) && "Missing entry in flags map");
481     Result[Name] = SymbolAliasMapEntry(Name, (*Flags)[Name]);
482   }
483 
484   return Result;
485 }
486 
487 class InProgressLookupState {
488 public:
489   InProgressLookupState(LookupKind K, JITDylibSearchOrder SearchOrder,
490                         SymbolLookupSet LookupSet, SymbolState RequiredState)
491       : K(K), SearchOrder(std::move(SearchOrder)),
492         LookupSet(std::move(LookupSet)), RequiredState(RequiredState) {
493     DefGeneratorCandidates = this->LookupSet;
494   }
495   virtual ~InProgressLookupState() {}
496   virtual void complete(std::unique_ptr<InProgressLookupState> IPLS) = 0;
497   virtual void fail(Error Err) = 0;
498 
499   LookupKind K;
500   JITDylibSearchOrder SearchOrder;
501   SymbolLookupSet LookupSet;
502   SymbolState RequiredState;
503 
504   std::unique_lock<std::mutex> GeneratorLock;
505   size_t CurSearchOrderIndex = 0;
506   bool NewJITDylib = true;
507   SymbolLookupSet DefGeneratorCandidates;
508   SymbolLookupSet DefGeneratorNonCandidates;
509   std::vector<std::weak_ptr<DefinitionGenerator>> CurDefGeneratorStack;
510 };
511 
512 class InProgressLookupFlagsState : public InProgressLookupState {
513 public:
514   InProgressLookupFlagsState(
515       LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet,
516       unique_function<void(Expected<SymbolFlagsMap>)> OnComplete)
517       : InProgressLookupState(K, std::move(SearchOrder), std::move(LookupSet),
518                               SymbolState::NeverSearched),
519         OnComplete(std::move(OnComplete)) {}
520 
521   void complete(std::unique_ptr<InProgressLookupState> IPLS) override {
522     GeneratorLock = {}; // Unlock and release.
523     auto &ES = SearchOrder.front().first->getExecutionSession();
524     ES.OL_completeLookupFlags(std::move(IPLS), std::move(OnComplete));
525   }
526 
527   void fail(Error Err) override {
528     GeneratorLock = {}; // Unlock and release.
529     OnComplete(std::move(Err));
530   }
531 
532 private:
533   unique_function<void(Expected<SymbolFlagsMap>)> OnComplete;
534 };
535 
536 class InProgressFullLookupState : public InProgressLookupState {
537 public:
538   InProgressFullLookupState(LookupKind K, JITDylibSearchOrder SearchOrder,
539                             SymbolLookupSet LookupSet,
540                             SymbolState RequiredState,
541                             std::shared_ptr<AsynchronousSymbolQuery> Q,
542                             RegisterDependenciesFunction RegisterDependencies)
543       : InProgressLookupState(K, std::move(SearchOrder), std::move(LookupSet),
544                               RequiredState),
545         Q(std::move(Q)), RegisterDependencies(std::move(RegisterDependencies)) {
546   }
547 
548   void complete(std::unique_ptr<InProgressLookupState> IPLS) override {
549     GeneratorLock = {}; // Unlock and release.
550     auto &ES = SearchOrder.front().first->getExecutionSession();
551     ES.OL_completeLookup(std::move(IPLS), std::move(Q),
552                          std::move(RegisterDependencies));
553   }
554 
555   void fail(Error Err) override {
556     GeneratorLock = {};
557     Q->detach();
558     Q->handleFailed(std::move(Err));
559   }
560 
561 private:
562   std::shared_ptr<AsynchronousSymbolQuery> Q;
563   RegisterDependenciesFunction RegisterDependencies;
564 };
565 
566 ReexportsGenerator::ReexportsGenerator(JITDylib &SourceJD,
567                                        JITDylibLookupFlags SourceJDLookupFlags,
568                                        SymbolPredicate Allow)
569     : SourceJD(SourceJD), SourceJDLookupFlags(SourceJDLookupFlags),
570       Allow(std::move(Allow)) {}
571 
572 Error ReexportsGenerator::tryToGenerate(LookupState &LS, LookupKind K,
573                                         JITDylib &JD,
574                                         JITDylibLookupFlags JDLookupFlags,
575                                         const SymbolLookupSet &LookupSet) {
576   assert(&JD != &SourceJD && "Cannot re-export from the same dylib");
577 
578   // Use lookupFlags to find the subset of symbols that match our lookup.
579   auto Flags = JD.getExecutionSession().lookupFlags(
580       K, {{&SourceJD, JDLookupFlags}}, LookupSet);
581   if (!Flags)
582     return Flags.takeError();
583 
584   // Create an alias map.
585   orc::SymbolAliasMap AliasMap;
586   for (auto &KV : *Flags)
587     if (!Allow || Allow(KV.first))
588       AliasMap[KV.first] = SymbolAliasMapEntry(KV.first, KV.second);
589 
590   if (AliasMap.empty())
591     return Error::success();
592 
593   // Define the re-exports.
594   return JD.define(reexports(SourceJD, AliasMap, SourceJDLookupFlags));
595 }
596 
597 LookupState::LookupState(std::unique_ptr<InProgressLookupState> IPLS)
598     : IPLS(std::move(IPLS)) {}
599 
600 void LookupState::reset(InProgressLookupState *IPLS) { this->IPLS.reset(IPLS); }
601 
602 LookupState::LookupState() = default;
603 LookupState::LookupState(LookupState &&) = default;
604 LookupState &LookupState::operator=(LookupState &&) = default;
605 LookupState::~LookupState() = default;
606 
607 void LookupState::continueLookup(Error Err) {
608   assert(IPLS && "Cannot call continueLookup on empty LookupState");
609   auto &ES = IPLS->SearchOrder.begin()->first->getExecutionSession();
610   ES.OL_applyQueryPhase1(std::move(IPLS), std::move(Err));
611 }
612 
613 DefinitionGenerator::~DefinitionGenerator() {}
614 
615 JITDylib::~JITDylib() {
616   LLVM_DEBUG(dbgs() << "Destroying JITDylib " << getName() << "\n");
617 }
618 
619 Error JITDylib::clear() {
620   std::vector<ResourceTrackerSP> TrackersToRemove;
621   ES.runSessionLocked([&]() {
622     assert(State != Closed && "JD is defunct");
623     for (auto &KV : TrackerSymbols)
624       TrackersToRemove.push_back(KV.first);
625     TrackersToRemove.push_back(getDefaultResourceTracker());
626   });
627 
628   Error Err = Error::success();
629   for (auto &RT : TrackersToRemove)
630     Err = joinErrors(std::move(Err), RT->remove());
631   return Err;
632 }
633 
634 ResourceTrackerSP JITDylib::getDefaultResourceTracker() {
635   return ES.runSessionLocked([this] {
636     assert(State != Closed && "JD is defunct");
637     if (!DefaultTracker)
638       DefaultTracker = new ResourceTracker(this);
639     return DefaultTracker;
640   });
641 }
642 
643 ResourceTrackerSP JITDylib::createResourceTracker() {
644   return ES.runSessionLocked([this] {
645     assert(State == Open && "JD is defunct");
646     ResourceTrackerSP RT = new ResourceTracker(this);
647     return RT;
648   });
649 }
650 
651 void JITDylib::removeGenerator(DefinitionGenerator &G) {
652   ES.runSessionLocked([&] {
653     assert(State == Open && "JD is defunct");
654     auto I = llvm::find_if(DefGenerators,
655                            [&](const std::shared_ptr<DefinitionGenerator> &H) {
656                              return H.get() == &G;
657                            });
658     assert(I != DefGenerators.end() && "Generator not found");
659     DefGenerators.erase(I);
660   });
661 }
662 
663 Expected<SymbolFlagsMap>
664 JITDylib::defineMaterializing(SymbolFlagsMap SymbolFlags) {
665 
666   return ES.runSessionLocked([&]() -> Expected<SymbolFlagsMap> {
667     std::vector<SymbolTable::iterator> AddedSyms;
668     std::vector<SymbolFlagsMap::iterator> RejectedWeakDefs;
669 
670     for (auto SFItr = SymbolFlags.begin(), SFEnd = SymbolFlags.end();
671          SFItr != SFEnd; ++SFItr) {
672 
673       auto &Name = SFItr->first;
674       auto &Flags = SFItr->second;
675 
676       auto EntryItr = Symbols.find(Name);
677 
678       // If the entry already exists...
679       if (EntryItr != Symbols.end()) {
680 
681         // If this is a strong definition then error out.
682         if (!Flags.isWeak()) {
683           // Remove any symbols already added.
684           for (auto &SI : AddedSyms)
685             Symbols.erase(SI);
686 
687           // FIXME: Return all duplicates.
688           return make_error<DuplicateDefinition>(std::string(*Name));
689         }
690 
691         // Otherwise just make a note to discard this symbol after the loop.
692         RejectedWeakDefs.push_back(SFItr);
693         continue;
694       } else
695         EntryItr =
696           Symbols.insert(std::make_pair(Name, SymbolTableEntry(Flags))).first;
697 
698       AddedSyms.push_back(EntryItr);
699       EntryItr->second.setState(SymbolState::Materializing);
700     }
701 
702     // Remove any rejected weak definitions from the SymbolFlags map.
703     while (!RejectedWeakDefs.empty()) {
704       SymbolFlags.erase(RejectedWeakDefs.back());
705       RejectedWeakDefs.pop_back();
706     }
707 
708     return SymbolFlags;
709   });
710 }
711 
712 Error JITDylib::replace(MaterializationResponsibility &FromMR,
713                         std::unique_ptr<MaterializationUnit> MU) {
714   assert(MU != nullptr && "Can not replace with a null MaterializationUnit");
715   std::unique_ptr<MaterializationUnit> MustRunMU;
716   std::unique_ptr<MaterializationResponsibility> MustRunMR;
717 
718   auto Err =
719       ES.runSessionLocked([&, this]() -> Error {
720         if (FromMR.RT->isDefunct())
721           return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
722 
723 #ifndef NDEBUG
724         for (auto &KV : MU->getSymbols()) {
725           auto SymI = Symbols.find(KV.first);
726           assert(SymI != Symbols.end() && "Replacing unknown symbol");
727           assert(SymI->second.getState() == SymbolState::Materializing &&
728                  "Can not replace a symbol that ha is not materializing");
729           assert(!SymI->second.hasMaterializerAttached() &&
730                  "Symbol should not have materializer attached already");
731           assert(UnmaterializedInfos.count(KV.first) == 0 &&
732                  "Symbol being replaced should have no UnmaterializedInfo");
733         }
734 #endif // NDEBUG
735 
736         // If the tracker is defunct we need to bail out immediately.
737 
738         // If any symbol has pending queries against it then we need to
739         // materialize MU immediately.
740         for (auto &KV : MU->getSymbols()) {
741           auto MII = MaterializingInfos.find(KV.first);
742           if (MII != MaterializingInfos.end()) {
743             if (MII->second.hasQueriesPending()) {
744               MustRunMR = ES.createMaterializationResponsibility(
745                   *FromMR.RT, std::move(MU->SymbolFlags),
746                   std::move(MU->InitSymbol));
747               MustRunMU = std::move(MU);
748               return Error::success();
749             }
750           }
751         }
752 
753         // Otherwise, make MU responsible for all the symbols.
754         auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU),
755                                                         FromMR.RT.get());
756         for (auto &KV : UMI->MU->getSymbols()) {
757           auto SymI = Symbols.find(KV.first);
758           assert(SymI->second.getState() == SymbolState::Materializing &&
759                  "Can not replace a symbol that is not materializing");
760           assert(!SymI->second.hasMaterializerAttached() &&
761                  "Can not replace a symbol that has a materializer attached");
762           assert(UnmaterializedInfos.count(KV.first) == 0 &&
763                  "Unexpected materializer entry in map");
764           SymI->second.setAddress(SymI->second.getAddress());
765           SymI->second.setMaterializerAttached(true);
766 
767           auto &UMIEntry = UnmaterializedInfos[KV.first];
768           assert((!UMIEntry || !UMIEntry->MU) &&
769                  "Replacing symbol with materializer still attached");
770           UMIEntry = UMI;
771         }
772 
773         return Error::success();
774       });
775 
776   if (Err)
777     return Err;
778 
779   if (MustRunMU) {
780     assert(MustRunMR && "MustRunMU set implies MustRunMR set");
781     ES.dispatchTask(std::make_unique<MaterializationTask>(
782         std::move(MustRunMU), std::move(MustRunMR)));
783   } else {
784     assert(!MustRunMR && "MustRunMU unset implies MustRunMR unset");
785   }
786 
787   return Error::success();
788 }
789 
790 Expected<std::unique_ptr<MaterializationResponsibility>>
791 JITDylib::delegate(MaterializationResponsibility &FromMR,
792                    SymbolFlagsMap SymbolFlags, SymbolStringPtr InitSymbol) {
793 
794   return ES.runSessionLocked(
795       [&]() -> Expected<std::unique_ptr<MaterializationResponsibility>> {
796         if (FromMR.RT->isDefunct())
797           return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
798 
799         return ES.createMaterializationResponsibility(
800             *FromMR.RT, std::move(SymbolFlags), std::move(InitSymbol));
801       });
802 }
803 
804 SymbolNameSet
805 JITDylib::getRequestedSymbols(const SymbolFlagsMap &SymbolFlags) const {
806   return ES.runSessionLocked([&]() {
807     SymbolNameSet RequestedSymbols;
808 
809     for (auto &KV : SymbolFlags) {
810       assert(Symbols.count(KV.first) && "JITDylib does not cover this symbol?");
811       assert(Symbols.find(KV.first)->second.getState() !=
812                  SymbolState::NeverSearched &&
813              Symbols.find(KV.first)->second.getState() != SymbolState::Ready &&
814              "getRequestedSymbols can only be called for symbols that have "
815              "started materializing");
816       auto I = MaterializingInfos.find(KV.first);
817       if (I == MaterializingInfos.end())
818         continue;
819 
820       if (I->second.hasQueriesPending())
821         RequestedSymbols.insert(KV.first);
822     }
823 
824     return RequestedSymbols;
825   });
826 }
827 
828 void JITDylib::addDependencies(const SymbolStringPtr &Name,
829                                const SymbolDependenceMap &Dependencies) {
830   ES.runSessionLocked([&]() {
831     assert(Symbols.count(Name) && "Name not in symbol table");
832     assert(Symbols[Name].getState() < SymbolState::Emitted &&
833            "Can not add dependencies for a symbol that is not materializing");
834 
835     LLVM_DEBUG({
836       dbgs() << "In " << getName() << " adding dependencies for " << *Name
837              << ": " << Dependencies << "\n";
838     });
839 
840     // If Name is already in an error state then just bail out.
841     if (Symbols[Name].getFlags().hasError())
842       return;
843 
844     auto &MI = MaterializingInfos[Name];
845     assert(Symbols[Name].getState() != SymbolState::Emitted &&
846            "Can not add dependencies to an emitted symbol");
847 
848     bool DependsOnSymbolInErrorState = false;
849 
850     // Register dependencies, record whether any depenendency is in the error
851     // state.
852     for (auto &KV : Dependencies) {
853       assert(KV.first && "Null JITDylib in dependency?");
854       auto &OtherJITDylib = *KV.first;
855       auto &DepsOnOtherJITDylib = MI.UnemittedDependencies[&OtherJITDylib];
856 
857       for (auto &OtherSymbol : KV.second) {
858 
859         // Check the sym entry for the dependency.
860         auto OtherSymI = OtherJITDylib.Symbols.find(OtherSymbol);
861 
862         // Assert that this symbol exists and has not reached the ready state
863         // already.
864         assert(OtherSymI != OtherJITDylib.Symbols.end() &&
865                "Dependency on unknown symbol");
866 
867         auto &OtherSymEntry = OtherSymI->second;
868 
869         // If the other symbol is already in the Ready state then there's no
870         // dependency to add.
871         if (OtherSymEntry.getState() == SymbolState::Ready)
872           continue;
873 
874         // If the dependency is in an error state then note this and continue,
875         // we will move this symbol to the error state below.
876         if (OtherSymEntry.getFlags().hasError()) {
877           DependsOnSymbolInErrorState = true;
878           continue;
879         }
880 
881         // If the dependency was not in the error state then add it to
882         // our list of dependencies.
883         auto &OtherMI = OtherJITDylib.MaterializingInfos[OtherSymbol];
884 
885         if (OtherSymEntry.getState() == SymbolState::Emitted)
886           transferEmittedNodeDependencies(MI, Name, OtherMI);
887         else if (&OtherJITDylib != this || OtherSymbol != Name) {
888           OtherMI.Dependants[this].insert(Name);
889           DepsOnOtherJITDylib.insert(OtherSymbol);
890         }
891       }
892 
893       if (DepsOnOtherJITDylib.empty())
894         MI.UnemittedDependencies.erase(&OtherJITDylib);
895     }
896 
897     // If this symbol dependended on any symbols in the error state then move
898     // this symbol to the error state too.
899     if (DependsOnSymbolInErrorState)
900       Symbols[Name].setFlags(Symbols[Name].getFlags() |
901                              JITSymbolFlags::HasError);
902   });
903 }
904 
905 Error JITDylib::resolve(MaterializationResponsibility &MR,
906                         const SymbolMap &Resolved) {
907   AsynchronousSymbolQuerySet CompletedQueries;
908 
909   if (auto Err = ES.runSessionLocked([&, this]() -> Error {
910         if (MR.RT->isDefunct())
911           return make_error<ResourceTrackerDefunct>(MR.RT);
912 
913         if (State != Open)
914           return make_error<StringError>("JITDylib " + getName() +
915                                              " is defunct",
916                                          inconvertibleErrorCode());
917 
918         struct WorklistEntry {
919           SymbolTable::iterator SymI;
920           JITEvaluatedSymbol ResolvedSym;
921         };
922 
923         SymbolNameSet SymbolsInErrorState;
924         std::vector<WorklistEntry> Worklist;
925         Worklist.reserve(Resolved.size());
926 
927         // Build worklist and check for any symbols in the error state.
928         for (const auto &KV : Resolved) {
929 
930           assert(!KV.second.getFlags().hasError() &&
931                  "Resolution result can not have error flag set");
932 
933           auto SymI = Symbols.find(KV.first);
934 
935           assert(SymI != Symbols.end() && "Symbol not found");
936           assert(!SymI->second.hasMaterializerAttached() &&
937                  "Resolving symbol with materializer attached?");
938           assert(SymI->second.getState() == SymbolState::Materializing &&
939                  "Symbol should be materializing");
940           assert(SymI->second.getAddress() == 0 &&
941                  "Symbol has already been resolved");
942 
943           if (SymI->second.getFlags().hasError())
944             SymbolsInErrorState.insert(KV.first);
945           else {
946             auto Flags = KV.second.getFlags();
947             Flags &= ~(JITSymbolFlags::Weak | JITSymbolFlags::Common);
948             assert(Flags ==
949                        (SymI->second.getFlags() &
950                         ~(JITSymbolFlags::Weak | JITSymbolFlags::Common)) &&
951                    "Resolved flags should match the declared flags");
952 
953             Worklist.push_back(
954                 {SymI, JITEvaluatedSymbol(KV.second.getAddress(), Flags)});
955           }
956         }
957 
958         // If any symbols were in the error state then bail out.
959         if (!SymbolsInErrorState.empty()) {
960           auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
961           (*FailedSymbolsDepMap)[this] = std::move(SymbolsInErrorState);
962           return make_error<FailedToMaterialize>(
963               std::move(FailedSymbolsDepMap));
964         }
965 
966         while (!Worklist.empty()) {
967           auto SymI = Worklist.back().SymI;
968           auto ResolvedSym = Worklist.back().ResolvedSym;
969           Worklist.pop_back();
970 
971           auto &Name = SymI->first;
972 
973           // Resolved symbols can not be weak: discard the weak flag.
974           JITSymbolFlags ResolvedFlags = ResolvedSym.getFlags();
975           SymI->second.setAddress(ResolvedSym.getAddress());
976           SymI->second.setFlags(ResolvedFlags);
977           SymI->second.setState(SymbolState::Resolved);
978 
979           auto MII = MaterializingInfos.find(Name);
980           if (MII == MaterializingInfos.end())
981             continue;
982 
983           auto &MI = MII->second;
984           for (auto &Q : MI.takeQueriesMeeting(SymbolState::Resolved)) {
985             Q->notifySymbolMetRequiredState(Name, ResolvedSym);
986             Q->removeQueryDependence(*this, Name);
987             if (Q->isComplete())
988               CompletedQueries.insert(std::move(Q));
989           }
990         }
991 
992         return Error::success();
993       }))
994     return Err;
995 
996   // Otherwise notify all the completed queries.
997   for (auto &Q : CompletedQueries) {
998     assert(Q->isComplete() && "Q not completed");
999     Q->handleComplete(ES);
1000   }
1001 
1002   return Error::success();
1003 }
1004 
1005 Error JITDylib::emit(MaterializationResponsibility &MR,
1006                      const SymbolFlagsMap &Emitted) {
1007   AsynchronousSymbolQuerySet CompletedQueries;
1008   DenseMap<JITDylib *, SymbolNameVector> ReadySymbols;
1009 
1010   if (auto Err = ES.runSessionLocked([&, this]() -> Error {
1011         if (MR.RT->isDefunct())
1012           return make_error<ResourceTrackerDefunct>(MR.RT);
1013 
1014         if (State != Open)
1015           return make_error<StringError>("JITDylib " + getName() +
1016                                              " is defunct",
1017                                          inconvertibleErrorCode());
1018 
1019         SymbolNameSet SymbolsInErrorState;
1020         std::vector<SymbolTable::iterator> Worklist;
1021 
1022         // Scan to build worklist, record any symbols in the erorr state.
1023         for (const auto &KV : Emitted) {
1024           auto &Name = KV.first;
1025 
1026           auto SymI = Symbols.find(Name);
1027           assert(SymI != Symbols.end() && "No symbol table entry for Name");
1028 
1029           if (SymI->second.getFlags().hasError())
1030             SymbolsInErrorState.insert(Name);
1031           else
1032             Worklist.push_back(SymI);
1033         }
1034 
1035         // If any symbols were in the error state then bail out.
1036         if (!SymbolsInErrorState.empty()) {
1037           auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
1038           (*FailedSymbolsDepMap)[this] = std::move(SymbolsInErrorState);
1039           return make_error<FailedToMaterialize>(
1040               std::move(FailedSymbolsDepMap));
1041         }
1042 
1043         // Otherwise update dependencies and move to the emitted state.
1044         while (!Worklist.empty()) {
1045           auto SymI = Worklist.back();
1046           Worklist.pop_back();
1047 
1048           auto &Name = SymI->first;
1049           auto &SymEntry = SymI->second;
1050 
1051           // Move symbol to the emitted state.
1052           assert(((SymEntry.getFlags().hasMaterializationSideEffectsOnly() &&
1053                    SymEntry.getState() == SymbolState::Materializing) ||
1054                   SymEntry.getState() == SymbolState::Resolved) &&
1055                  "Emitting from state other than Resolved");
1056           SymEntry.setState(SymbolState::Emitted);
1057 
1058           auto MII = MaterializingInfos.find(Name);
1059 
1060           // If this symbol has no MaterializingInfo then it's trivially ready.
1061           // Update its state and continue.
1062           if (MII == MaterializingInfos.end()) {
1063             SymEntry.setState(SymbolState::Ready);
1064             continue;
1065           }
1066 
1067           auto &MI = MII->second;
1068 
1069           // For each dependant, transfer this node's emitted dependencies to
1070           // it. If the dependant node is ready (i.e. has no unemitted
1071           // dependencies) then notify any pending queries.
1072           for (auto &KV : MI.Dependants) {
1073             auto &DependantJD = *KV.first;
1074             auto &DependantJDReadySymbols = ReadySymbols[&DependantJD];
1075             for (auto &DependantName : KV.second) {
1076               auto DependantMII =
1077                   DependantJD.MaterializingInfos.find(DependantName);
1078               assert(DependantMII != DependantJD.MaterializingInfos.end() &&
1079                      "Dependant should have MaterializingInfo");
1080 
1081               auto &DependantMI = DependantMII->second;
1082 
1083               // Remove the dependant's dependency on this node.
1084               assert(DependantMI.UnemittedDependencies.count(this) &&
1085                      "Dependant does not have an unemitted dependencies record "
1086                      "for "
1087                      "this JITDylib");
1088               assert(DependantMI.UnemittedDependencies[this].count(Name) &&
1089                      "Dependant does not count this symbol as a dependency?");
1090 
1091               DependantMI.UnemittedDependencies[this].erase(Name);
1092               if (DependantMI.UnemittedDependencies[this].empty())
1093                 DependantMI.UnemittedDependencies.erase(this);
1094 
1095               // Transfer unemitted dependencies from this node to the
1096               // dependant.
1097               DependantJD.transferEmittedNodeDependencies(DependantMI,
1098                                                           DependantName, MI);
1099 
1100               auto DependantSymI = DependantJD.Symbols.find(DependantName);
1101               assert(DependantSymI != DependantJD.Symbols.end() &&
1102                      "Dependant has no entry in the Symbols table");
1103               auto &DependantSymEntry = DependantSymI->second;
1104 
1105               // If the dependant is emitted and this node was the last of its
1106               // unemitted dependencies then the dependant node is now ready, so
1107               // notify any pending queries on the dependant node.
1108               if (DependantSymEntry.getState() == SymbolState::Emitted &&
1109                   DependantMI.UnemittedDependencies.empty()) {
1110                 assert(DependantMI.Dependants.empty() &&
1111                        "Dependants should be empty by now");
1112 
1113                 // Since this dependant is now ready, we erase its
1114                 // MaterializingInfo and update its materializing state.
1115                 DependantSymEntry.setState(SymbolState::Ready);
1116                 DependantJDReadySymbols.push_back(DependantName);
1117 
1118                 for (auto &Q :
1119                      DependantMI.takeQueriesMeeting(SymbolState::Ready)) {
1120                   Q->notifySymbolMetRequiredState(
1121                       DependantName, DependantSymI->second.getSymbol());
1122                   if (Q->isComplete())
1123                     CompletedQueries.insert(Q);
1124                   Q->removeQueryDependence(DependantJD, DependantName);
1125                 }
1126                 DependantJD.MaterializingInfos.erase(DependantMII);
1127               }
1128             }
1129           }
1130 
1131           auto &ThisJDReadySymbols = ReadySymbols[this];
1132           MI.Dependants.clear();
1133           if (MI.UnemittedDependencies.empty()) {
1134             SymI->second.setState(SymbolState::Ready);
1135             ThisJDReadySymbols.push_back(Name);
1136             for (auto &Q : MI.takeQueriesMeeting(SymbolState::Ready)) {
1137               Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
1138               if (Q->isComplete())
1139                 CompletedQueries.insert(Q);
1140               Q->removeQueryDependence(*this, Name);
1141             }
1142             MaterializingInfos.erase(MII);
1143           }
1144         }
1145 
1146         return Error::success();
1147       }))
1148     return Err;
1149 
1150   // Otherwise notify all the completed queries.
1151   for (auto &Q : CompletedQueries) {
1152     assert(Q->isComplete() && "Q is not complete");
1153     Q->handleComplete(ES);
1154   }
1155 
1156   return Error::success();
1157 }
1158 
1159 void JITDylib::unlinkMaterializationResponsibility(
1160     MaterializationResponsibility &MR) {
1161   ES.runSessionLocked([&]() {
1162     auto I = TrackerMRs.find(MR.RT.get());
1163     assert(I != TrackerMRs.end() && "No MRs in TrackerMRs list for RT");
1164     assert(I->second.count(&MR) && "MR not in TrackerMRs list for RT");
1165     I->second.erase(&MR);
1166     if (I->second.empty())
1167       TrackerMRs.erase(MR.RT.get());
1168   });
1169 }
1170 
1171 std::pair<JITDylib::AsynchronousSymbolQuerySet,
1172           std::shared_ptr<SymbolDependenceMap>>
1173 JITDylib::failSymbols(FailedSymbolsWorklist Worklist) {
1174   AsynchronousSymbolQuerySet FailedQueries;
1175   auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
1176 
1177   while (!Worklist.empty()) {
1178     assert(Worklist.back().first && "Failed JITDylib can not be null");
1179     auto &JD = *Worklist.back().first;
1180     auto Name = std::move(Worklist.back().second);
1181     Worklist.pop_back();
1182 
1183     (*FailedSymbolsMap)[&JD].insert(Name);
1184 
1185     // Look up the symbol to fail.
1186     auto SymI = JD.Symbols.find(Name);
1187 
1188     // It's possible that this symbol has already been removed, e.g. if a
1189     // materialization failure happens concurrently with a ResourceTracker or
1190     // JITDylib removal. In that case we can safely skip this symbol and
1191     // continue.
1192     if (SymI == JD.Symbols.end())
1193       continue;
1194     auto &Sym = SymI->second;
1195 
1196     // Move the symbol into the error state.
1197     // Note that this may be redundant: The symbol might already have been
1198     // moved to this state in response to the failure of a dependence.
1199     Sym.setFlags(Sym.getFlags() | JITSymbolFlags::HasError);
1200 
1201     // FIXME: Come up with a sane mapping of state to
1202     // presence-of-MaterializingInfo so that we can assert presence / absence
1203     // here, rather than testing it.
1204     auto MII = JD.MaterializingInfos.find(Name);
1205 
1206     if (MII == JD.MaterializingInfos.end())
1207       continue;
1208 
1209     auto &MI = MII->second;
1210 
1211     // Move all dependants to the error state and disconnect from them.
1212     for (auto &KV : MI.Dependants) {
1213       auto &DependantJD = *KV.first;
1214       for (auto &DependantName : KV.second) {
1215         assert(DependantJD.Symbols.count(DependantName) &&
1216                "No symbol table entry for DependantName");
1217         auto &DependantSym = DependantJD.Symbols[DependantName];
1218         DependantSym.setFlags(DependantSym.getFlags() |
1219                               JITSymbolFlags::HasError);
1220 
1221         assert(DependantJD.MaterializingInfos.count(DependantName) &&
1222                "No MaterializingInfo for dependant");
1223         auto &DependantMI = DependantJD.MaterializingInfos[DependantName];
1224 
1225         auto UnemittedDepI = DependantMI.UnemittedDependencies.find(&JD);
1226         assert(UnemittedDepI != DependantMI.UnemittedDependencies.end() &&
1227                "No UnemittedDependencies entry for this JITDylib");
1228         assert(UnemittedDepI->second.count(Name) &&
1229                "No UnemittedDependencies entry for this symbol");
1230         UnemittedDepI->second.erase(Name);
1231         if (UnemittedDepI->second.empty())
1232           DependantMI.UnemittedDependencies.erase(UnemittedDepI);
1233 
1234         // If this symbol is already in the emitted state then we need to
1235         // take responsibility for failing its queries, so add it to the
1236         // worklist.
1237         if (DependantSym.getState() == SymbolState::Emitted) {
1238           assert(DependantMI.Dependants.empty() &&
1239                  "Emitted symbol should not have dependants");
1240           Worklist.push_back(std::make_pair(&DependantJD, DependantName));
1241         }
1242       }
1243     }
1244     MI.Dependants.clear();
1245 
1246     // Disconnect from all unemitted depenencies.
1247     for (auto &KV : MI.UnemittedDependencies) {
1248       auto &UnemittedDepJD = *KV.first;
1249       for (auto &UnemittedDepName : KV.second) {
1250         auto UnemittedDepMII =
1251             UnemittedDepJD.MaterializingInfos.find(UnemittedDepName);
1252         assert(UnemittedDepMII != UnemittedDepJD.MaterializingInfos.end() &&
1253                "Missing MII for unemitted dependency");
1254         assert(UnemittedDepMII->second.Dependants.count(&JD) &&
1255                "JD not listed as a dependant of unemitted dependency");
1256         assert(UnemittedDepMII->second.Dependants[&JD].count(Name) &&
1257                "Name is not listed as a dependant of unemitted dependency");
1258         UnemittedDepMII->second.Dependants[&JD].erase(Name);
1259         if (UnemittedDepMII->second.Dependants[&JD].empty())
1260           UnemittedDepMII->second.Dependants.erase(&JD);
1261       }
1262     }
1263     MI.UnemittedDependencies.clear();
1264 
1265     // Collect queries to be failed for this MII.
1266     AsynchronousSymbolQueryList ToDetach;
1267     for (auto &Q : MII->second.pendingQueries()) {
1268       // Add the query to the list to be failed and detach it.
1269       FailedQueries.insert(Q);
1270       ToDetach.push_back(Q);
1271     }
1272     for (auto &Q : ToDetach)
1273       Q->detach();
1274 
1275     assert(MI.Dependants.empty() &&
1276            "Can not delete MaterializingInfo with dependants still attached");
1277     assert(MI.UnemittedDependencies.empty() &&
1278            "Can not delete MaterializingInfo with unemitted dependencies "
1279            "still attached");
1280     assert(!MI.hasQueriesPending() &&
1281            "Can not delete MaterializingInfo with queries pending");
1282     JD.MaterializingInfos.erase(MII);
1283   }
1284 
1285   return std::make_pair(std::move(FailedQueries), std::move(FailedSymbolsMap));
1286 }
1287 
1288 void JITDylib::setLinkOrder(JITDylibSearchOrder NewLinkOrder,
1289                             bool LinkAgainstThisJITDylibFirst) {
1290   ES.runSessionLocked([&]() {
1291     assert(State == Open && "JD is defunct");
1292     if (LinkAgainstThisJITDylibFirst) {
1293       LinkOrder.clear();
1294       if (NewLinkOrder.empty() || NewLinkOrder.front().first != this)
1295         LinkOrder.push_back(
1296             std::make_pair(this, JITDylibLookupFlags::MatchAllSymbols));
1297       llvm::append_range(LinkOrder, NewLinkOrder);
1298     } else
1299       LinkOrder = std::move(NewLinkOrder);
1300   });
1301 }
1302 
1303 void JITDylib::addToLinkOrder(JITDylib &JD, JITDylibLookupFlags JDLookupFlags) {
1304   ES.runSessionLocked([&]() { LinkOrder.push_back({&JD, JDLookupFlags}); });
1305 }
1306 
1307 void JITDylib::replaceInLinkOrder(JITDylib &OldJD, JITDylib &NewJD,
1308                                   JITDylibLookupFlags JDLookupFlags) {
1309   ES.runSessionLocked([&]() {
1310     assert(State == Open && "JD is defunct");
1311     for (auto &KV : LinkOrder)
1312       if (KV.first == &OldJD) {
1313         KV = {&NewJD, JDLookupFlags};
1314         break;
1315       }
1316   });
1317 }
1318 
1319 void JITDylib::removeFromLinkOrder(JITDylib &JD) {
1320   ES.runSessionLocked([&]() {
1321     assert(State == Open && "JD is defunct");
1322     auto I = llvm::find_if(LinkOrder,
1323                            [&](const JITDylibSearchOrder::value_type &KV) {
1324                              return KV.first == &JD;
1325                            });
1326     if (I != LinkOrder.end())
1327       LinkOrder.erase(I);
1328   });
1329 }
1330 
1331 Error JITDylib::remove(const SymbolNameSet &Names) {
1332   return ES.runSessionLocked([&]() -> Error {
1333     assert(State == Open && "JD is defunct");
1334     using SymbolMaterializerItrPair =
1335         std::pair<SymbolTable::iterator, UnmaterializedInfosMap::iterator>;
1336     std::vector<SymbolMaterializerItrPair> SymbolsToRemove;
1337     SymbolNameSet Missing;
1338     SymbolNameSet Materializing;
1339 
1340     for (auto &Name : Names) {
1341       auto I = Symbols.find(Name);
1342 
1343       // Note symbol missing.
1344       if (I == Symbols.end()) {
1345         Missing.insert(Name);
1346         continue;
1347       }
1348 
1349       // Note symbol materializing.
1350       if (I->second.getState() != SymbolState::NeverSearched &&
1351           I->second.getState() != SymbolState::Ready) {
1352         Materializing.insert(Name);
1353         continue;
1354       }
1355 
1356       auto UMII = I->second.hasMaterializerAttached()
1357                       ? UnmaterializedInfos.find(Name)
1358                       : UnmaterializedInfos.end();
1359       SymbolsToRemove.push_back(std::make_pair(I, UMII));
1360     }
1361 
1362     // If any of the symbols are not defined, return an error.
1363     if (!Missing.empty())
1364       return make_error<SymbolsNotFound>(ES.getSymbolStringPool(),
1365                                          std::move(Missing));
1366 
1367     // If any of the symbols are currently materializing, return an error.
1368     if (!Materializing.empty())
1369       return make_error<SymbolsCouldNotBeRemoved>(ES.getSymbolStringPool(),
1370                                                   std::move(Materializing));
1371 
1372     // Remove the symbols.
1373     for (auto &SymbolMaterializerItrPair : SymbolsToRemove) {
1374       auto UMII = SymbolMaterializerItrPair.second;
1375 
1376       // If there is a materializer attached, call discard.
1377       if (UMII != UnmaterializedInfos.end()) {
1378         UMII->second->MU->doDiscard(*this, UMII->first);
1379         UnmaterializedInfos.erase(UMII);
1380       }
1381 
1382       auto SymI = SymbolMaterializerItrPair.first;
1383       Symbols.erase(SymI);
1384     }
1385 
1386     return Error::success();
1387   });
1388 }
1389 
1390 void JITDylib::dump(raw_ostream &OS) {
1391   ES.runSessionLocked([&, this]() {
1392     OS << "JITDylib \"" << getName() << "\" (ES: "
1393        << format("0x%016" PRIx64, reinterpret_cast<uintptr_t>(&ES))
1394        << ", State = ";
1395     switch (State) {
1396     case Open:
1397       OS << "Open";
1398       break;
1399     case Closing:
1400       OS << "Closing";
1401       break;
1402     case Closed:
1403       OS << "Closed";
1404       break;
1405     }
1406     OS << ")\n";
1407     if (State == Closed)
1408       return;
1409     OS << "Link order: " << LinkOrder << "\n"
1410        << "Symbol table:\n";
1411 
1412     for (auto &KV : Symbols) {
1413       OS << "    \"" << *KV.first << "\": ";
1414       if (auto Addr = KV.second.getAddress())
1415         OS << format("0x%016" PRIx64, Addr) << ", " << KV.second.getFlags()
1416            << " ";
1417       else
1418         OS << "<not resolved> ";
1419 
1420       OS << KV.second.getFlags() << " " << KV.second.getState();
1421 
1422       if (KV.second.hasMaterializerAttached()) {
1423         OS << " (Materializer ";
1424         auto I = UnmaterializedInfos.find(KV.first);
1425         assert(I != UnmaterializedInfos.end() &&
1426                "Lazy symbol should have UnmaterializedInfo");
1427         OS << I->second->MU.get() << ", " << I->second->MU->getName() << ")\n";
1428       } else
1429         OS << "\n";
1430     }
1431 
1432     if (!MaterializingInfos.empty())
1433       OS << "  MaterializingInfos entries:\n";
1434     for (auto &KV : MaterializingInfos) {
1435       OS << "    \"" << *KV.first << "\":\n"
1436          << "      " << KV.second.pendingQueries().size()
1437          << " pending queries: { ";
1438       for (const auto &Q : KV.second.pendingQueries())
1439         OS << Q.get() << " (" << Q->getRequiredState() << ") ";
1440       OS << "}\n      Dependants:\n";
1441       for (auto &KV2 : KV.second.Dependants)
1442         OS << "        " << KV2.first->getName() << ": " << KV2.second << "\n";
1443       OS << "      Unemitted Dependencies:\n";
1444       for (auto &KV2 : KV.second.UnemittedDependencies)
1445         OS << "        " << KV2.first->getName() << ": " << KV2.second << "\n";
1446       assert((Symbols[KV.first].getState() != SymbolState::Ready ||
1447               !KV.second.pendingQueries().empty() ||
1448               !KV.second.Dependants.empty() ||
1449               !KV.second.UnemittedDependencies.empty()) &&
1450              "Stale materializing info entry");
1451     }
1452   });
1453 }
1454 
1455 void JITDylib::MaterializingInfo::addQuery(
1456     std::shared_ptr<AsynchronousSymbolQuery> Q) {
1457 
1458   auto I = std::lower_bound(
1459       PendingQueries.rbegin(), PendingQueries.rend(), Q->getRequiredState(),
1460       [](const std::shared_ptr<AsynchronousSymbolQuery> &V, SymbolState S) {
1461         return V->getRequiredState() <= S;
1462       });
1463   PendingQueries.insert(I.base(), std::move(Q));
1464 }
1465 
1466 void JITDylib::MaterializingInfo::removeQuery(
1467     const AsynchronousSymbolQuery &Q) {
1468   // FIXME: Implement 'find_as' for shared_ptr<T>/T*.
1469   auto I = llvm::find_if(
1470       PendingQueries, [&Q](const std::shared_ptr<AsynchronousSymbolQuery> &V) {
1471         return V.get() == &Q;
1472       });
1473   assert(I != PendingQueries.end() &&
1474          "Query is not attached to this MaterializingInfo");
1475   PendingQueries.erase(I);
1476 }
1477 
1478 JITDylib::AsynchronousSymbolQueryList
1479 JITDylib::MaterializingInfo::takeQueriesMeeting(SymbolState RequiredState) {
1480   AsynchronousSymbolQueryList Result;
1481   while (!PendingQueries.empty()) {
1482     if (PendingQueries.back()->getRequiredState() > RequiredState)
1483       break;
1484 
1485     Result.push_back(std::move(PendingQueries.back()));
1486     PendingQueries.pop_back();
1487   }
1488 
1489   return Result;
1490 }
1491 
1492 JITDylib::JITDylib(ExecutionSession &ES, std::string Name)
1493     : JITLinkDylib(std::move(Name)), ES(ES) {
1494   LinkOrder.push_back({this, JITDylibLookupFlags::MatchAllSymbols});
1495 }
1496 
1497 std::pair<JITDylib::AsynchronousSymbolQuerySet,
1498           std::shared_ptr<SymbolDependenceMap>>
1499 JITDylib::removeTracker(ResourceTracker &RT) {
1500   // Note: Should be called under the session lock.
1501   assert(State != Closed && "JD is defunct");
1502 
1503   SymbolNameVector SymbolsToRemove;
1504   std::vector<std::pair<JITDylib *, SymbolStringPtr>> SymbolsToFail;
1505 
1506   if (&RT == DefaultTracker.get()) {
1507     SymbolNameSet TrackedSymbols;
1508     for (auto &KV : TrackerSymbols)
1509       for (auto &Sym : KV.second)
1510         TrackedSymbols.insert(Sym);
1511 
1512     for (auto &KV : Symbols) {
1513       auto &Sym = KV.first;
1514       if (!TrackedSymbols.count(Sym))
1515         SymbolsToRemove.push_back(Sym);
1516     }
1517 
1518     DefaultTracker.reset();
1519   } else {
1520     /// Check for a non-default tracker.
1521     auto I = TrackerSymbols.find(&RT);
1522     if (I != TrackerSymbols.end()) {
1523       SymbolsToRemove = std::move(I->second);
1524       TrackerSymbols.erase(I);
1525     }
1526     // ... if not found this tracker was already defunct. Nothing to do.
1527   }
1528 
1529   for (auto &Sym : SymbolsToRemove) {
1530     assert(Symbols.count(Sym) && "Symbol not in symbol table");
1531 
1532     // If there is a MaterializingInfo then collect any queries to fail.
1533     auto MII = MaterializingInfos.find(Sym);
1534     if (MII != MaterializingInfos.end())
1535       SymbolsToFail.push_back({this, Sym});
1536   }
1537 
1538   AsynchronousSymbolQuerySet QueriesToFail;
1539   auto Result = failSymbols(std::move(SymbolsToFail));
1540 
1541   // Removed symbols should be taken out of the table altogether.
1542   for (auto &Sym : SymbolsToRemove) {
1543     auto I = Symbols.find(Sym);
1544     assert(I != Symbols.end() && "Symbol not present in table");
1545 
1546     // Remove Materializer if present.
1547     if (I->second.hasMaterializerAttached()) {
1548       // FIXME: Should this discard the symbols?
1549       UnmaterializedInfos.erase(Sym);
1550     } else {
1551       assert(!UnmaterializedInfos.count(Sym) &&
1552              "Symbol has materializer attached");
1553     }
1554 
1555     Symbols.erase(I);
1556   }
1557 
1558   return Result;
1559 }
1560 
1561 void JITDylib::transferTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT) {
1562   assert(State != Closed && "JD is defunct");
1563   assert(&DstRT != &SrcRT && "No-op transfers shouldn't call transferTracker");
1564   assert(&DstRT.getJITDylib() == this && "DstRT is not for this JITDylib");
1565   assert(&SrcRT.getJITDylib() == this && "SrcRT is not for this JITDylib");
1566 
1567   // Update trackers for any not-yet materialized units.
1568   for (auto &KV : UnmaterializedInfos) {
1569     if (KV.second->RT == &SrcRT)
1570       KV.second->RT = &DstRT;
1571   }
1572 
1573   // Update trackers for any active materialization responsibilities.
1574   {
1575     auto I = TrackerMRs.find(&SrcRT);
1576     if (I != TrackerMRs.end()) {
1577       auto &SrcMRs = I->second;
1578       auto &DstMRs = TrackerMRs[&DstRT];
1579       for (auto *MR : SrcMRs)
1580         MR->RT = &DstRT;
1581       if (DstMRs.empty())
1582         DstMRs = std::move(SrcMRs);
1583       else
1584         for (auto *MR : SrcMRs)
1585           DstMRs.insert(MR);
1586       // Erase SrcRT entry in TrackerMRs. Use &SrcRT key rather than iterator I
1587       // for this, since I may have been invalidated by 'TrackerMRs[&DstRT]'.
1588       TrackerMRs.erase(&SrcRT);
1589     }
1590   }
1591 
1592   // If we're transfering to the default tracker we just need to delete the
1593   // tracked symbols for the source tracker.
1594   if (&DstRT == DefaultTracker.get()) {
1595     TrackerSymbols.erase(&SrcRT);
1596     return;
1597   }
1598 
1599   // If we're transferring from the default tracker we need to find all
1600   // currently untracked symbols.
1601   if (&SrcRT == DefaultTracker.get()) {
1602     assert(!TrackerSymbols.count(&SrcRT) &&
1603            "Default tracker should not appear in TrackerSymbols");
1604 
1605     SymbolNameVector SymbolsToTrack;
1606 
1607     SymbolNameSet CurrentlyTrackedSymbols;
1608     for (auto &KV : TrackerSymbols)
1609       for (auto &Sym : KV.second)
1610         CurrentlyTrackedSymbols.insert(Sym);
1611 
1612     for (auto &KV : Symbols) {
1613       auto &Sym = KV.first;
1614       if (!CurrentlyTrackedSymbols.count(Sym))
1615         SymbolsToTrack.push_back(Sym);
1616     }
1617 
1618     TrackerSymbols[&DstRT] = std::move(SymbolsToTrack);
1619     return;
1620   }
1621 
1622   auto &DstTrackedSymbols = TrackerSymbols[&DstRT];
1623 
1624   // Finally if neither SrtRT or DstRT are the default tracker then
1625   // just append DstRT's tracked symbols to SrtRT's.
1626   auto SI = TrackerSymbols.find(&SrcRT);
1627   if (SI == TrackerSymbols.end())
1628     return;
1629 
1630   DstTrackedSymbols.reserve(DstTrackedSymbols.size() + SI->second.size());
1631   for (auto &Sym : SI->second)
1632     DstTrackedSymbols.push_back(std::move(Sym));
1633   TrackerSymbols.erase(SI);
1634 }
1635 
1636 Error JITDylib::defineImpl(MaterializationUnit &MU) {
1637 
1638   LLVM_DEBUG({ dbgs() << "  " << MU.getSymbols() << "\n"; });
1639 
1640   SymbolNameSet Duplicates;
1641   std::vector<SymbolStringPtr> ExistingDefsOverridden;
1642   std::vector<SymbolStringPtr> MUDefsOverridden;
1643 
1644   for (const auto &KV : MU.getSymbols()) {
1645     auto I = Symbols.find(KV.first);
1646 
1647     if (I != Symbols.end()) {
1648       if (KV.second.isStrong()) {
1649         if (I->second.getFlags().isStrong() ||
1650             I->second.getState() > SymbolState::NeverSearched)
1651           Duplicates.insert(KV.first);
1652         else {
1653           assert(I->second.getState() == SymbolState::NeverSearched &&
1654                  "Overridden existing def should be in the never-searched "
1655                  "state");
1656           ExistingDefsOverridden.push_back(KV.first);
1657         }
1658       } else
1659         MUDefsOverridden.push_back(KV.first);
1660     }
1661   }
1662 
1663   // If there were any duplicate definitions then bail out.
1664   if (!Duplicates.empty()) {
1665     LLVM_DEBUG(
1666         { dbgs() << "  Error: Duplicate symbols " << Duplicates << "\n"; });
1667     return make_error<DuplicateDefinition>(std::string(**Duplicates.begin()));
1668   }
1669 
1670   // Discard any overridden defs in this MU.
1671   LLVM_DEBUG({
1672     if (!MUDefsOverridden.empty())
1673       dbgs() << "  Defs in this MU overridden: " << MUDefsOverridden << "\n";
1674   });
1675   for (auto &S : MUDefsOverridden)
1676     MU.doDiscard(*this, S);
1677 
1678   // Discard existing overridden defs.
1679   LLVM_DEBUG({
1680     if (!ExistingDefsOverridden.empty())
1681       dbgs() << "  Existing defs overridden by this MU: " << MUDefsOverridden
1682              << "\n";
1683   });
1684   for (auto &S : ExistingDefsOverridden) {
1685 
1686     auto UMII = UnmaterializedInfos.find(S);
1687     assert(UMII != UnmaterializedInfos.end() &&
1688            "Overridden existing def should have an UnmaterializedInfo");
1689     UMII->second->MU->doDiscard(*this, S);
1690   }
1691 
1692   // Finally, add the defs from this MU.
1693   for (auto &KV : MU.getSymbols()) {
1694     auto &SymEntry = Symbols[KV.first];
1695     SymEntry.setFlags(KV.second);
1696     SymEntry.setState(SymbolState::NeverSearched);
1697     SymEntry.setMaterializerAttached(true);
1698   }
1699 
1700   return Error::success();
1701 }
1702 
1703 void JITDylib::installMaterializationUnit(
1704     std::unique_ptr<MaterializationUnit> MU, ResourceTracker &RT) {
1705 
1706   /// defineImpl succeeded.
1707   if (&RT != DefaultTracker.get()) {
1708     auto &TS = TrackerSymbols[&RT];
1709     TS.reserve(TS.size() + MU->getSymbols().size());
1710     for (auto &KV : MU->getSymbols())
1711       TS.push_back(KV.first);
1712   }
1713 
1714   auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU), &RT);
1715   for (auto &KV : UMI->MU->getSymbols())
1716     UnmaterializedInfos[KV.first] = UMI;
1717 }
1718 
1719 void JITDylib::detachQueryHelper(AsynchronousSymbolQuery &Q,
1720                                  const SymbolNameSet &QuerySymbols) {
1721   for (auto &QuerySymbol : QuerySymbols) {
1722     assert(MaterializingInfos.count(QuerySymbol) &&
1723            "QuerySymbol does not have MaterializingInfo");
1724     auto &MI = MaterializingInfos[QuerySymbol];
1725     MI.removeQuery(Q);
1726   }
1727 }
1728 
1729 void JITDylib::transferEmittedNodeDependencies(
1730     MaterializingInfo &DependantMI, const SymbolStringPtr &DependantName,
1731     MaterializingInfo &EmittedMI) {
1732   for (auto &KV : EmittedMI.UnemittedDependencies) {
1733     auto &DependencyJD = *KV.first;
1734     SymbolNameSet *UnemittedDependenciesOnDependencyJD = nullptr;
1735 
1736     for (auto &DependencyName : KV.second) {
1737       auto &DependencyMI = DependencyJD.MaterializingInfos[DependencyName];
1738 
1739       // Do not add self dependencies.
1740       if (&DependencyMI == &DependantMI)
1741         continue;
1742 
1743       // If we haven't looked up the dependencies for DependencyJD yet, do it
1744       // now and cache the result.
1745       if (!UnemittedDependenciesOnDependencyJD)
1746         UnemittedDependenciesOnDependencyJD =
1747             &DependantMI.UnemittedDependencies[&DependencyJD];
1748 
1749       DependencyMI.Dependants[this].insert(DependantName);
1750       UnemittedDependenciesOnDependencyJD->insert(DependencyName);
1751     }
1752   }
1753 }
1754 
1755 Platform::~Platform() {}
1756 
1757 Expected<DenseMap<JITDylib *, SymbolMap>> Platform::lookupInitSymbols(
1758     ExecutionSession &ES,
1759     const DenseMap<JITDylib *, SymbolLookupSet> &InitSyms) {
1760 
1761   DenseMap<JITDylib *, SymbolMap> CompoundResult;
1762   Error CompoundErr = Error::success();
1763   std::mutex LookupMutex;
1764   std::condition_variable CV;
1765   uint64_t Count = InitSyms.size();
1766 
1767   LLVM_DEBUG({
1768     dbgs() << "Issuing init-symbol lookup:\n";
1769     for (auto &KV : InitSyms)
1770       dbgs() << "  " << KV.first->getName() << ": " << KV.second << "\n";
1771   });
1772 
1773   for (auto &KV : InitSyms) {
1774     auto *JD = KV.first;
1775     auto Names = std::move(KV.second);
1776     ES.lookup(
1777         LookupKind::Static,
1778         JITDylibSearchOrder({{JD, JITDylibLookupFlags::MatchAllSymbols}}),
1779         std::move(Names), SymbolState::Ready,
1780         [&, JD](Expected<SymbolMap> Result) {
1781           {
1782             std::lock_guard<std::mutex> Lock(LookupMutex);
1783             --Count;
1784             if (Result) {
1785               assert(!CompoundResult.count(JD) &&
1786                      "Duplicate JITDylib in lookup?");
1787               CompoundResult[JD] = std::move(*Result);
1788             } else
1789               CompoundErr =
1790                   joinErrors(std::move(CompoundErr), Result.takeError());
1791           }
1792           CV.notify_one();
1793         },
1794         NoDependenciesToRegister);
1795   }
1796 
1797   std::unique_lock<std::mutex> Lock(LookupMutex);
1798   CV.wait(Lock, [&] { return Count == 0 || CompoundErr; });
1799 
1800   if (CompoundErr)
1801     return std::move(CompoundErr);
1802 
1803   return std::move(CompoundResult);
1804 }
1805 
1806 void Platform::lookupInitSymbolsAsync(
1807     unique_function<void(Error)> OnComplete, ExecutionSession &ES,
1808     const DenseMap<JITDylib *, SymbolLookupSet> &InitSyms) {
1809 
1810   class TriggerOnComplete {
1811   public:
1812     using OnCompleteFn = unique_function<void(Error)>;
1813     TriggerOnComplete(OnCompleteFn OnComplete)
1814         : OnComplete(std::move(OnComplete)) {}
1815     ~TriggerOnComplete() { OnComplete(std::move(LookupResult)); }
1816     void reportResult(Error Err) {
1817       std::lock_guard<std::mutex> Lock(ResultMutex);
1818       LookupResult = joinErrors(std::move(LookupResult), std::move(Err));
1819     }
1820 
1821   private:
1822     std::mutex ResultMutex;
1823     Error LookupResult{Error::success()};
1824     OnCompleteFn OnComplete;
1825   };
1826 
1827   LLVM_DEBUG({
1828     dbgs() << "Issuing init-symbol lookup:\n";
1829     for (auto &KV : InitSyms)
1830       dbgs() << "  " << KV.first->getName() << ": " << KV.second << "\n";
1831   });
1832 
1833   auto TOC = std::make_shared<TriggerOnComplete>(std::move(OnComplete));
1834 
1835   for (auto &KV : InitSyms) {
1836     auto *JD = KV.first;
1837     auto Names = std::move(KV.second);
1838     ES.lookup(
1839         LookupKind::Static,
1840         JITDylibSearchOrder({{JD, JITDylibLookupFlags::MatchAllSymbols}}),
1841         std::move(Names), SymbolState::Ready,
1842         [TOC](Expected<SymbolMap> Result) {
1843           TOC->reportResult(Result.takeError());
1844         },
1845         NoDependenciesToRegister);
1846   }
1847 }
1848 
1849 void MaterializationTask::printDescription(raw_ostream &OS) {
1850   OS << "Materialization task: " << MU->getName() << " in "
1851      << MR->getTargetJITDylib().getName();
1852 }
1853 
1854 void MaterializationTask::run() { MU->materialize(std::move(MR)); }
1855 
1856 ExecutionSession::ExecutionSession(std::unique_ptr<ExecutorProcessControl> EPC)
1857     : EPC(std::move(EPC)) {
1858   // Associated EPC and this.
1859   this->EPC->ES = this;
1860 }
1861 
1862 Error ExecutionSession::endSession() {
1863   LLVM_DEBUG(dbgs() << "Ending ExecutionSession " << this << "\n");
1864 
1865   std::vector<JITDylibSP> JITDylibsToClose = runSessionLocked([&] {
1866     SessionOpen = false;
1867     return std::move(JDs);
1868   });
1869 
1870   // TODO: notifiy platform? run static deinits?
1871 
1872   Error Err = Error::success();
1873   for (auto &JD : JITDylibsToClose)
1874     Err = joinErrors(std::move(Err), JD->clear());
1875 
1876   Err = joinErrors(std::move(Err), EPC->disconnect());
1877 
1878   return Err;
1879 }
1880 
1881 void ExecutionSession::registerResourceManager(ResourceManager &RM) {
1882   runSessionLocked([&] { ResourceManagers.push_back(&RM); });
1883 }
1884 
1885 void ExecutionSession::deregisterResourceManager(ResourceManager &RM) {
1886   runSessionLocked([&] {
1887     assert(!ResourceManagers.empty() && "No managers registered");
1888     if (ResourceManagers.back() == &RM)
1889       ResourceManagers.pop_back();
1890     else {
1891       auto I = llvm::find(ResourceManagers, &RM);
1892       assert(I != ResourceManagers.end() && "RM not registered");
1893       ResourceManagers.erase(I);
1894     }
1895   });
1896 }
1897 
1898 JITDylib *ExecutionSession::getJITDylibByName(StringRef Name) {
1899   return runSessionLocked([&, this]() -> JITDylib * {
1900     for (auto &JD : JDs)
1901       if (JD->getName() == Name)
1902         return JD.get();
1903     return nullptr;
1904   });
1905 }
1906 
1907 JITDylib &ExecutionSession::createBareJITDylib(std::string Name) {
1908   assert(!getJITDylibByName(Name) && "JITDylib with that name already exists");
1909   return runSessionLocked([&, this]() -> JITDylib & {
1910     JDs.push_back(new JITDylib(*this, std::move(Name)));
1911     return *JDs.back();
1912   });
1913 }
1914 
1915 Expected<JITDylib &> ExecutionSession::createJITDylib(std::string Name) {
1916   auto &JD = createBareJITDylib(Name);
1917   if (P)
1918     if (auto Err = P->setupJITDylib(JD))
1919       return std::move(Err);
1920   return JD;
1921 }
1922 
1923 Error ExecutionSession::removeJITDylib(JITDylib &JD) {
1924   // Keep JD alive throughout this routine, even if all other references
1925   // have been dropped.
1926   JITDylibSP JDKeepAlive = &JD;
1927 
1928   // Set JD to 'Closing' state and remove JD from the ExecutionSession.
1929   runSessionLocked([&] {
1930     assert(JD.State == JITDylib::Open && "JD already closed");
1931     JD.State = JITDylib::Closing;
1932     auto I = llvm::find(JDs, &JD);
1933     assert(I != JDs.end() && "JD does not appear in session JDs");
1934     JDs.erase(I);
1935   });
1936 
1937   // Clear the JITDylib.
1938   auto Err = JD.clear();
1939 
1940   // Set JD to closed state. Clear remaining data structures.
1941   runSessionLocked([&] {
1942     assert(JD.State == JITDylib::Closing && "JD should be closing");
1943     JD.State = JITDylib::Closed;
1944     assert(JD.Symbols.empty() && "JD.Symbols is not empty after clear");
1945     assert(JD.UnmaterializedInfos.empty() &&
1946            "JD.UnmaterializedInfos is not empty after clear");
1947     assert(JD.MaterializingInfos.empty() &&
1948            "JD.MaterializingInfos is not empty after clear");
1949     assert(JD.TrackerSymbols.empty() &&
1950            "TrackerSymbols is not empty after clear");
1951     JD.DefGenerators.clear();
1952     JD.LinkOrder.clear();
1953   });
1954   return Err;
1955 }
1956 
1957 std::vector<JITDylibSP> JITDylib::getDFSLinkOrder(ArrayRef<JITDylibSP> JDs) {
1958   if (JDs.empty())
1959     return {};
1960 
1961   auto &ES = JDs.front()->getExecutionSession();
1962   return ES.runSessionLocked([&]() {
1963     DenseSet<JITDylib *> Visited;
1964     std::vector<JITDylibSP> Result;
1965 
1966     for (auto &JD : JDs) {
1967 
1968       assert(JD->State == Open && "JD is defunct");
1969 
1970       if (Visited.count(JD.get()))
1971         continue;
1972 
1973       SmallVector<JITDylibSP, 64> WorkStack;
1974       WorkStack.push_back(JD);
1975       Visited.insert(JD.get());
1976 
1977       while (!WorkStack.empty()) {
1978         Result.push_back(std::move(WorkStack.back()));
1979         WorkStack.pop_back();
1980 
1981         for (auto &KV : llvm::reverse(Result.back()->LinkOrder)) {
1982           auto &JD = *KV.first;
1983           if (Visited.count(&JD))
1984             continue;
1985           Visited.insert(&JD);
1986           WorkStack.push_back(&JD);
1987         }
1988       }
1989     }
1990     return Result;
1991   });
1992 }
1993 
1994 std::vector<JITDylibSP>
1995 JITDylib::getReverseDFSLinkOrder(ArrayRef<JITDylibSP> JDs) {
1996   auto Tmp = getDFSLinkOrder(JDs);
1997   std::reverse(Tmp.begin(), Tmp.end());
1998   return Tmp;
1999 }
2000 
2001 std::vector<JITDylibSP> JITDylib::getDFSLinkOrder() {
2002   return getDFSLinkOrder({this});
2003 }
2004 
2005 std::vector<JITDylibSP> JITDylib::getReverseDFSLinkOrder() {
2006   return getReverseDFSLinkOrder({this});
2007 }
2008 
2009 void ExecutionSession::lookupFlags(
2010     LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet,
2011     unique_function<void(Expected<SymbolFlagsMap>)> OnComplete) {
2012 
2013   OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
2014                           K, std::move(SearchOrder), std::move(LookupSet),
2015                           std::move(OnComplete)),
2016                       Error::success());
2017 }
2018 
2019 Expected<SymbolFlagsMap>
2020 ExecutionSession::lookupFlags(LookupKind K, JITDylibSearchOrder SearchOrder,
2021                               SymbolLookupSet LookupSet) {
2022 
2023   std::promise<MSVCPExpected<SymbolFlagsMap>> ResultP;
2024   OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
2025                           K, std::move(SearchOrder), std::move(LookupSet),
2026                           [&ResultP](Expected<SymbolFlagsMap> Result) {
2027                             ResultP.set_value(std::move(Result));
2028                           }),
2029                       Error::success());
2030 
2031   auto ResultF = ResultP.get_future();
2032   return ResultF.get();
2033 }
2034 
2035 void ExecutionSession::lookup(
2036     LookupKind K, const JITDylibSearchOrder &SearchOrder,
2037     SymbolLookupSet Symbols, SymbolState RequiredState,
2038     SymbolsResolvedCallback NotifyComplete,
2039     RegisterDependenciesFunction RegisterDependencies) {
2040 
2041   LLVM_DEBUG({
2042     runSessionLocked([&]() {
2043       dbgs() << "Looking up " << Symbols << " in " << SearchOrder
2044              << " (required state: " << RequiredState << ")\n";
2045     });
2046   });
2047 
2048   // lookup can be re-entered recursively if running on a single thread. Run any
2049   // outstanding MUs in case this query depends on them, otherwise this lookup
2050   // will starve waiting for a result from an MU that is stuck in the queue.
2051   dispatchOutstandingMUs();
2052 
2053   auto Unresolved = std::move(Symbols);
2054   auto Q = std::make_shared<AsynchronousSymbolQuery>(Unresolved, RequiredState,
2055                                                      std::move(NotifyComplete));
2056 
2057   auto IPLS = std::make_unique<InProgressFullLookupState>(
2058       K, SearchOrder, std::move(Unresolved), RequiredState, std::move(Q),
2059       std::move(RegisterDependencies));
2060 
2061   OL_applyQueryPhase1(std::move(IPLS), Error::success());
2062 }
2063 
2064 Expected<SymbolMap>
2065 ExecutionSession::lookup(const JITDylibSearchOrder &SearchOrder,
2066                          const SymbolLookupSet &Symbols, LookupKind K,
2067                          SymbolState RequiredState,
2068                          RegisterDependenciesFunction RegisterDependencies) {
2069 #if LLVM_ENABLE_THREADS
2070   // In the threaded case we use promises to return the results.
2071   std::promise<SymbolMap> PromisedResult;
2072   Error ResolutionError = Error::success();
2073 
2074   auto NotifyComplete = [&](Expected<SymbolMap> R) {
2075     if (R)
2076       PromisedResult.set_value(std::move(*R));
2077     else {
2078       ErrorAsOutParameter _(&ResolutionError);
2079       ResolutionError = R.takeError();
2080       PromisedResult.set_value(SymbolMap());
2081     }
2082   };
2083 
2084 #else
2085   SymbolMap Result;
2086   Error ResolutionError = Error::success();
2087 
2088   auto NotifyComplete = [&](Expected<SymbolMap> R) {
2089     ErrorAsOutParameter _(&ResolutionError);
2090     if (R)
2091       Result = std::move(*R);
2092     else
2093       ResolutionError = R.takeError();
2094   };
2095 #endif
2096 
2097   // Perform the asynchronous lookup.
2098   lookup(K, SearchOrder, Symbols, RequiredState, NotifyComplete,
2099          RegisterDependencies);
2100 
2101 #if LLVM_ENABLE_THREADS
2102   auto ResultFuture = PromisedResult.get_future();
2103   auto Result = ResultFuture.get();
2104 
2105   if (ResolutionError)
2106     return std::move(ResolutionError);
2107 
2108   return std::move(Result);
2109 
2110 #else
2111   if (ResolutionError)
2112     return std::move(ResolutionError);
2113 
2114   return Result;
2115 #endif
2116 }
2117 
2118 Expected<JITEvaluatedSymbol>
2119 ExecutionSession::lookup(const JITDylibSearchOrder &SearchOrder,
2120                          SymbolStringPtr Name, SymbolState RequiredState) {
2121   SymbolLookupSet Names({Name});
2122 
2123   if (auto ResultMap = lookup(SearchOrder, std::move(Names), LookupKind::Static,
2124                               RequiredState, NoDependenciesToRegister)) {
2125     assert(ResultMap->size() == 1 && "Unexpected number of results");
2126     assert(ResultMap->count(Name) && "Missing result for symbol");
2127     return std::move(ResultMap->begin()->second);
2128   } else
2129     return ResultMap.takeError();
2130 }
2131 
2132 Expected<JITEvaluatedSymbol>
2133 ExecutionSession::lookup(ArrayRef<JITDylib *> SearchOrder, SymbolStringPtr Name,
2134                          SymbolState RequiredState) {
2135   return lookup(makeJITDylibSearchOrder(SearchOrder), Name, RequiredState);
2136 }
2137 
2138 Expected<JITEvaluatedSymbol>
2139 ExecutionSession::lookup(ArrayRef<JITDylib *> SearchOrder, StringRef Name,
2140                          SymbolState RequiredState) {
2141   return lookup(SearchOrder, intern(Name), RequiredState);
2142 }
2143 
2144 Error ExecutionSession::registerJITDispatchHandlers(
2145     JITDylib &JD, JITDispatchHandlerAssociationMap WFs) {
2146 
2147   auto TagAddrs = lookup({{&JD, JITDylibLookupFlags::MatchAllSymbols}},
2148                          SymbolLookupSet::fromMapKeys(
2149                              WFs, SymbolLookupFlags::WeaklyReferencedSymbol));
2150   if (!TagAddrs)
2151     return TagAddrs.takeError();
2152 
2153   // Associate tag addresses with implementations.
2154   std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
2155   for (auto &KV : *TagAddrs) {
2156     auto TagAddr = KV.second.getAddress();
2157     if (JITDispatchHandlers.count(TagAddr))
2158       return make_error<StringError>("Tag " + formatv("{0:x16}", TagAddr) +
2159                                          " (for " + *KV.first +
2160                                          ") already registered",
2161                                      inconvertibleErrorCode());
2162     auto I = WFs.find(KV.first);
2163     assert(I != WFs.end() && I->second &&
2164            "JITDispatchHandler implementation missing");
2165     JITDispatchHandlers[KV.second.getAddress()] =
2166         std::make_shared<JITDispatchHandlerFunction>(std::move(I->second));
2167     LLVM_DEBUG({
2168       dbgs() << "Associated function tag \"" << *KV.first << "\" ("
2169              << formatv("{0:x}", KV.second.getAddress()) << ") with handler\n";
2170     });
2171   }
2172   return Error::success();
2173 }
2174 
2175 void ExecutionSession::runJITDispatchHandler(
2176     SendResultFunction SendResult, JITTargetAddress HandlerFnTagAddr,
2177     ArrayRef<char> ArgBuffer) {
2178 
2179   std::shared_ptr<JITDispatchHandlerFunction> F;
2180   {
2181     std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
2182     auto I = JITDispatchHandlers.find(HandlerFnTagAddr);
2183     if (I != JITDispatchHandlers.end())
2184       F = I->second;
2185   }
2186 
2187   if (F)
2188     (*F)(std::move(SendResult), ArgBuffer.data(), ArgBuffer.size());
2189   else
2190     SendResult(shared::WrapperFunctionResult::createOutOfBandError(
2191         ("No function registered for tag " +
2192          formatv("{0:x16}", HandlerFnTagAddr))
2193             .str()));
2194 }
2195 
2196 void ExecutionSession::dump(raw_ostream &OS) {
2197   runSessionLocked([this, &OS]() {
2198     for (auto &JD : JDs)
2199       JD->dump(OS);
2200   });
2201 }
2202 
2203 void ExecutionSession::dispatchOutstandingMUs() {
2204   LLVM_DEBUG(dbgs() << "Dispatching MaterializationUnits...\n");
2205   while (1) {
2206     Optional<std::pair<std::unique_ptr<MaterializationUnit>,
2207                        std::unique_ptr<MaterializationResponsibility>>>
2208         JMU;
2209 
2210     {
2211       std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2212       if (!OutstandingMUs.empty()) {
2213         JMU.emplace(std::move(OutstandingMUs.back()));
2214         OutstandingMUs.pop_back();
2215       }
2216     }
2217 
2218     if (!JMU)
2219       break;
2220 
2221     assert(JMU->first && "No MU?");
2222     LLVM_DEBUG(dbgs() << "  Dispatching \"" << JMU->first->getName() << "\"\n");
2223     dispatchTask(std::make_unique<MaterializationTask>(std::move(JMU->first),
2224                                                        std::move(JMU->second)));
2225   }
2226   LLVM_DEBUG(dbgs() << "Done dispatching MaterializationUnits.\n");
2227 }
2228 
2229 Error ExecutionSession::removeResourceTracker(ResourceTracker &RT) {
2230   LLVM_DEBUG({
2231     dbgs() << "In " << RT.getJITDylib().getName() << " removing tracker "
2232            << formatv("{0:x}", RT.getKeyUnsafe()) << "\n";
2233   });
2234   std::vector<ResourceManager *> CurrentResourceManagers;
2235 
2236   JITDylib::AsynchronousSymbolQuerySet QueriesToFail;
2237   std::shared_ptr<SymbolDependenceMap> FailedSymbols;
2238 
2239   runSessionLocked([&] {
2240     CurrentResourceManagers = ResourceManagers;
2241     RT.makeDefunct();
2242     std::tie(QueriesToFail, FailedSymbols) = RT.getJITDylib().removeTracker(RT);
2243   });
2244 
2245   Error Err = Error::success();
2246 
2247   for (auto *L : reverse(CurrentResourceManagers))
2248     Err =
2249         joinErrors(std::move(Err), L->handleRemoveResources(RT.getKeyUnsafe()));
2250 
2251   for (auto &Q : QueriesToFail)
2252     Q->handleFailed(make_error<FailedToMaterialize>(FailedSymbols));
2253 
2254   return Err;
2255 }
2256 
2257 void ExecutionSession::transferResourceTracker(ResourceTracker &DstRT,
2258                                                ResourceTracker &SrcRT) {
2259   LLVM_DEBUG({
2260     dbgs() << "In " << SrcRT.getJITDylib().getName()
2261            << " transfering resources from tracker "
2262            << formatv("{0:x}", SrcRT.getKeyUnsafe()) << " to tracker "
2263            << formatv("{0:x}", DstRT.getKeyUnsafe()) << "\n";
2264   });
2265 
2266   // No-op transfers are allowed and do not invalidate the source.
2267   if (&DstRT == &SrcRT)
2268     return;
2269 
2270   assert(&DstRT.getJITDylib() == &SrcRT.getJITDylib() &&
2271          "Can't transfer resources between JITDylibs");
2272   runSessionLocked([&]() {
2273     SrcRT.makeDefunct();
2274     auto &JD = DstRT.getJITDylib();
2275     JD.transferTracker(DstRT, SrcRT);
2276     for (auto *L : reverse(ResourceManagers))
2277       L->handleTransferResources(DstRT.getKeyUnsafe(), SrcRT.getKeyUnsafe());
2278   });
2279 }
2280 
2281 void ExecutionSession::destroyResourceTracker(ResourceTracker &RT) {
2282   runSessionLocked([&]() {
2283     LLVM_DEBUG({
2284       dbgs() << "In " << RT.getJITDylib().getName() << " destroying tracker "
2285              << formatv("{0:x}", RT.getKeyUnsafe()) << "\n";
2286     });
2287     if (!RT.isDefunct())
2288       transferResourceTracker(*RT.getJITDylib().getDefaultResourceTracker(),
2289                               RT);
2290   });
2291 }
2292 
2293 Error ExecutionSession::IL_updateCandidatesFor(
2294     JITDylib &JD, JITDylibLookupFlags JDLookupFlags,
2295     SymbolLookupSet &Candidates, SymbolLookupSet *NonCandidates) {
2296   return Candidates.forEachWithRemoval(
2297       [&](const SymbolStringPtr &Name,
2298           SymbolLookupFlags SymLookupFlags) -> Expected<bool> {
2299         /// Search for the symbol. If not found then continue without
2300         /// removal.
2301         auto SymI = JD.Symbols.find(Name);
2302         if (SymI == JD.Symbols.end())
2303           return false;
2304 
2305         // If this is a non-exported symbol and we're matching exported
2306         // symbols only then remove this symbol from the candidates list.
2307         //
2308         // If we're tracking non-candidates then add this to the non-candidate
2309         // list.
2310         if (!SymI->second.getFlags().isExported() &&
2311             JDLookupFlags == JITDylibLookupFlags::MatchExportedSymbolsOnly) {
2312           if (NonCandidates)
2313             NonCandidates->add(Name, SymLookupFlags);
2314           return true;
2315         }
2316 
2317         // If we match against a materialization-side-effects only symbol
2318         // then make sure it is weakly-referenced. Otherwise bail out with
2319         // an error.
2320         // FIXME: Use a "materialization-side-effects-only symbols must be
2321         // weakly referenced" specific error here to reduce confusion.
2322         if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2323             SymLookupFlags != SymbolLookupFlags::WeaklyReferencedSymbol)
2324           return make_error<SymbolsNotFound>(getSymbolStringPool(),
2325                                              SymbolNameVector({Name}));
2326 
2327         // If we matched against this symbol but it is in the error state
2328         // then bail out and treat it as a failure to materialize.
2329         if (SymI->second.getFlags().hasError()) {
2330           auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2331           (*FailedSymbolsMap)[&JD] = {Name};
2332           return make_error<FailedToMaterialize>(std::move(FailedSymbolsMap));
2333         }
2334 
2335         // Otherwise this is a match. Remove it from the candidate set.
2336         return true;
2337       });
2338 }
2339 
2340 void ExecutionSession::OL_applyQueryPhase1(
2341     std::unique_ptr<InProgressLookupState> IPLS, Error Err) {
2342 
2343   LLVM_DEBUG({
2344     dbgs() << "Entering OL_applyQueryPhase1:\n"
2345            << "  Lookup kind: " << IPLS->K << "\n"
2346            << "  Search order: " << IPLS->SearchOrder
2347            << ", Current index = " << IPLS->CurSearchOrderIndex
2348            << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2349            << "  Lookup set: " << IPLS->LookupSet << "\n"
2350            << "  Definition generator candidates: "
2351            << IPLS->DefGeneratorCandidates << "\n"
2352            << "  Definition generator non-candidates: "
2353            << IPLS->DefGeneratorNonCandidates << "\n";
2354   });
2355 
2356   // FIXME: We should attach the query as we go: This provides a result in a
2357   // single pass in the common case where all symbols have already reached the
2358   // required state. The query could be detached again in the 'fail' method on
2359   // IPLS. Phase 2 would be reduced to collecting and dispatching the MUs.
2360 
2361   while (IPLS->CurSearchOrderIndex != IPLS->SearchOrder.size()) {
2362 
2363     // If we've been handed an error or received one back from a generator then
2364     // fail the query. We don't need to unlink: At this stage the query hasn't
2365     // actually been lodged.
2366     if (Err)
2367       return IPLS->fail(std::move(Err));
2368 
2369     // Get the next JITDylib and lookup flags.
2370     auto &KV = IPLS->SearchOrder[IPLS->CurSearchOrderIndex];
2371     auto &JD = *KV.first;
2372     auto JDLookupFlags = KV.second;
2373 
2374     LLVM_DEBUG({
2375       dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2376              << ") with lookup set " << IPLS->LookupSet << ":\n";
2377     });
2378 
2379     // If we've just reached a new JITDylib then perform some setup.
2380     if (IPLS->NewJITDylib) {
2381 
2382       // Acquire the generator lock for this JITDylib.
2383       IPLS->GeneratorLock = std::unique_lock<std::mutex>(JD.GeneratorsMutex);
2384 
2385       // Add any non-candidates from the last JITDylib (if any) back on to the
2386       // list of definition candidates for this JITDylib, reset definition
2387       // non-candiates to the empty set.
2388       SymbolLookupSet Tmp;
2389       std::swap(IPLS->DefGeneratorNonCandidates, Tmp);
2390       IPLS->DefGeneratorCandidates.append(std::move(Tmp));
2391 
2392       LLVM_DEBUG({
2393         dbgs() << "  First time visiting " << JD.getName()
2394                << ", resetting candidate sets and building generator stack\n";
2395       });
2396 
2397       // Build the definition generator stack for this JITDylib.
2398       runSessionLocked([&] {
2399         IPLS->CurDefGeneratorStack.reserve(JD.DefGenerators.size());
2400         for (auto &DG : reverse(JD.DefGenerators))
2401           IPLS->CurDefGeneratorStack.push_back(DG);
2402       });
2403 
2404       // Flag that we've done our initialization.
2405       IPLS->NewJITDylib = false;
2406     }
2407 
2408     // Remove any generation candidates that are already defined (and match) in
2409     // this JITDylib.
2410     runSessionLocked([&] {
2411       // Update the list of candidates (and non-candidates) for definition
2412       // generation.
2413       LLVM_DEBUG(dbgs() << "  Updating candidate set...\n");
2414       Err = IL_updateCandidatesFor(
2415           JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2416           JD.DefGenerators.empty() ? nullptr
2417                                    : &IPLS->DefGeneratorNonCandidates);
2418       LLVM_DEBUG({
2419         dbgs() << "    Remaining candidates = " << IPLS->DefGeneratorCandidates
2420                << "\n";
2421       });
2422     });
2423 
2424     // If we encountered an error while filtering generation candidates then
2425     // bail out.
2426     if (Err)
2427       return IPLS->fail(std::move(Err));
2428 
2429     /// Apply any definition generators on the stack.
2430     LLVM_DEBUG({
2431       if (IPLS->CurDefGeneratorStack.empty())
2432         LLVM_DEBUG(dbgs() << "  No generators to run for this JITDylib.\n");
2433       else if (IPLS->DefGeneratorCandidates.empty())
2434         LLVM_DEBUG(dbgs() << "  No candidates to generate.\n");
2435       else
2436         dbgs() << "  Running " << IPLS->CurDefGeneratorStack.size()
2437                << " remaining generators for "
2438                << IPLS->DefGeneratorCandidates.size() << " candidates\n";
2439     });
2440     while (!IPLS->CurDefGeneratorStack.empty() &&
2441            !IPLS->DefGeneratorCandidates.empty()) {
2442       auto DG = IPLS->CurDefGeneratorStack.back().lock();
2443       IPLS->CurDefGeneratorStack.pop_back();
2444 
2445       if (!DG)
2446         return IPLS->fail(make_error<StringError>(
2447             "DefinitionGenerator removed while lookup in progress",
2448             inconvertibleErrorCode()));
2449 
2450       auto K = IPLS->K;
2451       auto &LookupSet = IPLS->DefGeneratorCandidates;
2452 
2453       // Run the generator. If the generator takes ownership of QA then this
2454       // will break the loop.
2455       {
2456         LLVM_DEBUG(dbgs() << "  Attempting to generate " << LookupSet << "\n");
2457         LookupState LS(std::move(IPLS));
2458         Err = DG->tryToGenerate(LS, K, JD, JDLookupFlags, LookupSet);
2459         IPLS = std::move(LS.IPLS);
2460       }
2461 
2462       // If there was an error then fail the query.
2463       if (Err) {
2464         LLVM_DEBUG({
2465           dbgs() << "  Error attempting to generate " << LookupSet << "\n";
2466         });
2467         assert(IPLS && "LS cannot be retained if error is returned");
2468         return IPLS->fail(std::move(Err));
2469       }
2470 
2471       // Otherwise if QA was captured then break the loop.
2472       if (!IPLS) {
2473         LLVM_DEBUG(
2474             { dbgs() << "  LookupState captured. Exiting phase1 for now.\n"; });
2475         return;
2476       }
2477 
2478       // Otherwise if we're continuing around the loop then update candidates
2479       // for the next round.
2480       runSessionLocked([&] {
2481         LLVM_DEBUG(dbgs() << "  Updating candidate set post-generation\n");
2482         Err = IL_updateCandidatesFor(
2483             JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2484             JD.DefGenerators.empty() ? nullptr
2485                                      : &IPLS->DefGeneratorNonCandidates);
2486       });
2487 
2488       // If updating candidates failed then fail the query.
2489       if (Err) {
2490         LLVM_DEBUG(dbgs() << "  Error encountered while updating candidates\n");
2491         return IPLS->fail(std::move(Err));
2492       }
2493     }
2494 
2495     // If we get here then we've moved on to the next JITDylib.
2496     LLVM_DEBUG(dbgs() << "Phase 1 moving to next JITDylib.\n");
2497     ++IPLS->CurSearchOrderIndex;
2498     IPLS->NewJITDylib = true;
2499   }
2500 
2501   // Remove any weakly referenced candidates that could not be found/generated.
2502   IPLS->DefGeneratorCandidates.remove_if(
2503       [](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2504         return SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol;
2505       });
2506 
2507   // If we get here then we've finished searching all JITDylibs.
2508   // If we matched all symbols then move to phase 2, otherwise fail the query
2509   // with a SymbolsNotFound error.
2510   if (IPLS->DefGeneratorCandidates.empty()) {
2511     LLVM_DEBUG(dbgs() << "Phase 1 succeeded.\n");
2512     IPLS->complete(std::move(IPLS));
2513   } else {
2514     LLVM_DEBUG(dbgs() << "Phase 1 failed with unresolved symbols.\n");
2515     IPLS->fail(make_error<SymbolsNotFound>(
2516         getSymbolStringPool(), IPLS->DefGeneratorCandidates.getSymbolNames()));
2517   }
2518 }
2519 
2520 void ExecutionSession::OL_completeLookup(
2521     std::unique_ptr<InProgressLookupState> IPLS,
2522     std::shared_ptr<AsynchronousSymbolQuery> Q,
2523     RegisterDependenciesFunction RegisterDependencies) {
2524 
2525   LLVM_DEBUG({
2526     dbgs() << "Entering OL_completeLookup:\n"
2527            << "  Lookup kind: " << IPLS->K << "\n"
2528            << "  Search order: " << IPLS->SearchOrder
2529            << ", Current index = " << IPLS->CurSearchOrderIndex
2530            << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2531            << "  Lookup set: " << IPLS->LookupSet << "\n"
2532            << "  Definition generator candidates: "
2533            << IPLS->DefGeneratorCandidates << "\n"
2534            << "  Definition generator non-candidates: "
2535            << IPLS->DefGeneratorNonCandidates << "\n";
2536   });
2537 
2538   bool QueryComplete = false;
2539   DenseMap<JITDylib *, JITDylib::UnmaterializedInfosList> CollectedUMIs;
2540 
2541   auto LodgingErr = runSessionLocked([&]() -> Error {
2542     for (auto &KV : IPLS->SearchOrder) {
2543       auto &JD = *KV.first;
2544       auto JDLookupFlags = KV.second;
2545       LLVM_DEBUG({
2546         dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2547                << ") with lookup set " << IPLS->LookupSet << ":\n";
2548       });
2549 
2550       auto Err = IPLS->LookupSet.forEachWithRemoval(
2551           [&](const SymbolStringPtr &Name,
2552               SymbolLookupFlags SymLookupFlags) -> Expected<bool> {
2553             LLVM_DEBUG({
2554               dbgs() << "  Attempting to match \"" << Name << "\" ("
2555                      << SymLookupFlags << ")... ";
2556             });
2557 
2558             /// Search for the symbol. If not found then continue without
2559             /// removal.
2560             auto SymI = JD.Symbols.find(Name);
2561             if (SymI == JD.Symbols.end()) {
2562               LLVM_DEBUG(dbgs() << "skipping: not present\n");
2563               return false;
2564             }
2565 
2566             // If this is a non-exported symbol and we're matching exported
2567             // symbols only then skip this symbol without removal.
2568             if (!SymI->second.getFlags().isExported() &&
2569                 JDLookupFlags ==
2570                     JITDylibLookupFlags::MatchExportedSymbolsOnly) {
2571               LLVM_DEBUG(dbgs() << "skipping: not exported\n");
2572               return false;
2573             }
2574 
2575             // If we match against a materialization-side-effects only symbol
2576             // then make sure it is weakly-referenced. Otherwise bail out with
2577             // an error.
2578             // FIXME: Use a "materialization-side-effects-only symbols must be
2579             // weakly referenced" specific error here to reduce confusion.
2580             if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2581                 SymLookupFlags != SymbolLookupFlags::WeaklyReferencedSymbol) {
2582               LLVM_DEBUG({
2583                 dbgs() << "error: "
2584                           "required, but symbol is has-side-effects-only\n";
2585               });
2586               return make_error<SymbolsNotFound>(getSymbolStringPool(),
2587                                                  SymbolNameVector({Name}));
2588             }
2589 
2590             // If we matched against this symbol but it is in the error state
2591             // then bail out and treat it as a failure to materialize.
2592             if (SymI->second.getFlags().hasError()) {
2593               LLVM_DEBUG(dbgs() << "error: symbol is in error state\n");
2594               auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2595               (*FailedSymbolsMap)[&JD] = {Name};
2596               return make_error<FailedToMaterialize>(
2597                   std::move(FailedSymbolsMap));
2598             }
2599 
2600             // Otherwise this is a match.
2601 
2602             // If this symbol is already in the requried state then notify the
2603             // query, remove the symbol and continue.
2604             if (SymI->second.getState() >= Q->getRequiredState()) {
2605               LLVM_DEBUG(dbgs()
2606                          << "matched, symbol already in required state\n");
2607               Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
2608               return true;
2609             }
2610 
2611             // Otherwise this symbol does not yet meet the required state. Check
2612             // whether it has a materializer attached, and if so prepare to run
2613             // it.
2614             if (SymI->second.hasMaterializerAttached()) {
2615               assert(SymI->second.getAddress() == 0 &&
2616                      "Symbol not resolved but already has address?");
2617               auto UMII = JD.UnmaterializedInfos.find(Name);
2618               assert(UMII != JD.UnmaterializedInfos.end() &&
2619                      "Lazy symbol should have UnmaterializedInfo");
2620 
2621               auto UMI = UMII->second;
2622               assert(UMI->MU && "Materializer should not be null");
2623               assert(UMI->RT && "Tracker should not be null");
2624               LLVM_DEBUG({
2625                 dbgs() << "matched, preparing to dispatch MU@" << UMI->MU.get()
2626                        << " (" << UMI->MU->getName() << ")\n";
2627               });
2628 
2629               // Move all symbols associated with this MaterializationUnit into
2630               // materializing state.
2631               for (auto &KV : UMI->MU->getSymbols()) {
2632                 auto SymK = JD.Symbols.find(KV.first);
2633                 assert(SymK != JD.Symbols.end() &&
2634                        "No entry for symbol covered by MaterializationUnit");
2635                 SymK->second.setMaterializerAttached(false);
2636                 SymK->second.setState(SymbolState::Materializing);
2637                 JD.UnmaterializedInfos.erase(KV.first);
2638               }
2639 
2640               // Add MU to the list of MaterializationUnits to be materialized.
2641               CollectedUMIs[&JD].push_back(std::move(UMI));
2642             } else
2643               LLVM_DEBUG(dbgs() << "matched, registering query");
2644 
2645             // Add the query to the PendingQueries list and continue, deleting
2646             // the element from the lookup set.
2647             assert(SymI->second.getState() != SymbolState::NeverSearched &&
2648                    SymI->second.getState() != SymbolState::Ready &&
2649                    "By this line the symbol should be materializing");
2650             auto &MI = JD.MaterializingInfos[Name];
2651             MI.addQuery(Q);
2652             Q->addQueryDependence(JD, Name);
2653 
2654             return true;
2655           });
2656 
2657       // Handle failure.
2658       if (Err) {
2659 
2660         LLVM_DEBUG({
2661           dbgs() << "Lookup failed. Detaching query and replacing MUs.\n";
2662         });
2663 
2664         // Detach the query.
2665         Q->detach();
2666 
2667         // Replace the MUs.
2668         for (auto &KV : CollectedUMIs) {
2669           auto &JD = *KV.first;
2670           for (auto &UMI : KV.second)
2671             for (auto &KV2 : UMI->MU->getSymbols()) {
2672               assert(!JD.UnmaterializedInfos.count(KV2.first) &&
2673                      "Unexpected materializer in map");
2674               auto SymI = JD.Symbols.find(KV2.first);
2675               assert(SymI != JD.Symbols.end() && "Missing symbol entry");
2676               assert(SymI->second.getState() == SymbolState::Materializing &&
2677                      "Can not replace symbol that is not materializing");
2678               assert(!SymI->second.hasMaterializerAttached() &&
2679                      "MaterializerAttached flag should not be set");
2680               SymI->second.setMaterializerAttached(true);
2681               JD.UnmaterializedInfos[KV2.first] = UMI;
2682             }
2683         }
2684 
2685         return Err;
2686       }
2687     }
2688 
2689     LLVM_DEBUG(dbgs() << "Stripping unmatched weakly-referenced symbols\n");
2690     IPLS->LookupSet.forEachWithRemoval(
2691         [&](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2692           if (SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol) {
2693             Q->dropSymbol(Name);
2694             return true;
2695           } else
2696             return false;
2697         });
2698 
2699     if (!IPLS->LookupSet.empty()) {
2700       LLVM_DEBUG(dbgs() << "Failing due to unresolved symbols\n");
2701       return make_error<SymbolsNotFound>(getSymbolStringPool(),
2702                                          IPLS->LookupSet.getSymbolNames());
2703     }
2704 
2705     // Record whether the query completed.
2706     QueryComplete = Q->isComplete();
2707 
2708     LLVM_DEBUG({
2709       dbgs() << "Query successfully "
2710              << (QueryComplete ? "completed" : "lodged") << "\n";
2711     });
2712 
2713     // Move the collected MUs to the OutstandingMUs list.
2714     if (!CollectedUMIs.empty()) {
2715       std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2716 
2717       LLVM_DEBUG(dbgs() << "Adding MUs to dispatch:\n");
2718       for (auto &KV : CollectedUMIs) {
2719         LLVM_DEBUG({
2720           auto &JD = *KV.first;
2721           dbgs() << "  For " << JD.getName() << ": Adding " << KV.second.size()
2722                  << " MUs.\n";
2723         });
2724         for (auto &UMI : KV.second) {
2725           auto MR = createMaterializationResponsibility(
2726               *UMI->RT, std::move(UMI->MU->SymbolFlags),
2727               std::move(UMI->MU->InitSymbol));
2728           OutstandingMUs.push_back(
2729               std::make_pair(std::move(UMI->MU), std::move(MR)));
2730         }
2731       }
2732     } else
2733       LLVM_DEBUG(dbgs() << "No MUs to dispatch.\n");
2734 
2735     if (RegisterDependencies && !Q->QueryRegistrations.empty()) {
2736       LLVM_DEBUG(dbgs() << "Registering dependencies\n");
2737       RegisterDependencies(Q->QueryRegistrations);
2738     } else
2739       LLVM_DEBUG(dbgs() << "No dependencies to register\n");
2740 
2741     return Error::success();
2742   });
2743 
2744   if (LodgingErr) {
2745     LLVM_DEBUG(dbgs() << "Failing query\n");
2746     Q->detach();
2747     Q->handleFailed(std::move(LodgingErr));
2748     return;
2749   }
2750 
2751   if (QueryComplete) {
2752     LLVM_DEBUG(dbgs() << "Completing query\n");
2753     Q->handleComplete(*this);
2754   }
2755 
2756   dispatchOutstandingMUs();
2757 }
2758 
2759 void ExecutionSession::OL_completeLookupFlags(
2760     std::unique_ptr<InProgressLookupState> IPLS,
2761     unique_function<void(Expected<SymbolFlagsMap>)> OnComplete) {
2762 
2763   auto Result = runSessionLocked([&]() -> Expected<SymbolFlagsMap> {
2764     LLVM_DEBUG({
2765       dbgs() << "Entering OL_completeLookupFlags:\n"
2766              << "  Lookup kind: " << IPLS->K << "\n"
2767              << "  Search order: " << IPLS->SearchOrder
2768              << ", Current index = " << IPLS->CurSearchOrderIndex
2769              << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2770              << "  Lookup set: " << IPLS->LookupSet << "\n"
2771              << "  Definition generator candidates: "
2772              << IPLS->DefGeneratorCandidates << "\n"
2773              << "  Definition generator non-candidates: "
2774              << IPLS->DefGeneratorNonCandidates << "\n";
2775     });
2776 
2777     SymbolFlagsMap Result;
2778 
2779     // Attempt to find flags for each symbol.
2780     for (auto &KV : IPLS->SearchOrder) {
2781       auto &JD = *KV.first;
2782       auto JDLookupFlags = KV.second;
2783       LLVM_DEBUG({
2784         dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2785                << ") with lookup set " << IPLS->LookupSet << ":\n";
2786       });
2787 
2788       IPLS->LookupSet.forEachWithRemoval([&](const SymbolStringPtr &Name,
2789                                              SymbolLookupFlags SymLookupFlags) {
2790         LLVM_DEBUG({
2791           dbgs() << "  Attempting to match \"" << Name << "\" ("
2792                  << SymLookupFlags << ")... ";
2793         });
2794 
2795         // Search for the symbol. If not found then continue without removing
2796         // from the lookup set.
2797         auto SymI = JD.Symbols.find(Name);
2798         if (SymI == JD.Symbols.end()) {
2799           LLVM_DEBUG(dbgs() << "skipping: not present\n");
2800           return false;
2801         }
2802 
2803         // If this is a non-exported symbol then it doesn't match. Skip it.
2804         if (!SymI->second.getFlags().isExported() &&
2805             JDLookupFlags == JITDylibLookupFlags::MatchExportedSymbolsOnly) {
2806           LLVM_DEBUG(dbgs() << "skipping: not exported\n");
2807           return false;
2808         }
2809 
2810         LLVM_DEBUG({
2811           dbgs() << "matched, \"" << Name << "\" -> " << SymI->second.getFlags()
2812                  << "\n";
2813         });
2814         Result[Name] = SymI->second.getFlags();
2815         return true;
2816       });
2817     }
2818 
2819     // Remove any weakly referenced symbols that haven't been resolved.
2820     IPLS->LookupSet.remove_if(
2821         [](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2822           return SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol;
2823         });
2824 
2825     if (!IPLS->LookupSet.empty()) {
2826       LLVM_DEBUG(dbgs() << "Failing due to unresolved symbols\n");
2827       return make_error<SymbolsNotFound>(getSymbolStringPool(),
2828                                          IPLS->LookupSet.getSymbolNames());
2829     }
2830 
2831     LLVM_DEBUG(dbgs() << "Succeded, result = " << Result << "\n");
2832     return Result;
2833   });
2834 
2835   // Run the callback on the result.
2836   LLVM_DEBUG(dbgs() << "Sending result to handler.\n");
2837   OnComplete(std::move(Result));
2838 }
2839 
2840 void ExecutionSession::OL_destroyMaterializationResponsibility(
2841     MaterializationResponsibility &MR) {
2842 
2843   assert(MR.SymbolFlags.empty() &&
2844          "All symbols should have been explicitly materialized or failed");
2845   MR.JD.unlinkMaterializationResponsibility(MR);
2846 }
2847 
2848 SymbolNameSet ExecutionSession::OL_getRequestedSymbols(
2849     const MaterializationResponsibility &MR) {
2850   return MR.JD.getRequestedSymbols(MR.SymbolFlags);
2851 }
2852 
2853 Error ExecutionSession::OL_notifyResolved(MaterializationResponsibility &MR,
2854                                           const SymbolMap &Symbols) {
2855   LLVM_DEBUG({
2856     dbgs() << "In " << MR.JD.getName() << " resolving " << Symbols << "\n";
2857   });
2858 #ifndef NDEBUG
2859   for (auto &KV : Symbols) {
2860     auto WeakFlags = JITSymbolFlags::Weak | JITSymbolFlags::Common;
2861     auto I = MR.SymbolFlags.find(KV.first);
2862     assert(I != MR.SymbolFlags.end() &&
2863            "Resolving symbol outside this responsibility set");
2864     assert(!I->second.hasMaterializationSideEffectsOnly() &&
2865            "Can't resolve materialization-side-effects-only symbol");
2866     assert((KV.second.getFlags() & ~WeakFlags) == (I->second & ~WeakFlags) &&
2867            "Resolving symbol with incorrect flags");
2868   }
2869 #endif
2870 
2871   return MR.JD.resolve(MR, Symbols);
2872 }
2873 
2874 Error ExecutionSession::OL_notifyEmitted(MaterializationResponsibility &MR) {
2875   LLVM_DEBUG({
2876     dbgs() << "In " << MR.JD.getName() << " emitting " << MR.SymbolFlags
2877            << "\n";
2878   });
2879 
2880   if (auto Err = MR.JD.emit(MR, MR.SymbolFlags))
2881     return Err;
2882 
2883   MR.SymbolFlags.clear();
2884   return Error::success();
2885 }
2886 
2887 Error ExecutionSession::OL_defineMaterializing(
2888     MaterializationResponsibility &MR, SymbolFlagsMap NewSymbolFlags) {
2889 
2890   LLVM_DEBUG({
2891     dbgs() << "In " << MR.JD.getName() << " defining materializing symbols "
2892            << NewSymbolFlags << "\n";
2893   });
2894   if (auto AcceptedDefs =
2895           MR.JD.defineMaterializing(std::move(NewSymbolFlags))) {
2896     // Add all newly accepted symbols to this responsibility object.
2897     for (auto &KV : *AcceptedDefs)
2898       MR.SymbolFlags.insert(KV);
2899     return Error::success();
2900   } else
2901     return AcceptedDefs.takeError();
2902 }
2903 
2904 void ExecutionSession::OL_notifyFailed(MaterializationResponsibility &MR) {
2905 
2906   LLVM_DEBUG({
2907     dbgs() << "In " << MR.JD.getName() << " failing materialization for "
2908            << MR.SymbolFlags << "\n";
2909   });
2910 
2911   JITDylib::FailedSymbolsWorklist Worklist;
2912 
2913   for (auto &KV : MR.SymbolFlags)
2914     Worklist.push_back(std::make_pair(&MR.JD, KV.first));
2915   MR.SymbolFlags.clear();
2916 
2917   if (Worklist.empty())
2918     return;
2919 
2920   JITDylib::AsynchronousSymbolQuerySet FailedQueries;
2921   std::shared_ptr<SymbolDependenceMap> FailedSymbols;
2922 
2923   runSessionLocked([&]() {
2924     // If the tracker is defunct then there's nothing to do here.
2925     if (MR.RT->isDefunct())
2926       return;
2927 
2928     std::tie(FailedQueries, FailedSymbols) =
2929         JITDylib::failSymbols(std::move(Worklist));
2930   });
2931 
2932   for (auto &Q : FailedQueries)
2933     Q->handleFailed(make_error<FailedToMaterialize>(FailedSymbols));
2934 }
2935 
2936 Error ExecutionSession::OL_replace(MaterializationResponsibility &MR,
2937                                    std::unique_ptr<MaterializationUnit> MU) {
2938   for (auto &KV : MU->getSymbols()) {
2939     assert(MR.SymbolFlags.count(KV.first) &&
2940            "Replacing definition outside this responsibility set");
2941     MR.SymbolFlags.erase(KV.first);
2942   }
2943 
2944   if (MU->getInitializerSymbol() == MR.InitSymbol)
2945     MR.InitSymbol = nullptr;
2946 
2947   LLVM_DEBUG(MR.JD.getExecutionSession().runSessionLocked([&]() {
2948     dbgs() << "In " << MR.JD.getName() << " replacing symbols with " << *MU
2949            << "\n";
2950   }););
2951 
2952   return MR.JD.replace(MR, std::move(MU));
2953 }
2954 
2955 Expected<std::unique_ptr<MaterializationResponsibility>>
2956 ExecutionSession::OL_delegate(MaterializationResponsibility &MR,
2957                               const SymbolNameSet &Symbols) {
2958 
2959   SymbolStringPtr DelegatedInitSymbol;
2960   SymbolFlagsMap DelegatedFlags;
2961 
2962   for (auto &Name : Symbols) {
2963     auto I = MR.SymbolFlags.find(Name);
2964     assert(I != MR.SymbolFlags.end() &&
2965            "Symbol is not tracked by this MaterializationResponsibility "
2966            "instance");
2967 
2968     DelegatedFlags[Name] = std::move(I->second);
2969     if (Name == MR.InitSymbol)
2970       std::swap(MR.InitSymbol, DelegatedInitSymbol);
2971 
2972     MR.SymbolFlags.erase(I);
2973   }
2974 
2975   return MR.JD.delegate(MR, std::move(DelegatedFlags),
2976                         std::move(DelegatedInitSymbol));
2977 }
2978 
2979 void ExecutionSession::OL_addDependencies(
2980     MaterializationResponsibility &MR, const SymbolStringPtr &Name,
2981     const SymbolDependenceMap &Dependencies) {
2982   LLVM_DEBUG({
2983     dbgs() << "Adding dependencies for " << Name << ": " << Dependencies
2984            << "\n";
2985   });
2986   assert(MR.SymbolFlags.count(Name) &&
2987          "Symbol not covered by this MaterializationResponsibility instance");
2988   MR.JD.addDependencies(Name, Dependencies);
2989 }
2990 
2991 void ExecutionSession::OL_addDependenciesForAll(
2992     MaterializationResponsibility &MR,
2993     const SymbolDependenceMap &Dependencies) {
2994   LLVM_DEBUG({
2995     dbgs() << "Adding dependencies for all symbols in " << MR.SymbolFlags << ": "
2996            << Dependencies << "\n";
2997   });
2998   for (auto &KV : MR.SymbolFlags)
2999     MR.JD.addDependencies(KV.first, Dependencies);
3000 }
3001 
3002 #ifndef NDEBUG
3003 void ExecutionSession::dumpDispatchInfo(Task &T) {
3004   runSessionLocked([&]() {
3005     dbgs() << "Dispatching: ";
3006     T.printDescription(dbgs());
3007     dbgs() << "\n";
3008   });
3009 }
3010 #endif // NDEBUG
3011 
3012 } // End namespace orc.
3013 } // End namespace llvm.
3014