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::setLinkOrder(JITDylibSearchOrder NewLinkOrder,
1161                             bool LinkAgainstThisJITDylibFirst) {
1162   ES.runSessionLocked([&]() {
1163     if (LinkAgainstThisJITDylibFirst) {
1164       LinkOrder.clear();
1165       if (NewLinkOrder.empty() || NewLinkOrder.front().first != this)
1166         LinkOrder.push_back(
1167             std::make_pair(this, JITDylibLookupFlags::MatchAllSymbols));
1168       LinkOrder.insert(LinkOrder.end(), NewLinkOrder.begin(),
1169                        NewLinkOrder.end());
1170     } else
1171       LinkOrder = std::move(NewLinkOrder);
1172   });
1173 }
1174 
1175 void JITDylib::addToLinkOrder(JITDylib &JD, JITDylibLookupFlags JDLookupFlags) {
1176   ES.runSessionLocked([&]() { LinkOrder.push_back({&JD, JDLookupFlags}); });
1177 }
1178 
1179 void JITDylib::replaceInLinkOrder(JITDylib &OldJD, JITDylib &NewJD,
1180                                   JITDylibLookupFlags JDLookupFlags) {
1181   ES.runSessionLocked([&]() {
1182     for (auto &KV : LinkOrder)
1183       if (KV.first == &OldJD) {
1184         KV = {&NewJD, JDLookupFlags};
1185         break;
1186       }
1187   });
1188 }
1189 
1190 void JITDylib::removeFromLinkOrder(JITDylib &JD) {
1191   ES.runSessionLocked([&]() {
1192     auto I = std::find_if(LinkOrder.begin(), LinkOrder.end(),
1193                           [&](const JITDylibSearchOrder::value_type &KV) {
1194                             return KV.first == &JD;
1195                           });
1196     if (I != LinkOrder.end())
1197       LinkOrder.erase(I);
1198   });
1199 }
1200 
1201 Error JITDylib::remove(const SymbolNameSet &Names) {
1202   return ES.runSessionLocked([&]() -> Error {
1203     using SymbolMaterializerItrPair =
1204         std::pair<SymbolTable::iterator, UnmaterializedInfosMap::iterator>;
1205     std::vector<SymbolMaterializerItrPair> SymbolsToRemove;
1206     SymbolNameSet Missing;
1207     SymbolNameSet Materializing;
1208 
1209     for (auto &Name : Names) {
1210       auto I = Symbols.find(Name);
1211 
1212       // Note symbol missing.
1213       if (I == Symbols.end()) {
1214         Missing.insert(Name);
1215         continue;
1216       }
1217 
1218       // Note symbol materializing.
1219       if (I->second.getState() != SymbolState::NeverSearched &&
1220           I->second.getState() != SymbolState::Ready) {
1221         Materializing.insert(Name);
1222         continue;
1223       }
1224 
1225       auto UMII = I->second.hasMaterializerAttached()
1226                       ? UnmaterializedInfos.find(Name)
1227                       : UnmaterializedInfos.end();
1228       SymbolsToRemove.push_back(std::make_pair(I, UMII));
1229     }
1230 
1231     // If any of the symbols are not defined, return an error.
1232     if (!Missing.empty())
1233       return make_error<SymbolsNotFound>(std::move(Missing));
1234 
1235     // If any of the symbols are currently materializing, return an error.
1236     if (!Materializing.empty())
1237       return make_error<SymbolsCouldNotBeRemoved>(std::move(Materializing));
1238 
1239     // Remove the symbols.
1240     for (auto &SymbolMaterializerItrPair : SymbolsToRemove) {
1241       auto UMII = SymbolMaterializerItrPair.second;
1242 
1243       // If there is a materializer attached, call discard.
1244       if (UMII != UnmaterializedInfos.end()) {
1245         UMII->second->MU->doDiscard(*this, UMII->first);
1246         UnmaterializedInfos.erase(UMII);
1247       }
1248 
1249       auto SymI = SymbolMaterializerItrPair.first;
1250       Symbols.erase(SymI);
1251     }
1252 
1253     return Error::success();
1254   });
1255 }
1256 
1257 Expected<SymbolFlagsMap>
1258 JITDylib::lookupFlags(LookupKind K, JITDylibLookupFlags JDLookupFlags,
1259                       SymbolLookupSet LookupSet) {
1260   return ES.runSessionLocked([&, this]() -> Expected<SymbolFlagsMap> {
1261     SymbolFlagsMap Result;
1262     lookupFlagsImpl(Result, K, JDLookupFlags, LookupSet);
1263 
1264     // Run any definition generators.
1265     for (auto &DG : DefGenerators) {
1266 
1267       // Bail out early if we found everything.
1268       if (LookupSet.empty())
1269         break;
1270 
1271       // Run this generator.
1272       if (auto Err = DG->tryToGenerate(K, *this, JDLookupFlags, LookupSet))
1273         return std::move(Err);
1274 
1275       // Re-try the search.
1276       lookupFlagsImpl(Result, K, JDLookupFlags, LookupSet);
1277     }
1278 
1279     return Result;
1280   });
1281 }
1282 
1283 void JITDylib::lookupFlagsImpl(SymbolFlagsMap &Result, LookupKind K,
1284                                JITDylibLookupFlags JDLookupFlags,
1285                                SymbolLookupSet &LookupSet) {
1286 
1287   LookupSet.forEachWithRemoval(
1288       [&](const SymbolStringPtr &Name, SymbolLookupFlags Flags) -> bool {
1289         auto I = Symbols.find(Name);
1290         if (I == Symbols.end())
1291           return false;
1292         assert(!Result.count(Name) && "Symbol already present in Flags map");
1293         Result[Name] = I->second.getFlags();
1294         return true;
1295       });
1296 }
1297 
1298 Error JITDylib::lodgeQuery(MaterializationUnitList &MUs,
1299                            std::shared_ptr<AsynchronousSymbolQuery> &Q,
1300                            LookupKind K, JITDylibLookupFlags JDLookupFlags,
1301                            SymbolLookupSet &Unresolved) {
1302   assert(Q && "Query can not be null");
1303 
1304   if (auto Err = lodgeQueryImpl(MUs, Q, K, JDLookupFlags, Unresolved))
1305     return Err;
1306 
1307   // Run any definition generators.
1308   for (auto &DG : DefGenerators) {
1309 
1310     // Bail out early if we have resolved everything.
1311     if (Unresolved.empty())
1312       break;
1313 
1314     // Run the generator.
1315     if (auto Err = DG->tryToGenerate(K, *this, JDLookupFlags, Unresolved))
1316       return Err;
1317 
1318     // Lodge query. This can not fail as any new definitions were added
1319     // by the generator under the session locked. Since they can't have
1320     // started materializing yet they can not have failed.
1321     cantFail(lodgeQueryImpl(MUs, Q, K, JDLookupFlags, Unresolved));
1322   }
1323 
1324   return Error::success();
1325 }
1326 
1327 Error JITDylib::lodgeQueryImpl(MaterializationUnitList &MUs,
1328                                std::shared_ptr<AsynchronousSymbolQuery> &Q,
1329                                LookupKind K, JITDylibLookupFlags JDLookupFlags,
1330                                SymbolLookupSet &Unresolved) {
1331 
1332   return Unresolved.forEachWithRemoval(
1333       [&](const SymbolStringPtr &Name,
1334           SymbolLookupFlags SymLookupFlags) -> Expected<bool> {
1335         // Search for name in symbols. If not found then continue without
1336         // removal.
1337         auto SymI = Symbols.find(Name);
1338         if (SymI == Symbols.end())
1339           return false;
1340 
1341         // If we match against a materialization-side-effects only symbol then
1342         // make sure it is weakly-referenced. Otherwise bail out with an error.
1343         if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
1344             SymLookupFlags != SymbolLookupFlags::WeaklyReferencedSymbol)
1345           return make_error<SymbolsNotFound>(SymbolNameVector({Name}));
1346 
1347         // If this is a non exported symbol and we're matching exported symbols
1348         // only then skip this symbol without removal.
1349         if (!SymI->second.getFlags().isExported() &&
1350             JDLookupFlags == JITDylibLookupFlags::MatchExportedSymbolsOnly)
1351           return false;
1352 
1353         // If we matched against this symbol but it is in the error state then
1354         // bail out and treat it as a failure to materialize.
1355         if (SymI->second.getFlags().hasError()) {
1356           auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
1357           (*FailedSymbolsMap)[this] = {Name};
1358           return make_error<FailedToMaterialize>(std::move(FailedSymbolsMap));
1359         }
1360 
1361         // If this symbol already meets the required state for then notify the
1362         // query, then remove the symbol and continue.
1363         if (SymI->second.getState() >= Q->getRequiredState()) {
1364           Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
1365           return true;
1366         }
1367 
1368         // Otherwise this symbol does not yet meet the required state. Check
1369         // whether it has a materializer attached, and if so prepare to run it.
1370         if (SymI->second.hasMaterializerAttached()) {
1371           assert(SymI->second.getAddress() == 0 &&
1372                  "Symbol not resolved but already has address?");
1373           auto UMII = UnmaterializedInfos.find(Name);
1374           assert(UMII != UnmaterializedInfos.end() &&
1375                  "Lazy symbol should have UnmaterializedInfo");
1376           auto MU = std::move(UMII->second->MU);
1377           assert(MU != nullptr && "Materializer should not be null");
1378 
1379           // Move all symbols associated with this MaterializationUnit into
1380           // materializing state.
1381           for (auto &KV : MU->getSymbols()) {
1382             auto SymK = Symbols.find(KV.first);
1383             SymK->second.setMaterializerAttached(false);
1384             SymK->second.setState(SymbolState::Materializing);
1385             UnmaterializedInfos.erase(KV.first);
1386           }
1387 
1388           // Add MU to the list of MaterializationUnits to be materialized.
1389           MUs.push_back(std::move(MU));
1390         }
1391 
1392         // Add the query to the PendingQueries list and continue, deleting the
1393         // element.
1394         assert(SymI->second.getState() != SymbolState::NeverSearched &&
1395                SymI->second.getState() != SymbolState::Ready &&
1396                "By this line the symbol should be materializing");
1397         auto &MI = MaterializingInfos[Name];
1398         MI.addQuery(Q);
1399         Q->addQueryDependence(*this, Name);
1400         return true;
1401       });
1402 }
1403 
1404 Expected<SymbolNameSet>
1405 JITDylib::legacyLookup(std::shared_ptr<AsynchronousSymbolQuery> Q,
1406                        SymbolNameSet Names) {
1407   assert(Q && "Query can not be null");
1408 
1409   ES.runOutstandingMUs();
1410 
1411   bool QueryComplete = false;
1412   std::vector<std::unique_ptr<MaterializationUnit>> MUs;
1413 
1414   SymbolLookupSet Unresolved(Names);
1415   auto Err = ES.runSessionLocked([&, this]() -> Error {
1416     QueryComplete = lookupImpl(Q, MUs, Unresolved);
1417 
1418     // Run any definition generators.
1419     for (auto &DG : DefGenerators) {
1420 
1421       // Bail out early if we have resolved everything.
1422       if (Unresolved.empty())
1423         break;
1424 
1425       assert(!QueryComplete && "query complete but unresolved symbols remain?");
1426       if (auto Err = DG->tryToGenerate(LookupKind::Static, *this,
1427                                        JITDylibLookupFlags::MatchAllSymbols,
1428                                        Unresolved))
1429         return Err;
1430 
1431       if (!Unresolved.empty())
1432         QueryComplete = lookupImpl(Q, MUs, Unresolved);
1433     }
1434     return Error::success();
1435   });
1436 
1437   if (Err)
1438     return std::move(Err);
1439 
1440   assert((MUs.empty() || !QueryComplete) &&
1441          "If action flags are set, there should be no work to do (so no MUs)");
1442 
1443   if (QueryComplete)
1444     Q->handleComplete();
1445 
1446   // FIXME: Swap back to the old code below once RuntimeDyld works with
1447   //        callbacks from asynchronous queries.
1448   // Add MUs to the OutstandingMUs list.
1449   {
1450     std::lock_guard<std::recursive_mutex> Lock(ES.OutstandingMUsMutex);
1451     for (auto &MU : MUs)
1452       ES.OutstandingMUs.push_back(make_pair(this, std::move(MU)));
1453   }
1454   ES.runOutstandingMUs();
1455 
1456   // Dispatch any required MaterializationUnits for materialization.
1457   // for (auto &MU : MUs)
1458   //  ES.dispatchMaterialization(*this, std::move(MU));
1459 
1460   SymbolNameSet RemainingSymbols;
1461   for (auto &KV : Unresolved)
1462     RemainingSymbols.insert(KV.first);
1463 
1464   return RemainingSymbols;
1465 }
1466 
1467 bool JITDylib::lookupImpl(
1468     std::shared_ptr<AsynchronousSymbolQuery> &Q,
1469     std::vector<std::unique_ptr<MaterializationUnit>> &MUs,
1470     SymbolLookupSet &Unresolved) {
1471   bool QueryComplete = false;
1472 
1473   std::vector<SymbolStringPtr> ToRemove;
1474   Unresolved.forEachWithRemoval(
1475       [&](const SymbolStringPtr &Name, SymbolLookupFlags Flags) -> bool {
1476         // Search for the name in Symbols. Skip without removing if not found.
1477         auto SymI = Symbols.find(Name);
1478         if (SymI == Symbols.end())
1479           return false;
1480 
1481         // If the symbol is already in the required state then notify the query
1482         // and remove.
1483         if (SymI->second.getState() >= Q->getRequiredState()) {
1484           Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
1485           if (Q->isComplete())
1486             QueryComplete = true;
1487           return true;
1488         }
1489 
1490         // If the symbol is lazy, get the MaterialiaztionUnit for it.
1491         if (SymI->second.hasMaterializerAttached()) {
1492           assert(SymI->second.getAddress() == 0 &&
1493                  "Lazy symbol should not have a resolved address");
1494           auto UMII = UnmaterializedInfos.find(Name);
1495           assert(UMII != UnmaterializedInfos.end() &&
1496                  "Lazy symbol should have UnmaterializedInfo");
1497           auto MU = std::move(UMII->second->MU);
1498           assert(MU != nullptr && "Materializer should not be null");
1499 
1500           // Kick all symbols associated with this MaterializationUnit into
1501           // materializing state.
1502           for (auto &KV : MU->getSymbols()) {
1503             auto SymK = Symbols.find(KV.first);
1504             assert(SymK != Symbols.end() && "Missing symbol table entry");
1505             SymK->second.setState(SymbolState::Materializing);
1506             SymK->second.setMaterializerAttached(false);
1507             UnmaterializedInfos.erase(KV.first);
1508           }
1509 
1510           // Add MU to the list of MaterializationUnits to be materialized.
1511           MUs.push_back(std::move(MU));
1512         }
1513 
1514         // Add the query to the PendingQueries list.
1515         assert(SymI->second.getState() != SymbolState::NeverSearched &&
1516                SymI->second.getState() != SymbolState::Ready &&
1517                "By this line the symbol should be materializing");
1518         auto &MI = MaterializingInfos[Name];
1519         MI.addQuery(Q);
1520         Q->addQueryDependence(*this, Name);
1521         return true;
1522       });
1523 
1524   return QueryComplete;
1525 }
1526 
1527 void JITDylib::dump(raw_ostream &OS) {
1528   ES.runSessionLocked([&, this]() {
1529     OS << "JITDylib \"" << JITDylibName << "\" (ES: "
1530        << format("0x%016" PRIx64, reinterpret_cast<uintptr_t>(&ES)) << "):\n"
1531        << "Link order: " << LinkOrder << "\n"
1532        << "Symbol table:\n";
1533 
1534     for (auto &KV : Symbols) {
1535       OS << "    \"" << *KV.first << "\": ";
1536       if (auto Addr = KV.second.getAddress())
1537         OS << format("0x%016" PRIx64, Addr) << ", " << KV.second.getFlags()
1538            << " ";
1539       else
1540         OS << "<not resolved> ";
1541 
1542       OS << KV.second.getFlags() << " " << KV.second.getState();
1543 
1544       if (KV.second.hasMaterializerAttached()) {
1545         OS << " (Materializer ";
1546         auto I = UnmaterializedInfos.find(KV.first);
1547         assert(I != UnmaterializedInfos.end() &&
1548                "Lazy symbol should have UnmaterializedInfo");
1549         OS << I->second->MU.get() << ", " << I->second->MU->getName() << ")\n";
1550       } else
1551         OS << "\n";
1552     }
1553 
1554     if (!MaterializingInfos.empty())
1555       OS << "  MaterializingInfos entries:\n";
1556     for (auto &KV : MaterializingInfos) {
1557       OS << "    \"" << *KV.first << "\":\n"
1558          << "      " << KV.second.pendingQueries().size()
1559          << " pending queries: { ";
1560       for (const auto &Q : KV.second.pendingQueries())
1561         OS << Q.get() << " (" << Q->getRequiredState() << ") ";
1562       OS << "}\n      Dependants:\n";
1563       for (auto &KV2 : KV.second.Dependants)
1564         OS << "        " << KV2.first->getName() << ": " << KV2.second << "\n";
1565       OS << "      Unemitted Dependencies:\n";
1566       for (auto &KV2 : KV.second.UnemittedDependencies)
1567         OS << "        " << KV2.first->getName() << ": " << KV2.second << "\n";
1568     }
1569   });
1570 }
1571 
1572 void JITDylib::MaterializingInfo::addQuery(
1573     std::shared_ptr<AsynchronousSymbolQuery> Q) {
1574 
1575   auto I = std::lower_bound(
1576       PendingQueries.rbegin(), PendingQueries.rend(), Q->getRequiredState(),
1577       [](const std::shared_ptr<AsynchronousSymbolQuery> &V, SymbolState S) {
1578         return V->getRequiredState() <= S;
1579       });
1580   PendingQueries.insert(I.base(), std::move(Q));
1581 }
1582 
1583 void JITDylib::MaterializingInfo::removeQuery(
1584     const AsynchronousSymbolQuery &Q) {
1585   // FIXME: Implement 'find_as' for shared_ptr<T>/T*.
1586   auto I =
1587       std::find_if(PendingQueries.begin(), PendingQueries.end(),
1588                    [&Q](const std::shared_ptr<AsynchronousSymbolQuery> &V) {
1589                      return V.get() == &Q;
1590                    });
1591   assert(I != PendingQueries.end() &&
1592          "Query is not attached to this MaterializingInfo");
1593   PendingQueries.erase(I);
1594 }
1595 
1596 JITDylib::AsynchronousSymbolQueryList
1597 JITDylib::MaterializingInfo::takeQueriesMeeting(SymbolState RequiredState) {
1598   AsynchronousSymbolQueryList Result;
1599   while (!PendingQueries.empty()) {
1600     if (PendingQueries.back()->getRequiredState() > RequiredState)
1601       break;
1602 
1603     Result.push_back(std::move(PendingQueries.back()));
1604     PendingQueries.pop_back();
1605   }
1606 
1607   return Result;
1608 }
1609 
1610 JITDylib::JITDylib(ExecutionSession &ES, std::string Name)
1611     : ES(ES), JITDylibName(std::move(Name)) {
1612   LinkOrder.push_back({this, JITDylibLookupFlags::MatchAllSymbols});
1613 }
1614 
1615 Error JITDylib::defineImpl(MaterializationUnit &MU) {
1616 
1617   LLVM_DEBUG({ dbgs() << "  " << MU.getSymbols() << "\n"; });
1618 
1619   SymbolNameSet Duplicates;
1620   std::vector<SymbolStringPtr> ExistingDefsOverridden;
1621   std::vector<SymbolStringPtr> MUDefsOverridden;
1622 
1623   for (const auto &KV : MU.getSymbols()) {
1624     auto I = Symbols.find(KV.first);
1625 
1626     if (I != Symbols.end()) {
1627       if (KV.second.isStrong()) {
1628         if (I->second.getFlags().isStrong() ||
1629             I->second.getState() > SymbolState::NeverSearched)
1630           Duplicates.insert(KV.first);
1631         else {
1632           assert(I->second.getState() == SymbolState::NeverSearched &&
1633                  "Overridden existing def should be in the never-searched "
1634                  "state");
1635           ExistingDefsOverridden.push_back(KV.first);
1636         }
1637       } else
1638         MUDefsOverridden.push_back(KV.first);
1639     }
1640   }
1641 
1642   // If there were any duplicate definitions then bail out.
1643   if (!Duplicates.empty()) {
1644     LLVM_DEBUG(
1645         { dbgs() << "  Error: Duplicate symbols " << Duplicates << "\n"; });
1646     return make_error<DuplicateDefinition>(std::string(**Duplicates.begin()));
1647   }
1648 
1649   // Discard any overridden defs in this MU.
1650   LLVM_DEBUG({
1651     if (!MUDefsOverridden.empty())
1652       dbgs() << "  Defs in this MU overridden: " << MUDefsOverridden << "\n";
1653   });
1654   for (auto &S : MUDefsOverridden)
1655     MU.doDiscard(*this, S);
1656 
1657   // Discard existing overridden defs.
1658   LLVM_DEBUG({
1659     if (!ExistingDefsOverridden.empty())
1660       dbgs() << "  Existing defs overridden by this MU: " << MUDefsOverridden
1661              << "\n";
1662   });
1663   for (auto &S : ExistingDefsOverridden) {
1664 
1665     auto UMII = UnmaterializedInfos.find(S);
1666     assert(UMII != UnmaterializedInfos.end() &&
1667            "Overridden existing def should have an UnmaterializedInfo");
1668     UMII->second->MU->doDiscard(*this, S);
1669   }
1670 
1671   // Finally, add the defs from this MU.
1672   for (auto &KV : MU.getSymbols()) {
1673     auto &SymEntry = Symbols[KV.first];
1674     SymEntry.setFlags(KV.second);
1675     SymEntry.setState(SymbolState::NeverSearched);
1676     SymEntry.setMaterializerAttached(true);
1677   }
1678 
1679   return Error::success();
1680 }
1681 
1682 void JITDylib::detachQueryHelper(AsynchronousSymbolQuery &Q,
1683                                  const SymbolNameSet &QuerySymbols) {
1684   for (auto &QuerySymbol : QuerySymbols) {
1685     assert(MaterializingInfos.count(QuerySymbol) &&
1686            "QuerySymbol does not have MaterializingInfo");
1687     auto &MI = MaterializingInfos[QuerySymbol];
1688     MI.removeQuery(Q);
1689   }
1690 }
1691 
1692 void JITDylib::transferEmittedNodeDependencies(
1693     MaterializingInfo &DependantMI, const SymbolStringPtr &DependantName,
1694     MaterializingInfo &EmittedMI) {
1695   for (auto &KV : EmittedMI.UnemittedDependencies) {
1696     auto &DependencyJD = *KV.first;
1697     SymbolNameSet *UnemittedDependenciesOnDependencyJD = nullptr;
1698 
1699     for (auto &DependencyName : KV.second) {
1700       auto &DependencyMI = DependencyJD.MaterializingInfos[DependencyName];
1701 
1702       // Do not add self dependencies.
1703       if (&DependencyMI == &DependantMI)
1704         continue;
1705 
1706       // If we haven't looked up the dependencies for DependencyJD yet, do it
1707       // now and cache the result.
1708       if (!UnemittedDependenciesOnDependencyJD)
1709         UnemittedDependenciesOnDependencyJD =
1710             &DependantMI.UnemittedDependencies[&DependencyJD];
1711 
1712       DependencyMI.Dependants[this].insert(DependantName);
1713       UnemittedDependenciesOnDependencyJD->insert(DependencyName);
1714     }
1715   }
1716 }
1717 
1718 Platform::~Platform() {}
1719 
1720 Expected<DenseMap<JITDylib *, SymbolMap>> Platform::lookupInitSymbols(
1721     ExecutionSession &ES,
1722     const DenseMap<JITDylib *, SymbolLookupSet> &InitSyms) {
1723 
1724   DenseMap<JITDylib *, SymbolMap> CompoundResult;
1725   Error CompoundErr = Error::success();
1726   std::mutex LookupMutex;
1727   std::condition_variable CV;
1728   uint64_t Count = InitSyms.size();
1729 
1730   LLVM_DEBUG({
1731     dbgs() << "Issuing init-symbol lookup:\n";
1732     for (auto &KV : InitSyms)
1733       dbgs() << "  " << KV.first->getName() << ": " << KV.second << "\n";
1734   });
1735 
1736   for (auto &KV : InitSyms) {
1737     auto *JD = KV.first;
1738     auto Names = std::move(KV.second);
1739     ES.lookup(
1740         LookupKind::Static,
1741         JITDylibSearchOrder({{JD, JITDylibLookupFlags::MatchAllSymbols}}),
1742         std::move(Names), SymbolState::Ready,
1743         [&, JD](Expected<SymbolMap> Result) {
1744           {
1745             std::lock_guard<std::mutex> Lock(LookupMutex);
1746             --Count;
1747             if (Result) {
1748               assert(!CompoundResult.count(JD) &&
1749                      "Duplicate JITDylib in lookup?");
1750               CompoundResult[JD] = std::move(*Result);
1751             } else
1752               CompoundErr =
1753                   joinErrors(std::move(CompoundErr), Result.takeError());
1754           }
1755           CV.notify_one();
1756         },
1757         NoDependenciesToRegister);
1758   }
1759 
1760   std::unique_lock<std::mutex> Lock(LookupMutex);
1761   CV.wait(Lock, [&] { return Count == 0 || CompoundErr; });
1762 
1763   if (CompoundErr)
1764     return std::move(CompoundErr);
1765 
1766   return std::move(CompoundResult);
1767 }
1768 
1769 ExecutionSession::ExecutionSession(std::shared_ptr<SymbolStringPool> SSP)
1770     : SSP(SSP ? std::move(SSP) : std::make_shared<SymbolStringPool>()) {
1771 }
1772 
1773 JITDylib *ExecutionSession::getJITDylibByName(StringRef Name) {
1774   return runSessionLocked([&, this]() -> JITDylib * {
1775     for (auto &JD : JDs)
1776       if (JD->getName() == Name)
1777         return JD.get();
1778     return nullptr;
1779   });
1780 }
1781 
1782 JITDylib &ExecutionSession::createBareJITDylib(std::string Name) {
1783   assert(!getJITDylibByName(Name) && "JITDylib with that name already exists");
1784   return runSessionLocked([&, this]() -> JITDylib & {
1785     JDs.push_back(
1786         std::unique_ptr<JITDylib>(new JITDylib(*this, std::move(Name))));
1787     return *JDs.back();
1788   });
1789 }
1790 
1791 Expected<JITDylib &> ExecutionSession::createJITDylib(std::string Name) {
1792   auto &JD = createBareJITDylib(Name);
1793   if (P)
1794     if (auto Err = P->setupJITDylib(JD))
1795       return std::move(Err);
1796   return JD;
1797 }
1798 
1799 void ExecutionSession::legacyFailQuery(AsynchronousSymbolQuery &Q, Error Err) {
1800   assert(!!Err && "Error should be in failure state");
1801 
1802   bool SendErrorToQuery;
1803   runSessionLocked([&]() {
1804     Q.detach();
1805     SendErrorToQuery = Q.canStillFail();
1806   });
1807 
1808   if (SendErrorToQuery)
1809     Q.handleFailed(std::move(Err));
1810   else
1811     reportError(std::move(Err));
1812 }
1813 
1814 Expected<SymbolMap> ExecutionSession::legacyLookup(
1815     LegacyAsyncLookupFunction AsyncLookup, SymbolNameSet Names,
1816     SymbolState RequiredState,
1817     RegisterDependenciesFunction RegisterDependencies) {
1818 #if LLVM_ENABLE_THREADS
1819   // In the threaded case we use promises to return the results.
1820   std::promise<SymbolMap> PromisedResult;
1821   Error ResolutionError = Error::success();
1822   auto NotifyComplete = [&](Expected<SymbolMap> R) {
1823     if (R)
1824       PromisedResult.set_value(std::move(*R));
1825     else {
1826       ErrorAsOutParameter _(&ResolutionError);
1827       ResolutionError = R.takeError();
1828       PromisedResult.set_value(SymbolMap());
1829     }
1830   };
1831 #else
1832   SymbolMap Result;
1833   Error ResolutionError = Error::success();
1834 
1835   auto NotifyComplete = [&](Expected<SymbolMap> R) {
1836     ErrorAsOutParameter _(&ResolutionError);
1837     if (R)
1838       Result = std::move(*R);
1839     else
1840       ResolutionError = R.takeError();
1841   };
1842 #endif
1843 
1844   auto Query = std::make_shared<AsynchronousSymbolQuery>(
1845       SymbolLookupSet(Names), RequiredState, std::move(NotifyComplete));
1846   // FIXME: This should be run session locked along with the registration code
1847   // and error reporting below.
1848   SymbolNameSet UnresolvedSymbols = AsyncLookup(Query, std::move(Names));
1849 
1850   // If the query was lodged successfully then register the dependencies,
1851   // otherwise fail it with an error.
1852   if (UnresolvedSymbols.empty())
1853     RegisterDependencies(Query->QueryRegistrations);
1854   else {
1855     bool DeliverError = runSessionLocked([&]() {
1856       Query->detach();
1857       return Query->canStillFail();
1858     });
1859     auto Err = make_error<SymbolsNotFound>(std::move(UnresolvedSymbols));
1860     if (DeliverError)
1861       Query->handleFailed(std::move(Err));
1862     else
1863       reportError(std::move(Err));
1864   }
1865 
1866 #if LLVM_ENABLE_THREADS
1867   auto ResultFuture = PromisedResult.get_future();
1868   auto Result = ResultFuture.get();
1869   if (ResolutionError)
1870     return std::move(ResolutionError);
1871   return std::move(Result);
1872 
1873 #else
1874   if (ResolutionError)
1875     return std::move(ResolutionError);
1876 
1877   return Result;
1878 #endif
1879 }
1880 
1881 void ExecutionSession::lookup(
1882     LookupKind K, const JITDylibSearchOrder &SearchOrder,
1883     SymbolLookupSet Symbols, SymbolState RequiredState,
1884     SymbolsResolvedCallback NotifyComplete,
1885     RegisterDependenciesFunction RegisterDependencies) {
1886 
1887   LLVM_DEBUG({
1888     runSessionLocked([&]() {
1889       dbgs() << "Looking up " << Symbols << " in " << SearchOrder
1890              << " (required state: " << RequiredState << ")\n";
1891     });
1892   });
1893 
1894   // lookup can be re-entered recursively if running on a single thread. Run any
1895   // outstanding MUs in case this query depends on them, otherwise this lookup
1896   // will starve waiting for a result from an MU that is stuck in the queue.
1897   runOutstandingMUs();
1898 
1899   auto Unresolved = std::move(Symbols);
1900   std::map<JITDylib *, MaterializationUnitList> CollectedMUsMap;
1901   auto Q = std::make_shared<AsynchronousSymbolQuery>(Unresolved, RequiredState,
1902                                                      std::move(NotifyComplete));
1903   bool QueryComplete = false;
1904 
1905   auto LodgingErr = runSessionLocked([&]() -> Error {
1906     auto LodgeQuery = [&]() -> Error {
1907       for (auto &KV : SearchOrder) {
1908         assert(KV.first && "JITDylibList entries must not be null");
1909         assert(!CollectedMUsMap.count(KV.first) &&
1910                "JITDylibList should not contain duplicate entries");
1911 
1912         auto &JD = *KV.first;
1913         auto JDLookupFlags = KV.second;
1914         if (auto Err = JD.lodgeQuery(CollectedMUsMap[&JD], Q, K, JDLookupFlags,
1915                                      Unresolved))
1916           return Err;
1917       }
1918 
1919       // Strip any weakly referenced symbols that were not found.
1920       Unresolved.forEachWithRemoval(
1921           [&](const SymbolStringPtr &Name, SymbolLookupFlags Flags) {
1922             if (Flags == SymbolLookupFlags::WeaklyReferencedSymbol) {
1923               Q->dropSymbol(Name);
1924               return true;
1925             }
1926             return false;
1927           });
1928 
1929       if (!Unresolved.empty())
1930         return make_error<SymbolsNotFound>(Unresolved.getSymbolNames());
1931 
1932       return Error::success();
1933     };
1934 
1935     if (auto Err = LodgeQuery()) {
1936       // Query failed.
1937 
1938       // Disconnect the query from its dependencies.
1939       Q->detach();
1940 
1941       // Replace the MUs.
1942       for (auto &KV : CollectedMUsMap)
1943         for (auto &MU : KV.second)
1944           KV.first->replace(std::move(MU));
1945 
1946       return Err;
1947     }
1948 
1949     // Query lodged successfully.
1950 
1951     // Record whether this query is fully ready / resolved. We will use
1952     // this to call handleFullyResolved/handleFullyReady outside the session
1953     // lock.
1954     QueryComplete = Q->isComplete();
1955 
1956     // Call the register dependencies function.
1957     if (RegisterDependencies && !Q->QueryRegistrations.empty())
1958       RegisterDependencies(Q->QueryRegistrations);
1959 
1960     return Error::success();
1961   });
1962 
1963   if (LodgingErr) {
1964     Q->handleFailed(std::move(LodgingErr));
1965     return;
1966   }
1967 
1968   if (QueryComplete)
1969     Q->handleComplete();
1970 
1971   // Move the MUs to the OutstandingMUs list, then materialize.
1972   {
1973     std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
1974 
1975     for (auto &KV : CollectedMUsMap)
1976       for (auto &MU : KV.second)
1977         OutstandingMUs.push_back(std::make_pair(KV.first, std::move(MU)));
1978   }
1979 
1980   runOutstandingMUs();
1981 }
1982 
1983 Expected<SymbolMap>
1984 ExecutionSession::lookup(const JITDylibSearchOrder &SearchOrder,
1985                          const SymbolLookupSet &Symbols, LookupKind K,
1986                          SymbolState RequiredState,
1987                          RegisterDependenciesFunction RegisterDependencies) {
1988 #if LLVM_ENABLE_THREADS
1989   // In the threaded case we use promises to return the results.
1990   std::promise<SymbolMap> PromisedResult;
1991   Error ResolutionError = Error::success();
1992 
1993   auto NotifyComplete = [&](Expected<SymbolMap> R) {
1994     if (R)
1995       PromisedResult.set_value(std::move(*R));
1996     else {
1997       ErrorAsOutParameter _(&ResolutionError);
1998       ResolutionError = R.takeError();
1999       PromisedResult.set_value(SymbolMap());
2000     }
2001   };
2002 
2003 #else
2004   SymbolMap Result;
2005   Error ResolutionError = Error::success();
2006 
2007   auto NotifyComplete = [&](Expected<SymbolMap> R) {
2008     ErrorAsOutParameter _(&ResolutionError);
2009     if (R)
2010       Result = std::move(*R);
2011     else
2012       ResolutionError = R.takeError();
2013   };
2014 #endif
2015 
2016   // Perform the asynchronous lookup.
2017   lookup(K, SearchOrder, Symbols, RequiredState, NotifyComplete,
2018          RegisterDependencies);
2019 
2020 #if LLVM_ENABLE_THREADS
2021   auto ResultFuture = PromisedResult.get_future();
2022   auto Result = ResultFuture.get();
2023 
2024   if (ResolutionError)
2025     return std::move(ResolutionError);
2026 
2027   return std::move(Result);
2028 
2029 #else
2030   if (ResolutionError)
2031     return std::move(ResolutionError);
2032 
2033   return Result;
2034 #endif
2035 }
2036 
2037 Expected<JITEvaluatedSymbol>
2038 ExecutionSession::lookup(const JITDylibSearchOrder &SearchOrder,
2039                          SymbolStringPtr Name, SymbolState RequiredState) {
2040   SymbolLookupSet Names({Name});
2041 
2042   if (auto ResultMap = lookup(SearchOrder, std::move(Names), LookupKind::Static,
2043                               RequiredState, NoDependenciesToRegister)) {
2044     assert(ResultMap->size() == 1 && "Unexpected number of results");
2045     assert(ResultMap->count(Name) && "Missing result for symbol");
2046     return std::move(ResultMap->begin()->second);
2047   } else
2048     return ResultMap.takeError();
2049 }
2050 
2051 Expected<JITEvaluatedSymbol>
2052 ExecutionSession::lookup(ArrayRef<JITDylib *> SearchOrder, SymbolStringPtr Name,
2053                          SymbolState RequiredState) {
2054   return lookup(makeJITDylibSearchOrder(SearchOrder), Name, RequiredState);
2055 }
2056 
2057 Expected<JITEvaluatedSymbol>
2058 ExecutionSession::lookup(ArrayRef<JITDylib *> SearchOrder, StringRef Name,
2059                          SymbolState RequiredState) {
2060   return lookup(SearchOrder, intern(Name), RequiredState);
2061 }
2062 
2063 void ExecutionSession::dump(raw_ostream &OS) {
2064   runSessionLocked([this, &OS]() {
2065     for (auto &JD : JDs)
2066       JD->dump(OS);
2067   });
2068 }
2069 
2070 void ExecutionSession::runOutstandingMUs() {
2071   while (1) {
2072     std::pair<JITDylib *, std::unique_ptr<MaterializationUnit>> JITDylibAndMU;
2073 
2074     {
2075       std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2076       if (!OutstandingMUs.empty()) {
2077         JITDylibAndMU = std::move(OutstandingMUs.back());
2078         OutstandingMUs.pop_back();
2079       }
2080     }
2081 
2082     if (JITDylibAndMU.first) {
2083       assert(JITDylibAndMU.second && "JITDylib, but no MU?");
2084       dispatchMaterialization(*JITDylibAndMU.first,
2085                               std::move(JITDylibAndMU.second));
2086     } else
2087       break;
2088   }
2089 }
2090 
2091 #ifndef NDEBUG
2092 void ExecutionSession::dumpDispatchInfo(JITDylib &JD, MaterializationUnit &MU) {
2093   runSessionLocked([&]() {
2094     dbgs() << "Dispatching " << MU << " for " << JD.getName() << "\n";
2095   });
2096 }
2097 #endif // NDEBUG
2098 
2099 } // End namespace orc.
2100 } // End namespace llvm.
2101