LLVM 22.0.0git
Core.cpp
Go to the documentation of this file.
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
10
11#include "llvm/ADT/STLExtras.h"
12#include "llvm/Config/llvm-config.h"
18
19#include <condition_variable>
20#include <future>
21#include <optional>
22
23#define DEBUG_TYPE "orc"
24
25namespace llvm {
26namespace orc {
27
30char SymbolsNotFound::ID = 0;
36char LookupTask::ID = 0;
37
40
41void MaterializationUnit::anchor() {}
42
44 assert((reinterpret_cast<uintptr_t>(JD.get()) & 0x1) == 0 &&
45 "JITDylib must be two byte aligned");
46 JD->Retain();
47 JDAndFlag.store(reinterpret_cast<uintptr_t>(JD.get()));
48}
49
51 getJITDylib().getExecutionSession().destroyResourceTracker(*this);
53}
54
56 return getJITDylib().getExecutionSession().removeResourceTracker(*this);
57}
58
60 getJITDylib().getExecutionSession().transferResourceTracker(DstRT, *this);
61}
62
63void ResourceTracker::makeDefunct() {
64 uintptr_t Val = JDAndFlag.load();
65 Val |= 0x1U;
66 JDAndFlag.store(Val);
67}
68
70
73
77
79 OS << "Resource tracker " << (void *)RT.get() << " became defunct";
80}
81
83 std::shared_ptr<SymbolStringPool> SSP,
84 std::shared_ptr<SymbolDependenceMap> Symbols)
85 : SSP(std::move(SSP)), Symbols(std::move(Symbols)) {
86 assert(this->SSP && "String pool cannot be null");
87 assert(!this->Symbols->empty() && "Can not fail to resolve an empty set");
88
89 // FIXME: Use a new dep-map type for FailedToMaterialize errors so that we
90 // don't have to manually retain/release.
91 for (auto &[JD, Syms] : *this->Symbols)
92 JD->Retain();
93}
94
96 for (auto &[JD, Syms] : *Symbols)
97 JD->Release();
98}
99
103
105 OS << "Failed to materialize symbols: " << *Symbols;
106}
107
109 std::shared_ptr<SymbolStringPool> SSP, JITDylibSP JD,
110 SymbolNameSet FailedSymbols, SymbolDependenceMap BadDeps,
111 std::string Explanation)
112 : SSP(std::move(SSP)), JD(std::move(JD)),
113 FailedSymbols(std::move(FailedSymbols)), BadDeps(std::move(BadDeps)),
114 Explanation(std::move(Explanation)) {}
115
119
121 OS << "In " << JD->getName() << ", failed to materialize " << FailedSymbols
122 << ", due to unsatisfied dependencies " << BadDeps;
123 if (!Explanation.empty())
124 OS << " (" << Explanation << ")";
125}
126
127SymbolsNotFound::SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP,
128 SymbolNameSet Symbols)
129 : SSP(std::move(SSP)) {
130 llvm::append_range(this->Symbols, Symbols);
131 assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
132}
133
134SymbolsNotFound::SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP,
135 SymbolNameVector Symbols)
136 : SSP(std::move(SSP)), Symbols(std::move(Symbols)) {
137 assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
138}
139
143
145 OS << "Symbols not found: " << Symbols;
146}
147
149 std::shared_ptr<SymbolStringPool> SSP, SymbolNameSet Symbols)
150 : SSP(std::move(SSP)), Symbols(std::move(Symbols)) {
151 assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
152}
153
157
159 OS << "Symbols could not be removed: " << Symbols;
160}
161
165
167 OS << "Missing definitions in module " << ModuleName
168 << ": " << Symbols;
169}
170
174
176 OS << "Unexpected definitions in module " << ModuleName
177 << ": " << Symbols;
178}
179
181 JD->getExecutionSession().lookup(
184 [OnComplete = std::move(OnComplete)
185#ifndef NDEBUG
186 ,
187 Name = this->Name // Captured for the assert below only.
188#endif // NDEBUG
189 ](Expected<SymbolMap> Result) mutable {
190 if (Result) {
191 assert(Result->size() == 1 && "Unexpected number of results");
192 assert(Result->count(Name) &&
193 "Result does not contain expected symbol");
194 OnComplete(Result->begin()->second);
195 } else
196 OnComplete(Result.takeError());
197 },
199}
200
202 const SymbolLookupSet &Symbols, SymbolState RequiredState,
203 SymbolsResolvedCallback NotifyComplete)
204 : NotifyComplete(std::move(NotifyComplete)), RequiredState(RequiredState) {
205 assert(RequiredState >= SymbolState::Resolved &&
206 "Cannot query for a symbols that have not reached the resolve state "
207 "yet");
208
209 OutstandingSymbolsCount = Symbols.size();
210
211 for (auto &[Name, Flags] : Symbols)
212 ResolvedSymbols[Name] = ExecutorSymbolDef();
213}
214
216 const SymbolStringPtr &Name, ExecutorSymbolDef Sym) {
217 auto I = ResolvedSymbols.find(Name);
218 assert(I != ResolvedSymbols.end() &&
219 "Resolving symbol outside the requested set");
220 assert(I->second == ExecutorSymbolDef() &&
221 "Redundantly resolving symbol Name");
222
223 // If this is a materialization-side-effects-only symbol then drop it,
224 // otherwise update its map entry with its resolved address.
226 ResolvedSymbols.erase(I);
227 else
228 I->second = std::move(Sym);
229 --OutstandingSymbolsCount;
230}
231
232void AsynchronousSymbolQuery::handleComplete(ExecutionSession &ES) {
233 assert(OutstandingSymbolsCount == 0 &&
234 "Symbols remain, handleComplete called prematurely");
235
236 class RunQueryCompleteTask : public Task {
237 public:
238 RunQueryCompleteTask(SymbolMap ResolvedSymbols,
239 SymbolsResolvedCallback NotifyComplete)
240 : ResolvedSymbols(std::move(ResolvedSymbols)),
241 NotifyComplete(std::move(NotifyComplete)) {}
242 void printDescription(raw_ostream &OS) override {
243 OS << "Execute query complete callback for " << ResolvedSymbols;
244 }
245 void run() override { NotifyComplete(std::move(ResolvedSymbols)); }
246
247 private:
248 SymbolMap ResolvedSymbols;
249 SymbolsResolvedCallback NotifyComplete;
250 };
251
252 auto T = std::make_unique<RunQueryCompleteTask>(std::move(ResolvedSymbols),
253 std::move(NotifyComplete));
254 NotifyComplete = SymbolsResolvedCallback();
255 ES.dispatchTask(std::move(T));
256}
257
258void AsynchronousSymbolQuery::handleFailed(Error Err) {
259 assert(QueryRegistrations.empty() && ResolvedSymbols.empty() &&
260 OutstandingSymbolsCount == 0 &&
261 "Query should already have been abandoned");
262 NotifyComplete(std::move(Err));
263 NotifyComplete = SymbolsResolvedCallback();
264}
265
266void AsynchronousSymbolQuery::addQueryDependence(JITDylib &JD,
267 SymbolStringPtr Name) {
268 bool Added = QueryRegistrations[&JD].insert(std::move(Name)).second;
269 (void)Added;
270 assert(Added && "Duplicate dependence notification?");
271}
272
273void AsynchronousSymbolQuery::removeQueryDependence(
274 JITDylib &JD, const SymbolStringPtr &Name) {
275 auto QRI = QueryRegistrations.find(&JD);
276 assert(QRI != QueryRegistrations.end() &&
277 "No dependencies registered for JD");
278 assert(QRI->second.count(Name) && "No dependency on Name in JD");
279 QRI->second.erase(Name);
280 if (QRI->second.empty())
281 QueryRegistrations.erase(QRI);
282}
283
284void AsynchronousSymbolQuery::dropSymbol(const SymbolStringPtr &Name) {
285 auto I = ResolvedSymbols.find(Name);
286 assert(I != ResolvedSymbols.end() &&
287 "Redundant removal of weakly-referenced symbol");
288 ResolvedSymbols.erase(I);
289 --OutstandingSymbolsCount;
290}
291
292void AsynchronousSymbolQuery::detach() {
293 ResolvedSymbols.clear();
294 OutstandingSymbolsCount = 0;
295 for (auto &[JD, Syms] : QueryRegistrations)
296 JD->detachQueryHelper(*this, Syms);
297 QueryRegistrations.clear();
298}
299
301 JITDylib *SourceJD, JITDylibLookupFlags SourceJDLookupFlags,
302 SymbolAliasMap Aliases)
303 : MaterializationUnit(extractFlags(Aliases)), SourceJD(SourceJD),
304 SourceJDLookupFlags(SourceJDLookupFlags), Aliases(std::move(Aliases)) {}
305
307 return "<Reexports>";
308}
309
310void ReExportsMaterializationUnit::materialize(
311 std::unique_ptr<MaterializationResponsibility> R) {
312
313 auto &ES = R->getTargetJITDylib().getExecutionSession();
314 JITDylib &TgtJD = R->getTargetJITDylib();
315 JITDylib &SrcJD = SourceJD ? *SourceJD : TgtJD;
316
317 // Find the set of requested aliases and aliasees. Return any unrequested
318 // aliases back to the JITDylib so as to not prematurely materialize any
319 // aliasees.
320 auto RequestedSymbols = R->getRequestedSymbols();
321 SymbolAliasMap RequestedAliases;
322
323 for (auto &Name : RequestedSymbols) {
324 auto I = Aliases.find(Name);
325 assert(I != Aliases.end() && "Symbol not found in aliases map?");
326 RequestedAliases[Name] = std::move(I->second);
327 Aliases.erase(I);
328 }
329
330 LLVM_DEBUG({
331 ES.runSessionLocked([&]() {
332 dbgs() << "materializing reexports: target = " << TgtJD.getName()
333 << ", source = " << SrcJD.getName() << " " << RequestedAliases
334 << "\n";
335 });
336 });
337
338 if (!Aliases.empty()) {
339 auto Err = SourceJD ? R->replace(reexports(*SourceJD, std::move(Aliases),
340 SourceJDLookupFlags))
341 : R->replace(symbolAliases(std::move(Aliases)));
342
343 if (Err) {
344 // FIXME: Should this be reported / treated as failure to materialize?
345 // Or should this be treated as a sanctioned bailing-out?
346 ES.reportError(std::move(Err));
347 R->failMaterialization();
348 return;
349 }
350 }
351
352 // The OnResolveInfo struct will hold the aliases and responsibility for each
353 // query in the list.
354 struct OnResolveInfo {
355 OnResolveInfo(std::unique_ptr<MaterializationResponsibility> R,
356 SymbolAliasMap Aliases)
357 : R(std::move(R)), Aliases(std::move(Aliases)) {}
358
359 std::unique_ptr<MaterializationResponsibility> R;
360 SymbolAliasMap Aliases;
361 std::vector<SymbolDependenceGroup> SDGs;
362 };
363
364 // Build a list of queries to issue. In each round we build a query for the
365 // largest set of aliases that we can resolve without encountering a chain of
366 // aliases (e.g. Foo -> Bar, Bar -> Baz). Such a chain would deadlock as the
367 // query would be waiting on a symbol that it itself had to resolve. Creating
368 // a new query for each link in such a chain eliminates the possibility of
369 // deadlock. In practice chains are likely to be rare, and this algorithm will
370 // usually result in a single query to issue.
371
372 std::vector<std::pair<SymbolLookupSet, std::shared_ptr<OnResolveInfo>>>
373 QueryInfos;
374 while (!RequestedAliases.empty()) {
375 SymbolNameSet ResponsibilitySymbols;
376 SymbolLookupSet QuerySymbols;
377 SymbolAliasMap QueryAliases;
378
379 // Collect as many aliases as we can without including a chain.
380 for (auto &KV : RequestedAliases) {
381 // Chain detected. Skip this symbol for this round.
382 if (&SrcJD == &TgtJD && (QueryAliases.count(KV.second.Aliasee) ||
383 RequestedAliases.count(KV.second.Aliasee)))
384 continue;
385
386 ResponsibilitySymbols.insert(KV.first);
387 QuerySymbols.add(KV.second.Aliasee,
388 KV.second.AliasFlags.hasMaterializationSideEffectsOnly()
389 ? SymbolLookupFlags::WeaklyReferencedSymbol
390 : SymbolLookupFlags::RequiredSymbol);
391 QueryAliases[KV.first] = std::move(KV.second);
392 }
393
394 // Remove the aliases collected this round from the RequestedAliases map.
395 for (auto &KV : QueryAliases)
396 RequestedAliases.erase(KV.first);
397
398 assert(!QuerySymbols.empty() && "Alias cycle detected!");
399
400 auto NewR = R->delegate(ResponsibilitySymbols);
401 if (!NewR) {
402 ES.reportError(NewR.takeError());
403 R->failMaterialization();
404 return;
405 }
406
407 auto QueryInfo = std::make_shared<OnResolveInfo>(std::move(*NewR),
408 std::move(QueryAliases));
409 QueryInfos.push_back(
410 make_pair(std::move(QuerySymbols), std::move(QueryInfo)));
411 }
412
413 // Issue the queries.
414 while (!QueryInfos.empty()) {
415 auto QuerySymbols = std::move(QueryInfos.back().first);
416 auto QueryInfo = std::move(QueryInfos.back().second);
417
418 QueryInfos.pop_back();
419
420 auto RegisterDependencies = [QueryInfo,
421 &SrcJD](const SymbolDependenceMap &Deps) {
422 // If there were no materializing symbols, just bail out.
423 if (Deps.empty())
424 return;
425
426 // Otherwise the only deps should be on SrcJD.
427 assert(Deps.size() == 1 && Deps.count(&SrcJD) &&
428 "Unexpected dependencies for reexports");
429
430 auto &SrcJDDeps = Deps.find(&SrcJD)->second;
431
432 for (auto &[Alias, AliasInfo] : QueryInfo->Aliases)
433 if (SrcJDDeps.count(AliasInfo.Aliasee))
434 QueryInfo->SDGs.push_back({{Alias}, {{&SrcJD, {AliasInfo.Aliasee}}}});
435 };
436
437 auto OnComplete = [QueryInfo](Expected<SymbolMap> Result) {
438 auto &ES = QueryInfo->R->getTargetJITDylib().getExecutionSession();
439 if (Result) {
440 SymbolMap ResolutionMap;
441 for (auto &KV : QueryInfo->Aliases) {
442 assert((KV.second.AliasFlags.hasMaterializationSideEffectsOnly() ||
443 Result->count(KV.second.Aliasee)) &&
444 "Result map missing entry?");
445 // Don't try to resolve materialization-side-effects-only symbols.
446 if (KV.second.AliasFlags.hasMaterializationSideEffectsOnly())
447 continue;
448
449 ResolutionMap[KV.first] = {(*Result)[KV.second.Aliasee].getAddress(),
450 KV.second.AliasFlags};
451 }
452 if (auto Err = QueryInfo->R->notifyResolved(ResolutionMap)) {
453 ES.reportError(std::move(Err));
454 QueryInfo->R->failMaterialization();
455 return;
456 }
457 if (auto Err = QueryInfo->R->notifyEmitted(QueryInfo->SDGs)) {
458 ES.reportError(std::move(Err));
459 QueryInfo->R->failMaterialization();
460 return;
461 }
462 } else {
463 ES.reportError(Result.takeError());
464 QueryInfo->R->failMaterialization();
465 }
466 };
467
469 JITDylibSearchOrder({{&SrcJD, SourceJDLookupFlags}}),
470 QuerySymbols, SymbolState::Resolved, std::move(OnComplete),
471 std::move(RegisterDependencies));
472 }
473}
474
475void ReExportsMaterializationUnit::discard(const JITDylib &JD,
476 const SymbolStringPtr &Name) {
477 assert(Aliases.count(Name) &&
478 "Symbol not covered by this MaterializationUnit");
479 Aliases.erase(Name);
480}
481
482MaterializationUnit::Interface
483ReExportsMaterializationUnit::extractFlags(const SymbolAliasMap &Aliases) {
485 for (auto &KV : Aliases)
486 SymbolFlags[KV.first] = KV.second.AliasFlags;
487
488 return MaterializationUnit::Interface(std::move(SymbolFlags), nullptr);
489}
490
492 SymbolNameSet Symbols) {
493 SymbolLookupSet LookupSet(Symbols);
494 auto Flags = SourceJD.getExecutionSession().lookupFlags(
496 SymbolLookupSet(std::move(Symbols)));
497
498 if (!Flags)
499 return Flags.takeError();
500
502 for (auto &Name : Symbols) {
503 assert(Flags->count(Name) && "Missing entry in flags map");
504 Result[Name] = SymbolAliasMapEntry(Name, (*Flags)[Name]);
505 }
506
507 return Result;
508}
509
511public:
512 // FIXME: Reduce the number of SymbolStringPtrs here. See
513 // https://github.com/llvm/llvm-project/issues/55576.
514
521 virtual ~InProgressLookupState() = default;
522 virtual void complete(std::unique_ptr<InProgressLookupState> IPLS) = 0;
523 virtual void fail(Error Err) = 0;
524
529
531 bool NewJITDylib = true;
534
535 enum {
536 NotInGenerator, // Not currently using a generator.
537 ResumedForGenerator, // Resumed after being auto-suspended before generator.
538 InGenerator // Currently using generator.
539 } GenState = NotInGenerator;
540 std::vector<std::weak_ptr<DefinitionGenerator>> CurDefGeneratorStack;
541};
542
544public:
551
552 void complete(std::unique_ptr<InProgressLookupState> IPLS) override {
553 auto &ES = SearchOrder.front().first->getExecutionSession();
554 ES.OL_completeLookupFlags(std::move(IPLS), std::move(OnComplete));
555 }
556
557 void fail(Error Err) override { OnComplete(std::move(Err)); }
558
559private:
561};
562
564public:
568 std::shared_ptr<AsynchronousSymbolQuery> Q,
569 RegisterDependenciesFunction RegisterDependencies)
572 Q(std::move(Q)), RegisterDependencies(std::move(RegisterDependencies)) {
573 }
574
575 void complete(std::unique_ptr<InProgressLookupState> IPLS) override {
576 auto &ES = SearchOrder.front().first->getExecutionSession();
577 ES.OL_completeLookup(std::move(IPLS), std::move(Q),
578 std::move(RegisterDependencies));
579 }
580
581 void fail(Error Err) override {
582 Q->detach();
583 Q->handleFailed(std::move(Err));
584 }
585
586private:
587 std::shared_ptr<AsynchronousSymbolQuery> Q;
588 RegisterDependenciesFunction RegisterDependencies;
589};
590
592 JITDylibLookupFlags SourceJDLookupFlags,
593 SymbolPredicate Allow)
594 : SourceJD(SourceJD), SourceJDLookupFlags(SourceJDLookupFlags),
595 Allow(std::move(Allow)) {}
596
598 JITDylib &JD,
599 JITDylibLookupFlags JDLookupFlags,
600 const SymbolLookupSet &LookupSet) {
601 assert(&JD != &SourceJD && "Cannot re-export from the same dylib");
602
603 // Use lookupFlags to find the subset of symbols that match our lookup.
604 auto Flags = JD.getExecutionSession().lookupFlags(
605 K, {{&SourceJD, JDLookupFlags}}, LookupSet);
606 if (!Flags)
607 return Flags.takeError();
608
609 // Create an alias map.
610 orc::SymbolAliasMap AliasMap;
611 for (auto &KV : *Flags)
612 if (!Allow || Allow(KV.first))
613 AliasMap[KV.first] = SymbolAliasMapEntry(KV.first, KV.second);
614
615 if (AliasMap.empty())
616 return Error::success();
617
618 // Define the re-exports.
619 return JD.define(reexports(SourceJD, AliasMap, SourceJDLookupFlags));
620}
621
622LookupState::LookupState(std::unique_ptr<InProgressLookupState> IPLS)
623 : IPLS(std::move(IPLS)) {}
624
625void LookupState::reset(InProgressLookupState *IPLS) { this->IPLS.reset(IPLS); }
626
627LookupState::LookupState() = default;
628LookupState::LookupState(LookupState &&) = default;
629LookupState &LookupState::operator=(LookupState &&) = default;
630LookupState::~LookupState() = default;
631
633 assert(IPLS && "Cannot call continueLookup on empty LookupState");
634 auto &ES = IPLS->SearchOrder.begin()->first->getExecutionSession();
635 ES.OL_applyQueryPhase1(std::move(IPLS), std::move(Err));
636}
637
639 std::deque<LookupState> LookupsToFail;
640 {
641 std::lock_guard<std::mutex> Lock(M);
642 std::swap(PendingLookups, LookupsToFail);
643 InUse = false;
644 }
645
646 for (auto &LS : LookupsToFail)
647 LS.continueLookup(make_error<StringError>(
648 "Query waiting on DefinitionGenerator that was destroyed",
650}
651
653 LLVM_DEBUG(dbgs() << "Destroying JITDylib " << getName() << "\n");
654}
655
657 std::vector<ResourceTrackerSP> TrackersToRemove;
658 ES.runSessionLocked([&]() {
659 assert(State != Closed && "JD is defunct");
660 for (auto &KV : TrackerSymbols)
661 TrackersToRemove.push_back(KV.first);
662 TrackersToRemove.push_back(getDefaultResourceTracker());
663 });
664
665 Error Err = Error::success();
666 for (auto &RT : TrackersToRemove)
667 Err = joinErrors(std::move(Err), RT->remove());
668 return Err;
669}
670
672 return ES.runSessionLocked([this] {
673 assert(State != Closed && "JD is defunct");
674 if (!DefaultTracker)
675 DefaultTracker = new ResourceTracker(this);
676 return DefaultTracker;
677 });
678}
679
681 return ES.runSessionLocked([this] {
682 assert(State == Open && "JD is defunct");
683 ResourceTrackerSP RT = new ResourceTracker(this);
684 return RT;
685 });
686}
687
689 // DefGenerator moved into TmpDG to ensure that it's destroyed outside the
690 // session lock (since it may have to send errors to pending queries).
691 std::shared_ptr<DefinitionGenerator> TmpDG;
692
693 ES.runSessionLocked([&] {
694 assert(State == Open && "JD is defunct");
695 auto I = llvm::find_if(DefGenerators,
696 [&](const std::shared_ptr<DefinitionGenerator> &H) {
697 return H.get() == &G;
698 });
699 assert(I != DefGenerators.end() && "Generator not found");
700 TmpDG = std::move(*I);
701 DefGenerators.erase(I);
702 });
703}
704
706JITDylib::defineMaterializing(MaterializationResponsibility &FromMR,
707 SymbolFlagsMap SymbolFlags) {
708
709 return ES.runSessionLocked([&]() -> Expected<SymbolFlagsMap> {
710 if (FromMR.RT->isDefunct())
711 return make_error<ResourceTrackerDefunct>(FromMR.RT);
712
713 std::vector<NonOwningSymbolStringPtr> AddedSyms;
714 std::vector<NonOwningSymbolStringPtr> RejectedWeakDefs;
715
716 for (auto SFItr = SymbolFlags.begin(), SFEnd = SymbolFlags.end();
717 SFItr != SFEnd; ++SFItr) {
718
719 auto &Name = SFItr->first;
720 auto &Flags = SFItr->second;
721
722 auto EntryItr = Symbols.find(Name);
723
724 // If the entry already exists...
725 if (EntryItr != Symbols.end()) {
726
727 // If this is a strong definition then error out.
728 if (!Flags.isWeak()) {
729 // Remove any symbols already added.
730 for (auto &S : AddedSyms)
731 Symbols.erase(Symbols.find_as(S));
732
733 // FIXME: Return all duplicates.
735 std::string(*Name), "defineMaterializing operation");
736 }
737
738 // Otherwise just make a note to discard this symbol after the loop.
739 RejectedWeakDefs.push_back(NonOwningSymbolStringPtr(Name));
740 continue;
741 } else
742 EntryItr =
743 Symbols.insert(std::make_pair(Name, SymbolTableEntry(Flags))).first;
744
745 AddedSyms.push_back(NonOwningSymbolStringPtr(Name));
746 EntryItr->second.setState(SymbolState::Materializing);
747 }
748
749 // Remove any rejected weak definitions from the SymbolFlags map.
750 while (!RejectedWeakDefs.empty()) {
751 SymbolFlags.erase(SymbolFlags.find_as(RejectedWeakDefs.back()));
752 RejectedWeakDefs.pop_back();
753 }
754
755 return SymbolFlags;
756 });
757}
758
759Error JITDylib::replace(MaterializationResponsibility &FromMR,
760 std::unique_ptr<MaterializationUnit> MU) {
761 assert(MU != nullptr && "Can not replace with a null MaterializationUnit");
762 std::unique_ptr<MaterializationUnit> MustRunMU;
763 std::unique_ptr<MaterializationResponsibility> MustRunMR;
764
765 auto Err =
766 ES.runSessionLocked([&, this]() -> Error {
767 if (FromMR.RT->isDefunct())
768 return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
769
770#ifndef NDEBUG
771 for (auto &KV : MU->getSymbols()) {
772 auto SymI = Symbols.find(KV.first);
773 assert(SymI != Symbols.end() && "Replacing unknown symbol");
774 assert(SymI->second.getState() == SymbolState::Materializing &&
775 "Can not replace a symbol that ha is not materializing");
776 assert(!SymI->second.hasMaterializerAttached() &&
777 "Symbol should not have materializer attached already");
778 assert(UnmaterializedInfos.count(KV.first) == 0 &&
779 "Symbol being replaced should have no UnmaterializedInfo");
780 }
781#endif // NDEBUG
782
783 // If the tracker is defunct we need to bail out immediately.
784
785 // If any symbol has pending queries against it then we need to
786 // materialize MU immediately.
787 for (auto &KV : MU->getSymbols()) {
788 auto MII = MaterializingInfos.find(KV.first);
789 if (MII != MaterializingInfos.end()) {
790 if (MII->second.hasQueriesPending()) {
791 MustRunMR = ES.createMaterializationResponsibility(
792 *FromMR.RT, std::move(MU->SymbolFlags),
793 std::move(MU->InitSymbol));
794 MustRunMU = std::move(MU);
795 return Error::success();
796 }
797 }
798 }
799
800 // Otherwise, make MU responsible for all the symbols.
801 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU),
802 FromMR.RT.get());
803 for (auto &KV : UMI->MU->getSymbols()) {
804 auto SymI = Symbols.find(KV.first);
805 assert(SymI->second.getState() == SymbolState::Materializing &&
806 "Can not replace a symbol that is not materializing");
807 assert(!SymI->second.hasMaterializerAttached() &&
808 "Can not replace a symbol that has a materializer attached");
809 assert(UnmaterializedInfos.count(KV.first) == 0 &&
810 "Unexpected materializer entry in map");
811 SymI->second.setAddress(SymI->second.getAddress());
812 SymI->second.setMaterializerAttached(true);
813
814 auto &UMIEntry = UnmaterializedInfos[KV.first];
815 assert((!UMIEntry || !UMIEntry->MU) &&
816 "Replacing symbol with materializer still attached");
817 UMIEntry = UMI;
818 }
819
820 return Error::success();
821 });
822
823 if (Err)
824 return Err;
825
826 if (MustRunMU) {
827 assert(MustRunMR && "MustRunMU set implies MustRunMR set");
828 ES.dispatchTask(std::make_unique<MaterializationTask>(
829 std::move(MustRunMU), std::move(MustRunMR)));
830 } else {
831 assert(!MustRunMR && "MustRunMU unset implies MustRunMR unset");
832 }
833
834 return Error::success();
835}
836
837Expected<std::unique_ptr<MaterializationResponsibility>>
838JITDylib::delegate(MaterializationResponsibility &FromMR,
839 SymbolFlagsMap SymbolFlags, SymbolStringPtr InitSymbol) {
840
841 return ES.runSessionLocked(
842 [&]() -> Expected<std::unique_ptr<MaterializationResponsibility>> {
843 if (FromMR.RT->isDefunct())
844 return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
845
846 return ES.createMaterializationResponsibility(
847 *FromMR.RT, std::move(SymbolFlags), std::move(InitSymbol));
848 });
849}
850
852JITDylib::getRequestedSymbols(const SymbolFlagsMap &SymbolFlags) const {
853 return ES.runSessionLocked([&]() {
854 SymbolNameSet RequestedSymbols;
855
856 for (auto &KV : SymbolFlags) {
857 assert(Symbols.count(KV.first) && "JITDylib does not cover this symbol?");
858 assert(Symbols.find(KV.first)->second.getState() !=
860 Symbols.find(KV.first)->second.getState() != SymbolState::Ready &&
861 "getRequestedSymbols can only be called for symbols that have "
862 "started materializing");
863 auto I = MaterializingInfos.find(KV.first);
864 if (I == MaterializingInfos.end())
865 continue;
866
867 if (I->second.hasQueriesPending())
868 RequestedSymbols.insert(KV.first);
869 }
870
871 return RequestedSymbols;
872 });
873}
874
875Error JITDylib::resolve(MaterializationResponsibility &MR,
876 const SymbolMap &Resolved) {
877 AsynchronousSymbolQuerySet CompletedQueries;
878
879 if (auto Err = ES.runSessionLocked([&, this]() -> Error {
880 if (MR.RT->isDefunct())
881 return make_error<ResourceTrackerDefunct>(MR.RT);
882
883 if (State != Open)
884 return make_error<StringError>("JITDylib " + getName() +
885 " is defunct",
886 inconvertibleErrorCode());
887
888 struct WorklistEntry {
889 SymbolTable::iterator SymI;
890 ExecutorSymbolDef ResolvedSym;
891 };
892
893 SymbolNameSet SymbolsInErrorState;
894 std::vector<WorklistEntry> Worklist;
895 Worklist.reserve(Resolved.size());
896
897 // Build worklist and check for any symbols in the error state.
898 for (const auto &KV : Resolved) {
899
900 assert(!KV.second.getFlags().hasError() &&
901 "Resolution result can not have error flag set");
902
903 auto SymI = Symbols.find(KV.first);
904
905 assert(SymI != Symbols.end() && "Symbol not found");
906 assert(!SymI->second.hasMaterializerAttached() &&
907 "Resolving symbol with materializer attached?");
908 assert(SymI->second.getState() == SymbolState::Materializing &&
909 "Symbol should be materializing");
910 assert(SymI->second.getAddress() == ExecutorAddr() &&
911 "Symbol has already been resolved");
912
913 if (SymI->second.getFlags().hasError())
914 SymbolsInErrorState.insert(KV.first);
915 else {
916 if (SymI->second.getFlags() & JITSymbolFlags::Common) {
917 [[maybe_unused]] auto WeakOrCommon =
919 assert((KV.second.getFlags() & WeakOrCommon) &&
920 "Common symbols must be resolved as common or weak");
921 assert((KV.second.getFlags() & ~WeakOrCommon) ==
922 (SymI->second.getFlags() & ~JITSymbolFlags::Common) &&
923 "Resolving symbol with incorrect flags");
924
925 } else
926 assert(KV.second.getFlags() == SymI->second.getFlags() &&
927 "Resolved flags should match the declared flags");
928
929 Worklist.push_back(
930 {SymI, {KV.second.getAddress(), SymI->second.getFlags()}});
931 }
932 }
933
934 // If any symbols were in the error state then bail out.
935 if (!SymbolsInErrorState.empty()) {
936 auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
937 (*FailedSymbolsDepMap)[this] = std::move(SymbolsInErrorState);
938 return make_error<FailedToMaterialize>(
939 getExecutionSession().getSymbolStringPool(),
940 std::move(FailedSymbolsDepMap));
941 }
942
943 while (!Worklist.empty()) {
944 auto SymI = Worklist.back().SymI;
945 auto ResolvedSym = Worklist.back().ResolvedSym;
946 Worklist.pop_back();
947
948 auto &Name = SymI->first;
949
950 // Resolved symbols can not be weak: discard the weak flag.
951 JITSymbolFlags ResolvedFlags = ResolvedSym.getFlags();
952 SymI->second.setAddress(ResolvedSym.getAddress());
953 SymI->second.setFlags(ResolvedFlags);
954 SymI->second.setState(SymbolState::Resolved);
955
956 auto MII = MaterializingInfos.find(Name);
957 if (MII == MaterializingInfos.end())
958 continue;
959
960 auto &MI = MII->second;
961 for (auto &Q : MI.takeQueriesMeeting(SymbolState::Resolved)) {
962 Q->notifySymbolMetRequiredState(Name, ResolvedSym);
963 if (Q->isComplete())
964 CompletedQueries.insert(std::move(Q));
965 }
966 }
967
968 return Error::success();
969 }))
970 return Err;
971
972 // Otherwise notify all the completed queries.
973 for (auto &Q : CompletedQueries) {
974 assert(Q->isComplete() && "Q not completed");
975 Q->handleComplete(ES);
976 }
977
978 return Error::success();
979}
980
981void JITDylib::unlinkMaterializationResponsibility(
982 MaterializationResponsibility &MR) {
983 ES.runSessionLocked([&]() {
984 auto I = TrackerMRs.find(MR.RT.get());
985 assert(I != TrackerMRs.end() && "No MRs in TrackerMRs list for RT");
986 assert(I->second.count(&MR) && "MR not in TrackerMRs list for RT");
987 I->second.erase(&MR);
988 if (I->second.empty())
989 TrackerMRs.erase(MR.RT.get());
990 });
991}
992
993void JITDylib::shrinkMaterializationInfoMemory() {
994 // DenseMap::erase never shrinks its storage; use clear to heuristically free
995 // memory since we may have long-lived JDs after linking is done.
996
997 if (UnmaterializedInfos.empty())
998 UnmaterializedInfos.clear();
999
1000 if (MaterializingInfos.empty())
1001 MaterializingInfos.clear();
1002}
1003
1005 bool LinkAgainstThisJITDylibFirst) {
1006 ES.runSessionLocked([&]() {
1007 assert(State == Open && "JD is defunct");
1008 if (LinkAgainstThisJITDylibFirst) {
1009 LinkOrder.clear();
1010 if (NewLinkOrder.empty() || NewLinkOrder.front().first != this)
1011 LinkOrder.push_back(
1012 std::make_pair(this, JITDylibLookupFlags::MatchAllSymbols));
1013 llvm::append_range(LinkOrder, NewLinkOrder);
1014 } else
1015 LinkOrder = std::move(NewLinkOrder);
1016 });
1017}
1018
1020 ES.runSessionLocked([&]() {
1021 for (auto &KV : NewLinks) {
1022 // Skip elements of NewLinks that are already in the link order.
1023 if (llvm::is_contained(LinkOrder, KV))
1024 continue;
1025
1026 LinkOrder.push_back(std::move(KV));
1027 }
1028 });
1029}
1030
1032 ES.runSessionLocked([&]() { LinkOrder.push_back({&JD, JDLookupFlags}); });
1033}
1034
1036 JITDylibLookupFlags JDLookupFlags) {
1037 ES.runSessionLocked([&]() {
1038 assert(State == Open && "JD is defunct");
1039 for (auto &KV : LinkOrder)
1040 if (KV.first == &OldJD) {
1041 KV = {&NewJD, JDLookupFlags};
1042 break;
1043 }
1044 });
1045}
1046
1048 ES.runSessionLocked([&]() {
1049 assert(State == Open && "JD is defunct");
1050 auto I = llvm::find_if(LinkOrder,
1051 [&](const JITDylibSearchOrder::value_type &KV) {
1052 return KV.first == &JD;
1053 });
1054 if (I != LinkOrder.end())
1055 LinkOrder.erase(I);
1056 });
1057}
1058
1060 return ES.runSessionLocked([&]() -> Error {
1061 assert(State == Open && "JD is defunct");
1062 using SymbolMaterializerItrPair =
1063 std::pair<SymbolTable::iterator, UnmaterializedInfosMap::iterator>;
1064 std::vector<SymbolMaterializerItrPair> SymbolsToRemove;
1065 SymbolNameSet Missing;
1067
1068 for (auto &Name : Names) {
1069 auto I = Symbols.find(Name);
1070
1071 // Note symbol missing.
1072 if (I == Symbols.end()) {
1073 Missing.insert(Name);
1074 continue;
1075 }
1076
1077 // Note symbol materializing.
1078 if (I->second.getState() != SymbolState::NeverSearched &&
1079 I->second.getState() != SymbolState::Ready) {
1080 Materializing.insert(Name);
1081 continue;
1082 }
1083
1084 auto UMII = I->second.hasMaterializerAttached()
1085 ? UnmaterializedInfos.find(Name)
1086 : UnmaterializedInfos.end();
1087 SymbolsToRemove.push_back(std::make_pair(I, UMII));
1088 }
1089
1090 // If any of the symbols are not defined, return an error.
1091 if (!Missing.empty())
1092 return make_error<SymbolsNotFound>(ES.getSymbolStringPool(),
1093 std::move(Missing));
1094
1095 // If any of the symbols are currently materializing, return an error.
1096 if (!Materializing.empty())
1097 return make_error<SymbolsCouldNotBeRemoved>(ES.getSymbolStringPool(),
1098 std::move(Materializing));
1099
1100 // Remove the symbols.
1101 for (auto &SymbolMaterializerItrPair : SymbolsToRemove) {
1102 auto UMII = SymbolMaterializerItrPair.second;
1103
1104 // If there is a materializer attached, call discard.
1105 if (UMII != UnmaterializedInfos.end()) {
1106 UMII->second->MU->doDiscard(*this, UMII->first);
1107 UnmaterializedInfos.erase(UMII);
1108 }
1109
1110 auto SymI = SymbolMaterializerItrPair.first;
1111 Symbols.erase(SymI);
1112 }
1113
1114 shrinkMaterializationInfoMemory();
1115
1116 return Error::success();
1117 });
1118}
1119
1121 ES.runSessionLocked([&, this]() {
1122 OS << "JITDylib \"" << getName() << "\" (ES: "
1123 << format("0x%016" PRIx64, reinterpret_cast<uintptr_t>(&ES))
1124 << ", State = ";
1125 switch (State) {
1126 case Open:
1127 OS << "Open";
1128 break;
1129 case Closing:
1130 OS << "Closing";
1131 break;
1132 case Closed:
1133 OS << "Closed";
1134 break;
1135 }
1136 OS << ")\n";
1137 if (State == Closed)
1138 return;
1139 OS << "Link order: " << LinkOrder << "\n"
1140 << "Symbol table:\n";
1141
1142 // Sort symbols so we get a deterministic order and can check them in tests.
1143 std::vector<std::pair<SymbolStringPtr, SymbolTableEntry *>> SymbolsSorted;
1144 for (auto &KV : Symbols)
1145 SymbolsSorted.emplace_back(KV.first, &KV.second);
1146 std::sort(SymbolsSorted.begin(), SymbolsSorted.end(),
1147 [](const auto &L, const auto &R) { return *L.first < *R.first; });
1148
1149 for (auto &KV : SymbolsSorted) {
1150 OS << " \"" << *KV.first << "\": ";
1151 if (auto Addr = KV.second->getAddress())
1152 OS << Addr;
1153 else
1154 OS << "<not resolved> ";
1155
1156 OS << " " << KV.second->getFlags() << " " << KV.second->getState();
1157
1158 if (KV.second->hasMaterializerAttached()) {
1159 OS << " (Materializer ";
1160 auto I = UnmaterializedInfos.find(KV.first);
1161 assert(I != UnmaterializedInfos.end() &&
1162 "Lazy symbol should have UnmaterializedInfo");
1163 OS << I->second->MU.get() << ", " << I->second->MU->getName() << ")\n";
1164 } else
1165 OS << "\n";
1166 }
1167
1168 if (!MaterializingInfos.empty())
1169 OS << " MaterializingInfos entries:\n";
1170 for (auto &KV : MaterializingInfos) {
1171 OS << " \"" << *KV.first << "\":\n"
1172 << " " << KV.second.pendingQueries().size()
1173 << " pending queries: { ";
1174 for (const auto &Q : KV.second.pendingQueries())
1175 OS << Q.get() << " (" << Q->getRequiredState() << ") ";
1176 OS << "}\n";
1177 }
1178 });
1179}
1180
1181void JITDylib::MaterializingInfo::addQuery(
1182 std::shared_ptr<AsynchronousSymbolQuery> Q) {
1183
1184 auto I = llvm::lower_bound(
1185 llvm::reverse(PendingQueries), Q->getRequiredState(),
1186 [](const std::shared_ptr<AsynchronousSymbolQuery> &V, SymbolState S) {
1187 return V->getRequiredState() <= S;
1188 });
1189 PendingQueries.insert(I.base(), std::move(Q));
1190}
1191
1192void JITDylib::MaterializingInfo::removeQuery(
1193 const AsynchronousSymbolQuery &Q) {
1194 // FIXME: Implement 'find_as' for shared_ptr<T>/T*.
1195 auto I = llvm::find_if(
1196 PendingQueries, [&Q](const std::shared_ptr<AsynchronousSymbolQuery> &V) {
1197 return V.get() == &Q;
1198 });
1199 if (I != PendingQueries.end())
1200 PendingQueries.erase(I);
1201}
1202
1203JITDylib::AsynchronousSymbolQueryList
1204JITDylib::MaterializingInfo::takeQueriesMeeting(SymbolState RequiredState) {
1205 AsynchronousSymbolQueryList Result;
1206 while (!PendingQueries.empty()) {
1207 if (PendingQueries.back()->getRequiredState() > RequiredState)
1208 break;
1209
1210 Result.push_back(std::move(PendingQueries.back()));
1211 PendingQueries.pop_back();
1212 }
1213
1214 return Result;
1215}
1216
1217JITDylib::JITDylib(ExecutionSession &ES, std::string Name)
1218 : JITLinkDylib(std::move(Name)), ES(ES) {
1219 LinkOrder.push_back({this, JITDylibLookupFlags::MatchAllSymbols});
1220}
1221
1222JITDylib::RemoveTrackerResult JITDylib::IL_removeTracker(ResourceTracker &RT) {
1223 // Note: Should be called under the session lock.
1224 assert(State != Closed && "JD is defunct");
1225
1226 SymbolNameVector SymbolsToRemove;
1227 SymbolNameVector SymbolsToFail;
1228
1229 if (&RT == DefaultTracker.get()) {
1230 SymbolNameSet TrackedSymbols;
1231 for (auto &KV : TrackerSymbols)
1232 TrackedSymbols.insert_range(KV.second);
1233
1234 for (auto &KV : Symbols) {
1235 auto &Sym = KV.first;
1236 if (!TrackedSymbols.count(Sym))
1237 SymbolsToRemove.push_back(Sym);
1238 }
1239
1240 DefaultTracker.reset();
1241 } else {
1242 /// Check for a non-default tracker.
1243 auto I = TrackerSymbols.find(&RT);
1244 if (I != TrackerSymbols.end()) {
1245 SymbolsToRemove = std::move(I->second);
1246 TrackerSymbols.erase(I);
1247 }
1248 // ... if not found this tracker was already defunct. Nothing to do.
1249 }
1250
1251 for (auto &Sym : SymbolsToRemove) {
1252 assert(Symbols.count(Sym) && "Symbol not in symbol table");
1253
1254 // If there is a MaterializingInfo then collect any queries to fail.
1255 auto MII = MaterializingInfos.find(Sym);
1256 if (MII != MaterializingInfos.end())
1257 SymbolsToFail.push_back(Sym);
1258 }
1259
1260 auto [QueriesToFail, FailedSymbols] =
1261 ES.IL_failSymbols(*this, std::move(SymbolsToFail));
1262
1263 std::vector<std::unique_ptr<MaterializationUnit>> DefunctMUs;
1264
1265 // Removed symbols should be taken out of the table altogether.
1266 for (auto &Sym : SymbolsToRemove) {
1267 auto I = Symbols.find(Sym);
1268 assert(I != Symbols.end() && "Symbol not present in table");
1269
1270 // Remove Materializer if present.
1271 if (I->second.hasMaterializerAttached()) {
1272 // FIXME: Should this discard the symbols?
1273 auto J = UnmaterializedInfos.find(Sym);
1274 assert(J != UnmaterializedInfos.end() &&
1275 "Symbol table indicates MU present, but no UMI record");
1276 if (J->second->MU)
1277 DefunctMUs.push_back(std::move(J->second->MU));
1278 UnmaterializedInfos.erase(J);
1279 } else {
1280 assert(!UnmaterializedInfos.count(Sym) &&
1281 "Symbol has materializer attached");
1282 }
1283
1284 Symbols.erase(I);
1285 }
1286
1287 shrinkMaterializationInfoMemory();
1288
1289 return {std::move(QueriesToFail), std::move(FailedSymbols),
1290 std::move(DefunctMUs)};
1291}
1292
1293void JITDylib::transferTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT) {
1294 assert(State != Closed && "JD is defunct");
1295 assert(&DstRT != &SrcRT && "No-op transfers shouldn't call transferTracker");
1296 assert(&DstRT.getJITDylib() == this && "DstRT is not for this JITDylib");
1297 assert(&SrcRT.getJITDylib() == this && "SrcRT is not for this JITDylib");
1298
1299 // Update trackers for any not-yet materialized units.
1300 for (auto &KV : UnmaterializedInfos) {
1301 if (KV.second->RT == &SrcRT)
1302 KV.second->RT = &DstRT;
1303 }
1304
1305 // Update trackers for any active materialization responsibilities.
1306 {
1307 auto I = TrackerMRs.find(&SrcRT);
1308 if (I != TrackerMRs.end()) {
1309 auto &SrcMRs = I->second;
1310 auto &DstMRs = TrackerMRs[&DstRT];
1311 for (auto *MR : SrcMRs)
1312 MR->RT = &DstRT;
1313 if (DstMRs.empty())
1314 DstMRs = std::move(SrcMRs);
1315 else
1316 DstMRs.insert_range(SrcMRs);
1317 // Erase SrcRT entry in TrackerMRs. Use &SrcRT key rather than iterator I
1318 // for this, since I may have been invalidated by 'TrackerMRs[&DstRT]'.
1319 TrackerMRs.erase(&SrcRT);
1320 }
1321 }
1322
1323 // If we're transfering to the default tracker we just need to delete the
1324 // tracked symbols for the source tracker.
1325 if (&DstRT == DefaultTracker.get()) {
1326 TrackerSymbols.erase(&SrcRT);
1327 return;
1328 }
1329
1330 // If we're transferring from the default tracker we need to find all
1331 // currently untracked symbols.
1332 if (&SrcRT == DefaultTracker.get()) {
1333 assert(!TrackerSymbols.count(&SrcRT) &&
1334 "Default tracker should not appear in TrackerSymbols");
1335
1336 SymbolNameVector SymbolsToTrack;
1337
1338 SymbolNameSet CurrentlyTrackedSymbols;
1339 for (auto &KV : TrackerSymbols)
1340 CurrentlyTrackedSymbols.insert_range(KV.second);
1341
1342 for (auto &KV : Symbols) {
1343 auto &Sym = KV.first;
1344 if (!CurrentlyTrackedSymbols.count(Sym))
1345 SymbolsToTrack.push_back(Sym);
1346 }
1347
1348 TrackerSymbols[&DstRT] = std::move(SymbolsToTrack);
1349 return;
1350 }
1351
1352 auto &DstTrackedSymbols = TrackerSymbols[&DstRT];
1353
1354 // Finally if neither SrtRT or DstRT are the default tracker then
1355 // just append DstRT's tracked symbols to SrtRT's.
1356 auto SI = TrackerSymbols.find(&SrcRT);
1357 if (SI == TrackerSymbols.end())
1358 return;
1359
1360 DstTrackedSymbols.reserve(DstTrackedSymbols.size() + SI->second.size());
1361 for (auto &Sym : SI->second)
1362 DstTrackedSymbols.push_back(std::move(Sym));
1363 TrackerSymbols.erase(SI);
1364}
1365
1366Error JITDylib::defineImpl(MaterializationUnit &MU) {
1367 LLVM_DEBUG({ dbgs() << " " << MU.getSymbols() << "\n"; });
1368
1369 SymbolNameSet Duplicates;
1370 std::vector<SymbolStringPtr> ExistingDefsOverridden;
1371 std::vector<SymbolStringPtr> MUDefsOverridden;
1372
1373 for (const auto &KV : MU.getSymbols()) {
1374 auto I = Symbols.find(KV.first);
1375
1376 if (I != Symbols.end()) {
1377 if (KV.second.isStrong()) {
1378 if (I->second.getFlags().isStrong() ||
1379 I->second.getState() > SymbolState::NeverSearched)
1380 Duplicates.insert(KV.first);
1381 else {
1382 assert(I->second.getState() == SymbolState::NeverSearched &&
1383 "Overridden existing def should be in the never-searched "
1384 "state");
1385 ExistingDefsOverridden.push_back(KV.first);
1386 }
1387 } else
1388 MUDefsOverridden.push_back(KV.first);
1389 }
1390 }
1391
1392 // If there were any duplicate definitions then bail out.
1393 if (!Duplicates.empty()) {
1394 LLVM_DEBUG(
1395 { dbgs() << " Error: Duplicate symbols " << Duplicates << "\n"; });
1396 return make_error<DuplicateDefinition>(std::string(**Duplicates.begin()),
1397 MU.getName().str());
1398 }
1399
1400 // Discard any overridden defs in this MU.
1401 LLVM_DEBUG({
1402 if (!MUDefsOverridden.empty())
1403 dbgs() << " Defs in this MU overridden: " << MUDefsOverridden << "\n";
1404 });
1405 for (auto &S : MUDefsOverridden)
1406 MU.doDiscard(*this, S);
1407
1408 // Discard existing overridden defs.
1409 LLVM_DEBUG({
1410 if (!ExistingDefsOverridden.empty())
1411 dbgs() << " Existing defs overridden by this MU: " << MUDefsOverridden
1412 << "\n";
1413 });
1414 for (auto &S : ExistingDefsOverridden) {
1415
1416 auto UMII = UnmaterializedInfos.find(S);
1417 assert(UMII != UnmaterializedInfos.end() &&
1418 "Overridden existing def should have an UnmaterializedInfo");
1419 UMII->second->MU->doDiscard(*this, S);
1420 }
1421
1422 // Finally, add the defs from this MU.
1423 for (auto &KV : MU.getSymbols()) {
1424 auto &SymEntry = Symbols[KV.first];
1425 SymEntry.setFlags(KV.second);
1426 SymEntry.setState(SymbolState::NeverSearched);
1427 SymEntry.setMaterializerAttached(true);
1428 }
1429
1430 return Error::success();
1431}
1432
1433void JITDylib::installMaterializationUnit(
1434 std::unique_ptr<MaterializationUnit> MU, ResourceTracker &RT) {
1435
1436 /// defineImpl succeeded.
1437 if (&RT != DefaultTracker.get()) {
1438 auto &TS = TrackerSymbols[&RT];
1439 TS.reserve(TS.size() + MU->getSymbols().size());
1440 for (auto &KV : MU->getSymbols())
1441 TS.push_back(KV.first);
1442 }
1443
1444 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU), &RT);
1445 for (auto &KV : UMI->MU->getSymbols())
1446 UnmaterializedInfos[KV.first] = UMI;
1447}
1448
1449void JITDylib::detachQueryHelper(AsynchronousSymbolQuery &Q,
1450 const SymbolNameSet &QuerySymbols) {
1451 for (auto &QuerySymbol : QuerySymbols) {
1452 auto MII = MaterializingInfos.find(QuerySymbol);
1453 if (MII != MaterializingInfos.end())
1454 MII->second.removeQuery(Q);
1455 }
1456}
1457
1458Platform::~Platform() = default;
1459
1461 ExecutionSession &ES,
1462 const DenseMap<JITDylib *, SymbolLookupSet> &InitSyms) {
1463
1464 DenseMap<JITDylib *, SymbolMap> CompoundResult;
1465 Error CompoundErr = Error::success();
1466 std::mutex LookupMutex;
1467 std::condition_variable CV;
1468 uint64_t Count = InitSyms.size();
1469
1470 LLVM_DEBUG({
1471 dbgs() << "Issuing init-symbol lookup:\n";
1472 for (auto &KV : InitSyms)
1473 dbgs() << " " << KV.first->getName() << ": " << KV.second << "\n";
1474 });
1475
1476 for (auto &KV : InitSyms) {
1477 auto *JD = KV.first;
1478 auto Names = std::move(KV.second);
1479 ES.lookup(
1482 std::move(Names), SymbolState::Ready,
1483 [&, JD](Expected<SymbolMap> Result) {
1484 {
1485 std::lock_guard<std::mutex> Lock(LookupMutex);
1486 --Count;
1487 if (Result) {
1488 assert(!CompoundResult.count(JD) &&
1489 "Duplicate JITDylib in lookup?");
1490 CompoundResult[JD] = std::move(*Result);
1491 } else
1492 CompoundErr =
1493 joinErrors(std::move(CompoundErr), Result.takeError());
1494 }
1495 CV.notify_one();
1496 },
1498 }
1499
1500 std::unique_lock<std::mutex> Lock(LookupMutex);
1501 CV.wait(Lock, [&] { return Count == 0; });
1502
1503 if (CompoundErr)
1504 return std::move(CompoundErr);
1505
1506 return std::move(CompoundResult);
1507}
1508
1510 unique_function<void(Error)> OnComplete, ExecutionSession &ES,
1511 const DenseMap<JITDylib *, SymbolLookupSet> &InitSyms) {
1512
1513 class TriggerOnComplete {
1514 public:
1515 using OnCompleteFn = unique_function<void(Error)>;
1516 TriggerOnComplete(OnCompleteFn OnComplete)
1517 : OnComplete(std::move(OnComplete)) {}
1518 ~TriggerOnComplete() { OnComplete(std::move(LookupResult)); }
1519 void reportResult(Error Err) {
1520 std::lock_guard<std::mutex> Lock(ResultMutex);
1521 LookupResult = joinErrors(std::move(LookupResult), std::move(Err));
1522 }
1523
1524 private:
1525 std::mutex ResultMutex;
1526 Error LookupResult{Error::success()};
1527 OnCompleteFn OnComplete;
1528 };
1529
1530 LLVM_DEBUG({
1531 dbgs() << "Issuing init-symbol lookup:\n";
1532 for (auto &KV : InitSyms)
1533 dbgs() << " " << KV.first->getName() << ": " << KV.second << "\n";
1534 });
1535
1536 auto TOC = std::make_shared<TriggerOnComplete>(std::move(OnComplete));
1537
1538 for (auto &KV : InitSyms) {
1539 auto *JD = KV.first;
1540 auto Names = std::move(KV.second);
1541 ES.lookup(
1544 std::move(Names), SymbolState::Ready,
1546 TOC->reportResult(Result.takeError());
1547 },
1549 }
1550}
1551
1553 // If this task wasn't run then fail materialization.
1554 if (MR)
1555 MR->failMaterialization();
1556}
1557
1559 OS << "Materialization task: " << MU->getName() << " in "
1560 << MR->getTargetJITDylib().getName();
1561}
1562
1564 assert(MU && "MU should not be null");
1565 assert(MR && "MR should not be null");
1566 MU->materialize(std::move(MR));
1567}
1568
1569void LookupTask::printDescription(raw_ostream &OS) { OS << "Lookup task"; }
1570
1571void LookupTask::run() { LS.continueLookup(Error::success()); }
1572
1573ExecutionSession::ExecutionSession(std::unique_ptr<ExecutorProcessControl> EPC)
1574 : EPC(std::move(EPC)) {
1575 // Associated EPC and this.
1576 this->EPC->ES = this;
1577}
1578
1580 // You must call endSession prior to destroying the session.
1581 assert(!SessionOpen &&
1582 "Session still open. Did you forget to call endSession?");
1583}
1584
1586 LLVM_DEBUG(dbgs() << "Ending ExecutionSession " << this << "\n");
1587
1588 auto JDsToRemove = runSessionLocked([&] {
1589
1590#ifdef EXPENSIVE_CHECKS
1591 verifySessionState("Entering ExecutionSession::endSession");
1592#endif
1593
1594 SessionOpen = false;
1595 return JDs;
1596 });
1597
1598 std::reverse(JDsToRemove.begin(), JDsToRemove.end());
1599
1600 auto Err = removeJITDylibs(std::move(JDsToRemove));
1601
1602 Err = joinErrors(std::move(Err), EPC->disconnect());
1603
1604 return Err;
1605}
1606
1608 runSessionLocked([&] { ResourceManagers.push_back(&RM); });
1609}
1610
1612 runSessionLocked([&] {
1613 assert(!ResourceManagers.empty() && "No managers registered");
1614 if (ResourceManagers.back() == &RM)
1615 ResourceManagers.pop_back();
1616 else {
1617 auto I = llvm::find(ResourceManagers, &RM);
1618 assert(I != ResourceManagers.end() && "RM not registered");
1619 ResourceManagers.erase(I);
1620 }
1621 });
1622}
1623
1625 return runSessionLocked([&, this]() -> JITDylib * {
1626 for (auto &JD : JDs)
1627 if (JD->getName() == Name)
1628 return JD.get();
1629 return nullptr;
1630 });
1631}
1632
1634 assert(!getJITDylibByName(Name) && "JITDylib with that name already exists");
1635 return runSessionLocked([&, this]() -> JITDylib & {
1636 assert(SessionOpen && "Cannot create JITDylib after session is closed");
1637 JDs.push_back(new JITDylib(*this, std::move(Name)));
1638 return *JDs.back();
1639 });
1640}
1641
1643 auto &JD = createBareJITDylib(Name);
1644 if (P)
1645 if (auto Err = P->setupJITDylib(JD))
1646 return std::move(Err);
1647 return JD;
1648}
1649
1650Error ExecutionSession::removeJITDylibs(std::vector<JITDylibSP> JDsToRemove) {
1651 // Set JD to 'Closing' state and remove JD from the ExecutionSession.
1652 runSessionLocked([&] {
1653 for (auto &JD : JDsToRemove) {
1654 assert(JD->State == JITDylib::Open && "JD already closed");
1655 JD->State = JITDylib::Closing;
1656 auto I = llvm::find(JDs, JD);
1657 assert(I != JDs.end() && "JD does not appear in session JDs");
1658 JDs.erase(I);
1659 }
1660 });
1661
1662 // Clear JITDylibs and notify the platform.
1663 Error Err = Error::success();
1664 for (auto JD : JDsToRemove) {
1665 Err = joinErrors(std::move(Err), JD->clear());
1666 if (P)
1667 Err = joinErrors(std::move(Err), P->teardownJITDylib(*JD));
1668 }
1669
1670 // Set JD to closed state. Clear remaining data structures.
1671 runSessionLocked([&] {
1672 for (auto &JD : JDsToRemove) {
1673 assert(JD->State == JITDylib::Closing && "JD should be closing");
1674 JD->State = JITDylib::Closed;
1675 assert(JD->Symbols.empty() && "JD.Symbols is not empty after clear");
1676 assert(JD->UnmaterializedInfos.empty() &&
1677 "JD.UnmaterializedInfos is not empty after clear");
1678 assert(JD->MaterializingInfos.empty() &&
1679 "JD.MaterializingInfos is not empty after clear");
1680 assert(JD->TrackerSymbols.empty() &&
1681 "TrackerSymbols is not empty after clear");
1682 JD->DefGenerators.clear();
1683 JD->LinkOrder.clear();
1684 }
1685 });
1686
1687 return Err;
1688}
1689
1692 if (JDs.empty())
1693 return std::vector<JITDylibSP>();
1694
1695 auto &ES = JDs.front()->getExecutionSession();
1696 return ES.runSessionLocked([&]() -> Expected<std::vector<JITDylibSP>> {
1697 DenseSet<JITDylib *> Visited;
1698 std::vector<JITDylibSP> Result;
1699
1700 for (auto &JD : JDs) {
1701
1702 if (JD->State != Open)
1704 "Error building link order: " + JD->getName() + " is defunct",
1706 if (Visited.count(JD.get()))
1707 continue;
1708
1710 WorkStack.push_back(JD);
1711 Visited.insert(JD.get());
1712
1713 while (!WorkStack.empty()) {
1714 Result.push_back(std::move(WorkStack.back()));
1715 WorkStack.pop_back();
1716
1717 for (auto &KV : llvm::reverse(Result.back()->LinkOrder)) {
1718 auto &JD = *KV.first;
1719 if (!Visited.insert(&JD).second)
1720 continue;
1721 WorkStack.push_back(&JD);
1722 }
1723 }
1724 }
1725 return Result;
1726 });
1727}
1728
1731 auto Result = getDFSLinkOrder(JDs);
1732 if (Result)
1733 std::reverse(Result->begin(), Result->end());
1734 return Result;
1735}
1736
1740
1744
1746 LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet,
1747 unique_function<void(Expected<SymbolFlagsMap>)> OnComplete) {
1748
1749 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
1750 K, std::move(SearchOrder), std::move(LookupSet),
1751 std::move(OnComplete)),
1752 Error::success());
1753}
1754
1757 SymbolLookupSet LookupSet) {
1758
1759 std::promise<MSVCPExpected<SymbolFlagsMap>> ResultP;
1760 OL_applyQueryPhase1(std::make_unique<InProgressLookupFlagsState>(
1761 K, std::move(SearchOrder), std::move(LookupSet),
1762 [&ResultP](Expected<SymbolFlagsMap> Result) {
1763 ResultP.set_value(std::move(Result));
1764 }),
1765 Error::success());
1766
1767 auto ResultF = ResultP.get_future();
1768 return ResultF.get();
1769}
1770
1772 LookupKind K, const JITDylibSearchOrder &SearchOrder,
1773 SymbolLookupSet Symbols, SymbolState RequiredState,
1774 SymbolsResolvedCallback NotifyComplete,
1775 RegisterDependenciesFunction RegisterDependencies) {
1776
1777 LLVM_DEBUG({
1778 runSessionLocked([&]() {
1779 dbgs() << "Looking up " << Symbols << " in " << SearchOrder
1780 << " (required state: " << RequiredState << ")\n";
1781 });
1782 });
1783
1784 // lookup can be re-entered recursively if running on a single thread. Run any
1785 // outstanding MUs in case this query depends on them, otherwise this lookup
1786 // will starve waiting for a result from an MU that is stuck in the queue.
1787 dispatchOutstandingMUs();
1788
1789 auto Unresolved = std::move(Symbols);
1790 auto Q = std::make_shared<AsynchronousSymbolQuery>(Unresolved, RequiredState,
1791 std::move(NotifyComplete));
1792
1793 auto IPLS = std::make_unique<InProgressFullLookupState>(
1794 K, SearchOrder, std::move(Unresolved), RequiredState, std::move(Q),
1795 std::move(RegisterDependencies));
1796
1797 OL_applyQueryPhase1(std::move(IPLS), Error::success());
1798}
1799
1802 SymbolLookupSet Symbols, LookupKind K,
1803 SymbolState RequiredState,
1804 RegisterDependenciesFunction RegisterDependencies) {
1805#if LLVM_ENABLE_THREADS
1806 // In the threaded case we use promises to return the results.
1807 std::promise<MSVCPExpected<SymbolMap>> PromisedResult;
1808
1809 auto NotifyComplete = [&](Expected<SymbolMap> R) {
1810 PromisedResult.set_value(std::move(R));
1811 };
1812
1813#else
1815 Error ResolutionError = Error::success();
1816
1817 auto NotifyComplete = [&](Expected<SymbolMap> R) {
1818 ErrorAsOutParameter _(ResolutionError);
1819 if (R)
1820 Result = std::move(*R);
1821 else
1822 ResolutionError = R.takeError();
1823 };
1824#endif
1825
1826 // Perform the asynchronous lookup.
1827 lookup(K, SearchOrder, std::move(Symbols), RequiredState,
1828 std::move(NotifyComplete), RegisterDependencies);
1829
1830#if LLVM_ENABLE_THREADS
1831 return PromisedResult.get_future().get();
1832#else
1833 if (ResolutionError)
1834 return std::move(ResolutionError);
1835
1836 return Result;
1837#endif
1838}
1839
1842 SymbolStringPtr Name, SymbolState RequiredState) {
1843 SymbolLookupSet Names({Name});
1844
1845 if (auto ResultMap = lookup(SearchOrder, std::move(Names), LookupKind::Static,
1846 RequiredState, NoDependenciesToRegister)) {
1847 assert(ResultMap->size() == 1 && "Unexpected number of results");
1848 assert(ResultMap->count(Name) && "Missing result for symbol");
1849 return std::move(ResultMap->begin()->second);
1850 } else
1851 return ResultMap.takeError();
1852}
1853
1856 SymbolState RequiredState) {
1857 return lookup(makeJITDylibSearchOrder(SearchOrder), Name, RequiredState);
1858}
1859
1862 SymbolState RequiredState) {
1863 return lookup(SearchOrder, intern(Name), RequiredState);
1864}
1865
1868
1869 auto TagSyms = lookup({{&JD, JITDylibLookupFlags::MatchAllSymbols}},
1872 if (!TagSyms)
1873 return TagSyms.takeError();
1874
1875 // Associate tag addresses with implementations.
1876 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
1877
1878 // Check that no tags are being overwritten.
1879 for (auto &[TagName, TagSym] : *TagSyms) {
1880 auto TagAddr = TagSym.getAddress();
1881 if (JITDispatchHandlers.count(TagAddr))
1882 return make_error<StringError>("Tag " + formatv("{0:x}", TagAddr) +
1883 " (for " + *TagName +
1884 ") already registered",
1886 }
1887
1888 // At this point we're guaranteed to succeed. Install the handlers.
1889 for (auto &[TagName, TagSym] : *TagSyms) {
1890 auto TagAddr = TagSym.getAddress();
1891 auto I = WFs.find(TagName);
1892 assert(I != WFs.end() && I->second &&
1893 "JITDispatchHandler implementation missing");
1894 JITDispatchHandlers[TagAddr] =
1895 std::make_shared<JITDispatchHandlerFunction>(std::move(I->second));
1896 LLVM_DEBUG({
1897 dbgs() << "Associated function tag \"" << *TagName << "\" ("
1898 << formatv("{0:x}", TagAddr) << ") with handler\n";
1899 });
1900 }
1901
1902 return Error::success();
1903}
1904
1906 ExecutorAddr HandlerFnTagAddr,
1907 ArrayRef<char> ArgBuffer) {
1908
1909 std::shared_ptr<JITDispatchHandlerFunction> F;
1910 {
1911 std::lock_guard<std::mutex> Lock(JITDispatchHandlersMutex);
1912 auto I = JITDispatchHandlers.find(HandlerFnTagAddr);
1913 if (I != JITDispatchHandlers.end())
1914 F = I->second;
1915 }
1916
1917 if (F)
1918 (*F)(std::move(SendResult), ArgBuffer.data(), ArgBuffer.size());
1919 else
1921 ("No function registered for tag " +
1922 formatv("{0:x16}", HandlerFnTagAddr))
1923 .str()));
1924}
1925
1927 runSessionLocked([this, &OS]() {
1928 for (auto &JD : JDs)
1929 JD->dump(OS);
1930 });
1931}
1932
1933#ifdef EXPENSIVE_CHECKS
1934bool ExecutionSession::verifySessionState(Twine Phase) {
1935 return runSessionLocked([&]() {
1936 bool AllOk = true;
1937
1938 for (auto &JD : JDs) {
1939
1940 auto LogFailure = [&]() -> raw_fd_ostream & {
1941 auto &Stream = errs();
1942 if (AllOk)
1943 Stream << "ERROR: Bad ExecutionSession state detected " << Phase
1944 << "\n";
1945 Stream << " In JITDylib " << JD->getName() << ", ";
1946 AllOk = false;
1947 return Stream;
1948 };
1949
1950 if (JD->State != JITDylib::Open) {
1951 LogFailure()
1952 << "state is not Open, but JD is in ExecutionSession list.";
1953 }
1954
1955 // Check symbol table.
1956 // 1. If the entry state isn't resolved then check that no address has
1957 // been set.
1958 // 2. Check that if the hasMaterializerAttached flag is set then there is
1959 // an UnmaterializedInfo entry, and vice-versa.
1960 for (auto &[Sym, Entry] : JD->Symbols) {
1961 // Check that unresolved symbols have null addresses.
1962 if (Entry.getState() < SymbolState::Resolved) {
1963 if (Entry.getAddress()) {
1964 LogFailure() << "symbol " << Sym << " has state "
1965 << Entry.getState()
1966 << " (not-yet-resolved) but non-null address "
1967 << Entry.getAddress() << ".\n";
1968 }
1969 }
1970
1971 // Check that the hasMaterializerAttached flag is correct.
1972 auto UMIItr = JD->UnmaterializedInfos.find(Sym);
1973 if (Entry.hasMaterializerAttached()) {
1974 if (UMIItr == JD->UnmaterializedInfos.end()) {
1975 LogFailure() << "symbol " << Sym
1976 << " entry claims materializer attached, but "
1977 "UnmaterializedInfos has no corresponding entry.\n";
1978 }
1979 } else if (UMIItr != JD->UnmaterializedInfos.end()) {
1980 LogFailure()
1981 << "symbol " << Sym
1982 << " entry claims no materializer attached, but "
1983 "UnmaterializedInfos has an unexpected entry for it.\n";
1984 }
1985 }
1986
1987 // Check that every UnmaterializedInfo entry has a corresponding entry
1988 // in the Symbols table.
1989 for (auto &[Sym, UMI] : JD->UnmaterializedInfos) {
1990 auto SymItr = JD->Symbols.find(Sym);
1991 if (SymItr == JD->Symbols.end()) {
1992 LogFailure()
1993 << "symbol " << Sym
1994 << " has UnmaterializedInfos entry, but no Symbols entry.\n";
1995 }
1996 }
1997
1998 // Check consistency of the MaterializingInfos table.
1999 for (auto &[Sym, MII] : JD->MaterializingInfos) {
2000
2001 auto SymItr = JD->Symbols.find(Sym);
2002 if (SymItr == JD->Symbols.end()) {
2003 // If there's no Symbols entry for this MaterializingInfos entry then
2004 // report that.
2005 LogFailure()
2006 << "symbol " << Sym
2007 << " has MaterializingInfos entry, but no Symbols entry.\n";
2008 } else {
2009 // Otherwise check consistency between Symbols and MaterializingInfos.
2010
2011 // Ready symbols should not have MaterializingInfos.
2012 if (SymItr->second.getState() == SymbolState::Ready) {
2013 LogFailure()
2014 << "symbol " << Sym
2015 << " is in Ready state, should not have MaterializingInfo.\n";
2016 }
2017
2018 // Pending queries should be for subsequent states.
2019 auto CurState = static_cast<SymbolState>(
2020 static_cast<std::underlying_type_t<SymbolState>>(
2021 SymItr->second.getState()) + 1);
2022 for (auto &Q : MII.PendingQueries) {
2023 if (Q->getRequiredState() != CurState) {
2024 if (Q->getRequiredState() > CurState)
2025 CurState = Q->getRequiredState();
2026 else
2027 LogFailure() << "symbol " << Sym
2028 << " has stale or misordered queries.\n";
2029 }
2030 }
2031 }
2032 }
2033 }
2034
2035 return AllOk;
2036 });
2037}
2038#endif // EXPENSIVE_CHECKS
2039
2040void ExecutionSession::dispatchOutstandingMUs() {
2041 LLVM_DEBUG(dbgs() << "Dispatching MaterializationUnits...\n");
2042 while (true) {
2043 std::optional<std::pair<std::unique_ptr<MaterializationUnit>,
2044 std::unique_ptr<MaterializationResponsibility>>>
2045 JMU;
2046
2047 {
2048 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2049 if (!OutstandingMUs.empty()) {
2050 JMU.emplace(std::move(OutstandingMUs.back()));
2051 OutstandingMUs.pop_back();
2052 }
2053 }
2054
2055 if (!JMU)
2056 break;
2057
2058 assert(JMU->first && "No MU?");
2059 LLVM_DEBUG(dbgs() << " Dispatching \"" << JMU->first->getName() << "\"\n");
2060 dispatchTask(std::make_unique<MaterializationTask>(std::move(JMU->first),
2061 std::move(JMU->second)));
2062 }
2063 LLVM_DEBUG(dbgs() << "Done dispatching MaterializationUnits.\n");
2064}
2065
2066Error ExecutionSession::removeResourceTracker(ResourceTracker &RT) {
2067 LLVM_DEBUG({
2068 dbgs() << "In " << RT.getJITDylib().getName() << " removing tracker "
2069 << formatv("{0:x}", RT.getKeyUnsafe()) << "\n";
2070 });
2071 std::vector<ResourceManager *> CurrentResourceManagers;
2072
2073 JITDylib::RemoveTrackerResult R;
2074
2075 runSessionLocked([&] {
2076 CurrentResourceManagers = ResourceManagers;
2077 RT.makeDefunct();
2078 R = RT.getJITDylib().IL_removeTracker(RT);
2079 });
2080
2081 // Release any defunct MaterializationUnits.
2082 R.DefunctMUs.clear();
2083
2084 Error Err = Error::success();
2085
2086 auto &JD = RT.getJITDylib();
2087 for (auto *L : reverse(CurrentResourceManagers))
2088 Err = joinErrors(std::move(Err),
2089 L->handleRemoveResources(JD, RT.getKeyUnsafe()));
2090
2091 for (auto &Q : R.QueriesToFail)
2093 R.FailedSymbols));
2094
2095 return Err;
2096}
2097
2098void ExecutionSession::transferResourceTracker(ResourceTracker &DstRT,
2099 ResourceTracker &SrcRT) {
2100 LLVM_DEBUG({
2101 dbgs() << "In " << SrcRT.getJITDylib().getName()
2102 << " transfering resources from tracker "
2103 << formatv("{0:x}", SrcRT.getKeyUnsafe()) << " to tracker "
2104 << formatv("{0:x}", DstRT.getKeyUnsafe()) << "\n";
2105 });
2106
2107 // No-op transfers are allowed and do not invalidate the source.
2108 if (&DstRT == &SrcRT)
2109 return;
2110
2111 assert(&DstRT.getJITDylib() == &SrcRT.getJITDylib() &&
2112 "Can't transfer resources between JITDylibs");
2113 runSessionLocked([&]() {
2114 SrcRT.makeDefunct();
2115 auto &JD = DstRT.getJITDylib();
2116 JD.transferTracker(DstRT, SrcRT);
2117 for (auto *L : reverse(ResourceManagers))
2118 L->handleTransferResources(JD, DstRT.getKeyUnsafe(),
2119 SrcRT.getKeyUnsafe());
2120 });
2121}
2122
2123void ExecutionSession::destroyResourceTracker(ResourceTracker &RT) {
2124 runSessionLocked([&]() {
2125 LLVM_DEBUG({
2126 dbgs() << "In " << RT.getJITDylib().getName() << " destroying tracker "
2127 << formatv("{0:x}", RT.getKeyUnsafe()) << "\n";
2128 });
2129 if (!RT.isDefunct())
2130 transferResourceTracker(*RT.getJITDylib().getDefaultResourceTracker(),
2131 RT);
2132 });
2133}
2134
2135Error ExecutionSession::IL_updateCandidatesFor(
2136 JITDylib &JD, JITDylibLookupFlags JDLookupFlags,
2137 SymbolLookupSet &Candidates, SymbolLookupSet *NonCandidates) {
2138 return Candidates.forEachWithRemoval(
2139 [&](const SymbolStringPtr &Name,
2140 SymbolLookupFlags SymLookupFlags) -> Expected<bool> {
2141 /// Search for the symbol. If not found then continue without
2142 /// removal.
2143 auto SymI = JD.Symbols.find(Name);
2144 if (SymI == JD.Symbols.end())
2145 return false;
2146
2147 // If this is a non-exported symbol and we're matching exported
2148 // symbols only then remove this symbol from the candidates list.
2149 //
2150 // If we're tracking non-candidates then add this to the non-candidate
2151 // list.
2152 if (!SymI->second.getFlags().isExported() &&
2154 if (NonCandidates)
2155 NonCandidates->add(Name, SymLookupFlags);
2156 return true;
2157 }
2158
2159 // If we match against a materialization-side-effects only symbol
2160 // then make sure it is weakly-referenced. Otherwise bail out with
2161 // an error.
2162 // FIXME: Use a "materialization-side-effects-only symbols must be
2163 // weakly referenced" specific error here to reduce confusion.
2164 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2168
2169 // If we matched against this symbol but it is in the error state
2170 // then bail out and treat it as a failure to materialize.
2171 if (SymI->second.getFlags().hasError()) {
2172 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2173 (*FailedSymbolsMap)[&JD] = {Name};
2175 std::move(FailedSymbolsMap));
2176 }
2177
2178 // Otherwise this is a match. Remove it from the candidate set.
2179 return true;
2180 });
2181}
2182
2183void ExecutionSession::OL_resumeLookupAfterGeneration(
2184 InProgressLookupState &IPLS) {
2185
2187 "Should not be called for not-in-generator lookups");
2189
2191
2192 if (auto DG = IPLS.CurDefGeneratorStack.back().lock()) {
2193 IPLS.CurDefGeneratorStack.pop_back();
2194 std::lock_guard<std::mutex> Lock(DG->M);
2195
2196 // If there are no pending lookups then mark the generator as free and
2197 // return.
2198 if (DG->PendingLookups.empty()) {
2199 DG->InUse = false;
2200 return;
2201 }
2202
2203 // Otherwise resume the next lookup.
2204 LS = std::move(DG->PendingLookups.front());
2205 DG->PendingLookups.pop_front();
2206 }
2207
2208 if (LS.IPLS) {
2210 dispatchTask(std::make_unique<LookupTask>(std::move(LS)));
2211 }
2212}
2213
2214void ExecutionSession::OL_applyQueryPhase1(
2215 std::unique_ptr<InProgressLookupState> IPLS, Error Err) {
2216
2217 LLVM_DEBUG({
2218 dbgs() << "Entering OL_applyQueryPhase1:\n"
2219 << " Lookup kind: " << IPLS->K << "\n"
2220 << " Search order: " << IPLS->SearchOrder
2221 << ", Current index = " << IPLS->CurSearchOrderIndex
2222 << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2223 << " Lookup set: " << IPLS->LookupSet << "\n"
2224 << " Definition generator candidates: "
2225 << IPLS->DefGeneratorCandidates << "\n"
2226 << " Definition generator non-candidates: "
2227 << IPLS->DefGeneratorNonCandidates << "\n";
2228 });
2229
2230 if (IPLS->GenState == InProgressLookupState::InGenerator)
2231 OL_resumeLookupAfterGeneration(*IPLS);
2232
2233 assert(IPLS->GenState != InProgressLookupState::InGenerator &&
2234 "Lookup should not be in InGenerator state here");
2235
2236 // FIXME: We should attach the query as we go: This provides a result in a
2237 // single pass in the common case where all symbols have already reached the
2238 // required state. The query could be detached again in the 'fail' method on
2239 // IPLS. Phase 2 would be reduced to collecting and dispatching the MUs.
2240
2241 while (IPLS->CurSearchOrderIndex != IPLS->SearchOrder.size()) {
2242
2243 // If we've been handed an error or received one back from a generator then
2244 // fail the query. We don't need to unlink: At this stage the query hasn't
2245 // actually been lodged.
2246 if (Err)
2247 return IPLS->fail(std::move(Err));
2248
2249 // Get the next JITDylib and lookup flags.
2250 auto &KV = IPLS->SearchOrder[IPLS->CurSearchOrderIndex];
2251 auto &JD = *KV.first;
2252 auto JDLookupFlags = KV.second;
2253
2254 LLVM_DEBUG({
2255 dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2256 << ") with lookup set " << IPLS->LookupSet << ":\n";
2257 });
2258
2259 // If we've just reached a new JITDylib then perform some setup.
2260 if (IPLS->NewJITDylib) {
2261 // Add any non-candidates from the last JITDylib (if any) back on to the
2262 // list of definition candidates for this JITDylib, reset definition
2263 // non-candidates to the empty set.
2264 SymbolLookupSet Tmp;
2265 std::swap(IPLS->DefGeneratorNonCandidates, Tmp);
2266 IPLS->DefGeneratorCandidates.append(std::move(Tmp));
2267
2268 LLVM_DEBUG({
2269 dbgs() << " First time visiting " << JD.getName()
2270 << ", resetting candidate sets and building generator stack\n";
2271 });
2272
2273 // Build the definition generator stack for this JITDylib.
2274 runSessionLocked([&] {
2275 IPLS->CurDefGeneratorStack.reserve(JD.DefGenerators.size());
2276 llvm::append_range(IPLS->CurDefGeneratorStack,
2277 reverse(JD.DefGenerators));
2278 });
2279
2280 // Flag that we've done our initialization.
2281 IPLS->NewJITDylib = false;
2282 }
2283
2284 // Remove any generation candidates that are already defined (and match) in
2285 // this JITDylib.
2286 runSessionLocked([&] {
2287 // Update the list of candidates (and non-candidates) for definition
2288 // generation.
2289 LLVM_DEBUG(dbgs() << " Updating candidate set...\n");
2290 Err = IL_updateCandidatesFor(
2291 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2292 JD.DefGenerators.empty() ? nullptr
2293 : &IPLS->DefGeneratorNonCandidates);
2294 LLVM_DEBUG({
2295 dbgs() << " Remaining candidates = " << IPLS->DefGeneratorCandidates
2296 << "\n";
2297 });
2298
2299 // If this lookup was resumed after auto-suspension but all candidates
2300 // have already been generated (by some previous call to the generator)
2301 // treat the lookup as if it had completed generation.
2302 if (IPLS->GenState == InProgressLookupState::ResumedForGenerator &&
2303 IPLS->DefGeneratorCandidates.empty())
2304 OL_resumeLookupAfterGeneration(*IPLS);
2305 });
2306
2307 // If we encountered an error while filtering generation candidates then
2308 // bail out.
2309 if (Err)
2310 return IPLS->fail(std::move(Err));
2311
2312 /// Apply any definition generators on the stack.
2313 LLVM_DEBUG({
2314 if (IPLS->CurDefGeneratorStack.empty())
2315 LLVM_DEBUG(dbgs() << " No generators to run for this JITDylib.\n");
2316 else if (IPLS->DefGeneratorCandidates.empty())
2317 LLVM_DEBUG(dbgs() << " No candidates to generate.\n");
2318 else
2319 dbgs() << " Running " << IPLS->CurDefGeneratorStack.size()
2320 << " remaining generators for "
2321 << IPLS->DefGeneratorCandidates.size() << " candidates\n";
2322 });
2323 while (!IPLS->CurDefGeneratorStack.empty() &&
2324 !IPLS->DefGeneratorCandidates.empty()) {
2325 auto DG = IPLS->CurDefGeneratorStack.back().lock();
2326
2327 if (!DG)
2328 return IPLS->fail(make_error<StringError>(
2329 "DefinitionGenerator removed while lookup in progress",
2331
2332 // At this point the lookup is in either the NotInGenerator state, or in
2333 // the ResumedForGenerator state.
2334 // If this lookup is in the NotInGenerator state then check whether the
2335 // generator is in use. If the generator is not in use then move the
2336 // lookup to the InGenerator state and continue. If the generator is
2337 // already in use then just add this lookup to the pending lookups list
2338 // and bail out.
2339 // If this lookup is in the ResumedForGenerator state then just move it
2340 // to InGenerator and continue.
2341 if (IPLS->GenState == InProgressLookupState::NotInGenerator) {
2342 std::lock_guard<std::mutex> Lock(DG->M);
2343 if (DG->InUse) {
2344 DG->PendingLookups.push_back(std::move(IPLS));
2345 return;
2346 }
2347 DG->InUse = true;
2348 }
2349
2350 IPLS->GenState = InProgressLookupState::InGenerator;
2351
2352 auto K = IPLS->K;
2353 auto &LookupSet = IPLS->DefGeneratorCandidates;
2354
2355 // Run the generator. If the generator takes ownership of QA then this
2356 // will break the loop.
2357 {
2358 LLVM_DEBUG(dbgs() << " Attempting to generate " << LookupSet << "\n");
2359 LookupState LS(std::move(IPLS));
2360 Err = DG->tryToGenerate(LS, K, JD, JDLookupFlags, LookupSet);
2361 IPLS = std::move(LS.IPLS);
2362 }
2363
2364 // If the lookup returned then pop the generator stack and unblock the
2365 // next lookup on this generator (if any).
2366 if (IPLS)
2367 OL_resumeLookupAfterGeneration(*IPLS);
2368
2369 // If there was an error then fail the query.
2370 if (Err) {
2371 LLVM_DEBUG({
2372 dbgs() << " Error attempting to generate " << LookupSet << "\n";
2373 });
2374 assert(IPLS && "LS cannot be retained if error is returned");
2375 return IPLS->fail(std::move(Err));
2376 }
2377
2378 // Otherwise if QA was captured then break the loop.
2379 if (!IPLS) {
2380 LLVM_DEBUG(
2381 { dbgs() << " LookupState captured. Exiting phase1 for now.\n"; });
2382 return;
2383 }
2384
2385 // Otherwise if we're continuing around the loop then update candidates
2386 // for the next round.
2387 runSessionLocked([&] {
2388 LLVM_DEBUG(dbgs() << " Updating candidate set post-generation\n");
2389 Err = IL_updateCandidatesFor(
2390 JD, JDLookupFlags, IPLS->DefGeneratorCandidates,
2391 JD.DefGenerators.empty() ? nullptr
2392 : &IPLS->DefGeneratorNonCandidates);
2393 });
2394
2395 // If updating candidates failed then fail the query.
2396 if (Err) {
2397 LLVM_DEBUG(dbgs() << " Error encountered while updating candidates\n");
2398 return IPLS->fail(std::move(Err));
2399 }
2400 }
2401
2402 if (IPLS->DefGeneratorCandidates.empty() &&
2403 IPLS->DefGeneratorNonCandidates.empty()) {
2404 // Early out if there are no remaining symbols.
2405 LLVM_DEBUG(dbgs() << "All symbols matched.\n");
2406 IPLS->CurSearchOrderIndex = IPLS->SearchOrder.size();
2407 break;
2408 } else {
2409 // If we get here then we've moved on to the next JITDylib with candidates
2410 // remaining.
2411 LLVM_DEBUG(dbgs() << "Phase 1 moving to next JITDylib.\n");
2412 ++IPLS->CurSearchOrderIndex;
2413 IPLS->NewJITDylib = true;
2414 }
2415 }
2416
2417 // Remove any weakly referenced candidates that could not be found/generated.
2418 IPLS->DefGeneratorCandidates.remove_if(
2419 [](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2420 return SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol;
2421 });
2422
2423 // If we get here then we've finished searching all JITDylibs.
2424 // If we matched all symbols then move to phase 2, otherwise fail the query
2425 // with a SymbolsNotFound error.
2426 if (IPLS->DefGeneratorCandidates.empty()) {
2427 LLVM_DEBUG(dbgs() << "Phase 1 succeeded.\n");
2428 IPLS->complete(std::move(IPLS));
2429 } else {
2430 LLVM_DEBUG(dbgs() << "Phase 1 failed with unresolved symbols.\n");
2431 IPLS->fail(make_error<SymbolsNotFound>(
2432 getSymbolStringPool(), IPLS->DefGeneratorCandidates.getSymbolNames()));
2433 }
2434}
2435
2436void ExecutionSession::OL_completeLookup(
2437 std::unique_ptr<InProgressLookupState> IPLS,
2438 std::shared_ptr<AsynchronousSymbolQuery> Q,
2439 RegisterDependenciesFunction RegisterDependencies) {
2440
2441 LLVM_DEBUG({
2442 dbgs() << "Entering OL_completeLookup:\n"
2443 << " Lookup kind: " << IPLS->K << "\n"
2444 << " Search order: " << IPLS->SearchOrder
2445 << ", Current index = " << IPLS->CurSearchOrderIndex
2446 << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2447 << " Lookup set: " << IPLS->LookupSet << "\n"
2448 << " Definition generator candidates: "
2449 << IPLS->DefGeneratorCandidates << "\n"
2450 << " Definition generator non-candidates: "
2451 << IPLS->DefGeneratorNonCandidates << "\n";
2452 });
2453
2454 bool QueryComplete = false;
2455 DenseMap<JITDylib *, JITDylib::UnmaterializedInfosList> CollectedUMIs;
2456
2457 auto LodgingErr = runSessionLocked([&]() -> Error {
2458 for (auto &KV : IPLS->SearchOrder) {
2459 auto &JD = *KV.first;
2460 auto JDLookupFlags = KV.second;
2461 LLVM_DEBUG({
2462 dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2463 << ") with lookup set " << IPLS->LookupSet << ":\n";
2464 });
2465
2466 auto Err = IPLS->LookupSet.forEachWithRemoval(
2467 [&](const SymbolStringPtr &Name,
2468 SymbolLookupFlags SymLookupFlags) -> Expected<bool> {
2469 LLVM_DEBUG({
2470 dbgs() << " Attempting to match \"" << Name << "\" ("
2471 << SymLookupFlags << ")... ";
2472 });
2473
2474 /// Search for the symbol. If not found then continue without
2475 /// removal.
2476 auto SymI = JD.Symbols.find(Name);
2477 if (SymI == JD.Symbols.end()) {
2478 LLVM_DEBUG(dbgs() << "skipping: not present\n");
2479 return false;
2480 }
2481
2482 // If this is a non-exported symbol and we're matching exported
2483 // symbols only then skip this symbol without removal.
2484 if (!SymI->second.getFlags().isExported() &&
2485 JDLookupFlags ==
2487 LLVM_DEBUG(dbgs() << "skipping: not exported\n");
2488 return false;
2489 }
2490
2491 // If we match against a materialization-side-effects only symbol
2492 // then make sure it is weakly-referenced. Otherwise bail out with
2493 // an error.
2494 // FIXME: Use a "materialization-side-effects-only symbols must be
2495 // weakly referenced" specific error here to reduce confusion.
2496 if (SymI->second.getFlags().hasMaterializationSideEffectsOnly() &&
2498 LLVM_DEBUG({
2499 dbgs() << "error: "
2500 "required, but symbol is has-side-effects-only\n";
2501 });
2504 }
2505
2506 // If we matched against this symbol but it is in the error state
2507 // then bail out and treat it as a failure to materialize.
2508 if (SymI->second.getFlags().hasError()) {
2509 LLVM_DEBUG(dbgs() << "error: symbol is in error state\n");
2510 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
2511 (*FailedSymbolsMap)[&JD] = {Name};
2513 getSymbolStringPool(), std::move(FailedSymbolsMap));
2514 }
2515
2516 // Otherwise this is a match.
2517
2518 // If this symbol is already in the required state then notify the
2519 // query, remove the symbol and continue.
2520 if (SymI->second.getState() >= Q->getRequiredState()) {
2522 << "matched, symbol already in required state\n");
2523 Q->notifySymbolMetRequiredState(Name, SymI->second.getSymbol());
2524
2525 // If this symbol is in anything other than the Ready state then
2526 // we need to track the dependence.
2527 if (SymI->second.getState() != SymbolState::Ready)
2528 Q->addQueryDependence(JD, Name);
2529
2530 return true;
2531 }
2532
2533 // Otherwise this symbol does not yet meet the required state. Check
2534 // whether it has a materializer attached, and if so prepare to run
2535 // it.
2536 if (SymI->second.hasMaterializerAttached()) {
2537 assert(SymI->second.getAddress() == ExecutorAddr() &&
2538 "Symbol not resolved but already has address?");
2539 auto UMII = JD.UnmaterializedInfos.find(Name);
2540 assert(UMII != JD.UnmaterializedInfos.end() &&
2541 "Lazy symbol should have UnmaterializedInfo");
2542
2543 auto UMI = UMII->second;
2544 assert(UMI->MU && "Materializer should not be null");
2545 assert(UMI->RT && "Tracker should not be null");
2546 LLVM_DEBUG({
2547 dbgs() << "matched, preparing to dispatch MU@" << UMI->MU.get()
2548 << " (" << UMI->MU->getName() << ")\n";
2549 });
2550
2551 // Move all symbols associated with this MaterializationUnit into
2552 // materializing state.
2553 for (auto &KV : UMI->MU->getSymbols()) {
2554 auto SymK = JD.Symbols.find(KV.first);
2555 assert(SymK != JD.Symbols.end() &&
2556 "No entry for symbol covered by MaterializationUnit");
2557 SymK->second.setMaterializerAttached(false);
2558 SymK->second.setState(SymbolState::Materializing);
2559 JD.UnmaterializedInfos.erase(KV.first);
2560 }
2561
2562 // Add MU to the list of MaterializationUnits to be materialized.
2563 CollectedUMIs[&JD].push_back(std::move(UMI));
2564 } else
2565 LLVM_DEBUG(dbgs() << "matched, registering query");
2566
2567 // Add the query to the PendingQueries list and continue, deleting
2568 // the element from the lookup set.
2569 assert(SymI->second.getState() != SymbolState::NeverSearched &&
2570 SymI->second.getState() != SymbolState::Ready &&
2571 "By this line the symbol should be materializing");
2572 auto &MI = JD.MaterializingInfos[Name];
2573 MI.addQuery(Q);
2574 Q->addQueryDependence(JD, Name);
2575
2576 return true;
2577 });
2578
2579 JD.shrinkMaterializationInfoMemory();
2580
2581 // Handle failure.
2582 if (Err) {
2583
2584 LLVM_DEBUG({
2585 dbgs() << "Lookup failed. Detaching query and replacing MUs.\n";
2586 });
2587
2588 // Detach the query.
2589 Q->detach();
2590
2591 // Replace the MUs.
2592 for (auto &KV : CollectedUMIs) {
2593 auto &JD = *KV.first;
2594 for (auto &UMI : KV.second)
2595 for (auto &KV2 : UMI->MU->getSymbols()) {
2596 assert(!JD.UnmaterializedInfos.count(KV2.first) &&
2597 "Unexpected materializer in map");
2598 auto SymI = JD.Symbols.find(KV2.first);
2599 assert(SymI != JD.Symbols.end() && "Missing symbol entry");
2600 assert(SymI->second.getState() == SymbolState::Materializing &&
2601 "Can not replace symbol that is not materializing");
2602 assert(!SymI->second.hasMaterializerAttached() &&
2603 "MaterializerAttached flag should not be set");
2604 SymI->second.setMaterializerAttached(true);
2605 JD.UnmaterializedInfos[KV2.first] = UMI;
2606 }
2607 }
2608
2609 return Err;
2610 }
2611 }
2612
2613 LLVM_DEBUG(dbgs() << "Stripping unmatched weakly-referenced symbols\n");
2614 IPLS->LookupSet.forEachWithRemoval(
2615 [&](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2616 if (SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol) {
2617 Q->dropSymbol(Name);
2618 return true;
2619 } else
2620 return false;
2621 });
2622
2623 if (!IPLS->LookupSet.empty()) {
2624 LLVM_DEBUG(dbgs() << "Failing due to unresolved symbols\n");
2626 IPLS->LookupSet.getSymbolNames());
2627 }
2628
2629 // Record whether the query completed.
2630 QueryComplete = Q->isComplete();
2631
2632 LLVM_DEBUG({
2633 dbgs() << "Query successfully "
2634 << (QueryComplete ? "completed" : "lodged") << "\n";
2635 });
2636
2637 // Move the collected MUs to the OutstandingMUs list.
2638 if (!CollectedUMIs.empty()) {
2639 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex);
2640
2641 LLVM_DEBUG(dbgs() << "Adding MUs to dispatch:\n");
2642 for (auto &KV : CollectedUMIs) {
2643 LLVM_DEBUG({
2644 auto &JD = *KV.first;
2645 dbgs() << " For " << JD.getName() << ": Adding " << KV.second.size()
2646 << " MUs.\n";
2647 });
2648 for (auto &UMI : KV.second) {
2649 auto MR = createMaterializationResponsibility(
2650 *UMI->RT, std::move(UMI->MU->SymbolFlags),
2651 std::move(UMI->MU->InitSymbol));
2652 OutstandingMUs.push_back(
2653 std::make_pair(std::move(UMI->MU), std::move(MR)));
2654 }
2655 }
2656 } else
2657 LLVM_DEBUG(dbgs() << "No MUs to dispatch.\n");
2658
2659 if (RegisterDependencies && !Q->QueryRegistrations.empty()) {
2660 LLVM_DEBUG(dbgs() << "Registering dependencies\n");
2661 RegisterDependencies(Q->QueryRegistrations);
2662 } else
2663 LLVM_DEBUG(dbgs() << "No dependencies to register\n");
2664
2665 return Error::success();
2666 });
2667
2668 if (LodgingErr) {
2669 LLVM_DEBUG(dbgs() << "Failing query\n");
2670 Q->detach();
2671 Q->handleFailed(std::move(LodgingErr));
2672 return;
2673 }
2674
2675 if (QueryComplete) {
2676 LLVM_DEBUG(dbgs() << "Completing query\n");
2677 Q->handleComplete(*this);
2678 }
2679
2680 dispatchOutstandingMUs();
2681}
2682
2683void ExecutionSession::OL_completeLookupFlags(
2684 std::unique_ptr<InProgressLookupState> IPLS,
2685 unique_function<void(Expected<SymbolFlagsMap>)> OnComplete) {
2686
2687 auto Result = runSessionLocked([&]() -> Expected<SymbolFlagsMap> {
2688 LLVM_DEBUG({
2689 dbgs() << "Entering OL_completeLookupFlags:\n"
2690 << " Lookup kind: " << IPLS->K << "\n"
2691 << " Search order: " << IPLS->SearchOrder
2692 << ", Current index = " << IPLS->CurSearchOrderIndex
2693 << (IPLS->NewJITDylib ? " (entering new JITDylib)" : "") << "\n"
2694 << " Lookup set: " << IPLS->LookupSet << "\n"
2695 << " Definition generator candidates: "
2696 << IPLS->DefGeneratorCandidates << "\n"
2697 << " Definition generator non-candidates: "
2698 << IPLS->DefGeneratorNonCandidates << "\n";
2699 });
2700
2702
2703 // Attempt to find flags for each symbol.
2704 for (auto &KV : IPLS->SearchOrder) {
2705 auto &JD = *KV.first;
2706 auto JDLookupFlags = KV.second;
2707 LLVM_DEBUG({
2708 dbgs() << "Visiting \"" << JD.getName() << "\" (" << JDLookupFlags
2709 << ") with lookup set " << IPLS->LookupSet << ":\n";
2710 });
2711
2712 IPLS->LookupSet.forEachWithRemoval([&](const SymbolStringPtr &Name,
2713 SymbolLookupFlags SymLookupFlags) {
2714 LLVM_DEBUG({
2715 dbgs() << " Attempting to match \"" << Name << "\" ("
2716 << SymLookupFlags << ")... ";
2717 });
2718
2719 // Search for the symbol. If not found then continue without removing
2720 // from the lookup set.
2721 auto SymI = JD.Symbols.find(Name);
2722 if (SymI == JD.Symbols.end()) {
2723 LLVM_DEBUG(dbgs() << "skipping: not present\n");
2724 return false;
2725 }
2726
2727 // If this is a non-exported symbol then it doesn't match. Skip it.
2728 if (!SymI->second.getFlags().isExported() &&
2730 LLVM_DEBUG(dbgs() << "skipping: not exported\n");
2731 return false;
2732 }
2733
2734 LLVM_DEBUG({
2735 dbgs() << "matched, \"" << Name << "\" -> " << SymI->second.getFlags()
2736 << "\n";
2737 });
2738 Result[Name] = SymI->second.getFlags();
2739 return true;
2740 });
2741 }
2742
2743 // Remove any weakly referenced symbols that haven't been resolved.
2744 IPLS->LookupSet.remove_if(
2745 [](const SymbolStringPtr &Name, SymbolLookupFlags SymLookupFlags) {
2746 return SymLookupFlags == SymbolLookupFlags::WeaklyReferencedSymbol;
2747 });
2748
2749 if (!IPLS->LookupSet.empty()) {
2750 LLVM_DEBUG(dbgs() << "Failing due to unresolved symbols\n");
2752 IPLS->LookupSet.getSymbolNames());
2753 }
2754
2755 LLVM_DEBUG(dbgs() << "Succeded, result = " << Result << "\n");
2756 return Result;
2757 });
2758
2759 // Run the callback on the result.
2760 LLVM_DEBUG(dbgs() << "Sending result to handler.\n");
2761 OnComplete(std::move(Result));
2762}
2763
2764void ExecutionSession::OL_destroyMaterializationResponsibility(
2766
2767 assert(MR.SymbolFlags.empty() &&
2768 "All symbols should have been explicitly materialized or failed");
2769 MR.JD.unlinkMaterializationResponsibility(MR);
2770}
2771
2772SymbolNameSet ExecutionSession::OL_getRequestedSymbols(
2774 return MR.JD.getRequestedSymbols(MR.SymbolFlags);
2775}
2776
2777Error ExecutionSession::OL_notifyResolved(MaterializationResponsibility &MR,
2778 const SymbolMap &Symbols) {
2779 LLVM_DEBUG({
2780 dbgs() << "In " << MR.JD.getName() << " resolving " << Symbols << "\n";
2781 });
2782#ifndef NDEBUG
2783 for (auto &KV : Symbols) {
2784 auto I = MR.SymbolFlags.find(KV.first);
2785 assert(I != MR.SymbolFlags.end() &&
2786 "Resolving symbol outside this responsibility set");
2787 assert(!I->second.hasMaterializationSideEffectsOnly() &&
2788 "Can't resolve materialization-side-effects-only symbol");
2789 if (I->second & JITSymbolFlags::Common) {
2790 auto WeakOrCommon = JITSymbolFlags::Weak | JITSymbolFlags::Common;
2791 assert((KV.second.getFlags() & WeakOrCommon) &&
2792 "Common symbols must be resolved as common or weak");
2793 assert((KV.second.getFlags() & ~WeakOrCommon) ==
2794 (I->second & ~JITSymbolFlags::Common) &&
2795 "Resolving symbol with incorrect flags");
2796 } else
2797 assert(KV.second.getFlags() == I->second &&
2798 "Resolving symbol with incorrect flags");
2799 }
2800#endif
2801
2802 return MR.JD.resolve(MR, Symbols);
2803}
2804
2806ExecutionSession::IL_getSymbolState(JITDylib *JD,
2808 if (JD->State != JITDylib::Open)
2809 return WaitingOnGraph::ExternalState::Failed;
2810
2811 auto I = JD->Symbols.find_as(Name);
2812
2813 // FIXME: Can we eliminate this possibility if we support query binding?
2814 if (I == JD->Symbols.end())
2815 return WaitingOnGraph::ExternalState::Failed;
2816
2817 if (I->second.getFlags().hasError())
2818 return WaitingOnGraph::ExternalState::Failed;
2819
2820 if (I->second.getState() == SymbolState::Ready)
2821 return WaitingOnGraph::ExternalState::Ready;
2822
2823 return WaitingOnGraph::ExternalState::None;
2824}
2825
2826template <typename UpdateSymbolFn, typename UpdateQueryFn>
2827void ExecutionSession::IL_collectQueries(
2828 JITDylib::AsynchronousSymbolQuerySet &Qs,
2829 WaitingOnGraph::ContainerElementsMap &QualifiedSymbols,
2830 UpdateSymbolFn &&UpdateSymbol, UpdateQueryFn &&UpdateQuery) {
2831
2832 for (auto &[JD, Symbols] : QualifiedSymbols) {
2833 // IL_emit and JITDylib removal are synchronized by the session lock.
2834 // Since JITDylib removal removes any contained nodes from the
2835 // WaitingOnGraph, we should be able to assert that all nodes in the
2836 // WaitingOnGraph have not been removed.
2837 assert(JD->State == JITDylib::Open &&
2838 "WaitingOnGraph includes definition in defunct JITDylib");
2839 for (auto &Symbol : Symbols) {
2840 // Update symbol table.
2841 auto I = JD->Symbols.find_as(Symbol);
2842 assert(I != JD->Symbols.end() &&
2843 "Failed Symbol missing from JD symbol table");
2844 auto &Entry = I->second;
2845 UpdateSymbol(Entry);
2846
2847 // Collect queries.
2848 auto J = JD->MaterializingInfos.find_as(Symbol);
2849 if (J != JD->MaterializingInfos.end()) {
2850 for (auto &Q : J->second.takeAllPendingQueries()) {
2851 UpdateQuery(*Q, *JD, Symbol, Entry);
2852 Qs.insert(std::move(Q));
2853 }
2854 JD->MaterializingInfos.erase(J);
2855 }
2856 }
2857 }
2858}
2859
2860Expected<ExecutionSession::EmitQueries>
2861ExecutionSession::IL_emit(MaterializationResponsibility &MR,
2862 WaitingOnGraph::SimplifyResult SR) {
2863
2864 if (MR.RT->isDefunct())
2866
2867 auto &TargetJD = MR.getTargetJITDylib();
2868 if (TargetJD.State != JITDylib::Open)
2869 return make_error<StringError>("JITDylib " + TargetJD.getName() +
2870 " is defunct",
2872
2873#ifdef EXPENSIVE_CHECKS
2874 verifySessionState("entering ExecutionSession::IL_emit");
2875#endif
2876
2877 auto ER = G.emit(std::move(SR),
2878 [this](JITDylib *JD, NonOwningSymbolStringPtr Name) {
2879 return IL_getSymbolState(JD, Name);
2880 });
2881
2882 EmitQueries EQ;
2883
2884 // Handle failed queries.
2885 for (auto &SN : ER.Failed)
2886 IL_collectQueries(
2887 EQ.Failed, SN->defs(),
2888 [](JITDylib::SymbolTableEntry &E) {
2889 E.setFlags(E.getFlags() = JITSymbolFlags::HasError);
2890 },
2891 [&](AsynchronousSymbolQuery &Q, JITDylib &JD,
2892 NonOwningSymbolStringPtr Name, JITDylib::SymbolTableEntry &E) {
2893 auto &FS = EQ.FailedSymsForQuery[&Q];
2894 if (!FS)
2895 FS = std::make_shared<SymbolDependenceMap>();
2896 (*FS)[&JD].insert(SymbolStringPtr(Name));
2897 });
2898
2899 for (auto &FQ : EQ.Failed)
2900 FQ->detach();
2901
2902 for (auto &SN : ER.Ready)
2903 IL_collectQueries(
2904 EQ.Completed, SN->defs(),
2905 [](JITDylib::SymbolTableEntry &E) { E.setState(SymbolState::Ready); },
2906 [](AsynchronousSymbolQuery &Q, JITDylib &JD,
2907 NonOwningSymbolStringPtr Name, JITDylib::SymbolTableEntry &E) {
2908 Q.notifySymbolMetRequiredState(SymbolStringPtr(Name), E.getSymbol());
2909 });
2910
2911 // std::erase_if is not available in C++17, and llvm::erase_if does not work
2912 // here.
2913 for (auto it = EQ.Completed.begin(), end = EQ.Completed.end(); it != end;) {
2914 if ((*it)->isComplete()) {
2915 ++it;
2916 } else {
2917 it = EQ.Completed.erase(it);
2918 }
2919 }
2920
2921#ifdef EXPENSIVE_CHECKS
2922 verifySessionState("exiting ExecutionSession::IL_emit");
2923#endif
2924
2925 return std::move(EQ);
2926}
2927
2928Error ExecutionSession::OL_notifyEmitted(
2931 LLVM_DEBUG({
2932 dbgs() << "In " << MR.JD.getName() << " emitting " << MR.SymbolFlags
2933 << "\n";
2934 if (!DepGroups.empty()) {
2935 dbgs() << " Initial dependencies:\n";
2936 for (auto &SDG : DepGroups) {
2937 dbgs() << " Symbols: " << SDG.Symbols
2938 << ", Dependencies: " << SDG.Dependencies << "\n";
2939 }
2940 }
2941 });
2942
2943#ifndef NDEBUG
2944 SymbolNameSet Visited;
2945 for (auto &DG : DepGroups) {
2946 for (auto &Sym : DG.Symbols) {
2947 assert(MR.SymbolFlags.count(Sym) &&
2948 "DG contains dependence for symbol outside this MR");
2949 assert(Visited.insert(Sym).second &&
2950 "DG contains duplicate entries for Name");
2951 }
2952 }
2953#endif // NDEBUG
2954
2955 std::vector<std::unique_ptr<WaitingOnGraph::SuperNode>> SNs;
2957 {
2958 auto &JDResidual = Residual[&MR.getTargetJITDylib()];
2959 for (auto &[Name, Flags] : MR.getSymbols())
2960 JDResidual.insert(NonOwningSymbolStringPtr(Name));
2961
2962 for (auto &SDG : DepGroups) {
2964 assert(!SDG.Symbols.empty());
2965 auto &JDDefs = Defs[&MR.getTargetJITDylib()];
2966 for (auto &Def : SDG.Symbols) {
2967 JDDefs.insert(NonOwningSymbolStringPtr(Def));
2968 JDResidual.erase(NonOwningSymbolStringPtr(Def));
2969 }
2971 if (!SDG.Dependencies.empty()) {
2972 for (auto &[JD, Syms] : SDG.Dependencies) {
2973 auto &JDDeps = Deps[JD];
2974 for (auto &Dep : Syms)
2975 JDDeps.insert(NonOwningSymbolStringPtr(Dep));
2976 }
2977 }
2978 SNs.push_back(std::make_unique<WaitingOnGraph::SuperNode>(
2979 std::move(Defs), std::move(Deps)));
2980 }
2981 if (!JDResidual.empty())
2982 SNs.push_back(std::make_unique<WaitingOnGraph::SuperNode>(
2983 std::move(Residual), WaitingOnGraph::ContainerElementsMap()));
2984 }
2985
2986 auto SR = WaitingOnGraph::simplify(std::move(SNs));
2987
2988 LLVM_DEBUG({
2989 dbgs() << " Simplified dependencies:\n";
2990 for (auto &SN : SR.superNodes()) {
2991
2992 auto SortedLibs = [](WaitingOnGraph::ContainerElementsMap &C) {
2993 std::vector<JITDylib *> JDs;
2994 for (auto &[JD, _] : C)
2995 JDs.push_back(JD);
2996 llvm::sort(JDs, [](const JITDylib *LHS, const JITDylib *RHS) {
2997 return LHS->getName() < RHS->getName();
2998 });
2999 return JDs;
3000 };
3001
3002 auto SortedNames = [](WaitingOnGraph::ElementSet &Elems) {
3003 std::vector<NonOwningSymbolStringPtr> Names(Elems.begin(), Elems.end());
3004 llvm::sort(Names, [](const NonOwningSymbolStringPtr &LHS,
3005 const NonOwningSymbolStringPtr &RHS) {
3006 return *LHS < *RHS;
3007 });
3008 return Names;
3009 };
3010
3011 dbgs() << " Defs: {";
3012 for (auto *JD : SortedLibs(SN->defs())) {
3013 dbgs() << " (" << JD->getName() << ", [";
3014 for (auto &Sym : SortedNames(SN->defs()[JD]))
3015 dbgs() << " " << Sym;
3016 dbgs() << " ])";
3017 }
3018 dbgs() << " }, Deps: {";
3019 for (auto *JD : SortedLibs(SN->deps())) {
3020 dbgs() << " (" << JD->getName() << ", [";
3021 for (auto &Sym : SortedNames(SN->deps()[JD]))
3022 dbgs() << " " << Sym;
3023 dbgs() << " ])";
3024 }
3025 dbgs() << " }\n";
3026 }
3027 });
3028 auto EmitQueries =
3029 runSessionLocked([&]() { return IL_emit(MR, std::move(SR)); });
3030
3031 // On error bail out.
3032 if (!EmitQueries)
3033 return EmitQueries.takeError();
3034
3035 // Otherwise notify failed queries, and any updated queries that have been
3036 // completed.
3037
3038 // FIXME: Get rid of error return from notifyEmitted.
3039 SymbolDependenceMap BadDeps;
3040 {
3041 for (auto &FQ : EmitQueries->Failed) {
3042 FQ->detach();
3043 assert(EmitQueries->FailedSymsForQuery.count(FQ.get()) &&
3044 "Missing failed symbols for query");
3045 auto FailedSyms = std::move(EmitQueries->FailedSymsForQuery[FQ.get()]);
3046 for (auto &[JD, Syms] : *FailedSyms) {
3047 auto &BadDepsForJD = BadDeps[JD];
3048 for (auto &Sym : Syms)
3049 BadDepsForJD.insert(Sym);
3050 }
3052 std::move(FailedSyms)));
3053 }
3054 }
3055
3056 for (auto &UQ : EmitQueries->Completed)
3057 UQ->handleComplete(*this);
3058
3059 // If there are any bad dependencies then return an error.
3060 if (!BadDeps.empty()) {
3061 SymbolNameSet BadNames;
3062 // Note: The name set calculated here is bogus: it includes all symbols in
3063 // the MR, not just the ones that failed. We want to remove the error
3064 // return path from notifyEmitted anyway, so this is just a brief
3065 // placeholder to maintain (roughly) the current error behavior.
3066 for (auto &[Name, Flags] : MR.getSymbols())
3067 BadNames.insert(Name);
3068 MR.SymbolFlags.clear();
3070 getSymbolStringPool(), &MR.getTargetJITDylib(), std::move(BadNames),
3071 std::move(BadDeps), "dependencies removed or in error state");
3072 }
3073
3074 MR.SymbolFlags.clear();
3075 return Error::success();
3076}
3077
3078Error ExecutionSession::OL_defineMaterializing(
3079 MaterializationResponsibility &MR, SymbolFlagsMap NewSymbolFlags) {
3080
3081 LLVM_DEBUG({
3082 dbgs() << "In " << MR.JD.getName() << " defining materializing symbols "
3083 << NewSymbolFlags << "\n";
3084 });
3085 if (auto AcceptedDefs =
3086 MR.JD.defineMaterializing(MR, std::move(NewSymbolFlags))) {
3087 // Add all newly accepted symbols to this responsibility object.
3088 for (auto &KV : *AcceptedDefs)
3089 MR.SymbolFlags.insert(KV);
3090 return Error::success();
3091 } else
3092 return AcceptedDefs.takeError();
3093}
3094
3095std::pair<JITDylib::AsynchronousSymbolQuerySet,
3096 std::shared_ptr<SymbolDependenceMap>>
3097ExecutionSession::IL_failSymbols(JITDylib &JD,
3098 const SymbolNameVector &SymbolsToFail) {
3099
3100#ifdef EXPENSIVE_CHECKS
3101 verifySessionState("entering ExecutionSession::IL_failSymbols");
3102#endif
3103
3104 JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3105 auto Fail = [&](JITDylib *FailJD, NonOwningSymbolStringPtr FailSym) {
3106 auto I = FailJD->Symbols.find_as(FailSym);
3107 assert(I != FailJD->Symbols.end());
3108 I->second.setFlags(I->second.getFlags() | JITSymbolFlags::HasError);
3109 auto J = FailJD->MaterializingInfos.find_as(FailSym);
3110 if (J != FailJD->MaterializingInfos.end()) {
3111 for (auto &Q : J->second.takeAllPendingQueries())
3112 FailedQueries.insert(std::move(Q));
3113 FailJD->MaterializingInfos.erase(J);
3114 }
3115 };
3116
3117 auto FailedSymbolsMap = std::make_shared<SymbolDependenceMap>();
3118
3119 {
3120 auto &FailedSymsForJD = (*FailedSymbolsMap)[&JD];
3121 for (auto &Sym : SymbolsToFail) {
3122 FailedSymsForJD.insert(Sym);
3123 Fail(&JD, NonOwningSymbolStringPtr(Sym));
3124 }
3125 }
3126
3128 auto &JDToFail = ToFail[&JD];
3129 for (auto &Sym : SymbolsToFail)
3130 JDToFail.insert(NonOwningSymbolStringPtr(Sym));
3131
3132 auto FailedSNs = G.fail(ToFail);
3133
3134 for (auto &SN : FailedSNs) {
3135 for (auto &[FailJD, Defs] : SN->defs()) {
3136 auto &FailedSymsForFailJD = (*FailedSymbolsMap)[FailJD];
3137 for (auto &Def : Defs) {
3138 FailedSymsForFailJD.insert(SymbolStringPtr(Def));
3139 Fail(FailJD, Def);
3140 }
3141 }
3142 }
3143
3144 // Detach all failed queries.
3145 for (auto &Q : FailedQueries)
3146 Q->detach();
3147
3148#ifdef EXPENSIVE_CHECKS
3149 verifySessionState("exiting ExecutionSession::IL_failSymbols");
3150#endif
3151
3152 return std::make_pair(std::move(FailedQueries), std::move(FailedSymbolsMap));
3153}
3154
3155void ExecutionSession::OL_notifyFailed(MaterializationResponsibility &MR) {
3156
3157 LLVM_DEBUG({
3158 dbgs() << "In " << MR.JD.getName() << " failing materialization for "
3159 << MR.SymbolFlags << "\n";
3160 });
3161
3162 if (MR.SymbolFlags.empty())
3163 return;
3164
3165 SymbolNameVector SymbolsToFail;
3166 for (auto &[Name, Flags] : MR.SymbolFlags)
3167 SymbolsToFail.push_back(Name);
3168 MR.SymbolFlags.clear();
3169
3170 JITDylib::AsynchronousSymbolQuerySet FailedQueries;
3171 std::shared_ptr<SymbolDependenceMap> FailedSymbols;
3172
3173 std::tie(FailedQueries, FailedSymbols) = runSessionLocked([&]() {
3174 // If the tracker is defunct then there's nothing to do here.
3175 if (MR.RT->isDefunct())
3176 return std::pair<JITDylib::AsynchronousSymbolQuerySet,
3177 std::shared_ptr<SymbolDependenceMap>>();
3178 return IL_failSymbols(MR.getTargetJITDylib(), SymbolsToFail);
3179 });
3180
3181 for (auto &Q : FailedQueries) {
3182 Q->detach();
3183 Q->handleFailed(
3185 }
3186}
3187
3188Error ExecutionSession::OL_replace(MaterializationResponsibility &MR,
3189 std::unique_ptr<MaterializationUnit> MU) {
3190 for (auto &KV : MU->getSymbols()) {
3191 assert(MR.SymbolFlags.count(KV.first) &&
3192 "Replacing definition outside this responsibility set");
3193 MR.SymbolFlags.erase(KV.first);
3194 }
3195
3196 if (MU->getInitializerSymbol() == MR.InitSymbol)
3197 MR.InitSymbol = nullptr;
3198
3199 LLVM_DEBUG(MR.JD.getExecutionSession().runSessionLocked([&]() {
3200 dbgs() << "In " << MR.JD.getName() << " replacing symbols with " << *MU
3201 << "\n";
3202 }););
3203
3204 return MR.JD.replace(MR, std::move(MU));
3205}
3206
3207Expected<std::unique_ptr<MaterializationResponsibility>>
3208ExecutionSession::OL_delegate(MaterializationResponsibility &MR,
3209 const SymbolNameSet &Symbols) {
3210
3211 SymbolStringPtr DelegatedInitSymbol;
3212 SymbolFlagsMap DelegatedFlags;
3213
3214 for (auto &Name : Symbols) {
3215 auto I = MR.SymbolFlags.find(Name);
3216 assert(I != MR.SymbolFlags.end() &&
3217 "Symbol is not tracked by this MaterializationResponsibility "
3218 "instance");
3219
3220 DelegatedFlags[Name] = std::move(I->second);
3221 if (Name == MR.InitSymbol)
3222 std::swap(MR.InitSymbol, DelegatedInitSymbol);
3223
3224 MR.SymbolFlags.erase(I);
3225 }
3226
3227 return MR.JD.delegate(MR, std::move(DelegatedFlags),
3228 std::move(DelegatedInitSymbol));
3229}
3230
3231#ifndef NDEBUG
3232void ExecutionSession::dumpDispatchInfo(Task &T) {
3233 runSessionLocked([&]() {
3234 dbgs() << "Dispatching: ";
3235 T.printDescription(dbgs());
3236 dbgs() << "\n";
3237 });
3238}
3239#endif // NDEBUG
3240
3241} // End namespace orc.
3242} // End namespace llvm.
#define Fail
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
aarch64 falkor hwpf fix Falkor HW Prefetch Fix Late Phase
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define _
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
#define G(x, y, z)
Definition MD5.cpp:56
#define H(x, y, z)
Definition MD5.cpp:57
#define T
if(PassOpts->AAPipeline)
static StringRef getName(Value *V)
This file contains some templates that are useful if you are working with the STL at all.
#define LLVM_DEBUG(...)
Definition Debug.h:114
Value * RHS
Value * LHS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
const T & front() const
front - Get the first element.
Definition ArrayRef.h:146
size_t size() const
size - Get the array size.
Definition ArrayRef.h:143
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:138
const T * data() const
Definition ArrayRef.h:140
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
bool erase(const KeyT &Val)
Definition DenseMap.h:322
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
Definition DenseMap.h:191
unsigned size() const
Definition DenseMap.h:110
bool empty() const
Definition DenseMap.h:109
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:174
iterator end()
Definition DenseMap.h:81
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:233
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
Helper for Errors used as out-parameters.
Definition Error.h:1144
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
bool hasMaterializationSideEffectsOnly() const
Returns true if this symbol is a materialization-side-effects-only symbol.
Definition JITSymbol.h:162
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:202
void reserve(size_t Size)
Grow the DenseSet so that it can contain at least NumEntries items before resizing again.
Definition DenseSet.h:96
void insert_range(Range &&R)
Definition DenseSet.h:228
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:180
A symbol query that returns results via a callback when results are ready.
Definition Core.h:789
LLVM_ABI AsynchronousSymbolQuery(const SymbolLookupSet &Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete)
Create a query for the given symbols.
Definition Core.cpp:201
LLVM_ABI void notifySymbolMetRequiredState(const SymbolStringPtr &Name, ExecutorSymbolDef Sym)
Notify the query that a requested symbol has reached the required state.
Definition Core.cpp:215
Definition generators can be attached to JITDylibs to generate new definitions for otherwise unresolv...
Definition Core.h:863
An ExecutionSession represents a running JIT program.
Definition Core.h:1342
LLVM_ABI Error endSession()
End the session.
Definition Core.cpp:1585
unique_function< void(shared::WrapperFunctionResult)> SendResultFunction
Send a result to the remote.
Definition Core.h:1355
void reportError(Error Err)
Report a error for this execution session.
Definition Core.h:1477
friend class JITDylib
Definition Core.h:1345
LLVM_ABI void lookupFlags(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet Symbols, unique_function< void(Expected< SymbolFlagsMap >)> OnComplete)
Search the given JITDylibs to find the flags associated with each of the given symbols.
Definition Core.cpp:1745
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition Core.h:1396
LLVM_ABI JITDylib * getJITDylibByName(StringRef Name)
Return a pointer to the "name" JITDylib.
Definition Core.cpp:1624
friend class LookupState
Definition Core.h:1346
LLVM_ABI JITDylib & createBareJITDylib(std::string Name)
Add a new bare JITDylib to this ExecutionSession.
Definition Core.cpp:1633
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
Definition Core.h:1391
LLVM_ABI void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete, RegisterDependenciesFunction RegisterDependencies)
Search the given JITDylibs for the given symbols.
Definition Core.cpp:1771
LLVM_ABI Error registerJITDispatchHandlers(JITDylib &JD, JITDispatchHandlerAssociationMap WFs)
For each tag symbol name, associate the corresponding AsyncHandlerWrapperFunction with the address of...
Definition Core.cpp:1866
LLVM_ABI void registerResourceManager(ResourceManager &RM)
Register the given ResourceManager with this ExecutionSession.
Definition Core.cpp:1607
LLVM_ABI ~ExecutionSession()
Destroy an ExecutionSession.
Definition Core.cpp:1579
LLVM_ABI void runJITDispatchHandler(SendResultFunction SendResult, ExecutorAddr HandlerFnTagAddr, ArrayRef< char > ArgBuffer)
Run a registered jit-side wrapper function.
Definition Core.cpp:1905
LLVM_ABI void deregisterResourceManager(ResourceManager &RM)
Deregister the given ResourceManager with this ExecutionSession.
Definition Core.cpp:1611
LLVM_ABI ExecutionSession(std::unique_ptr< ExecutorProcessControl > EPC)
Construct an ExecutionSession with the given ExecutorProcessControl object.
Definition Core.cpp:1573
decltype(auto) runSessionLocked(Func &&F)
Run the given lambda with the session mutex locked.
Definition Core.h:1406
LLVM_ABI void dump(raw_ostream &OS)
Dump the state of all the JITDylibs in this session.
Definition Core.cpp:1926
LLVM_ABI Error removeJITDylibs(std::vector< JITDylibSP > JDsToRemove)
Removes the given JITDylibs from the ExecutionSession.
Definition Core.cpp:1650
LLVM_ABI Expected< JITDylib & > createJITDylib(std::string Name)
Add a new JITDylib to this ExecutionSession.
Definition Core.cpp:1642
void dispatchTask(std::unique_ptr< Task > T)
Materialize the given unit.
Definition Core.h:1551
DenseMap< SymbolStringPtr, JITDispatchHandlerFunction > JITDispatchHandlerAssociationMap
A map associating tag names with asynchronous wrapper function implementations in the JIT.
Definition Core.h:1365
Represents an address in the executor process.
Represents a defining location for a JIT symbol.
const JITSymbolFlags & getFlags() const
FailedToMaterialize(std::shared_ptr< SymbolStringPool > SSP, std::shared_ptr< SymbolDependenceMap > Symbols)
Definition Core.cpp:82
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:100
~FailedToMaterialize() override
Definition Core.cpp:95
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:104
InProgressFullLookupState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, SymbolState RequiredState, std::shared_ptr< AsynchronousSymbolQuery > Q, RegisterDependenciesFunction RegisterDependencies)
Definition Core.cpp:565
void complete(std::unique_ptr< InProgressLookupState > IPLS) override
Definition Core.cpp:575
void fail(Error Err) override
Definition Core.cpp:581
void complete(std::unique_ptr< InProgressLookupState > IPLS) override
Definition Core.cpp:552
void fail(Error Err) override
Definition Core.cpp:557
InProgressLookupFlagsState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, unique_function< void(Expected< SymbolFlagsMap >)> OnComplete)
Definition Core.cpp:545
virtual ~InProgressLookupState()=default
SymbolLookupSet DefGeneratorCandidates
Definition Core.cpp:532
JITDylibSearchOrder SearchOrder
Definition Core.cpp:526
std::vector< std::weak_ptr< DefinitionGenerator > > CurDefGeneratorStack
Definition Core.cpp:540
virtual void complete(std::unique_ptr< InProgressLookupState > IPLS)=0
InProgressLookupState(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet, SymbolState RequiredState)
Definition Core.cpp:515
SymbolLookupSet DefGeneratorNonCandidates
Definition Core.cpp:533
virtual void fail(Error Err)=0
Represents a JIT'd dynamic library.
Definition Core.h:906
LLVM_ABI ~JITDylib()
Definition Core.cpp:652
LLVM_ABI Error remove(const SymbolNameSet &Names)
Tries to remove the given symbols.
Definition Core.cpp:1059
LLVM_ABI Error clear()
Calls remove on all trackers currently associated with this JITDylib.
Definition Core.cpp:656
LLVM_ABI void dump(raw_ostream &OS)
Dump current JITDylib state to OS.
Definition Core.cpp:1120
LLVM_ABI void replaceInLinkOrder(JITDylib &OldJD, JITDylib &NewJD, JITDylibLookupFlags JDLookupFlags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Replace OldJD with NewJD in the link order if OldJD is present.
Definition Core.cpp:1035
Error define(std::unique_ptr< MaterializationUnitType > &&MU, ResourceTrackerSP RT=nullptr)
Define all symbols provided by the materialization unit to be part of this JITDylib.
Definition Core.h:1866
ExecutionSession & getExecutionSession() const
Get a reference to the ExecutionSession for this JITDylib.
Definition Core.h:925
LLVM_ABI void addToLinkOrder(const JITDylibSearchOrder &NewLinks)
Append the given JITDylibSearchOrder to the link order for this JITDylib (discarding any elements alr...
Definition Core.cpp:1019
LLVM_ABI ResourceTrackerSP createResourceTracker()
Create a resource tracker for this JITDylib.
Definition Core.cpp:680
LLVM_ABI void removeFromLinkOrder(JITDylib &JD)
Remove the given JITDylib from the link order for this JITDylib if it is present.
Definition Core.cpp:1047
LLVM_ABI void setLinkOrder(JITDylibSearchOrder NewSearchOrder, bool LinkAgainstThisJITDylibFirst=true)
Set the link order to be used when fixing up definitions in JITDylib.
Definition Core.cpp:1004
LLVM_ABI Expected< std::vector< JITDylibSP > > getReverseDFSLinkOrder()
Rteurn this JITDylib and its transitive dependencies in reverse DFS order based on linkage relationsh...
Definition Core.cpp:1741
LLVM_ABI ResourceTrackerSP getDefaultResourceTracker()
Get the default resource tracker for this JITDylib.
Definition Core.cpp:671
JITDylib(const JITDylib &)=delete
LLVM_ABI void removeGenerator(DefinitionGenerator &G)
Remove a definition generator from this JITDylib.
Definition Core.cpp:688
LLVM_ABI Expected< std::vector< JITDylibSP > > getDFSLinkOrder()
Return this JITDylib and its transitive dependencies in DFS order based on linkage relationships.
Definition Core.cpp:1737
Wraps state for a lookup-in-progress.
Definition Core.h:838
LLVM_ABI void continueLookup(Error Err)
Continue the lookup.
Definition Core.cpp:632
LLVM_ABI LookupState & operator=(LookupState &&)
void run() override
Definition Core.cpp:1571
static char ID
Definition Core.h:1331
void printDescription(raw_ostream &OS) override
Definition Core.cpp:1569
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
Definition Core.h:580
void printDescription(raw_ostream &OS) override
Definition Core.cpp:1558
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:162
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:166
Non-owning SymbolStringPool entry pointer.
static void lookupInitSymbolsAsync(unique_function< void(Error)> OnComplete, ExecutionSession &ES, const DenseMap< JITDylib *, SymbolLookupSet > &InitSyms)
Performs an async lookup for the given symbols in each of the given JITDylibs, calling the given hand...
Definition Core.cpp:1509
static Expected< DenseMap< JITDylib *, SymbolMap > > lookupInitSymbols(ExecutionSession &ES, const DenseMap< JITDylib *, SymbolLookupSet > &InitSyms)
A utility function for looking up initializer symbols.
Definition Core.cpp:1460
StringRef getName() const override
Return the name of this materialization unit.
Definition Core.cpp:306
ReExportsMaterializationUnit(JITDylib *SourceJD, JITDylibLookupFlags SourceJDLookupFlags, SymbolAliasMap Aliases)
SourceJD is allowed to be nullptr, in which case the source JITDylib is taken to be whatever JITDylib...
Definition Core.cpp:300
std::function< bool(SymbolStringPtr)> SymbolPredicate
Definition Core.h:1955
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &LookupSet) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
Definition Core.cpp:597
ReexportsGenerator(JITDylib &SourceJD, JITDylibLookupFlags SourceJDLookupFlags, SymbolPredicate Allow=SymbolPredicate())
Create a reexports generator.
Definition Core.cpp:591
Listens for ResourceTracker operations.
Definition Core.h:130
ResourceTrackerDefunct(ResourceTrackerSP RT)
Definition Core.cpp:71
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:78
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:74
API to remove / transfer ownership of JIT resources.
Definition Core.h:82
JITDylib & getJITDylib() const
Return the JITDylib targeted by this tracker.
Definition Core.h:97
LLVM_ABI void transferTo(ResourceTracker &DstRT)
Transfer all resources associated with this key to the given tracker, which must target the same JITD...
Definition Core.cpp:59
LLVM_ABI ~ResourceTracker()
Definition Core.cpp:50
ResourceTracker(const ResourceTracker &)=delete
LLVM_ABI Error remove()
Remove all resources associated with this key.
Definition Core.cpp:55
LLVM_ABI void lookupAsync(LookupAsyncOnCompleteFn OnComplete) const
Definition Core.cpp:180
unique_function< void(Expected< ExecutorSymbolDef >)> LookupAsyncOnCompleteFn
Definition Core.h:62
A set of symbols to look up, each associated with a SymbolLookupFlags value.
Definition Core.h:199
static SymbolLookupSet fromMapKeys(const DenseMap< SymbolStringPtr, ValT > &M, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Construct a SymbolLookupSet from DenseMap keys.
Definition Core.h:253
Pointer to a pooled string representing a symbol name.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:154
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:158
SymbolsCouldNotBeRemoved(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
Definition Core.cpp:148
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:144
SymbolsNotFound(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
Definition Core.cpp:127
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:140
Represents an abstract task for ORC to run.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:171
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:175
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:120
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:116
UnsatisfiedSymbolDependencies(std::shared_ptr< SymbolStringPool > SSP, JITDylibSP JD, SymbolNameSet FailedSymbols, SymbolDependenceMap BadDeps, std::string Explanation)
Definition Core.cpp:108
static SimplifyResult simplify(std::vector< std::unique_ptr< SuperNode > > SNs)
static WrapperFunctionResult createOutOfBandError(const char *Msg)
Create an out-of-band error by copying the given string.
A raw_ostream that writes to a file descriptor.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
unique_function is a type-erasing functor similar to std::function.
@ Entry
Definition COFF.h:862
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
SymbolFlags
Symbol flags.
Definition Symbol.h:25
JITDylibSearchOrder makeJITDylibSearchOrder(ArrayRef< JITDylib * > JDs, JITDylibLookupFlags Flags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Convenience function for creating a search order from an ArrayRef of JITDylib*, all with the same fla...
Definition Core.h:182
std::vector< std::pair< JITDylib *, JITDylibLookupFlags > > JITDylibSearchOrder
A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search order during symbol lookup.
Definition Core.h:177
IntrusiveRefCntPtr< JITDylib > JITDylibSP
Definition Core.h:57
IntrusiveRefCntPtr< ResourceTracker > ResourceTrackerSP
Definition Core.h:56
std::unique_ptr< ReExportsMaterializationUnit > symbolAliases(SymbolAliasMap Aliases)
Create a ReExportsMaterializationUnit with the given aliases.
Definition Core.h:754
std::function< void(const SymbolDependenceMap &)> RegisterDependenciesFunction
Callback to register the dependencies for a given query.
Definition Core.h:423
SymbolLookupFlags
Lookup flags that apply to each symbol in a lookup.
Definition Core.h:161
std::unique_ptr< ReExportsMaterializationUnit > reexports(JITDylib &SourceJD, SymbolAliasMap Aliases, JITDylibLookupFlags SourceJDLookupFlags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Create a materialization unit for re-exporting symbols from another JITDylib with alternative names/f...
Definition Core.h:763
LLVM_ABI Expected< SymbolAliasMap > buildSimpleReexportsAliasMap(JITDylib &SourceJD, const SymbolNameSet &Symbols)
Build a SymbolAliasMap for the common case where you want to re-export symbols from another JITDylib ...
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
Definition Core.h:151
DenseMap< SymbolStringPtr, ExecutorSymbolDef > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
LookupKind
Describes the kind of lookup being performed.
Definition Core.h:173
LLVM_ABI RegisterDependenciesFunction NoDependenciesToRegister
This can be used as the value for a RegisterDependenciesFunction if there are no dependants to regist...
Definition Core.cpp:38
std::vector< SymbolStringPtr > SymbolNameVector
A vector of symbol names.
DenseMap< JITDylib *, SymbolNameSet > SymbolDependenceMap
A map from JITDylibs to sets of symbols.
DenseSet< SymbolStringPtr > SymbolNameSet
A set of symbol names (represented by SymbolStringPtrs for.
SymbolState
Represents the state that a symbol has reached during materialization.
Definition Core.h:776
@ Materializing
Added to the symbol table, never queried.
Definition Core.h:779
@ NeverSearched
No symbol should be in this state.
Definition Core.h:778
@ Ready
Emitted to memory, but waiting on transitive dependencies.
Definition Core.h:782
@ Resolved
Queried, materialization begun.
Definition Core.h:780
DenseMap< SymbolStringPtr, SymbolAliasMapEntry > SymbolAliasMap
A map of Symbols to (Symbol, Flags) pairs.
Definition Core.h:417
LLVM_ABI std::error_code orcError(OrcErrorCode ErrCode)
Definition OrcError.cpp:84
unique_function< void(Expected< SymbolMap >)> SymbolsResolvedCallback
Callback to notify client that symbols have been resolved.
Definition Core.h:420
DenseMap< SymbolStringPtr, JITSymbolFlags > SymbolFlagsMap
A map from symbol names (as SymbolStringPtrs) to JITSymbolFlags.
This is an optimization pass for GlobalISel generic memory operations.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1751
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:98
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2136
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:406
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition Error.h:442
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1622
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:129
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:1994
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1867
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1758
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1897
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:867
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:869
#define EQ(a, b)
Definition regexec.c:65