Debian Codegraph @

js/src/wasm/WasmTypeDef.cpp

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 2015 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 #include "wasm/WasmTypeDef.h"
20
21 #include "mozilla/MathAlgorithms.h"
22
23 #include "jit/JitOptions.h"
24 #include "js/friend/ErrorMessages.h" // JSMSG_*
25 #include "js/HashTable.h"
26 #include "js/Printf.h"
27 #include "js/Value.h"
28 #include "threading/ExclusiveData.h"
29 #include "vm/Runtime.h"
30 #include "vm/StringType.h"
31 #include "wasm/WasmCodegenConstants.h"
32 #include "wasm/WasmGcObject.h"
33 #include "wasm/WasmJS.h"
34
35 using namespace js;
36 using namespace js::jit;
37 using namespace js::wasm;
38
39 using mozilla::CheckedInt32;
40 using mozilla::CheckedUint32;
41 using mozilla::IsPowerOfTwo;
42 using mozilla::MallocSizeOf;
43
44 // [SMDOC] Immediate type signature encoding
45 //
46 // call_indirect requires a signature check to ensure the dynamic callee type
47 // matches the static specified callee type. This involves comparing whether
48 // the two function types are equal. We canonicalize function types so that
49 // comparing the pointers of the types will indicate if they're equal. The
50 // canonicalized function types are loaded from the instance at runtime.
51 //
52 // For the common case of simple/small function types, we can avoid the cost
53 // of loading the function type pointers from the instance by having an
54 // alternate 'immediate' form that encodes a function type in a constant.
55 // We encode the function types such that bitwise equality implies the original
56 // function types were equal. We use a tag bit such that if one of the types
57 // is a pointer and the other an immediate, they will not compare as equal.
58 //
59 // The encoding is optimized for common function types that have at most one
60 // result and an arbitrary amount of arguments.
61 //
62 // [
63 // 1 bit : tag (always 1),
64 // 1 bit : numResults,
65 // 3 bits : numArgs,
66 // numResults * 3 bits : results,
67 // numArgs * 3 bits : args
68 // ]
69 // (lsb -> msb order)
70 //
71 // Any function type that cannot be encoded in the above format is falls back
72 // to the pointer representation.
73 //
74
75 //=========================================================================
76 // ImmediateType
77
78 // ImmediateType is 32-bits to ensure it's easy to materialize the constant
79 // on all platforms.
80 using ImmediateType = uint32_t;
81 static const unsigned sTotalBits = sizeof(ImmediateType) * 8;
82 static const unsigned sTagBits = 1;
83 static const unsigned sNumResultsBits = 1;
84 static const unsigned sNumArgsBits = 3;
85 static const unsigned sValTypeBits = 3;
86 static const unsigned sMaxValTypes = 8;
87
88 static_assert(((1 << sNumResultsBits) - 1) + ((1 << sNumArgsBits) - 1) ==
89 sMaxValTypes,
90 "sNumResultsBits, sNumArgsBits, sMaxValTypes are consistent");
91
92 static_assert(sTagBits + sNumResultsBits + sNumArgsBits +
93 sValTypeBits * sMaxValTypes <=
94 sTotalBits,
95 "have room");
96
97 static bool IsImmediateValType(ValType vt) {
98 switch (vt.kind()) {
99 case ValType::I32:
100 case ValType::I64:
101 case ValType::F32:
102 case ValType::F64:
103 case ValType::V128:
104 return true;
105 case ValType::Ref:
106 // We don't have space to encode nullability, so we optimize for
107 // non-nullable types.
108 if (!vt.isNullable()) {
109 return false;
110 }
111 switch (vt.refType().kind()) {
112 case RefType::Func:
113 case RefType::Extern:
114 case RefType::Any:
115 return true;
116 default:
117 return false;
118 }
119 default:
120 return false;
121 }
122 }
123
124 static unsigned EncodeImmediateValType(ValType vt) {
125 // We have run out of bits for each type, anything new must increase the
126 // sValTypeBits.
127 static_assert(7 < (1 << sValTypeBits), "enough space for ValType kind");
128
129 switch (vt.kind()) {
130 case ValType::I32:
131 return 0;
132 case ValType::I64:
133 return 1;
134 case ValType::F32:
135 return 2;
136 case ValType::F64:
137 return 3;
138 case ValType::V128:
139 return 4;
140 case ValType::Ref:
141 MOZ_ASSERT(vt.isNullable());
142 switch (vt.refType().kind()) {
143 case RefType::Func:
144 return 5;
145 case RefType::Extern:
146 return 6;
147 case RefType::Any:
148 return 7;
149 default:
150 MOZ_CRASH("bad RefType");
151 }
152 default:
153 MOZ_CRASH("bad ValType");
154 }
155 }
156
157 static bool IsImmediateFuncType(const FuncType& funcType) {
158 const ValTypeVector& results = funcType.results();
159 const ValTypeVector& args = funcType.args();
160
161 // Check the number of results and args fits
162 if (results.length() > ((1 << sNumResultsBits) - 1) ||
163 args.length() > ((1 << sNumArgsBits) - 1)) {
164 return false;
165 }
166
167 // Ensure every result is compatible
168 for (ValType v : results) {
169 if (!IsImmediateValType(v)) {
170 return false;
171 }
172 }
173
174 // Ensure every arg is compatible
175 for (ValType v : args) {
176 if (!IsImmediateValType(v)) {
177 return false;
178 }
179 }
180
181 return true;
182 }
183
184 static ImmediateType EncodeNumResults(uint32_t numResults) {
185 MOZ_ASSERT(numResults <= (1 << sNumResultsBits) - 1);
186 return numResults;
187 }
188
189 static ImmediateType EncodeNumArgs(uint32_t numArgs) {
190 MOZ_ASSERT(numArgs <= (1 << sNumArgsBits) - 1);
191 return numArgs;
192 }
193
194 static ImmediateType EncodeImmediateFuncType(const FuncType& funcType) {
195 ImmediateType immediate = FuncType::ImmediateBit;
196 uint32_t shift = sTagBits;
197
198 // Encode the results
199 immediate |= EncodeNumResults(funcType.results().length()) << shift;
200 shift += sNumResultsBits;
201
202 for (ValType resultType : funcType.results()) {
203 immediate |= EncodeImmediateValType(resultType) << shift;
204 shift += sValTypeBits;
205 }
206
207 // Encode the args
208 immediate |= EncodeNumArgs(funcType.args().length()) << shift;
209 shift += sNumArgsBits;
210
211 for (ValType argType : funcType.args()) {
212 immediate |= EncodeImmediateValType(argType) << shift;
213 shift += sValTypeBits;
214 }
215
216 MOZ_ASSERT(shift <= sTotalBits);
217 return immediate;
218 }
219
220 //=========================================================================
221 // FuncType
222
223 void FuncType::initImmediateTypeId(bool isFinal, const TypeDef* superTypeDef,
224 uint32_t recGroupLength) {
225 // To improve the performance of the structural type check in
226 // the call_indirect function prologue, we attempt to encode the
227 // entire function type into an immediate such that bitwise equality
228 // implies structural equality. With the GC proposal, we don't
229 // want to generalize the immediate form for the new type system, so
230 // we don't use it when a type is non-final (i.e. may have sub types), or
231 // has super types, or is in a recursion group with other types.
232 //
233 // If non-final types are allowed, then the type can have subtypes, and we
234 // should therefore do a full subtype check on call_indirect, which
235 // doesn't work well with immediates. If the type has a super type, the
236 // same reason applies. And finally, types in recursion groups of
237 // size > 1 may not be considered equivalent even if they are
238 // structurally equivalent in every respect.
239 if (!isFinal || superTypeDef || recGroupLength != 1) {
240 immediateTypeId_ = NO_IMMEDIATE_TYPE_ID;
241 return;
242 }
243
244 // Otherwise, try to encode this function type into an immediate.
245 if (!IsImmediateFuncType(*this)) {
246 immediateTypeId_ = NO_IMMEDIATE_TYPE_ID;
247 return;
248 }
249 immediateTypeId_ = EncodeImmediateFuncType(*this);
250 }
251
252 bool FuncType::canHaveJitEntry() const {
253 return !hasUnexposableArgOrRet() &&
254 !temporarilyUnsupportedReftypeForEntry() &&
255 !temporarilyUnsupportedResultCountForJitEntry() &&
256 JitOptions.enableWasmJitEntry;
257 }
258
259 bool FuncType::canHaveJitExit() const {
260 return !hasUnexposableArgOrRet() && !temporarilyUnsupportedReftypeForExit() &&
261 !hasInt64Arg() && !temporarilyUnsupportedResultCountForJitExit() &&
262 JitOptions.enableWasmJitExit;
263 }
264
265 size_t FuncType::sizeOfExcludingThis(MallocSizeOf mallocSizeOf) const {
266 return args_.sizeOfExcludingThis(mallocSizeOf);
267 }
268
269 //=========================================================================
270 // StructType and StructLayout
271
272 static inline CheckedInt32 RoundUpToAlignment(CheckedInt32 address,
273 uint32_t align) {
274 MOZ_ASSERT(IsPowerOfTwo(align));
275
276 // Note: Be careful to order operators such that we first make the
277 // value smaller and then larger, so that we don't get false
278 // overflow errors due to (e.g.) adding `align` and then
279 // subtracting `1` afterwards when merely adding `align-1` would
280 // not have overflowed. Note that due to the nature of two's
281 // complement representation, if `address` is already aligned,
282 // then adding `align-1` cannot itself cause an overflow.
283
284 return ((address + (align - 1)) / align) * align;
285 }
286
287 CheckedInt32 StructLayout::addField(StorageType type) {
288 uint32_t fieldSize = type.size();
289 uint32_t fieldAlignment = type.alignmentInStruct();
290
291 // We have to ensure that `offset` is chosen so that no field crosses the
292 // inline/outline boundary. The assertions here ensure that. See comment
293 // on `class StructLayout` for background.
294 MOZ_ASSERT(fieldSize >= 1 && fieldSize <= 16);
295 MOZ_ASSERT((fieldSize & (fieldSize - 1)) == 0); // is a power of 2
296 MOZ_ASSERT(fieldAlignment == fieldSize); // is naturally aligned
297
298 // Alignment of the struct is the max of the alignment of its fields.
299 structAlignment = std::max(structAlignment, fieldAlignment);
300
301 // Align the pointer.
302 CheckedInt32 offset = RoundUpToAlignment(sizeSoFar, fieldAlignment);
303 if (!offset.isValid()) {
304 return offset;
305 }
306
307 // Allocate space.
308 sizeSoFar = offset + fieldSize;
309 if (!sizeSoFar.isValid()) {
310 return sizeSoFar;
311 }
312
313 // The following should hold if the three assertions above hold.
314 MOZ_ASSERT(offset / 16 == (offset + fieldSize - 1) / 16);
315 return offset;
316 }
317
318 CheckedInt32 StructLayout::close() {
319 CheckedInt32 size = RoundUpToAlignment(sizeSoFar, structAlignment);
320 // What we are computing into `size` is the size of
321 // WasmGcObject::inlineData_, or the size of the outline data area. Either
322 // way, it is helpful if the area size is an integral number of machine
323 // words, since this would make any initialisation loop for inline
324 // allocation able to operate on machine word sized units, should we decide
325 // to do inline allocation.
326 if (structAlignment < sizeof(uintptr_t)) {
327 size = RoundUpToAlignment(size, sizeof(uintptr_t));
328 }
329 return size;
330 }
331
332 bool StructType::init() {
333 bool isDefaultable = true;
334
335 StructLayout layout;
336 for (FieldType& field : fields_) {
337 CheckedInt32 offset = layout.addField(field.type);
338 if (!offset.isValid()) {
339 return false;
340 }
341
342 // Add the offset to the list
343 if (!fieldOffsets_.append(offset.value())) {
344 return false;
345 }
346
347 // If any field is not defaultable, this whole struct is not defaultable
348 if (!field.type.isDefaultable()) {
349 isDefaultable = false;
350 }
351
352 // If this field is not a ref, then don't add it to the trace lists
353 if (!field.type.isRefRepr()) {
354 continue;
355 }
356
357 bool isOutline;
358 uint32_t adjustedOffset;
359 WasmStructObject::fieldOffsetToAreaAndOffset(field.type, offset.value(),
360 &isOutline, &adjustedOffset);
361 if (isOutline) {
362 if (!outlineTraceOffsets_.append(adjustedOffset)) {
363 return false;
364 }
365 } else {
366 if (!inlineTraceOffsets_.append(adjustedOffset)) {
367 return false;
368 }
369 }
370 }
371
372 CheckedInt32 size = layout.close();
373 if (!size.isValid()) {
374 return false;
375 }
376
377 size_ = size.value();
378 isDefaultable_ = isDefaultable;
379 return true;
380 }
381
382 /* static */
383 bool StructType::createImmutable(const ValTypeVector& types,
384 StructType* struct_) {
385 FieldTypeVector fields;
386 if (!fields.resize(types.length())) {
387 return false;
388 }
389 for (size_t i = 0; i < types.length(); i++) {
390 fields[i].type = StorageType(types[i].packed());
391 fields[i].isMutable = false;
392 }
393 *struct_ = StructType(std::move(fields));
394 return struct_->init();
395 }
396
397 size_t StructType::sizeOfExcludingThis(MallocSizeOf mallocSizeOf) const {
398 return fields_.sizeOfExcludingThis(mallocSizeOf);
399 }
400
401 size_t ArrayType::sizeOfExcludingThis(MallocSizeOf mallocSizeOf) const {
402 return 0;
403 }
404
405 size_t TypeDef::sizeOfExcludingThis(MallocSizeOf mallocSizeOf) const {
406 switch (kind_) {
407 case TypeDefKind::Struct: {
408 return structType_.sizeOfExcludingThis(mallocSizeOf);
409 }
410 case TypeDefKind::Func: {
411 return funcType_.sizeOfExcludingThis(mallocSizeOf);
412 }
413 case TypeDefKind::Array: {
414 return arrayType_.sizeOfExcludingThis(mallocSizeOf);
415 }
416 case TypeDefKind::None: {
417 return 0;
418 }
419 default:
420 break;
421 }
422 MOZ_ASSERT_UNREACHABLE();
423 return 0;
424 }
425
426 //=========================================================================
427 // SuperTypeVector
428
429 /* static */
430 size_t SuperTypeVector::offsetOfSTVInVector(uint32_t subTypingDepth) {
431 return offsetof(SuperTypeVector, types_) + sizeof(void*) * subTypingDepth;
432 }
433
434 /* static */
435 size_t SuperTypeVector::lengthForTypeDef(const TypeDef& typeDef) {
436 return std::max(uint32_t(typeDef.subTypingDepth()) + 1,
437 MinSuperTypeVectorLength);
438 }
439
440 /* static */
441 size_t SuperTypeVector::byteSizeForTypeDef(const TypeDef& typeDef) {
442 static_assert(
443 sizeof(SuperTypeVector) + sizeof(void*) * (MaxSubTypingDepth + 1) <=
444 UINT16_MAX,
445 "cannot overflow");
446 return sizeof(SuperTypeVector) + (sizeof(void*) * lengthForTypeDef(typeDef));
447 }
448
449 /* static */
450 const SuperTypeVector* SuperTypeVector::createMultipleForRecGroup(
451 RecGroup* recGroup) {
452 // Pre-size the amount of space needed for all the super type vectors in this
453 // recursion group.
454 CheckedUint32 totalBytes = 0;
455 for (uint32_t typeIndex = 0; typeIndex < recGroup->numTypes(); typeIndex++) {
456 totalBytes +=
457 SuperTypeVector::byteSizeForTypeDef(recGroup->type(typeIndex));
458 }
459 if (!totalBytes.isValid()) {
460 return nullptr;
461 }
462
463 // Allocate the batch, and retain reference to the first one.
464 SuperTypeVector* firstVector =
465 (SuperTypeVector*)js_malloc(totalBytes.value());
466 if (!firstVector) {
467 return nullptr;
468 }
469
470 // Initialize the vectors, one by one
471 SuperTypeVector* currentVector = firstVector;
472 for (uint32_t typeIndex = 0; typeIndex < recGroup->numTypes(); typeIndex++) {
473 TypeDef& typeDef = recGroup->type(typeIndex);
474
475 // Compute the size again to know where the next vector can be found.
476 size_t vectorByteSize = SuperTypeVector::byteSizeForTypeDef(typeDef);
477
478 // Make the typedef and the vector point at each other.
479 typeDef.setSuperTypeVector(currentVector);
480 currentVector->typeDef_ = &typeDef;
481 currentVector->subTypingDepth_ = typeDef.subTypingDepth();
482
483 // Every vector stores all ancestor types and itself.
484 currentVector->length_ = SuperTypeVector::lengthForTypeDef(typeDef);
485
486 // Initialize the entries in the vector
487 const TypeDef* currentTypeDef = &typeDef;
488 for (uint32_t index = 0; index < currentVector->length(); index++) {
489 uint32_t reverseIndex = currentVector->length() - index - 1;
490
491 // If this entry is required just to hit the minimum size, then
492 // initialize it to null.
493 if (reverseIndex > typeDef.subTypingDepth()) {
494 currentVector->types_[reverseIndex] = nullptr;
495 continue;
496 }
497
498 // Otherwise we should always be iterating at the same depth as our
499 // currentTypeDef.
500 MOZ_ASSERT(reverseIndex == currentTypeDef->subTypingDepth());
501
502 currentVector->types_[reverseIndex] = currentTypeDef->superTypeVector();
503 currentTypeDef = currentTypeDef->superTypeDef();
504 }
505
506 // There should be no more super types left over
507 MOZ_ASSERT(currentTypeDef == nullptr);
508
509 // Advance to the next super type vector
510 currentVector =
511 (SuperTypeVector*)(((const char*)currentVector) + vectorByteSize);
512 }
513
514 return firstVector;
515 }
516
517 //=========================================================================
518 // TypeIdSet and TypeContext
519
520 struct RecGroupHashPolicy {
521 using Lookup = const SharedRecGroup&;
522
523 static HashNumber hash(Lookup lookup) { return lookup->hash(); }
524
525 static bool match(const SharedRecGroup& lhs, Lookup rhs) {
526 return RecGroup::isoEquals(*rhs, *lhs);
527 }
528 };
529
530 // A global hash set of recursion groups for use in fast type equality checks.
531 class TypeIdSet {
532 using Set = HashSet<SharedRecGroup, RecGroupHashPolicy, SystemAllocPolicy>;
533 Set set_;
534
535 public:
536 // Attempt to insert a recursion group into the set, returning an existing
537 // recursion group if there was one.
538 SharedRecGroup insert(SharedRecGroup recGroup) {
539 Set::AddPtr p = set_.lookupForAdd(recGroup);
540 if (p) {
541 // A canonical recursion group already existed, return it.
542 return *p;
543 }
544
545 // Insert this recursion group into the set, and return it as the canonical
546 // recursion group instance.
547 if (!set_.add(p, recGroup)) {
548 return nullptr;
549 }
550 return recGroup;
551 }
552
553 void purge() {
554 // TODO: this is not guaranteed to remove all types that are not referenced
555 // from outside the canonical set, as removing a type may make a previous
556 // type we've visited now only have one ref and be eligible to be freed.
557 //
558 // Solving this either involves iterating to a fixed point, or else a much
559 // more invasive change to the lifetime management of recursion groups.
560 for (auto iter = set_.modIter(); !iter.done(); iter.next()) {
561 if (iter.get()->hasOneRef()) {
562 iter.remove();
563 }
564 }
565 }
566
567 // Release the provided recursion group reference and remove it from the
568 // canonical set if it was the last reference. This is one unified method
569 // because we need to perform the lookup before releasing the reference, but
570 // need to release the reference in order to see if it was the last reference
571 // outside the canonical set.
572 void clearRecGroup(SharedRecGroup* recGroupCell) {
573 if (Set::Ptr p = set_.lookup(*recGroupCell)) {
574 *recGroupCell = nullptr;
575 if ((*p)->hasOneRef()) {
576 set_.remove(p);
577 }
578 } else {
579 *recGroupCell = nullptr;
580 }
581 }
582 };
583
584 MOZ_RUNINIT ExclusiveData<TypeIdSet> typeIdSet(mutexid::WasmTypeIdSet);
585
586 void wasm::PurgeCanonicalTypes() {
587 ExclusiveData<TypeIdSet>::Guard locked = typeIdSet.lock();
588 locked->purge();
589 }
590
591 SharedRecGroup TypeContext::canonicalizeGroup(SharedRecGroup recGroup) {
592 ExclusiveData<TypeIdSet>::Guard locked = typeIdSet.lock();
593 return locked->insert(recGroup);
594 }
595
596 TypeContext::~TypeContext() {
597 ExclusiveData<TypeIdSet>::Guard locked = typeIdSet.lock();
598
599 // Clear out the recursion groups in this module, freeing them from the
600 // canonical type set if needed.
601 //
602 // We iterate backwards here so that we free every previous recursion group
603 // that may be referring to the current recursion group we're freeing. This
604 // is possible due to recursion groups being ordered.
605 for (int32_t groupIndex = recGroups_.length() - 1; groupIndex >= 0;
606 groupIndex--) {
607 // Try to remove this entry from the canonical set if we have the last
608 // strong reference. The entry may not exist if canonicalization failed
609 // and this type context was aborted. This will clear the reference in the
610 // vector.
611 locked->clearRecGroup(&recGroups_[groupIndex]);
612 }
613 }