Debian Codegraph @

js/src/wasm/WasmValType.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 *
4 * Copyright 2021 Mozilla Foundation
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 #ifndef wasm_valtype_h
20 #define wasm_valtype_h
21
22 #include "mozilla/HashTable.h"
23 #include "mozilla/Maybe.h"
24
25 #include <type_traits>
26
27 #include "jit/IonTypes.h"
28 #include "wasm/WasmConstants.h"
29 #include "wasm/WasmSerialize.h"
30 #include "wasm/WasmTypeDecls.h"
31
32 namespace js {
33 namespace wasm {
34
35 // A PackedTypeCode represents any value type.
36 union PackedTypeCode {
37 public:
38 using PackedRepr = uint64_t;
39
40 private:
41 static constexpr size_t NullableBits = 1;
42 static constexpr size_t TypeCodeBits = 8;
43 static constexpr size_t TypeDefBits = 48;
44 static constexpr size_t PointerTagBits = 2;
45 static constexpr size_t UnusedBits = 5;
46
47 static_assert(NullableBits + TypeCodeBits + TypeDefBits + PointerTagBits +
48 UnusedBits ==
49 (sizeof(PackedRepr) * 8),
50 "enough bits");
51
52 PackedRepr bits_;
53 struct {
54 PackedRepr nullable_ : NullableBits;
55 PackedRepr typeCode_ : TypeCodeBits;
56 // A pointer to the TypeDef this type references. We use 48-bits for this,
57 // and rely on system memory allocators not allocating outside of this
58 // range. This is also assumed by JS::Value, and so should be safe here.
59 PackedRepr typeDef_ : TypeDefBits;
60 // Reserve the bottom two bits for use as a tagging scheme for BlockType
61 // and ResultType, which can encode a ValType inside themselves in special
62 // cases.
63 PackedRepr pointerTag_ : PointerTagBits;
64 // The remaining bits are unused, but still need to be explicitly
65 // initialized to zero.
66 PackedRepr unused_ : UnusedBits;
67 };
68
69 explicit constexpr PackedTypeCode(PackedRepr bits) : bits_(bits) {}
70
71 constexpr PackedTypeCode(PackedRepr nullable, PackedRepr typeCode,
72 PackedRepr typeDef)
73 : nullable_(nullable),
74 typeCode_(typeCode),
75 typeDef_(typeDef),
76 pointerTag_(0),
77 unused_(0) {}
78
79 public:
80 PackedTypeCode() = default;
81
82 static constexpr PackedRepr NoTypeCode = ((uint64_t)1 << TypeCodeBits) - 1;
83
84 static constexpr PackedTypeCode invalid() {
85 return PackedTypeCode{false, NoTypeCode, 0};
86 }
87
88 static constexpr PackedTypeCode fromBits(PackedRepr bits) {
89 return PackedTypeCode{bits};
90 }
91
92 static PackedTypeCode pack(TypeCode tc, const TypeDef* typeDef,
93 bool isNullable) {
94 MOZ_ASSERT(uint32_t(tc) <= ((1 << TypeCodeBits) - 1));
95 MOZ_ASSERT_IF(tc != AbstractTypeRefCode, typeDef == nullptr);
96 MOZ_ASSERT_IF(tc == AbstractTypeRefCode, typeDef != nullptr);
97 auto tydef = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(typeDef));
98 #if defined(JS_64BIT) && defined(DEBUG)
99 // Double check that `typeDef` only has 48 significant bits, with the top
100 // 16 being zero. This is necessary since we will only store the lowest
101 // 48 bits of it, as noted above. There's no equivalent check on 32 bit
102 // targets since we can store the whole pointer.
103 static_assert(sizeof(int64_t) == sizeof(uintptr_t));
104 MOZ_ASSERT((tydef >> TypeDefBits) == 0);
105 #endif
106 return PackedTypeCode{isNullable, PackedRepr(tc), tydef};
107 }
108
109 static constexpr PackedTypeCode pack(TypeCode tc, bool nullable) {
110 MOZ_ASSERT(uint32_t(tc) <= ((1 << TypeCodeBits) - 1));
111 MOZ_ASSERT(tc != AbstractTypeRefCode);
112 return PackedTypeCode{nullable, PackedRepr(tc), 0};
113 }
114
115 static constexpr PackedTypeCode pack(TypeCode tc) { return pack(tc, false); }
116
117 constexpr bool isValid() const { return typeCode_ != NoTypeCode; }
118
119 PackedRepr bits() const { return bits_; }
120
121 constexpr TypeCode typeCode() const {
122 MOZ_ASSERT(isValid());
123 return TypeCode(typeCode_);
124 }
125
126 // Return the TypeCode, but return AbstractReferenceTypeCode for any reference
127 // type.
128 //
129 // This function is very, very hot, hence what would normally be a switch on
130 // the value `c` to map the reference types to AbstractReferenceTypeCode has
131 // been distilled into a simple comparison; this is fastest. Should type
132 // codes become too complicated for this to work then a lookup table also has
133 // better performance than a switch.
134 //
135 // An alternative is for the PackedTypeCode to represent something closer to
136 // what ValType needs, so that this decoding step is not necessary, but that
137 // moves complexity elsewhere, and the perf gain here would be only about 1%
138 // for baseline compilation throughput.
139 constexpr TypeCode typeCodeAbstracted() const {
140 TypeCode tc = typeCode();
141 return tc < LowestPrimitiveTypeCode ? AbstractReferenceTypeCode : tc;
142 }
143
144 // Return whether this type is a reference type.
145 bool isRefType() const {
146 return typeCodeAbstracted() == AbstractReferenceTypeCode;
147 }
148
149 // Return whether this type is represented by a reference at runtime.
150 bool isRefRepr() const { return typeCode() < LowestPrimitiveTypeCode; }
151
152 const TypeDef* typeDef() const {
153 MOZ_ASSERT(isValid());
154 // On a 64-bit target, this reconstitutes the pointer by zero-extending
155 // the lowest TypeDefBits bits of `typeDef_`. On a 32-bit target, the
156 // pointer is stored exactly in the lowest 32 bits of `typeDef_`.
157 return (const TypeDef*)(uintptr_t)typeDef_;
158 }
159
160 bool isNullable() const {
161 MOZ_ASSERT(isValid());
162 return bool(nullable_);
163 }
164
165 PackedTypeCode withIsNullable(bool nullable) const {
166 MOZ_ASSERT(isRefType());
167 PackedTypeCode mutated = *this;
168 mutated.nullable_ = (PackedRepr)nullable;
169 return mutated;
170 }
171
172 bool operator==(const PackedTypeCode& rhs) const {
173 return bits_ == rhs.bits_;
174 }
175 bool operator!=(const PackedTypeCode& rhs) const {
176 return bits_ != rhs.bits_;
177 }
178 };
179
180 static_assert(sizeof(PackedTypeCode) == sizeof(uint64_t), "packed");
181
182 // A SerializableTypeCode represents any value type in a form that can be
183 // serialized and deserialized.
184 union SerializableTypeCode {
185 using PackedRepr = uintptr_t;
186
187 static constexpr size_t NullableBits = 1;
188 static constexpr size_t TypeCodeBits = 8;
189 static constexpr size_t TypeIndexBits = 20;
190
191 PackedRepr bits;
192 struct {
193 PackedRepr nullable : NullableBits;
194 PackedRepr typeCode : TypeCodeBits;
195 PackedRepr typeIndex : TypeIndexBits;
196 };
197
198 WASM_CHECK_CACHEABLE_POD(bits);
199
200 static constexpr PackedRepr NoTypeIndex = (1 << TypeIndexBits) - 1;
201
202 static_assert(NullableBits + TypeCodeBits + TypeIndexBits <=
203 (sizeof(PackedRepr) * 8),
204 "enough bits");
205 static_assert(NoTypeIndex < (1 << TypeIndexBits), "enough bits");
206 static_assert(MaxTypes < NoTypeIndex, "enough bits");
207
208 // Defined in WasmSerialize.cpp
209 static inline SerializableTypeCode serialize(PackedTypeCode ptc,
210 const TypeContext& types);
211 inline PackedTypeCode deserialize(const TypeContext& types);
212 };
213
214 WASM_DECLARE_CACHEABLE_POD(SerializableTypeCode);
215 static_assert(sizeof(SerializableTypeCode) == sizeof(uintptr_t), "packed");
216
217 // [SMDOC] Comparing type definitions
218 //
219 // WebAssembly type equality is structural, and we implement canonicalization
220 // such that equality of pointers to type definitions means that the type
221 // definitions are structurally equal.
222 //
223 // 'IsoEquals' is the algorithm used to determine if two types are equal while
224 // canonicalizing types.
225 //
226 // A iso equals type code encodes a type code for use in equality and hashing
227 // matching. It normalizes type references that are local to a recursion group
228 // so that they can be bitwise compared to type references from other recursion
229 // groups.
230 //
231 // This is useful for the following example:
232 // (rec (func $a))
233 // (rec
234 // (func $b)
235 // (struct
236 // (field (ref $a)))
237 // (field (ref $b)))
238 // )
239 // (rec
240 // (func $c)
241 // (struct
242 // (field (ref $a)))
243 // (field (ref $c)))
244 // )
245 //
246 // The last two recursion groups are identical and should canonicalize to the
247 // same instance. However, they will be initially represented as two separate
248 // recursion group instances each with an array type instance with element
249 // types that point to the function type instance before them. A bitwise
250 // comparison of the element type pointers would fail.
251 //
252 // To solve this, we use `IsoEqualsTypeCode` to convert the example to:
253 // (rec (func $a))
254 // (rec
255 // (func $b)
256 // (struct
257 // (field (ref nonlocal $a)))
258 // (field (ref local 0)))
259 // )
260 // (rec
261 // (func $c)
262 // (struct
263 // (field (ref nonlocal $a)))
264 // (field (ref local 0)))
265 // )
266 //
267 // Now, comparing the element types will see that these are local type
268 // references of the same kinds. `IsoEqualsTypeCode` performs the same mechanism
269 // as `tie` in the MVP presentation of type equality [1].
270 //
271 // [1]
272 // https://github.com/WebAssembly/gc/blob/main/proposals/gc/MVP.md#equivalence
273 union IsoEqualsTypeCode {
274 using PackedRepr = uint64_t;
275
276 static constexpr size_t NullableBits = 1;
277 static constexpr size_t TypeCodeBits = 8;
278 static constexpr size_t TypeRefBits = 48;
279
280 PackedRepr bits;
281 struct {
282 PackedRepr nullable : NullableBits;
283 PackedRepr typeCode : TypeCodeBits;
284 PackedRepr typeRef : TypeRefBits;
285 };
286
287 WASM_CHECK_CACHEABLE_POD(bits);
288
289 static_assert(NullableBits + TypeCodeBits + TypeRefBits <=
290 (sizeof(PackedRepr) * 8),
291 "enough bits");
292
293 // Defined in WasmTypeDef.h to avoid a cycle while allowing inlining
294 static inline IsoEqualsTypeCode forIsoEquals(PackedTypeCode ptc,
295 const RecGroup* recGroup);
296
297 bool operator==(IsoEqualsTypeCode other) const { return bits == other.bits; }
298 bool operator!=(IsoEqualsTypeCode other) const { return bits != other.bits; }
299 HashNumber hash() const { return HashNumber(bits); }
300 };
301
302 // An enum that describes the representation classes for tables; The table
303 // element type is mapped into this by Table::repr().
304
305 enum class TableRepr { Ref, Func };
306
307 // An enum that describes the different type hierarchies.
308
309 enum class RefTypeHierarchy { Func, Extern, Exn, Any };
310
311 // The RefType carries more information about types t for which t.isRefType()
312 // is true.
313
314 class RefType {
315 public:
316 enum Kind {
317 Func = uint8_t(TypeCode::FuncRef),
318 Extern = uint8_t(TypeCode::ExternRef),
319 Exn = uint8_t(TypeCode::ExnRef),
320 Any = uint8_t(TypeCode::AnyRef),
321 NoFunc = uint8_t(TypeCode::NullFuncRef),
322 NoExtern = uint8_t(TypeCode::NullExternRef),
323 NoExn = uint8_t(TypeCode::NullExnRef),
324 None = uint8_t(TypeCode::NullAnyRef),
325 Eq = uint8_t(TypeCode::EqRef),
326 I31 = uint8_t(TypeCode::I31Ref),
327 Struct = uint8_t(TypeCode::StructRef),
328 Array = uint8_t(TypeCode::ArrayRef),
329 TypeRef = uint8_t(AbstractTypeRefCode)
330 };
331
332 private:
333 PackedTypeCode ptc_;
334
335 RefType(Kind kind, bool nullable)
336 : ptc_(PackedTypeCode::pack(TypeCode(kind), nullable)) {
337 MOZ_ASSERT(isValid());
338 }
339
340 RefType(const TypeDef* typeDef, bool nullable)
341 : ptc_(PackedTypeCode::pack(AbstractTypeRefCode, typeDef, nullable)) {
342 MOZ_ASSERT(isValid());
343 }
344
345 public:
346 RefType() : ptc_(PackedTypeCode::invalid()) {}
347 explicit RefType(PackedTypeCode ptc) : ptc_(ptc) { MOZ_ASSERT(isValid()); }
348
349 static RefType fromKind(Kind kind, bool nullable) {
350 MOZ_ASSERT(kind != TypeRef);
351 return RefType(kind, nullable);
352 }
353
354 static RefType fromTypeCode(TypeCode tc, bool nullable) {
355 MOZ_ASSERT(tc != AbstractTypeRefCode);
356 return RefType(Kind(tc), nullable);
357 }
358
359 static RefType fromTypeDef(const TypeDef* typeDef, bool nullable) {
360 return RefType(typeDef, nullable);
361 }
362
363 Kind kind() const { return Kind(ptc_.typeCode()); }
364
365 const TypeDef* typeDef() const { return ptc_.typeDef(); }
366
367 PackedTypeCode packed() const { return ptc_; }
368 PackedTypeCode* addressOfPacked() { return &ptc_; }
369 const PackedTypeCode* addressOfPacked() const { return &ptc_; }
370
371 // Further restricts PackedTypeCode::isValid() to only those TypeCodes which
372 // represent a wasm reference type.
373 bool isValid() const {
374 if (!ptc_.isValid()) {
375 return false;
376 }
377
378 MOZ_ASSERT((ptc_.typeCode() == AbstractTypeRefCode) ==
379 (ptc_.typeDef() != nullptr));
380 switch (ptc_.typeCode()) {
381 case TypeCode::FuncRef:
382 case TypeCode::ExternRef:
383 case TypeCode::ExnRef:
384 case TypeCode::AnyRef:
385 case TypeCode::EqRef:
386 case TypeCode::I31Ref:
387 case TypeCode::StructRef:
388 case TypeCode::ArrayRef:
389 case TypeCode::NullFuncRef:
390 case TypeCode::NullExternRef:
391 case TypeCode::NullExnRef:
392 case TypeCode::NullAnyRef:
393 case AbstractTypeRefCode:
394 return true;
395 default:
396 return false;
397 }
398 }
399
400 static RefType func() { return RefType(Func, true); }
401 static RefType extern_() { return RefType(Extern, true); }
402 static RefType exn() { return RefType(Exn, true); }
403 static RefType any() { return RefType(Any, true); }
404 static RefType nofunc() { return RefType(NoFunc, true); }
405 static RefType noextern() { return RefType(NoExtern, true); }
406 static RefType noexn() { return RefType(NoExn, true); }
407 static RefType none() { return RefType(None, true); }
408 static RefType eq() { return RefType(Eq, true); }
409 static RefType i31() { return RefType(I31, true); }
410 static RefType struct_() { return RefType(Struct, true); }
411 static RefType array() { return RefType(Array, true); }
412
413 bool isFunc() const { return kind() == RefType::Func; }
414 bool isExtern() const { return kind() == RefType::Extern; }
415 bool isAny() const { return kind() == RefType::Any; }
416 bool isNoFunc() const { return kind() == RefType::NoFunc; }
417 bool isNoExtern() const { return kind() == RefType::NoExtern; }
418 bool isNoExn() const { return kind() == RefType::NoExn; }
419 bool isNone() const { return kind() == RefType::None; }
420 bool isEq() const { return kind() == RefType::Eq; }
421 bool isI31() const { return kind() == RefType::I31; }
422 bool isStruct() const { return kind() == RefType::Struct; }
423 bool isArray() const { return kind() == RefType::Array; }
424 bool isTypeRef() const { return kind() == RefType::TypeRef; }
425
426 bool isNullable() const { return bool(ptc_.isNullable()); }
427 RefType asNonNullable() const { return withIsNullable(false); }
428 RefType withIsNullable(bool nullable) const {
429 return RefType(ptc_.withIsNullable(nullable));
430 }
431
432 bool isRefBottom() const {
433 return isNone() || isNoFunc() || isNoExtern() || isNoExn();
434 }
435
436 // These methods are defined in WasmTypeDef.h to avoid a cycle while allowing
437 // inlining.
438 inline RefTypeHierarchy hierarchy() const;
439 inline TableRepr tableRepr() const;
440 inline bool isFuncHierarchy() const;
441 inline bool isExternHierarchy() const;
442 inline bool isAnyHierarchy() const;
443 inline bool isExnHierarchy() const;
444 static bool isSubTypeOf(RefType subType, RefType superType);
445 static bool castPossible(RefType sourceType, RefType destType);
446
447 // Gets the top of the given type's hierarchy, e.g. Any for structs and
448 // arrays, and Func for funcs.
449 RefType topType() const;
450
451 // Gets the bottom of the given type's hierarchy, e.g. None for structs and
452 // arrays, and NoFunc for funcs.
453 RefType bottomType() const;
454
455 static RefType leastUpperBound(RefType a, RefType b);
456
457 // Gets the TypeDefKind associated with this RefType, e.g. TypeDefKind::Struct
458 // for RefType::Struct.
459 TypeDefKind typeDefKind() const;
460
461 inline void AddRef() const;
462 inline void Release() const;
463
464 bool operator==(const RefType& that) const { return ptc_ == that.ptc_; }
465 bool operator!=(const RefType& that) const { return ptc_ != that.ptc_; }
466 };
467
468 using RefTypeVector = Vector<RefType, 0, SystemAllocPolicy>;
469
470 class StorageTypeTraits {
471 public:
472 enum Kind {
473 I8 = uint8_t(TypeCode::I8),
474 I16 = uint8_t(TypeCode::I16),
475 I32 = uint8_t(TypeCode::I32),
476 I64 = uint8_t(TypeCode::I64),
477 F32 = uint8_t(TypeCode::F32),
478 F64 = uint8_t(TypeCode::F64),
479 V128 = uint8_t(TypeCode::V128),
480 Ref = uint8_t(AbstractReferenceTypeCode),
481 };
482
483 static bool isValidTypeCode(TypeCode tc) {
484 switch (tc) {
485 case TypeCode::I8:
486 case TypeCode::I16:
487 case TypeCode::I32:
488 case TypeCode::I64:
489 case TypeCode::F32:
490 case TypeCode::F64:
491 #ifdef ENABLE_WASM_SIMD
492 case TypeCode::V128:
493 #endif
494 case TypeCode::FuncRef:
495 case TypeCode::ExternRef:
496 case TypeCode::ExnRef:
497 case TypeCode::NullExnRef:
498 case TypeCode::AnyRef:
499 case TypeCode::EqRef:
500 case TypeCode::I31Ref:
501 case TypeCode::StructRef:
502 case TypeCode::ArrayRef:
503 case TypeCode::NullFuncRef:
504 case TypeCode::NullExternRef:
505 case TypeCode::NullAnyRef:
506 case AbstractTypeRefCode:
507 return true;
508 default:
509 return false;
510 }
511 }
512
513 static bool isNumberTypeCode(TypeCode tc) {
514 switch (tc) {
515 case TypeCode::I32:
516 case TypeCode::I64:
517 case TypeCode::F32:
518 case TypeCode::F64:
519 return true;
520 default:
521 return false;
522 }
523 }
524
525 static bool isPackedTypeCode(TypeCode tc) {
526 switch (tc) {
527 case TypeCode::I8:
528 case TypeCode::I16:
529 return true;
530 default:
531 return false;
532 }
533 }
534
535 static bool isVectorTypeCode(TypeCode tc) {
536 switch (tc) {
537 #ifdef ENABLE_WASM_SIMD
538 case TypeCode::V128:
539 return true;
540 #endif
541 default:
542 return false;
543 }
544 }
545 };
546
547 class ValTypeTraits {
548 public:
549 enum Kind {
550 I32 = uint8_t(TypeCode::I32),
551 I64 = uint8_t(TypeCode::I64),
552 F32 = uint8_t(TypeCode::F32),
553 F64 = uint8_t(TypeCode::F64),
554 V128 = uint8_t(TypeCode::V128),
555 Ref = uint8_t(AbstractReferenceTypeCode),
556 };
557
558 static const char* KindEnumName(Kind kind) {
559 switch (kind) {
560 case Kind::I32:
561 return "I32";
562 case Kind::I64:
563 return "I64";
564 case Kind::F32:
565 return "F32";
566 case Kind::F64:
567 return "F64";
568 case Kind::V128:
569 return "V128";
570 case Kind::Ref:
571 return "Ref";
572 }
573 MOZ_CRASH("Unknown kind");
574 }
575
576 static constexpr bool isValidTypeCode(TypeCode tc) {
577 switch (tc) {
578 case TypeCode::I32:
579 case TypeCode::I64:
580 case TypeCode::F32:
581 case TypeCode::F64:
582 #ifdef ENABLE_WASM_SIMD
583 case TypeCode::V128:
584 #endif
585 case TypeCode::FuncRef:
586 case TypeCode::ExternRef:
587 case TypeCode::ExnRef:
588 case TypeCode::NullExnRef:
589 case TypeCode::AnyRef:
590 case TypeCode::EqRef:
591 case TypeCode::I31Ref:
592 case TypeCode::StructRef:
593 case TypeCode::ArrayRef:
594 case TypeCode::NullFuncRef:
595 case TypeCode::NullExternRef:
596 case TypeCode::NullAnyRef:
597 case AbstractTypeRefCode:
598 return true;
599 default:
600 return false;
601 }
602 }
603
604 static bool isNumberTypeCode(TypeCode tc) {
605 switch (tc) {
606 case TypeCode::I32:
607 case TypeCode::I64:
608 case TypeCode::F32:
609 case TypeCode::F64:
610 return true;
611 default:
612 return false;
613 }
614 }
615
616 static bool isPackedTypeCode(TypeCode tc) { return false; }
617
618 static bool isVectorTypeCode(TypeCode tc) {
619 switch (tc) {
620 #ifdef ENABLE_WASM_SIMD
621 case TypeCode::V128:
622 return true;
623 #endif
624 default:
625 return false;
626 }
627 }
628 };
629
630 // The PackedType represents the storage type of a WebAssembly location, whether
631 // parameter, local, field, or global. See specializations below for ValType and
632 // StorageType.
633
634 template <class T>
635 class PackedType : public T {
636 public:
637 using Kind = typename T::Kind;
638
639 protected:
640 PackedTypeCode tc_;
641
642 explicit PackedType(TypeCode c) : tc_(PackedTypeCode::pack(c)) {
643 MOZ_ASSERT(c != AbstractTypeRefCode);
644 MOZ_ASSERT(isValid());
645 }
646
647 TypeCode typeCode() const {
648 MOZ_ASSERT(isValid());
649 return tc_.typeCode();
650 }
651
652 public:
653 constexpr PackedType() : tc_(PackedTypeCode::invalid()) {}
654
655 MOZ_IMPLICIT constexpr PackedType(Kind c)
656 : tc_(PackedTypeCode::pack(TypeCode(c))) {
657 MOZ_ASSERT(c != Kind::Ref);
658 MOZ_ASSERT(isValid());
659 }
660
661 MOZ_IMPLICIT PackedType(RefType rt) : tc_(rt.packed()) {
662 MOZ_ASSERT(isValid());
663 }
664
665 explicit constexpr PackedType(PackedTypeCode ptc) : tc_(ptc) {
666 MOZ_ASSERT(isValid());
667 }
668
669 inline void AddRef() const;
670 inline void Release() const;
671
672 static constexpr PackedType i32() { return PackedType(PackedType::I32); }
673 static constexpr PackedType f32() { return PackedType(PackedType::F32); }
674 static constexpr PackedType i64() { return PackedType(PackedType::I64); }
675 static constexpr PackedType f64() { return PackedType(PackedType::F64); }
676
677 static PackedType fromMIRType(jit::MIRType mty) {
678 switch (mty) {
679 case jit::MIRType::Int32:
680 return PackedType::I32;
681 break;
682 case jit::MIRType::Int64:
683 return PackedType::I64;
684 break;
685 case jit::MIRType::Float32:
686 return PackedType::F32;
687 break;
688 case jit::MIRType::Double:
689 return PackedType::F64;
690 break;
691 case jit::MIRType::Simd128:
692 return PackedType::V128;
693 break;
694 case jit::MIRType::WasmAnyRef:
695 return PackedType::Ref;
696 default:
697 MOZ_CRASH("fromMIRType: unexpected type");
698 }
699 }
700
701 static PackedType fromNonRefTypeCode(TypeCode tc) {
702 #ifdef DEBUG
703 switch (tc) {
704 case TypeCode::I8:
705 case TypeCode::I16:
706 case TypeCode::I32:
707 case TypeCode::I64:
708 case TypeCode::F32:
709 case TypeCode::F64:
710 case TypeCode::V128:
711 break;
712 default:
713 MOZ_CRASH("Bad type code");
714 }
715 #endif
716 return PackedType(tc);
717 }
718
719 static PackedType fromBitsUnsafe(PackedTypeCode::PackedRepr bits) {
720 return PackedType(PackedTypeCode::fromBits(bits));
721 }
722
723 constexpr bool isValid() const {
724 if (!tc_.isValid()) {
725 return false;
726 }
727 return T::isValidTypeCode(tc_.typeCode());
728 }
729
730 IsoEqualsTypeCode forIsoEquals(const RecGroup* recGroup) const {
731 return IsoEqualsTypeCode::forIsoEquals(tc_, recGroup);
732 }
733
734 PackedTypeCode packed() const {
735 MOZ_ASSERT(isValid());
736 return tc_;
737 }
738 PackedTypeCode* addressOfPacked() { return &tc_; }
739 const PackedTypeCode* addressOfPacked() const { return &tc_; }
740
741 PackedTypeCode::PackedRepr bitsUnsafe() const {
742 MOZ_ASSERT(isValid());
743 return tc_.bits();
744 }
745
746 bool isNumber() const { return T::isNumberTypeCode(tc_.typeCode()); }
747
748 bool isPacked() const { return T::isPackedTypeCode(tc_.typeCode()); }
749
750 bool isVector() const { return T::isVectorTypeCode(tc_.typeCode()); }
751
752 bool isRefType() const { return tc_.isRefType(); }
753
754 bool isFuncRef() const { return tc_.typeCode() == TypeCode::FuncRef; }
755
756 bool isExternRef() const { return tc_.typeCode() == TypeCode::ExternRef; }
757
758 bool isExnRef() const { return tc_.typeCode() == TypeCode::ExnRef; }
759
760 bool isAnyRef() const { return tc_.typeCode() == TypeCode::AnyRef; }
761
762 bool isNoFunc() const { return tc_.typeCode() == TypeCode::NullFuncRef; }
763
764 bool isNoExtern() const { return tc_.typeCode() == TypeCode::NullExternRef; }
765
766 bool isNoExn() const { return tc_.typeCode() == TypeCode::NullExnRef; }
767
768 bool isNone() const { return tc_.typeCode() == TypeCode::NullAnyRef; }
769
770 bool isEqRef() const { return tc_.typeCode() == TypeCode::EqRef; }
771
772 bool isI31Ref() const { return tc_.typeCode() == TypeCode::I31Ref; }
773
774 bool isStructRef() const { return tc_.typeCode() == TypeCode::StructRef; }
775
776 bool isArrayRef() const { return tc_.typeCode() == TypeCode::ArrayRef; }
777
778 bool isTypeRef() const { return tc_.typeCode() == AbstractTypeRefCode; }
779
780 bool isRefRepr() const { return tc_.isRefRepr(); }
781
782 // Returns whether the type has a default value.
783 bool isDefaultable() const { return !(isRefType() && !isNullable()); }
784
785 // Returns whether the type has a representation in JS.
786 bool isExposable() const {
787 #if defined(ENABLE_WASM_SIMD)
788 return kind() != Kind::V128 && !isExnRef() && !isNoExn();
789 #else
790 return !isExnRef() && !isNoExn();
791 #endif
792 }
793
794 bool isNullable() const { return tc_.isNullable(); }
795
796 const TypeDef* typeDef() const { return tc_.typeDef(); }
797
798 Kind kind() const { return Kind(tc_.typeCodeAbstracted()); }
799
800 RefType refType() const {
801 MOZ_ASSERT(isRefType());
802 return RefType(tc_);
803 }
804
805 RefType::Kind refTypeKind() const {
806 MOZ_ASSERT(isRefType());
807 return RefType(tc_).kind();
808 }
809
810 // Some types are encoded as JS::Value when they escape from Wasm (when passed
811 // as parameters to imports or returned from exports). For ExternRef the
812 // Value encoding is pretty much a requirement. For other types it's a choice
813 // that may (temporarily) simplify some code.
814 bool isEncodedAsJSValueOnEscape() const { return isRefType(); }
815
816 uint32_t size() const {
817 switch (tc_.typeCodeAbstracted()) {
818 case TypeCode::I8:
819 return 1;
820 case TypeCode::I16:
821 return 2;
822 case TypeCode::I32:
823 return 4;
824 case TypeCode::I64:
825 return 8;
826 case TypeCode::F32:
827 return 4;
828 case TypeCode::F64:
829 return 8;
830 case TypeCode::V128:
831 return 16;
832 case AbstractReferenceTypeCode:
833 return sizeof(void*);
834 default:
835 MOZ_ASSERT_UNREACHABLE();
836 return 0;
837 }
838 }
839 uint32_t alignmentInStruct() const { return size(); }
840 uint32_t indexingShift() const {
841 switch (size()) {
842 case 1:
843 return 0;
844 case 2:
845 return 1;
846 case 4:
847 return 2;
848 case 8:
849 return 3;
850 case 16:
851 return 4;
852 default:
853 MOZ_ASSERT_UNREACHABLE();
854 return 0;
855 }
856 }
857
858 PackedType<ValTypeTraits> widenToValType() const {
859 switch (tc_.typeCodeAbstracted()) {
860 case TypeCode::I8:
861 case TypeCode::I16:
862 return PackedType<ValTypeTraits>::I32;
863 default:
864 return PackedType<ValTypeTraits>(tc_);
865 }
866 }
867
868 PackedType<ValTypeTraits> valType() const {
869 MOZ_ASSERT(isValType());
870 return PackedType<ValTypeTraits>(tc_);
871 }
872
873 // Note, ToMIRType is only correct within Wasm, where an AnyRef is represented
874 // as a pointer. At the JS/wasm boundary, an AnyRef can be represented as a
875 // JS::Value, and the type translation may have to be handled specially and on
876 // a case-by-case basis.
877 constexpr jit::MIRType toMIRType() const {
878 switch (tc_.typeCodeAbstracted()) {
879 case TypeCode::I32:
880 return jit::MIRType::Int32;
881 case TypeCode::I64:
882 return jit::MIRType::Int64;
883 case TypeCode::F32:
884 return jit::MIRType::Float32;
885 case TypeCode::F64:
886 return jit::MIRType::Double;
887 case TypeCode::V128:
888 return jit::MIRType::Simd128;
889 case AbstractReferenceTypeCode:
890 return jit::MIRType::WasmAnyRef;
891 default:
892 MOZ_CRASH("bad type");
893 }
894 }
895
896 MaybeRefType toMaybeRefType() const;
897
898 bool isValType() const {
899 switch (tc_.typeCode()) {
900 case TypeCode::I8:
901 case TypeCode::I16:
902 return false;
903 default:
904 return true;
905 }
906 }
907
908 PackedType<StorageTypeTraits> storageType() const {
909 MOZ_ASSERT(isValid());
910 return PackedType<StorageTypeTraits>(tc_);
911 }
912
913 static bool isSubTypeOf(PackedType subType, PackedType superType) {
914 // Anything is a subtype of itself.
915 if (subType == superType) {
916 return true;
917 }
918
919 // A reference may be a subtype of another reference
920 if (subType.isRefType() && superType.isRefType()) {
921 return RefType::isSubTypeOf(subType.refType(), superType.refType());
922 }
923
924 return false;
925 }
926
927 bool operator==(const PackedType& that) const {
928 MOZ_ASSERT(isValid() && that.isValid());
929 return tc_ == that.tc_;
930 }
931
932 bool operator!=(const PackedType& that) const {
933 MOZ_ASSERT(isValid() && that.isValid());
934 return tc_ != that.tc_;
935 }
936
937 bool operator==(Kind that) const {
938 MOZ_ASSERT(isValid());
939 MOZ_ASSERT(that != Kind::Ref);
940 return Kind(typeCode()) == that;
941 }
942
943 bool operator!=(Kind that) const { return !(*this == that); }
944 };
945
946 using StorageType = PackedType<StorageTypeTraits>;
947
948 // The dominant use of this data type is for locals and args, and profiling
949 // with ZenGarden and Tanks suggests an initial size of 16 minimises heap
950 // allocation, both in terms of blocks and bytes.
951 using ValTypeVector = Vector<ValType, 16, SystemAllocPolicy>;
952
953 // A MaybeRefType behaves like a mozilla::Maybe<RefType>, but saves space by
954 // reusing PackedTypeCode. If the inner RefType is not valid, it will be
955 // considered Nothing; otherwise it will be considered Some.
956 class MaybeRefType {
957 private:
958 RefType inner_;
959
960 public:
961 // Creates a MaybeRefType that isNothing().
962 MaybeRefType() { MOZ_ASSERT(isNothing()); }
963
964 // Creates a MaybeRefType that isSome().
965 explicit MaybeRefType(RefType type) : inner_(type) {
966 MOZ_RELEASE_ASSERT(isSome());
967 }
968
969 bool isSome() const { return inner_.isValid(); }
970 bool isNothing() const { return !isSome(); }
971
972 /* Returns the inner RefType by value. Unsafe unless |isSome()|. */
973 RefType& value() & {
974 MOZ_RELEASE_ASSERT(isSome());
975 return inner_;
976 };
977 const RefType& value() const& {
978 MOZ_RELEASE_ASSERT(isSome());
979 return inner_;
980 };
981
982 RefType& valueOr(RefType& aDefault) {
983 if (isSome()) {
984 return value();
985 }
986 return aDefault;
987 }
988 const RefType& valueOr(const RefType& aDefault) {
989 if (isSome()) {
990 return value();
991 }
992 return aDefault;
993 }
994
995 bool operator==(const MaybeRefType& other) { return inner_ == other.inner_; }
996 bool operator!=(const MaybeRefType& other) { return inner_ != other.inner_; }
997
998 explicit operator bool() const { return isSome(); }
999
1000 mozilla::Maybe<wasm::RefTypeHierarchy> hierarchy() const {
1001 if (isSome()) {
1002 return mozilla::Some(value().hierarchy());
1003 }
1004 return mozilla::Nothing();
1005 }
1006
1007 static MaybeRefType leastUpperBound(MaybeRefType a, MaybeRefType b) {
1008 if (a.isSome() && b.isSome()) {
1009 return MaybeRefType(RefType::leastUpperBound(a.value(), b.value()));
1010 }
1011 return MaybeRefType();
1012 }
1013 };
1014
1015 template <class T>
1016 MaybeRefType PackedType<T>::toMaybeRefType() const {
1017 if (!isRefType()) {
1018 return MaybeRefType();
1019 }
1020 return MaybeRefType(refType());
1021 };
1022
1023 // ValType utilities
1024
1025 extern bool ToValType(JSContext* cx, HandleValue v, ValType* out);
1026 extern bool ToRefType(JSContext* cx, HandleValue v, RefType* out);
1027
1028 extern UniqueChars ToString(RefType type, const TypeContext* types);
1029 extern UniqueChars ToString(ValType type, const TypeContext* types);
1030 extern UniqueChars ToString(StorageType type, const TypeContext* types);
1031 extern UniqueChars ToString(const mozilla::Maybe<ValType>& type,
1032 const TypeContext* types);
1033 extern UniqueChars ToString(const MaybeRefType& type, const TypeContext* types);
1034
1035 } // namespace wasm
1036 } // namespace js
1037
1038 #endif // wasm_valtype_h