forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCore.cpp
3029 lines (2535 loc) · 106 KB
/
Core.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- Core.cpp - Core ORC APIs (MaterializationUnit, JITDylib, etc.) ---===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/ExecutionEngine/Orc/Core.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/ExecutionEngine/Orc/DebugUtils.h"
#include "llvm/ExecutionEngine/Orc/Shared/OrcError.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/MSVCErrorWorkarounds.h"
#include <condition_variable>
#include <future>
#define DEBUG_TYPE "orc"
namespace llvm {
namespace orc {
char ResourceTrackerDefunct::ID = 0;
char FailedToMaterialize::ID = 0;
char SymbolsNotFound::ID = 0;
char SymbolsCouldNotBeRemoved::ID = 0;
char MissingSymbolDefinitions::ID = 0;
char UnexpectedSymbolDefinitions::ID = 0;
char MaterializationTask::ID = 0;
RegisterDependenciesFunction NoDependenciesToRegister =
RegisterDependenciesFunction();
void MaterializationUnit::anchor() {}
ResourceTracker::ResourceTracker(JITDylibSP JD) {
assert((reinterpret_cast<uintptr_t>(JD.get()) & 0x1) == 0 &&
"JITDylib must be two byte aligned");
JD->Retain();
JDAndFlag.store(reinterpret_cast<uintptr_t>(JD.get()));
}
ResourceTracker::~ResourceTracker() {
getJITDylib().getExecutionSession().destroyResourceTracker(*this);
getJITDylib().Release();
}
Error ResourceTracker::remove() {
return getJITDylib().getExecutionSession().removeResourceTracker(*this);
}
void ResourceTracker::transferTo(ResourceTracker &DstRT) {
getJITDylib().getExecutionSession().transferResourceTracker(DstRT, *this);
}
void ResourceTracker::makeDefunct() {
uintptr_t Val = JDAndFlag.load();
Val |= 0x1U;
JDAndFlag.store(Val);
}
ResourceManager::~ResourceManager() = default;
ResourceTrackerDefunct::ResourceTrackerDefunct(ResourceTrackerSP RT)
: RT(std::move(RT)) {}
std::error_code ResourceTrackerDefunct::convertToErrorCode() const {
return orcError(OrcErrorCode::UnknownORCError);
}
void ResourceTrackerDefunct::log(raw_ostream &OS) const {
OS << "Resource tracker " << (void *)RT.get() << " became defunct";
}
FailedToMaterialize::FailedToMaterialize(
std::shared_ptr<SymbolDependenceMap> Symbols)
: Symbols(std::move(Symbols)) {
assert(!this->Symbols->empty() && "Can not fail to resolve an empty set");
}
std::error_code FailedToMaterialize::convertToErrorCode() const {
return orcError(OrcErrorCode::UnknownORCError);
}
void FailedToMaterialize::log(raw_ostream &OS) const {
OS << "Failed to materialize symbols: " << *Symbols;
}
SymbolsNotFound::SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP,
SymbolNameSet Symbols)
: SSP(std::move(SSP)) {
for (auto &Sym : Symbols)
this->Symbols.push_back(Sym);
assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
}
SymbolsNotFound::SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP,
SymbolNameVector Symbols)
: SSP(std::move(SSP)), Symbols(std::move(Symbols)) {
assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
}
std::error_code SymbolsNotFound::convertToErrorCode() const {
return orcError(OrcErrorCode::UnknownORCError);
}
void SymbolsNotFound::log(raw_ostream &OS) const {
OS << "Symbols not found: " << Symbols;
}
SymbolsCouldNotBeRemoved::SymbolsCouldNotBeRemoved(
std::shared_ptr<SymbolStringPool> SSP, SymbolNameSet Symbols)
: SSP(std::move(SSP)), Symbols(std::move(Symbols)) {
assert(!this->Symbols.empty() && "Can not fail to resolve an empty set");
}
std::error_code SymbolsCouldNotBeRemoved::convertToErrorCode() const {
return orcError(OrcErrorCode::UnknownORCError);
}
void SymbolsCouldNotBeRemoved::log(raw_ostream &OS) const {
OS << "Symbols could not be removed: " << Symbols;
}
std::error_code MissingSymbolDefinitions::convertToErrorCode() const {
return orcError(OrcErrorCode::MissingSymbolDefinitions);
}
void MissingSymbolDefinitions::log(raw_ostream &OS) const {
OS << "Missing definitions in module " << ModuleName
<< ": " << Symbols;
}
std::error_code UnexpectedSymbolDefinitions::convertToErrorCode() const {
return orcError(OrcErrorCode::UnexpectedSymbolDefinitions);
}
void UnexpectedSymbolDefinitions::log(raw_ostream &OS) const {
OS << "Unexpected definitions in module " << ModuleName
<< ": " << Symbols;
}
AsynchronousSymbolQuery::AsynchronousSymbolQuery(
const SymbolLookupSet &Symbols, SymbolState RequiredState,
SymbolsResolvedCallback NotifyComplete)
: NotifyComplete(std::move(NotifyComplete)), RequiredState(RequiredState) {
assert(RequiredState >= SymbolState::Resolved &&
"Cannot query for a symbols that have not reached the resolve state "
"yet");
OutstandingSymbolsCount = Symbols.size();
for (auto &KV : Symbols)
ResolvedSymbols[KV.first] = nullptr;
}
void AsynchronousSymbolQuery::notifySymbolMetRequiredState(
const SymbolStringPtr &Name, JITEvaluatedSymbol Sym) {
auto I = ResolvedSymbols.find(Name);
assert(I != ResolvedSymbols.end() &&
"Resolving symbol outside the requested set");
assert(I->second.getAddress() == 0 && "Redundantly resolving symbol Name");
// If this is a materialization-side-effects-only symbol then drop it,
// otherwise update its map entry with its resolved address.
if (Sym.getFlags().hasMaterializationSideEffectsOnly())
ResolvedSymbols.erase(I);
else
I->second = std::move(Sym);
--OutstandingSymbolsCount;
}
void AsynchronousSymbolQuery::handleComplete(ExecutionSession &ES) {
assert(OutstandingSymbolsCount == 0 &&
"Symbols remain, handleComplete called prematurely");
class RunQueryCompleteTask : public Task {
public:
RunQueryCompleteTask(SymbolMap ResolvedSymbols,
SymbolsResolvedCallback NotifyComplete)
: ResolvedSymbols(std::move(ResolvedSymbols)),
NotifyComplete(std::move(NotifyComplete)) {}
void printDescription(raw_ostream &OS) override {
OS << "Execute query complete callback for " << ResolvedSymbols;
}
void run() override { NotifyComplete(std::move(ResolvedSymbols)); }
private:
SymbolMap ResolvedSymbols;
SymbolsResolvedCallback NotifyComplete;
};
auto T = std::make_unique<RunQueryCompleteTask>(std::move(ResolvedSymbols),
std::move(NotifyComplete));
NotifyComplete = SymbolsResolvedCallback();
ES.dispatchTask(std::move(T));
}
void AsynchronousSymbolQuery::handleFailed(Error Err) {
assert(QueryRegistrations.empty() && ResolvedSymbols.empty() &&
OutstandingSymbolsCount == 0 &&
"Query should already have been abandoned");
NotifyComplete(std::move(Err));
NotifyComplete = SymbolsResolvedCallback();
}
void AsynchronousSymbolQuery::addQueryDependence(JITDylib &JD,
SymbolStringPtr Name) {
bool Added = QueryRegistrations[&JD].insert(std::move(Name)).second;
(void)Added;
assert(Added && "Duplicate dependence notification?");
}
void AsynchronousSymbolQuery::removeQueryDependence(
JITDylib &JD, const SymbolStringPtr &Name) {
auto QRI = QueryRegistrations.find(&JD);
assert(QRI != QueryRegistrations.end() &&
"No dependencies registered for JD");
assert(QRI->second.count(Name) && "No dependency on Name in JD");
QRI->second.erase(Name);
if (QRI->second.empty())
QueryRegistrations.erase(QRI);
}
void AsynchronousSymbolQuery::dropSymbol(const SymbolStringPtr &Name) {
auto I = ResolvedSymbols.find(Name);
assert(I != ResolvedSymbols.end() &&
"Redundant removal of weakly-referenced symbol");
ResolvedSymbols.erase(I);
--OutstandingSymbolsCount;
}
void AsynchronousSymbolQuery::detach() {
ResolvedSymbols.clear();
OutstandingSymbolsCount = 0;
for (auto &KV : QueryRegistrations)
KV.first->detachQueryHelper(*this, KV.second);
QueryRegistrations.clear();
}
AbsoluteSymbolsMaterializationUnit::AbsoluteSymbolsMaterializationUnit(
SymbolMap Symbols)
: MaterializationUnit(extractFlags(Symbols)), Symbols(std::move(Symbols)) {}
StringRef AbsoluteSymbolsMaterializationUnit::getName() const {
return "<Absolute Symbols>";
}
void AbsoluteSymbolsMaterializationUnit::materialize(
std::unique_ptr<MaterializationResponsibility> R) {
// No dependencies, so these calls can't fail.
cantFail(R->notifyResolved(Symbols));
cantFail(R->notifyEmitted());
}
void AbsoluteSymbolsMaterializationUnit::discard(const JITDylib &JD,
const SymbolStringPtr &Name) {
assert(Symbols.count(Name) && "Symbol is not part of this MU");
Symbols.erase(Name);
}
MaterializationUnit::Interface
AbsoluteSymbolsMaterializationUnit::extractFlags(const SymbolMap &Symbols) {
SymbolFlagsMap Flags;
for (const auto &KV : Symbols)
Flags[KV.first] = KV.second.getFlags();
return MaterializationUnit::Interface(std::move(Flags), nullptr);
}
ReExportsMaterializationUnit::ReExportsMaterializationUnit(
JITDylib *SourceJD, JITDylibLookupFlags SourceJDLookupFlags,
SymbolAliasMap Aliases)
: MaterializationUnit(extractFlags(Aliases)), SourceJD(SourceJD),
SourceJDLookupFlags(SourceJDLookupFlags), Aliases(std::move(Aliases)) {}
StringRef ReExportsMaterializationUnit::getName() const {
return "<Reexports>";
}
void ReExportsMaterializationUnit::materialize(
std::unique_ptr<MaterializationResponsibility> R) {
auto &ES = R->getTargetJITDylib().getExecutionSession();
JITDylib &TgtJD = R->getTargetJITDylib();
JITDylib &SrcJD = SourceJD ? *SourceJD : TgtJD;
// Find the set of requested aliases and aliasees. Return any unrequested
// aliases back to the JITDylib so as to not prematurely materialize any
// aliasees.
auto RequestedSymbols = R->getRequestedSymbols();
SymbolAliasMap RequestedAliases;
for (auto &Name : RequestedSymbols) {
auto I = Aliases.find(Name);
assert(I != Aliases.end() && "Symbol not found in aliases map?");
RequestedAliases[Name] = std::move(I->second);
Aliases.erase(I);
}
LLVM_DEBUG({
ES.runSessionLocked([&]() {
dbgs() << "materializing reexports: target = " << TgtJD.getName()
<< ", source = " << SrcJD.getName() << " " << RequestedAliases
<< "\n";
});
});
if (!Aliases.empty()) {
auto Err = SourceJD ? R->replace(reexports(*SourceJD, std::move(Aliases),
SourceJDLookupFlags))
: R->replace(symbolAliases(std::move(Aliases)));
if (Err) {
// FIXME: Should this be reported / treated as failure to materialize?
// Or should this be treated as a sanctioned bailing-out?
ES.reportError(std::move(Err));
R->failMaterialization();
return;
}
}
// The OnResolveInfo struct will hold the aliases and responsibilty for each
// query in the list.
struct OnResolveInfo {
OnResolveInfo(std::unique_ptr<MaterializationResponsibility> R,
SymbolAliasMap Aliases)
: R(std::move(R)), Aliases(std::move(Aliases)) {}
std::unique_ptr<MaterializationResponsibility> R;
SymbolAliasMap Aliases;
};
// Build a list of queries to issue. In each round we build a query for the
// largest set of aliases that we can resolve without encountering a chain of
// aliases (e.g. Foo -> Bar, Bar -> Baz). Such a chain would deadlock as the
// query would be waiting on a symbol that it itself had to resolve. Creating
// a new query for each link in such a chain eliminates the possibility of
// deadlock. In practice chains are likely to be rare, and this algorithm will
// usually result in a single query to issue.
std::vector<std::pair<SymbolLookupSet, std::shared_ptr<OnResolveInfo>>>
QueryInfos;
while (!RequestedAliases.empty()) {
SymbolNameSet ResponsibilitySymbols;
SymbolLookupSet QuerySymbols;
SymbolAliasMap QueryAliases;
// Collect as many aliases as we can without including a chain.
for (auto &KV : RequestedAliases) {
// Chain detected. Skip this symbol for this round.
if (&SrcJD == &TgtJD && (QueryAliases.count(KV.second.Aliasee) ||
RequestedAliases.count(KV.second.Aliasee)))
continue;
ResponsibilitySymbols.insert(KV.first);
QuerySymbols.add(KV.second.Aliasee,
KV.second.AliasFlags.hasMaterializationSideEffectsOnly()
? SymbolLookupFlags::WeaklyReferencedSymbol
: SymbolLookupFlags::RequiredSymbol);
QueryAliases[KV.first] = std::move(KV.second);
}
// Remove the aliases collected this round from the RequestedAliases map.
for (auto &KV : QueryAliases)
RequestedAliases.erase(KV.first);
assert(!QuerySymbols.empty() && "Alias cycle detected!");
auto NewR = R->delegate(ResponsibilitySymbols);
if (!NewR) {
ES.reportError(NewR.takeError());
R->failMaterialization();
return;
}
auto QueryInfo = std::make_shared<OnResolveInfo>(std::move(*NewR),
std::move(QueryAliases));
QueryInfos.push_back(
make_pair(std::move(QuerySymbols), std::move(QueryInfo)));
}
// Issue the queries.
while (!QueryInfos.empty()) {
auto QuerySymbols = std::move(QueryInfos.back().first);
auto QueryInfo = std::move(QueryInfos.back().second);
QueryInfos.pop_back();
auto RegisterDependencies = [QueryInfo,
&SrcJD](const SymbolDependenceMap &Deps) {
// If there were no materializing symbols, just bail out.
if (Deps.empty())
return;
// Otherwise the only deps should be on SrcJD.
assert(Deps.size() == 1 && Deps.count(&SrcJD) &&
"Unexpected dependencies for reexports");
auto &SrcJDDeps = Deps.find(&SrcJD)->second;
SymbolDependenceMap PerAliasDepsMap;
auto &PerAliasDeps = PerAliasDepsMap[&SrcJD];
for (auto &KV : QueryInfo->Aliases)
if (SrcJDDeps.count(KV.second.Aliasee)) {
PerAliasDeps = {KV.second.Aliasee};
QueryInfo->R->addDependencies(KV.first, PerAliasDepsMap);
}
};
auto OnComplete = [QueryInfo](Expected<SymbolMap> Result) {
auto &ES = QueryInfo->R->getTargetJITDylib().getExecutionSession();
if (Result) {
SymbolMap ResolutionMap;
for (auto &KV : QueryInfo->Aliases) {
assert((KV.second.AliasFlags.hasMaterializationSideEffectsOnly() ||
Result->count(KV.second.Aliasee)) &&
"Result map missing entry?");
// Don't try to resolve materialization-side-effects-only symbols.
if (KV.second.AliasFlags.hasMaterializationSideEffectsOnly())
continue;
ResolutionMap[KV.first] = JITEvaluatedSymbol(
(*Result)[KV.second.Aliasee].getAddress(), KV.second.AliasFlags);
}
if (auto Err = QueryInfo->R->notifyResolved(ResolutionMap)) {
ES.reportError(std::move(Err));
QueryInfo->R->failMaterialization();
return;
}
if (auto Err = QueryInfo->R->notifyEmitted()) {
ES.reportError(std::move(Err));
QueryInfo->R->failMaterialization();
return;
}
} else {
ES.reportError(Result.takeError());
QueryInfo->R->failMaterialization();
}
};
ES.lookup(LookupKind::Static,
JITDylibSearchOrder({{&SrcJD, SourceJDLookupFlags}}),
QuerySymbols, SymbolState::Resolved, std::move(OnComplete),
std::move(RegisterDependencies));
}
}
void ReExportsMaterializationUnit::discard(const JITDylib &JD,
const SymbolStringPtr &Name) {
assert(Aliases.count(Name) &&
"Symbol not covered by this MaterializationUnit");
Aliases.erase(Name);
}
MaterializationUnit::Interface
ReExportsMaterializationUnit::extractFlags(const SymbolAliasMap &Aliases) {
SymbolFlagsMap SymbolFlags;
for (auto &KV : Aliases)
SymbolFlags[KV.first] = KV.second.AliasFlags;
return MaterializationUnit::Interface(std::move(SymbolFlags), nullptr);
}
Expected<SymbolAliasMap> buildSimpleReexportsAliasMap(JITDylib &SourceJD,
SymbolNameSet Symbols) {
SymbolLookupSet LookupSet(Symbols);
auto Flags = SourceJD.getExecutionSession().lookupFlags(
LookupKind::Static, {{&SourceJD, JITDylibLookupFlags::MatchAllSymbols}},
SymbolLookupSet(std::move(Symbols)));
if (!Flags)
return Flags.takeError();
SymbolAliasMap Result;
for (auto &Name : Symbols) {
assert(Flags->count(Name) && "Missing entry in flags map");
Result[Name] = SymbolAliasMapEntry(Name, (*Flags)[Name]);
}
return Result;
}
class InProgressLookupState {
public:
InProgressLookupState(LookupKind K, JITDylibSearchOrder SearchOrder,
SymbolLookupSet LookupSet, SymbolState RequiredState)
: K(K), SearchOrder(std::move(SearchOrder)),
LookupSet(std::move(LookupSet)), RequiredState(RequiredState) {
DefGeneratorCandidates = this->LookupSet;
}
virtual ~InProgressLookupState() = default;
virtual void complete(std::unique_ptr<InProgressLookupState> IPLS) = 0;
virtual void fail(Error Err) = 0;
LookupKind K;
JITDylibSearchOrder SearchOrder;
SymbolLookupSet LookupSet;
SymbolState RequiredState;
std::unique_lock<std::mutex> GeneratorLock;
size_t CurSearchOrderIndex = 0;
bool NewJITDylib = true;
SymbolLookupSet DefGeneratorCandidates;
SymbolLookupSet DefGeneratorNonCandidates;
std::vector<std::weak_ptr<DefinitionGenerator>> CurDefGeneratorStack;
};
class InProgressLookupFlagsState : public InProgressLookupState {
public:
InProgressLookupFlagsState(
LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet LookupSet,
unique_function<void(Expected<SymbolFlagsMap>)> OnComplete)
: InProgressLookupState(K, std::move(SearchOrder), std::move(LookupSet),
SymbolState::NeverSearched),
OnComplete(std::move(OnComplete)) {}
void complete(std::unique_ptr<InProgressLookupState> IPLS) override {
GeneratorLock = {}; // Unlock and release.
auto &ES = SearchOrder.front().first->getExecutionSession();
ES.OL_completeLookupFlags(std::move(IPLS), std::move(OnComplete));
}
void fail(Error Err) override {
GeneratorLock = {}; // Unlock and release.
OnComplete(std::move(Err));
}
private:
unique_function<void(Expected<SymbolFlagsMap>)> OnComplete;
};
class InProgressFullLookupState : public InProgressLookupState {
public:
InProgressFullLookupState(LookupKind K, JITDylibSearchOrder SearchOrder,
SymbolLookupSet LookupSet,
SymbolState RequiredState,
std::shared_ptr<AsynchronousSymbolQuery> Q,
RegisterDependenciesFunction RegisterDependencies)
: InProgressLookupState(K, std::move(SearchOrder), std::move(LookupSet),
RequiredState),
Q(std::move(Q)), RegisterDependencies(std::move(RegisterDependencies)) {
}
void complete(std::unique_ptr<InProgressLookupState> IPLS) override {
GeneratorLock = {}; // Unlock and release.
auto &ES = SearchOrder.front().first->getExecutionSession();
ES.OL_completeLookup(std::move(IPLS), std::move(Q),
std::move(RegisterDependencies));
}
void fail(Error Err) override {
GeneratorLock = {};
Q->detach();
Q->handleFailed(std::move(Err));
}
private:
std::shared_ptr<AsynchronousSymbolQuery> Q;
RegisterDependenciesFunction RegisterDependencies;
};
ReexportsGenerator::ReexportsGenerator(JITDylib &SourceJD,
JITDylibLookupFlags SourceJDLookupFlags,
SymbolPredicate Allow)
: SourceJD(SourceJD), SourceJDLookupFlags(SourceJDLookupFlags),
Allow(std::move(Allow)) {}
Error ReexportsGenerator::tryToGenerate(LookupState &LS, LookupKind K,
JITDylib &JD,
JITDylibLookupFlags JDLookupFlags,
const SymbolLookupSet &LookupSet) {
assert(&JD != &SourceJD && "Cannot re-export from the same dylib");
// Use lookupFlags to find the subset of symbols that match our lookup.
auto Flags = JD.getExecutionSession().lookupFlags(
K, {{&SourceJD, JDLookupFlags}}, LookupSet);
if (!Flags)
return Flags.takeError();
// Create an alias map.
orc::SymbolAliasMap AliasMap;
for (auto &KV : *Flags)
if (!Allow || Allow(KV.first))
AliasMap[KV.first] = SymbolAliasMapEntry(KV.first, KV.second);
if (AliasMap.empty())
return Error::success();
// Define the re-exports.
return JD.define(reexports(SourceJD, AliasMap, SourceJDLookupFlags));
}
LookupState::LookupState(std::unique_ptr<InProgressLookupState> IPLS)
: IPLS(std::move(IPLS)) {}
void LookupState::reset(InProgressLookupState *IPLS) { this->IPLS.reset(IPLS); }
LookupState::LookupState() = default;
LookupState::LookupState(LookupState &&) = default;
LookupState &LookupState::operator=(LookupState &&) = default;
LookupState::~LookupState() = default;
void LookupState::continueLookup(Error Err) {
assert(IPLS && "Cannot call continueLookup on empty LookupState");
auto &ES = IPLS->SearchOrder.begin()->first->getExecutionSession();
ES.OL_applyQueryPhase1(std::move(IPLS), std::move(Err));
}
DefinitionGenerator::~DefinitionGenerator() = default;
JITDylib::~JITDylib() {
LLVM_DEBUG(dbgs() << "Destroying JITDylib " << getName() << "\n");
}
Error JITDylib::clear() {
std::vector<ResourceTrackerSP> TrackersToRemove;
ES.runSessionLocked([&]() {
assert(State != Closed && "JD is defunct");
for (auto &KV : TrackerSymbols)
TrackersToRemove.push_back(KV.first);
TrackersToRemove.push_back(getDefaultResourceTracker());
});
Error Err = Error::success();
for (auto &RT : TrackersToRemove)
Err = joinErrors(std::move(Err), RT->remove());
return Err;
}
ResourceTrackerSP JITDylib::getDefaultResourceTracker() {
return ES.runSessionLocked([this] {
assert(State != Closed && "JD is defunct");
if (!DefaultTracker)
DefaultTracker = new ResourceTracker(this);
return DefaultTracker;
});
}
ResourceTrackerSP JITDylib::createResourceTracker() {
return ES.runSessionLocked([this] {
assert(State == Open && "JD is defunct");
ResourceTrackerSP RT = new ResourceTracker(this);
return RT;
});
}
void JITDylib::removeGenerator(DefinitionGenerator &G) {
ES.runSessionLocked([&] {
assert(State == Open && "JD is defunct");
auto I = llvm::find_if(DefGenerators,
[&](const std::shared_ptr<DefinitionGenerator> &H) {
return H.get() == &G;
});
assert(I != DefGenerators.end() && "Generator not found");
DefGenerators.erase(I);
});
}
Expected<SymbolFlagsMap>
JITDylib::defineMaterializing(SymbolFlagsMap SymbolFlags) {
return ES.runSessionLocked([&]() -> Expected<SymbolFlagsMap> {
std::vector<SymbolTable::iterator> AddedSyms;
std::vector<SymbolFlagsMap::iterator> RejectedWeakDefs;
for (auto SFItr = SymbolFlags.begin(), SFEnd = SymbolFlags.end();
SFItr != SFEnd; ++SFItr) {
auto &Name = SFItr->first;
auto &Flags = SFItr->second;
auto EntryItr = Symbols.find(Name);
// If the entry already exists...
if (EntryItr != Symbols.end()) {
// If this is a strong definition then error out.
if (!Flags.isWeak()) {
// Remove any symbols already added.
for (auto &SI : AddedSyms)
Symbols.erase(SI);
// FIXME: Return all duplicates.
return make_error<DuplicateDefinition>(std::string(*Name));
}
// Otherwise just make a note to discard this symbol after the loop.
RejectedWeakDefs.push_back(SFItr);
continue;
} else
EntryItr =
Symbols.insert(std::make_pair(Name, SymbolTableEntry(Flags))).first;
AddedSyms.push_back(EntryItr);
EntryItr->second.setState(SymbolState::Materializing);
}
// Remove any rejected weak definitions from the SymbolFlags map.
while (!RejectedWeakDefs.empty()) {
SymbolFlags.erase(RejectedWeakDefs.back());
RejectedWeakDefs.pop_back();
}
return SymbolFlags;
});
}
Error JITDylib::replace(MaterializationResponsibility &FromMR,
std::unique_ptr<MaterializationUnit> MU) {
assert(MU != nullptr && "Can not replace with a null MaterializationUnit");
std::unique_ptr<MaterializationUnit> MustRunMU;
std::unique_ptr<MaterializationResponsibility> MustRunMR;
auto Err =
ES.runSessionLocked([&, this]() -> Error {
if (FromMR.RT->isDefunct())
return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
#ifndef NDEBUG
for (auto &KV : MU->getSymbols()) {
auto SymI = Symbols.find(KV.first);
assert(SymI != Symbols.end() && "Replacing unknown symbol");
assert(SymI->second.getState() == SymbolState::Materializing &&
"Can not replace a symbol that ha is not materializing");
assert(!SymI->second.hasMaterializerAttached() &&
"Symbol should not have materializer attached already");
assert(UnmaterializedInfos.count(KV.first) == 0 &&
"Symbol being replaced should have no UnmaterializedInfo");
}
#endif // NDEBUG
// If the tracker is defunct we need to bail out immediately.
// If any symbol has pending queries against it then we need to
// materialize MU immediately.
for (auto &KV : MU->getSymbols()) {
auto MII = MaterializingInfos.find(KV.first);
if (MII != MaterializingInfos.end()) {
if (MII->second.hasQueriesPending()) {
MustRunMR = ES.createMaterializationResponsibility(
*FromMR.RT, std::move(MU->SymbolFlags),
std::move(MU->InitSymbol));
MustRunMU = std::move(MU);
return Error::success();
}
}
}
// Otherwise, make MU responsible for all the symbols.
auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU),
FromMR.RT.get());
for (auto &KV : UMI->MU->getSymbols()) {
auto SymI = Symbols.find(KV.first);
assert(SymI->second.getState() == SymbolState::Materializing &&
"Can not replace a symbol that is not materializing");
assert(!SymI->second.hasMaterializerAttached() &&
"Can not replace a symbol that has a materializer attached");
assert(UnmaterializedInfos.count(KV.first) == 0 &&
"Unexpected materializer entry in map");
SymI->second.setAddress(SymI->second.getAddress());
SymI->second.setMaterializerAttached(true);
auto &UMIEntry = UnmaterializedInfos[KV.first];
assert((!UMIEntry || !UMIEntry->MU) &&
"Replacing symbol with materializer still attached");
UMIEntry = UMI;
}
return Error::success();
});
if (Err)
return Err;
if (MustRunMU) {
assert(MustRunMR && "MustRunMU set implies MustRunMR set");
ES.dispatchTask(std::make_unique<MaterializationTask>(
std::move(MustRunMU), std::move(MustRunMR)));
} else {
assert(!MustRunMR && "MustRunMU unset implies MustRunMR unset");
}
return Error::success();
}
Expected<std::unique_ptr<MaterializationResponsibility>>
JITDylib::delegate(MaterializationResponsibility &FromMR,
SymbolFlagsMap SymbolFlags, SymbolStringPtr InitSymbol) {
return ES.runSessionLocked(
[&]() -> Expected<std::unique_ptr<MaterializationResponsibility>> {
if (FromMR.RT->isDefunct())
return make_error<ResourceTrackerDefunct>(std::move(FromMR.RT));
return ES.createMaterializationResponsibility(
*FromMR.RT, std::move(SymbolFlags), std::move(InitSymbol));
});
}
SymbolNameSet
JITDylib::getRequestedSymbols(const SymbolFlagsMap &SymbolFlags) const {
return ES.runSessionLocked([&]() {
SymbolNameSet RequestedSymbols;
for (auto &KV : SymbolFlags) {
assert(Symbols.count(KV.first) && "JITDylib does not cover this symbol?");
assert(Symbols.find(KV.first)->second.getState() !=
SymbolState::NeverSearched &&
Symbols.find(KV.first)->second.getState() != SymbolState::Ready &&
"getRequestedSymbols can only be called for symbols that have "
"started materializing");
auto I = MaterializingInfos.find(KV.first);
if (I == MaterializingInfos.end())
continue;
if (I->second.hasQueriesPending())
RequestedSymbols.insert(KV.first);
}
return RequestedSymbols;
});
}
void JITDylib::addDependencies(const SymbolStringPtr &Name,
const SymbolDependenceMap &Dependencies) {
ES.runSessionLocked([&]() {
assert(Symbols.count(Name) && "Name not in symbol table");
assert(Symbols[Name].getState() < SymbolState::Emitted &&
"Can not add dependencies for a symbol that is not materializing");
LLVM_DEBUG({
dbgs() << "In " << getName() << " adding dependencies for " << *Name
<< ": " << Dependencies << "\n";
});
// If Name is already in an error state then just bail out.
if (Symbols[Name].getFlags().hasError())
return;
auto &MI = MaterializingInfos[Name];
assert(Symbols[Name].getState() != SymbolState::Emitted &&
"Can not add dependencies to an emitted symbol");
bool DependsOnSymbolInErrorState = false;
// Register dependencies, record whether any depenendency is in the error
// state.
for (auto &KV : Dependencies) {
assert(KV.first && "Null JITDylib in dependency?");
auto &OtherJITDylib = *KV.first;
auto &DepsOnOtherJITDylib = MI.UnemittedDependencies[&OtherJITDylib];
for (auto &OtherSymbol : KV.second) {
// Check the sym entry for the dependency.
auto OtherSymI = OtherJITDylib.Symbols.find(OtherSymbol);
// Assert that this symbol exists and has not reached the ready state
// already.
assert(OtherSymI != OtherJITDylib.Symbols.end() &&
"Dependency on unknown symbol");
auto &OtherSymEntry = OtherSymI->second;
// If the other symbol is already in the Ready state then there's no
// dependency to add.
if (OtherSymEntry.getState() == SymbolState::Ready)
continue;
// If the dependency is in an error state then note this and continue,
// we will move this symbol to the error state below.
if (OtherSymEntry.getFlags().hasError()) {
DependsOnSymbolInErrorState = true;
continue;
}
// If the dependency was not in the error state then add it to
// our list of dependencies.
auto &OtherMI = OtherJITDylib.MaterializingInfos[OtherSymbol];
if (OtherSymEntry.getState() == SymbolState::Emitted)
transferEmittedNodeDependencies(MI, Name, OtherMI);
else if (&OtherJITDylib != this || OtherSymbol != Name) {
OtherMI.Dependants[this].insert(Name);
DepsOnOtherJITDylib.insert(OtherSymbol);
}
}
if (DepsOnOtherJITDylib.empty())
MI.UnemittedDependencies.erase(&OtherJITDylib);
}
// If this symbol dependended on any symbols in the error state then move
// this symbol to the error state too.
if (DependsOnSymbolInErrorState)
Symbols[Name].setFlags(Symbols[Name].getFlags() |
JITSymbolFlags::HasError);
});
}
Error JITDylib::resolve(MaterializationResponsibility &MR,
const SymbolMap &Resolved) {
AsynchronousSymbolQuerySet CompletedQueries;
if (auto Err = ES.runSessionLocked([&, this]() -> Error {
if (MR.RT->isDefunct())
return make_error<ResourceTrackerDefunct>(MR.RT);
if (State != Open)
return make_error<StringError>("JITDylib " + getName() +
" is defunct",
inconvertibleErrorCode());
struct WorklistEntry {
SymbolTable::iterator SymI;
JITEvaluatedSymbol ResolvedSym;
};
SymbolNameSet SymbolsInErrorState;
std::vector<WorklistEntry> Worklist;
Worklist.reserve(Resolved.size());
// Build worklist and check for any symbols in the error state.
for (const auto &KV : Resolved) {
assert(!KV.second.getFlags().hasError() &&
"Resolution result can not have error flag set");
auto SymI = Symbols.find(KV.first);
assert(SymI != Symbols.end() && "Symbol not found");
assert(!SymI->second.hasMaterializerAttached() &&
"Resolving symbol with materializer attached?");
assert(SymI->second.getState() == SymbolState::Materializing &&
"Symbol should be materializing");
assert(SymI->second.getAddress() == 0 &&
"Symbol has already been resolved");
if (SymI->second.getFlags().hasError())
SymbolsInErrorState.insert(KV.first);
else {
auto Flags = KV.second.getFlags();
Flags &= ~(JITSymbolFlags::Weak | JITSymbolFlags::Common);
assert(Flags ==
(SymI->second.getFlags() &
~(JITSymbolFlags::Weak | JITSymbolFlags::Common)) &&
"Resolved flags should match the declared flags");
Worklist.push_back(
{SymI, JITEvaluatedSymbol(KV.second.getAddress(), Flags)});
}
}
// If any symbols were in the error state then bail out.
if (!SymbolsInErrorState.empty()) {
auto FailedSymbolsDepMap = std::make_shared<SymbolDependenceMap>();
(*FailedSymbolsDepMap)[this] = std::move(SymbolsInErrorState);
return make_error<FailedToMaterialize>(
std::move(FailedSymbolsDepMap));
}
while (!Worklist.empty()) {
auto SymI = Worklist.back().SymI;
auto ResolvedSym = Worklist.back().ResolvedSym;
Worklist.pop_back();
auto &Name = SymI->first;
// Resolved symbols can not be weak: discard the weak flag.
JITSymbolFlags ResolvedFlags = ResolvedSym.getFlags();
SymI->second.setAddress(ResolvedSym.getAddress());
SymI->second.setFlags(ResolvedFlags);
SymI->second.setState(SymbolState::Resolved);
auto MII = MaterializingInfos.find(Name);
if (MII == MaterializingInfos.end())
continue;
auto &MI = MII->second;
for (auto &Q : MI.takeQueriesMeeting(SymbolState::Resolved)) {
Q->notifySymbolMetRequiredState(Name, ResolvedSym);
Q->removeQueryDependence(*this, Name);
if (Q->isComplete())
CompletedQueries.insert(std::move(Q));
}
}
return Error::success();
}))
return Err;
// Otherwise notify all the completed queries.
for (auto &Q : CompletedQueries) {
assert(Q->isComplete() && "Q not completed");
Q->handleComplete(ES);
}