-
Notifications
You must be signed in to change notification settings - Fork 778
/
Copy pathwasm-type.cpp
2779 lines (2523 loc) · 78.3 KB
/
wasm-type.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
/*
* 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 {
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;
Shareability share = Unshared;
// The supertype of this HeapType, if it exists.
HeapTypeInfo* supertype = nullptr;
// The descriptor of this HeapType, if it exists.
HeapTypeInfo* descriptor = nullptr;
// The HeapType described by this one, if it exists.
HeapTypeInfo* described = 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;
HeapTypeKind kind;
union {
Signature signature;
Continuation continuation;
Struct struct_;
Array array;
};
HeapTypeInfo(Signature sig) : kind(HeapTypeKind::Func), signature(sig) {}
HeapTypeInfo(Continuation continuation)
: kind(HeapTypeKind::Cont), continuation(continuation) {}
HeapTypeInfo(const Struct& struct_)
: kind(HeapTypeKind::Struct), struct_(struct_) {}
HeapTypeInfo(Struct&& struct_)
: kind(HeapTypeKind::Struct), struct_(std::move(struct_)) {}
HeapTypeInfo(Array array) : kind(HeapTypeKind::Array), array(array) {}
~HeapTypeInfo();
constexpr bool isSignature() const { return kind == HeapTypeKind::Func; }
constexpr bool isContinuation() const { return kind == HeapTypeKind::Cont; }
constexpr bool isStruct() const { return kind == HeapTypeKind::Struct; }
constexpr bool isArray() const { return kind == HeapTypeKind::Array; }
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 Continuation& a, const Continuation& 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 Continuation& cont);
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 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 Continuation& 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 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 Continuation& a, const Continuation& 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}();
}
};
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 {
HeapTypeInfo* getHeapTypeInfo(HeapType ht) {
assert(!ht.isBasic());
return (HeapTypeInfo*)(ht.getRawID());
}
HeapType asHeapType(std::unique_ptr<HeapTypeInfo>& info) {
return HeapType(uintptr_t(info.get()));
}
bool isTemp(HeapType type) {
return !type.isBasic() && getHeapTypeInfo(type)->isTemp;
}
// 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, which should override `scanType` and/or `scanHeapType`. Edges
// from reference types to the referenced heap types are not walked, so
// subclasses should handle referenced heap types when their reference types are
// visited.
template<typename Self> struct TypeGraphWalkerBase {
void walkRoot(Type* type) {
assert(taskList.empty());
taskList.push_back(Task::scan(type));
doWalk();
}
void walkRoot(HeapType* ht) {
assert(taskList.empty());
taskList.push_back(Task::scan(ht));
doWalk();
}
protected:
Self& self() { return *static_cast<Self*>(this); }
void scanType(Type* type) {
if (type->isTuple()) {
auto& types = const_cast<Tuple&>(type->getTuple());
for (auto it = types.rbegin(); it != types.rend(); ++it) {
taskList.push_back(Task::scan(&*it));
}
}
}
void scanHeapType(HeapType* ht) {
if (ht->isBasic()) {
return;
}
auto* info = getHeapTypeInfo(*ht);
switch (info->kind) {
case HeapTypeKind::Func:
taskList.push_back(Task::scan(&info->signature.results));
taskList.push_back(Task::scan(&info->signature.params));
break;
case HeapTypeKind::Cont:
taskList.push_back(Task::scan(&info->continuation.type));
break;
case HeapTypeKind::Struct: {
auto& fields = info->struct_.fields;
for (auto field = fields.rbegin(); field != fields.rend(); ++field) {
taskList.push_back(Task::scan(&field->type));
}
break;
}
case HeapTypeKind::Array:
taskList.push_back(Task::scan(&info->array.element.type));
break;
case HeapTypeKind::Basic:
WASM_UNREACHABLE("unexpected kind");
}
}
private:
struct Task {
enum Kind {
ScanType,
ScanHeapType,
} kind;
union {
Type* type;
HeapType* heapType;
};
static Task scan(Type* type) { return Task(type, ScanType); }
static Task scan(HeapType* ht) { return Task(ht, ScanHeapType); }
private:
Task(Type* type, Kind kind) : kind(kind), type(type) {}
Task(HeapType* ht, Kind kind) : kind(kind), heapType(ht) {}
};
std::vector<Task> taskList;
void doWalk() {
while (!taskList.empty()) {
auto curr = taskList.back();
taskList.pop_back();
switch (curr.kind) {
case Task::ScanType:
self().scanType(curr.type);
break;
case Task::ScanHeapType:
self().scanHeapType(curr.heapType);
break;
}
}
}
};
// A type graph walker that scans each each direct HeapType child of the root.
template<typename Self> struct HeapTypeChildWalker : TypeGraphWalkerBase<Self> {
void scanType(Type* type) {
isTopLevel = false;
if (type->isRef()) {
this->self().noteChild(type->getHeapType());
} else {
TypeGraphWalkerBase<Self>::scanType(type);
}
}
void scanHeapType(HeapType* type) {
if (isTopLevel) {
isTopLevel = false;
TypeGraphWalkerBase<Self>::scanHeapType(type);
} else {
this->self().noteChild(*type);
}
}
private:
bool isTopLevel = true;
};
struct HeapTypeChildCollector : HeapTypeChildWalker<HeapTypeChildCollector> {
std::vector<HeapType> children;
void noteChild(HeapType type) { children.push_back(type); }
};
HeapType::BasicHeapType getBasicHeapSupertype(HeapType type) {
if (type.isBasic()) {
return HeapType::BasicHeapType(type.getID());
}
auto* info = getHeapTypeInfo(type);
switch (info->kind) {
case HeapTypeKind::Func:
return HeapTypes::func.getBasic(info->share);
case HeapTypeKind::Cont:
return HeapTypes::cont.getBasic(info->share);
case HeapTypeKind::Struct:
return HeapTypes::struct_.getBasic(info->share);
case HeapTypeKind::Array:
return HeapTypes::array.getBasic(info->share);
case HeapTypeKind::Basic:
break;
}
WASM_UNREACHABLE("unexpected kind");
};
std::optional<HeapType> getBasicHeapTypeLUB(HeapType::BasicHeapType a,
HeapType::BasicHeapType b) {
if (a == b) {
return a;
}
if (HeapType(a).getTop() != HeapType(b).getTop()) {
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);
}
auto bUnshared = HeapType(b).getBasic(Unshared);
HeapType lubUnshared;
switch (HeapType(a).getBasic(Unshared)) {
case HeapType::ext:
if (bUnshared != HeapType::string) {
return std::nullopt;
}
lubUnshared = HeapType::ext;
break;
case HeapType::func:
case HeapType::cont:
case HeapType::exn:
return std::nullopt;
case HeapType::any:
lubUnshared = HeapType::any;
break;
case HeapType::eq:
if (bUnshared == HeapType::i31 || bUnshared == HeapType::struct_ ||
bUnshared == HeapType::array) {
lubUnshared = HeapType::eq;
} else {
lubUnshared = HeapType::any;
}
break;
case HeapType::i31:
if (bUnshared == HeapType::struct_ || bUnshared == HeapType::array) {
lubUnshared = HeapType::eq;
} else {
lubUnshared = HeapType::any;
}
break;
case HeapType::struct_:
if (bUnshared == HeapType::array) {
lubUnshared = HeapType::eq;
} else {
lubUnshared = HeapType::any;
}
break;
case HeapType::array:
lubUnshared = HeapType::any;
break;
case HeapType::string:
// String has already been handled: we sorted before in a way that ensures
// the type the string is compared to is of a higher index, which means it
// is a bottom type (string is the last type that is not a bottom type),
// but we have handled the case of either a or b being a bottom type
// earlier already.
case HeapType::none:
case HeapType::noext:
case HeapType::nofunc:
case HeapType::nocont:
case HeapType::noexn:
// Bottom types already handled.
WASM_UNREACHABLE("unexpected basic type");
}
auto share = HeapType(a).getShared();
return {lubUnshared.getBasic(share)};
}
} // anonymous namespace
HeapTypeInfo::~HeapTypeInfo() {
switch (kind) {
case HeapTypeKind::Func:
signature.~Signature();
return;
case HeapTypeKind::Cont:
continuation.~Continuation();
return;
case HeapTypeKind::Struct:
struct_.~Struct();
return;
case HeapTypeKind::Array:
array.~Array();
return;
case HeapTypeKind::Basic:
break;
}
WASM_UNREACHABLE("unexpected kind");
}
namespace {
struct TupleStore {
std::recursive_mutex mutex;
// Track unique_ptrs for constructed tuples to avoid leaks.
std::vector<std::unique_ptr<Tuple>> constructedTuples;
// Maps from constructed tuples to their canonical Type IDs.
std::unordered_map<std::reference_wrapper<const Tuple>, uintptr_t> typeIDs;
Type insert(const Tuple& info) { return doInsert(info); }
Type insert(std::unique_ptr<Tuple>&& info) { return doInsert(info); }
bool hasCanonical(const Tuple& info, Tuple& canonical);
void clear() {
typeIDs.clear();
constructedTuples.clear();
}
private:
template<typename Ref> Type doInsert(Ref& tupleRef) {
const Tuple& tuple = [&]() {
if constexpr (std::is_same_v<Ref, const Tuple>) {
return tupleRef;
} else if constexpr (std::is_same_v<Ref, std::unique_ptr<Tuple>>) {
return *tupleRef;
}
}();
auto getPtr = [&]() -> std::unique_ptr<Tuple> {
if constexpr (std::is_same_v<Ref, const Tuple>) {
return std::make_unique<Tuple>(tupleRef);
} else if constexpr (std::is_same_v<Ref, std::unique_ptr<Tuple>>) {
return std::move(tupleRef);
}
};
auto insertNew = [&]() {
auto ptr = getPtr();
TypeID id = uintptr_t(ptr.get()) | 1;
assert(id > Type::_last_basic_type);
typeIDs.insert({*ptr, id});
constructedTuples.emplace_back(std::move(ptr));
return Type(id);
};
// Turn e.g. singleton tuple into non-tuple.
if (tuple.size() == 0) {
return Type::none;
}
if (tuple.size() == 1) {
return tuple[0];
}
std::lock_guard<std::recursive_mutex> lock(mutex);
// Check whether we already have a type for this tuple.
auto indexIt = typeIDs.find(std::cref(tuple));
if (indexIt != typeIDs.end()) {
return Type(indexIt->second);
}
// We do not have a type for this tuple already. Create one.
return insertNew();
}
};
static TupleStore globalTupleStore;
static std::vector<std::unique_ptr<HeapTypeInfo>> globalHeapTypeStore;
static std::recursive_mutex globalHeapTypeStoreMutex;
// 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() {
globalTupleStore.clear();
globalHeapTypeStore.clear();
globalRecGroupStore.clear();
}
Type::Type(std::initializer_list<Type> types) : Type(Tuple(types)) {}
Type::Type(const Tuple& tuple) {
validateTuple(tuple);
new (this) Type(globalTupleStore.insert(tuple));
}
Type::Type(Tuple&& tuple) {
new (this) Type(globalTupleStore.insert(std::move(tuple)));
}
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();
}
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()) {
return t.getHeapType().getFeatures();
}
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);
}
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;
}
Type Type::getLeastUpperBound(Type a, Type b) {
if (a == b) {
return a;
}
if (a == Type::unreachable) {
return b;
}
if (b == Type::unreachable) {
return a;
}
if (a.isTuple() && b.isTuple()) {
auto size = a.size();
if (size != b.size()) {
return Type::none;
}
std::vector<Type> elems;
elems.reserve(size);
for (size_t i = 0; i < size; ++i) {
auto lub = Type::getLeastUpperBound(a[i], b[i]);
if (lub == Type::none) {
return Type::none;
}
elems.push_back(lub);
}
return Type(elems);
}
if (a.isRef() && b.isRef()) {
if (auto heapType =
HeapType::getLeastUpperBound(a.getHeapType(), b.getHeapType())) {
auto nullability =
(a.isNullable() || b.isNullable()) ? Nullable : NonNullable;
return Type(*heapType, nullability);
}
}
return Type::none;
}
Type Type::getGreatestLowerBound(Type a, Type b) {
if (a == b) {
return a;
}
if (a.isTuple() && b.isTuple() && a.size() == b.size()) {
std::vector<Type> elems;
size_t size = a.size();
elems.reserve(size);
for (size_t i = 0; i < size; ++i) {
auto glb = Type::getGreatestLowerBound(a[i], b[i]);
if (glb == Type::unreachable) {
return Type::unreachable;
}
elems.push_back(glb);
}
return Tuple(elems);
}
if (!a.isRef() || !b.isRef()) {
return Type::unreachable;
}
auto heapA = a.getHeapType();
auto heapB = b.getHeapType();
if (heapA.getBottom() != heapB.getBottom()) {
return Type::unreachable;
}
auto nullability =
(a.isNonNullable() || b.isNonNullable()) ? NonNullable : Nullable;
HeapType heapType;
if (HeapType::isSubType(heapA, heapB)) {
heapType = heapA;
} else if (HeapType::isSubType(heapB, heapA)) {
heapType = heapB;
} else {
heapType = heapA.getBottom();
}
return Type(heapType, nullability);
}
const Type& Type::Iterator::operator*() const {
if (parent->isTuple()) {
return parent->getTuple()[index];
} else {
assert(index == 0 && *parent != Type::none && "Index out of bounds");
return *parent;
}
}
HeapType::HeapType(Signature sig) {
new (this)
HeapType(globalRecGroupStore.insert(std::make_unique<HeapTypeInfo>(sig)));
}
HeapType::HeapType(Continuation continuation) {
new (this) HeapType(
globalRecGroupStore.insert(std::make_unique<HeapTypeInfo>(continuation)));
}
HeapType::HeapType(const Struct& struct_) {
new (this) HeapType(
globalRecGroupStore.insert(std::make_unique<HeapTypeInfo>(struct_)));
}
HeapType::HeapType(Struct&& struct_) {
new (this) HeapType(globalRecGroupStore.insert(
std::make_unique<HeapTypeInfo>(std::move(struct_))));
}
HeapType::HeapType(Array array) {
new (this)
HeapType(globalRecGroupStore.insert(std::make_unique<HeapTypeInfo>(array)));
}
HeapTypeKind HeapType::getKind() const {
if (isBasic()) {
return HeapTypeKind::Basic;
}
return getHeapTypeInfo(*this)->kind;
}
bool HeapType::isOpen() const {
if (isBasic()) {
return false;
} else {
return getHeapTypeInfo(*this)->isOpen;
}
}
Shareability HeapType::getShared() const {
if (isBasic()) {
return (id & SharedMask) != 0 ? Shared : Unshared;
} else {
return getHeapTypeInfo(*this)->share;
}
}
Signature HeapType::getSignature() const {
assert(isSignature());
return getHeapTypeInfo(*this)->signature;
}
Continuation HeapType::getContinuation() const {
assert(isContinuation());
return getHeapTypeInfo(*this)->continuation;
}
const Struct& HeapType::getStruct() const {
assert(isStruct());
return getHeapTypeInfo(*this)->struct_;
}
Array HeapType::getArray() const {
assert(isArray());
return getHeapTypeInfo(*this)->array;
}
std::optional<HeapType> HeapType::getDeclaredSuperType() const {
if (isBasic()) {
return {};
}
HeapTypeInfo* super = getHeapTypeInfo(*this)->supertype;
if (super != nullptr) {
return HeapType(uintptr_t(super));
}
return {};
}
std::optional<HeapType> HeapType::getSuperType() const {
auto ret = getDeclaredSuperType();
if (ret) {
return ret;
}
auto share = getShared();
// There may be a basic supertype.
if (isBasic()) {
switch (getBasic(Unshared)) {
case ext:
case noext:
case func:
case nofunc:
case cont:
case nocont:
case any:
case none:
case exn:
case noexn:
return {};
case string:
return HeapType(ext).getBasic(share);
case eq:
return HeapType(any).getBasic(share);
case i31:
case struct_:
case array:
return HeapType(eq).getBasic(share);
}
}
auto* info = getHeapTypeInfo(*this);
switch (info->kind) {
case HeapTypeKind::Func:
return HeapType(func).getBasic(share);
case HeapTypeKind::Cont:
return HeapType(cont).getBasic(share);
case HeapTypeKind::Struct:
return HeapType(struct_).getBasic(share);
case HeapTypeKind::Array:
return HeapType(array).getBasic(share);
case HeapTypeKind::Basic:
break;
}
WASM_UNREACHABLE("unexpected kind");
}
std::optional<HeapType> HeapType::getDescriptorType() const {
if (isBasic()) {
return std::nullopt;
}
if (auto* desc = getHeapTypeInfo(*this)->descriptor) {
return HeapType(uintptr_t(desc));
}
return std::nullopt;
}
std::optional<HeapType> HeapType::getDescribedType() const {
if (isBasic()) {
return std::nullopt;
}
if (auto* desc = getHeapTypeInfo(*this)->described) {
return HeapType(uintptr_t(desc));
}
return std::nullopt;
}
size_t HeapType::getDepth() const {
size_t depth = 0;
std::optional<HeapType> super;