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