forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCore.cpp
2004 lines (1662 loc) · 64 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.) ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ExecutionEngine/Orc/Core.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/ExecutionEngine/Orc/OrcError.h"
#include "llvm/IR/Mangler.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Format.h"
#if LLVM_ENABLE_THREADS
#include <future>
#endif
#define DEBUG_TYPE "orc"
using namespace llvm;
namespace {
#ifndef NDEBUG
cl::opt<bool> PrintHidden("debug-orc-print-hidden", cl::init(false),
cl::desc("debug print hidden symbols defined by "
"materialization units"),
cl::Hidden);
cl::opt<bool> PrintCallable("debug-orc-print-callable", cl::init(false),
cl::desc("debug print callable symbols defined by "
"materialization units"),
cl::Hidden);
cl::opt<bool> PrintData("debug-orc-print-data", cl::init(false),
cl::desc("debug print data symbols defined by "
"materialization units"),
cl::Hidden);
#endif // NDEBUG
// SetPrinter predicate that prints every element.
template <typename T> struct PrintAll {
bool operator()(const T &E) { return true; }
};
bool anyPrintSymbolOptionSet() {
#ifndef NDEBUG
return PrintHidden || PrintCallable || PrintData;
#else
return false;
#endif // NDEBUG
}
bool flagsMatchCLOpts(const JITSymbolFlags &Flags) {
#ifndef NDEBUG
// Bail out early if this is a hidden symbol and we're not printing hiddens.
if (!PrintHidden && !Flags.isExported())
return false;
// Return true if this is callable and we're printing callables.
if (PrintCallable && Flags.isCallable())
return true;
// Return true if this is data and we're printing data.
if (PrintData && !Flags.isCallable())
return true;
// otherwise return false.
return false;
#else
return false;
#endif // NDEBUG
}
// Prints a set of items, filtered by an user-supplied predicate.
template <typename Set, typename Pred = PrintAll<typename Set::value_type>>
class SetPrinter {
public:
SetPrinter(const Set &S, Pred ShouldPrint = Pred())
: S(S), ShouldPrint(std::move(ShouldPrint)) {}
void printTo(llvm::raw_ostream &OS) const {
bool PrintComma = false;
OS << "{";
for (auto &E : S) {
if (ShouldPrint(E)) {
if (PrintComma)
OS << ',';
OS << ' ' << E;
PrintComma = true;
}
}
OS << " }";
}
private:
const Set &S;
mutable Pred ShouldPrint;
};
template <typename Set, typename Pred>
SetPrinter<Set, Pred> printSet(const Set &S, Pred P = Pred()) {
return SetPrinter<Set, Pred>(S, std::move(P));
}
// Render a SetPrinter by delegating to its printTo method.
template <typename Set, typename Pred>
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
const SetPrinter<Set, Pred> &Printer) {
Printer.printTo(OS);
return OS;
}
struct PrintSymbolFlagsMapElemsMatchingCLOpts {
bool operator()(const orc::SymbolFlagsMap::value_type &KV) {
return flagsMatchCLOpts(KV.second);
}
};
struct PrintSymbolMapElemsMatchingCLOpts {
bool operator()(const orc::SymbolMap::value_type &KV) {
return flagsMatchCLOpts(KV.second.getFlags());
}
};
} // end anonymous namespace
namespace llvm {
namespace orc {
SymbolStringPool::PoolMapEntry SymbolStringPtr::Tombstone(0);
char FailedToMaterialize::ID = 0;
char SymbolsNotFound::ID = 0;
char SymbolsCouldNotBeRemoved::ID = 0;
RegisterDependenciesFunction NoDependenciesToRegister =
RegisterDependenciesFunction();
void MaterializationUnit::anchor() {}
raw_ostream &operator<<(raw_ostream &OS, const SymbolStringPtr &Sym) {
return OS << *Sym;
}
raw_ostream &operator<<(raw_ostream &OS, const SymbolNameSet &Symbols) {
return OS << printSet(Symbols, PrintAll<SymbolStringPtr>());
}
raw_ostream &operator<<(raw_ostream &OS, const JITSymbolFlags &Flags) {
if (Flags.isCallable())
OS << "[Callable]";
else
OS << "[Data]";
if (Flags.isWeak())
OS << "[Weak]";
else if (Flags.isCommon())
OS << "[Common]";
if (!Flags.isExported())
OS << "[Hidden]";
return OS;
}
raw_ostream &operator<<(raw_ostream &OS, const JITEvaluatedSymbol &Sym) {
return OS << format("0x%016" PRIx64, Sym.getAddress()) << " "
<< Sym.getFlags();
}
raw_ostream &operator<<(raw_ostream &OS, const SymbolFlagsMap::value_type &KV) {
return OS << "(\"" << KV.first << "\", " << KV.second << ")";
}
raw_ostream &operator<<(raw_ostream &OS, const SymbolMap::value_type &KV) {
return OS << "(\"" << KV.first << "\": " << KV.second << ")";
}
raw_ostream &operator<<(raw_ostream &OS, const SymbolFlagsMap &SymbolFlags) {
return OS << printSet(SymbolFlags, PrintSymbolFlagsMapElemsMatchingCLOpts());
}
raw_ostream &operator<<(raw_ostream &OS, const SymbolMap &Symbols) {
return OS << printSet(Symbols, PrintSymbolMapElemsMatchingCLOpts());
}
raw_ostream &operator<<(raw_ostream &OS,
const SymbolDependenceMap::value_type &KV) {
return OS << "(" << KV.first << ", " << KV.second << ")";
}
raw_ostream &operator<<(raw_ostream &OS, const SymbolDependenceMap &Deps) {
return OS << printSet(Deps, PrintAll<SymbolDependenceMap::value_type>());
}
raw_ostream &operator<<(raw_ostream &OS, const MaterializationUnit &MU) {
OS << "MU@" << &MU << " (\"" << MU.getName() << "\"";
if (anyPrintSymbolOptionSet())
OS << ", " << MU.getSymbols();
return OS << ")";
}
raw_ostream &operator<<(raw_ostream &OS, const JITDylibSearchList &JDs) {
OS << "[";
if (!JDs.empty()) {
assert(JDs.front().first && "JITDylibList entries must not be null");
OS << " (\"" << JDs.front().first->getName() << "\", "
<< (JDs.front().second ? "true" : "false") << ")";
for (auto &KV : make_range(std::next(JDs.begin()), JDs.end())) {
assert(KV.first && "JITDylibList entries must not be null");
OS << ", (\"" << KV.first->getName() << "\", "
<< (KV.second ? "true" : "false") << ")";
}
}
OS << " ]";
return OS;
}
FailedToMaterialize::FailedToMaterialize(SymbolNameSet 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(SymbolNameSet Symbols)
: 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(SymbolNameSet Symbols)
: 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;
}
AsynchronousSymbolQuery::AsynchronousSymbolQuery(
const SymbolNameSet &Symbols, SymbolsResolvedCallback NotifySymbolsResolved,
SymbolsReadyCallback NotifySymbolsReady)
: NotifySymbolsResolved(std::move(NotifySymbolsResolved)),
NotifySymbolsReady(std::move(NotifySymbolsReady)) {
NotYetResolvedCount = NotYetReadyCount = Symbols.size();
for (auto &S : Symbols)
ResolvedSymbols[S] = nullptr;
}
void AsynchronousSymbolQuery::resolve(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");
I->second = std::move(Sym);
--NotYetResolvedCount;
}
void AsynchronousSymbolQuery::handleFullyResolved() {
assert(NotYetResolvedCount == 0 && "Not fully resolved?");
if (!NotifySymbolsResolved) {
// handleFullyResolved may be called by handleFullyReady (see comments in
// that method), in which case this is a no-op, so bail out.
assert(!NotifySymbolsReady &&
"NotifySymbolsResolved already called or an error occurred");
return;
}
auto TmpNotifySymbolsResolved = std::move(NotifySymbolsResolved);
NotifySymbolsResolved = SymbolsResolvedCallback();
TmpNotifySymbolsResolved(std::move(ResolvedSymbols));
}
void AsynchronousSymbolQuery::notifySymbolReady() {
assert(NotYetReadyCount != 0 && "All symbols already emitted");
--NotYetReadyCount;
}
void AsynchronousSymbolQuery::handleFullyReady() {
assert(NotifySymbolsReady &&
"NotifySymbolsReady already called or an error occurred");
auto TmpNotifySymbolsReady = std::move(NotifySymbolsReady);
NotifySymbolsReady = SymbolsReadyCallback();
if (NotYetResolvedCount == 0 && NotifySymbolsResolved) {
// The NotifyResolved callback of one query must have caused this query to
// become ready (i.e. there is still a handleFullyResolved callback waiting
// to be made back up the stack). Fold the handleFullyResolved call into
// this one before proceeding. This will cause the call further up the
// stack to become a no-op.
handleFullyResolved();
}
assert(QueryRegistrations.empty() &&
"Query is still registered with some symbols");
assert(!NotifySymbolsResolved && "Resolution not applied yet");
TmpNotifySymbolsReady(Error::success());
}
bool AsynchronousSymbolQuery::canStillFail() {
return (NotifySymbolsResolved || NotifySymbolsReady);
}
void AsynchronousSymbolQuery::handleFailed(Error Err) {
assert(QueryRegistrations.empty() && ResolvedSymbols.empty() &&
NotYetResolvedCount == 0 && NotYetReadyCount == 0 &&
"Query should already have been abandoned");
if (NotifySymbolsResolved) {
NotifySymbolsResolved(std::move(Err));
NotifySymbolsResolved = SymbolsResolvedCallback();
} else {
assert(NotifySymbolsReady && "Failed after both callbacks issued?");
NotifySymbolsReady(std::move(Err));
}
NotifySymbolsReady = SymbolsReadyCallback();
}
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::detach() {
ResolvedSymbols.clear();
NotYetResolvedCount = 0;
NotYetReadyCount = 0;
for (auto &KV : QueryRegistrations)
KV.first->detachQueryHelper(*this, KV.second);
QueryRegistrations.clear();
}
MaterializationResponsibility::MaterializationResponsibility(
JITDylib &JD, SymbolFlagsMap SymbolFlags, VModuleKey K)
: JD(JD), SymbolFlags(std::move(SymbolFlags)), K(std::move(K)) {
assert(!this->SymbolFlags.empty() && "Materializing nothing?");
#ifndef NDEBUG
for (auto &KV : this->SymbolFlags)
KV.second |= JITSymbolFlags::Materializing;
#endif
}
MaterializationResponsibility::~MaterializationResponsibility() {
assert(SymbolFlags.empty() &&
"All symbols should have been explicitly materialized or failed");
}
SymbolNameSet MaterializationResponsibility::getRequestedSymbols() const {
return JD.getRequestedSymbols(SymbolFlags);
}
void MaterializationResponsibility::resolve(const SymbolMap &Symbols) {
LLVM_DEBUG(dbgs() << "In " << JD.getName() << " resolving " << Symbols
<< "\n");
#ifndef NDEBUG
for (auto &KV : Symbols) {
auto I = SymbolFlags.find(KV.first);
assert(I != SymbolFlags.end() &&
"Resolving symbol outside this responsibility set");
assert(I->second.isMaterializing() && "Duplicate resolution");
I->second &= ~JITSymbolFlags::Materializing;
if (I->second.isWeak())
assert(I->second == (KV.second.getFlags() | JITSymbolFlags::Weak) &&
"Resolving symbol with incorrect flags");
else
assert(I->second == KV.second.getFlags() &&
"Resolving symbol with incorrect flags");
}
#endif
JD.resolve(Symbols);
}
void MaterializationResponsibility::emit() {
#ifndef NDEBUG
for (auto &KV : SymbolFlags)
assert(!KV.second.isMaterializing() &&
"Failed to resolve symbol before emission");
#endif // NDEBUG
JD.emit(SymbolFlags);
SymbolFlags.clear();
}
Error MaterializationResponsibility::defineMaterializing(
const SymbolFlagsMap &NewSymbolFlags) {
// Add the given symbols to this responsibility object.
// It's ok if we hit a duplicate here: In that case the new version will be
// discarded, and the JITDylib::defineMaterializing method will return a
// duplicate symbol error.
for (auto &KV : NewSymbolFlags) {
auto I = SymbolFlags.insert(KV).first;
(void)I;
#ifndef NDEBUG
I->second |= JITSymbolFlags::Materializing;
#endif
}
return JD.defineMaterializing(NewSymbolFlags);
}
void MaterializationResponsibility::failMaterialization() {
SymbolNameSet FailedSymbols;
for (auto &KV : SymbolFlags)
FailedSymbols.insert(KV.first);
JD.notifyFailed(FailedSymbols);
SymbolFlags.clear();
}
void MaterializationResponsibility::replace(
std::unique_ptr<MaterializationUnit> MU) {
for (auto &KV : MU->getSymbols())
SymbolFlags.erase(KV.first);
LLVM_DEBUG(JD.getExecutionSession().runSessionLocked([&]() {
dbgs() << "In " << JD.getName() << " replacing symbols with " << *MU
<< "\n";
}););
JD.replace(std::move(MU));
}
MaterializationResponsibility
MaterializationResponsibility::delegate(const SymbolNameSet &Symbols,
VModuleKey NewKey) {
if (NewKey == VModuleKey())
NewKey = K;
SymbolFlagsMap DelegatedFlags;
for (auto &Name : Symbols) {
auto I = SymbolFlags.find(Name);
assert(I != SymbolFlags.end() &&
"Symbol is not tracked by this MaterializationResponsibility "
"instance");
DelegatedFlags[Name] = std::move(I->second);
SymbolFlags.erase(I);
}
return MaterializationResponsibility(JD, std::move(DelegatedFlags),
std::move(NewKey));
}
void MaterializationResponsibility::addDependencies(
const SymbolStringPtr &Name, const SymbolDependenceMap &Dependencies) {
assert(SymbolFlags.count(Name) &&
"Symbol not covered by this MaterializationResponsibility instance");
JD.addDependencies(Name, Dependencies);
}
void MaterializationResponsibility::addDependenciesForAll(
const SymbolDependenceMap &Dependencies) {
for (auto &KV : SymbolFlags)
JD.addDependencies(KV.first, Dependencies);
}
AbsoluteSymbolsMaterializationUnit::AbsoluteSymbolsMaterializationUnit(
SymbolMap Symbols, VModuleKey K)
: MaterializationUnit(extractFlags(Symbols), std::move(K)),
Symbols(std::move(Symbols)) {}
StringRef AbsoluteSymbolsMaterializationUnit::getName() const {
return "<Absolute Symbols>";
}
void AbsoluteSymbolsMaterializationUnit::materialize(
MaterializationResponsibility R) {
R.resolve(Symbols);
R.emit();
}
void AbsoluteSymbolsMaterializationUnit::discard(const JITDylib &JD,
const SymbolStringPtr &Name) {
assert(Symbols.count(Name) && "Symbol is not part of this MU");
Symbols.erase(Name);
}
SymbolFlagsMap
AbsoluteSymbolsMaterializationUnit::extractFlags(const SymbolMap &Symbols) {
SymbolFlagsMap Flags;
for (const auto &KV : Symbols)
Flags[KV.first] = KV.second.getFlags();
return Flags;
}
ReExportsMaterializationUnit::ReExportsMaterializationUnit(
JITDylib *SourceJD, bool MatchNonExported, SymbolAliasMap Aliases,
VModuleKey K)
: MaterializationUnit(extractFlags(Aliases), std::move(K)),
SourceJD(SourceJD), MatchNonExported(MatchNonExported),
Aliases(std::move(Aliases)) {}
StringRef ReExportsMaterializationUnit::getName() const {
return "<Reexports>";
}
void ReExportsMaterializationUnit::materialize(
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);
}
if (!Aliases.empty()) {
if (SourceJD)
R.replace(reexports(*SourceJD, std::move(Aliases), MatchNonExported));
else
R.replace(symbolAliases(std::move(Aliases)));
}
// The OnResolveInfo struct will hold the aliases and responsibilty for each
// query in the list.
struct OnResolveInfo {
OnResolveInfo(MaterializationResponsibility R, SymbolAliasMap Aliases)
: R(std::move(R)), Aliases(std::move(Aliases)) {}
MaterializationResponsibility R;
SymbolAliasMap Aliases;
};
// Build a list of queries to issue. In each round we build the largest set of
// aliases that we can resolve without encountering a chain definition of the
// form Foo -> Bar, Bar -> Baz. Such a form would deadlock as the query would
// be waitin on a symbol that it itself had to resolve. Usually this will just
// involve one round and a single query.
std::vector<std::pair<SymbolNameSet, std::shared_ptr<OnResolveInfo>>>
QueryInfos;
while (!RequestedAliases.empty()) {
SymbolNameSet ResponsibilitySymbols;
SymbolNameSet 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.insert(KV.second.Aliasee);
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 QueryInfo = std::make_shared<OnResolveInfo>(
R.delegate(ResponsibilitySymbols), 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 OnResolve = [QueryInfo](Expected<SymbolMap> Result) {
if (Result) {
SymbolMap ResolutionMap;
for (auto &KV : QueryInfo->Aliases) {
assert(Result->count(KV.second.Aliasee) &&
"Result map missing entry?");
ResolutionMap[KV.first] = JITEvaluatedSymbol(
(*Result)[KV.second.Aliasee].getAddress(), KV.second.AliasFlags);
}
QueryInfo->R.resolve(ResolutionMap);
QueryInfo->R.emit();
} else {
auto &ES = QueryInfo->R.getTargetJITDylib().getExecutionSession();
ES.reportError(Result.takeError());
QueryInfo->R.failMaterialization();
}
};
auto OnReady = [&ES](Error Err) { ES.reportError(std::move(Err)); };
ES.lookup(JITDylibSearchList({{&SrcJD, MatchNonExported}}), QuerySymbols,
std::move(OnResolve), std::move(OnReady),
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);
}
SymbolFlagsMap
ReExportsMaterializationUnit::extractFlags(const SymbolAliasMap &Aliases) {
SymbolFlagsMap SymbolFlags;
for (auto &KV : Aliases)
SymbolFlags[KV.first] = KV.second.AliasFlags;
return SymbolFlags;
}
Expected<SymbolAliasMap>
buildSimpleReexportsAliasMap(JITDylib &SourceJD, const SymbolNameSet &Symbols) {
auto Flags = SourceJD.lookupFlags(Symbols);
if (Flags.size() != Symbols.size()) {
SymbolNameSet Unresolved = Symbols;
for (auto &KV : Flags)
Unresolved.erase(KV.first);
return make_error<SymbolsNotFound>(std::move(Unresolved));
}
SymbolAliasMap Result;
for (auto &Name : Symbols) {
assert(Flags.count(Name) && "Missing entry in flags map");
Result[Name] = SymbolAliasMapEntry(Name, Flags[Name]);
}
return Result;
}
ReexportsGenerator::ReexportsGenerator(JITDylib &SourceJD,
bool MatchNonExported,
SymbolPredicate Allow)
: SourceJD(SourceJD), MatchNonExported(MatchNonExported),
Allow(std::move(Allow)) {}
SymbolNameSet ReexportsGenerator::operator()(JITDylib &JD,
const SymbolNameSet &Names) {
orc::SymbolNameSet Added;
orc::SymbolAliasMap AliasMap;
auto Flags = SourceJD.lookupFlags(Names);
for (auto &KV : Flags) {
if (Allow && !Allow(KV.first))
continue;
AliasMap[KV.first] = SymbolAliasMapEntry(KV.first, KV.second);
Added.insert(KV.first);
}
if (!Added.empty())
cantFail(JD.define(reexports(SourceJD, AliasMap, MatchNonExported)));
return Added;
}
Error JITDylib::defineMaterializing(const SymbolFlagsMap &SymbolFlags) {
return ES.runSessionLocked([&]() -> Error {
std::vector<SymbolMap::iterator> AddedSyms;
for (auto &KV : SymbolFlags) {
SymbolMap::iterator EntryItr;
bool Added;
auto NewFlags = KV.second;
NewFlags |= JITSymbolFlags::Materializing;
std::tie(EntryItr, Added) = Symbols.insert(
std::make_pair(KV.first, JITEvaluatedSymbol(0, NewFlags)));
if (Added)
AddedSyms.push_back(EntryItr);
else {
// Remove any symbols already added.
for (auto &SI : AddedSyms)
Symbols.erase(SI);
// FIXME: Return all duplicates.
return make_error<DuplicateDefinition>(*KV.first);
}
}
return Error::success();
});
}
void JITDylib::replace(std::unique_ptr<MaterializationUnit> MU) {
assert(MU != nullptr && "Can not replace with a null MaterializationUnit");
auto MustRunMU =
ES.runSessionLocked([&, this]() -> std::unique_ptr<MaterializationUnit> {
#ifndef NDEBUG
for (auto &KV : MU->getSymbols()) {
auto SymI = Symbols.find(KV.first);
assert(SymI != Symbols.end() && "Replacing unknown symbol");
assert(!SymI->second.getFlags().isLazy() &&
SymI->second.getFlags().isMaterializing() &&
"Can not replace symbol that is not materializing");
assert(UnmaterializedInfos.count(KV.first) == 0 &&
"Symbol being replaced should have no UnmaterializedInfo");
}
#endif // NDEBUG
// 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.PendingQueries.empty())
return std::move(MU);
}
}
// Otherwise, make MU responsible for all the symbols.
auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU));
for (auto &KV : UMI->MU->getSymbols()) {
assert(!KV.second.isLazy() &&
"Lazy flag should be managed internally.");
assert(!KV.second.isMaterializing() &&
"Materializing flags should be managed internally.");
auto SymI = Symbols.find(KV.first);
JITSymbolFlags ReplaceFlags = KV.second;
ReplaceFlags |= JITSymbolFlags::Lazy;
SymI->second = JITEvaluatedSymbol(SymI->second.getAddress(),
std::move(ReplaceFlags));
UnmaterializedInfos[KV.first] = UMI;
}
return nullptr;
});
if (MustRunMU)
ES.dispatchMaterialization(*this, std::move(MustRunMU));
}
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.getFlags().isMaterializing() &&
"getRequestedSymbols can only be called for materializing "
"symbols");
auto I = MaterializingInfos.find(KV.first);
if (I == MaterializingInfos.end())
continue;
if (!I->second.PendingQueries.empty())
RequestedSymbols.insert(KV.first);
}
return RequestedSymbols;
});
}
void JITDylib::addDependencies(const SymbolStringPtr &Name,
const SymbolDependenceMap &Dependencies) {
assert(Symbols.count(Name) && "Name not in symbol table");
assert((Symbols[Name].getFlags().isLazy() ||
Symbols[Name].getFlags().isMaterializing()) &&
"Symbol is not lazy or materializing");
auto &MI = MaterializingInfos[Name];
assert(!MI.IsEmitted && "Can not add dependencies to an emitted symbol");
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) {
#ifndef NDEBUG
// Assert that this symbol exists and has not been emitted already.
auto SymI = OtherJITDylib.Symbols.find(OtherSymbol);
assert(SymI != OtherJITDylib.Symbols.end() &&
(SymI->second.getFlags().isLazy() ||
SymI->second.getFlags().isMaterializing()) &&
"Dependency on emitted symbol");
#endif
auto &OtherMI = OtherJITDylib.MaterializingInfos[OtherSymbol];
if (OtherMI.IsEmitted)
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);
}
}
void JITDylib::resolve(const SymbolMap &Resolved) {
auto FullyResolvedQueries = ES.runSessionLocked([&, this]() {
AsynchronousSymbolQuerySet FullyResolvedQueries;
for (const auto &KV : Resolved) {
auto &Name = KV.first;
auto Sym = KV.second;
assert(!Sym.getFlags().isLazy() && !Sym.getFlags().isMaterializing() &&
"Materializing flags should be managed internally");
auto I = Symbols.find(Name);
assert(I != Symbols.end() && "Symbol not found");
assert(!I->second.getFlags().isLazy() &&
I->second.getFlags().isMaterializing() &&
"Symbol should be materializing");
assert(I->second.getAddress() == 0 && "Symbol has already been resolved");
assert((Sym.getFlags() & ~JITSymbolFlags::Weak) ==
(JITSymbolFlags::stripTransientFlags(I->second.getFlags()) &
~JITSymbolFlags::Weak) &&
"Resolved flags should match the declared flags");
// Once resolved, symbols can never be weak.
JITSymbolFlags ResolvedFlags = Sym.getFlags();
ResolvedFlags &= ~JITSymbolFlags::Weak;
ResolvedFlags |= JITSymbolFlags::Materializing;
I->second = JITEvaluatedSymbol(Sym.getAddress(), ResolvedFlags);
auto &MI = MaterializingInfos[Name];
for (auto &Q : MI.PendingQueries) {
Q->resolve(Name, Sym);
if (Q->isFullyResolved())
FullyResolvedQueries.insert(Q);
}
}
return FullyResolvedQueries;
});
for (auto &Q : FullyResolvedQueries) {
assert(Q->isFullyResolved() && "Q not fully resolved");
Q->handleFullyResolved();
}
}
void JITDylib::emit(const SymbolFlagsMap &Emitted) {
auto FullyReadyQueries = ES.runSessionLocked([&, this]() {
AsynchronousSymbolQuerySet ReadyQueries;
for (const auto &KV : Emitted) {
const auto &Name = KV.first;
auto MII = MaterializingInfos.find(Name);
assert(MII != MaterializingInfos.end() &&
"Missing MaterializingInfo entry");
auto &MI = MII->second;
// For each dependant, transfer this node's emitted dependencies to
// it. If the dependant node is ready (i.e. has no unemitted
// dependencies) then notify any pending queries.
for (auto &KV : MI.Dependants) {
auto &DependantJD = *KV.first;
for (auto &DependantName : KV.second) {
auto DependantMII =
DependantJD.MaterializingInfos.find(DependantName);
assert(DependantMII != DependantJD.MaterializingInfos.end() &&
"Dependant should have MaterializingInfo");
auto &DependantMI = DependantMII->second;
// Remove the dependant's dependency on this node.
assert(DependantMI.UnemittedDependencies[this].count(Name) &&
"Dependant does not count this symbol as a dependency?");
DependantMI.UnemittedDependencies[this].erase(Name);
if (DependantMI.UnemittedDependencies[this].empty())
DependantMI.UnemittedDependencies.erase(this);
// Transfer unemitted dependencies from this node to the dependant.
DependantJD.transferEmittedNodeDependencies(DependantMI,
DependantName, MI);
// If the dependant is emitted and this node was the last of its
// unemitted dependencies then the dependant node is now ready, so
// notify any pending queries on the dependant node.
if (DependantMI.IsEmitted &&
DependantMI.UnemittedDependencies.empty()) {
assert(DependantMI.Dependants.empty() &&
"Dependants should be empty by now");
for (auto &Q : DependantMI.PendingQueries) {
Q->notifySymbolReady();
if (Q->isFullyReady())
ReadyQueries.insert(Q);
Q->removeQueryDependence(DependantJD, DependantName);
}
// Since this dependant is now ready, we erase its MaterializingInfo
// and update its materializing state.
assert(DependantJD.Symbols.count(DependantName) &&
"Dependant has no entry in the Symbols table");
auto &DependantSym = DependantJD.Symbols[DependantName];
DependantSym.setFlags(DependantSym.getFlags() &
~JITSymbolFlags::Materializing);
DependantJD.MaterializingInfos.erase(DependantMII);
}
}
}
MI.Dependants.clear();
MI.IsEmitted = true;
if (MI.UnemittedDependencies.empty()) {
for (auto &Q : MI.PendingQueries) {
Q->notifySymbolReady();
if (Q->isFullyReady())
ReadyQueries.insert(Q);
Q->removeQueryDependence(*this, Name);
}
assert(Symbols.count(Name) &&
"Symbol has no entry in the Symbols table");
auto &Sym = Symbols[Name];
Sym.setFlags(Sym.getFlags() & ~JITSymbolFlags::Materializing);
MaterializingInfos.erase(MII);
}
}