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