forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTypeLowering.cpp
2750 lines (2414 loc) · 88.7 KB
/
TypeLowering.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
//===--- TypeLowering.cpp - Swift Type Lowering for Reflection ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Implements logic for computing in-memory layouts from TypeRefs loaded from
// reflection metadata.
//
// This has to match up with layout algorithms used in IRGen and the runtime,
// and a bit of SIL type lowering to boot.
//
//===----------------------------------------------------------------------===//
#if SWIFT_ENABLE_REFLECTION
#include "llvm/Support/MathExtras.h"
#include "swift/ABI/Enum.h"
#include "swift/ABI/MetadataValues.h"
#include "swift/RemoteInspection/TypeLowering.h"
#include "swift/RemoteInspection/TypeRef.h"
#include "swift/RemoteInspection/TypeRefBuilder.h"
#include "swift/Basic/Unreachable.h"
#include <iostream>
#include <sstream>
#include <limits>
#ifdef DEBUG_TYPE_LOWERING
#define DEBUG_LOG(expr) expr;
#else
#define DEBUG_LOG(expr)
#endif
namespace swift {
namespace reflection {
void TypeInfo::dump() const {
dump(std::cerr);
}
namespace {
class PrintTypeInfo {
std::ostream &stream;
unsigned Indent;
std::ostream &indent(unsigned Amount) {
for (unsigned i = 0; i < Amount; ++i)
stream << " ";
return stream;
}
std::ostream &printHeader(const std::string &name) {
indent(Indent) << "(" << name;
return stream;
}
std::ostream &printField(const std::string &name, const std::string &value) {
if (!name.empty())
stream << " " << name << "=" << value;
else
stream << " " << name;
return stream;
}
void printRec(const TypeInfo &TI) {
stream << "\n";
Indent += 2;
print(TI);
Indent -= 2;
}
void printBasic(const TypeInfo &TI) {
printField("size", std::to_string(TI.getSize()));
printField("alignment", std::to_string(TI.getAlignment()));
printField("stride", std::to_string(TI.getStride()));
printField("num_extra_inhabitants", std::to_string(TI.getNumExtraInhabitants()));
printField("bitwise_takable", TI.isBitwiseTakable() ? "1" : "0");
}
void printFields(const RecordTypeInfo &TI) {
Indent += 2;
for (auto Field : TI.getFields()) {
stream << "\n";
printHeader("field");
if (!Field.Name.empty())
printField("name", Field.Name);
printField("offset", std::to_string(Field.Offset));
printRec(Field.TI);
stream << ")";
}
Indent -= 2;
}
void printCases(const EnumTypeInfo &TI) {
Indent += 2;
int Index = -1;
for (auto Case : TI.getCases()) {
Index += 1;
stream << "\n";
printHeader("case");
if (!Case.Name.empty())
printField("name", Case.Name);
printField("index", std::to_string(Index));
if (Case.TR) {
printField("offset", std::to_string(Case.Offset));
printRec(Case.TI);
}
stream << ")";
}
Indent -= 2;
}
public:
PrintTypeInfo(std::ostream &stream, unsigned Indent)
: stream(stream), Indent(Indent) {}
void print(const TypeInfo &TI) {
switch (TI.getKind()) {
case TypeInfoKind::Invalid:
printHeader("invalid");
stream << ")";
return;
case TypeInfoKind::Builtin:
printHeader("builtin");
printBasic(TI);
stream << ")";
return;
case TypeInfoKind::Record: {
auto &RecordTI = cast<RecordTypeInfo>(TI);
switch (RecordTI.getRecordKind()) {
case RecordKind::Invalid:
printHeader("invalid");
break;
case RecordKind::Struct:
printHeader("struct");
break;
case RecordKind::Tuple:
printHeader("tuple");
break;
case RecordKind::ThickFunction:
printHeader("thick_function");
break;
case RecordKind::OpaqueExistential:
printHeader("opaque_existential");
break;
case RecordKind::ClassExistential:
printHeader("class_existential");
break;
case RecordKind::ErrorExistential:
printHeader("error_existential");
break;
case RecordKind::ExistentialMetatype:
printHeader("existential_metatype");
break;
case RecordKind::ClassInstance:
printHeader("class_instance");
break;
case RecordKind::ClosureContext:
printHeader("closure_context");
break;
}
printBasic(TI);
printFields(RecordTI);
stream << ")";
return;
}
case TypeInfoKind::Enum: {
auto &EnumTI = cast<EnumTypeInfo>(TI);
switch (EnumTI.getEnumKind()) {
case EnumKind::NoPayloadEnum:
printHeader("no_payload_enum");
break;
case EnumKind::SinglePayloadEnum:
printHeader("single_payload_enum");
break;
case EnumKind::MultiPayloadEnum:
printHeader("multi_payload_enum");
break;
}
printBasic(TI);
printCases(EnumTI);
stream << ")";
return;
}
case TypeInfoKind::Reference: {
printHeader("reference");
auto &ReferenceTI = cast<ReferenceTypeInfo>(TI);
switch (ReferenceTI.getReferenceKind()) {
case ReferenceKind::Strong: printField("kind", "strong"); break;
#define REF_STORAGE(Name, name, ...) \
case ReferenceKind::Name: printField("kind", #name); break;
#include "swift/AST/ReferenceStorage.def"
}
switch (ReferenceTI.getReferenceCounting()) {
case ReferenceCounting::Native:
printField("refcounting", "native");
break;
case ReferenceCounting::Unknown:
printField("refcounting", "unknown");
break;
}
stream << ")";
return;
}
}
swift_unreachable("Bad TypeInfo kind");
}
};
} // end anonymous namespace
void TypeInfo::dump(std::ostream &stream, unsigned Indent) const {
PrintTypeInfo(stream, Indent).print(*this);
stream << "\n";
}
BuiltinTypeInfo::BuiltinTypeInfo(TypeRefBuilder &builder,
RemoteRef<BuiltinTypeDescriptor> descriptor)
: TypeInfo(TypeInfoKind::Builtin,
descriptor->Size,
descriptor->getAlignment(),
descriptor->Stride,
descriptor->NumExtraInhabitants,
descriptor->isBitwiseTakable()),
Name(builder.getTypeRefString(
builder.readTypeRef(descriptor, descriptor->TypeName)))
{}
bool BuiltinTypeInfo::readExtraInhabitantIndex(
remote::MemoryReader &reader, remote::RemoteAddress address,
int *extraInhabitantIndex) const {
if (getNumExtraInhabitants() == 0) {
*extraInhabitantIndex = -1;
return true;
}
// If it has extra inhabitants, it could be an integer type with extra
// inhabitants (a bool) or a pointer.
// Check if it's an integer first. The mangling of an integer type is
// type ::= 'Bi' NATURAL '_'
llvm::StringRef nameRef(Name);
if (nameRef.startswith("Bi") && nameRef.endswith("_")) {
// Drop the front "Bi" and "_" end, check that what we're left with is a
// bool.
llvm::StringRef naturalRef = nameRef.drop_front(2).drop_back();
uint8_t natural;
if (naturalRef.getAsInteger(10, natural))
return false;
assert(natural == 1 &&
"Reading extra inhabitants of integer with more than 1 byte!");
if (natural != 1)
return false;
assert(getSize() == 1 && "Reading extra inhabitants of integer but size of "
"type info is different than 1!");
if (getSize() != 1)
return false;
assert(getNumExtraInhabitants() == 254 &&
"Boolean type info should have 254 extra inhabitants!");
if (getNumExtraInhabitants() != 254)
return false;
uint8_t rawValue;
if (!reader.readInteger(address, &rawValue))
return false;
// The max valid value, for a bool valid values are 0 or 1, so this would
// be 1.
auto maxValidValue = 1;
// If the raw value falls outside the range of valid values, this is an
// extra inhabitant.
if (maxValidValue < rawValue)
*extraInhabitantIndex = rawValue - maxValidValue - 1;
else
*extraInhabitantIndex = -1;
return true;
} else if (Name == "yyXf") {
// But there are two different conventions, one for function pointers:
return reader.readFunctionPointerExtraInhabitantIndex(address,
extraInhabitantIndex);
} else {
// And one for pointers to heap-allocated blocks of memory
return reader.readHeapObjectExtraInhabitantIndex(address,
extraInhabitantIndex);
}
}
bool RecordTypeInfo::readExtraInhabitantIndex(remote::MemoryReader &reader,
remote::RemoteAddress address,
int *extraInhabitantIndex) const {
*extraInhabitantIndex = -1;
switch (SubKind) {
case RecordKind::Invalid:
case RecordKind::ClosureContext:
return false;
case RecordKind::OpaqueExistential:
case RecordKind::ExistentialMetatype: {
if (Fields.size() < 1) {
return false;
}
auto metadata = Fields[0];
auto metadataFieldAddress = address + metadata.Offset;
return metadata.TI.readExtraInhabitantIndex(
reader, metadataFieldAddress, extraInhabitantIndex);
}
case RecordKind::ThickFunction: {
if (Fields.size() < 2) {
return false;
}
auto function = Fields[0];
auto context = Fields[1];
if (function.Offset != 0) {
return false;
}
auto functionFieldAddress = address;
return function.TI.readExtraInhabitantIndex(
reader, functionFieldAddress, extraInhabitantIndex);
}
case RecordKind::ClassExistential:
case RecordKind::ErrorExistential: {
if (Fields.size() < 1) {
return true;
}
auto first = Fields[0];
auto firstFieldAddress = address + first.Offset;
return first.TI.readExtraInhabitantIndex(reader, firstFieldAddress,
extraInhabitantIndex);
}
case RecordKind::ClassInstance:
// This case seems unlikely to ever happen; if we're using XIs with a
// class, it'll be with a reference, not with the instance itself (i.e.
// we'll be in the RecordKind::ClassExistential case).
return false;
case RecordKind::Tuple:
case RecordKind::Struct: {
if (Fields.size() == 0) {
return true;
}
// Tuples and Structs inherit XIs from their most capacious member
auto mostCapaciousField = std::max_element(
Fields.begin(), Fields.end(),
[](const FieldInfo &lhs, const FieldInfo &rhs) {
return lhs.TI.getNumExtraInhabitants() < rhs.TI.getNumExtraInhabitants();
});
auto fieldAddress = remote::RemoteAddress(address.getAddressData()
+ mostCapaciousField->Offset);
return mostCapaciousField->TI.readExtraInhabitantIndex(
reader, fieldAddress, extraInhabitantIndex);
}
}
return false;
}
class UnsupportedEnumTypeInfo: public EnumTypeInfo {
public:
UnsupportedEnumTypeInfo(unsigned Size, unsigned Alignment,
unsigned Stride, unsigned NumExtraInhabitants,
bool BitwiseTakable, EnumKind Kind,
const std::vector<FieldInfo> &Cases)
: EnumTypeInfo(Size, Alignment, Stride, NumExtraInhabitants,
BitwiseTakable, Kind, Cases) {}
bool readExtraInhabitantIndex(remote::MemoryReader &reader,
remote::RemoteAddress address,
int *index) const override {
return false;
}
bool projectEnumValue(remote::MemoryReader &reader,
remote::RemoteAddress address,
int *CaseIndex) const override {
return false;
}
};
class EmptyEnumTypeInfo: public EnumTypeInfo {
public:
EmptyEnumTypeInfo(const std::vector<FieldInfo> &Cases)
: EnumTypeInfo(/*Size*/ 0, /* Alignment*/ 1, /*Stride*/ 1,
/*NumExtraInhabitants*/ 0, /*BitwiseTakable*/ true,
EnumKind::NoPayloadEnum, Cases) {
// No cases
assert(Cases.size() == 0);
}
bool readExtraInhabitantIndex(remote::MemoryReader &reader,
remote::RemoteAddress address,
int *index) const override {
return false;
}
bool projectEnumValue(remote::MemoryReader &reader,
remote::RemoteAddress address,
int *CaseIndex) const override {
return false;
}
};
// Enum with a single non-payload case
class TrivialEnumTypeInfo: public EnumTypeInfo {
public:
TrivialEnumTypeInfo(EnumKind Kind, const std::vector<FieldInfo> &Cases)
: EnumTypeInfo(/*Size*/ 0,
/* Alignment*/ 1,
/*Stride*/ 1,
/*NumExtraInhabitants*/ 0,
/*BitwiseTakable*/ true,
Kind, Cases) {
// Exactly one case
assert(Cases.size() == 1);
// The only case has no payload
assert(Cases[0].TR == 0);
}
bool readExtraInhabitantIndex(remote::MemoryReader &reader,
remote::RemoteAddress address,
int *index) const override {
*index = -1;
return true;
}
bool projectEnumValue(remote::MemoryReader &reader,
remote::RemoteAddress address,
int *CaseIndex) const override {
*CaseIndex = 0;
return true;
}
};
// Enum with 2 or more non-payload cases and no payload cases
class NoPayloadEnumTypeInfo: public EnumTypeInfo {
public:
NoPayloadEnumTypeInfo(unsigned Size, unsigned Alignment,
unsigned Stride, unsigned NumExtraInhabitants,
EnumKind Kind,
const std::vector<FieldInfo> &Cases)
: EnumTypeInfo(Size, Alignment, Stride, NumExtraInhabitants,
/*BitwiseTakable*/ true,
Kind, Cases) {
// There are at least 2 cases
// (one case would be trivial, zero is impossible)
assert(Cases.size() >= 2);
// No non-empty payloads
assert(getNumNonEmptyPayloadCases() == 0);
}
bool readExtraInhabitantIndex(remote::MemoryReader &reader,
remote::RemoteAddress address,
int *index) const override {
uint32_t tag = 0;
if (!reader.readInteger(address, getSize(), &tag)) {
return false;
}
if (tag < getNumCases()) {
*index = -1;
} else {
*index = tag - getNumCases();
}
return true;
}
bool projectEnumValue(remote::MemoryReader &reader,
remote::RemoteAddress address,
int *CaseIndex) const override {
uint32_t tag = 0;
if (!reader.readInteger(address, getSize(), &tag)) {
return false;
}
if (tag < getNumCases()) {
*CaseIndex = tag;
return true;
} else {
return false;
}
}
};
// Enum with 1 payload case and zero or more non-payload cases
class SinglePayloadEnumTypeInfo: public EnumTypeInfo {
public:
SinglePayloadEnumTypeInfo(unsigned Size, unsigned Alignment,
unsigned Stride, unsigned NumExtraInhabitants,
bool BitwiseTakable,
EnumKind Kind,
const std::vector<FieldInfo> &Cases)
: EnumTypeInfo(Size, Alignment, Stride, NumExtraInhabitants,
BitwiseTakable, Kind, Cases) {
// The first case has a payload (possibly empty)
assert(Cases[0].TR != 0);
// At most one non-empty payload case
assert(getNumNonEmptyPayloadCases() <= 1);
}
bool readExtraInhabitantIndex(remote::MemoryReader &reader,
remote::RemoteAddress address,
int *extraInhabitantIndex) const override {
FieldInfo PayloadCase = getCases()[0];
if (getSize() < PayloadCase.TI.getSize()) {
// Single payload enums that use a separate tag don't export any XIs
// So this is an invalid request.
return false;
}
// Single payload enums inherit XIs from their payload type
auto NumCases = getNumCases();
if (NumCases == 1) {
*extraInhabitantIndex = -1;
return true;
} else {
if (!PayloadCase.TI.readExtraInhabitantIndex(reader, address,
extraInhabitantIndex)) {
return false;
}
auto NumNonPayloadCases = NumCases - 1;
if (*extraInhabitantIndex < 0
|| (unsigned long)*extraInhabitantIndex < NumNonPayloadCases) {
*extraInhabitantIndex = -1;
} else {
*extraInhabitantIndex -= NumNonPayloadCases;
}
return true;
}
}
// Think of a single-payload enum as being encoded in "pages".
// The discriminator (tag) tells us which page we're on:
// * Page 0 is the payload page which can either store
// the single payload case (any valid value
// for the payload) or any of N non-payload cases
// (encoded as XIs for the payload)
// * Other pages use the payload area to encode non-payload
// cases. The number of cases that can be encoded
// on each such page depends only on the size of the
// payload area.
//
// The above logic generalizes the following important cases:
// * A payload with XIs will generally have enough to
// encode all payload cases. If so, then it will have
// no discriminator allocated, so the discriminator is
// always treated as zero.
// * If the payload has no XIs but is not zero-sized, then
// we'll need a page one. That page will usually be
// large enough to encode all non-payload cases.
// * If the payload is zero-sized, then we only have a
// discriminator. In effect, the single-payload enum
// degenerates in this case to a non-payload enum
// (except for the subtle distinction that the
// single-payload enum doesn't export XIs).
bool projectEnumValue(remote::MemoryReader &reader,
remote::RemoteAddress address,
int *CaseIndex) const override {
auto PayloadCase = getCases()[0];
auto PayloadSize = PayloadCase.TI.getSize();
auto DiscriminatorAddress = address + PayloadSize;
auto DiscriminatorSize = getSize() - PayloadSize;
unsigned discriminator = 0;
if (DiscriminatorSize > 0) {
if (!reader.readInteger(DiscriminatorAddress,
DiscriminatorSize,
&discriminator)) {
return false;
}
}
unsigned nonPayloadCasesUsingXIs = PayloadCase.TI.getNumExtraInhabitants();
int ComputedCase = 0;
if (discriminator == 0) {
// This is Page 0, which encodes payload case and some additional cases in Xis
int XITag;
if (!PayloadCase.TI.readExtraInhabitantIndex(reader, address, &XITag)) {
return false;
}
ComputedCase = XITag < 0 ? 0 : XITag + 1;
} else {
// This is some other page, so the entire payload area is just a case index
unsigned payloadTag;
if (!reader.readInteger(address, PayloadSize, &payloadTag)) {
return false;
}
auto casesPerNonPayloadPage =
PayloadSize >= 4
? ValueWitnessFlags::MaxNumExtraInhabitants
: (1UL << (PayloadSize * 8UL));
ComputedCase =
1 + nonPayloadCasesUsingXIs // Cases on page 0
+ (discriminator - 1) * casesPerNonPayloadPage // Cases on other pages
+ payloadTag; // Cases on this page
}
if (static_cast<unsigned>(ComputedCase) < getNumCases()) {
*CaseIndex = ComputedCase;
return true;
}
*CaseIndex = -1;
return false;
}
};
// *Tagged* Multi-payload enums use a separate tag value exclusively.
// This may be because it only has one payload (with no XIs) or
// because it's a true MPE but with no "spare bits" in the payload area.
// This includes cases such as:
//
// ```
// // Enums with non-pointer payloads (only pointers carry spare bits)
// enum A {
// case a(Int)
// case b(Double)
// case c((Int8, UInt8))
// }
//
// // Generic enums (compiler doesn't have layout details)
// enum Either<T,U>{
// case a(T)
// case b(U)
// }
//
// // Enums where payload is covered by a non-pointer
// enum A {
// case a(ClassTypeA)
// case b(ClassTypeB)
// case c(Int)
// }
//
// // Enums with one non-empty payload but that has no XIs
// // (This is almost but not quite the same as the single-payload
// // case. Different in that this MPE exposes extra tag values
// // as XIs to an enclosing enum; SPEs don't do that.)
// enum A {
// case a(Int)
// case b(Void)
// }
// ```
class TaggedMultiPayloadEnumTypeInfo: public EnumTypeInfo {
unsigned NumEffectivePayloadCases;
public:
TaggedMultiPayloadEnumTypeInfo(unsigned Size, unsigned Alignment,
unsigned Stride, unsigned NumExtraInhabitants,
bool BitwiseTakable,
const std::vector<FieldInfo> &Cases,
unsigned NumEffectivePayloadCases)
: EnumTypeInfo(Size, Alignment, Stride, NumExtraInhabitants,
BitwiseTakable, EnumKind::MultiPayloadEnum, Cases),
NumEffectivePayloadCases(NumEffectivePayloadCases) {
// Definition of "multi-payload enum"
assert(getCases().size() > 1); // At least 2 cases
assert(Cases[0].TR != 0); // At least 2 payloads
// assert(Cases[1].TR != 0);
// At least one payload is non-empty (otherwise this
// would get laid out as a non-payload enum)
assert(getNumNonEmptyPayloadCases() > 0);
// There's a tag, so the total size must be bigger than any payload
// assert(getSize() > getPayloadSize());
}
bool readExtraInhabitantIndex(remote::MemoryReader &reader,
remote::RemoteAddress address,
int *extraInhabitantIndex) const override {
unsigned long PayloadSize = getPayloadSize();
unsigned PayloadCount = getNumPayloadCases();
unsigned TagSize = getSize() - PayloadSize;
unsigned tag = 0;
if (!reader.readInteger(address + PayloadSize,
getSize() - PayloadSize,
&tag)) {
return false;
}
if (tag < PayloadCount + 1) {
*extraInhabitantIndex = -1; // Valid payload, not an XI
} else {
// XIs are coded starting from the highest value that fits
// E.g., for 1-byte tag, tag 255 == XI #0, tag 254 == XI #1, etc.
unsigned maxTag = (TagSize >= 4) ? ~0U : (1U << (TagSize * 8U)) - 1;
*extraInhabitantIndex = maxTag - tag;
}
return true;
}
bool projectEnumValue(remote::MemoryReader &reader,
remote::RemoteAddress address,
int *CaseIndex) const override {
unsigned long PayloadSize = getPayloadSize();
unsigned PayloadCount = NumEffectivePayloadCases;
unsigned NumCases = getNumCases();
unsigned TagSize = getSize() - PayloadSize;
unsigned tag = 0;
if (!reader.readInteger(address + PayloadSize,
getSize() - PayloadSize,
&tag)) {
return false;
}
if (tag > ValueWitnessFlags::MaxNumExtraInhabitants) {
return false;
} else if (tag < PayloadCount) {
*CaseIndex = tag;
} else if (PayloadSize >= 4) {
unsigned payloadTag = 0;
if (tag > PayloadCount
|| !reader.readInteger(address, PayloadSize, &payloadTag)
|| PayloadCount + payloadTag >= getNumCases()) {
return false;
}
*CaseIndex = PayloadCount + payloadTag;
} else {
unsigned payloadTagCount = (1U << (TagSize * 8U)) - 1;
unsigned maxValidTag = (NumCases - PayloadCount) / payloadTagCount + PayloadCount;
unsigned payloadTag = 0;
if (tag > maxValidTag
|| !reader.readInteger(address, PayloadSize, &payloadTag)) {
return false;
}
unsigned ComputedCase = PayloadCount
+ (tag - PayloadCount) * payloadTagCount + payloadTag;
if (ComputedCase >= NumCases) {
return false;
}
*CaseIndex = ComputedCase;
}
return true;
}
};
// A variable-length bitmap used to track "spare bits" for general multi-payload
// enums.
class BitMask {
static constexpr unsigned maxSize = 128 * 1024 * 1024; // 128MB
unsigned size; // Size of mask in bytes
uint8_t *mask;
public:
~BitMask() {
free(mask);
}
// Construct a bitmask of the appropriate number of bytes
// initialized to all bits set
BitMask(unsigned sizeInBytes): size(sizeInBytes) {
// Gracefully fail by constructing an empty mask if we exceed the size
// limit.
if (size > maxSize) {
size = 0;
mask = nullptr;
return;
}
mask = (uint8_t *)malloc(size);
if (!mask) {
// Malloc might fail if size is large due to some bad data. Assert in
// asserts builds, and fail gracefully in non-asserts builds by
// constructing an empty BitMask.
assert(false && "Failed to allocate BitMask");
size = 0;
return;
}
memset(mask, 0xff, size);
}
// Construct a bitmask of the appropriate number of bytes
// initialized with bits from the specified buffer
BitMask(unsigned sizeInBytes, const uint8_t *initialValue,
unsigned initialValueBytes, unsigned offset)
: size(sizeInBytes) {
// Gracefully fail by constructing an empty mask if we exceed the size
// limit.
if (size > maxSize) {
size = 0;
mask = nullptr;
return;
}
// Bad data could cause the initial value location to be off the end of our
// size. If initialValueBytes + offset is beyond sizeInBytes (or overflows),
// assert in asserts builds, and fail gracefully in non-asserts builds by
// constructing an empty BitMask.
bool overflowed = false;
unsigned initialValueEnd =
llvm::SaturatingAdd(initialValueBytes, offset, &overflowed);
if (overflowed) {
assert(false && "initialValueBytes + offset overflowed");
size = 0;
mask = nullptr;
return;
}
assert(initialValueEnd <= sizeInBytes);
if (initialValueEnd > size) {
assert(false && "initialValueBytes + offset is greater than size");
size = 0;
mask = nullptr;
return;
}
mask = (uint8_t *)calloc(1, size);
if (!mask) {
// Malloc might fail if size is large due to some bad data. Assert in
// asserts builds, and fail gracefully in non-asserts builds by
// constructing an empty BitMask.
assert(false && "Failed to allocate BitMask");
size = 0;
return;
}
memcpy(mask + offset, initialValue, initialValueBytes);
}
// Move constructor moves ownership and zeros the src
BitMask(BitMask&& src) noexcept: size(src.size), mask(std::move(src.mask)) {
src.size = 0;
src.mask = nullptr;
}
// Copy constructor makes a copy of the mask storage
BitMask(const BitMask& src) noexcept: size(src.size), mask(nullptr) {
mask = (uint8_t *)malloc(size);
memcpy(mask, src.mask, size);
}
std::string str() const {
std::ostringstream buff;
buff << size << ":0x";
for (unsigned i = 0; i < size; i++) {
buff << std::hex << ((mask[i] >> 4) & 0x0f) << (mask[i] & 0x0f);
}
return buff.str();
}
bool operator==(const BitMask& rhs) const {
// The two masks may be of different sizes.
// The common prefix must be identical.
size_t common = std::min(size, rhs.size);
if (memcmp(mask, rhs.mask, common) != 0)
return false;
// The remainder of the longer mask must be
// all zero bits.
unsigned mustBeZeroSize = std::max(size, rhs.size) - common;
uint8_t *mustBeZero;
if (size < rhs.size) {
mustBeZero = rhs.mask + size;
} else if (size > rhs.size) {
mustBeZero = mask + rhs.size;
}
for (unsigned i = 0; i < mustBeZeroSize; ++i) {
if (mustBeZero[i] != 0) {
return false;
}
}
return true;
}
bool operator!=(const BitMask& rhs) const {
return !(*this == rhs);
}
bool isNonZero() const { return !isZero(); }
bool isZero() const {
for (unsigned i = 0; i < size; ++i) {
if (mask[i] != 0) {
return false;
}
}
return true;
}
void makeZero() {
memset(mask, 0, size * sizeof(mask[0]));
}
void complement() {
for (unsigned i = 0; i < size; ++i) {
mask[i] = ~mask[i];
}
}
int countSetBits() const {
static const int counter[] =
{0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};
int bits = 0;
for (unsigned i = 0; i < size; ++i) {
bits += counter[mask[i] >> 4] + counter[mask[i] & 15];
}
return bits;
}
int countZeroBits() const {
static const int counter[] =
{4, 3, 3, 2, 3, 2, 2, 1, 3, 2, 2, 1, 2, 1, 1, 0};
int bits = 0;
for (unsigned i = 0; i < size; ++i) {
bits += counter[mask[i] >> 4] + counter[mask[i] & 15];
}
return bits;
}
// Treat the provided value as a mask, `and` it with
// the part of the mask at the provided byte offset.
// Bits outside the specified area are unchanged.
template<typename IntegerType>
void andMask(IntegerType value, unsigned byteOffset) {
andMask((void *)&value, sizeof(value), byteOffset);
}
// As above, but using the provided bitmask instead
// of an integer.
void andMask(BitMask mask, unsigned offset) {
andMask(mask.mask, mask.size, offset);
}
// As above, but using the complement of the
// provided mask.
void andNotMask(BitMask mask, unsigned offset) {
if (offset < size) {
andNotMask(mask.mask, mask.size, offset);
}
}
// Zero all bits except for the `n` most significant ones.
// XXX TODO: Big-endian support?
void keepOnlyMostSignificantBits(unsigned n) {
unsigned count = 0;
if (size < 1) {
return;
}
unsigned i = size;
while (i > 0) {
i -= 1;
if (count < n) {
for (int b = 128; b > 0; b >>= 1) {
if (count >= n) {
mask[i] &= ~b;
} else if ((mask[i] & b) != 0) {
++count;
}
}
} else {
mask[i] = 0;
}
}
}
unsigned numBits() const {
return size * 8;
}
unsigned numSetBits() const {
unsigned count = 0;
for (unsigned i = 0; i < size; ++i) {
if (mask[i] != 0) {
for (unsigned b = 1; b < 256; b <<= 1) {
if ((mask[i] & b) != 0) {
++count;
}
}
}
}
return count;
}
// Read a mask-sized area from the target and collect
// the masked bits into a single integer.
template<typename IntegerType>
bool readMaskedInteger(remote::MemoryReader &reader,
remote::RemoteAddress address,
IntegerType *dest) const {
auto data = reader.readBytes(address, size);
if (!data) {
return false;
}
#if defined(__BIG_ENDIAN__)
assert(false && "Big endian not supported for readMaskedInteger");
#else
IntegerType result = 0;
IntegerType resultBit = 1; // Start from least-significant bit
auto bytes = static_cast<const uint8_t *>(data.get());
for (unsigned i = 0; i < size; ++i) {
for (unsigned b = 1; b < 256; b <<= 1) {
if ((mask[i] & b) != 0) {
if ((bytes[i] & b) != 0) {
result |= resultBit;
}
resultBit <<= 1;