Debian Codegraph @

js/src/wasm/WasmCodegenTypes.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_codegen_types_h
20 #define wasm_codegen_types_h
21
22 #include "mozilla/CheckedInt.h"
23 #include "mozilla/EnumeratedArray.h"
24 #include "mozilla/PodOperations.h"
25 #include "mozilla/Span.h"
26
27 #include <stdint.h>
28
29 #include "jit/IonTypes.h"
30 #include "jit/PerfSpewer.h"
31 #include "threading/ExclusiveData.h"
32 #include "wasm/WasmBuiltins.h"
33 #include "wasm/WasmCodegenConstants.h"
34 #include "wasm/WasmConstants.h"
35 #include "wasm/WasmInstanceData.h"
36 #include "wasm/WasmSerialize.h"
37 #include "wasm/WasmShareable.h"
38 #include "wasm/WasmTypeDef.h"
39 #include "wasm/WasmUtility.h"
40
41 namespace js {
42
43 namespace jit {
44 template <class VecT, class ABIArgGeneratorT>
45 class ABIArgIterBase;
46 } // namespace jit
47
48 namespace wasm {
49
50 struct CodeMetadata;
51 struct TableDesc;
52 struct V128;
53
54 // ArgTypeVector type.
55 //
56 // Functions usually receive one ABI argument per WebAssembly argument. However
57 // if a function has multiple results and some of those results go to the stack,
58 // then it additionally receives a synthetic ABI argument holding a pointer to
59 // the stack result area.
60 //
61 // Given the presence of synthetic arguments, sometimes we need a name for
62 // non-synthetic arguments. We call those "natural" arguments.
63
64 enum class StackResults { HasStackResults, NoStackResults };
65
66 class ArgTypeVector {
67 const ValTypeVector& args_;
68 bool hasStackResults_;
69
70 // To allow ABIArgIterBase<VecT, ABIArgGeneratorT>, we define a private
71 // length() method. To prevent accidental errors, other users need to be
72 // explicit and call lengthWithStackResults() or
73 // lengthWithoutStackResults().
74 size_t length() const { return args_.length() + size_t(hasStackResults_); }
75 template <class VecT, class ABIArgGeneratorT>
76 friend class jit::ABIArgIterBase;
77
78 public:
79 ArgTypeVector(const ValTypeVector& args, StackResults stackResults)
80 : args_(args),
81 hasStackResults_(stackResults == StackResults::HasStackResults) {}
82 explicit ArgTypeVector(const FuncType& funcType);
83
84 bool hasSyntheticStackResultPointerArg() const { return hasStackResults_; }
85 StackResults stackResults() const {
86 return hasSyntheticStackResultPointerArg() ? StackResults::HasStackResults
87 : StackResults::NoStackResults;
88 }
89 size_t lengthWithoutStackResults() const { return args_.length(); }
90 bool isSyntheticStackResultPointerArg(size_t idx) const {
91 // The pointer to stack results area, if present, is a synthetic argument
92 // tacked on at the end.
93 MOZ_ASSERT(idx < lengthWithStackResults());
94 return idx == args_.length();
95 }
96 bool isNaturalArg(size_t idx) const {
97 return !isSyntheticStackResultPointerArg(idx);
98 }
99 size_t naturalIndex(size_t idx) const {
100 MOZ_ASSERT(isNaturalArg(idx));
101 // Because the synthetic argument, if present, is tacked on the end, an
102 // argument index that isn't synthetic is natural.
103 return idx;
104 }
105
106 size_t lengthWithStackResults() const { return length(); }
107 jit::MIRType operator[](size_t i) const {
108 MOZ_ASSERT(i < lengthWithStackResults());
109 if (isSyntheticStackResultPointerArg(i)) {
110 return jit::MIRType::StackResults;
111 }
112 return args_[naturalIndex(i)].toMIRType();
113 }
114 };
115
116 // A wrapper around the bytecode offset of a wasm instruction within a whole
117 // module, used for trap offsets or call offsets. These offsets should refer to
118 // the first byte of the instruction that triggered the trap / did the call and
119 // should ultimately derive from OpIter::bytecodeOffset.
120
121 class BytecodeOffset {
122 static const uint32_t INVALID = UINT32_MAX;
123 static_assert(INVALID > wasm::MaxModuleBytes);
124 uint32_t offset_;
125
126 WASM_CHECK_CACHEABLE_POD(offset_);
127
128 public:
129 BytecodeOffset() : offset_(INVALID) {}
130 explicit BytecodeOffset(uint32_t offset) : offset_(offset) {}
131
132 bool isValid() const { return offset_ != INVALID; }
133 uint32_t offset() const {
134 MOZ_ASSERT(isValid());
135 return offset_;
136 }
137 };
138
139 WASM_DECLARE_CACHEABLE_POD(BytecodeOffset);
140 using BytecodeOffsetVector =
141 mozilla::Vector<BytecodeOffset, 4, SystemAllocPolicy>;
142 using BytecodeOffsetSpan = mozilla::Span<const BytecodeOffset>;
143 using ShareableBytecodeOffsetVector =
144 ShareableVector<BytecodeOffset, 4, SystemAllocPolicy>;
145 using SharedBytecodeOffsetVector = RefPtr<const ShareableBytecodeOffsetVector>;
146 using MutableBytecodeOffsetVector = RefPtr<ShareableBytecodeOffsetVector>;
147
148 // A TrapMachineInsn describes roughly what kind of machine instruction has
149 // caused a trap. This is used only for validation of trap placement in debug
150 // builds, in ModuleGenerator::finishMetadataTier, and is not necessary for
151 // execution of wasm code.
152 enum class TrapMachineInsn {
153 // The "official" undefined insn for the target, or something equivalent
154 // that we use for that purpose. The key property is that it always raises
155 // SIGILL when executed. For example, UD2 on Intel.
156 OfficialUD,
157 // Loads and stores that move 8, 16, 32, 64 or 128 bits of data, regardless
158 // of their type and how they are subsequently used (widened or duplicated).
159 Load8,
160 Load16,
161 Load32,
162 Load64,
163 Load128,
164 Store8,
165 Store16,
166 Store32,
167 Store64,
168 Store128,
169 // Any kind of atomic r-m-w or CAS memory transaction, but not including
170 // Load-Linked or Store-Checked style insns -- those count as plain LoadX
171 // and StoreX.
172 Atomic
173 };
174 using TrapMachineInsnVector =
175 mozilla::Vector<TrapMachineInsn, 0, SystemAllocPolicy>;
176
177 static inline TrapMachineInsn TrapMachineInsnForLoad(int byteSize) {
178 switch (byteSize) {
179 case 1:
180 return TrapMachineInsn::Load8;
181 case 2:
182 return TrapMachineInsn::Load16;
183 case 4:
184 return TrapMachineInsn::Load32;
185 case 8:
186 return TrapMachineInsn::Load64;
187 case 16:
188 return TrapMachineInsn::Load128;
189 default:
190 MOZ_CRASH("TrapMachineInsnForLoad");
191 }
192 }
193 static inline TrapMachineInsn TrapMachineInsnForLoadWord() {
194 return TrapMachineInsnForLoad(sizeof(void*));
195 }
196
197 static inline TrapMachineInsn TrapMachineInsnForStore(int byteSize) {
198 switch (byteSize) {
199 case 1:
200 return TrapMachineInsn::Store8;
201 case 2:
202 return TrapMachineInsn::Store16;
203 case 4:
204 return TrapMachineInsn::Store32;
205 case 8:
206 return TrapMachineInsn::Store64;
207 case 16:
208 return TrapMachineInsn::Store128;
209 default:
210 MOZ_CRASH("TrapMachineInsnForStore");
211 }
212 }
213 static inline TrapMachineInsn TrapMachineInsnForStoreWord() {
214 return TrapMachineInsnForStore(sizeof(void*));
215 }
216 #ifdef DEBUG
217 const char* ToString(Trap trap);
218 const char* ToString(TrapMachineInsn tmi);
219 #endif
220
221 // This holds an assembler buffer offset, which indicates the offset of a
222 // faulting instruction, and is used for the construction of TrapSites below.
223 // It is wrapped up as a new type only to avoid getting it confused with any
224 // other uint32_t or with CodeOffset.
225
226 class FaultingCodeOffset {
227 static constexpr uint32_t INVALID = UINT32_MAX;
228 uint32_t offset_;
229
230 public:
231 FaultingCodeOffset() : offset_(INVALID) {}
232 explicit FaultingCodeOffset(uint32_t offset) : offset_(offset) {
233 MOZ_ASSERT(offset != INVALID);
234 }
235 bool isValid() const { return offset_ != INVALID; }
236 uint32_t get() const {
237 MOZ_ASSERT(isValid());
238 return offset_;
239 }
240 };
241 static_assert(sizeof(FaultingCodeOffset) == 4);
242
243 // And this holds two such offsets. Needed for 64-bit integer transactions on
244 // 32-bit targets.
245 using FaultingCodeOffsetPair =
246 std::pair<FaultingCodeOffset, FaultingCodeOffset>;
247 static_assert(sizeof(FaultingCodeOffsetPair) == 8);
248
249 // The bytecode offsets of all the callers of a function that has been inlined.
250 // See CallSiteDesc/TrapSiteDesc for uses of this.
251 using InlinedCallerOffsets = BytecodeOffsetVector;
252
253 // An index into InliningContext to get an InlinedCallerOffsets. This may be
254 // 'None' to indicate an empty InlinedCallerOffsets.
255 struct InlinedCallerOffsetIndex {
256 private:
257 // Sentinel value for an empty InlinedCallerOffsets.
258 static constexpr uint32_t NONE = UINT32_MAX;
259
260 uint32_t value_;
261
262 public:
263 // The maximum value allowed here, checked by assertions. InliningContext
264 // will OOM if this value is exceeded.
265 static constexpr uint32_t MAX = UINT32_MAX - 1;
266
267 // Construct 'none'.
268 InlinedCallerOffsetIndex() : value_(NONE) {}
269
270 // Construct a non-'none' value. The value must be less than or equal to MAX.
271 explicit InlinedCallerOffsetIndex(uint32_t index) : value_(index) {
272 MOZ_RELEASE_ASSERT(index <= MAX);
273 }
274
275 // The value of this index, if it is not nothing.
276 uint32_t value() const {
277 MOZ_RELEASE_ASSERT(!isNone());
278 return value_;
279 }
280
281 // Whether this value is none or not.
282 bool isNone() const { return value_ == NONE; }
283 };
284 static_assert(sizeof(InlinedCallerOffsetIndex) == sizeof(uint32_t));
285
286 // A hash map from some index (either call site or trap site) to
287 // InlinedCallerOffsetIndex.
288 using InlinedCallerOffsetsIndexHashMap =
289 mozilla::HashMap<uint32_t, InlinedCallerOffsetIndex,
290 mozilla::DefaultHasher<uint32_t>, SystemAllocPolicy>;
291
292 // A collection of InlinedCallerOffsets for a code block.
293 class InliningContext {
294 using Storage = mozilla::Vector<InlinedCallerOffsets, 0, SystemAllocPolicy>;
295 Storage storage_;
296 bool mutable_ = true;
297
298 public:
299 InliningContext() = default;
300
301 bool empty() const { return storage_.empty(); }
302 uint32_t length() const { return storage_.length(); }
303
304 void setImmutable() {
305 MOZ_RELEASE_ASSERT(mutable_);
306 mutable_ = false;
307 }
308
309 const InlinedCallerOffsets* operator[](InlinedCallerOffsetIndex index) const {
310 // Don't give out interior pointers into the vector until we've
311 // transitioned to immutable.
312 MOZ_RELEASE_ASSERT(!mutable_);
313 // Index must be in bounds.
314 MOZ_RELEASE_ASSERT(index.value() < length());
315 return &storage_[index.value()];
316 }
317
318 [[nodiscard]] bool append(InlinedCallerOffsets&& inlinedCallerOffsets,
319 InlinedCallerOffsetIndex* index) {
320 MOZ_RELEASE_ASSERT(mutable_);
321
322 // Skip adding an entry if the offset vector is empty and just return an
323 // 'none' index.
324 if (inlinedCallerOffsets.empty()) {
325 *index = InlinedCallerOffsetIndex();
326 return true;
327 }
328
329 // OOM if we'll be growing beyond the maximum index allowed, or if we
330 // fail to append.
331 if (storage_.length() == InlinedCallerOffsetIndex::MAX ||
332 !storage_.append(std::move(inlinedCallerOffsets))) {
333 return false;
334 }
335 *index = InlinedCallerOffsetIndex(storage_.length() - 1);
336 return true;
337 }
338
339 [[nodiscard]] bool appendAll(InliningContext&& other) {
340 MOZ_RELEASE_ASSERT(mutable_);
341 if (!storage_.appendAll(std::move(other.storage_))) {
342 return false;
343 }
344
345 // OOM if we just grew beyond the maximum index allowed.
346 return storage_.length() <= InlinedCallerOffsetIndex::MAX;
347 }
348
349 void swap(InliningContext& other) {
350 MOZ_RELEASE_ASSERT(mutable_);
351 storage_.swap(other.storage_);
352 }
353
354 void shrinkStorageToFit() { storage_.shrinkStorageToFit(); }
355
356 void clear() {
357 MOZ_RELEASE_ASSERT(mutable_);
358 storage_.clear();
359 }
360
361 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
362 return storage_.sizeOfExcludingThis(mallocSizeOf);
363 }
364 };
365
366 // The fields of a TrapSite that do not depend on code generation.
367
368 struct TrapSiteDesc {
369 explicit TrapSiteDesc(BytecodeOffset bytecodeOffset,
370 InlinedCallerOffsetIndex inlinedCallerOffsetsIndex =
371 InlinedCallerOffsetIndex())
372 : bytecodeOffset(bytecodeOffset),
373 inlinedCallerOffsetsIndex(inlinedCallerOffsetsIndex) {}
374 TrapSiteDesc() : TrapSiteDesc(BytecodeOffset(0)) {};
375
376 bool isValid() const { return bytecodeOffset.isValid(); }
377
378 BytecodeOffset bytecodeOffset;
379 InlinedCallerOffsetIndex inlinedCallerOffsetsIndex;
380 };
381
382 using MaybeTrapSiteDesc = mozilla::Maybe<TrapSiteDesc>;
383
384 // A TrapSite represents a wasm instruction at a given bytecode offset that
385 // can fault at the given pc offset. When such a fault occurs, a signal/
386 // exception handler looks up the TrapSite to confirm the fault is intended/
387 // safe and redirects pc to the trap stub.
388
389 struct TrapSite : TrapSiteDesc {
390 // If this trap site is in a function that was inlined, these are the call
391 // site bytecode offsets of the caller functions that this trap site was
392 // inlined into. The direct ancestor of this function (i.e. the one
393 // directly above it on the stack) is the last entry in the vector.
394 const InlinedCallerOffsets* inlinedCallerOffsets = nullptr;
395
396 BytecodeOffsetSpan inlinedCallerOffsetsSpan() const {
397 if (!inlinedCallerOffsets) {
398 return BytecodeOffsetSpan();
399 }
400 return BytecodeOffsetSpan(inlinedCallerOffsets->begin(),
401 inlinedCallerOffsets->end());
402 }
403 };
404
405 // A collection of TrapSite for a specific trap kind that is optimized for
406 // compact storage.
407 //
408 // The individual fields are split to be in their own vectors to minimize
409 // overhead due to alignment for small fields like TrapMachineInsn.
410 class TrapSitesForKind {
411 // Define our own vectors without any inline storage so they can be used
412 // with swap.
413 using Uint32Vector = Vector<uint32_t, 0, SystemAllocPolicy>;
414 using BytecodeOffsetVector =
415 mozilla::Vector<BytecodeOffset, 0, SystemAllocPolicy>;
416
417 #ifdef DEBUG
418 TrapMachineInsnVector machineInsns_;
419 #endif
420 Uint32Vector pcOffsets_;
421 BytecodeOffsetVector bytecodeOffsets_;
422 InlinedCallerOffsetsIndexHashMap inlinedCallerOffsetsMap_;
423
424 public:
425 explicit TrapSitesForKind() = default;
426
427 // We limit the maximum amount of trap sites to fit in a uint32_t for better
428 // compaction of the sparse hash map. This is dynamically enforced, but
429 // should be safe. The maximum executable memory in a process is at most
430 // ~2GiB, a trapping machine instruction is at least a byte (realistically
431 // much more), which would put the limit of trap sites far below UINT32_MAX.
432 // We subtract one so that this check is not idempotent on 32-bit systems.
433 static constexpr size_t MAX_LENGTH = UINT32_MAX - 1;
434
435 uint32_t length() const {
436 size_t result = pcOffsets_.length();
437 // Enforced by dynamic checks in mutation functions.
438 MOZ_ASSERT(result <= MAX_LENGTH);
439 return (uint32_t)result;
440 }
441
442 bool empty() const { return pcOffsets_.empty(); }
443
444 [[nodiscard]]
445 bool reserve(size_t length) {
446 // See comment on MAX_LENGTH for details.
447 if (length > MAX_LENGTH) {
448 return false;
449 }
450
451 #ifdef DEBUG
452 if (!machineInsns_.reserve(length)) {
453 return false;
454 }
455 #endif
456 return pcOffsets_.reserve(length) && bytecodeOffsets_.reserve(length);
457 }
458
459 [[nodiscard]]
460 bool append(TrapMachineInsn insn, uint32_t pcOffset,
461 const TrapSiteDesc& desc) {
462 MOZ_ASSERT(desc.bytecodeOffset.isValid());
463
464 #ifdef DEBUG
465 if (!machineInsns_.append(insn)) {
466 return false;
467 }
468 #endif
469
470 uint32_t index = length();
471
472 // Add an entry in our map for the trap's inlined caller offsets.
473 if (!desc.inlinedCallerOffsetsIndex.isNone() &&
474 !inlinedCallerOffsetsMap_.putNew(index,
475 desc.inlinedCallerOffsetsIndex)) {
476 return false;
477 }
478
479 return pcOffsets_.append(pcOffset) &&
480 bytecodeOffsets_.append(desc.bytecodeOffset);
481 }
482
483 [[nodiscard]]
484 bool appendAll(TrapSitesForKind&& other, uint32_t baseCodeOffset,
485 InlinedCallerOffsetIndex baseInlinedCallerOffsetIndex) {
486 // See comment on MAX_LENGTH for details.
487 mozilla::CheckedUint32 newLength =
488 mozilla::CheckedUint32(length()) + other.length();
489 if (!newLength.isValid() || newLength.value() > MAX_LENGTH) {
490 return false;
491 }
492
493 #ifdef DEBUG
494 if (!machineInsns_.appendAll(other.machineInsns_)) {
495 return false;
496 }
497 #endif
498
499 // Copy over the map of `other`s inlined caller offsets. The keys are trap
500 // site indices, and must be updated for the base index that `other` is
501 // being inserted into. The values are inlined caller offsets and must be
502 // updated for the base inlined caller offset that the associated inlining
503 // context was added to. See ModuleGenerator::linkCompiledCode.
504 uint32_t baseTrapSiteIndex = length();
505 for (auto iter = other.inlinedCallerOffsetsMap_.modIter(); !iter.done();
506 iter.next()) {
507 uint32_t newTrapSiteIndex = baseTrapSiteIndex + iter.get().key();
508 uint32_t newInlinedCallerOffsetIndex =
509 iter.get().value().value() + baseInlinedCallerOffsetIndex.value();
510
511 if (!inlinedCallerOffsetsMap_.putNew(newTrapSiteIndex,
512 newInlinedCallerOffsetIndex)) {
513 return false;
514 }
515 }
516
517 // Add the baseCodeOffset to the pcOffsets that we are adding to ourselves.
518 for (uint32_t& pcOffset : other.pcOffsets_) {
519 pcOffset += baseCodeOffset;
520 }
521
522 return pcOffsets_.appendAll(other.pcOffsets_) &&
523 bytecodeOffsets_.appendAll(other.bytecodeOffsets_);
524 }
525
526 void clear() {
527 #ifdef DEBUG
528 machineInsns_.clear();
529 #endif
530 pcOffsets_.clear();
531 bytecodeOffsets_.clear();
532 inlinedCallerOffsetsMap_.clear();
533 }
534
535 void swap(TrapSitesForKind& other) {
536 #ifdef DEBUG
537 machineInsns_.swap(other.machineInsns_);
538 #endif
539 pcOffsets_.swap(other.pcOffsets_);
540 bytecodeOffsets_.swap(other.bytecodeOffsets_);
541 inlinedCallerOffsetsMap_.swap(other.inlinedCallerOffsetsMap_);
542 }
543
544 void shrinkStorageToFit() {
545 #ifdef DEBUG
546 machineInsns_.shrinkStorageToFit();
547 #endif
548 pcOffsets_.shrinkStorageToFit();
549 bytecodeOffsets_.shrinkStorageToFit();
550 inlinedCallerOffsetsMap_.compact();
551 }
552
553 bool lookup(uint32_t trapInstructionOffset,
554 const InliningContext& inliningContext, TrapSite* trapOut) const;
555
556 void checkInvariants(const uint8_t* codeBase) const;
557
558 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
559 size_t result = 0;
560 #ifdef DEBUG
561 result += machineInsns_.sizeOfExcludingThis(mallocSizeOf);
562 #endif
563 ShareableBytecodeOffsetVector::SeenSet seen;
564 return result + pcOffsets_.sizeOfExcludingThis(mallocSizeOf) +
565 bytecodeOffsets_.sizeOfExcludingThis(mallocSizeOf) +
566 inlinedCallerOffsetsMap_.shallowSizeOfExcludingThis(mallocSizeOf);
567 }
568
569 WASM_DECLARE_FRIEND_SERIALIZE(TrapSitesForKind);
570 };
571
572 // A collection of TrapSite for any kind of trap and optimized for
573 // compact storage.
574 class TrapSites {
575 using TrapSiteVectorArray =
576 mozilla::EnumeratedArray<Trap, TrapSitesForKind, size_t(Trap::Limit)>;
577
578 TrapSiteVectorArray array_;
579
580 public:
581 explicit TrapSites() = default;
582
583 bool empty() const {
584 for (Trap trap : mozilla::MakeEnumeratedRange(Trap::Limit)) {
585 if (!array_[trap].empty()) {
586 return false;
587 }
588 }
589
590 return true;
591 }
592
593 [[nodiscard]]
594 bool reserve(Trap trap, size_t length) {
595 return array_[trap].reserve(length);
596 }
597
598 [[nodiscard]]
599 bool append(Trap trap, TrapMachineInsn insn, uint32_t pcOffset,
600 const TrapSiteDesc& desc) {
601 return array_[trap].append(insn, pcOffset, desc);
602 }
603
604 [[nodiscard]]
605 bool appendAll(TrapSites&& other, uint32_t baseCodeOffset,
606 InlinedCallerOffsetIndex baseInlinedCallerOffsetIndex) {
607 for (Trap trap : mozilla::MakeEnumeratedRange(Trap::Limit)) {
608 if (!array_[trap].appendAll(std::move(other.array_[trap]), baseCodeOffset,
609 baseInlinedCallerOffsetIndex)) {
610 return false;
611 }
612 }
613 return true;
614 }
615
616 void clear() {
617 for (Trap trap : mozilla::MakeEnumeratedRange(Trap::Limit)) {
618 array_[trap].clear();
619 }
620 }
621
622 void swap(TrapSites& rhs) {
623 for (Trap trap : mozilla::MakeEnumeratedRange(Trap::Limit)) {
624 array_[trap].swap(rhs.array_[trap]);
625 }
626 }
627
628 void shrinkStorageToFit() {
629 for (Trap trap : mozilla::MakeEnumeratedRange(Trap::Limit)) {
630 array_[trap].shrinkStorageToFit();
631 }
632 }
633
634 [[nodiscard]]
635 bool lookup(uint32_t trapInstructionOffset,
636 const InliningContext& inliningContext, Trap* kindOut,
637 TrapSite* trapOut) const {
638 for (Trap trap : mozilla::MakeEnumeratedRange(Trap::Limit)) {
639 const TrapSitesForKind& trapSitesForKind = array_[trap];
640 if (trapSitesForKind.lookup(trapInstructionOffset, inliningContext,
641 trapOut)) {
642 *kindOut = trap;
643 return true;
644 }
645 }
646 return false;
647 }
648
649 void checkInvariants(const uint8_t* codeBase) const {
650 for (Trap trap : mozilla::MakeEnumeratedRange(Trap::Limit)) {
651 array_[trap].checkInvariants(codeBase);
652 }
653 }
654
655 size_t sumOfLengths() const {
656 size_t result = 0;
657 for (Trap trap : mozilla::MakeEnumeratedRange(Trap::Limit)) {
658 result += array_[trap].length();
659 }
660 return result;
661 }
662
663 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
664 size_t result = 0;
665 for (Trap trap : mozilla::MakeEnumeratedRange(Trap::Limit)) {
666 result += array_[trap].sizeOfExcludingThis(mallocSizeOf);
667 }
668 return result;
669 }
670
671 WASM_DECLARE_FRIEND_SERIALIZE(TrapSites);
672 };
673
674 struct CallFarJump {
675 uint32_t targetFuncIndex;
676 uint32_t jumpOffset;
677 WASM_CHECK_CACHEABLE_POD(targetFuncIndex, jumpOffset);
678
679 CallFarJump(uint32_t targetFuncIndex, uint32_t jumpOffset)
680 : targetFuncIndex(targetFuncIndex), jumpOffset(jumpOffset) {}
681 };
682 WASM_DECLARE_CACHEABLE_POD(CallFarJump);
683
684 using CallFarJumpVector = Vector<CallFarJump, 0, SystemAllocPolicy>;
685
686 class CallRefMetricsPatch {
687 private:
688 // The offset of where to patch in the offset of the CallRefMetrics.
689 uint32_t offsetOfOffsetPatch_;
690 static constexpr uint32_t NO_OFFSET = UINT32_MAX;
691
692 WASM_CHECK_CACHEABLE_POD(offsetOfOffsetPatch_);
693
694 public:
695 explicit CallRefMetricsPatch() : offsetOfOffsetPatch_(NO_OFFSET) {}
696
697 bool hasOffsetOfOffsetPatch() const {
698 return offsetOfOffsetPatch_ != NO_OFFSET;
699 }
700 uint32_t offsetOfOffsetPatch() const { return offsetOfOffsetPatch_; }
701 void setOffset(uint32_t indexOffset) {
702 MOZ_ASSERT(!hasOffsetOfOffsetPatch());
703 MOZ_ASSERT(indexOffset != NO_OFFSET);
704 offsetOfOffsetPatch_ = indexOffset;
705 }
706 };
707
708 using CallRefMetricsPatchVector =
709 Vector<CallRefMetricsPatch, 0, SystemAllocPolicy>;
710
711 class AllocSitePatch {
712 private:
713 uint32_t patchOffset_;
714 static constexpr uint32_t NO_OFFSET = UINT32_MAX;
715
716 public:
717 explicit AllocSitePatch() : patchOffset_(NO_OFFSET) {}
718
719 bool hasPatchOffset() const { return patchOffset_ != NO_OFFSET; }
720 uint32_t patchOffset() const { return patchOffset_; }
721 void setPatchOffset(uint32_t offset) {
722 MOZ_ASSERT(!hasPatchOffset());
723 MOZ_ASSERT(offset != NO_OFFSET);
724 patchOffset_ = offset;
725 }
726 };
727
728 using AllocSitePatchVector = Vector<AllocSitePatch, 0, SystemAllocPolicy>;
729
730 // On trap, the bytecode offset to be reported in callstacks is saved.
731
732 struct TrapData {
733 // The resumePC indicates where, if the trap doesn't throw, the trap stub
734 // should jump to after restoring all register state.
735 void* resumePC;
736
737 // The unwoundPC is the PC after adjustment by wasm::StartUnwinding(), which
738 // basically unwinds partially-construted wasm::Frames when pc is in the
739 // prologue/epilogue. Stack traces during a trap should use this PC since
740 // it corresponds to the JitActivation::wasmExitFP.
741 void* unwoundPC;
742
743 Trap trap;
744 TrapSite trapSite;
745
746 // A return_call_indirect from the first function in an activation into
747 // a signature mismatch may leave us with only one frame. This frame is
748 // validly constructed, but has no debug frame yet.
749 bool failedUnwindSignatureMismatch;
750 };
751
752 // The (,Callable,Func)Offsets classes are used to record the offsets of
753 // different key points in a CodeRange during compilation.
754
755 struct Offsets {
756 explicit Offsets(uint32_t begin = 0, uint32_t end = 0)
757 : begin(begin), end(end) {}
758
759 // These define a [begin, end) contiguous range of instructions compiled
760 // into a CodeRange.
761 uint32_t begin;
762 uint32_t end;
763
764 WASM_CHECK_CACHEABLE_POD(begin, end);
765 };
766
767 WASM_DECLARE_CACHEABLE_POD(Offsets);
768
769 struct CallableOffsets : Offsets {
770 MOZ_IMPLICIT CallableOffsets(uint32_t ret = 0) : ret(ret) {}
771
772 // The offset of the return instruction precedes 'end' by a variable number
773 // of instructions due to out-of-line codegen.
774 uint32_t ret;
775
776 WASM_CHECK_CACHEABLE_POD_WITH_PARENT(Offsets, ret);
777 };
778
779 WASM_DECLARE_CACHEABLE_POD(CallableOffsets);
780
781 struct ImportOffsets : CallableOffsets {
782 MOZ_IMPLICIT ImportOffsets() : afterFallbackCheck(0) {}
783
784 // The entry point after initial prologue check.
785 uint32_t afterFallbackCheck;
786
787 WASM_CHECK_CACHEABLE_POD_WITH_PARENT(CallableOffsets, afterFallbackCheck);
788 };
789
790 WASM_DECLARE_CACHEABLE_POD(ImportOffsets);
791
792 struct FuncOffsets : CallableOffsets {
793 MOZ_IMPLICIT FuncOffsets() : uncheckedCallEntry(0), tierEntry(0) {}
794
795 // Function CodeRanges have a checked call entry which takes an extra
796 // signature argument which is checked against the callee's signature before
797 // falling through to the normal prologue. The checked call entry is thus at
798 // the beginning of the CodeRange and the unchecked call entry is at some
799 // offset after the checked call entry.
800 //
801 // Note that there won't always be a checked call entry because not all
802 // functions require them. See GenerateFunctionPrologue.
803 uint32_t uncheckedCallEntry;
804
805 // The tierEntry is the point within a function to which the patching code
806 // within a Tier-1 function jumps. It could be the instruction following
807 // the jump in the Tier-1 function, or the point following the standard
808 // prologue within a Tier-2 function.
809 uint32_t tierEntry;
810
811 WASM_CHECK_CACHEABLE_POD_WITH_PARENT(CallableOffsets, uncheckedCallEntry,
812 tierEntry);
813 };
814
815 WASM_DECLARE_CACHEABLE_POD(FuncOffsets);
816
817 using FuncOffsetsVector = Vector<FuncOffsets, 0, SystemAllocPolicy>;
818
819 // A CodeRange describes a single contiguous range of code within a wasm
820 // module's code segment. A CodeRange describes what the code does and, for
821 // function bodies, the name and source coordinates of the function.
822
823 class CodeRange {
824 public:
825 enum Kind {
826 Function, // function definition
827 InterpEntry, // calls into wasm from C++
828 JitEntry, // calls into wasm from jit code
829 ImportInterpExit, // slow-path calling from wasm into C++ interp
830 ImportJitExit, // fast-path calling from wasm into jit code
831 BuiltinThunk, // fast-path calling from wasm into a C++ native
832 TrapExit, // calls C++ to report and jumps to throw stub
833 DebugStub, // calls C++ to handle debug event
834 RequestTierUpStub, // calls C++ to request tier-2 compilation
835 UpdateCallRefMetricsStub, // updates a CallRefMetrics
836 FarJumpIsland, // inserted to connect otherwise out-of-range insns
837 Throw // special stack-unwinding stub jumped to by other stubs
838 };
839
840 private:
841 // All fields are treated as cacheable POD:
842 uint32_t begin_;
843 uint32_t ret_;
844 uint32_t end_;
845 union {
846 struct {
847 uint32_t funcIndex_;
848 union {
849 struct {
850 uint16_t beginToUncheckedCallEntry_;
851 uint16_t beginToTierEntry_;
852 bool hasUnwindInfo_;
853 } func;
854 uint16_t jitExitEntry_;
855 };
856 };
857 Trap trap_;
858 } u;
859 Kind kind_ : 8;
860
861 WASM_CHECK_CACHEABLE_POD(begin_, ret_, end_, u.funcIndex_,
862 u.func.beginToUncheckedCallEntry_,
863 u.func.beginToTierEntry_, u.func.hasUnwindInfo_,
864 u.trap_, kind_);
865
866 public:
867 CodeRange() = default;
868 CodeRange(Kind kind, Offsets offsets);
869 CodeRange(Kind kind, uint32_t funcIndex, Offsets offsets);
870 CodeRange(Kind kind, CallableOffsets offsets);
871 CodeRange(Kind kind, uint32_t funcIndex, CallableOffsets);
872 CodeRange(Kind kind, uint32_t funcIndex, ImportOffsets offsets);
873 CodeRange(uint32_t funcIndex, FuncOffsets offsets, bool hasUnwindInfo);
874
875 void offsetBy(uint32_t offset) {
876 begin_ += offset;
877 end_ += offset;
878 if (hasReturn()) {
879 ret_ += offset;
880 }
881 }
882
883 // All CodeRanges have a begin and end.
884
885 uint32_t begin() const { return begin_; }
886 uint32_t end() const { return end_; }
887
888 // Other fields are only available for certain CodeRange::Kinds.
889
890 Kind kind() const { return kind_; }
891
892 bool isFunction() const { return kind() == Function; }
893 bool isImportExit() const {
894 return kind() == ImportJitExit || kind() == ImportInterpExit ||
895 kind() == BuiltinThunk;
896 }
897 bool isImportInterpExit() const { return kind() == ImportInterpExit; }
898 bool isImportJitExit() const { return kind() == ImportJitExit; }
899 bool isTrapExit() const { return kind() == TrapExit; }
900 bool isDebugStub() const { return kind() == DebugStub; }
901 bool isRequestTierUpStub() const { return kind() == RequestTierUpStub; }
902 bool isUpdateCallRefMetricsStub() const {
903 return kind() == UpdateCallRefMetricsStub;
904 }
905 bool isThunk() const { return kind() == FarJumpIsland; }
906
907 // Functions, import exits, debug stubs and JitEntry stubs have standard
908 // callable prologues and epilogues. Asynchronous frame iteration needs to
909 // know the offset of the return instruction to calculate the frame pointer.
910
911 bool hasReturn() const {
912 return isFunction() || isImportExit() || isDebugStub() ||
913 isRequestTierUpStub() || isUpdateCallRefMetricsStub() ||
914 isJitEntry();
915 }
916 uint32_t ret() const {
917 MOZ_ASSERT(hasReturn());
918 return ret_;
919 }
920
921 // Functions, export stubs and import stubs all have an associated function
922 // index.
923
924 bool isJitEntry() const { return kind() == JitEntry; }
925 bool isInterpEntry() const { return kind() == InterpEntry; }
926 bool isEntry() const { return isInterpEntry() || isJitEntry(); }
927 bool hasFuncIndex() const {
928 return isFunction() || isImportExit() || isEntry();
929 }
930 uint32_t funcIndex() const {
931 MOZ_ASSERT(hasFuncIndex());
932 return u.funcIndex_;
933 }
934
935 // TrapExit CodeRanges have a Trap field.
936
937 Trap trap() const {
938 MOZ_ASSERT(isTrapExit());
939 return u.trap_;
940 }
941
942 // Function CodeRanges have two entry points: one for normal calls (with a
943 // known signature) and one for table calls (which involves dynamic
944 // signature checking).
945
946 uint32_t funcCheckedCallEntry() const {
947 MOZ_ASSERT(isFunction());
948 // not all functions have the checked call prologue;
949 // see GenerateFunctionPrologue
950 MOZ_ASSERT(u.func.beginToUncheckedCallEntry_ != 0);
951 return begin_;
952 }
953 uint32_t funcUncheckedCallEntry() const {
954 MOZ_ASSERT(isFunction());
955 return begin_ + u.func.beginToUncheckedCallEntry_;
956 }
957 uint32_t funcTierEntry() const {
958 MOZ_ASSERT(isFunction());
959 return begin_ + u.func.beginToTierEntry_;
960 }
961 bool funcHasUnwindInfo() const {
962 MOZ_ASSERT(isFunction());
963 return u.func.hasUnwindInfo_;
964 }
965 uint32_t importJitExitEntry() const {
966 MOZ_ASSERT(isImportJitExit());
967 return begin_ + u.jitExitEntry_;
968 }
969
970 // A sorted array of CodeRanges can be looked up via BinarySearch and
971 // OffsetInCode.
972
973 struct OffsetInCode {
974 size_t offset;
975 explicit OffsetInCode(size_t offset) : offset(offset) {}
976 bool operator==(const CodeRange& rhs) const {
977 return offset >= rhs.begin() && offset < rhs.end();
978 }
979 bool operator<(const CodeRange& rhs) const { return offset < rhs.begin(); }
980 };
981 };
982
983 WASM_DECLARE_CACHEABLE_POD(CodeRange);
984 WASM_DECLARE_POD_VECTOR(CodeRange, CodeRangeVector)
985
986 extern const CodeRange* LookupInSorted(const CodeRangeVector& codeRanges,
987 CodeRange::OffsetInCode target);
988
989 // While the frame-pointer chain allows the stack to be unwound without
990 // metadata, Error.stack still needs to know the line/column of every call in
991 // the chain. A CallSiteDesc describes a single callsite to which CallSite adds
992 // the metadata necessary to walk up to the next frame. Lastly CallSiteAndTarget
993 // adds the function index of the callee.
994
995 enum class CallSiteKind : uint8_t {
996 Func, // pc-relative call to a specific function
997 Import, // wasm import call
998 Indirect, // dynamic callee called via register, context on stack
999 IndirectFast, // dynamically determined to be same-instance
1000 FuncRef, // call using direct function reference
1001 FuncRefFast, // call using direct function reference within same-instance
1002 ReturnFunc, // return call to a specific function
1003 ReturnStub, // return call trampoline
1004 Symbolic, // call to a single symbolic callee
1005 EnterFrame, // call to a enter frame handler
1006 LeaveFrame, // call to a leave frame handler
1007 CollapseFrame, // call to a leave frame handler during tail call
1008 StackSwitch, // stack switch point
1009 Breakpoint, // call to instruction breakpoint
1010 RequestTierUp // call to request tier-2 compilation of this function
1011 };
1012
1013 WASM_DECLARE_CACHEABLE_POD(CallSiteKind);
1014 WASM_DECLARE_POD_VECTOR(CallSiteKind, CallSiteKindVector)
1015
1016 class CallSiteDesc {
1017 // The line of bytecode offset that this call site is at.
1018 uint32_t lineOrBytecode_;
1019 // If this call site has been inlined into another function, the inlined
1020 // caller functions. The direct ancestor of this function (i.e. the one
1021 // directly above it on the stack) is the last entry in the vector.
1022 InlinedCallerOffsetIndex inlinedCallerOffsetsIndex_;
1023 CallSiteKind kind_;
1024
1025 public:
1026 // Some call sites do not have a bytecode offset associated with them
1027 // (such as ones in import function wrappers). We represent them using '0' as
1028 // the bytecode offset. This should never be confused with a real offset,
1029 // because the binary format has overhead from the magic number and section
1030 // headers.
1031 static constexpr uint32_t NO_LINE_OR_BYTECODE = 0;
1032 static constexpr uint32_t FIRST_VALID_BYTECODE_OFFSET =
1033 NO_LINE_OR_BYTECODE + 1;
1034 static_assert(NO_LINE_OR_BYTECODE < sizeof(wasm::MagicNumber));
1035 // Limit lines or bytecodes to the maximum module size.
1036 static constexpr uint32_t MAX_LINE_OR_BYTECODE_VALUE = wasm::MaxModuleBytes;
1037
1038 CallSiteDesc()
1039 : lineOrBytecode_(NO_LINE_OR_BYTECODE), kind_(CallSiteKind::Func) {}
1040 explicit CallSiteDesc(CallSiteKind kind)
1041 : lineOrBytecode_(NO_LINE_OR_BYTECODE), kind_(kind) {
1042 MOZ_ASSERT(kind == CallSiteKind(kind_));
1043 }
1044 CallSiteDesc(uint32_t lineOrBytecode, CallSiteKind kind)
1045 : lineOrBytecode_(lineOrBytecode), kind_(kind) {
1046 MOZ_ASSERT(kind == CallSiteKind(kind_));
1047 MOZ_ASSERT(lineOrBytecode == lineOrBytecode_);
1048 }
1049 CallSiteDesc(BytecodeOffset bytecodeOffset, CallSiteKind kind)
1050 : lineOrBytecode_(bytecodeOffset.offset()), kind_(kind) {
1051 MOZ_ASSERT(kind == CallSiteKind(kind_));
1052 MOZ_ASSERT(bytecodeOffset.offset() == lineOrBytecode_);
1053 }
1054 CallSiteDesc(uint32_t lineOrBytecode,
1055 InlinedCallerOffsetIndex inlinedCallerOffsetsIndex,
1056 CallSiteKind kind)
1057 : lineOrBytecode_(lineOrBytecode),
1058 inlinedCallerOffsetsIndex_(inlinedCallerOffsetsIndex),
1059 kind_(kind) {
1060 MOZ_ASSERT(kind == CallSiteKind(kind_));
1061 MOZ_ASSERT(lineOrBytecode == lineOrBytecode_);
1062 }
1063 CallSiteDesc(BytecodeOffset bytecodeOffset,
1064 uint32_t inlinedCallerOffsetsIndex, CallSiteKind kind)
1065 : lineOrBytecode_(bytecodeOffset.offset()),
1066 inlinedCallerOffsetsIndex_(inlinedCallerOffsetsIndex),
1067 kind_(kind) {
1068 MOZ_ASSERT(kind == CallSiteKind(kind_));
1069 MOZ_ASSERT(bytecodeOffset.offset() == lineOrBytecode_);
1070 }
1071 uint32_t lineOrBytecode() const { return lineOrBytecode_; }
1072 InlinedCallerOffsetIndex inlinedCallerOffsetsIndex() const {
1073 return inlinedCallerOffsetsIndex_;
1074 }
1075 TrapSiteDesc toTrapSiteDesc() const {
1076 return TrapSiteDesc(wasm::BytecodeOffset(lineOrBytecode()),
1077 inlinedCallerOffsetsIndex_);
1078 }
1079 CallSiteKind kind() const { return kind_; }
1080 bool isImportCall() const { return kind() == CallSiteKind::Import; }
1081 bool isIndirectCall() const { return kind() == CallSiteKind::Indirect; }
1082 bool isFuncRefCall() const { return kind() == CallSiteKind::FuncRef; }
1083 bool isReturnStub() const { return kind() == CallSiteKind::ReturnStub; }
1084 bool isStackSwitch() const { return kind() == CallSiteKind::StackSwitch; }
1085 bool mightBeCrossInstance() const {
1086 return isImportCall() || isIndirectCall() || isFuncRefCall() ||
1087 isReturnStub() || isStackSwitch();
1088 }
1089 };
1090
1091 using CallSiteDescVector = mozilla::Vector<CallSiteDesc, 0, SystemAllocPolicy>;
1092
1093 class CallSite : public CallSiteDesc {
1094 uint32_t returnAddressOffset_;
1095 const InlinedCallerOffsets* inlinedCallerOffsets_;
1096
1097 CallSite(const CallSiteDesc& desc, uint32_t returnAddressOffset,
1098 const InlinedCallerOffsets* inlinedCallerOffsets)
1099 : CallSiteDesc(desc),
1100 returnAddressOffset_(returnAddressOffset),
1101 inlinedCallerOffsets_(inlinedCallerOffsets) {}
1102 friend class CallSites;
1103
1104 public:
1105 CallSite() : returnAddressOffset_(0), inlinedCallerOffsets_(nullptr) {}
1106
1107 uint32_t returnAddressOffset() const { return returnAddressOffset_; }
1108 BytecodeOffsetSpan inlinedCallerOffsetsSpan() const {
1109 if (!inlinedCallerOffsets_) {
1110 return BytecodeOffsetSpan();
1111 }
1112 return BytecodeOffsetSpan(inlinedCallerOffsets_->begin(),
1113 inlinedCallerOffsets_->end());
1114 }
1115 const InlinedCallerOffsets* inlinedCallerOffsets() const {
1116 return inlinedCallerOffsets_;
1117 }
1118 };
1119
1120 // A collection of CallSite that is optimized for compact storage.
1121 //
1122 // The individual fields are split to be in their own vectors to minimize
1123 // overhead due to alignment for small fields like CallSiteKind.
1124 //
1125 // The `inlinedCallerOffsets` field is split into a sparse hash map as it's
1126 // expected that many call sites will not be in inlined functions.
1127 class CallSites {
1128 // Define our own Uint32Vector without any inline storage so it can be used
1129 // with swap.
1130 using Uint32Vector = Vector<uint32_t, 0, SystemAllocPolicy>;
1131
1132 CallSiteKindVector kinds_;
1133 Uint32Vector lineOrBytecodes_;
1134 Uint32Vector returnAddressOffsets_;
1135 InlinedCallerOffsetsIndexHashMap inlinedCallerOffsetsMap_;
1136
1137 public:
1138 explicit CallSites() = default;
1139
1140 // We limit the maximum amount of call sites to fit in a uint32_t for better
1141 // compaction of the sparse hash map. This is dynamically enforced, but
1142 // should be safe. The maximum executable memory in a process is at most
1143 // ~2GiB, a machine call instruction is at least two bytes (realistically
1144 // much more), which would put the limit of call sites far below UINT32_MAX.
1145 // We subtract one so that this check is not idempotent on 32-bit systems.
1146 static constexpr size_t MAX_LENGTH = UINT32_MAX - 1;
1147
1148 uint32_t length() const {
1149 size_t result = kinds_.length();
1150 // Enforced by dynamic checks in mutation functions.
1151 MOZ_ASSERT(result <= MAX_LENGTH);
1152 return (uint32_t)result;
1153 }
1154
1155 bool empty() const { return kinds_.empty(); }
1156
1157 CallSiteKind kind(size_t index) const { return kinds_[index]; }
1158 BytecodeOffset bytecodeOffset(size_t index) const {
1159 return BytecodeOffset(lineOrBytecodes_[index]);
1160 }
1161 uint32_t returnAddressOffset(size_t index) const {
1162 return returnAddressOffsets_[index];
1163 }
1164
1165 CallSite get(size_t index, const InliningContext& inliningContext) const {
1166 InlinedCallerOffsetIndex inlinedCallerOffsetsIndex;
1167 const InlinedCallerOffsets* inlinedCallerOffsets = nullptr;
1168 if (auto entry = inlinedCallerOffsetsMap_.lookup(index)) {
1169 inlinedCallerOffsetsIndex = entry->value();
1170 inlinedCallerOffsets = inliningContext[entry->value()];
1171 }
1172 return CallSite(CallSiteDesc(lineOrBytecodes_[index],
1173 inlinedCallerOffsetsIndex, kinds_[index]),
1174 returnAddressOffsets_[index], inlinedCallerOffsets);
1175 }
1176
1177 [[nodiscard]]
1178 bool lookup(uint32_t returnAddressOffset,
1179 const InliningContext& inliningContext, CallSite* callSite) const;
1180
1181 [[nodiscard]]
1182 bool append(const CallSiteDesc& callSiteDesc, uint32_t returnAddressOffset) {
1183 // See comment on MAX_LENGTH for details.
1184 if (length() == MAX_LENGTH) {
1185 return false;
1186 }
1187
1188 uint32_t index = length();
1189
1190 // If there are inline caller offsets, then insert an entry in our hash map.
1191 InlinedCallerOffsetIndex inlinedCallerOffsetsIndex =
1192 callSiteDesc.inlinedCallerOffsetsIndex();
1193 if (!inlinedCallerOffsetsIndex.isNone() &&
1194 !inlinedCallerOffsetsMap_.putNew(index, inlinedCallerOffsetsIndex)) {
1195 return false;
1196 }
1197
1198 return kinds_.append(callSiteDesc.kind()) &&
1199 lineOrBytecodes_.append(callSiteDesc.lineOrBytecode()) &&
1200 returnAddressOffsets_.append(returnAddressOffset);
1201 }
1202
1203 [[nodiscard]]
1204 bool appendAll(CallSites&& other, uint32_t baseCodeOffset,
1205 InlinedCallerOffsetIndex baseInlinedCallerOffsetIndex) {
1206 // See comment on MAX_LENGTH for details.
1207 mozilla::CheckedUint32 newLength =
1208 mozilla::CheckedUint32(length()) + other.length();
1209 if (!newLength.isValid() || newLength.value() > MAX_LENGTH) {
1210 return false;
1211 }
1212
1213 // Copy over the map of `other`s inlined caller offsets. The keys are call
1214 // site indices, and must be updated for the base index that `other` is
1215 // being inserted into. The values are inlined caller offsets and must be
1216 // updated for the base inlined caller offset that the associated inlining
1217 // context was added to. See ModuleGenerator::linkCompiledCode.
1218 uint32_t baseCallSiteIndex = length();
1219 for (auto iter = other.inlinedCallerOffsetsMap_.modIter(); !iter.done();
1220 iter.next()) {
1221 uint32_t newCallSiteIndex = iter.get().key() + baseCallSiteIndex;
1222 uint32_t newInlinedCallerOffsetIndex =
1223 iter.get().value().value() + baseInlinedCallerOffsetIndex.value();
1224
1225 if (!inlinedCallerOffsetsMap_.putNew(newCallSiteIndex,
1226 newInlinedCallerOffsetIndex)) {
1227 return false;
1228 }
1229 }
1230
1231 // Add the baseCodeOffset to the pcOffsets that we are adding to ourselves.
1232 for (uint32_t& pcOffset : other.returnAddressOffsets_) {
1233 pcOffset += baseCodeOffset;
1234 }
1235
1236 return kinds_.appendAll(other.kinds_) &&
1237 lineOrBytecodes_.appendAll(other.lineOrBytecodes_) &&
1238 returnAddressOffsets_.appendAll(other.returnAddressOffsets_);
1239 }
1240
1241 void swap(CallSites& other) {
1242 kinds_.swap(other.kinds_);
1243 lineOrBytecodes_.swap(other.lineOrBytecodes_);
1244 returnAddressOffsets_.swap(other.returnAddressOffsets_);
1245 inlinedCallerOffsetsMap_.swap(other.inlinedCallerOffsetsMap_);
1246 }
1247
1248 void clear() {
1249 kinds_.clear();
1250 lineOrBytecodes_.clear();
1251 returnAddressOffsets_.clear();
1252 inlinedCallerOffsetsMap_.clear();
1253 }
1254
1255 [[nodiscard]]
1256 bool reserve(size_t length) {
1257 // See comment on MAX_LENGTH for details.
1258 if (length > MAX_LENGTH) {
1259 return false;
1260 }
1261
1262 return kinds_.reserve(length) && lineOrBytecodes_.reserve(length) &&
1263 returnAddressOffsets_.reserve(length);
1264 }
1265
1266 void shrinkStorageToFit() {
1267 kinds_.shrinkStorageToFit();
1268 lineOrBytecodes_.shrinkStorageToFit();
1269 returnAddressOffsets_.shrinkStorageToFit();
1270 inlinedCallerOffsetsMap_.compact();
1271 }
1272
1273 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
1274 return kinds_.sizeOfExcludingThis(mallocSizeOf) +
1275 lineOrBytecodes_.sizeOfExcludingThis(mallocSizeOf) +
1276 returnAddressOffsets_.sizeOfExcludingThis(mallocSizeOf) +
1277 inlinedCallerOffsetsMap_.shallowSizeOfExcludingThis(mallocSizeOf);
1278 }
1279
1280 void checkInvariants() const {
1281 #ifdef DEBUG
1282 MOZ_ASSERT(kinds_.length() == lineOrBytecodes_.length());
1283 MOZ_ASSERT(kinds_.length() == returnAddressOffsets_.length());
1284 uint32_t last = 0;
1285 for (uint32_t returnAddressOffset : returnAddressOffsets_) {
1286 MOZ_ASSERT(returnAddressOffset >= last);
1287 last = returnAddressOffset;
1288 }
1289 for (auto iter = inlinedCallerOffsetsMap_.iter(); !iter.done();
1290 iter.next()) {
1291 MOZ_ASSERT(iter.get().key() < length());
1292 MOZ_ASSERT(!iter.get().value().isNone());
1293 }
1294 #endif
1295 }
1296
1297 WASM_DECLARE_FRIEND_SERIALIZE(CallSites);
1298 };
1299
1300 // A CallSiteTarget describes the callee of a CallSite, either a function or a
1301 // trap exit. Although checked in debug builds, a CallSiteTarget doesn't
1302 // officially know whether it targets a function or trap, relying on the Kind of
1303 // the CallSite to discriminate.
1304
1305 class CallSiteTarget {
1306 uint32_t packed_;
1307
1308 WASM_CHECK_CACHEABLE_POD(packed_);
1309 #ifdef DEBUG
1310 enum Kind { None, FuncIndex, TrapExit } kind_;
1311 WASM_CHECK_CACHEABLE_POD(kind_);
1312 #endif
1313
1314 public:
1315 explicit CallSiteTarget()
1316 : packed_(UINT32_MAX)
1317 #ifdef DEBUG
1318 ,
1319 kind_(None)
1320 #endif
1321 {
1322 }
1323
1324 explicit CallSiteTarget(uint32_t funcIndex)
1325 : packed_(funcIndex)
1326 #ifdef DEBUG
1327 ,
1328 kind_(FuncIndex)
1329 #endif
1330 {
1331 }
1332
1333 explicit CallSiteTarget(Trap trap)
1334 : packed_(uint32_t(trap))
1335 #ifdef DEBUG
1336 ,
1337 kind_(TrapExit)
1338 #endif
1339 {
1340 }
1341
1342 uint32_t funcIndex() const {
1343 MOZ_ASSERT(kind_ == FuncIndex);
1344 return packed_;
1345 }
1346
1347 Trap trap() const {
1348 MOZ_ASSERT(kind_ == TrapExit);
1349 MOZ_ASSERT(packed_ < uint32_t(Trap::Limit));
1350 return Trap(packed_);
1351 }
1352 };
1353
1354 WASM_DECLARE_CACHEABLE_POD(CallSiteTarget);
1355
1356 using CallSiteTargetVector = Vector<CallSiteTarget, 0, SystemAllocPolicy>;
1357
1358 // TryNotes are stored in a vector that acts as an exception table for
1359 // wasm try-catch blocks. These represent the information needed to take
1360 // exception handling actions after a throw is executed.
1361 struct TryNote {
1362 private:
1363 // Sentinel value to detect a try note that has not been given a try body.
1364 static const uint32_t BEGIN_NONE = UINT32_MAX;
1365
1366 // Sentinel value used in `entryPointOrIsDelegate_`.
1367 static const uint32_t IS_DELEGATE = UINT32_MAX;
1368
1369 // Begin code offset of the try body.
1370 uint32_t begin_;
1371 // Exclusive end code offset of the try body.
1372 uint32_t end_;
1373 // Either a marker that this is a 'delegate' or else the code offset of the
1374 // landing pad to jump to.
1375 uint32_t entryPointOrIsDelegate_;
1376 // If this is a delegate, then this is the code offset to delegate to,
1377 // otherwise this is the offset from the frame pointer of the stack pointer
1378 // to use when jumping to the landing pad.
1379 uint32_t framePushedOrDelegateOffset_;
1380
1381 WASM_CHECK_CACHEABLE_POD(begin_, end_, entryPointOrIsDelegate_,
1382 framePushedOrDelegateOffset_);
1383
1384 public:
1385 explicit TryNote()
1386 : begin_(BEGIN_NONE),
1387 end_(0),
1388 entryPointOrIsDelegate_(0),
1389 framePushedOrDelegateOffset_(0) {}
1390
1391 // Returns whether a try note has been assigned a range for the try body.
1392 bool hasTryBody() const { return begin_ != BEGIN_NONE; }
1393
1394 // The code offset of the beginning of the try body.
1395 uint32_t tryBodyBegin() const { return begin_; }
1396
1397 // The code offset of the exclusive end of the try body.
1398 uint32_t tryBodyEnd() const { return end_; }
1399
1400 // Returns whether an offset is within this try note's body.
1401 bool offsetWithinTryBody(uint32_t offset) const {
1402 return offset > begin_ && offset <= end_;
1403 }
1404
1405 // Check if the unwinder should delegate the handling of this try note to the
1406 // try note given at the delegate offset.
1407 bool isDelegate() const { return entryPointOrIsDelegate_ == IS_DELEGATE; }
1408
1409 // The code offset to delegate the handling of this try note to.
1410 uint32_t delegateOffset() const {
1411 MOZ_ASSERT(isDelegate());
1412 return framePushedOrDelegateOffset_;
1413 }
1414
1415 // The code offset of the entry to the landing pad.
1416 uint32_t landingPadEntryPoint() const {
1417 MOZ_ASSERT(!isDelegate());
1418 return entryPointOrIsDelegate_;
1419 }
1420
1421 // The stack frame pushed amount at the entry to the landing pad.
1422 uint32_t landingPadFramePushed() const {
1423 MOZ_ASSERT(!isDelegate());
1424 return framePushedOrDelegateOffset_;
1425 }
1426
1427 // Set the beginning of the try body.
1428 void setTryBodyBegin(uint32_t begin) {
1429 // There must not be a begin to the try body yet
1430 MOZ_ASSERT(begin_ == BEGIN_NONE);
1431 begin_ = begin;
1432 }
1433
1434 // Set the end of the try body.
1435 void setTryBodyEnd(uint32_t end) {
1436 // There must be a begin to the try body
1437 MOZ_ASSERT(begin_ != BEGIN_NONE);
1438 end_ = end;
1439 // We do not allow empty try bodies
1440 MOZ_ASSERT(end_ > begin_);
1441 }
1442
1443 // Mark this try note as a delegate, requesting the unwinder to use the try
1444 // note found at the delegate offset.
1445 void setDelegate(uint32_t delegateOffset) {
1446 entryPointOrIsDelegate_ = IS_DELEGATE;
1447 framePushedOrDelegateOffset_ = delegateOffset;
1448 }
1449
1450 // Set the entry point and frame pushed of the landing pad.
1451 void setLandingPad(uint32_t entryPoint, uint32_t framePushed) {
1452 MOZ_ASSERT(!isDelegate());
1453 entryPointOrIsDelegate_ = entryPoint;
1454 framePushedOrDelegateOffset_ = framePushed;
1455 }
1456
1457 // Adjust all code offsets in this try note by a delta.
1458 void offsetBy(uint32_t offset) {
1459 begin_ += offset;
1460 end_ += offset;
1461 if (isDelegate()) {
1462 framePushedOrDelegateOffset_ += offset;
1463 } else {
1464 entryPointOrIsDelegate_ += offset;
1465 }
1466 }
1467
1468 bool operator<(const TryNote& other) const {
1469 // Special case comparison with self. This avoids triggering the assertion
1470 // about non-intersection below. This case can arise in std::sort.
1471 if (this == &other) {
1472 return false;
1473 }
1474 // Try notes must be properly nested without touching at begin and end
1475 MOZ_ASSERT(end_ <= other.begin_ || begin_ >= other.end_ ||
1476 (begin_ > other.begin_ && end_ < other.end_) ||
1477 (other.begin_ > begin_ && other.end_ < end_));
1478 // A total order is therefore given solely by comparing end points. This
1479 // order will be such that the first try note to intersect a point is the
1480 // innermost try note for that point.
1481 return end_ < other.end_;
1482 }
1483 };
1484
1485 WASM_DECLARE_CACHEABLE_POD(TryNote);
1486 WASM_DECLARE_POD_VECTOR(TryNote, TryNoteVector)
1487
1488 class CodeRangeUnwindInfo {
1489 public:
1490 enum UnwindHow {
1491 Normal,
1492 RestoreFpRa,
1493 RestoreFp,
1494 UseFpLr,
1495 UseFp,
1496 };
1497
1498 private:
1499 uint32_t offset_;
1500 UnwindHow unwindHow_;
1501
1502 WASM_CHECK_CACHEABLE_POD(offset_, unwindHow_);
1503
1504 public:
1505 CodeRangeUnwindInfo(uint32_t offset, UnwindHow unwindHow)
1506 : offset_(offset), unwindHow_(unwindHow) {}
1507
1508 uint32_t offset() const { return offset_; }
1509 UnwindHow unwindHow() const { return unwindHow_; }
1510
1511 // Adjust all code offsets in this info by a delta.
1512 void offsetBy(uint32_t offset) { offset_ += offset; }
1513 };
1514
1515 WASM_DECLARE_CACHEABLE_POD(CodeRangeUnwindInfo);
1516 WASM_DECLARE_POD_VECTOR(CodeRangeUnwindInfo, CodeRangeUnwindInfoVector)
1517
1518 enum class CallIndirectIdKind {
1519 // Generate a no-op signature check prologue, asm.js function tables are
1520 // homogenous.
1521 AsmJS,
1522 // Use a machine code immediate for the signature check, only works on simple
1523 // function types, without super types, and without siblings in their
1524 // recursion group.
1525 Immediate,
1526 // Use the full type definition and subtyping machinery when performing the
1527 // signature check.
1528 Global,
1529 // Don't generate any signature check prologue, for functions that cannot be
1530 // stored in tables.
1531 None
1532 };
1533
1534 // CallIndirectId describes how to compile a call_indirect and matching
1535 // signature check in the function prologue for a given function type.
1536
1537 class CallIndirectId {
1538 CallIndirectIdKind kind_;
1539 union {
1540 size_t immediate_;
1541 struct {
1542 size_t instanceDataOffset_;
1543 bool hasSuperType_;
1544 } global_;
1545 };
1546
1547 explicit CallIndirectId(CallIndirectIdKind kind) : kind_(kind) {}
1548
1549 public:
1550 CallIndirectId() : kind_(CallIndirectIdKind::None) {}
1551
1552 // Get a CallIndirectId for an asm.js function which will generate a no-op
1553 // checked call prologue.
1554 static CallIndirectId forAsmJSFunc();
1555
1556 // Get the CallIndirectId for a function in a specific module.
1557 static CallIndirectId forFunc(const CodeMetadata& codeMeta,
1558 uint32_t funcIndex);
1559
1560 // Get the CallIndirectId for a function type in a specific module.
1561 static CallIndirectId forFuncType(const CodeMetadata& codeMeta,
1562 uint32_t funcTypeIndex);
1563
1564 CallIndirectIdKind kind() const { return kind_; }
1565 bool isGlobal() const { return kind_ == CallIndirectIdKind::Global; }
1566
1567 // The bit-packed representation of simple function types. See FuncType in
1568 // WasmTypeDef.h for more information.
1569 uint32_t immediate() const {
1570 MOZ_ASSERT(kind_ == CallIndirectIdKind::Immediate);
1571 return immediate_;
1572 }
1573
1574 // The offset of the TypeDefInstanceData for the function type.
1575 uint32_t instanceDataOffset() const {
1576 MOZ_ASSERT(kind_ == CallIndirectIdKind::Global);
1577 return global_.instanceDataOffset_;
1578 }
1579
1580 // Whether the TypeDef has any super types.
1581 bool hasSuperType() const {
1582 MOZ_ASSERT(kind_ == CallIndirectIdKind::Global);
1583 return global_.hasSuperType_;
1584 }
1585 };
1586
1587 // CalleeDesc describes how to compile one of the variety of asm.js/wasm calls.
1588 // This is hoisted into WasmCodegenTypes.h for sharing between Ion and Baseline.
1589
1590 class CalleeDesc {
1591 public:
1592 enum Which {
1593 // Calls a function defined in the same module by its index.
1594 Func,
1595
1596 // Calls the import identified by the offset of its FuncImportInstanceData
1597 // in
1598 // thread-local data.
1599 Import,
1600
1601 // Calls a WebAssembly table (heterogeneous, index must be bounds
1602 // checked, callee instance depends on TableDesc).
1603 WasmTable,
1604
1605 // Calls an asm.js table (homogeneous, masked index, same-instance).
1606 AsmJSTable,
1607
1608 // Call a C++ function identified by SymbolicAddress.
1609 Builtin,
1610
1611 // Like Builtin, but automatically passes Instance* as first argument.
1612 BuiltinInstanceMethod,
1613
1614 // Calls a function reference.
1615 FuncRef,
1616 };
1617
1618 private:
1619 // which_ shall be initialized in the static constructors
1620 MOZ_INIT_OUTSIDE_CTOR Which which_;
1621 union U {
1622 U() : funcIndex_(0) {}
1623 uint32_t funcIndex_;
1624 struct {
1625 uint32_t instanceDataOffset_;
1626 } import;
1627 struct {
1628 uint32_t instanceDataOffset_;
1629 uint64_t minLength_;
1630 mozilla::Maybe<uint64_t> maxLength_;
1631 CallIndirectId callIndirectId_;
1632 } table;
1633 SymbolicAddress builtin_;
1634 } u;
1635
1636 public:
1637 CalleeDesc() = default;
1638 static CalleeDesc function(uint32_t funcIndex);
1639 static CalleeDesc import(uint32_t instanceDataOffset);
1640 static CalleeDesc wasmTable(const CodeMetadata& codeMeta,
1641 const TableDesc& desc, uint32_t tableIndex,
1642 CallIndirectId callIndirectId);
1643 static CalleeDesc asmJSTable(const CodeMetadata& codeMeta,
1644 uint32_t tableIndex);
1645 static CalleeDesc builtin(SymbolicAddress callee);
1646 static CalleeDesc builtinInstanceMethod(SymbolicAddress callee);
1647 static CalleeDesc wasmFuncRef();
1648 Which which() const { return which_; }
1649 uint32_t funcIndex() const {
1650 MOZ_ASSERT(which_ == Func);
1651 return u.funcIndex_;
1652 }
1653 uint32_t importInstanceDataOffset() const {
1654 MOZ_ASSERT(which_ == Import);
1655 return u.import.instanceDataOffset_;
1656 }
1657 bool isTable() const { return which_ == WasmTable || which_ == AsmJSTable; }
1658 uint32_t tableLengthInstanceDataOffset() const {
1659 MOZ_ASSERT(isTable());
1660 return u.table.instanceDataOffset_ + offsetof(TableInstanceData, length);
1661 }
1662 uint32_t tableFunctionBaseInstanceDataOffset() const {
1663 MOZ_ASSERT(isTable());
1664 return u.table.instanceDataOffset_ + offsetof(TableInstanceData, elements);
1665 }
1666 CallIndirectId wasmTableSigId() const {
1667 MOZ_ASSERT(which_ == WasmTable);
1668 return u.table.callIndirectId_;
1669 }
1670 uint32_t wasmTableMinLength() const {
1671 MOZ_ASSERT(which_ == WasmTable);
1672 return u.table.minLength_;
1673 }
1674 mozilla::Maybe<uint32_t> wasmTableMaxLength() const {
1675 MOZ_ASSERT(which_ == WasmTable);
1676 return u.table.maxLength_;
1677 }
1678 SymbolicAddress builtin() const {
1679 MOZ_ASSERT(which_ == Builtin || which_ == BuiltinInstanceMethod);
1680 return u.builtin_;
1681 }
1682 bool isFuncRef() const { return which_ == FuncRef; }
1683 };
1684
1685 struct FuncIonPerfSpewer {
1686 uint32_t funcIndex = 0;
1687 jit::IonPerfSpewer spewer;
1688
1689 FuncIonPerfSpewer() = default;
1690 FuncIonPerfSpewer(uint32_t funcIndex, jit::IonPerfSpewer&& spewer)
1691 : funcIndex(funcIndex), spewer(std::move(spewer)) {}
1692 FuncIonPerfSpewer(FuncIonPerfSpewer&) = delete;
1693 FuncIonPerfSpewer(FuncIonPerfSpewer&&) = default;
1694 FuncIonPerfSpewer& operator=(FuncIonPerfSpewer&) = delete;
1695 FuncIonPerfSpewer& operator=(FuncIonPerfSpewer&&) = default;
1696 };
1697
1698 using FuncIonPerfSpewerVector = Vector<FuncIonPerfSpewer, 8, SystemAllocPolicy>;
1699 using FuncIonPerfSpewerSpan = mozilla::Span<FuncIonPerfSpewer>;
1700
1701 struct FuncBaselinePerfSpewer {
1702 uint32_t funcIndex = 0;
1703 jit::WasmBaselinePerfSpewer spewer;
1704
1705 FuncBaselinePerfSpewer() = default;
1706 FuncBaselinePerfSpewer(uint32_t funcIndex,
1707 jit::WasmBaselinePerfSpewer&& spewer)
1708 : funcIndex(funcIndex), spewer(std::move(spewer)) {}
1709 FuncBaselinePerfSpewer(FuncBaselinePerfSpewer&) = delete;
1710 FuncBaselinePerfSpewer(FuncBaselinePerfSpewer&&) = default;
1711 FuncBaselinePerfSpewer& operator=(FuncBaselinePerfSpewer&) = delete;
1712 FuncBaselinePerfSpewer& operator=(FuncBaselinePerfSpewer&&) = default;
1713 };
1714
1715 using FuncBaselinePerfSpewerVector =
1716 Vector<FuncBaselinePerfSpewer, 8, SystemAllocPolicy>;
1717 using FuncBaselinePerfSpewerSpan = mozilla::Span<FuncBaselinePerfSpewer>;
1718
1719 // This holds stats relating to compilation of some arbitrary set of functions.
1720 // If you add fields, don't forget to update its `clear` and `empty` methods.
1721 struct CompileStats {
1722 // number of functions in the set
1723 size_t numFuncs;
1724 // bytecode size of the functions
1725 size_t bytecodeSize;
1726 // number of direct-call / call-ref sites inlined
1727 size_t inlinedDirectCallCount;
1728 size_t inlinedCallRefCount;
1729 // total extra bytecode size from direct-call / call-ref inlining
1730 size_t inlinedDirectCallBytecodeSize;
1731 size_t inlinedCallRefBytecodeSize;
1732 // number of funcs for which inlining stopped due to budget overrun
1733 size_t numInliningBudgetOverruns;
1734 // number of funcs for which inlining was made less aggressive because the
1735 // function was already large
1736 size_t numLargeFunctionBackoffs = 0;
1737
1738 void clear() {
1739 numFuncs = 0;
1740 bytecodeSize = 0;
1741 inlinedDirectCallCount = 0;
1742 inlinedCallRefCount = 0;
1743 inlinedDirectCallBytecodeSize = 0;
1744 inlinedCallRefBytecodeSize = 0;
1745 numInliningBudgetOverruns = 0;
1746 numLargeFunctionBackoffs = 0;
1747 }
1748 CompileStats() { clear(); }
1749
1750 bool empty() const {
1751 return 0 == (numFuncs | bytecodeSize | inlinedDirectCallCount |
1752 inlinedCallRefCount | inlinedDirectCallBytecodeSize |
1753 inlinedCallRefBytecodeSize | numInliningBudgetOverruns |
1754 numLargeFunctionBackoffs);
1755 }
1756
1757 // Merge in the counts from `other`. When using this, be careful to avoid
1758 // double-accounting bugs -- conceptually, `other` should be zeroed out as a
1759 // result of the merge. Doing that as part of this routine would be nice but
1760 // unfortunately interferes with `const` qualification and thread-safety, so
1761 // that isn't done.
1762 void merge(const CompileStats& other);
1763 };
1764
1765 // Same as CompileStats, but includes info about compiled-code size.
1766 struct CompileAndLinkStats : public CompileStats {
1767 // total mapped addr space for generated code (a multiple of the page size)
1768 size_t codeBytesMapped;
1769 // total used space for generated code (will be less than the above)
1770 size_t codeBytesUsed;
1771
1772 void clear() {
1773 CompileStats::clear();
1774 codeBytesMapped = 0;
1775 codeBytesUsed = 0;
1776 }
1777 CompileAndLinkStats() { clear(); }
1778
1779 bool empty() const {
1780 return 0 == (codeBytesMapped | codeBytesUsed) && CompileStats::empty();
1781 }
1782
1783 // Same comments as for CompileStats::merge apply.
1784 void merge(const CompileAndLinkStats& other);
1785
1786 // Merge in just CompileStats from `other`.
1787 void mergeCompileStats(const CompileStats& other) {
1788 CompileStats::merge(other);
1789 }
1790
1791 void print() const;
1792 };
1793
1794 } // namespace wasm
1795 } // namespace js
1796
1797 #endif // wasm_codegen_types_h