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