-
Notifications
You must be signed in to change notification settings - Fork 855
Expand file tree
/
Copy pathwasm-type.cpp
More file actions
2656 lines (2375 loc) · 73.4 KB
/
wasm-type.cpp
File metadata and controls
2656 lines (2375 loc) · 73.4 KB
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
/*
* Copyright 2017 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <algorithm>
#include <array>
#include <cassert>
#include <map>
#include <shared_mutex>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
#include <variant>
#include "compiler-support.h"
#include "support/hash.h"
#include "support/insert_ordered.h"
#include "wasm-features.h"
#include "wasm-type-printing.h"
#include "wasm-type.h"
#define TRACE_CANONICALIZATION 0
#if TRACE_CANONICALIZATION
#include <iostream>
#endif
namespace wasm {
namespace {
struct TypeInfo {
using type_t = Type;
// Used in assertions to ensure that temporary types don't leak into the
// global store.
bool isTemp = false;
enum Kind {
TupleKind,
RefKind,
} kind;
struct Ref {
HeapType heapType;
Nullability nullability;
};
union {
Tuple tuple;
Ref ref;
};
TypeInfo(const Tuple& tuple) : kind(TupleKind), tuple(tuple) {}
TypeInfo(Tuple&& tuple) : kind(TupleKind), tuple(std::move(tuple)) {}
TypeInfo(HeapType heapType, Nullability nullable)
: kind(RefKind), ref{heapType, nullable} {}
TypeInfo(const TypeInfo& other);
~TypeInfo();
constexpr bool isTuple() const { return kind == TupleKind; }
constexpr bool isRef() const { return kind == RefKind; }
// If this TypeInfo represents a Type that can be represented more simply,
// return that simpler Type. For example, this handles eliminating singleton
// tuple types.
std::optional<Type> getCanonical() const;
bool operator==(const TypeInfo& other) const;
bool operator!=(const TypeInfo& other) const { return !(*this == other); }
};
using RecGroupInfo = std::vector<HeapType>;
struct HeapTypeInfo {
using type_t = HeapType;
// Used in assertions to ensure that temporary types don't leak into the
// global store.
bool isTemp = false;
bool isOpen = false;
// The supertype of this HeapType, if it exists.
HeapTypeInfo* supertype = nullptr;
// The recursion group of this type or null if the recursion group is trivial
// (i.e. contains only this type).
RecGroupInfo* recGroup = nullptr;
size_t recGroupIndex = 0;
enum Kind {
SignatureKind,
StructKind,
ArrayKind,
} kind;
union {
Signature signature;
Struct struct_;
Array array;
};
HeapTypeInfo(Signature sig) : kind(SignatureKind), signature(sig) {}
HeapTypeInfo(const Struct& struct_) : kind(StructKind), struct_(struct_) {}
HeapTypeInfo(Struct&& struct_)
: kind(StructKind), struct_(std::move(struct_)) {}
HeapTypeInfo(Array array) : kind(ArrayKind), array(array) {}
~HeapTypeInfo();
constexpr bool isSignature() const { return kind == SignatureKind; }
constexpr bool isStruct() const { return kind == StructKind; }
constexpr bool isArray() const { return kind == ArrayKind; }
constexpr bool isData() const { return isStruct() || isArray(); }
};
// Helper for coinductively checking whether a pair of Types or HeapTypes are in
// a subtype relation.
struct SubTyper {
bool isSubType(Type a, Type b);
bool isSubType(HeapType a, HeapType b);
bool isSubType(const Tuple& a, const Tuple& b);
bool isSubType(const Field& a, const Field& b);
bool isSubType(const Signature& a, const Signature& b);
bool isSubType(const Struct& a, const Struct& b);
bool isSubType(const Array& a, const Array& b);
};
// Helper for finding the equirecursive least upper bound of two types.
// Helper for printing types.
struct TypePrinter {
// The stream we are printing to.
std::ostream& os;
// The default generator state if no other generator is provided.
std::optional<DefaultTypeNameGenerator> defaultGenerator;
// The function we call to get HeapType names.
HeapTypeNameGenerator generator;
TypePrinter(std::ostream& os, HeapTypeNameGenerator generator)
: os(os), defaultGenerator(), generator(generator) {}
TypePrinter(std::ostream& os)
: TypePrinter(
os, [&](HeapType type) { return defaultGenerator->getNames(type); }) {
defaultGenerator = DefaultTypeNameGenerator{};
}
void printHeapTypeName(HeapType type);
std::ostream& print(Type type);
std::ostream& print(HeapType type);
std::ostream& print(const Tuple& tuple);
std::ostream& print(const Field& field);
std::ostream& print(const Signature& sig);
std::ostream& print(const Struct& struct_,
const std::unordered_map<Index, Name>& fieldNames);
std::ostream& print(const Array& array);
};
struct RecGroupHasher {
// `group` may or may not be canonical, but any other recursion group it
// reaches must be canonical.
RecGroup group;
RecGroupHasher(RecGroup group) : group(group) {}
// Perform the hash.
size_t operator()() const;
// `topLevelHash` is applied to the top-level group members and observes their
// structure, while `hash(HeapType)` is applied to the children of group
// members and does not observe their structure.
size_t topLevelHash(HeapType type) const;
size_t hash(Type type) const;
size_t hash(HeapType type) const;
size_t hash(const TypeInfo& info) const;
size_t hash(const HeapTypeInfo& info) const;
size_t hash(const Tuple& tuple) const;
size_t hash(const Field& field) const;
size_t hash(const Signature& sig) const;
size_t hash(const Struct& struct_) const;
size_t hash(const Array& array) const;
};
struct RecGroupEquator {
// `newGroup` may or may not be canonical, but `otherGroup` and any other
// recursion group reachable by either of them must be canonical.
RecGroup newGroup, otherGroup;
RecGroupEquator(RecGroup newGroup, RecGroup otherGroup)
: newGroup(newGroup), otherGroup(otherGroup) {}
// Perform the comparison.
bool operator()() const;
// `topLevelEq` is applied to the top-level group members and observes their
// structure, while `eq(HeapType)` is applied to the children of group members
// and does not observe their structure.
bool topLevelEq(HeapType a, HeapType b) const;
bool eq(Type a, Type b) const;
bool eq(HeapType a, HeapType b) const;
bool eq(const TypeInfo& a, const TypeInfo& b) const;
bool eq(const HeapTypeInfo& a, const HeapTypeInfo& b) const;
bool eq(const Tuple& a, const Tuple& b) const;
bool eq(const Field& a, const Field& b) const;
bool eq(const Signature& a, const Signature& b) const;
bool eq(const Struct& a, const Struct& b) const;
bool eq(const Array& a, const Array& b) const;
};
// A wrapper around a RecGroup that provides equality and hashing based on the
// structure of the group such that isorecursively equivalent recursion groups
// will compare equal and will have the same hash. Assumes that all recursion
// groups reachable from this one have been canonicalized, except for the
// wrapped group itself.
struct RecGroupStructure {
RecGroup group;
bool operator==(const RecGroupStructure& other) const {
return RecGroupEquator{group, other.group}();
}
};
} // anonymous namespace
} // namespace wasm
namespace std {
template<> class hash<wasm::RecGroupStructure> {
public:
size_t operator()(const wasm::RecGroupStructure& structure) const {
return wasm::RecGroupHasher{structure.group}();
}
};
} // namespace std
namespace wasm {
namespace {
// Generic utility for traversing type graphs. The inserted roots must live as
// long as the Walker because they are referenced by address. This base class
// only has logic for traversing type graphs; figuring out when to stop
// traversing the graph and doing useful work during the traversal is left to
// subclasses.
template<typename Self> struct TypeGraphWalkerBase {
void walkRoot(Type* type);
void walkRoot(HeapType* ht);
// Override these in subclasses to do useful work.
void preVisitType(Type* type) {}
void preVisitHeapType(HeapType* ht) {}
void postVisitType(Type* type) {}
void postVisitHeapType(HeapType* ht) {}
// This base walker does not know when to stop scanning, so at least one of
// these needs to be overridden with a method that calls the base scanning
// method only if some end condition isn't met.
void scanType(Type* type);
void scanHeapType(HeapType* ht);
private:
struct Task {
enum Kind {
PreType,
PreHeapType,
ScanType,
ScanHeapType,
PostType,
PostHeapType,
} kind;
union {
Type* type;
HeapType* heapType;
};
static Task preVisit(Type* type) { return Task(type, PreType); }
static Task preVisit(HeapType* ht) { return Task(ht, PreHeapType); }
static Task scan(Type* type) { return Task(type, ScanType); }
static Task scan(HeapType* ht) { return Task(ht, ScanHeapType); }
static Task postVisit(Type* type) { return Task(type, PostType); }
static Task postVisit(HeapType* ht) { return Task(ht, PostHeapType); }
private:
Task(Type* type, Kind kind) : kind(kind), type(type) {}
Task(HeapType* ht, Kind kind) : kind(kind), heapType(ht) {}
};
void doWalk();
std::vector<Task> taskList;
void push(Type* type);
void push(HeapType* type);
Self& self() { return *static_cast<Self*>(this); }
};
// A type graph walker base class that still does no useful work, but at least
// knows to scan each HeapType only once.
template<typename Self> struct HeapTypeGraphWalker : TypeGraphWalkerBase<Self> {
// Override this.
void noteHeapType(HeapType ht) {}
void scanHeapType(HeapType* ht) {
if (scanned.insert(*ht).second) {
static_cast<Self*>(this)->noteHeapType(*ht);
TypeGraphWalkerBase<Self>::scanHeapType(ht);
}
}
private:
std::unordered_set<HeapType> scanned;
};
// A type graph walker base class that still does no useful work, but at least
// knows to scan each HeapType and Type only once.
template<typename Self> struct TypeGraphWalker : TypeGraphWalkerBase<Self> {
// Override these.
void noteType(Type type) {}
void noteHeapType(HeapType ht) {}
void scanType(Type* type) {
if (scannedTypes.insert(*type).second) {
static_cast<Self*>(this)->noteType(*type);
TypeGraphWalkerBase<Self>::scanType(type);
}
}
void scanHeapType(HeapType* ht) {
if (scannedHeapTypes.insert(*ht).second) {
static_cast<Self*>(this)->noteHeapType(*ht);
TypeGraphWalkerBase<Self>::scanHeapType(ht);
}
}
private:
std::unordered_set<HeapType> scannedHeapTypes;
std::unordered_set<Type> scannedTypes;
};
// A type graph walker that only traverses the direct HeapType children of the
// root, looking through child Types. What to do with each child is left to
// subclasses.
template<typename Self> struct HeapTypeChildWalker : HeapTypeGraphWalker<Self> {
// Override this.
void noteChild(HeapType* child) {}
void scanType(Type* type) {
isTopLevel = false;
HeapTypeGraphWalker<Self>::scanType(type);
}
void scanHeapType(HeapType* ht) {
if (isTopLevel) {
HeapTypeGraphWalker<Self>::scanHeapType(ht);
} else {
static_cast<Self*>(this)->noteChild(ht);
}
}
private:
bool isTopLevel = true;
};
struct HeapTypeChildCollector : HeapTypeChildWalker<HeapTypeChildCollector> {
std::vector<HeapType> children;
void noteChild(HeapType* child) { children.push_back(*child); }
};
} // anonymous namespace
} // namespace wasm
namespace std {
template<> class hash<wasm::TypeInfo> {
public:
size_t operator()(const wasm::TypeInfo& info) const;
};
template<typename T> class hash<reference_wrapper<const T>> {
public:
size_t operator()(const reference_wrapper<const T>& ref) const {
return hash<T>{}(ref.get());
}
};
template<typename T> class equal_to<reference_wrapper<const T>> {
public:
bool operator()(const reference_wrapper<const T>& a,
const reference_wrapper<const T>& b) const {
return equal_to<T>{}(a.get(), b.get());
}
};
} // namespace std
namespace wasm {
namespace {
TypeInfo* getTypeInfo(Type type) {
assert(!type.isBasic());
return (TypeInfo*)type.getID();
}
HeapTypeInfo* getHeapTypeInfo(HeapType ht) {
assert(!ht.isBasic());
return (HeapTypeInfo*)ht.getID();
}
HeapType asHeapType(std::unique_ptr<HeapTypeInfo>& info) {
return HeapType(uintptr_t(info.get()));
}
Type markTemp(Type type) {
if (!type.isBasic()) {
getTypeInfo(type)->isTemp = true;
}
return type;
}
bool isTemp(Type type) { return !type.isBasic() && getTypeInfo(type)->isTemp; }
bool isTemp(HeapType type) {
return !type.isBasic() && getHeapTypeInfo(type)->isTemp;
}
HeapType::BasicHeapType getBasicHeapSupertype(HeapType type) {
if (type.isBasic()) {
return type.getBasic();
}
auto* info = getHeapTypeInfo(type);
switch (info->kind) {
case HeapTypeInfo::SignatureKind:
return HeapType::func;
case HeapTypeInfo::StructKind:
return HeapType::struct_;
case HeapTypeInfo::ArrayKind:
return HeapType::array;
}
WASM_UNREACHABLE("unexpected kind");
};
std::optional<HeapType> getBasicHeapTypeLUB(HeapType::BasicHeapType a,
HeapType::BasicHeapType b) {
if (a == b) {
return a;
}
if (HeapType(a).getBottom() != HeapType(b).getBottom()) {
return {};
}
if (HeapType(a).isBottom()) {
return b;
}
if (HeapType(b).isBottom()) {
return a;
}
// Canonicalize to have `a` be the lesser type.
if (unsigned(a) > unsigned(b)) {
std::swap(a, b);
}
switch (a) {
case HeapType::ext:
case HeapType::func:
return std::nullopt;
case HeapType::any:
return {HeapType::any};
case HeapType::eq:
if (b == HeapType::i31 || b == HeapType::struct_ ||
b == HeapType::array) {
return {HeapType::eq};
}
return {HeapType::any};
case HeapType::i31:
if (b == HeapType::struct_ || b == HeapType::array) {
return {HeapType::eq};
}
return {HeapType::any};
case HeapType::struct_:
if (b == HeapType::array) {
return {HeapType::eq};
}
return {HeapType::any};
case HeapType::array:
case HeapType::string:
case HeapType::stringview_wtf8:
case HeapType::stringview_wtf16:
case HeapType::stringview_iter:
return {HeapType::any};
case HeapType::none:
case HeapType::noext:
case HeapType::nofunc:
// Bottom types already handled.
break;
}
WASM_UNREACHABLE("unexpected basic type");
}
TypeInfo::TypeInfo(const TypeInfo& other) {
kind = other.kind;
switch (kind) {
case TupleKind:
new (&tuple) auto(other.tuple);
return;
case RefKind:
new (&ref) auto(other.ref);
return;
}
WASM_UNREACHABLE("unexpected kind");
}
TypeInfo::~TypeInfo() {
switch (kind) {
case TupleKind:
tuple.~Tuple();
return;
case RefKind:
ref.~Ref();
return;
}
WASM_UNREACHABLE("unexpected kind");
}
std::optional<Type> TypeInfo::getCanonical() const {
if (isTuple()) {
if (tuple.size() == 0) {
return Type::none;
}
if (tuple.size() == 1) {
return tuple[0];
}
}
return {};
}
bool TypeInfo::operator==(const TypeInfo& other) const {
if (kind != other.kind) {
return false;
}
switch (kind) {
case TupleKind:
return tuple == other.tuple;
case RefKind:
return ref.nullability == other.ref.nullability &&
ref.heapType == other.ref.heapType;
}
WASM_UNREACHABLE("unexpected kind");
}
HeapTypeInfo::~HeapTypeInfo() {
switch (kind) {
case SignatureKind:
signature.~Signature();
return;
case StructKind:
struct_.~Struct();
return;
case ArrayKind:
array.~Array();
return;
}
WASM_UNREACHABLE("unexpected kind");
}
struct TypeStore {
std::recursive_mutex mutex;
// Track unique_ptrs for constructed types to avoid leaks.
std::vector<std::unique_ptr<TypeInfo>> constructedTypes;
// Maps from constructed types to their canonical Type IDs.
std::unordered_map<std::reference_wrapper<const TypeInfo>, uintptr_t> typeIDs;
#ifndef NDEBUG
bool isGlobalStore();
#endif
Type insert(const TypeInfo& info) { return doInsert(info); }
Type insert(std::unique_ptr<TypeInfo>&& info) { return doInsert(info); }
bool hasCanonical(const TypeInfo& info, Type& canonical);
void clear() {
typeIDs.clear();
constructedTypes.clear();
}
private:
template<typename Ref> Type doInsert(Ref& infoRef) {
const TypeInfo& info = [&]() {
if constexpr (std::is_same_v<Ref, const TypeInfo>) {
return infoRef;
} else if constexpr (std::is_same_v<Ref, std::unique_ptr<TypeInfo>>) {
infoRef->isTemp = false;
return *infoRef;
}
}();
auto getPtr = [&]() -> std::unique_ptr<TypeInfo> {
if constexpr (std::is_same_v<Ref, const TypeInfo>) {
return std::make_unique<TypeInfo>(infoRef);
} else if constexpr (std::is_same_v<Ref, std::unique_ptr<TypeInfo>>) {
return std::move(infoRef);
}
};
auto insertNew = [&]() {
assert((!isGlobalStore() || !info.isTemp) && "Leaking temporary type!");
auto ptr = getPtr();
TypeID id = uintptr_t(ptr.get());
assert(id > Type::_last_basic_type);
typeIDs.insert({*ptr, id});
constructedTypes.emplace_back(std::move(ptr));
return Type(id);
};
// Turn e.g. singleton tuple into non-tuple.
if (auto canonical = info.getCanonical()) {
return *canonical;
}
std::lock_guard<std::recursive_mutex> lock(mutex);
// Check whether we already have a type for this structural Info.
auto indexIt = typeIDs.find(std::cref(info));
if (indexIt != typeIDs.end()) {
return Type(indexIt->second);
}
// We do not have a type for this Info already. Create one.
return insertNew();
}
};
static TypeStore globalTypeStore;
static std::vector<std::unique_ptr<HeapTypeInfo>> globalHeapTypeStore;
static std::recursive_mutex globalHeapTypeStoreMutex;
#ifndef NDEBUG
bool TypeStore::isGlobalStore() { return this == &globalTypeStore; }
#endif
// Keep track of the constructed recursion groups.
struct RecGroupStore {
std::mutex mutex;
// Store the structures of all rec groups created so far so we can avoid
// creating duplicates.
std::unordered_set<RecGroupStructure> canonicalGroups;
// Keep the `RecGroupInfos` for the nontrivial groups stored in
// `canonicalGroups` alive.
std::vector<std::unique_ptr<RecGroupInfo>> builtGroups;
RecGroup insert(RecGroup group) {
RecGroupStructure structure{group};
auto [it, inserted] = canonicalGroups.insert(structure);
if (inserted) {
return group;
} else {
return it->group;
}
}
RecGroup insert(std::unique_ptr<RecGroupInfo>&& info) {
RecGroup group{uintptr_t(info.get())};
auto canonical = insert(group);
if (canonical == group) {
builtGroups.emplace_back(std::move(info));
}
return canonical;
}
// Utility for canonicalizing HeapTypes with trivial recursion groups.
HeapType insert(std::unique_ptr<HeapTypeInfo>&& info) {
std::lock_guard<std::mutex> lock(mutex);
assert(!info->recGroup && "Unexpected nontrivial rec group");
auto group = asHeapType(info).getRecGroup();
auto canonical = insert(group);
if (group == canonical) {
std::lock_guard<std::recursive_mutex> storeLock(globalHeapTypeStoreMutex);
globalHeapTypeStore.emplace_back(std::move(info));
}
return canonical[0];
}
void clear() {
canonicalGroups.clear();
builtGroups.clear();
}
};
static RecGroupStore globalRecGroupStore;
void validateTuple(const Tuple& tuple) {
#ifndef NDEBUG
for (auto type : tuple) {
assert(type.isSingle());
}
#endif
}
} // anonymous namespace
void destroyAllTypesForTestingPurposesOnly() {
globalTypeStore.clear();
globalHeapTypeStore.clear();
globalRecGroupStore.clear();
}
Type::Type(std::initializer_list<Type> types) : Type(Tuple(types)) {}
Type::Type(const Tuple& tuple) {
validateTuple(tuple);
#ifndef NDEBUG
for (auto type : tuple) {
assert(!isTemp(type) && "Leaking temporary type!");
}
#endif
new (this) Type(globalTypeStore.insert(tuple));
}
Type::Type(Tuple&& tuple) {
#ifndef NDEBUG
for (auto type : tuple) {
assert(!isTemp(type) && "Leaking temporary type!");
}
#endif
new (this) Type(globalTypeStore.insert(std::move(tuple)));
}
Type::Type(HeapType heapType, Nullability nullable) {
assert(!isTemp(heapType) && "Leaking temporary type!");
new (this) Type(globalTypeStore.insert(TypeInfo(heapType, nullable)));
}
bool Type::isTuple() const {
if (isBasic()) {
return false;
} else {
return getTypeInfo(*this)->isTuple();
}
}
bool Type::isRef() const {
if (isBasic()) {
return false;
} else {
return getTypeInfo(*this)->isRef();
}
}
bool Type::isFunction() const {
if (isBasic()) {
return false;
} else {
auto* info = getTypeInfo(*this);
return info->isRef() && info->ref.heapType.isFunction();
}
}
bool Type::isData() const {
if (isBasic()) {
return false;
} else {
auto* info = getTypeInfo(*this);
return info->isRef() && info->ref.heapType.isData();
}
}
bool Type::isNullable() const {
if (isRef()) {
return getTypeInfo(*this)->ref.nullability == Nullable;
} else {
return false;
}
}
bool Type::isNonNullable() const {
if (isRef()) {
return getTypeInfo(*this)->ref.nullability == NonNullable;
} else {
return false;
}
}
bool Type::isStruct() const { return isRef() && getHeapType().isStruct(); }
bool Type::isArray() const { return isRef() && getHeapType().isArray(); }
bool Type::isString() const { return isRef() && getHeapType().isString(); }
bool Type::isDefaultable() const {
// A variable can get a default value if its type is concrete (unreachable
// and none have no values, hence no default), and if it's a reference, it
// must be nullable.
if (isTuple()) {
for (auto t : *this) {
if (!t.isDefaultable()) {
return false;
}
}
return true;
}
return isConcrete() && !isNonNullable();
}
Nullability Type::getNullability() const {
return isNullable() ? Nullable : NonNullable;
}
unsigned Type::getByteSize() const {
// TODO: alignment?
auto getSingleByteSize = [](Type t) {
switch (t.getBasic()) {
case Type::i32:
case Type::f32:
return 4;
case Type::i64:
case Type::f64:
return 8;
case Type::v128:
return 16;
case Type::none:
case Type::unreachable:
break;
}
WASM_UNREACHABLE("invalid type");
};
if (isTuple()) {
unsigned size = 0;
for (const auto& t : *this) {
size += getSingleByteSize(t);
}
return size;
}
return getSingleByteSize(*this);
}
unsigned Type::hasByteSize() const {
auto hasSingleByteSize = [](Type t) { return t.isNumber(); };
if (isTuple()) {
for (const auto& t : *this) {
if (!hasSingleByteSize(t)) {
return false;
}
}
return true;
}
return hasSingleByteSize(*this);
}
Type Type::reinterpret() const {
assert(!isTuple() && "Unexpected tuple type");
switch ((*begin()).getBasic()) {
case Type::i32:
return f32;
case Type::i64:
return f64;
case Type::f32:
return i32;
case Type::f64:
return i64;
default:
WASM_UNREACHABLE("invalid type");
}
}
FeatureSet Type::getFeatures() const {
auto getSingleFeatures = [](Type t) -> FeatureSet {
if (t.isRef()) {
// A reference type implies we need that feature. Some also require
// more, such as GC or exceptions, and may require us to look into child
// types.
struct ReferenceFeatureCollector
: HeapTypeChildWalker<ReferenceFeatureCollector> {
FeatureSet feats = FeatureSet::None;
void noteChild(HeapType* heapType) {
if (heapType->isBasic()) {
switch (heapType->getBasic()) {
case HeapType::ext:
case HeapType::func:
feats |= FeatureSet::ReferenceTypes;
return;
case HeapType::any:
case HeapType::eq:
case HeapType::i31:
case HeapType::struct_:
case HeapType::array:
feats |= FeatureSet::ReferenceTypes | FeatureSet::GC;
return;
case HeapType::string:
case HeapType::stringview_wtf8:
case HeapType::stringview_wtf16:
case HeapType::stringview_iter:
feats |= FeatureSet::ReferenceTypes | FeatureSet::Strings;
return;
case HeapType::none:
case HeapType::noext:
case HeapType::nofunc:
// Technically introduced in GC, but used internally as part of
// ref.null with just reference types.
feats |= FeatureSet::ReferenceTypes;
return;
}
}
if (heapType->isStruct() || heapType->isArray() ||
heapType->getRecGroup().size() > 1 || heapType->getSuperType()) {
feats |= FeatureSet::ReferenceTypes | FeatureSet::GC;
} else if (heapType->isSignature()) {
// This is a function reference, which requires reference types and
// possibly also multivalue (if it has multiple returns). Note that
// technically typed function references also require GC, however,
// we use these types internally regardless of the presence of GC
// (in particular, since during load of the wasm we don't know the
// features yet, so we apply the more refined types), so we don't
// add that in any case here.
feats |= FeatureSet::ReferenceTypes;
auto sig = heapType->getSignature();
if (sig.results.isTuple()) {
feats |= FeatureSet::Multivalue;
}
}
// In addition, scan their non-ref children, to add dependencies on
// things like SIMD.
for (auto child : heapType->getTypeChildren()) {
if (!child.isRef()) {
feats |= child.getFeatures();
}
}
}
};
ReferenceFeatureCollector collector;
auto heapType = t.getHeapType();
collector.walkRoot(&heapType);
collector.noteChild(&heapType);
return collector.feats;
}
TODO_SINGLE_COMPOUND(t);
switch (t.getBasic()) {
case Type::v128:
return FeatureSet::SIMD;
default:
return FeatureSet::MVP;
}
};
if (isTuple()) {
FeatureSet feats = FeatureSet::Multivalue;
for (const auto& t : *this) {
feats |= getSingleFeatures(t);
}
return feats;
}
return getSingleFeatures(*this);
}
const Tuple& Type::getTuple() const {
assert(isTuple());
return getTypeInfo(*this)->tuple;
}
HeapType Type::getHeapType() const {
assert(isRef());
return getTypeInfo(*this)->ref.heapType;
}
Type Type::get(unsigned byteSize, bool float_) {
if (byteSize < 4) {
return Type::i32;
}
if (byteSize == 4) {
return float_ ? Type::f32 : Type::i32;
}
if (byteSize == 8) {
return float_ ? Type::f64 : Type::i64;
}
if (byteSize == 16) {
return Type::v128;
}
WASM_UNREACHABLE("invalid size");
}
bool Type::isSubType(Type left, Type right) {
// As an optimization, in the common case do not even construct a SubTyper.
if (left == right) {
return true;
}
return SubTyper().isSubType(left, right);
}
std::vector<HeapType> Type::getHeapTypeChildren() {
HeapTypeChildCollector collector;
collector.walkRoot(this);
return collector.children;
}
bool Type::hasLeastUpperBound(Type a, Type b) {
return getLeastUpperBound(a, b) != Type::none;
}