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