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/OrcError.h"
15 
16 #include <condition_variable>
17 #if LLVM_ENABLE_THREADS
18 #include <future>
19 #endif
20 
21 #define DEBUG_TYPE "orc"
22 
23 namespace llvm {
24 namespace orc {
25 
26 char FailedToMaterialize::ID = 0;
27 char SymbolsNotFound::ID = 0;
28 char SymbolsCouldNotBeRemoved::ID = 0;
29 char MissingSymbolDefinitions::ID = 0;
30 char UnexpectedSymbolDefinitions::ID = 0;
31 
32 RegisterDependenciesFunction NoDependenciesToRegister =
33     RegisterDependenciesFunction();
34 
35 void MaterializationUnit::anchor() {}
36 
37 FailedToMaterialize::FailedToMaterialize(
38     std::shared_ptr<SymbolDependenceMap> Symbols)
39     : Symbols(std::move(Symbols)) {
40   assert(!this->Symbols->empty() && "Can not fail to resolve an empty set");
41 }
42 
43 std::error_code FailedToMaterialize::convertToErrorCode() const {
44   return orcError(OrcErrorCode::UnknownORCError);
45 }
46 
47 void FailedToMaterialize::log(raw_ostream &OS) const {
48   OS << "Failed to materialize symbols: " << *Symbols;
49 }
50 
51 SymbolsNotFound::SymbolsNotFound(SymbolNameSet Symbols) {
52   for (auto &Sym : Symbols)
53     this->Symbols.push_back(Sym);
54   assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
55 }
56 
57 SymbolsNotFound::SymbolsNotFound(SymbolNameVector Symbols)
58     : Symbols(std::move(Symbols)) {
59   assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
60 }
61 
62 std::error_code SymbolsNotFound::convertToErrorCode() const {
63   return orcError(OrcErrorCode::UnknownORCError);
64 }
65 
66 void SymbolsNotFound::log(raw_ostream &OS) const {
67   OS << "Symbols not found: " << Symbols;
68 }
69 
70 SymbolsCouldNotBeRemoved::SymbolsCouldNotBeRemoved(SymbolNameSet Symbols)
71     : Symbols(std::move(Symbols)) {
72   assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
73 }
74 
75 std::error_code SymbolsCouldNotBeRemoved::convertToErrorCode() const {
76   return orcError(OrcErrorCode::UnknownORCError);
77 }
78 
79 void SymbolsCouldNotBeRemoved::log(raw_ostream &OS) const {
80   OS << "Symbols could not be removed: " << Symbols;
81 }
82 
83 std::error_code MissingSymbolDefinitions::convertToErrorCode() const {
84   return orcError(OrcErrorCode::MissingSymbolDefinitions);
85 }
86 
87 void MissingSymbolDefinitions::log(raw_ostream &OS) const {
88   OS << "Missing definitions in module " << ModuleName
89      << ": " << Symbols;
90 }
91 
92 std::error_code UnexpectedSymbolDefinitions::convertToErrorCode() const {
93   return orcError(OrcErrorCode::UnexpectedSymbolDefinitions);
94 }
95 
96 void UnexpectedSymbolDefinitions::log(raw_ostream &OS) const {
97   OS << "Unexpected definitions in module " << ModuleName
98      << ": " << Symbols;
99 }
100 
101 AsynchronousSymbolQuery::AsynchronousSymbolQuery(
102     const SymbolLookupSet &Symbols, SymbolState RequiredState,
103     SymbolsResolvedCallback NotifyComplete)
104     : NotifyComplete(std::move(NotifyComplete)), RequiredState(RequiredState) {
105   assert(RequiredState >= SymbolState::Resolved &&
106          "Cannot query for a symbols that have not reached the resolve state "
107          "yet");
108 
109   OutstandingSymbolsCount = Symbols.size();
110 
111   for (auto &KV : Symbols)
112     ResolvedSymbols[KV.first] = nullptr;
113 }
114 
115 void AsynchronousSymbolQuery::notifySymbolMetRequiredState(
116     const SymbolStringPtr &Name, JITEvaluatedSymbol Sym) {
117   auto I = ResolvedSymbols.find(Name);
118   assert(I != ResolvedSymbols.end() &&
119          "Resolving symbol outside the requested set");
120   assert(I->second.getAddress() == 0 && "Redundantly resolving symbol Name");
121 
122   // If this is a materialization-side-effects-only symbol then drop it,
123   // otherwise update its map entry with its resolved address.
124   if (Sym.getFlags().hasMaterializationSideEffectsOnly())
125     ResolvedSymbols.erase(I);
126   else
127     I->second = std::move(Sym);
128   --OutstandingSymbolsCount;
129 }
130 
131 void AsynchronousSymbolQuery::handleComplete() {
132   assert(OutstandingSymbolsCount == 0 &&
133          "Symbols remain, handleComplete called prematurely");
134 
135   auto TmpNotifyComplete = std::move(NotifyComplete);
136   NotifyComplete = SymbolsResolvedCallback();
137   TmpNotifyComplete(std::move(ResolvedSymbols));
138 }
139 
140 bool AsynchronousSymbolQuery::canStillFail() { return !!NotifyComplete; }
141 
142 void AsynchronousSymbolQuery::handleFailed(Error Err) {
143   assert(QueryRegistrations.empty() && ResolvedSymbols.empty() &&
144          OutstandingSymbolsCount == 0 &&
145          "Query should already have been abandoned");
146   NotifyComplete(std::move(Err));
147   NotifyComplete = SymbolsResolvedCallback();
148 }
149 
150 void AsynchronousSymbolQuery::addQueryDependence(JITDylib &JD,
151                                                  SymbolStringPtr Name) {
152   bool Added = QueryRegistrations[&JD].insert(std::move(Name)).second;
153   (void)Added;
154   assert(Added && "Duplicate dependence notification?");
155 }
156 
157 void AsynchronousSymbolQuery::removeQueryDependence(
158     JITDylib &JD, const SymbolStringPtr &Name) {
159   auto QRI = QueryRegistrations.find(&JD);
160   assert(QRI != QueryRegistrations.end() &&
161          "No dependencies registered for JD");
162   assert(QRI->second.count(Name) && "No dependency on Name in JD");
163   QRI->second.erase(Name);
164   if (QRI->second.empty())
165     QueryRegistrations.erase(QRI);
166 }
167 
168 void AsynchronousSymbolQuery::dropSymbol(const SymbolStringPtr &Name) {
169   auto I = ResolvedSymbols.find(Name);
170   assert(I != ResolvedSymbols.end() &&
171          "Redundant removal of weakly-referenced symbol");
172   ResolvedSymbols.erase(I);
173   --OutstandingSymbolsCount;
174 }
175 
176 void AsynchronousSymbolQuery::detach() {
177   ResolvedSymbols.clear();
178   OutstandingSymbolsCount = 0;
179   for (auto &KV : QueryRegistrations)
180     KV.first->detachQueryHelper(*this, KV.second);
181   QueryRegistrations.clear();
182 }
183 
184 MaterializationResponsibility::~MaterializationResponsibility() {
185   assert(SymbolFlags.empty() &&
186          "All symbols should have been explicitly materialized or failed");
187 }
188 
189 SymbolNameSet MaterializationResponsibility::getRequestedSymbols() const {
190   return JD->getRequestedSymbols(SymbolFlags);
191 }
192 
193 Error MaterializationResponsibility::notifyResolved(const SymbolMap &Symbols) {
194   LLVM_DEBUG({
195     dbgs() << "In " << JD->getName() << " resolving " << Symbols << "\n";
196   });
197 #ifndef NDEBUG
198   for (auto &KV : Symbols) {
199     auto WeakFlags = JITSymbolFlags::Weak | JITSymbolFlags::Common;
200     auto I = SymbolFlags.find(KV.first);
201     assert(I != SymbolFlags.end() &&
202            "Resolving symbol outside this responsibility set");
203     assert(!I->second.hasMaterializationSideEffectsOnly() &&
204            "Can't resolve materialization-side-effects-only symbol");
205     assert((KV.second.getFlags() & ~WeakFlags) == (I->second & ~WeakFlags) &&
206            "Resolving symbol with incorrect flags");
207   }
208 #endif
209 
210   return JD->resolve(Symbols);
211 }
212 
213 Error MaterializationResponsibility::notifyEmitted() {
214 
215   LLVM_DEBUG({
216     dbgs() << "In " << JD->getName() << " emitting " << SymbolFlags << "\n";
217   });
218 
219   if (auto Err = JD->emit(SymbolFlags))
220     return Err;
221 
222   SymbolFlags.clear();
223   return Error::success();
224 }
225 
226 Error MaterializationResponsibility::defineMaterializing(
227     SymbolFlagsMap NewSymbolFlags) {
228 
229   LLVM_DEBUG({
230     dbgs() << "In " << JD->getName() << " defining materializing symbols "
231            << NewSymbolFlags << "\n";
232   });
233   if (auto AcceptedDefs = JD->defineMaterializing(std::move(NewSymbolFlags))) {
234     // Add all newly accepted symbols to this responsibility object.
235     for (auto &KV : *AcceptedDefs)
236       SymbolFlags.insert(KV);
237     return Error::success();
238   } else
239     return AcceptedDefs.takeError();
240 }
241 
242 void MaterializationResponsibility::failMaterialization() {
243 
244   LLVM_DEBUG({
245     dbgs() << "In " << JD->getName() << " failing materialization for "
246            << SymbolFlags << "\n";
247   });
248 
249   JITDylib::FailedSymbolsWorklist Worklist;
250 
251   for (auto &KV : SymbolFlags)
252     Worklist.push_back(std::make_pair(JD.get(), KV.first));
253   SymbolFlags.clear();
254 
255   JD->notifyFailed(std::move(Worklist));
256 }
257 
258 void MaterializationResponsibility::replace(
259     std::unique_ptr<MaterializationUnit> MU) {
260 
261   // If the replacement MU is empty then return.
262   if (MU->getSymbols().empty())
263     return;
264 
265   for (auto &KV : MU->getSymbols()) {
266     assert(SymbolFlags.count(KV.first) &&
267            "Replacing definition outside this responsibility set");
268     SymbolFlags.erase(KV.first);
269   }
270 
271   if (MU->getInitializerSymbol() == InitSymbol)
272     InitSymbol = nullptr;
273 
274   LLVM_DEBUG(JD->getExecutionSession().runSessionLocked([&]() {
275     dbgs() << "In " << JD->getName() << " replacing symbols with " << *MU
276            << "\n";
277   }););
278 
279   JD->replace(std::move(MU));
280 }
281 
282 std::unique_ptr<MaterializationResponsibility>
283 MaterializationResponsibility::delegate(const SymbolNameSet &Symbols,
284                                         VModuleKey NewKey) {
285 
286   if (NewKey == VModuleKey())
287     NewKey = K;
288 
289   SymbolStringPtr DelegatedInitSymbol;
290   SymbolFlagsMap DelegatedFlags;
291 
292   for (auto &Name : Symbols) {
293     auto I = SymbolFlags.find(Name);
294     assert(I != SymbolFlags.end() &&
295            "Symbol is not tracked by this MaterializationResponsibility "
296            "instance");
297 
298     DelegatedFlags[Name] = std::move(I->second);
299     if (Name == InitSymbol)
300       std::swap(InitSymbol, DelegatedInitSymbol);
301 
302     SymbolFlags.erase(I);
303   }
304 
305   return std::unique_ptr<MaterializationResponsibility>(
306       new MaterializationResponsibility(JD, std::move(DelegatedFlags),
307                                         std::move(DelegatedInitSymbol),
308                                         std::move(NewKey)));
309 }
310 
311 void MaterializationResponsibility::addDependencies(
312     const SymbolStringPtr &Name, const SymbolDependenceMap &Dependencies) {
313   LLVM_DEBUG({
314     dbgs() << "Adding dependencies for " << Name << ": " << Dependencies
315            << "\n";
316   });
317   assert(SymbolFlags.count(Name) &&
318          "Symbol not covered by this MaterializationResponsibility instance");
319   JD->addDependencies(Name, Dependencies);
320 }
321 
322 void MaterializationResponsibility::addDependenciesForAll(
323     const SymbolDependenceMap &Dependencies) {
324   LLVM_DEBUG({
325     dbgs() << "Adding dependencies for all symbols in " << SymbolFlags << ": "
326            << Dependencies << "\n";
327   });
328   for (auto &KV : SymbolFlags)
329     JD->addDependencies(KV.first, Dependencies);
330 }
331 
332 AbsoluteSymbolsMaterializationUnit::AbsoluteSymbolsMaterializationUnit(
333     SymbolMap Symbols, VModuleKey K)
334     : MaterializationUnit(extractFlags(Symbols), nullptr, std::move(K)),
335       Symbols(std::move(Symbols)) {}
336 
337 StringRef AbsoluteSymbolsMaterializationUnit::getName() const {
338   return "<Absolute Symbols>";
339 }
340 
341 void AbsoluteSymbolsMaterializationUnit::materialize(
342     std::unique_ptr<MaterializationResponsibility> R) {
343   // No dependencies, so these calls can't fail.
344   cantFail(R->notifyResolved(Symbols));
345   cantFail(R->notifyEmitted());
346 }
347 
348 void AbsoluteSymbolsMaterializationUnit::discard(const JITDylib &JD,
349                                                  const SymbolStringPtr &Name) {
350   assert(Symbols.count(Name) && "Symbol is not part of this MU");
351   Symbols.erase(Name);
352 }
353 
354 SymbolFlagsMap
355 AbsoluteSymbolsMaterializationUnit::extractFlags(const SymbolMap &Symbols) {
356   SymbolFlagsMap Flags;
357   for (const auto &KV : Symbols)
358     Flags[KV.first] = KV.second.getFlags();
359   return Flags;
360 }
361 
362 ReExportsMaterializationUnit::ReExportsMaterializationUnit(
363     JITDylib *SourceJD, JITDylibLookupFlags SourceJDLookupFlags,
364     SymbolAliasMap Aliases, VModuleKey K)
365     : MaterializationUnit(extractFlags(Aliases), nullptr, std::move(K)),
366       SourceJD(SourceJD), SourceJDLookupFlags(SourceJDLookupFlags),
367       Aliases(std::move(Aliases)) {}
368 
369 StringRef ReExportsMaterializationUnit::getName() const {
370   return "<Reexports>";
371 }
372 
373 void ReExportsMaterializationUnit::materialize(
374     std::unique_ptr<MaterializationResponsibility> R) {
375 
376   auto &ES = R->getTargetJITDylib().getExecutionSession();
377   JITDylib &TgtJD = R->getTargetJITDylib();
378   JITDylib &SrcJD = SourceJD ? *SourceJD : TgtJD;
379 
380   // Find the set of requested aliases and aliasees. Return any unrequested
381   // aliases back to the JITDylib so as to not prematurely materialize any
382   // aliasees.
383   auto RequestedSymbols = R->getRequestedSymbols();
384   SymbolAliasMap RequestedAliases;
385 
386   for (auto &Name : RequestedSymbols) {
387     auto I = Aliases.find(Name);
388     assert(I != Aliases.end() && "Symbol not found in aliases map?");
389     RequestedAliases[Name] = std::move(I->second);
390     Aliases.erase(I);
391   }
392 
393   LLVM_DEBUG({
394     ES.runSessionLocked([&]() {
395       dbgs() << "materializing reexports: target = " << TgtJD.getName()
396              << ", source = " << SrcJD.getName() << " " << RequestedAliases
397              << "\n";
398     });
399   });
400 
401   if (!Aliases.empty()) {
402     if (SourceJD)
403       R->replace(reexports(*SourceJD, std::move(Aliases), SourceJDLookupFlags));
404     else
405       R->replace(symbolAliases(std::move(Aliases)));
406   }
407 
408   // The OnResolveInfo struct will hold the aliases and responsibilty for each
409   // query in the list.
410   struct OnResolveInfo {
411     OnResolveInfo(std::unique_ptr<MaterializationResponsibility> R,
412                   SymbolAliasMap Aliases)
413         : R(std::move(R)), Aliases(std::move(Aliases)) {}
414 
415     std::unique_ptr<MaterializationResponsibility> R;
416     SymbolAliasMap Aliases;
417   };
418 
419   // Build a list of queries to issue. In each round we build a query for the
420   // largest set of aliases that we can resolve without encountering a chain of
421   // aliases (e.g. Foo -> Bar, Bar -> Baz). Such a chain would deadlock as the
422   // query would be waiting on a symbol that it itself had to resolve. Creating
423   // a new query for each link in such a chain eliminates the possibility of
424   // deadlock. In practice chains are likely to be rare, and this algorithm will
425   // usually result in a single query to issue.
426 
427   std::vector<std::pair<SymbolLookupSet, std::shared_ptr<OnResolveInfo>>>
428       QueryInfos;
429   while (!RequestedAliases.empty()) {
430     SymbolNameSet ResponsibilitySymbols;
431     SymbolLookupSet QuerySymbols;
432     SymbolAliasMap QueryAliases;
433 
434     // Collect as many aliases as we can without including a chain.
435     for (auto &KV : RequestedAliases) {
436       // Chain detected. Skip this symbol for this round.
437       if (&SrcJD == &TgtJD && (QueryAliases.count(KV.second.Aliasee) ||
438                                RequestedAliases.count(KV.second.Aliasee)))
439         continue;
440 
441       ResponsibilitySymbols.insert(KV.first);
442       QuerySymbols.add(KV.second.Aliasee,
443                        KV.second.AliasFlags.hasMaterializationSideEffectsOnly()
444                            ? SymbolLookupFlags::WeaklyReferencedSymbol
445                            : SymbolLookupFlags::RequiredSymbol);
446       QueryAliases[KV.first] = std::move(KV.second);
447     }
448 
449     // Remove the aliases collected this round from the RequestedAliases map.
450     for (auto &KV : QueryAliases)
451       RequestedAliases.erase(KV.first);
452 
453     assert(!QuerySymbols.empty() && "Alias cycle detected!");
454 
455     auto QueryInfo = std::make_shared<OnResolveInfo>(
456         R->delegate(ResponsibilitySymbols), std::move(QueryAliases));
457     QueryInfos.push_back(
458         make_pair(std::move(QuerySymbols), std::move(QueryInfo)));
459   }
460 
461   // Issue the queries.
462   while (!QueryInfos.empty()) {
463     auto QuerySymbols = std::move(QueryInfos.back().first);
464     auto QueryInfo = std::move(QueryInfos.back().second);
465 
466     QueryInfos.pop_back();
467 
468     auto RegisterDependencies = [QueryInfo,
469                                  &SrcJD](const SymbolDependenceMap &Deps) {
470       // If there were no materializing symbols, just bail out.
471       if (Deps.empty())
472         return;
473 
474       // Otherwise the only deps should be on SrcJD.
475       assert(Deps.size() == 1 && Deps.count(&SrcJD) &&
476              "Unexpected dependencies for reexports");
477 
478       auto &SrcJDDeps = Deps.find(&SrcJD)->second;
479       SymbolDependenceMap PerAliasDepsMap;
480       auto &PerAliasDeps = PerAliasDepsMap[&SrcJD];
481 
482       for (auto &KV : QueryInfo->Aliases)
483         if (SrcJDDeps.count(KV.second.Aliasee)) {
484           PerAliasDeps = {KV.second.Aliasee};
485           QueryInfo->R->addDependencies(KV.first, PerAliasDepsMap);
486         }
487     };
488 
489     auto OnComplete = [QueryInfo](Expected<SymbolMap> Result) {
490       auto &ES = QueryInfo->R->getTargetJITDylib().getExecutionSession();
491       if (Result) {
492         SymbolMap ResolutionMap;
493         for (auto &KV : QueryInfo->Aliases) {
494           assert((KV.second.AliasFlags.hasMaterializationSideEffectsOnly() ||
495                   Result->count(KV.second.Aliasee)) &&
496                  "Result map missing entry?");
497           // Don't try to resolve materialization-side-effects-only symbols.
498           if (KV.second.AliasFlags.hasMaterializationSideEffectsOnly())
499             continue;
500 
501           ResolutionMap[KV.first] = JITEvaluatedSymbol(
502               (*Result)[KV.second.Aliasee].getAddress(), KV.second.AliasFlags);
503         }
504         if (auto Err = QueryInfo->R->notifyResolved(ResolutionMap)) {
505           ES.reportError(std::move(Err));
506           QueryInfo->R->failMaterialization();
507           return;
508         }
509         if (auto Err = QueryInfo->R->notifyEmitted()) {
510           ES.reportError(std::move(Err));
511           QueryInfo->R->failMaterialization();
512           return;
513         }
514       } else {
515         ES.reportError(Result.takeError());
516         QueryInfo->R->failMaterialization();
517       }
518     };
519 
520     ES.lookup(LookupKind::Static,
521               JITDylibSearchOrder({{&SrcJD, SourceJDLookupFlags}}),
522               QuerySymbols, SymbolState::Resolved, std::move(OnComplete),
523               std::move(RegisterDependencies));
524   }
525 }
526 
527 void ReExportsMaterializationUnit::discard(const JITDylib &JD,
528                                            const SymbolStringPtr &Name) {
529   assert(Aliases.count(Name) &&
530          "Symbol not covered by this MaterializationUnit");
531   Aliases.erase(Name);
532 }
533 
534 SymbolFlagsMap
535 ReExportsMaterializationUnit::extractFlags(const SymbolAliasMap &Aliases) {
536   SymbolFlagsMap SymbolFlags;
537   for (auto &KV : Aliases)
538     SymbolFlags[KV.first] = KV.second.AliasFlags;
539 
540   return SymbolFlags;
541 }
542 
543 Expected<SymbolAliasMap>
544 buildSimpleReexportsAliasMap(JITDylib &SourceJD, const SymbolNameSet &Symbols) {
545   SymbolLookupSet LookupSet(Symbols);
546   auto Flags = SourceJD.lookupFlags(
547       LookupKind::Static, JITDylibLookupFlags::MatchAllSymbols, LookupSet);
548 
549   if (!Flags)
550     return Flags.takeError();
551 
552   if (!LookupSet.empty()) {
553     LookupSet.sortByName();
554     return make_error<SymbolsNotFound>(LookupSet.getSymbolNames());
555   }
556 
557   SymbolAliasMap Result;
558   for (auto &Name : Symbols) {
559     assert(Flags->count(Name) && "Missing entry in flags map");
560     Result[Name] = SymbolAliasMapEntry(Name, (*Flags)[Name]);
561   }
562 
563   return Result;
564 }
565 
566 ReexportsGenerator::ReexportsGenerator(JITDylib &SourceJD,
567                                        JITDylibLookupFlags SourceJDLookupFlags,
568                                        SymbolPredicate Allow)
569     : SourceJD(SourceJD), SourceJDLookupFlags(SourceJDLookupFlags),
570       Allow(std::move(Allow)) {}
571 
572 Error ReexportsGenerator::tryToGenerate(LookupKind K, JITDylib &JD,
573                                         JITDylibLookupFlags JDLookupFlags,
574                                         const SymbolLookupSet &LookupSet) {
575   assert(&JD != &SourceJD && "Cannot re-export from the same dylib");
576 
577   // Use lookupFlags to find the subset of symbols that match our lookup.
578   auto Flags = SourceJD.lookupFlags(K, JDLookupFlags, LookupSet);
579   if (!Flags)
580     return Flags.takeError();
581 
582   // Create an alias map.
583   orc::SymbolAliasMap AliasMap;
584   for (auto &KV : *Flags)
585     if (!Allow || Allow(KV.first))
586       AliasMap[KV.first] = SymbolAliasMapEntry(KV.first, KV.second);
587 
588   if (AliasMap.empty())
589     return Error::success();
590 
591   // Define the re-exports.
592   return JD.define(reexports(SourceJD, AliasMap, SourceJDLookupFlags));
593 }
594 
595 JITDylib::DefinitionGenerator::~DefinitionGenerator() {}
596 
597 void JITDylib::removeGenerator(DefinitionGenerator &G) {
598   ES.runSessionLocked([&]() {
599     auto I = std::find_if(DefGenerators.begin(), DefGenerators.end(),
600                           [&](const std::unique_ptr<DefinitionGenerator> &H) {
601                             return H.get() == &G;
602                           });
603     assert(I != DefGenerators.end() && "Generator not found");
604     DefGenerators.erase(I);
605   });
606 }
607 
608 Expected<SymbolFlagsMap>
609 JITDylib::defineMaterializing(SymbolFlagsMap SymbolFlags) {
610 
611   return ES.runSessionLocked([&]() -> Expected<SymbolFlagsMap> {
612     std::vector<SymbolTable::iterator> AddedSyms;
613     std::vector<SymbolFlagsMap::iterator> RejectedWeakDefs;
614 
615     for (auto SFItr = SymbolFlags.begin(), SFEnd = SymbolFlags.end();
616          SFItr != SFEnd; ++SFItr) {
617 
618       auto &Name = SFItr->first;
619       auto &Flags = SFItr->second;
620 
621       auto EntryItr = Symbols.find(Name);
622 
623       // If the entry already exists...
624       if (EntryItr != Symbols.end()) {
625 
626         // If this is a strong definition then error out.
627         if (!Flags.isWeak()) {
628           // Remove any symbols already added.
629           for (auto &SI : AddedSyms)
630             Symbols.erase(SI);
631 
632           // FIXME: Return all duplicates.
633           return make_error<DuplicateDefinition>(std::string(*Name));
634         }
635 
636         // Otherwise just make a note to discard this symbol after the loop.
637         RejectedWeakDefs.push_back(SFItr);
638         continue;
639       } else
640         EntryItr =
641           Symbols.insert(std::make_pair(Name, SymbolTableEntry(Flags))).first;
642 
643       AddedSyms.push_back(EntryItr);
644       EntryItr->second.setState(SymbolState::Materializing);
645     }
646 
647     // Remove any rejected weak definitions from the SymbolFlags map.
648     while (!RejectedWeakDefs.empty()) {
649       SymbolFlags.erase(RejectedWeakDefs.back());
650       RejectedWeakDefs.pop_back();
651     }
652 
653     return SymbolFlags;
654   });
655 }
656 
657 void JITDylib::replace(std::unique_ptr<MaterializationUnit> MU) {
658   assert(MU != nullptr && "Can not replace with a null MaterializationUnit");
659 
660   auto MustRunMU =
661       ES.runSessionLocked([&, this]() -> std::unique_ptr<MaterializationUnit> {
662 
663 #ifndef NDEBUG
664         for (auto &KV : MU->getSymbols()) {
665           auto SymI = Symbols.find(KV.first);
666           assert(SymI != Symbols.end() && "Replacing unknown symbol");
667           assert(SymI->second.getState() == SymbolState::Materializing &&
668                  "Can not replace a symbol that ha is not materializing");
669           assert(!SymI->second.hasMaterializerAttached() &&
670                  "Symbol should not have materializer attached already");
671           assert(UnmaterializedInfos.count(KV.first) == 0 &&
672                  "Symbol being replaced should have no UnmaterializedInfo");
673         }
674 #endif // NDEBUG
675 
676         // If any symbol has pending queries against it then we need to
677         // materialize MU immediately.
678         for (auto &KV : MU->getSymbols()) {
679           auto MII = MaterializingInfos.find(KV.first);
680           if (MII != MaterializingInfos.end()) {
681             if (MII->second.hasQueriesPending())
682               return std::move(MU);
683           }
684         }
685 
686         // Otherwise, make MU responsible for all the symbols.
687         auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU));
688         for (auto &KV : UMI->MU->getSymbols()) {
689           auto SymI = Symbols.find(KV.first);
690           assert(SymI->second.getState() == SymbolState::Materializing &&
691                  "Can not replace a symbol that is not materializing");
692           assert(!SymI->second.hasMaterializerAttached() &&
693                  "Can not replace a symbol that has a materializer attached");
694           assert(UnmaterializedInfos.count(KV.first) == 0 &&
695                  "Unexpected materializer entry in map");
696           SymI->second.setAddress(SymI->second.getAddress());
697           SymI->second.setMaterializerAttached(true);
698 
699           auto &UMIEntry = UnmaterializedInfos[KV.first];
700           assert((!UMIEntry || !UMIEntry->MU) &&
701                  "Replacing symbol with materializer still attached");
702           UMIEntry = UMI;
703         }
704 
705         return nullptr;
706       });
707 
708   if (MustRunMU) {
709     auto MR =
710         MustRunMU->createMaterializationResponsibility(shared_from_this());
711     ES.dispatchMaterialization(std::move(MustRunMU), std::move(MR));
712   }
713 }
714 
715 SymbolNameSet
716 JITDylib::getRequestedSymbols(const SymbolFlagsMap &SymbolFlags) const {
717   return ES.runSessionLocked([&]() {
718     SymbolNameSet RequestedSymbols;
719 
720     for (auto &KV : SymbolFlags) {
721       assert(Symbols.count(KV.first) && "JITDylib does not cover this symbol?");
722       assert(Symbols.find(KV.first)->second.getState() !=
723                  SymbolState::NeverSearched &&
724              Symbols.find(KV.first)->second.getState() != SymbolState::Ready &&
725              "getRequestedSymbols can only be called for symbols that have "
726              "started materializing");
727       auto I = MaterializingInfos.find(KV.first);
728       if (I == MaterializingInfos.end())
729         continue;
730 
731       if (I->second.hasQueriesPending())
732         RequestedSymbols.insert(KV.first);
733     }
734 
735     return RequestedSymbols;
736   });
737 }
738 
739 void JITDylib::addDependencies(const SymbolStringPtr &Name,
740                                const SymbolDependenceMap &Dependencies) {
741   assert(Symbols.count(Name) && "Name not in symbol table");
742   assert(Symbols[Name].getState() < SymbolState::Emitted &&
743          "Can not add dependencies for a symbol that is not materializing");
744 
745   LLVM_DEBUG({
746       dbgs() << "In " << getName() << " adding dependencies for "
747              << *Name << ": " << Dependencies << "\n";
748     });
749 
750   // If Name is already in an error state then just bail out.
751   if (Symbols[Name].getFlags().hasError())
752     return;
753 
754   auto &MI = MaterializingInfos[Name];
755   assert(Symbols[Name].getState() != SymbolState::Emitted &&
756          "Can not add dependencies to an emitted symbol");
757 
758   bool DependsOnSymbolInErrorState = false;
759 
760   // Register dependencies, record whether any depenendency is in the error
761   // state.
762   for (auto &KV : Dependencies) {
763     assert(KV.first && "Null JITDylib in dependency?");
764     auto &OtherJITDylib = *KV.first;
765     auto &DepsOnOtherJITDylib = MI.UnemittedDependencies[&OtherJITDylib];
766 
767     for (auto &OtherSymbol : KV.second) {
768 
769       // Check the sym entry for the dependency.
770       auto OtherSymI = OtherJITDylib.Symbols.find(OtherSymbol);
771 
772       // Assert that this symbol exists and has not reached the ready state
773       // already.
774       assert(OtherSymI != OtherJITDylib.Symbols.end() &&
775              "Dependency on unknown symbol");
776 
777       auto &OtherSymEntry = OtherSymI->second;
778 
779       // If the other symbol is already in the Ready state then there's no
780       // dependency to add.
781       if (OtherSymEntry.getState() == SymbolState::Ready)
782         continue;
783 
784       // If the dependency is in an error state then note this and continue,
785       // we will move this symbol to the error state below.
786       if (OtherSymEntry.getFlags().hasError()) {
787         DependsOnSymbolInErrorState = true;
788         continue;
789       }
790 
791       // If the dependency was not in the error state then add it to
792       // our list of dependencies.
793       auto &OtherMI = OtherJITDylib.MaterializingInfos[OtherSymbol];
794 
795       if (OtherSymEntry.getState() == SymbolState::Emitted)
796         transferEmittedNodeDependencies(MI, Name, OtherMI);
797       else if (&OtherJITDylib != this || OtherSymbol != Name) {
798         OtherMI.Dependants[this].insert(Name);
799         DepsOnOtherJITDylib.insert(OtherSymbol);
800       }
801     }
802 
803     if (DepsOnOtherJITDylib.empty())
804       MI.UnemittedDependencies.erase(&OtherJITDylib);
805   }
806 
807   // If this symbol dependended on any symbols in the error state then move
808   // this symbol to the error state too.
809   if (DependsOnSymbolInErrorState)
810     Symbols[Name].setFlags(Symbols[Name].getFlags() | JITSymbolFlags::HasError);
811 }
812 
813 Error JITDylib::resolve(const SymbolMap &Resolved) {
814   SymbolNameSet SymbolsInErrorState;
815   AsynchronousSymbolQuerySet CompletedQueries;
816 
817   ES.runSessionLocked([&, this]() {
818     struct WorklistEntry {
819       SymbolTable::iterator SymI;
820       JITEvaluatedSymbol ResolvedSym;
821     };
822 
823     std::vector<WorklistEntry> Worklist;
824     Worklist.reserve(Resolved.size());
825 
826     // Build worklist and check for any symbols in the error state.
827     for (const auto &KV : Resolved) {
828 
829       assert(!KV.second.getFlags().hasError() &&
830              "Resolution result can not have error flag set");
831 
832       auto SymI = Symbols.find(KV.first);
833 
834       assert(SymI != Symbols.end() && "Symbol not found");
835       assert(!SymI->second.hasMaterializerAttached() &&
836              "Resolving symbol with materializer attached?");
837       assert(SymI->second.getState() == SymbolState::Materializing &&
838              "Symbol should be materializing");
839       assert(SymI->second.getAddress() == 0 &&
840              "Symbol has already been resolved");
841 
842       if (SymI->second.getFlags().hasError())
843         SymbolsInErrorState.insert(KV.first);
844       else {
845         auto Flags = KV.second.getFlags();
846         Flags &= ~(JITSymbolFlags::Weak | JITSymbolFlags::Common);
847         assert(Flags == (SymI->second.getFlags() &
848                          ~(JITSymbolFlags::Weak | JITSymbolFlags::Common)) &&
849                "Resolved flags should match the declared flags");
850 
851         Worklist.push_back(
852             {SymI, JITEvaluatedSymbol(KV.second.getAddress(), Flags)});
853       }
854     }
855 
856     // If any symbols were in the error state then bail out.
857     if (!SymbolsInErrorState.empty())
858       return;
859 
860     while (!Worklist.empty()) {
861       auto SymI = Worklist.back().SymI;
862       auto ResolvedSym = Worklist.back().ResolvedSym;
863       Worklist.pop_back();
864 
865       auto &Name = SymI->first;
866 
867       // Resolved symbols can not be weak: discard the weak flag.
868       JITSymbolFlags ResolvedFlags = ResolvedSym.getFlags();
869       SymI->second.setAddress(ResolvedSym.getAddress());
870       SymI->second.setFlags(ResolvedFlags);
871       SymI->second.setState(SymbolState::Resolved);
872 
873       auto MII = MaterializingInfos.find(Name);
874       if (MII == MaterializingInfos.end())
875         continue;
876 
877       auto &MI = MII->second;
878       for (auto &Q : MI.takeQueriesMeeting(SymbolState::Resolved)) {
879         Q->notifySymbolMetRequiredState(Name, ResolvedSym);
880         Q->removeQueryDependence(*this, Name);
881         if (Q->isComplete())
882           CompletedQueries.insert(std::move(Q));
883       }
884     }
885   });
886 
887   assert((SymbolsInErrorState.empty() || CompletedQueries.empty()) &&
888          "Can't fail symbols and completed queries at the same time");
889 
890   // If we failed any symbols then return an error.
891   if (!SymbolsInErrorState.empty()) {
892     auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
893     (*FailedSymbolsDepMap)[this] = std::move(SymbolsInErrorState);
894     return make_error<FailedToMaterialize>(std::move(FailedSymbolsDepMap));
895   }
896 
897   // Otherwise notify all the completed queries.
898   for (auto &Q : CompletedQueries) {
899     assert(Q->isComplete() && "Q not completed");
900     Q->handleComplete();
901   }
902 
903   return Error::success();
904 }
905 
906 Error JITDylib::emit(const SymbolFlagsMap &Emitted) {
907   AsynchronousSymbolQuerySet CompletedQueries;
908   SymbolNameSet SymbolsInErrorState;
909   DenseMap<JITDylib *, SymbolNameVector> ReadySymbols;
910 
911   ES.runSessionLocked([&, this]() {
912     std::vector<SymbolTable::iterator> Worklist;
913 
914     // Scan to build worklist, record any symbols in the erorr state.
915     for (const auto &KV : Emitted) {
916       auto &Name = KV.first;
917 
918       auto SymI = Symbols.find(Name);
919       assert(SymI != Symbols.end() && "No symbol table entry for Name");
920 
921       if (SymI->second.getFlags().hasError())
922         SymbolsInErrorState.insert(Name);
923       else
924         Worklist.push_back(SymI);
925     }
926 
927     // If any symbols were in the error state then bail out.
928     if (!SymbolsInErrorState.empty())
929       return;
930 
931     // Otherwise update dependencies and move to the emitted state.
932     while (!Worklist.empty()) {
933       auto SymI = Worklist.back();
934       Worklist.pop_back();
935 
936       auto &Name = SymI->first;
937       auto &SymEntry = SymI->second;
938 
939       // Move symbol to the emitted state.
940       assert(((SymEntry.getFlags().hasMaterializationSideEffectsOnly() &&
941                SymEntry.getState() == SymbolState::Materializing) ||
942               SymEntry.getState() == SymbolState::Resolved) &&
943              "Emitting from state other than Resolved");
944       SymEntry.setState(SymbolState::Emitted);
945 
946       auto MII = MaterializingInfos.find(Name);
947 
948       // If this symbol has no MaterializingInfo then it's trivially ready.
949       // Update its state and continue.
950       if (MII == MaterializingInfos.end()) {
951         SymEntry.setState(SymbolState::Ready);
952         continue;
953       }
954 
955       auto &MI = MII->second;
956 
957       // For each dependant, transfer this node's emitted dependencies to
958       // it. If the dependant node is ready (i.e. has no unemitted
959       // dependencies) then notify any pending queries.
960       for (auto &KV : MI.Dependants) {
961         auto &DependantJD = *KV.first;
962         auto &DependantJDReadySymbols = ReadySymbols[&DependantJD];
963         for (auto &DependantName : KV.second) {
964           auto DependantMII =
965               DependantJD.MaterializingInfos.find(DependantName);
966           assert(DependantMII != DependantJD.MaterializingInfos.end() &&
967                  "Dependant should have MaterializingInfo");
968 
969           auto &DependantMI = DependantMII->second;
970 
971           // Remove the dependant's dependency on this node.
972           assert(DependantMI.UnemittedDependencies.count(this) &&
973                  "Dependant does not have an unemitted dependencies record for "
974                  "this JITDylib");
975           assert(DependantMI.UnemittedDependencies[this].count(Name) &&
976                  "Dependant does not count this symbol as a dependency?");
977 
978           DependantMI.UnemittedDependencies[this].erase(Name);
979           if (DependantMI.UnemittedDependencies[this].empty())
980             DependantMI.UnemittedDependencies.erase(this);
981 
982           // Transfer unemitted dependencies from this node to the dependant.
983           DependantJD.transferEmittedNodeDependencies(DependantMI,
984                                                       DependantName, MI);
985 
986           auto DependantSymI = DependantJD.Symbols.find(DependantName);
987           assert(DependantSymI != DependantJD.Symbols.end() &&
988                  "Dependant has no entry in the Symbols table");
989           auto &DependantSymEntry = DependantSymI->second;
990 
991           // If the dependant is emitted and this node was the last of its
992           // unemitted dependencies then the dependant node is now ready, so
993           // notify any pending queries on the dependant node.
994           if (DependantSymEntry.getState() == SymbolState::Emitted &&
995               DependantMI.UnemittedDependencies.empty()) {
996             assert(DependantMI.Dependants.empty() &&
997                    "Dependants should be empty by now");
998 
999             // Since this dependant is now ready, we erase its MaterializingInfo
1000             // and update its materializing state.
1001             DependantSymEntry.setState(SymbolState::Ready);
1002             DependantJDReadySymbols.push_back(DependantName);
1003 
1004             for (auto &Q : DependantMI.takeQueriesMeeting(SymbolState::Ready)) {
1005               Q->notifySymbolMetRequiredState(
1006                   DependantName, DependantSymI->second.getSymbol());
1007               if (Q->isComplete())
1008                 CompletedQueries.insert(Q);
1009               Q->removeQueryDependence(DependantJD, DependantName);
1010             }
1011           }
1012         }
1013       }
1014 
1015       auto &ThisJDReadySymbols = ReadySymbols[this];
1016       MI.Dependants.clear();
1017       if (MI.UnemittedDependencies.empty()) {
1018         SymI->second.setState(SymbolState::Ready);
1019         ThisJDReadySymbols.push_back(Name);
1020         for (auto &Q : MI.takeQueriesMeeting(SymbolState::Ready)) {
1021           Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
1022           if (Q->isComplete())
1023             CompletedQueries.insert(Q);
1024           Q->removeQueryDependence(*this, Name);
1025         }
1026       }
1027     }
1028   });
1029 
1030   assert((SymbolsInErrorState.empty() || CompletedQueries.empty()) &&
1031          "Can't fail symbols and completed queries at the same time");
1032 
1033   // If we failed any symbols then return an error.
1034   if (!SymbolsInErrorState.empty()) {
1035     auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
1036     (*FailedSymbolsDepMap)[this] = std::move(SymbolsInErrorState);
1037     return make_error<FailedToMaterialize>(std::move(FailedSymbolsDepMap));
1038   }
1039 
1040   // Otherwise notify all the completed queries.
1041   for (auto &Q : CompletedQueries) {
1042     assert(Q->isComplete() && "Q is not complete");
1043     Q->handleComplete();
1044   }
1045 
1046   return Error::success();
1047 }
1048 
1049 void JITDylib::notifyFailed(FailedSymbolsWorklist Worklist) {
1050   AsynchronousSymbolQuerySet FailedQueries;
1051   auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
1052 
1053   // Failing no symbols is a no-op.
1054   if (Worklist.empty())
1055     return;
1056 
1057   auto &ES = Worklist.front().first->getExecutionSession();
1058 
1059   ES.runSessionLocked([&]() {
1060     while (!Worklist.empty()) {
1061       assert(Worklist.back().first && "Failed JITDylib can not be null");
1062       auto &JD = *Worklist.back().first;
1063       auto Name = std::move(Worklist.back().second);
1064       Worklist.pop_back();
1065 
1066       (*FailedSymbolsMap)[&JD].insert(Name);
1067 
1068       assert(JD.Symbols.count(Name) && "No symbol table entry for Name");
1069       auto &Sym = JD.Symbols[Name];
1070 
1071       // Move the symbol into the error state.
1072       // Note that this may be redundant: The symbol might already have been
1073       // moved to this state in response to the failure of a dependence.
1074       Sym.setFlags(Sym.getFlags() | JITSymbolFlags::HasError);
1075 
1076       // FIXME: Come up with a sane mapping of state to
1077       // presence-of-MaterializingInfo so that we can assert presence / absence
1078       // here, rather than testing it.
1079       auto MII = JD.MaterializingInfos.find(Name);
1080 
1081       if (MII == JD.MaterializingInfos.end())
1082         continue;
1083 
1084       auto &MI = MII->second;
1085 
1086       // Move all dependants to the error state and disconnect from them.
1087       for (auto &KV : MI.Dependants) {
1088         auto &DependantJD = *KV.first;
1089         for (auto &DependantName : KV.second) {
1090           assert(DependantJD.Symbols.count(DependantName) &&
1091                  "No symbol table entry for DependantName");
1092           auto &DependantSym = DependantJD.Symbols[DependantName];
1093           DependantSym.setFlags(DependantSym.getFlags() |
1094                                 JITSymbolFlags::HasError);
1095 
1096           assert(DependantJD.MaterializingInfos.count(DependantName) &&
1097                  "No MaterializingInfo for dependant");
1098           auto &DependantMI = DependantJD.MaterializingInfos[DependantName];
1099 
1100           auto UnemittedDepI = DependantMI.UnemittedDependencies.find(&JD);
1101           assert(UnemittedDepI != DependantMI.UnemittedDependencies.end() &&
1102                  "No UnemittedDependencies entry for this JITDylib");
1103           assert(UnemittedDepI->second.count(Name) &&
1104                  "No UnemittedDependencies entry for this symbol");
1105           UnemittedDepI->second.erase(Name);
1106           if (UnemittedDepI->second.empty())
1107             DependantMI.UnemittedDependencies.erase(UnemittedDepI);
1108 
1109           // If this symbol is already in the emitted state then we need to
1110           // take responsibility for failing its queries, so add it to the
1111           // worklist.
1112           if (DependantSym.getState() == SymbolState::Emitted) {
1113             assert(DependantMI.Dependants.empty() &&
1114                    "Emitted symbol should not have dependants");
1115             Worklist.push_back(std::make_pair(&DependantJD, DependantName));
1116           }
1117         }
1118       }
1119       MI.Dependants.clear();
1120 
1121       // Disconnect from all unemitted depenencies.
1122       for (auto &KV : MI.UnemittedDependencies) {
1123         auto &UnemittedDepJD = *KV.first;
1124         for (auto &UnemittedDepName : KV.second) {
1125           auto UnemittedDepMII =
1126               UnemittedDepJD.MaterializingInfos.find(UnemittedDepName);
1127           assert(UnemittedDepMII != UnemittedDepJD.MaterializingInfos.end() &&
1128                  "Missing MII for unemitted dependency");
1129           assert(UnemittedDepMII->second.Dependants.count(&JD) &&
1130                  "JD not listed as a dependant of unemitted dependency");
1131           assert(UnemittedDepMII->second.Dependants[&JD].count(Name) &&
1132                  "Name is not listed as a dependant of unemitted dependency");
1133           UnemittedDepMII->second.Dependants[&JD].erase(Name);
1134           if (UnemittedDepMII->second.Dependants[&JD].empty())
1135             UnemittedDepMII->second.Dependants.erase(&JD);
1136         }
1137       }
1138       MI.UnemittedDependencies.clear();
1139 
1140       // Collect queries to be failed for this MII.
1141       AsynchronousSymbolQueryList ToDetach;
1142       for (auto &Q : MII->second.pendingQueries()) {
1143         // Add the query to the list to be failed and detach it.
1144         FailedQueries.insert(Q);
1145         ToDetach.push_back(Q);
1146       }
1147       for (auto &Q : ToDetach)
1148         Q->detach();
1149 
1150       assert(MI.Dependants.empty() &&
1151              "Can not delete MaterializingInfo with dependants still attached");
1152       assert(MI.UnemittedDependencies.empty() &&
1153              "Can not delete MaterializingInfo with unemitted dependencies "
1154              "still attached");
1155       assert(!MI.hasQueriesPending() &&
1156              "Can not delete MaterializingInfo with queries pending");
1157       JD.MaterializingInfos.erase(MII);
1158     }
1159   });
1160 
1161   for (auto &Q : FailedQueries)
1162     Q->handleFailed(make_error<FailedToMaterialize>(FailedSymbolsMap));
1163 }
1164 
1165 void JITDylib::setLinkOrder(JITDylibSearchOrder NewLinkOrder,
1166                             bool LinkAgainstThisJITDylibFirst) {
1167   ES.runSessionLocked([&]() {
1168     if (LinkAgainstThisJITDylibFirst) {
1169       LinkOrder.clear();
1170       if (NewLinkOrder.empty() || NewLinkOrder.front().first != this)
1171         LinkOrder.push_back(
1172             std::make_pair(this, JITDylibLookupFlags::MatchAllSymbols));
1173       LinkOrder.insert(LinkOrder.end(), NewLinkOrder.begin(),
1174                        NewLinkOrder.end());
1175     } else
1176       LinkOrder = std::move(NewLinkOrder);
1177   });
1178 }
1179 
1180 void JITDylib::addToLinkOrder(JITDylib &JD, JITDylibLookupFlags JDLookupFlags) {
1181   ES.runSessionLocked([&]() { LinkOrder.push_back({&JD, JDLookupFlags}); });
1182 }
1183 
1184 void JITDylib::replaceInLinkOrder(JITDylib &OldJD, JITDylib &NewJD,
1185                                   JITDylibLookupFlags JDLookupFlags) {
1186   ES.runSessionLocked([&]() {
1187     for (auto &KV : LinkOrder)
1188       if (KV.first == &OldJD) {
1189         KV = {&NewJD, JDLookupFlags};
1190         break;
1191       }
1192   });
1193 }
1194 
1195 void JITDylib::removeFromLinkOrder(JITDylib &JD) {
1196   ES.runSessionLocked([&]() {
1197     auto I = std::find_if(LinkOrder.begin(), LinkOrder.end(),
1198                           [&](const JITDylibSearchOrder::value_type &KV) {
1199                             return KV.first == &JD;
1200                           });
1201     if (I != LinkOrder.end())
1202       LinkOrder.erase(I);
1203   });
1204 }
1205 
1206 Error JITDylib::remove(const SymbolNameSet &Names) {
1207   return ES.runSessionLocked([&]() -> Error {
1208     using SymbolMaterializerItrPair =
1209         std::pair<SymbolTable::iterator, UnmaterializedInfosMap::iterator>;
1210     std::vector<SymbolMaterializerItrPair> SymbolsToRemove;
1211     SymbolNameSet Missing;
1212     SymbolNameSet Materializing;
1213 
1214     for (auto &Name : Names) {
1215       auto I = Symbols.find(Name);
1216 
1217       // Note symbol missing.
1218       if (I == Symbols.end()) {
1219         Missing.insert(Name);
1220         continue;
1221       }
1222 
1223       // Note symbol materializing.
1224       if (I->second.getState() != SymbolState::NeverSearched &&
1225           I->second.getState() != SymbolState::Ready) {
1226         Materializing.insert(Name);
1227         continue;
1228       }
1229 
1230       auto UMII = I->second.hasMaterializerAttached()
1231                       ? UnmaterializedInfos.find(Name)
1232                       : UnmaterializedInfos.end();
1233       SymbolsToRemove.push_back(std::make_pair(I, UMII));
1234     }
1235 
1236     // If any of the symbols are not defined, return an error.
1237     if (!Missing.empty())
1238       return make_error<SymbolsNotFound>(std::move(Missing));
1239 
1240     // If any of the symbols are currently materializing, return an error.
1241     if (!Materializing.empty())
1242       return make_error<SymbolsCouldNotBeRemoved>(std::move(Materializing));
1243 
1244     // Remove the symbols.
1245     for (auto &SymbolMaterializerItrPair : SymbolsToRemove) {
1246       auto UMII = SymbolMaterializerItrPair.second;
1247 
1248       // If there is a materializer attached, call discard.
1249       if (UMII != UnmaterializedInfos.end()) {
1250         UMII->second->MU->doDiscard(*this, UMII->first);
1251         UnmaterializedInfos.erase(UMII);
1252       }
1253 
1254       auto SymI = SymbolMaterializerItrPair.first;
1255       Symbols.erase(SymI);
1256     }
1257 
1258     return Error::success();
1259   });
1260 }
1261 
1262 Expected<SymbolFlagsMap>
1263 JITDylib::lookupFlags(LookupKind K, JITDylibLookupFlags JDLookupFlags,
1264                       SymbolLookupSet LookupSet) {
1265   return ES.runSessionLocked([&, this]() -> Expected<SymbolFlagsMap> {
1266     SymbolFlagsMap Result;
1267     lookupFlagsImpl(Result, K, JDLookupFlags, LookupSet);
1268 
1269     // Run any definition generators.
1270     for (auto &DG : DefGenerators) {
1271 
1272       // Bail out early if we found everything.
1273       if (LookupSet.empty())
1274         break;
1275 
1276       // Run this generator.
1277       if (auto Err = DG->tryToGenerate(K, *this, JDLookupFlags, LookupSet))
1278         return std::move(Err);
1279 
1280       // Re-try the search.
1281       lookupFlagsImpl(Result, K, JDLookupFlags, LookupSet);
1282     }
1283 
1284     return Result;
1285   });
1286 }
1287 
1288 void JITDylib::lookupFlagsImpl(SymbolFlagsMap &Result, LookupKind K,
1289                                JITDylibLookupFlags JDLookupFlags,
1290                                SymbolLookupSet &LookupSet) {
1291 
1292   LookupSet.forEachWithRemoval(
1293       [&](const SymbolStringPtr &Name, SymbolLookupFlags Flags) -> bool {
1294         auto I = Symbols.find(Name);
1295         if (I == Symbols.end())
1296           return false;
1297         assert(!Result.count(Name) && "Symbol already present in Flags map");
1298         Result[Name] = I->second.getFlags();
1299         return true;
1300       });
1301 }
1302 
1303 Error JITDylib::lodgeQuery(MaterializationUnitList &MUs,
1304                            std::shared_ptr<AsynchronousSymbolQuery> &Q,
1305                            LookupKind K, JITDylibLookupFlags JDLookupFlags,
1306                            SymbolLookupSet &Unresolved) {
1307   assert(Q && "Query can not be null");
1308 
1309   if (auto Err = lodgeQueryImpl(MUs, Q, K, JDLookupFlags, Unresolved))
1310     return Err;
1311 
1312   // Run any definition generators.
1313   for (auto &DG : DefGenerators) {
1314 
1315     // Bail out early if we have resolved everything.
1316     if (Unresolved.empty())
1317       break;
1318 
1319     // Run the generator.
1320     if (auto Err = DG->tryToGenerate(K, *this, JDLookupFlags, Unresolved))
1321       return Err;
1322 
1323     // Lodge query. This can not fail as any new definitions were added
1324     // by the generator under the session locked. Since they can't have
1325     // started materializing yet they can not have failed.
1326     cantFail(lodgeQueryImpl(MUs, Q, K, JDLookupFlags, Unresolved));
1327   }
1328 
1329   return Error::success();
1330 }
1331 
1332 Error JITDylib::lodgeQueryImpl(MaterializationUnitList &MUs,
1333                                std::shared_ptr<AsynchronousSymbolQuery> &Q,
1334                                LookupKind K, JITDylibLookupFlags JDLookupFlags,
1335                                SymbolLookupSet &Unresolved) {
1336 
1337   return Unresolved.forEachWithRemoval(
1338       [&](const SymbolStringPtr &Name,
1339           SymbolLookupFlags SymLookupFlags) -> Expected<bool> {
1340         // Search for name in symbols. If not found then continue without
1341         // removal.
1342         auto SymI = Symbols.find(Name);
1343         if (SymI == Symbols.end())
1344           return false;
1345 
1346         // If we match against a materialization-side-effects only symbol then
1347         // make sure it is weakly-referenced. Otherwise bail out with an error.
1348         if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
1349             SymLookupFlags != SymbolLookupFlags::WeaklyReferencedSymbol)
1350           return make_error<SymbolsNotFound>(SymbolNameVector({Name}));
1351 
1352         // If this is a non exported symbol and we're matching exported symbols
1353         // only then skip this symbol without removal.
1354         if (!SymI->second.getFlags().isExported() &&
1355             JDLookupFlags == JITDylibLookupFlags::MatchExportedSymbolsOnly)
1356           return false;
1357 
1358         // If we matched against this symbol but it is in the error state then
1359         // bail out and treat it as a failure to materialize.
1360         if (SymI->second.getFlags().hasError()) {
1361           auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
1362           (*FailedSymbolsMap)[this] = {Name};
1363           return make_error<FailedToMaterialize>(std::move(FailedSymbolsMap));
1364         }
1365 
1366         // If this symbol already meets the required state for then notify the
1367         // query, then remove the symbol and continue.
1368         if (SymI->second.getState() >= Q->getRequiredState()) {
1369           Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
1370           return true;
1371         }
1372 
1373         // Otherwise this symbol does not yet meet the required state. Check
1374         // whether it has a materializer attached, and if so prepare to run it.
1375         if (SymI->second.hasMaterializerAttached()) {
1376           assert(SymI->second.getAddress() == 0 &&
1377                  "Symbol not resolved but already has address?");
1378           auto UMII = UnmaterializedInfos.find(Name);
1379           assert(UMII != UnmaterializedInfos.end() &&
1380                  "Lazy symbol should have UnmaterializedInfo");
1381           auto MU = std::move(UMII->second->MU);
1382           assert(MU != nullptr && "Materializer should not be null");
1383 
1384           // Move all symbols associated with this MaterializationUnit into
1385           // materializing state.
1386           for (auto &KV : MU->getSymbols()) {
1387             auto SymK = Symbols.find(KV.first);
1388             SymK->second.setMaterializerAttached(false);
1389             SymK->second.setState(SymbolState::Materializing);
1390             UnmaterializedInfos.erase(KV.first);
1391           }
1392 
1393           // Add MU to the list of MaterializationUnits to be materialized.
1394           MUs.push_back(std::move(MU));
1395         }
1396 
1397         // Add the query to the PendingQueries list and continue, deleting the
1398         // element.
1399         assert(SymI->second.getState() != SymbolState::NeverSearched &&
1400                SymI->second.getState() != SymbolState::Ready &&
1401                "By this line the symbol should be materializing");
1402         auto &MI = MaterializingInfos[Name];
1403         MI.addQuery(Q);
1404         Q->addQueryDependence(*this, Name);
1405         return true;
1406       });
1407 }
1408 
1409 Expected<SymbolNameSet>
1410 JITDylib::legacyLookup(std::shared_ptr<AsynchronousSymbolQuery> Q,
1411                        SymbolNameSet Names) {
1412   assert(Q && "Query can not be null");
1413 
1414   ES.runOutstandingMUs();
1415 
1416   bool QueryComplete = false;
1417   std::vector<std::unique_ptr<MaterializationUnit>> MUs;
1418 
1419   SymbolLookupSet Unresolved(Names);
1420   auto Err = ES.runSessionLocked([&, this]() -> Error {
1421     QueryComplete = lookupImpl(Q, MUs, Unresolved);
1422 
1423     // Run any definition generators.
1424     for (auto &DG : DefGenerators) {
1425 
1426       // Bail out early if we have resolved everything.
1427       if (Unresolved.empty())
1428         break;
1429 
1430       assert(!QueryComplete && "query complete but unresolved symbols remain?");
1431       if (auto Err = DG->tryToGenerate(LookupKind::Static, *this,
1432                                        JITDylibLookupFlags::MatchAllSymbols,
1433                                        Unresolved))
1434         return Err;
1435 
1436       if (!Unresolved.empty())
1437         QueryComplete = lookupImpl(Q, MUs, Unresolved);
1438     }
1439     return Error::success();
1440   });
1441 
1442   if (Err)
1443     return std::move(Err);
1444 
1445   assert((MUs.empty() || !QueryComplete) &&
1446          "If action flags are set, there should be no work to do (so no MUs)");
1447 
1448   if (QueryComplete)
1449     Q->handleComplete();
1450 
1451   // FIXME: Swap back to the old code below once RuntimeDyld works with
1452   //        callbacks from asynchronous queries.
1453   // Add MUs to the OutstandingMUs list.
1454   {
1455     std::lock_guard<std::recursive_mutex> Lock(ES.OutstandingMUsMutex);
1456     auto ThisJD = shared_from_this();
1457     for (auto &MU : MUs) {
1458       auto MR = MU->createMaterializationResponsibility(ThisJD);
1459       ES.OutstandingMUs.push_back(make_pair(std::move(MU), std::move(MR)));
1460     }
1461   }
1462   ES.runOutstandingMUs();
1463 
1464   // Dispatch any required MaterializationUnits for materialization.
1465   // for (auto &MU : MUs)
1466   //  ES.dispatchMaterialization(*this, std::move(MU));
1467 
1468   SymbolNameSet RemainingSymbols;
1469   for (auto &KV : Unresolved)
1470     RemainingSymbols.insert(KV.first);
1471 
1472   return RemainingSymbols;
1473 }
1474 
1475 bool JITDylib::lookupImpl(
1476     std::shared_ptr<AsynchronousSymbolQuery> &Q,
1477     std::vector<std::unique_ptr<MaterializationUnit>> &MUs,
1478     SymbolLookupSet &Unresolved) {
1479   bool QueryComplete = false;
1480 
1481   std::vector<SymbolStringPtr> ToRemove;
1482   Unresolved.forEachWithRemoval(
1483       [&](const SymbolStringPtr &Name, SymbolLookupFlags Flags) -> bool {
1484         // Search for the name in Symbols. Skip without removing if not found.
1485         auto SymI = Symbols.find(Name);
1486         if (SymI == Symbols.end())
1487           return false;
1488 
1489         // If the symbol is already in the required state then notify the query
1490         // and remove.
1491         if (SymI->second.getState() >= Q->getRequiredState()) {
1492           Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
1493           if (Q->isComplete())
1494             QueryComplete = true;
1495           return true;
1496         }
1497 
1498         // If the symbol is lazy, get the MaterialiaztionUnit for it.
1499         if (SymI->second.hasMaterializerAttached()) {
1500           assert(SymI->second.getAddress() == 0 &&
1501                  "Lazy symbol should not have a resolved address");
1502           auto UMII = UnmaterializedInfos.find(Name);
1503           assert(UMII != UnmaterializedInfos.end() &&
1504                  "Lazy symbol should have UnmaterializedInfo");
1505           auto MU = std::move(UMII->second->MU);
1506           assert(MU != nullptr && "Materializer should not be null");
1507 
1508           // Kick all symbols associated with this MaterializationUnit into
1509           // materializing state.
1510           for (auto &KV : MU->getSymbols()) {
1511             auto SymK = Symbols.find(KV.first);
1512             assert(SymK != Symbols.end() && "Missing symbol table entry");
1513             SymK->second.setState(SymbolState::Materializing);
1514             SymK->second.setMaterializerAttached(false);
1515             UnmaterializedInfos.erase(KV.first);
1516           }
1517 
1518           // Add MU to the list of MaterializationUnits to be materialized.
1519           MUs.push_back(std::move(MU));
1520         }
1521 
1522         // Add the query to the PendingQueries list.
1523         assert(SymI->second.getState() != SymbolState::NeverSearched &&
1524                SymI->second.getState() != SymbolState::Ready &&
1525                "By this line the symbol should be materializing");
1526         auto &MI = MaterializingInfos[Name];
1527         MI.addQuery(Q);
1528         Q->addQueryDependence(*this, Name);
1529         return true;
1530       });
1531 
1532   return QueryComplete;
1533 }
1534 
1535 void JITDylib::dump(raw_ostream &OS) {
1536   ES.runSessionLocked([&, this]() {
1537     OS << "JITDylib \"" << JITDylibName << "\" (ES: "
1538        << format("0x%016" PRIx64, reinterpret_cast<uintptr_t>(&ES)) << "):\n"
1539        << "Link order: " << LinkOrder << "\n"
1540        << "Symbol table:\n";
1541 
1542     for (auto &KV : Symbols) {
1543       OS << "    \"" << *KV.first << "\": ";
1544       if (auto Addr = KV.second.getAddress())
1545         OS << format("0x%016" PRIx64, Addr) << ", " << KV.second.getFlags()
1546            << " ";
1547       else
1548         OS << "<not resolved> ";
1549 
1550       OS << KV.second.getFlags() << " " << KV.second.getState();
1551 
1552       if (KV.second.hasMaterializerAttached()) {
1553         OS << " (Materializer ";
1554         auto I = UnmaterializedInfos.find(KV.first);
1555         assert(I != UnmaterializedInfos.end() &&
1556                "Lazy symbol should have UnmaterializedInfo");
1557         OS << I->second->MU.get() << ", " << I->second->MU->getName() << ")\n";
1558       } else
1559         OS << "\n";
1560     }
1561 
1562     if (!MaterializingInfos.empty())
1563       OS << "  MaterializingInfos entries:\n";
1564     for (auto &KV : MaterializingInfos) {
1565       OS << "    \"" << *KV.first << "\":\n"
1566          << "      " << KV.second.pendingQueries().size()
1567          << " pending queries: { ";
1568       for (const auto &Q : KV.second.pendingQueries())
1569         OS << Q.get() << " (" << Q->getRequiredState() << ") ";
1570       OS << "}\n      Dependants:\n";
1571       for (auto &KV2 : KV.second.Dependants)
1572         OS << "        " << KV2.first->getName() << ": " << KV2.second << "\n";
1573       OS << "      Unemitted Dependencies:\n";
1574       for (auto &KV2 : KV.second.UnemittedDependencies)
1575         OS << "        " << KV2.first->getName() << ": " << KV2.second << "\n";
1576     }
1577   });
1578 }
1579 
1580 void JITDylib::MaterializingInfo::addQuery(
1581     std::shared_ptr<AsynchronousSymbolQuery> Q) {
1582 
1583   auto I = std::lower_bound(
1584       PendingQueries.rbegin(), PendingQueries.rend(), Q->getRequiredState(),
1585       [](const std::shared_ptr<AsynchronousSymbolQuery> &V, SymbolState S) {
1586         return V->getRequiredState() <= S;
1587       });
1588   PendingQueries.insert(I.base(), std::move(Q));
1589 }
1590 
1591 void JITDylib::MaterializingInfo::removeQuery(
1592     const AsynchronousSymbolQuery &Q) {
1593   // FIXME: Implement 'find_as' for shared_ptr<T>/T*.
1594   auto I =
1595       std::find_if(PendingQueries.begin(), PendingQueries.end(),
1596                    [&Q](const std::shared_ptr<AsynchronousSymbolQuery> &V) {
1597                      return V.get() == &Q;
1598                    });
1599   assert(I != PendingQueries.end() &&
1600          "Query is not attached to this MaterializingInfo");
1601   PendingQueries.erase(I);
1602 }
1603 
1604 JITDylib::AsynchronousSymbolQueryList
1605 JITDylib::MaterializingInfo::takeQueriesMeeting(SymbolState RequiredState) {
1606   AsynchronousSymbolQueryList Result;
1607   while (!PendingQueries.empty()) {
1608     if (PendingQueries.back()->getRequiredState() > RequiredState)
1609       break;
1610 
1611     Result.push_back(std::move(PendingQueries.back()));
1612     PendingQueries.pop_back();
1613   }
1614 
1615   return Result;
1616 }
1617 
1618 JITDylib::JITDylib(ExecutionSession &ES, std::string Name)
1619     : ES(ES), JITDylibName(std::move(Name)) {
1620   LinkOrder.push_back({this, JITDylibLookupFlags::MatchAllSymbols});
1621 }
1622 
1623 Error JITDylib::defineImpl(MaterializationUnit &MU) {
1624 
1625   LLVM_DEBUG({ dbgs() << "  " << MU.getSymbols() << "\n"; });
1626 
1627   SymbolNameSet Duplicates;
1628   std::vector<SymbolStringPtr> ExistingDefsOverridden;
1629   std::vector<SymbolStringPtr> MUDefsOverridden;
1630 
1631   for (const auto &KV : MU.getSymbols()) {
1632     auto I = Symbols.find(KV.first);
1633 
1634     if (I != Symbols.end()) {
1635       if (KV.second.isStrong()) {
1636         if (I->second.getFlags().isStrong() ||
1637             I->second.getState() > SymbolState::NeverSearched)
1638           Duplicates.insert(KV.first);
1639         else {
1640           assert(I->second.getState() == SymbolState::NeverSearched &&
1641                  "Overridden existing def should be in the never-searched "
1642                  "state");
1643           ExistingDefsOverridden.push_back(KV.first);
1644         }
1645       } else
1646         MUDefsOverridden.push_back(KV.first);
1647     }
1648   }
1649 
1650   // If there were any duplicate definitions then bail out.
1651   if (!Duplicates.empty()) {
1652     LLVM_DEBUG(
1653         { dbgs() << "  Error: Duplicate symbols " << Duplicates << "\n"; });
1654     return make_error<DuplicateDefinition>(std::string(**Duplicates.begin()));
1655   }
1656 
1657   // Discard any overridden defs in this MU.
1658   LLVM_DEBUG({
1659     if (!MUDefsOverridden.empty())
1660       dbgs() << "  Defs in this MU overridden: " << MUDefsOverridden << "\n";
1661   });
1662   for (auto &S : MUDefsOverridden)
1663     MU.doDiscard(*this, S);
1664 
1665   // Discard existing overridden defs.
1666   LLVM_DEBUG({
1667     if (!ExistingDefsOverridden.empty())
1668       dbgs() << "  Existing defs overridden by this MU: " << MUDefsOverridden
1669              << "\n";
1670   });
1671   for (auto &S : ExistingDefsOverridden) {
1672 
1673     auto UMII = UnmaterializedInfos.find(S);
1674     assert(UMII != UnmaterializedInfos.end() &&
1675            "Overridden existing def should have an UnmaterializedInfo");
1676     UMII->second->MU->doDiscard(*this, S);
1677   }
1678 
1679   // Finally, add the defs from this MU.
1680   for (auto &KV : MU.getSymbols()) {
1681     auto &SymEntry = Symbols[KV.first];
1682     SymEntry.setFlags(KV.second);
1683     SymEntry.setState(SymbolState::NeverSearched);
1684     SymEntry.setMaterializerAttached(true);
1685   }
1686 
1687   return Error::success();
1688 }
1689 
1690 void JITDylib::detachQueryHelper(AsynchronousSymbolQuery &Q,
1691                                  const SymbolNameSet &QuerySymbols) {
1692   for (auto &QuerySymbol : QuerySymbols) {
1693     assert(MaterializingInfos.count(QuerySymbol) &&
1694            "QuerySymbol does not have MaterializingInfo");
1695     auto &MI = MaterializingInfos[QuerySymbol];
1696     MI.removeQuery(Q);
1697   }
1698 }
1699 
1700 void JITDylib::transferEmittedNodeDependencies(
1701     MaterializingInfo &DependantMI, const SymbolStringPtr &DependantName,
1702     MaterializingInfo &EmittedMI) {
1703   for (auto &KV : EmittedMI.UnemittedDependencies) {
1704     auto &DependencyJD = *KV.first;
1705     SymbolNameSet *UnemittedDependenciesOnDependencyJD = nullptr;
1706 
1707     for (auto &DependencyName : KV.second) {
1708       auto &DependencyMI = DependencyJD.MaterializingInfos[DependencyName];
1709 
1710       // Do not add self dependencies.
1711       if (&DependencyMI == &DependantMI)
1712         continue;
1713 
1714       // If we haven't looked up the dependencies for DependencyJD yet, do it
1715       // now and cache the result.
1716       if (!UnemittedDependenciesOnDependencyJD)
1717         UnemittedDependenciesOnDependencyJD =
1718             &DependantMI.UnemittedDependencies[&DependencyJD];
1719 
1720       DependencyMI.Dependants[this].insert(DependantName);
1721       UnemittedDependenciesOnDependencyJD->insert(DependencyName);
1722     }
1723   }
1724 }
1725 
1726 Platform::~Platform() {}
1727 
1728 Expected<DenseMap<JITDylib *, SymbolMap>> Platform::lookupInitSymbols(
1729     ExecutionSession &ES,
1730     const DenseMap<JITDylib *, SymbolLookupSet> &InitSyms) {
1731 
1732   DenseMap<JITDylib *, SymbolMap> CompoundResult;
1733   Error CompoundErr = Error::success();
1734   std::mutex LookupMutex;
1735   std::condition_variable CV;
1736   uint64_t Count = InitSyms.size();
1737 
1738   LLVM_DEBUG({
1739     dbgs() << "Issuing init-symbol lookup:\n";
1740     for (auto &KV : InitSyms)
1741       dbgs() << "  " << KV.first->getName() << ": " << KV.second << "\n";
1742   });
1743 
1744   for (auto &KV : InitSyms) {
1745     auto *JD = KV.first;
1746     auto Names = std::move(KV.second);
1747     ES.lookup(
1748         LookupKind::Static,
1749         JITDylibSearchOrder({{JD, JITDylibLookupFlags::MatchAllSymbols}}),
1750         std::move(Names), SymbolState::Ready,
1751         [&, JD](Expected<SymbolMap> Result) {
1752           {
1753             std::lock_guard<std::mutex> Lock(LookupMutex);
1754             --Count;
1755             if (Result) {
1756               assert(!CompoundResult.count(JD) &&
1757                      "Duplicate JITDylib in lookup?");
1758               CompoundResult[JD] = std::move(*Result);
1759             } else
1760               CompoundErr =
1761                   joinErrors(std::move(CompoundErr), Result.takeError());
1762           }
1763           CV.notify_one();
1764         },
1765         NoDependenciesToRegister);
1766   }
1767 
1768   std::unique_lock<std::mutex> Lock(LookupMutex);
1769   CV.wait(Lock, [&] { return Count == 0 || CompoundErr; });
1770 
1771   if (CompoundErr)
1772     return std::move(CompoundErr);
1773 
1774   return std::move(CompoundResult);
1775 }
1776 
1777 ExecutionSession::ExecutionSession(std::shared_ptr<SymbolStringPool> SSP)
1778     : SSP(SSP ? std::move(SSP) : std::make_shared<SymbolStringPool>()) {
1779 }
1780 
1781 JITDylib *ExecutionSession::getJITDylibByName(StringRef Name) {
1782   return runSessionLocked([&, this]() -> JITDylib * {
1783     for (auto &JD : JDs)
1784       if (JD->getName() == Name)
1785         return JD.get();
1786     return nullptr;
1787   });
1788 }
1789 
1790 JITDylib &ExecutionSession::createBareJITDylib(std::string Name) {
1791   assert(!getJITDylibByName(Name) && "JITDylib with that name already exists");
1792   return runSessionLocked([&, this]() -> JITDylib & {
1793     JDs.push_back(
1794         std::shared_ptr<JITDylib>(new JITDylib(*this, std::move(Name))));
1795     return *JDs.back();
1796   });
1797 }
1798 
1799 Expected<JITDylib &> ExecutionSession::createJITDylib(std::string Name) {
1800   auto &JD = createBareJITDylib(Name);
1801   if (P)
1802     if (auto Err = P->setupJITDylib(JD))
1803       return std::move(Err);
1804   return JD;
1805 }
1806 
1807 void ExecutionSession::legacyFailQuery(AsynchronousSymbolQuery &Q, Error Err) {
1808   assert(!!Err && "Error should be in failure state");
1809 
1810   bool SendErrorToQuery;
1811   runSessionLocked([&]() {
1812     Q.detach();
1813     SendErrorToQuery = Q.canStillFail();
1814   });
1815 
1816   if (SendErrorToQuery)
1817     Q.handleFailed(std::move(Err));
1818   else
1819     reportError(std::move(Err));
1820 }
1821 
1822 Expected<SymbolMap> ExecutionSession::legacyLookup(
1823     LegacyAsyncLookupFunction AsyncLookup, SymbolNameSet Names,
1824     SymbolState RequiredState,
1825     RegisterDependenciesFunction RegisterDependencies) {
1826 #if LLVM_ENABLE_THREADS
1827   // In the threaded case we use promises to return the results.
1828   std::promise<SymbolMap> PromisedResult;
1829   Error ResolutionError = Error::success();
1830   auto NotifyComplete = [&](Expected<SymbolMap> R) {
1831     if (R)
1832       PromisedResult.set_value(std::move(*R));
1833     else {
1834       ErrorAsOutParameter _(&ResolutionError);
1835       ResolutionError = R.takeError();
1836       PromisedResult.set_value(SymbolMap());
1837     }
1838   };
1839 #else
1840   SymbolMap Result;
1841   Error ResolutionError = Error::success();
1842 
1843   auto NotifyComplete = [&](Expected<SymbolMap> R) {
1844     ErrorAsOutParameter _(&ResolutionError);
1845     if (R)
1846       Result = std::move(*R);
1847     else
1848       ResolutionError = R.takeError();
1849   };
1850 #endif
1851 
1852   auto Query = std::make_shared<AsynchronousSymbolQuery>(
1853       SymbolLookupSet(Names), RequiredState, std::move(NotifyComplete));
1854   // FIXME: This should be run session locked along with the registration code
1855   // and error reporting below.
1856   SymbolNameSet UnresolvedSymbols = AsyncLookup(Query, std::move(Names));
1857 
1858   // If the query was lodged successfully then register the dependencies,
1859   // otherwise fail it with an error.
1860   if (UnresolvedSymbols.empty())
1861     RegisterDependencies(Query->QueryRegistrations);
1862   else {
1863     bool DeliverError = runSessionLocked([&]() {
1864       Query->detach();
1865       return Query->canStillFail();
1866     });
1867     auto Err = make_error<SymbolsNotFound>(std::move(UnresolvedSymbols));
1868     if (DeliverError)
1869       Query->handleFailed(std::move(Err));
1870     else
1871       reportError(std::move(Err));
1872   }
1873 
1874 #if LLVM_ENABLE_THREADS
1875   auto ResultFuture = PromisedResult.get_future();
1876   auto Result = ResultFuture.get();
1877   if (ResolutionError)
1878     return std::move(ResolutionError);
1879   return std::move(Result);
1880 
1881 #else
1882   if (ResolutionError)
1883     return std::move(ResolutionError);
1884 
1885   return Result;
1886 #endif
1887 }
1888 
1889 std::vector<std::shared_ptr<JITDylib>>
1890 JITDylib::getDFSLinkOrder(ArrayRef<std::shared_ptr<JITDylib>> JDs) {
1891   if (JDs.empty())
1892     return {};
1893 
1894   auto &ES = JDs.front()->getExecutionSession();
1895   return ES.runSessionLocked([&]() {
1896     DenseSet<JITDylib *> Visited;
1897     std::vector<std::shared_ptr<JITDylib>> Result;
1898 
1899     for (auto &JD : JDs) {
1900 
1901       if (Visited.count(JD.get()))
1902         continue;
1903 
1904       SmallVector<std::shared_ptr<JITDylib>, 64> WorkStack;
1905       WorkStack.push_back(JD);
1906       Visited.insert(JD.get());
1907 
1908       while (!WorkStack.empty()) {
1909         Result.push_back(std::move(WorkStack.back()));
1910         WorkStack.pop_back();
1911 
1912         for (auto &KV : llvm::reverse(Result.back()->LinkOrder)) {
1913           auto &JD = *KV.first;
1914           if (Visited.count(&JD))
1915             continue;
1916           Visited.insert(&JD);
1917           WorkStack.push_back(JD.shared_from_this());
1918         }
1919       }
1920     }
1921     return Result;
1922   });
1923 }
1924 
1925 std::vector<std::shared_ptr<JITDylib>>
1926 JITDylib::getReverseDFSLinkOrder(ArrayRef<std::shared_ptr<JITDylib>> JDs) {
1927   auto Tmp = getDFSLinkOrder(JDs);
1928   std::reverse(Tmp.begin(), Tmp.end());
1929   return Tmp;
1930 }
1931 
1932 std::vector<std::shared_ptr<JITDylib>> JITDylib::getDFSLinkOrder() {
1933   return getDFSLinkOrder({shared_from_this()});
1934 }
1935 
1936 std::vector<std::shared_ptr<JITDylib>> JITDylib::getReverseDFSLinkOrder() {
1937   return getReverseDFSLinkOrder({shared_from_this()});
1938 }
1939 
1940 void ExecutionSession::lookup(
1941     LookupKind K, const JITDylibSearchOrder &SearchOrder,
1942     SymbolLookupSet Symbols, SymbolState RequiredState,
1943     SymbolsResolvedCallback NotifyComplete,
1944     RegisterDependenciesFunction RegisterDependencies) {
1945 
1946   LLVM_DEBUG({
1947     runSessionLocked([&]() {
1948       dbgs() << "Looking up " << Symbols << " in " << SearchOrder
1949              << " (required state: " << RequiredState << ")\n";
1950     });
1951   });
1952 
1953   // lookup can be re-entered recursively if running on a single thread. Run any
1954   // outstanding MUs in case this query depends on them, otherwise this lookup
1955   // will starve waiting for a result from an MU that is stuck in the queue.
1956   runOutstandingMUs();
1957 
1958   auto Unresolved = std::move(Symbols);
1959   std::map<JITDylib *, MaterializationUnitList> CollectedMUsMap;
1960   auto Q = std::make_shared<AsynchronousSymbolQuery>(Unresolved, RequiredState,
1961                                                      std::move(NotifyComplete));
1962   bool QueryComplete = false;
1963 
1964   auto LodgingErr = runSessionLocked([&]() -> Error {
1965     auto LodgeQuery = [&]() -> Error {
1966       for (auto &KV : SearchOrder) {
1967         assert(KV.first && "JITDylibList entries must not be null");
1968         assert(!CollectedMUsMap.count(KV.first) &&
1969                "JITDylibList should not contain duplicate entries");
1970 
1971         auto &JD = *KV.first;
1972         auto JDLookupFlags = KV.second;
1973         if (auto Err = JD.lodgeQuery(CollectedMUsMap[&JD], Q, K, JDLookupFlags,
1974                                      Unresolved))
1975           return Err;
1976       }
1977 
1978       // Strip any weakly referenced symbols that were not found.
1979       Unresolved.forEachWithRemoval(
1980           [&](const SymbolStringPtr &Name, SymbolLookupFlags Flags) {
1981             if (Flags == SymbolLookupFlags::WeaklyReferencedSymbol) {
1982               Q->dropSymbol(Name);
1983               return true;
1984             }
1985             return false;
1986           });
1987 
1988       if (!Unresolved.empty())
1989         return make_error<SymbolsNotFound>(Unresolved.getSymbolNames());
1990 
1991       return Error::success();
1992     };
1993 
1994     if (auto Err = LodgeQuery()) {
1995       // Query failed.
1996 
1997       // Disconnect the query from its dependencies.
1998       Q->detach();
1999 
2000       // Replace the MUs.
2001       for (auto &KV : CollectedMUsMap)
2002         for (auto &MU : KV.second)
2003           KV.first->replace(std::move(MU));
2004 
2005       return Err;
2006     }
2007 
2008     // Query lodged successfully.
2009 
2010     // Record whether this query is fully ready / resolved. We will use
2011     // this to call handleFullyResolved/handleFullyReady outside the session
2012     // lock.
2013     QueryComplete = Q->isComplete();
2014 
2015     // Call the register dependencies function.
2016     if (RegisterDependencies && !Q->QueryRegistrations.empty())
2017       RegisterDependencies(Q->QueryRegistrations);
2018 
2019     return Error::success();
2020   });
2021 
2022   if (LodgingErr) {
2023     Q->handleFailed(std::move(LodgingErr));
2024     return;
2025   }
2026 
2027   if (QueryComplete)
2028     Q->handleComplete();
2029 
2030   // Move the MUs to the OutstandingMUs list, then materialize.
2031   {
2032     std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2033 
2034     for (auto &KV : CollectedMUsMap) {
2035       auto JD = KV.first->shared_from_this();
2036       for (auto &MU : KV.second) {
2037         auto MR = MU->createMaterializationResponsibility(JD);
2038         OutstandingMUs.push_back(std::make_pair(std::move(MU), std::move(MR)));
2039       }
2040     }
2041   }
2042 
2043   runOutstandingMUs();
2044 }
2045 
2046 Expected<SymbolMap>
2047 ExecutionSession::lookup(const JITDylibSearchOrder &SearchOrder,
2048                          const SymbolLookupSet &Symbols, LookupKind K,
2049                          SymbolState RequiredState,
2050                          RegisterDependenciesFunction RegisterDependencies) {
2051 #if LLVM_ENABLE_THREADS
2052   // In the threaded case we use promises to return the results.
2053   std::promise<SymbolMap> PromisedResult;
2054   Error ResolutionError = Error::success();
2055 
2056   auto NotifyComplete = [&](Expected<SymbolMap> R) {
2057     if (R)
2058       PromisedResult.set_value(std::move(*R));
2059     else {
2060       ErrorAsOutParameter _(&ResolutionError);
2061       ResolutionError = R.takeError();
2062       PromisedResult.set_value(SymbolMap());
2063     }
2064   };
2065 
2066 #else
2067   SymbolMap Result;
2068   Error ResolutionError = Error::success();
2069 
2070   auto NotifyComplete = [&](Expected<SymbolMap> R) {
2071     ErrorAsOutParameter _(&ResolutionError);
2072     if (R)
2073       Result = std::move(*R);
2074     else
2075       ResolutionError = R.takeError();
2076   };
2077 #endif
2078 
2079   // Perform the asynchronous lookup.
2080   lookup(K, SearchOrder, Symbols, RequiredState, NotifyComplete,
2081          RegisterDependencies);
2082 
2083 #if LLVM_ENABLE_THREADS
2084   auto ResultFuture = PromisedResult.get_future();
2085   auto Result = ResultFuture.get();
2086 
2087   if (ResolutionError)
2088     return std::move(ResolutionError);
2089 
2090   return std::move(Result);
2091 
2092 #else
2093   if (ResolutionError)
2094     return std::move(ResolutionError);
2095 
2096   return Result;
2097 #endif
2098 }
2099 
2100 Expected<JITEvaluatedSymbol>
2101 ExecutionSession::lookup(const JITDylibSearchOrder &SearchOrder,
2102                          SymbolStringPtr Name, SymbolState RequiredState) {
2103   SymbolLookupSet Names({Name});
2104 
2105   if (auto ResultMap = lookup(SearchOrder, std::move(Names), LookupKind::Static,
2106                               RequiredState, NoDependenciesToRegister)) {
2107     assert(ResultMap->size() == 1 && "Unexpected number of results");
2108     assert(ResultMap->count(Name) && "Missing result for symbol");
2109     return std::move(ResultMap->begin()->second);
2110   } else
2111     return ResultMap.takeError();
2112 }
2113 
2114 Expected<JITEvaluatedSymbol>
2115 ExecutionSession::lookup(ArrayRef<JITDylib *> SearchOrder, SymbolStringPtr Name,
2116                          SymbolState RequiredState) {
2117   return lookup(makeJITDylibSearchOrder(SearchOrder), Name, RequiredState);
2118 }
2119 
2120 Expected<JITEvaluatedSymbol>
2121 ExecutionSession::lookup(ArrayRef<JITDylib *> SearchOrder, StringRef Name,
2122                          SymbolState RequiredState) {
2123   return lookup(SearchOrder, intern(Name), RequiredState);
2124 }
2125 
2126 void ExecutionSession::dump(raw_ostream &OS) {
2127   runSessionLocked([this, &OS]() {
2128     for (auto &JD : JDs)
2129       JD->dump(OS);
2130   });
2131 }
2132 
2133 void ExecutionSession::runOutstandingMUs() {
2134   while (1) {
2135     Optional<std::pair<std::unique_ptr<MaterializationUnit>,
2136                        std::unique_ptr<MaterializationResponsibility>>>
2137         JMU;
2138 
2139     {
2140       std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2141       if (!OutstandingMUs.empty()) {
2142         JMU.emplace(std::move(OutstandingMUs.back()));
2143         OutstandingMUs.pop_back();
2144       }
2145     }
2146 
2147     if (!JMU)
2148       break;
2149 
2150     assert(JMU->first && "No MU?");
2151     dispatchMaterialization(std::move(JMU->first), std::move(JMU->second));
2152   }
2153 }
2154 
2155 #ifndef NDEBUG
2156 void ExecutionSession::dumpDispatchInfo(JITDylib &JD, MaterializationUnit &MU) {
2157   runSessionLocked([&]() {
2158     dbgs() << "Dispatching " << MU << " for " << JD.getName() << "\n";
2159   });
2160 }
2161 #endif // NDEBUG
2162 
2163 } // End namespace orc.
2164 } // End namespace llvm.
2165