Debian Codegraph @

js/src/wasm/WasmBaselineCompile.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 2016 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 /*
20 * [SMDOC] WebAssembly baseline compiler (RabaldrMonkey)
21 *
22 * For now, see WasmBCClass.h for general comments about the compiler's
23 * structure.
24 *
25 * ----------------
26 *
27 * General assumptions for 32-bit vs 64-bit code:
28 *
29 * - A 32-bit register can be extended in-place to a 64-bit register on 64-bit
30 * systems.
31 *
32 * - Code that knows that Register64 has a '.reg' member on 64-bit systems and
33 * '.high' and '.low' members on 32-bit systems, or knows the implications
34 * thereof, is #ifdef JS_PUNBOX64. All other code is #if(n)?def JS_64BIT.
35 *
36 * Coding standards are a little fluid:
37 *
38 * - In "small" code generating functions (eg emitMultiplyF64, emitQuotientI32,
39 * and surrounding functions; most functions fall into this class) where the
40 * meaning is obvious:
41 *
42 * Old school:
43 * - if there is a single source + destination register, it is called 'r'
44 * - if there is one source and a different destination, they are called 'rs'
45 * and 'rd'
46 * - if there is one source + destination register and another source register
47 * they are called 'r' and 'rs'
48 * - if there are two source registers and a destination register they are
49 * called 'rs0', 'rs1', and 'rd'.
50 *
51 * The new thing:
52 * - what is called 'r' in the old-school naming scheme is increasingly called
53 * 'rsd' in source+dest cases.
54 *
55 * - Generic temp registers are named /temp[0-9]?/ not /tmp[0-9]?/.
56 *
57 * - Registers can be named non-generically for their function ('rp' for the
58 * 'pointer' register and 'rv' for the 'value' register are typical) and those
59 * names may or may not have an 'r' prefix.
60 *
61 * - "Larger" code generating functions make their own rules.
62 */
63
64 /*
65 * [SMDOC] WebAssembly baseline compiler -- Lazy Tier-Up mechanism
66 *
67 * For baseline functions, we compile in code to monitor the function's
68 * "hotness" and request tier-up once that hotness crosses a threshold.
69 *
70 * (1) Each function has an associated int32_t counter,
71 * FuncDefInstanceData::hotnessCounter. These are stored in an array in
72 * the Instance. Hence access to them is fast and thread-local.
73 *
74 * (2) On instantiation, the counters are set to some positive number
75 * (Instance::init, Instance::computeInitialHotnessCounter), which is a
76 * very crude estimate of the cost of Ion compilation of the function.
77 *
78 * (3) In baseline compilation, a function decrements its counter at every
79 * entry (BaseCompiler::beginFunction) and at the start of every loop
80 * iteration (BaseCompiler::emitLoop). The decrement code is created by
81 * BaseCompiler::addHotnessCheck.
82 *
83 * (4) The decrement is by some value in the range 1 .. 127, as computed from
84 * the function or loop-body size, by BlockSizeToDownwardsStep.
85 *
86 * (5) For loops, the body size is known only at the end of the loop, but the
87 * check is required at the start of the body. Hence the value is patched
88 * in at the end (BaseCompiler::emitEnd, case LabelKind::Loop).
89 *
90 * (6) BaseCompiler::addHotnessCheck creates the shortest possible
91 * decrement/check code, to minimise both time and code-space overhead. On
92 * Intel it is only two instructions. The counter has the value from (4)
93 * subtracted from it. If the result is negative, we jump to OOL code
94 * (class OutOfLineRequestTierUp) which requests tier up; control then
95 * continues immediately after the check.
96 *
97 * (7) The OOL tier-up request code calls the stub pointed to by
98 * Instance::requestTierUpStub_. This always points to the stub created by
99 * GenerateRequestTierUpStub. This saves all registers and calls onwards
100 * to WasmHandleRequestTierUp in C++-land.
101 *
102 * (8) WasmHandleRequestTierUp figures out which function in which Instance is
103 * requesting tier-up. It sets the function's counter (1) to the largest
104 * possible value, which is 2^31-1. It then calls onwards to
105 * Code::requestTierUp, which requests off-thread Ion compilation of the
106 * function, then immediately returns.
107 *
108 * (9) It is important that (8) sets the counter to 2^31-1 (as close to
109 * infinity as possible). This is because it may be arbitrarily long
110 * before the optimised code becomes available. In the meantime the
111 * baseline version of the function will continue to run. We do not want
112 * it to make frequent duplicate requests for tier-up. Although a request
113 * for tier-up is relatively cheap (a few hundred instructions), it is
114 * still way more expensive than the fast-case for a hotness check (2 insns
115 * on Intel), and performance of the baseline code will be badly affected
116 * if it makes many duplicate requests.
117 *
118 * (10) Of course it is impossible to *guarantee* that a baseline function will
119 * not make a duplicate request, because the Ion compilation of the
120 * function could take arbitrarily long, or even fail completely (eg OOM).
121 * Hence it is necessary for WasmCode::requestTierUp (8) to detect and
122 * ignore duplicate requests.
123 *
124 * (11) Each Instance of a Module runs in its own thread and has its own array
125 * of counters. This makes the counter updating thread-local and cheap.
126 * But it means that, if a Module has multiple threads (Instances), it
127 * could be that a function never gets hot enough to request tier up,
128 * because it is not hot enough in any single thread, even though the
129 * total hotness summed across all threads is enough to request tier up.
130 * Whether this inaccuracy is a problem in practice remains to be seen.
131 *
132 * (12) Code::requestTierUp (8) creates a PartialTier2CompileTask and queues it
133 * for execution. It does not do the compilation itself.
134 *
135 * (13) A PartialTier2CompileTask's runHelperThreadTask (running on a helper
136 * thread) calls CompilePartialTier2. This compiles the function with Ion
137 * and racily updates the tiering table entry for the function, which
138 * lives in Code::jumpTables_::tiering_.
139 *
140 * (14) Subsequent calls to the function's baseline entry points will then jump
141 * to the Ion version of the function. Hence lazy tier-up is achieved.
142 */
143
144 #include "wasm/WasmBaselineCompile.h"
145
146 #include "wasm/WasmAnyRef.h"
147 #include "wasm/WasmBCClass.h"
148 #include "wasm/WasmBCDefs.h"
149 #include "wasm/WasmBCFrame.h"
150 #include "wasm/WasmBCRegDefs.h"
151 #include "wasm/WasmBCStk.h"
152 #include "wasm/WasmValType.h"
153
154 #include "jit/MacroAssembler-inl.h"
155 #include "wasm/WasmBCClass-inl.h"
156 #include "wasm/WasmBCCodegen-inl.h"
157 #include "wasm/WasmBCRegDefs-inl.h"
158 #include "wasm/WasmBCRegMgmt-inl.h"
159 #include "wasm/WasmBCStkMgmt-inl.h"
160
161 namespace js {
162 namespace wasm {
163
164 using namespace js::jit;
165
166 using mozilla::Maybe;
167 using mozilla::Nothing;
168 using mozilla::Some;
169
170 ////////////////////////////////////////////////////////////
171 //
172 // Out of line code management.
173
174 // The baseline compiler will use OOL code more sparingly than Ion since our
175 // code is not high performance and frills like code density and branch
176 // prediction friendliness will be less important.
177 class OutOfLineCode : public TempObject {
178 private:
179 NonAssertingLabel entry_;
180 NonAssertingLabel rejoin_;
181 StackHeight stackHeight_;
182
183 public:
184 OutOfLineCode() : stackHeight_(StackHeight::Invalid()) {}
185
186 Label* entry() { return &entry_; }
187 Label* rejoin() { return &rejoin_; }
188
189 void setStackHeight(StackHeight stackHeight) {
190 MOZ_ASSERT(!stackHeight_.isValid());
191 stackHeight_ = stackHeight;
192 }
193
194 void bind(BaseStackFrame* fr, MacroAssembler* masm) {
195 MOZ_ASSERT(stackHeight_.isValid());
196 masm->bind(&entry_);
197 fr->setStackHeight(stackHeight_);
198 }
199
200 // The generate() method must be careful about register use because it will be
201 // invoked when there is a register assignment in the BaseCompiler that does
202 // not correspond to the available registers when the generated OOL code is
203 // executed. The register allocator *must not* be called.
204 //
205 // The best strategy is for the creator of the OOL object to allocate all
206 // temps that the OOL code will need.
207 //
208 // Input, output, and temp registers are embedded in the OOL object and are
209 // known to the code generator.
210 //
211 // Scratch registers are available to use in OOL code.
212 //
213 // All other registers must be explicitly saved and restored by the OOL code
214 // before being used.
215
216 virtual void generate(MacroAssembler* masm) = 0;
217 };
218
219 OutOfLineCode* BaseCompiler::addOutOfLineCode(OutOfLineCode* ool) {
220 if (!ool || !outOfLine_.append(ool)) {
221 return nullptr;
222 }
223 ool->setStackHeight(fr.stackHeight());
224 return ool;
225 }
226
227 bool BaseCompiler::generateOutOfLineCode() {
228 for (auto* ool : outOfLine_) {
229 if (!ool->entry()->used()) {
230 continue;
231 }
232 ool->bind(&fr, &masm);
233 ool->generate(&masm);
234 }
235
236 return !masm.oom();
237 }
238
239 //////////////////////////////////////////////////////////////////////////////
240 //
241 // Sundry code generation.
242
243 bool BaseCompiler::addInterruptCheck() {
244 #ifdef RABALDR_PIN_INSTANCE
245 Register tmp(InstanceReg);
246 #else
247 ScratchI32 tmp(*this);
248 fr.loadInstancePtr(tmp);
249 #endif
250 Label ok;
251 masm.branch32(Assembler::Equal,
252 Address(tmp, wasm::Instance::offsetOfInterrupt()), Imm32(0),
253 &ok);
254 trap(wasm::Trap::CheckInterrupt);
255 masm.bind(&ok);
256 return createStackMap("addInterruptCheck");
257 }
258
259 void BaseCompiler::checkDivideByZero(RegI32 rhs) {
260 Label nonZero;
261 masm.branchTest32(Assembler::NonZero, rhs, rhs, &nonZero);
262 trap(Trap::IntegerDivideByZero);
263 masm.bind(&nonZero);
264 }
265
266 void BaseCompiler::checkDivideByZero(RegI64 r) {
267 Label nonZero;
268 ScratchI32 scratch(*this);
269 masm.branchTest64(Assembler::NonZero, r, r, scratch, &nonZero);
270 trap(Trap::IntegerDivideByZero);
271 masm.bind(&nonZero);
272 }
273
274 void BaseCompiler::checkDivideSignedOverflow(RegI32 rhs, RegI32 srcDest,
275 Label* done, bool zeroOnOverflow) {
276 Label notMin;
277 masm.branch32(Assembler::NotEqual, srcDest, Imm32(INT32_MIN), &notMin);
278 if (zeroOnOverflow) {
279 masm.branch32(Assembler::NotEqual, rhs, Imm32(-1), &notMin);
280 moveImm32(0, srcDest);
281 masm.jump(done);
282 } else {
283 masm.branch32(Assembler::NotEqual, rhs, Imm32(-1), &notMin);
284 trap(Trap::IntegerOverflow);
285 }
286 masm.bind(&notMin);
287 }
288
289 void BaseCompiler::checkDivideSignedOverflow(RegI64 rhs, RegI64 srcDest,
290 Label* done, bool zeroOnOverflow) {
291 Label notmin;
292 masm.branch64(Assembler::NotEqual, srcDest, Imm64(INT64_MIN), &notmin);
293 masm.branch64(Assembler::NotEqual, rhs, Imm64(-1), &notmin);
294 if (zeroOnOverflow) {
295 masm.xor64(srcDest, srcDest);
296 masm.jump(done);
297 } else {
298 trap(Trap::IntegerOverflow);
299 }
300 masm.bind(&notmin);
301 }
302
303 void BaseCompiler::jumpTable(const LabelVector& labels, Label* theTable) {
304 // Flush constant pools to ensure that the table is never interrupted by
305 // constant pool entries.
306 masm.flush();
307
308 #if defined(JS_CODEGEN_ARM) || defined(JS_CODEGEN_ARM64)
309 // Prevent nop sequences to appear in the jump table.
310 AutoForbidNops afn(&masm);
311 #endif
312 masm.bind(theTable);
313
314 for (const auto& label : labels) {
315 CodeLabel cl;
316 masm.writeCodePointer(&cl);
317 cl.target()->bind(label.offset());
318 masm.addCodeLabel(cl);
319 }
320 }
321
322 void BaseCompiler::tableSwitch(Label* theTable, RegI32 switchValue,
323 Label* dispatchCode) {
324 masm.bind(dispatchCode);
325
326 #if defined(JS_CODEGEN_X64) || defined(JS_CODEGEN_X86)
327 ScratchI32 scratch(*this);
328 CodeLabel tableCl;
329
330 masm.mov(&tableCl, scratch);
331
332 tableCl.target()->bind(theTable->offset());
333 masm.addCodeLabel(tableCl);
334
335 masm.jmp(Operand(scratch, switchValue, ScalePointer));
336 #elif defined(JS_CODEGEN_ARM)
337 // Flush constant pools: offset must reflect the distance from the MOV
338 // to the start of the table; as the address of the MOV is given by the
339 // label, nothing must come between the bind() and the ma_mov().
340 AutoForbidPoolsAndNops afp(&masm,
341 /* number of instructions in scope = */ 5);
342
343 ScratchI32 scratch(*this);
344
345 // Compute the offset from the ma_mov instruction to the jump table.
346 Label here;
347 masm.bind(&here);
348 uint32_t offset = here.offset() - theTable->offset();
349
350 // Read PC+8
351 masm.ma_mov(pc, scratch);
352
353 // ARM scratch register is required by ma_sub.
354 ScratchRegisterScope arm_scratch(*this);
355
356 // Compute the absolute table base pointer into `scratch`, offset by 8
357 // to account for the fact that ma_mov read PC+8.
358 masm.ma_sub(Imm32(offset + 8), scratch, arm_scratch);
359
360 // Jump indirect via table element.
361 masm.ma_ldr(DTRAddr(scratch, DtrRegImmShift(switchValue, LSL, 2)), pc, Offset,
362 Assembler::Always);
363 #elif defined(JS_CODEGEN_MIPS64) || defined(JS_CODEGEN_LOONG64) || \
364 defined(JS_CODEGEN_RISCV64)
365 ScratchI32 scratch(*this);
366 CodeLabel tableCl;
367
368 masm.ma_li(scratch, &tableCl);
369
370 tableCl.target()->bind(theTable->offset());
371 masm.addCodeLabel(tableCl);
372
373 masm.branchToComputedAddress(BaseIndex(scratch, switchValue, ScalePointer));
374 #elif defined(JS_CODEGEN_ARM64)
375 AutoForbidPoolsAndNops afp(&masm,
376 /* number of instructions in scope = */ 4);
377
378 ScratchI32 scratch(*this);
379
380 ARMRegister s(scratch, 64);
381 ARMRegister v(switchValue, 64);
382 masm.Adr(s, theTable);
383 masm.Add(s, s, Operand(v, vixl::LSL, 3));
384 masm.Ldr(s, MemOperand(s, 0));
385 masm.Br(s);
386 #else
387 MOZ_CRASH("BaseCompiler platform hook: tableSwitch");
388 #endif
389 }
390
391 // Helpers for accessing the "baseline scratch" areas: all targets
392 void BaseCompiler::stashWord(RegPtr instancePtr, size_t index, RegPtr r) {
393 MOZ_ASSERT(r != instancePtr);
394 MOZ_ASSERT(index < Instance::N_BASELINE_SCRATCH_WORDS);
395 masm.storePtr(r,
396 Address(instancePtr, Instance::offsetOfBaselineScratchWords() +
397 index * sizeof(uintptr_t)));
398 }
399
400 void BaseCompiler::unstashWord(RegPtr instancePtr, size_t index, RegPtr r) {
401 MOZ_ASSERT(index < Instance::N_BASELINE_SCRATCH_WORDS);
402 masm.loadPtr(Address(instancePtr, Instance::offsetOfBaselineScratchWords() +
403 index * sizeof(uintptr_t)),
404 r);
405 }
406
407 // Helpers for accessing the "baseline scratch" areas: X86 only
408 #ifdef JS_CODEGEN_X86
409 void BaseCompiler::stashI64(RegPtr regForInstance, RegI64 r) {
410 static_assert(sizeof(uintptr_t) == 4);
411 MOZ_ASSERT(Instance::sizeOfBaselineScratchWords() >= 8);
412 MOZ_ASSERT(regForInstance != r.low && regForInstance != r.high);
413 # ifdef RABALDR_PIN_INSTANCE
414 # error "Pinned instance not expected"
415 # endif
416 fr.loadInstancePtr(regForInstance);
417 masm.store32(
418 r.low, Address(regForInstance, Instance::offsetOfBaselineScratchWords()));
419 masm.store32(r.high, Address(regForInstance,
420 Instance::offsetOfBaselineScratchWords() + 4));
421 }
422
423 void BaseCompiler::unstashI64(RegPtr regForInstance, RegI64 r) {
424 static_assert(sizeof(uintptr_t) == 4);
425 MOZ_ASSERT(Instance::sizeOfBaselineScratchWords() >= 8);
426 # ifdef RABALDR_PIN_INSTANCE
427 # error "Pinned instance not expected"
428 # endif
429 fr.loadInstancePtr(regForInstance);
430 if (regForInstance == r.low) {
431 masm.load32(
432 Address(regForInstance, Instance::offsetOfBaselineScratchWords() + 4),
433 r.high);
434 masm.load32(
435 Address(regForInstance, Instance::offsetOfBaselineScratchWords()),
436 r.low);
437 } else {
438 masm.load32(
439 Address(regForInstance, Instance::offsetOfBaselineScratchWords()),
440 r.low);
441 masm.load32(
442 Address(regForInstance, Instance::offsetOfBaselineScratchWords() + 4),
443 r.high);
444 }
445 }
446 #endif
447
448 // Given the bytecode size of a block (a complete function body, or a loop
449 // body), return the required downwards step for the associated hotness
450 // counter. Returned value will be in 1 .. 127 inclusive.
451 static uint32_t BlockSizeToDownwardsStep(size_t blockBytecodeSize) {
452 MOZ_RELEASE_ASSERT(blockBytecodeSize <= size_t(MaxFunctionBytes));
453 const uint32_t BYTECODES_PER_STEP = 20; // tunable parameter
454 size_t step = blockBytecodeSize / BYTECODES_PER_STEP;
455 step = std::max<uint32_t>(step, 1);
456 step = std::min<uint32_t>(step, 127);
457 return uint32_t(step);
458 }
459
460 //////////////////////////////////////////////////////////////////////////////
461 //
462 // Function entry and exit
463
464 bool BaseCompiler::beginFunction() {
465 AutoCreatedBy acb(masm, "(wasm)BaseCompiler::beginFunction");
466
467 JitSpew(JitSpew_Codegen, "# ========================================");
468 JitSpew(JitSpew_Codegen, "# Emitting wasm baseline code");
469 JitSpew(JitSpew_Codegen,
470 "# beginFunction: start of function prologue for index %d",
471 (int)func_.index);
472
473 // Make a start on the stackmap for this function. Inspect the args so
474 // as to determine which of them are both in-memory and pointer-typed, and
475 // add entries to machineStackTracker as appropriate.
476
477 ArgTypeVector args(funcType());
478 size_t inboundStackArgBytes = StackArgAreaSizeUnaligned(args);
479 MOZ_ASSERT(inboundStackArgBytes % sizeof(void*) == 0);
480 stackMapGenerator_.numStackArgBytes = inboundStackArgBytes;
481
482 MOZ_ASSERT(stackMapGenerator_.machineStackTracker.length() == 0);
483 if (!stackMapGenerator_.machineStackTracker.pushNonGCPointers(
484 stackMapGenerator_.numStackArgBytes / sizeof(void*))) {
485 return false;
486 }
487
488 // Identify GC-managed pointers passed on the stack.
489 for (WasmABIArgIter i(args); !i.done(); i++) {
490 ABIArg argLoc = *i;
491 if (argLoc.kind() == ABIArg::Stack &&
492 args[i.index()] == MIRType::WasmAnyRef) {
493 uint32_t offset = argLoc.offsetFromArgBase();
494 MOZ_ASSERT(offset < inboundStackArgBytes);
495 MOZ_ASSERT(offset % sizeof(void*) == 0);
496 stackMapGenerator_.machineStackTracker.setGCPointer(offset /
497 sizeof(void*));
498 }
499 }
500
501 perfSpewer_.markStartOffset(masm.currentOffset());
502 perfSpewer_.recordOffset(masm, "Prologue");
503 GenerateFunctionPrologue(
504 masm, CallIndirectId::forFunc(codeMeta_, func_.index),
505 compilerEnv_.mode() != CompileMode::Once ? Some(func_.index) : Nothing(),
506 &offsets_);
507
508 // GenerateFunctionPrologue pushes exactly one wasm::Frame's worth of
509 // stuff, and none of the values are GC pointers. Hence:
510 if (!stackMapGenerator_.machineStackTracker.pushNonGCPointers(
511 sizeof(Frame) / sizeof(void*))) {
512 return false;
513 }
514
515 // Initialize DebugFrame fields before the stack overflow trap so that
516 // we have the invariant that all observable Frames in a debugEnabled
517 // Module have valid DebugFrames.
518 if (compilerEnv_.debugEnabled()) {
519 #ifdef JS_CODEGEN_ARM64
520 static_assert(DebugFrame::offsetOfFrame() % WasmStackAlignment == 0,
521 "aligned");
522 #endif
523 masm.reserveStack(DebugFrame::offsetOfFrame());
524 if (!stackMapGenerator_.machineStackTracker.pushNonGCPointers(
525 DebugFrame::offsetOfFrame() / sizeof(void*))) {
526 return false;
527 }
528
529 masm.store32(Imm32(func_.index), Address(masm.getStackPointer(),
530 DebugFrame::offsetOfFuncIndex()));
531 masm.store32(Imm32(0),
532 Address(masm.getStackPointer(), DebugFrame::offsetOfFlags()));
533
534 // No need to initialize cachedReturnJSValue_ or any ref-typed spilled
535 // register results, as they are traced if and only if a corresponding
536 // flag (hasCachedReturnJSValue or hasSpilledRefRegisterResult) is set.
537 }
538
539 // Generate a stack-overflow check and its associated stackmap.
540
541 fr.checkStack(ABINonArgReg0,
542 TrapSiteDesc(BytecodeOffset(func_.lineOrBytecode)));
543
544 ExitStubMapVector extras;
545 if (!stackMapGenerator_.generateStackmapEntriesForTrapExit(args, &extras)) {
546 return false;
547 }
548 if (!createStackMap("stack check", extras, masm.currentOffset(),
549 HasDebugFrameWithLiveRefs::No)) {
550 return false;
551 }
552
553 size_t reservedBytes = fr.fixedAllocSize() - masm.framePushed();
554 MOZ_ASSERT(0 == (reservedBytes % sizeof(void*)));
555
556 masm.reserveStack(reservedBytes);
557 fr.onFixedStackAllocated();
558 if (!stackMapGenerator_.machineStackTracker.pushNonGCPointers(
559 reservedBytes / sizeof(void*))) {
560 return false;
561 }
562
563 // Locals are stack allocated. Mark ref-typed ones in the stackmap
564 // accordingly.
565 for (const Local& l : localInfo_) {
566 // Locals that are stack arguments were already added to the stackmap
567 // before pushing the frame.
568 if (l.type == MIRType::WasmAnyRef && !l.isStackArgument()) {
569 uint32_t offs = fr.localOffsetFromSp(l);
570 MOZ_ASSERT(0 == (offs % sizeof(void*)));
571 stackMapGenerator_.machineStackTracker.setGCPointer(offs / sizeof(void*));
572 }
573 }
574
575 // Copy arguments from registers to stack.
576 for (WasmABIArgIter i(args); !i.done(); i++) {
577 if (args.isSyntheticStackResultPointerArg(i.index())) {
578 // If there are stack results and the pointer to stack results
579 // was passed in a register, store it to the stack.
580 if (i->argInRegister()) {
581 fr.storeIncomingStackResultAreaPtr(RegPtr(i->gpr()));
582 }
583 // If we're in a debug frame, copy the stack result pointer arg
584 // to a well-known place.
585 if (compilerEnv_.debugEnabled()) {
586 Register target = ABINonArgReturnReg0;
587 fr.loadIncomingStackResultAreaPtr(RegPtr(target));
588 size_t debugFrameOffset =
589 masm.framePushed() - DebugFrame::offsetOfFrame();
590 size_t debugStackResultsPointerOffset =
591 debugFrameOffset + DebugFrame::offsetOfStackResultsPointer();
592 masm.storePtr(target, Address(masm.getStackPointer(),
593 debugStackResultsPointerOffset));
594 }
595 continue;
596 }
597 if (!i->argInRegister()) {
598 continue;
599 }
600 Local& l = localInfo_[args.naturalIndex(i.index())];
601 switch (i.mirType()) {
602 case MIRType::Int32:
603 fr.storeLocalI32(RegI32(i->gpr()), l);
604 break;
605 case MIRType::Int64:
606 fr.storeLocalI64(RegI64(i->gpr64()), l);
607 break;
608 case MIRType::WasmAnyRef: {
609 mozilla::DebugOnly<uint32_t> offs = fr.localOffsetFromSp(l);
610 MOZ_ASSERT(0 == (offs % sizeof(void*)));
611 fr.storeLocalRef(RegRef(i->gpr()), l);
612 // We should have just visited this local in the preceding loop.
613 MOZ_ASSERT(stackMapGenerator_.machineStackTracker.isGCPointer(
614 offs / sizeof(void*)));
615 break;
616 }
617 case MIRType::Double:
618 fr.storeLocalF64(RegF64(i->fpu()), l);
619 break;
620 case MIRType::Float32:
621 fr.storeLocalF32(RegF32(i->fpu()), l);
622 break;
623 #ifdef ENABLE_WASM_SIMD
624 case MIRType::Simd128:
625 fr.storeLocalV128(RegV128(i->fpu()), l);
626 break;
627 #endif
628 default:
629 MOZ_CRASH("Function argument type");
630 }
631 }
632
633 fr.zeroLocals(&ra);
634 fr.storeInstancePtr(InstanceReg);
635
636 if (compilerEnv_.debugEnabled()) {
637 insertBreakablePoint(CallSiteKind::EnterFrame);
638 if (!createStackMap("debug: enter-frame breakpoint")) {
639 return false;
640 }
641 }
642
643 JitSpew(JitSpew_Codegen,
644 "# beginFunction: enter body with masm.framePushed = %u",
645 masm.framePushed());
646 MOZ_ASSERT(stackMapGenerator_.framePushedAtEntryToBody.isNothing());
647 stackMapGenerator_.framePushedAtEntryToBody.emplace(masm.framePushed());
648
649 if (compilerEnv_.mode() == CompileMode::LazyTiering) {
650 size_t funcBytecodeSize = func_.end - func_.begin;
651 uint32_t step = BlockSizeToDownwardsStep(funcBytecodeSize);
652
653 // Create a patchable hotness check and patch it immediately (only because
654 // there's no way to directly create a non-patchable check directly).
655 Maybe<CodeOffset> ctrDecOffset = addHotnessCheck();
656 if (ctrDecOffset.isNothing()) {
657 return false;
658 }
659 patchHotnessCheck(ctrDecOffset.value(), step);
660 }
661
662 return true;
663 }
664
665 bool BaseCompiler::endFunction() {
666 AutoCreatedBy acb(masm, "(wasm)BaseCompiler::endFunction");
667
668 JitSpew(JitSpew_Codegen, "# endFunction: start of function epilogue");
669
670 // Always branch to returnLabel_.
671 masm.breakpoint();
672
673 // Patch the add in the prologue so that it checks against the correct
674 // frame size. Flush the constant pool in case it needs to be patched.
675 masm.flush();
676
677 // Precondition for patching.
678 if (masm.oom()) {
679 return false;
680 }
681
682 fr.patchCheckStack();
683
684 // We could skip generating the epilogue for functions which never return,
685 // but that would mess up invariants that all functions have a return address
686 // offset in CodeRange. It's also a rare thing, so not worth optimizing for.
687 deadCode_ = !returnLabel_.used();
688 masm.bind(&returnLabel_);
689
690 ResultType resultType(ResultType::Vector(funcType().results()));
691
692 popStackReturnValues(resultType);
693
694 if (compilerEnv_.debugEnabled() && !deadCode_) {
695 // Store and reload the return value from DebugFrame::return so that
696 // it can be clobbered, and/or modified by the debug trap.
697 saveRegisterReturnValues(resultType);
698 insertBreakablePoint(CallSiteKind::Breakpoint);
699 if (!createStackMap("debug: return-point breakpoint",
700 HasDebugFrameWithLiveRefs::Maybe)) {
701 return false;
702 }
703 insertBreakablePoint(CallSiteKind::LeaveFrame);
704 if (!createStackMap("debug: leave-frame breakpoint",
705 HasDebugFrameWithLiveRefs::Maybe)) {
706 return false;
707 }
708 restoreRegisterReturnValues(resultType);
709 }
710
711 #ifndef RABALDR_PIN_INSTANCE
712 // To satisy instance extent invariant we need to reload InstanceReg because
713 // baseline can clobber it.
714 fr.loadInstancePtr(InstanceReg);
715 #endif
716 perfSpewer_.recordOffset(masm, "Epilogue");
717 GenerateFunctionEpilogue(masm, fr.fixedAllocSize(), &offsets_);
718
719 #if defined(JS_ION_PERF)
720 // FIXME - profiling code missing. No bug for this.
721
722 // Note the end of the inline code and start of the OOL code.
723 // gen->perfSpewer().noteEndInlineCode(masm);
724 #endif
725 JitSpew(JitSpew_Codegen, "# endFunction: end of function epilogue");
726
727 JitSpew(JitSpew_Codegen, "# endFunction: start of OOL code");
728 perfSpewer_.recordOffset(masm, "OOLCode");
729 if (!generateOutOfLineCode()) {
730 return false;
731 }
732 JitSpew(JitSpew_Codegen, "# endFunction: end of OOL code");
733
734 if (compilerEnv_.debugEnabled()) {
735 JitSpew(JitSpew_Codegen, "# endFunction: start of per-function debug stub");
736 insertPerFunctionDebugStub();
737 JitSpew(JitSpew_Codegen, "# endFunction: end of per-function debug stub");
738 }
739
740 offsets_.end = masm.currentOffset();
741
742 if (!fr.checkStackHeight()) {
743 return decoder_.fail(decoder_.beginOffset(), "stack frame is too large");
744 }
745
746 JitSpew(JitSpew_Codegen, "# endFunction: end of OOL code for index %d",
747 (int)func_.index);
748 return !masm.oom();
749 }
750
751 //////////////////////////////////////////////////////////////////////////////
752 //
753 // Debugger API.
754
755 // [SMDOC] Wasm debug traps -- code details
756 //
757 // There are four pieces of code involved.
758 //
759 // (1) The "breakable point". This is placed at every location where we might
760 // want to transfer control to the debugger, most commonly before every
761 // bytecode. It must be as short and fast as possible. It checks
762 // Instance::debugStub_, which is either null or a pointer to (3). If
763 // non-null, a call to (2) is performed; when null, nothing happens.
764 //
765 // (2) The "per function debug stub". There is one per function. It consults
766 // a bit-vector attached to the Instance, to see whether breakpoints for
767 // the current function are enabled. If not, it returns (to (1), hence
768 // having no effect). Otherwise, it jumps (not calls) onwards to (3).
769 //
770 // (3) The "debug stub" -- not to be confused with the "per function debug
771 // stub". There is one per module. This saves all the registers and
772 // calls onwards to (4), which is in C++ land. When that call returns,
773 // (3) itself returns, which transfers control directly back to (after)
774 // (1).
775 //
776 // (4) In C++ land -- WasmHandleDebugTrap, corresponding to
777 // SymbolicAddress::HandleDebugTrap. This contains the detailed logic
778 // needed to handle the breakpoint.
779
780 void BaseCompiler::insertBreakablePoint(CallSiteKind kind) {
781 MOZ_ASSERT(!deadCode_);
782 #ifndef RABALDR_PIN_INSTANCE
783 fr.loadInstancePtr(InstanceReg);
784 #endif
785
786 // The breakpoint code must call the breakpoint handler installed on the
787 // instance if it is not null. There is one breakable point before
788 // every bytecode, and one at the beginning and at the end of the function.
789 //
790 // There are many constraints:
791 //
792 // - Code should be read-only; we do not want to patch
793 // - The breakpoint code should be as dense as possible, given the volume of
794 // breakable points
795 // - The handler-is-null case should be as fast as we can make it
796 //
797 // The scratch register is available here.
798 //
799 // An unconditional callout would be densest but is too slow. The best
800 // balance results from an inline test for null with a conditional call. The
801 // best code sequence is platform-dependent.
802 //
803 // The conditional call goes to a stub attached to the function that performs
804 // further filtering before calling the breakpoint handler.
805 #if defined(JS_CODEGEN_X64)
806 // REX 83 MODRM OFFS IB
807 static_assert(Instance::offsetOfDebugStub() < 128);
808 masm.cmpq(Imm32(0),
809 Operand(Address(InstanceReg, Instance::offsetOfDebugStub())));
810
811 // 74 OFFS
812 Label L;
813 L.bind(masm.currentOffset() + 7);
814 masm.j(Assembler::Zero, &L);
815
816 // E8 OFFS OFFS OFFS OFFS
817 masm.call(&perFunctionDebugStub_);
818 masm.append(CallSiteDesc(iter_.lastOpcodeOffset(), kind),
819 CodeOffset(masm.currentOffset()));
820
821 // Branch destination
822 MOZ_ASSERT_IF(!masm.oom(), masm.currentOffset() == uint32_t(L.offset()));
823 #elif defined(JS_CODEGEN_X86)
824 // 83 MODRM OFFS IB
825 static_assert(Instance::offsetOfDebugStub() < 128);
826 masm.cmpl(Imm32(0),
827 Operand(Address(InstanceReg, Instance::offsetOfDebugStub())));
828
829 // 74 OFFS
830 Label L;
831 L.bind(masm.currentOffset() + 7);
832 masm.j(Assembler::Zero, &L);
833
834 // E8 OFFS OFFS OFFS OFFS
835 masm.call(&perFunctionDebugStub_);
836 masm.append(CallSiteDesc(iter_.lastOpcodeOffset(), kind),
837 CodeOffset(masm.currentOffset()));
838
839 // Branch destination
840 MOZ_ASSERT_IF(!masm.oom(), masm.currentOffset() == uint32_t(L.offset()));
841 #elif defined(JS_CODEGEN_ARM64)
842 ScratchPtr scratch(*this);
843 ARMRegister tmp(scratch, 64);
844 Label L;
845 masm.Ldr(tmp,
846 MemOperand(Address(InstanceReg, Instance::offsetOfDebugStub())));
847 masm.Cbz(tmp, &L);
848 masm.Bl(&perFunctionDebugStub_);
849 masm.append(CallSiteDesc(iter_.lastOpcodeOffset(), kind),
850 CodeOffset(masm.currentOffset()));
851 masm.bind(&L);
852 #elif defined(JS_CODEGEN_ARM)
853 ScratchPtr scratch(*this);
854 masm.loadPtr(Address(InstanceReg, Instance::offsetOfDebugStub()), scratch);
855 masm.ma_orr(scratch, scratch, SetCC);
856 masm.ma_bl(&perFunctionDebugStub_, Assembler::NonZero);
857 masm.append(CallSiteDesc(iter_.lastOpcodeOffset(), kind),
858 CodeOffset(masm.currentOffset()));
859 #elif defined(JS_CODEGEN_LOONG64) || defined(JS_CODEGEN_MIPS64) || \
860 defined(JS_CODEGEN_RISCV64)
861 ScratchPtr scratch(*this);
862 Label L;
863 masm.loadPtr(Address(InstanceReg, Instance::offsetOfDebugStub()), scratch);
864 masm.branchPtr(Assembler::Equal, scratch, ImmWord(0), &L);
865 masm.call(&perFunctionDebugStub_);
866 masm.append(CallSiteDesc(iter_.lastOpcodeOffset(), kind),
867 CodeOffset(masm.currentOffset()));
868 masm.bind(&L);
869 #else
870 MOZ_CRASH("BaseCompiler platform hook: insertBreakablePoint");
871 #endif
872 }
873
874 void BaseCompiler::insertPerFunctionDebugStub() {
875 // The per-function debug stub performs out-of-line filtering before jumping
876 // to the per-module debug stub if necessary. The per-module debug stub
877 // returns directly to the breakable point.
878 //
879 // NOTE, the link register is live here on platforms that have LR.
880 //
881 // The scratch register is available here (as it was at the call site).
882 //
883 // It's useful for the per-function debug stub to be compact, as every
884 // function gets one.
885
886 Label L;
887 masm.bind(&perFunctionDebugStub_);
888
889 #if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
890 {
891 ScratchPtr scratch(*this);
892
893 // Get the per-instance table of filtering bits.
894 masm.loadPtr(Address(InstanceReg, Instance::offsetOfDebugFilter()),
895 scratch);
896
897 // Check the filter bit. There is one bit per function in the module.
898 // Table elements are 32-bit because the masm makes that convenient.
899 masm.branchTest32(Assembler::NonZero, Address(scratch, func_.index / 32),
900 Imm32(1 << (func_.index % 32)), &L);
901
902 // Fast path: return to the execution.
903 masm.ret();
904 }
905 #elif defined(JS_CODEGEN_ARM64)
906 {
907 ScratchPtr scratch(*this);
908
909 // Logic as above, except abiret to jump to the LR directly
910 masm.loadPtr(Address(InstanceReg, Instance::offsetOfDebugFilter()),
911 scratch);
912 masm.branchTest32(Assembler::NonZero, Address(scratch, func_.index / 32),
913 Imm32(1 << (func_.index % 32)), &L);
914 masm.abiret();
915 }
916 #elif defined(JS_CODEGEN_ARM)
917 {
918 // We must be careful not to use the SecondScratchRegister, which usually
919 // is LR, as LR is live here. This means avoiding masm abstractions such
920 // as branchTest32.
921
922 static_assert(ScratchRegister != lr);
923 static_assert(Instance::offsetOfDebugFilter() < 0x1000);
924
925 ScratchRegisterScope tmp1(masm);
926 ScratchI32 tmp2(*this);
927 masm.ma_ldr(
928 DTRAddr(InstanceReg, DtrOffImm(Instance::offsetOfDebugFilter())), tmp1);
929 masm.ma_mov(Imm32(func_.index / 32), tmp2);
930 masm.ma_ldr(DTRAddr(tmp1, DtrRegImmShift(tmp2, LSL, 0)), tmp2);
931 masm.ma_tst(tmp2, Imm32(1 << func_.index % 32), tmp1, Assembler::Always);
932 masm.ma_bx(lr, Assembler::Zero);
933 }
934 #elif defined(JS_CODEGEN_LOONG64) || defined(JS_CODEGEN_MIPS64) || \
935 defined(JS_CODEGEN_RISCV64)
936 {
937 ScratchPtr scratch(*this);
938
939 // Logic same as ARM64.
940 masm.loadPtr(Address(InstanceReg, Instance::offsetOfDebugFilter()),
941 scratch);
942 masm.branchTest32(Assembler::NonZero, Address(scratch, func_.index / 32),
943 Imm32(1 << (func_.index % 32)), &L);
944 masm.abiret();
945 }
946 #else
947 MOZ_CRASH("BaseCompiler platform hook: endFunction");
948 #endif
949
950 // Jump to the per-module debug stub, which calls onwards to C++ land.
951 masm.bind(&L);
952 masm.jump(Address(InstanceReg, Instance::offsetOfDebugStub()));
953 }
954
955 void BaseCompiler::saveRegisterReturnValues(const ResultType& resultType) {
956 MOZ_ASSERT(compilerEnv_.debugEnabled());
957 size_t debugFrameOffset = masm.framePushed() - DebugFrame::offsetOfFrame();
958 size_t registerResultIdx = 0;
959 for (ABIResultIter i(resultType); !i.done(); i.next()) {
960 const ABIResult result = i.cur();
961 if (!result.inRegister()) {
962 #ifdef DEBUG
963 for (i.next(); !i.done(); i.next()) {
964 MOZ_ASSERT(!i.cur().inRegister());
965 }
966 #endif
967 break;
968 }
969
970 size_t resultOffset = DebugFrame::offsetOfRegisterResult(registerResultIdx);
971 Address dest(masm.getStackPointer(), debugFrameOffset + resultOffset);
972 switch (result.type().kind()) {
973 case ValType::I32:
974 masm.store32(RegI32(result.gpr()), dest);
975 break;
976 case ValType::I64:
977 masm.store64(RegI64(result.gpr64()), dest);
978 break;
979 case ValType::F64:
980 masm.storeDouble(RegF64(result.fpr()), dest);
981 break;
982 case ValType::F32:
983 masm.storeFloat32(RegF32(result.fpr()), dest);
984 break;
985 case ValType::Ref: {
986 uint32_t flag =
987 DebugFrame::hasSpilledRegisterRefResultBitMask(registerResultIdx);
988 // Tell Instance::traceFrame that we have a pointer to trace.
989 masm.or32(Imm32(flag),
990 Address(masm.getStackPointer(),
991 debugFrameOffset + DebugFrame::offsetOfFlags()));
992 masm.storePtr(RegRef(result.gpr()), dest);
993 break;
994 }
995 case ValType::V128:
996 #ifdef ENABLE_WASM_SIMD
997 masm.storeUnalignedSimd128(RegV128(result.fpr()), dest);
998 break;
999 #else
1000 MOZ_CRASH("No SIMD support");
1001 #endif
1002 }
1003 registerResultIdx++;
1004 }
1005 }
1006
1007 void BaseCompiler::restoreRegisterReturnValues(const ResultType& resultType) {
1008 MOZ_ASSERT(compilerEnv_.debugEnabled());
1009 size_t debugFrameOffset = masm.framePushed() - DebugFrame::offsetOfFrame();
1010 size_t registerResultIdx = 0;
1011 for (ABIResultIter i(resultType); !i.done(); i.next()) {
1012 const ABIResult result = i.cur();
1013 if (!result.inRegister()) {
1014 #ifdef DEBUG
1015 for (i.next(); !i.done(); i.next()) {
1016 MOZ_ASSERT(!i.cur().inRegister());
1017 }
1018 #endif
1019 break;
1020 }
1021 size_t resultOffset =
1022 DebugFrame::offsetOfRegisterResult(registerResultIdx++);
1023 Address src(masm.getStackPointer(), debugFrameOffset + resultOffset);
1024 switch (result.type().kind()) {
1025 case ValType::I32:
1026 masm.load32(src, RegI32(result.gpr()));
1027 break;
1028 case ValType::I64:
1029 masm.load64(src, RegI64(result.gpr64()));
1030 break;
1031 case ValType::F64:
1032 masm.loadDouble(src, RegF64(result.fpr()));
1033 break;
1034 case ValType::F32:
1035 masm.loadFloat32(src, RegF32(result.fpr()));
1036 break;
1037 case ValType::Ref:
1038 masm.loadPtr(src, RegRef(result.gpr()));
1039 break;
1040 case ValType::V128:
1041 #ifdef ENABLE_WASM_SIMD
1042 masm.loadUnalignedSimd128(src, RegV128(result.fpr()));
1043 break;
1044 #else
1045 MOZ_CRASH("No SIMD support");
1046 #endif
1047 }
1048 }
1049 }
1050
1051 //////////////////////////////////////////////////////////////////////////////
1052 //
1053 // Support for lazy tiering
1054
1055 // The key thing here is, we generate a short piece of code which, most of the
1056 // time, has no effect, but just occasionally wants to call out to C++ land.
1057 // That's a similar requirement to the Debugger API support (see above) and so
1058 // we have a similar, but simpler, solution. Specifically, we use a single
1059 // stub routine for the whole module, whereas for debugging, there are
1060 // per-function stub routines as well as a whole-module stub routine involved.
1061
1062 class OutOfLineRequestTierUp : public OutOfLineCode {
1063 Register instance_; // points at the instance at entry; must remain unchanged
1064 Maybe<RegI32> scratch_; // only provided on arm32
1065 size_t lastOpcodeOffset_; // a bytecode offset
1066
1067 public:
1068 OutOfLineRequestTierUp(Register instance, Maybe<RegI32> scratch,
1069 size_t lastOpcodeOffset)
1070 : instance_(instance),
1071 scratch_(scratch),
1072 lastOpcodeOffset_(lastOpcodeOffset) {}
1073 virtual void generate(MacroAssembler* masm) override {
1074 // Generate:
1075 //
1076 // [optionally, if `instance_` != InstanceReg: swap(instance_, InstanceReg)]
1077 // call * $offsetOfRequestTierUpStub(InstanceReg)
1078 // [optionally, if `instance_` != InstanceReg: swap(instance_, InstanceReg)]
1079 // goto rejoin
1080 //
1081 // This is the unlikely path, where we call the (per-module)
1082 // request-tier-up stub. The stub wants the instance pointer to be in the
1083 // official InstanceReg at this point, but InstanceReg itself might hold
1084 // arbitrary other live data. Hence, if necessary, swap `instance_` and
1085 // InstanceReg before the call and swap them back after it.
1086 #ifndef RABALDR_PIN_INSTANCE
1087 if (Register(instance_) != InstanceReg) {
1088 # ifdef JS_CODEGEN_X86
1089 // On x86_32 this is easy.
1090 masm->xchgl(instance_, InstanceReg);
1091 # elif JS_CODEGEN_ARM
1092 masm->mov(instance_,
1093 scratch_.value()); // note, destination is second arg
1094 masm->mov(InstanceReg, instance_);
1095 masm->mov(scratch_.value(), InstanceReg);
1096 # else
1097 MOZ_CRASH("BaseCompiler::OutOfLineRequestTierUp #1");
1098 # endif
1099 }
1100 #endif
1101 // Call the stub
1102 masm->call(Address(InstanceReg, Instance::offsetOfRequestTierUpStub()));
1103 masm->append(CallSiteDesc(lastOpcodeOffset_, CallSiteKind::RequestTierUp),
1104 CodeOffset(masm->currentOffset()));
1105 // And swap again, if we swapped above.
1106 #ifndef RABALDR_PIN_INSTANCE
1107 if (Register(instance_) != InstanceReg) {
1108 # ifdef JS_CODEGEN_X86
1109 masm->xchgl(instance_, InstanceReg);
1110 # elif JS_CODEGEN_ARM
1111 masm->mov(instance_, scratch_.value());
1112 masm->mov(InstanceReg, instance_);
1113 masm->mov(scratch_.value(), InstanceReg);
1114 # else
1115 MOZ_CRASH("BaseCompiler::OutOfLineRequestTierUp #2");
1116 # endif
1117 }
1118 #endif
1119
1120 masm->jump(rejoin());
1121 }
1122 };
1123
1124 Maybe<CodeOffset> BaseCompiler::addHotnessCheck() {
1125 // Here's an example of what we'll create. The path that almost always
1126 // happens, where the counter doesn't go negative, has just one branch.
1127 //
1128 // subl $to_be_filled_in_later, 0x170(%r14)
1129 // js oolCode // almost never taken
1130 // rejoin:
1131 // ----------------
1132 // oolCode: // we get here when the counter is negative, viz, almost never
1133 // call *0x160(%r14) // RequestTierUpStub
1134 // jmp rejoin
1135 //
1136 // Note that the counter is updated regardless of whether or not it has gone
1137 // negative. That means that, at entry to RequestTierUpStub, we know the
1138 // counter must be negative, and not merely zero.
1139 //
1140 // Non-Intel targets will have to generate a load / subtract-and-set-flags /
1141 // store / jcond sequence.
1142 //
1143 // To ensure the shortest possible encoding, `to_be_filled_in_later` must be
1144 // a value in the range 1 .. 127 inclusive. This is good enough for
1145 // hotness-counting purposes.
1146
1147 AutoCreatedBy acb(masm, "BC::addHotnessCheck");
1148
1149 #ifdef RABALDR_PIN_INSTANCE
1150 Register instance(InstanceReg);
1151 #else
1152 // This seems to assume that any non-RABALDR_PIN_INSTANCE target is 32-bit
1153 ScratchI32 instance(*this);
1154 fr.loadInstancePtr(instance);
1155 #endif
1156
1157 Address addressOfCounter = Address(
1158 instance, wasm::Instance::offsetInData(
1159 codeMeta_.offsetOfFuncDefInstanceData(func_.index)));
1160
1161 #if JS_CODEGEN_ARM
1162 Maybe<RegI32> scratch = Some(needI32());
1163 #else
1164 Maybe<RegI32> scratch = Nothing();
1165 #endif
1166
1167 OutOfLineCode* ool = addOutOfLineCode(new (alloc_) OutOfLineRequestTierUp(
1168 instance, scratch, iter_.lastOpcodeOffset()));
1169 if (!ool) {
1170 return Nothing();
1171 }
1172
1173 // Because of the Intel arch instruction formats, `patchPoint` points to the
1174 // byte immediately following the last byte of the instruction to patch.
1175 CodeOffset patchPoint = masm.sub32FromMemAndBranchIfNegativeWithPatch(
1176 addressOfCounter, ool->entry());
1177
1178 masm.bind(ool->rejoin());
1179
1180 if (scratch.isSome()) {
1181 freeI32(scratch.value());
1182 }
1183
1184 // `patchPoint` might be invalid if the assembler OOMd at some point.
1185 return masm.oom() ? Nothing() : Some(patchPoint);
1186 }
1187
1188 void BaseCompiler::patchHotnessCheck(CodeOffset offset, uint32_t step) {
1189 // Zero makes the hotness check pointless. Above 127 is not representable in
1190 // the short-form Intel encoding.
1191 MOZ_RELEASE_ASSERT(step > 0 && step <= 127);
1192 MOZ_ASSERT(!masm.oom());
1193 masm.patchSub32FromMemAndBranchIfNegative(offset, Imm32(step));
1194 }
1195
1196 //////////////////////////////////////////////////////////////////////////////
1197 //
1198 // Results and block parameters
1199
1200 void BaseCompiler::popStackReturnValues(const ResultType& resultType) {
1201 uint32_t bytes = ABIResultIter::MeasureStackBytes(resultType);
1202 if (bytes == 0) {
1203 return;
1204 }
1205 Register target = ABINonArgReturnReg0;
1206 Register temp = ABINonArgReturnReg1;
1207 fr.loadIncomingStackResultAreaPtr(RegPtr(target));
1208 fr.popStackResultsToMemory(target, bytes, temp);
1209 }
1210
1211 // TODO / OPTIMIZE (Bug 1316818): At the moment we use the Wasm
1212 // inter-procedure ABI for block returns, which allocates ReturnReg as the
1213 // single block result register. It is possible other choices would lead to
1214 // better register allocation, as ReturnReg is often first in the register set
1215 // and will be heavily wanted by the register allocator that uses takeFirst().
1216 //
1217 // Obvious options:
1218 // - pick a register at the back of the register set
1219 // - pick a random register per block (different blocks have
1220 // different join regs)
1221
1222 void BaseCompiler::popRegisterResults(ABIResultIter& iter) {
1223 // Pop register results. Note that in the single-value case, popping to a
1224 // register may cause a sync(); for multi-value we sync'd already.
1225 for (; !iter.done(); iter.next()) {
1226 const ABIResult& result = iter.cur();
1227 if (!result.inRegister()) {
1228 // TODO / OPTIMIZE: We sync here to avoid solving the general parallel
1229 // move problem in popStackResults. However we could avoid syncing the
1230 // values that are going to registers anyway, if they are already in
1231 // registers.
1232 sync();
1233 break;
1234 }
1235 switch (result.type().kind()) {
1236 case ValType::I32:
1237 popI32(RegI32(result.gpr()));
1238 break;
1239 case ValType::I64:
1240 popI64(RegI64(result.gpr64()));
1241 break;
1242 case ValType::F32:
1243 popF32(RegF32(result.fpr()));
1244 break;
1245 case ValType::F64:
1246 popF64(RegF64(result.fpr()));
1247 break;
1248 case ValType::Ref:
1249 popRef(RegRef(result.gpr()));
1250 break;
1251 case ValType::V128:
1252 #ifdef ENABLE_WASM_SIMD
1253 popV128(RegV128(result.fpr()));
1254 #else
1255 MOZ_CRASH("No SIMD support");
1256 #endif
1257 }
1258 }
1259 }
1260
1261 void BaseCompiler::popStackResults(ABIResultIter& iter, StackHeight stackBase) {
1262 MOZ_ASSERT(!iter.done());
1263
1264 // The iterator should be advanced beyond register results, and register
1265 // results should be popped already from the value stack.
1266 uint32_t alreadyPopped = iter.index();
1267
1268 // At this point, only stack arguments are remaining. Iterate through them
1269 // to measure how much stack space they will take up.
1270 for (; !iter.done(); iter.next()) {
1271 MOZ_ASSERT(iter.cur().onStack());
1272 }
1273
1274 // Calculate the space needed to store stack results, in bytes.
1275 uint32_t stackResultBytes = iter.stackBytesConsumedSoFar();
1276 MOZ_ASSERT(stackResultBytes);
1277
1278 // Compute the stack height including the stack results. Note that it's
1279 // possible that this call expands the stack, for example if some of the
1280 // results are supplied by constants and so are not already on the machine
1281 // stack.
1282 uint32_t endHeight = fr.prepareStackResultArea(stackBase, stackResultBytes);
1283
1284 // Find a free GPR to use when shuffling stack values. If none is
1285 // available, push ReturnReg and restore it after we're done.
1286 bool saved = false;
1287 RegPtr temp = ra.needTempPtr(RegPtr(ReturnReg), &saved);
1288
1289 // The sequence of Stk values is in the same order on the machine stack as
1290 // the result locations, but there is a complication: constant values are
1291 // not actually pushed on the machine stack. (At this point registers and
1292 // locals have been spilled already.) So, moving the Stk values into place
1293 // isn't simply a shuffle-down or shuffle-up operation. There is a part of
1294 // the Stk sequence that shuffles toward the FP, a part that's already in
1295 // place, and a part that shuffles toward the SP. After shuffling, we have
1296 // to materialize the constants.
1297
1298 // Shuffle mem values toward the frame pointer, copying deepest values
1299 // first. Stop when we run out of results, get to a register result, or
1300 // find a Stk value that is closer to the FP than the result.
1301 for (iter.switchToPrev(); !iter.done(); iter.prev()) {
1302 const ABIResult& result = iter.cur();
1303 if (!result.onStack()) {
1304 break;
1305 }
1306 MOZ_ASSERT(result.stackOffset() < stackResultBytes);
1307 uint32_t destHeight = endHeight - result.stackOffset();
1308 uint32_t stkBase = stk_.length() - (iter.count() - alreadyPopped);
1309 Stk& v = stk_[stkBase + iter.index()];
1310 if (v.isMem()) {
1311 uint32_t srcHeight = v.offs();
1312 if (srcHeight <= destHeight) {
1313 break;
1314 }
1315 fr.shuffleStackResultsTowardFP(srcHeight, destHeight, result.size(),
1316 temp);
1317 }
1318 }
1319
1320 // Reset iterator and skip register results.
1321 for (iter.reset(); !iter.done(); iter.next()) {
1322 if (iter.cur().onStack()) {
1323 break;
1324 }
1325 }
1326
1327 // Revisit top stack values, shuffling mem values toward the stack pointer,
1328 // copying shallowest values first.
1329 for (; !iter.done(); iter.next()) {
1330 const ABIResult& result = iter.cur();
1331 MOZ_ASSERT(result.onStack());
1332 MOZ_ASSERT(result.stackOffset() < stackResultBytes);
1333 uint32_t destHeight = endHeight - result.stackOffset();
1334 Stk& v = stk_[stk_.length() - (iter.index() - alreadyPopped) - 1];
1335 if (v.isMem()) {
1336 uint32_t srcHeight = v.offs();
1337 if (srcHeight >= destHeight) {
1338 break;
1339 }
1340 fr.shuffleStackResultsTowardSP(srcHeight, destHeight, result.size(),
1341 temp);
1342 }
1343 }
1344
1345 // Reset iterator and skip register results, which are already popped off
1346 // the value stack.
1347 for (iter.reset(); !iter.done(); iter.next()) {
1348 if (iter.cur().onStack()) {
1349 break;
1350 }
1351 }
1352
1353 // Materialize constants and pop the remaining items from the value stack.
1354 for (; !iter.done(); iter.next()) {
1355 const ABIResult& result = iter.cur();
1356 uint32_t resultHeight = endHeight - result.stackOffset();
1357 Stk& v = stk_.back();
1358 switch (v.kind()) {
1359 case Stk::ConstI32:
1360 #if defined(JS_CODEGEN_MIPS64) || defined(JS_CODEGEN_LOONG64) || \
1361 defined(JS_CODEGEN_RISCV64)
1362 fr.storeImmediatePtrToStack(v.i32val_, resultHeight, temp);
1363 #else
1364 fr.storeImmediatePtrToStack(uint32_t(v.i32val_), resultHeight, temp);
1365 #endif
1366 break;
1367 case Stk::ConstF32:
1368 fr.storeImmediateF32ToStack(v.f32val_, resultHeight, temp);
1369 break;
1370 case Stk::ConstI64:
1371 fr.storeImmediateI64ToStack(v.i64val_, resultHeight, temp);
1372 break;
1373 case Stk::ConstF64:
1374 fr.storeImmediateF64ToStack(v.f64val_, resultHeight, temp);
1375 break;
1376 #ifdef ENABLE_WASM_SIMD
1377 case Stk::ConstV128:
1378 fr.storeImmediateV128ToStack(v.v128val_, resultHeight, temp);
1379 break;
1380 #endif
1381 case Stk::ConstRef:
1382 fr.storeImmediatePtrToStack(v.refval_, resultHeight, temp);
1383 break;
1384 case Stk::MemRef:
1385 // Update bookkeeping as we pop the Stk entry.
1386 stackMapGenerator_.memRefsOnStk--;
1387 break;
1388 default:
1389 MOZ_ASSERT(v.isMem());
1390 break;
1391 }
1392 stk_.popBack();
1393 }
1394
1395 ra.freeTempPtr(temp, saved);
1396
1397 // This will pop the stack if needed.
1398 fr.finishStackResultArea(stackBase, stackResultBytes);
1399 }
1400
1401 void BaseCompiler::popBlockResults(ResultType type, StackHeight stackBase,
1402 ContinuationKind kind) {
1403 if (!type.empty()) {
1404 ABIResultIter iter(type);
1405 popRegisterResults(iter);
1406 if (!iter.done()) {
1407 popStackResults(iter, stackBase);
1408 // Because popStackResults might clobber the stack, it leaves the stack
1409 // pointer already in the right place for the continuation, whether the
1410 // continuation is a jump or fallthrough.
1411 return;
1412 }
1413 }
1414 // We get here if there are no stack results. For a fallthrough, the stack
1415 // is already at the right height. For a jump, we may need to pop the stack
1416 // pointer if the continuation's stack height is lower than the current
1417 // stack height.
1418 if (kind == ContinuationKind::Jump) {
1419 fr.popStackBeforeBranch(stackBase, type);
1420 }
1421 }
1422
1423 // This function is similar to popBlockResults, but additionally handles the
1424 // implicit exception pointer that is pushed to the value stack on entry to
1425 // a catch handler by dropping it appropriately.
1426 void BaseCompiler::popCatchResults(ResultType type, StackHeight stackBase) {
1427 if (!type.empty()) {
1428 ABIResultIter iter(type);
1429 popRegisterResults(iter);
1430 if (!iter.done()) {
1431 popStackResults(iter, stackBase);
1432 // Since popStackResults clobbers the stack, we only need to free the
1433 // exception off of the value stack.
1434 popValueStackBy(1);
1435 } else {
1436 // If there are no stack results, we have to adjust the stack by
1437 // dropping the exception reference that's now on the stack.
1438 dropValue();
1439 }
1440 } else {
1441 dropValue();
1442 }
1443 fr.popStackBeforeBranch(stackBase, type);
1444 }
1445
1446 Stk BaseCompiler::captureStackResult(const ABIResult& result,
1447 StackHeight resultsBase,
1448 uint32_t stackResultBytes) {
1449 MOZ_ASSERT(result.onStack());
1450 uint32_t offs = fr.locateStackResult(result, resultsBase, stackResultBytes);
1451 return Stk::StackResult(result.type(), offs);
1452 }
1453
1454 // TODO: It may be fruitful to inline the fast path here, as it will be common.
1455
1456 bool BaseCompiler::pushResults(ResultType type, StackHeight resultsBase) {
1457 if (type.empty()) {
1458 return true;
1459 }
1460
1461 if (type.length() > 1) {
1462 // Reserve extra space on the stack for all the values we'll push.
1463 // Multi-value push is not accounted for by the pre-sizing of the stack in
1464 // the decoding loop.
1465 //
1466 // Also make sure we leave headroom for other pushes that will occur after
1467 // pushing results, just to be safe.
1468 if (!stk_.reserve(stk_.length() + type.length() + MaxPushesPerOpcode)) {
1469 return false;
1470 }
1471 }
1472
1473 // We need to push the results in reverse order, so first iterate through
1474 // all results to determine the locations of stack result types.
1475 ABIResultIter iter(type);
1476 while (!iter.done()) {
1477 iter.next();
1478 }
1479 uint32_t stackResultBytes = iter.stackBytesConsumedSoFar();
1480 for (iter.switchToPrev(); !iter.done(); iter.prev()) {
1481 const ABIResult& result = iter.cur();
1482 if (!result.onStack()) {
1483 break;
1484 }
1485 Stk v = captureStackResult(result, resultsBase, stackResultBytes);
1486 push(v);
1487 if (v.kind() == Stk::MemRef) {
1488 stackMapGenerator_.memRefsOnStk++;
1489 }
1490 }
1491
1492 for (; !iter.done(); iter.prev()) {
1493 const ABIResult& result = iter.cur();
1494 MOZ_ASSERT(result.inRegister());
1495 switch (result.type().kind()) {
1496 case ValType::I32:
1497 pushI32(RegI32(result.gpr()));
1498 break;
1499 case ValType::I64:
1500 pushI64(RegI64(result.gpr64()));
1501 break;
1502 case ValType::V128:
1503 #ifdef ENABLE_WASM_SIMD
1504 pushV128(RegV128(result.fpr()));
1505 break;
1506 #else
1507 MOZ_CRASH("No SIMD support");
1508 #endif
1509 case ValType::F32:
1510 pushF32(RegF32(result.fpr()));
1511 break;
1512 case ValType::F64:
1513 pushF64(RegF64(result.fpr()));
1514 break;
1515 case ValType::Ref:
1516 pushRef(RegRef(result.gpr()));
1517 break;
1518 }
1519 }
1520
1521 return true;
1522 }
1523
1524 bool BaseCompiler::pushBlockResults(ResultType type) {
1525 return pushResults(type, controlItem().stackHeight);
1526 }
1527
1528 // A combination of popBlockResults + pushBlockResults, used when entering a
1529 // block with a control-flow join (loops) or split (if) to shuffle the
1530 // fallthrough block parameters into the locations expected by the
1531 // continuation.
1532 bool BaseCompiler::topBlockParams(ResultType type) {
1533 // This function should only be called when entering a block with a
1534 // control-flow join at the entry, where there are no live temporaries in
1535 // the current block.
1536 StackHeight base = controlItem().stackHeight;
1537 MOZ_ASSERT(fr.stackResultsBase(stackConsumed(type.length())) == base);
1538 popBlockResults(type, base, ContinuationKind::Fallthrough);
1539 return pushBlockResults(type);
1540 }
1541
1542 // A combination of popBlockResults + pushBlockResults, used before branches
1543 // where we don't know the target (br_if / br_table). If and when the branch
1544 // is taken, the stack results will be shuffled down into place. For br_if
1545 // that has fallthrough, the parameters for the untaken branch flow through to
1546 // the continuation.
1547 bool BaseCompiler::topBranchParams(ResultType type, StackHeight* height) {
1548 if (type.empty()) {
1549 *height = fr.stackHeight();
1550 return true;
1551 }
1552 // There may be temporary values that need spilling; delay computation of
1553 // the stack results base until after the popRegisterResults(), which spills
1554 // if needed.
1555 ABIResultIter iter(type);
1556 popRegisterResults(iter);
1557 StackHeight base = fr.stackResultsBase(stackConsumed(iter.remaining()));
1558 if (!iter.done()) {
1559 popStackResults(iter, base);
1560 }
1561 if (!pushResults(type, base)) {
1562 return false;
1563 }
1564 *height = base;
1565 return true;
1566 }
1567
1568 // Conditional branches with fallthrough are preceded by a topBranchParams, so
1569 // we know that there are no stack results that need to be materialized. In
1570 // that case, we can just shuffle the whole block down before popping the
1571 // stack.
1572 void BaseCompiler::shuffleStackResultsBeforeBranch(StackHeight srcHeight,
1573 StackHeight destHeight,
1574 ResultType type) {
1575 uint32_t stackResultBytes = 0;
1576
1577 if (ABIResultIter::HasStackResults(type)) {
1578 MOZ_ASSERT(stk_.length() >= type.length());
1579 ABIResultIter iter(type);
1580 for (; !iter.done(); iter.next()) {
1581 #ifdef DEBUG
1582 const ABIResult& result = iter.cur();
1583 const Stk& v = stk_[stk_.length() - iter.index() - 1];
1584 MOZ_ASSERT(v.isMem() == result.onStack());
1585 #endif
1586 }
1587
1588 stackResultBytes = iter.stackBytesConsumedSoFar();
1589 MOZ_ASSERT(stackResultBytes > 0);
1590
1591 if (srcHeight != destHeight) {
1592 // Find a free GPR to use when shuffling stack values. If none
1593 // is available, push ReturnReg and restore it after we're done.
1594 bool saved = false;
1595 RegPtr temp = ra.needTempPtr(RegPtr(ReturnReg), &saved);
1596 fr.shuffleStackResultsTowardFP(srcHeight, destHeight, stackResultBytes,
1597 temp);
1598 ra.freeTempPtr(temp, saved);
1599 }
1600 }
1601
1602 fr.popStackBeforeBranch(destHeight, stackResultBytes);
1603 }
1604
1605 bool BaseCompiler::insertDebugCollapseFrame() {
1606 if (!compilerEnv_.debugEnabled() || deadCode_) {
1607 return true;
1608 }
1609 insertBreakablePoint(CallSiteKind::CollapseFrame);
1610 return createStackMap("debug: collapse-frame breakpoint",
1611 HasDebugFrameWithLiveRefs::Maybe);
1612 }
1613
1614 //////////////////////////////////////////////////////////////////////////////
1615 //
1616 // Function calls.
1617
1618 void BaseCompiler::beginCall(
1619 FunctionCall& call, UseABI useABI,
1620 RestoreRegisterStateAndRealm restoreRegisterStateAndRealm) {
1621 MOZ_ASSERT_IF(
1622 useABI == UseABI::Builtin,
1623 restoreRegisterStateAndRealm == RestoreRegisterStateAndRealm::False);
1624
1625 call.restoreRegisterStateAndRealm =
1626 restoreRegisterStateAndRealm == RestoreRegisterStateAndRealm::True;
1627 call.usesSystemAbi = useABI == UseABI::System;
1628
1629 if (call.usesSystemAbi) {
1630 // Call-outs need to use the appropriate system ABI.
1631 #if defined(JS_CODEGEN_ARM)
1632 call.hardFP = ARMFlags::UseHardFpABI();
1633 call.abi.setUseHardFp(call.hardFP);
1634 #endif
1635 } else {
1636 #if defined(JS_CODEGEN_ARM)
1637 MOZ_ASSERT(call.hardFP, "All private ABIs pass FP arguments in registers");
1638 #endif
1639 }
1640
1641 // Use masm.framePushed() because the value we want here does not depend
1642 // on the height of the frame's stack area, but the actual size of the
1643 // allocated frame.
1644 call.frameAlignAdjustment = ComputeByteAlignment(
1645 masm.framePushed() + sizeof(Frame), JitStackAlignment);
1646 }
1647
1648 void BaseCompiler::endCall(FunctionCall& call, size_t stackSpace) {
1649 size_t adjustment = call.stackArgAreaSize + call.frameAlignAdjustment;
1650 fr.freeArgAreaAndPopBytes(adjustment, stackSpace);
1651
1652 MOZ_ASSERT(stackMapGenerator_.framePushedExcludingOutboundCallArgs.isSome());
1653 stackMapGenerator_.framePushedExcludingOutboundCallArgs.reset();
1654
1655 if (call.restoreRegisterStateAndRealm) {
1656 // The instance has been clobbered, so always reload
1657 fr.loadInstancePtr(InstanceReg);
1658 masm.loadWasmPinnedRegsFromInstance(mozilla::Nothing());
1659 masm.switchToWasmInstanceRealm(ABINonArgReturnReg0, ABINonArgReturnReg1);
1660 } else if (call.usesSystemAbi) {
1661 // On x86 there are no pinned registers, so don't waste time
1662 // reloading the instance.
1663 #ifndef JS_CODEGEN_X86
1664 // The instance has been clobbered, so always reload
1665 fr.loadInstancePtr(InstanceReg);
1666 masm.loadWasmPinnedRegsFromInstance(mozilla::Nothing());
1667 #endif
1668 }
1669 }
1670
1671 void BaseCompiler::startCallArgs(size_t stackArgAreaSizeUnaligned,
1672 FunctionCall* call) {
1673 size_t stackArgAreaSizeAligned =
1674 AlignStackArgAreaSize(stackArgAreaSizeUnaligned);
1675 MOZ_ASSERT(stackArgAreaSizeUnaligned <= stackArgAreaSizeAligned);
1676
1677 // Record the masm.framePushed() value at this point, before we push args
1678 // for the call and any required alignment space. This defines the lower limit
1679 // of the stackmap that will be created for this call.
1680 MOZ_ASSERT(
1681 stackMapGenerator_.framePushedExcludingOutboundCallArgs.isNothing());
1682 stackMapGenerator_.framePushedExcludingOutboundCallArgs.emplace(
1683 // However much we've pushed so far
1684 masm.framePushed() +
1685 // Extra space we'll push to get the frame aligned
1686 call->frameAlignAdjustment);
1687
1688 call->stackArgAreaSize = stackArgAreaSizeAligned;
1689
1690 size_t adjustment = call->stackArgAreaSize + call->frameAlignAdjustment;
1691 fr.allocArgArea(adjustment);
1692 }
1693
1694 ABIArg BaseCompiler::reservePointerArgument(FunctionCall* call) {
1695 return call->abi.next(MIRType::Pointer);
1696 }
1697
1698 // TODO / OPTIMIZE (Bug 1316821): Note passArg is used only in one place.
1699 // (Or it was, until Luke wandered through, but that can be fixed again.)
1700 // I'm not saying we should manually inline it, but we could hoist the
1701 // dispatch into the caller and have type-specific implementations of
1702 // passArg: passArgI32(), etc. Then those might be inlined, at least in PGO
1703 // builds.
1704 //
1705 // The bulk of the work here (60%) is in the next() call, though.
1706 //
1707 // Notably, since next() is so expensive, StackArgAreaSizeUnaligned()
1708 // becomes expensive too.
1709 //
1710 // Somehow there could be a trick here where the sequence of argument types
1711 // (read from the input stream) leads to a cached entry for
1712 // StackArgAreaSizeUnaligned() and for how to pass arguments...
1713 //
1714 // But at least we could reduce the cost of StackArgAreaSizeUnaligned() by
1715 // first reading the argument types into a (reusable) vector, then we have
1716 // the outgoing size at low cost, and then we can pass args based on the
1717 // info we read.
1718
1719 void BaseCompiler::passArg(ValType type, const Stk& arg, FunctionCall* call) {
1720 switch (type.kind()) {
1721 case ValType::I32: {
1722 ABIArg argLoc = call->abi.next(MIRType::Int32);
1723 if (argLoc.kind() == ABIArg::Stack) {
1724 ScratchI32 scratch(*this);
1725 loadI32(arg, scratch);
1726 masm.store32(scratch, Address(masm.getStackPointer(),
1727 argLoc.offsetFromArgBase()));
1728 } else {
1729 loadI32(arg, RegI32(argLoc.gpr()));
1730 }
1731 break;
1732 }
1733 case ValType::I64: {
1734 ABIArg argLoc = call->abi.next(MIRType::Int64);
1735 if (argLoc.kind() == ABIArg::Stack) {
1736 ScratchI32 scratch(*this);
1737 #ifdef JS_PUNBOX64
1738 loadI64(arg, fromI32(scratch));
1739 masm.storePtr(scratch, Address(masm.getStackPointer(),
1740 argLoc.offsetFromArgBase()));
1741 #else
1742 loadI64Low(arg, scratch);
1743 masm.store32(scratch, LowWord(Address(masm.getStackPointer(),
1744 argLoc.offsetFromArgBase())));
1745 loadI64High(arg, scratch);
1746 masm.store32(scratch, HighWord(Address(masm.getStackPointer(),
1747 argLoc.offsetFromArgBase())));
1748 #endif
1749 } else {
1750 loadI64(arg, RegI64(argLoc.gpr64()));
1751 }
1752 break;
1753 }
1754 case ValType::V128: {
1755 #ifdef ENABLE_WASM_SIMD
1756 ABIArg argLoc = call->abi.next(MIRType::Simd128);
1757 switch (argLoc.kind()) {
1758 case ABIArg::Stack: {
1759 ScratchV128 scratch(*this);
1760 loadV128(arg, scratch);
1761 masm.storeUnalignedSimd128(
1762 (RegV128)scratch,
1763 Address(masm.getStackPointer(), argLoc.offsetFromArgBase()));
1764 break;
1765 }
1766 case ABIArg::GPR: {
1767 MOZ_CRASH("Unexpected parameter passing discipline");
1768 }
1769 case ABIArg::FPU: {
1770 loadV128(arg, RegV128(argLoc.fpu()));
1771 break;
1772 }
1773 # if defined(JS_CODEGEN_REGISTER_PAIR)
1774 case ABIArg::GPR_PAIR: {
1775 MOZ_CRASH("Unexpected parameter passing discipline");
1776 }
1777 # endif
1778 case ABIArg::Uninitialized:
1779 MOZ_CRASH("Uninitialized ABIArg kind");
1780 }
1781 break;
1782 #else
1783 MOZ_CRASH("No SIMD support");
1784 #endif
1785 }
1786 case ValType::F64: {
1787 ABIArg argLoc = call->abi.next(MIRType::Double);
1788 switch (argLoc.kind()) {
1789 case ABIArg::Stack: {
1790 ScratchF64 scratch(*this);
1791 loadF64(arg, scratch);
1792 masm.storeDouble(scratch, Address(masm.getStackPointer(),
1793 argLoc.offsetFromArgBase()));
1794 break;
1795 }
1796 #if defined(JS_CODEGEN_REGISTER_PAIR)
1797 case ABIArg::GPR_PAIR: {
1798 # if defined(JS_CODEGEN_ARM)
1799 ScratchF64 scratch(*this);
1800 loadF64(arg, scratch);
1801 masm.ma_vxfer(scratch, argLoc.evenGpr(), argLoc.oddGpr());
1802 break;
1803 # else
1804 MOZ_CRASH("BaseCompiler platform hook: passArg F64 pair");
1805 # endif
1806 }
1807 #endif
1808 case ABIArg::FPU: {
1809 loadF64(arg, RegF64(argLoc.fpu()));
1810 break;
1811 }
1812 case ABIArg::GPR: {
1813 MOZ_CRASH("Unexpected parameter passing discipline");
1814 }
1815 case ABIArg::Uninitialized:
1816 MOZ_CRASH("Uninitialized ABIArg kind");
1817 }
1818 break;
1819 }
1820 case ValType::F32: {
1821 ABIArg argLoc = call->abi.next(MIRType::Float32);
1822 switch (argLoc.kind()) {
1823 case ABIArg::Stack: {
1824 ScratchF32 scratch(*this);
1825 loadF32(arg, scratch);
1826 masm.storeFloat32(scratch, Address(masm.getStackPointer(),
1827 argLoc.offsetFromArgBase()));
1828 break;
1829 }
1830 case ABIArg::GPR: {
1831 ScratchF32 scratch(*this);
1832 loadF32(arg, scratch);
1833 masm.moveFloat32ToGPR(scratch, argLoc.gpr());
1834 break;
1835 }
1836 case ABIArg::FPU: {
1837 loadF32(arg, RegF32(argLoc.fpu()));
1838 break;
1839 }
1840 #if defined(JS_CODEGEN_REGISTER_PAIR)
1841 case ABIArg::GPR_PAIR: {
1842 MOZ_CRASH("Unexpected parameter passing discipline");
1843 }
1844 #endif
1845 case ABIArg::Uninitialized:
1846 MOZ_CRASH("Uninitialized ABIArg kind");
1847 }
1848 break;
1849 }
1850 case ValType::Ref: {
1851 ABIArg argLoc = call->abi.next(MIRType::WasmAnyRef);
1852 if (argLoc.kind() == ABIArg::Stack) {
1853 ScratchRef scratch(*this);
1854 loadRef(arg, scratch);
1855 masm.storePtr(scratch, Address(masm.getStackPointer(),
1856 argLoc.offsetFromArgBase()));
1857 } else {
1858 loadRef(arg, RegRef(argLoc.gpr()));
1859 }
1860 break;
1861 }
1862 }
1863 }
1864
1865 CodeOffset BaseCompiler::callDefinition(uint32_t funcIndex,
1866 const FunctionCall& call) {
1867 CallSiteDesc desc(bytecodeOffset(), CallSiteKind::Func);
1868 return masm.call(desc, funcIndex);
1869 }
1870
1871 CodeOffset BaseCompiler::callSymbolic(SymbolicAddress callee,
1872 const FunctionCall& call) {
1873 CallSiteDesc desc(bytecodeOffset(), CallSiteKind::Symbolic);
1874 return masm.call(desc, callee);
1875 }
1876
1877 // Precondition: sync()
1878
1879 class OutOfLineAbortingTrap : public OutOfLineCode {
1880 Trap trap_;
1881 TrapSiteDesc desc_;
1882
1883 public:
1884 OutOfLineAbortingTrap(Trap trap, const TrapSiteDesc& desc)
1885 : trap_(trap), desc_(desc) {}
1886
1887 virtual void generate(MacroAssembler* masm) override {
1888 masm->wasmTrap(trap_, desc_);
1889 MOZ_ASSERT(!rejoin()->bound());
1890 }
1891 };
1892
1893 static ReturnCallAdjustmentInfo BuildReturnCallAdjustmentInfo(
1894 const FuncType& callerType, const FuncType& calleeType) {
1895 return ReturnCallAdjustmentInfo(
1896 StackArgAreaSizeUnaligned(ArgTypeVector(calleeType)),
1897 StackArgAreaSizeUnaligned(ArgTypeVector(callerType)));
1898 }
1899
1900 bool BaseCompiler::callIndirect(uint32_t funcTypeIndex, uint32_t tableIndex,
1901 const Stk& indexVal, const FunctionCall& call,
1902 bool tailCall, CodeOffset* fastCallOffset,
1903 CodeOffset* slowCallOffset) {
1904 CallIndirectId callIndirectId =
1905 CallIndirectId::forFuncType(codeMeta_, funcTypeIndex);
1906 MOZ_ASSERT(callIndirectId.kind() != CallIndirectIdKind::AsmJS);
1907
1908 const TableDesc& table = codeMeta_.tables[tableIndex];
1909
1910 loadI32(indexVal, RegI32(WasmTableCallIndexReg));
1911
1912 CallSiteDesc desc(bytecodeOffset(), CallSiteKind::Indirect);
1913 CalleeDesc callee =
1914 CalleeDesc::wasmTable(codeMeta_, table, tableIndex, callIndirectId);
1915 OutOfLineCode* oob = addOutOfLineCode(
1916 new (alloc_) OutOfLineAbortingTrap(Trap::OutOfBounds, trapSiteDesc()));
1917 if (!oob) {
1918 return false;
1919 }
1920 Label* nullCheckFailed = nullptr;
1921 #ifndef WASM_HAS_HEAPREG
1922 OutOfLineCode* nullref = addOutOfLineCode(new (alloc_) OutOfLineAbortingTrap(
1923 Trap::IndirectCallToNull, trapSiteDesc()));
1924 if (!nullref) {
1925 return false;
1926 }
1927 nullCheckFailed = nullref->entry();
1928 #endif
1929 if (!tailCall) {
1930 masm.wasmCallIndirect(desc, callee, oob->entry(), nullCheckFailed,
1931 mozilla::Nothing(), fastCallOffset, slowCallOffset);
1932 } else {
1933 ReturnCallAdjustmentInfo retCallInfo = BuildReturnCallAdjustmentInfo(
1934 this->funcType(), (*codeMeta_.types)[funcTypeIndex].funcType());
1935 masm.wasmReturnCallIndirect(desc, callee, oob->entry(), nullCheckFailed,
1936 mozilla::Nothing(), retCallInfo);
1937 }
1938 return true;
1939 }
1940
1941 class OutOfLineUpdateCallRefMetrics : public OutOfLineCode {
1942 public:
1943 virtual void generate(MacroAssembler* masm) override {
1944 // Call the stub pointed to by Instance::updateCallRefMetricsStub, then
1945 // rejoin. See "Register management" in BaseCompiler::updateCallRefMetrics
1946 // for details of register management.
1947 //
1948 // The monitored call may or may not be cross-instance. The stub will only
1949 // modify `regMetrics`, `regFuncRef`, `regScratch` and `regMetrics*` (that
1950 // is, the pointed-at CallRefMetrics) and cannot fail or trap.
1951 masm->call(
1952 Address(InstanceReg, Instance::offsetOfUpdateCallRefMetricsStub()));
1953 masm->jump(rejoin());
1954 }
1955 };
1956
1957 // Generate code that updates the `callRefIndex`th CallRefMetrics attached to
1958 // the current Instance, to reflect the fact that this call site is just about
1959 // to make a call to the funcref to which WasmCallRefReg currently points.
1960 bool BaseCompiler::updateCallRefMetrics(size_t callRefIndex) {
1961 AutoCreatedBy acb(masm, "BC::updateCallRefMetrics");
1962
1963 // See declaration of CallRefMetrics for comments about assignments of
1964 // funcrefs to `CallRefMetrics::targets[]` fields.
1965
1966 // Register management: we will use three regs, `regMetrics`, `regFuncRef`,
1967 // `regScratch` as detailed below. All of them may be trashed. But
1968 // WasmCallRefReg needs to be unchanged across the update, so copy it into
1969 // `regFuncRef` and use that instead of the original.
1970 //
1971 // At entry here, at entry to the OOL code, and at entry to the stub it
1972 // calls, InstanceReg must be pointing at a valid Instance.
1973 const Register regMetrics = WasmCallRefCallScratchReg0; // CallRefMetrics*
1974 const Register regFuncRef = WasmCallRefCallScratchReg1; // FuncExtended*
1975 const Register regScratch = WasmCallRefCallScratchReg2; // scratch
1976
1977 OutOfLineCode* ool =
1978 addOutOfLineCode(new (alloc_) OutOfLineUpdateCallRefMetrics());
1979 if (!ool) {
1980 return false;
1981 }
1982
1983 // We only need one Rejoin label, so use ool->rejoin() for that.
1984
1985 // if (target == nullptr) goto Rejoin
1986 masm.branchWasmAnyRefIsNull(/*isNull=*/true, WasmCallRefReg, ool->rejoin());
1987
1988 // regFuncRef = target (make a copy of WasmCallRefReg)
1989 masm.mov(WasmCallRefReg, regFuncRef);
1990
1991 // regMetrics = thisInstance::callRefMetrics_ + <imm>
1992 //
1993 // Emit a patchable mov32 which will load the offset of the `CallRefMetrics`
1994 // stored inside the `Instance::callRefMetrics_` array
1995 const CodeOffset offsetOfCallRefOffset = masm.move32WithPatch(regScratch);
1996 masm.callRefMetricsPatches()[callRefIndex].setOffset(
1997 offsetOfCallRefOffset.offset());
1998 // Get a pointer to the `CallRefMetrics` for this call_ref
1999 masm.loadPtr(Address(InstanceReg, wasm::Instance::offsetOfCallRefMetrics()),
2000 regMetrics);
2001 masm.addPtr(regScratch, regMetrics);
2002
2003 // At this point, regFuncRef = the FuncExtended*, regMetrics = the
2004 // CallRefMetrics* and we know regFuncRef is not null.
2005 //
2006 // if (target->instance != thisInstance) goto Out-Of-Line
2007 const size_t instanceSlotOffset = FunctionExtended::offsetOfExtendedSlot(
2008 FunctionExtended::WASM_INSTANCE_SLOT);
2009 masm.loadPtr(Address(regFuncRef, instanceSlotOffset), regScratch);
2010 masm.branchPtr(Assembler::NotEqual, InstanceReg, regScratch, ool->entry());
2011
2012 // At this point, regFuncRef = the FuncExtended*, regMetrics = the
2013 // CallRefMetrics*, we know regFuncRef is not null and it's a same-instance
2014 // call.
2015 //
2016 // if (target != metrics->targets[0]) goto Out-Of-Line
2017 const size_t offsetOfTarget0 = CallRefMetrics::offsetOfTarget(0);
2018 masm.loadPtr(Address(regMetrics, offsetOfTarget0), regScratch);
2019 masm.branchPtr(Assembler::NotEqual, regScratch, regFuncRef, ool->entry());
2020
2021 // At this point, regFuncRef = the FuncExtended*, regMetrics = the
2022 // CallRefMetrics*, we know regFuncRef is not null, it's a same-instance
2023 // call, and it is to the destination `regMetrics->targets[0]`.
2024 //
2025 // metrics->count0++
2026 const size_t offsetOfCount0 = CallRefMetrics::offsetOfCount(0);
2027 masm.load32(Address(regMetrics, offsetOfCount0), regScratch);
2028 masm.add32(Imm32(1), regScratch);
2029 masm.store32(regScratch, Address(regMetrics, offsetOfCount0));
2030
2031 masm.bind(ool->rejoin());
2032 return true;
2033 }
2034
2035 bool BaseCompiler::callRef(const Stk& calleeRef, const FunctionCall& call,
2036 mozilla::Maybe<size_t> callRefIndex,
2037 CodeOffset* fastCallOffset,
2038 CodeOffset* slowCallOffset) {
2039 CallSiteDesc desc(bytecodeOffset(), CallSiteKind::FuncRef);
2040 CalleeDesc callee = CalleeDesc::wasmFuncRef();
2041
2042 loadRef(calleeRef, RegRef(WasmCallRefReg));
2043 if (compilerEnv_.mode() == CompileMode::LazyTiering) {
2044 if (!updateCallRefMetrics(*callRefIndex)) {
2045 return false;
2046 }
2047 } else {
2048 MOZ_ASSERT(callRefIndex.isNothing());
2049 }
2050
2051 masm.wasmCallRef(desc, callee, fastCallOffset, slowCallOffset);
2052 return true;
2053 }
2054
2055 void BaseCompiler::returnCallRef(const Stk& calleeRef, const FunctionCall& call,
2056 const FuncType& funcType) {
2057 CallSiteDesc desc(bytecodeOffset(), CallSiteKind::FuncRef);
2058 CalleeDesc callee = CalleeDesc::wasmFuncRef();
2059
2060 loadRef(calleeRef, RegRef(WasmCallRefReg));
2061 ReturnCallAdjustmentInfo retCallInfo =
2062 BuildReturnCallAdjustmentInfo(this->funcType(), funcType);
2063 masm.wasmReturnCallRef(desc, callee, retCallInfo);
2064 }
2065
2066 // Precondition: sync()
2067
2068 CodeOffset BaseCompiler::callImport(unsigned instanceDataOffset,
2069 const FunctionCall& call) {
2070 CallSiteDesc desc(bytecodeOffset(), CallSiteKind::Import);
2071 CalleeDesc callee = CalleeDesc::import(instanceDataOffset);
2072 return masm.wasmCallImport(desc, callee);
2073 }
2074
2075 CodeOffset BaseCompiler::builtinCall(SymbolicAddress builtin,
2076 const FunctionCall& call) {
2077 return callSymbolic(builtin, call);
2078 }
2079
2080 CodeOffset BaseCompiler::builtinInstanceMethodCall(
2081 const SymbolicAddressSignature& builtin, const ABIArg& instanceArg,
2082 const FunctionCall& call) {
2083 #ifndef RABALDR_PIN_INSTANCE
2084 // Builtin method calls assume the instance register has been set.
2085 fr.loadInstancePtr(InstanceReg);
2086 #endif
2087 CallSiteDesc desc(bytecodeOffset(), CallSiteKind::Symbolic);
2088 return masm.wasmCallBuiltinInstanceMethod(desc, instanceArg, builtin.identity,
2089 builtin.failureMode);
2090 }
2091
2092 bool BaseCompiler::pushCallResults(const FunctionCall& call, ResultType type,
2093 const StackResultsLoc& loc) {
2094 #if defined(JS_CODEGEN_ARM)
2095 // pushResults currently bypasses special case code in captureReturnedFxx()
2096 // that converts GPR results to FPR results for systemABI+softFP. If we
2097 // ever start using that combination for calls we need more code. This
2098 // assert is stronger than we need - we only care about results in return
2099 // registers - but that's OK.
2100 MOZ_ASSERT(!call.usesSystemAbi || call.hardFP);
2101 #endif
2102 return pushResults(type, fr.stackResultsBase(loc.bytes()));
2103 }
2104
2105 //////////////////////////////////////////////////////////////////////////////
2106 //
2107 // Exception handling
2108
2109 // Abstracted helper for throwing, used for throw, rethrow, and rethrowing
2110 // at the end of a series of catch blocks (if none matched the exception).
2111 bool BaseCompiler::throwFrom(RegRef exn) {
2112 pushRef(exn);
2113
2114 // ThrowException invokes a trap, and the rest is dead code.
2115 return emitInstanceCall(SASigThrowException);
2116 }
2117
2118 void BaseCompiler::loadTag(RegPtr instance, uint32_t tagIndex, RegRef tagDst) {
2119 size_t offset =
2120 Instance::offsetInData(codeMeta_.offsetOfTagInstanceData(tagIndex));
2121 masm.loadPtr(Address(instance, offset), tagDst);
2122 }
2123
2124 void BaseCompiler::consumePendingException(RegPtr instance, RegRef* exnDst,
2125 RegRef* tagDst) {
2126 RegPtr pendingAddr = RegPtr(PreBarrierReg);
2127 needPtr(pendingAddr);
2128 masm.computeEffectiveAddress(
2129 Address(instance, Instance::offsetOfPendingException()), pendingAddr);
2130 *exnDst = needRef();
2131 masm.loadPtr(Address(pendingAddr, 0), *exnDst);
2132 emitBarrieredClear(pendingAddr);
2133
2134 *tagDst = needRef();
2135 masm.computeEffectiveAddress(
2136 Address(instance, Instance::offsetOfPendingExceptionTag()), pendingAddr);
2137 masm.loadPtr(Address(pendingAddr, 0), *tagDst);
2138 emitBarrieredClear(pendingAddr);
2139 freePtr(pendingAddr);
2140 }
2141
2142 bool BaseCompiler::startTryNote(size_t* tryNoteIndex) {
2143 // Check the previous try note to ensure that we don't share an edge with
2144 // it that could lead to ambiguity. Insert a nop, if required.
2145 TryNoteVector& tryNotes = masm.tryNotes();
2146 if (tryNotes.length() > 0) {
2147 const TryNote& previous = tryNotes.back();
2148 uint32_t currentOffset = masm.currentOffset();
2149 if (previous.tryBodyBegin() == currentOffset ||
2150 previous.tryBodyEnd() == currentOffset) {
2151 masm.nop();
2152 }
2153 }
2154
2155 // Mark the beginning of the try note
2156 wasm::TryNote tryNote = wasm::TryNote();
2157 tryNote.setTryBodyBegin(masm.currentOffset());
2158 return masm.append(tryNote, tryNoteIndex);
2159 }
2160
2161 void BaseCompiler::finishTryNote(size_t tryNoteIndex) {
2162 TryNoteVector& tryNotes = masm.tryNotes();
2163 TryNote& tryNote = tryNotes[tryNoteIndex];
2164
2165 // Disallow zero-length try notes by inserting a no-op
2166 if (tryNote.tryBodyBegin() == masm.currentOffset()) {
2167 masm.nop();
2168 }
2169
2170 // Check the most recent finished try note to ensure that we don't share an
2171 // edge with it that could lead to ambiguity. Insert a nop, if required.
2172 //
2173 // Notice that finishTryNote is called in LIFO order -- using depth-first
2174 // search numbering to see if we are traversing back from a nested try to a
2175 // parent try, where we may need to ensure that the end offsets do not
2176 // coincide.
2177 //
2178 // In the case the tryNodeIndex >= mostRecentFinishedTryNoteIndex_, we have
2179 // finished a try that began after the most recent finished try, and so
2180 // startTryNote will take care of any nops.
2181 if (tryNoteIndex < mostRecentFinishedTryNoteIndex_) {
2182 const TryNote& previous = tryNotes[mostRecentFinishedTryNoteIndex_];
2183 uint32_t currentOffset = masm.currentOffset();
2184 if (previous.tryBodyEnd() == currentOffset) {
2185 masm.nop();
2186 }
2187 }
2188 mostRecentFinishedTryNoteIndex_ = tryNoteIndex;
2189
2190 // Don't set the end of the try note if we've OOM'ed, as the above nop's may
2191 // not have been placed. This is okay as this compilation will be thrown
2192 // away.
2193 if (masm.oom()) {
2194 return;
2195 }
2196
2197 // Mark the end of the try note
2198 tryNote.setTryBodyEnd(masm.currentOffset());
2199 }
2200
2201 ////////////////////////////////////////////////////////////
2202 //
2203 // Platform-specific popping and register targeting.
2204
2205 // The simple popping methods pop values into targeted registers; the caller
2206 // can free registers using standard functions. These are always called
2207 // popXForY where X says something about types and Y something about the
2208 // operation being targeted.
2209
2210 RegI32 BaseCompiler::needRotate64Temp() {
2211 #if defined(JS_CODEGEN_X86)
2212 return needI32();
2213 #elif defined(JS_CODEGEN_X64) || defined(JS_CODEGEN_ARM) || \
2214 defined(JS_CODEGEN_ARM64) || defined(JS_CODEGEN_MIPS64) || \
2215 defined(JS_CODEGEN_LOONG64) || defined(JS_CODEGEN_RISCV64)
2216 return RegI32::Invalid();
2217 #else
2218 MOZ_CRASH("BaseCompiler platform hook: needRotate64Temp");
2219 #endif
2220 }
2221
2222 void BaseCompiler::popAndAllocateForDivAndRemI32(RegI32* r0, RegI32* r1,
2223 RegI32* reserved) {
2224 #if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
2225 // r0 must be eax, and edx will be clobbered.
2226 need2xI32(specific_.eax, specific_.edx);
2227 *r1 = popI32();
2228 *r0 = popI32ToSpecific(specific_.eax);
2229 *reserved = specific_.edx;
2230 #else
2231 pop2xI32(r0, r1);
2232 #endif
2233 }
2234
2235 static void QuotientI32(MacroAssembler& masm, RegI32 rs, RegI32 rsd,
2236 RegI32 reserved, IsUnsigned isUnsigned) {
2237 #if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
2238 masm.quotient32(rs, rsd, reserved, isUnsigned);
2239 #else
2240 masm.quotient32(rs, rsd, isUnsigned);
2241 #endif
2242 }
2243
2244 static void RemainderI32(MacroAssembler& masm, RegI32 rs, RegI32 rsd,
2245 RegI32 reserved, IsUnsigned isUnsigned) {
2246 #if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
2247 masm.remainder32(rs, rsd, reserved, isUnsigned);
2248 #else
2249 masm.remainder32(rs, rsd, isUnsigned);
2250 #endif
2251 }
2252
2253 void BaseCompiler::popAndAllocateForMulI64(RegI64* r0, RegI64* r1,
2254 RegI32* temp) {
2255 #if defined(JS_CODEGEN_X64)
2256 pop2xI64(r0, r1);
2257 #elif defined(JS_CODEGEN_X86)
2258 // lhsDest must be edx:eax and rhs must not be that.
2259 needI64(specific_.edx_eax);
2260 *r1 = popI64();
2261 *r0 = popI64ToSpecific(specific_.edx_eax);
2262 *temp = needI32();
2263 #elif defined(JS_CODEGEN_MIPS64)
2264 pop2xI64(r0, r1);
2265 #elif defined(JS_CODEGEN_ARM)
2266 pop2xI64(r0, r1);
2267 *temp = needI32();
2268 #elif defined(JS_CODEGEN_ARM64)
2269 pop2xI64(r0, r1);
2270 #elif defined(JS_CODEGEN_LOONG64)
2271 pop2xI64(r0, r1);
2272 #elif defined(JS_CODEGEN_RISCV64)
2273 pop2xI64(r0, r1);
2274 #else
2275 MOZ_CRASH("BaseCompiler porting interface: popAndAllocateForMulI64");
2276 #endif
2277 }
2278
2279 #ifndef RABALDR_INT_DIV_I64_CALLOUT
2280
2281 void BaseCompiler::popAndAllocateForDivAndRemI64(RegI64* r0, RegI64* r1,
2282 RegI64* reserved,
2283 IsRemainder isRemainder) {
2284 # if defined(JS_CODEGEN_X64)
2285 // r0 must be rax, and rdx will be clobbered.
2286 need2xI64(specific_.rax, specific_.rdx);
2287 *r1 = popI64();
2288 *r0 = popI64ToSpecific(specific_.rax);
2289 *reserved = specific_.rdx;
2290 # elif defined(JS_CODEGEN_ARM64)
2291 pop2xI64(r0, r1);
2292 if (isRemainder) {
2293 *reserved = needI64();
2294 }
2295 # else
2296 pop2xI64(r0, r1);
2297 # endif
2298 }
2299
2300 static void QuotientI64(MacroAssembler& masm, RegI64 rhs, RegI64 srcDest,
2301 RegI64 reserved, IsUnsigned isUnsigned) {
2302 # if defined(JS_CODEGEN_X64)
2303 // The caller must set up the following situation.
2304 MOZ_ASSERT(srcDest.reg == rax);
2305 MOZ_ASSERT(reserved.reg == rdx);
2306 if (isUnsigned) {
2307 masm.xorq(rdx, rdx);
2308 masm.udivq(rhs.reg);
2309 } else {
2310 masm.cqo();
2311 masm.idivq(rhs.reg);
2312 }
2313 # elif defined(JS_CODEGEN_MIPS64)
2314 MOZ_ASSERT(reserved.isInvalid());
2315 if (isUnsigned) {
2316 masm.as_ddivu(srcDest.reg, rhs.reg);
2317 } else {
2318 masm.as_ddiv(srcDest.reg, rhs.reg);
2319 }
2320 masm.as_mflo(srcDest.reg);
2321 # elif defined(JS_CODEGEN_ARM64)
2322 MOZ_ASSERT(reserved.isInvalid());
2323 ARMRegister sd(srcDest.reg, 64);
2324 ARMRegister r(rhs.reg, 64);
2325 if (isUnsigned) {
2326 masm.Udiv(sd, sd, r);
2327 } else {
2328 masm.Sdiv(sd, sd, r);
2329 }
2330 # elif defined(JS_CODEGEN_LOONG64)
2331 if (isUnsigned) {
2332 masm.as_div_du(srcDest.reg, srcDest.reg, rhs.reg);
2333 } else {
2334 masm.as_div_d(srcDest.reg, srcDest.reg, rhs.reg);
2335 }
2336 # elif defined(JS_CODEGEN_RISCV64)
2337 if (isUnsigned) {
2338 masm.divu(srcDest.reg, srcDest.reg, rhs.reg);
2339 } else {
2340 masm.div(srcDest.reg, srcDest.reg, rhs.reg);
2341 }
2342 # else
2343 MOZ_CRASH("BaseCompiler platform hook: quotientI64");
2344 # endif
2345 }
2346
2347 static void RemainderI64(MacroAssembler& masm, RegI64 rhs, RegI64 srcDest,
2348 RegI64 reserved, IsUnsigned isUnsigned) {
2349 # if defined(JS_CODEGEN_X64)
2350 // The caller must set up the following situation.
2351 MOZ_ASSERT(srcDest.reg == rax);
2352 MOZ_ASSERT(reserved.reg == rdx);
2353
2354 if (isUnsigned) {
2355 masm.xorq(rdx, rdx);
2356 masm.udivq(rhs.reg);
2357 } else {
2358 masm.cqo();
2359 masm.idivq(rhs.reg);
2360 }
2361 masm.movq(rdx, rax);
2362 # elif defined(JS_CODEGEN_MIPS64)
2363 MOZ_ASSERT(reserved.isInvalid());
2364 if (isUnsigned) {
2365 masm.as_ddivu(srcDest.reg, rhs.reg);
2366 } else {
2367 masm.as_ddiv(srcDest.reg, rhs.reg);
2368 }
2369 masm.as_mfhi(srcDest.reg);
2370 # elif defined(JS_CODEGEN_ARM64)
2371 ARMRegister sd(srcDest.reg, 64);
2372 ARMRegister r(rhs.reg, 64);
2373 ARMRegister t(reserved.reg, 64);
2374 if (isUnsigned) {
2375 masm.Udiv(t, sd, r);
2376 } else {
2377 masm.Sdiv(t, sd, r);
2378 }
2379 masm.Mul(t, t, r);
2380 masm.Sub(sd, sd, t);
2381 # elif defined(JS_CODEGEN_LOONG64)
2382 if (isUnsigned) {
2383 masm.as_mod_du(srcDest.reg, srcDest.reg, rhs.reg);
2384 } else {
2385 masm.as_mod_d(srcDest.reg, srcDest.reg, rhs.reg);
2386 }
2387 # elif defined(JS_CODEGEN_RISCV64)
2388 if (isUnsigned) {
2389 masm.remu(srcDest.reg, srcDest.reg, rhs.reg);
2390 } else {
2391 masm.rem(srcDest.reg, srcDest.reg, rhs.reg);
2392 }
2393 # else
2394 MOZ_CRASH("BaseCompiler platform hook: remainderI64");
2395 # endif
2396 }
2397
2398 #endif // RABALDR_INT_DIV_I64_CALLOUT
2399
2400 RegI32 BaseCompiler::popI32RhsForShift() {
2401 #if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
2402 // r1 must be ecx for a variable shift, unless BMI2 is available.
2403 if (!Assembler::HasBMI2()) {
2404 return popI32(specific_.ecx);
2405 }
2406 #endif
2407 RegI32 r = popI32();
2408 #if defined(JS_CODEGEN_ARM)
2409 masm.and32(Imm32(31), r);
2410 #endif
2411 return r;
2412 }
2413
2414 RegI32 BaseCompiler::popI32RhsForShiftI64() {
2415 #if defined(JS_CODEGEN_X86)
2416 // A limitation in the x86 masm requires ecx here
2417 return popI32(specific_.ecx);
2418 #elif defined(JS_CODEGEN_X64)
2419 if (!Assembler::HasBMI2()) {
2420 return popI32(specific_.ecx);
2421 }
2422 return popI32();
2423 #else
2424 return popI32();
2425 #endif
2426 }
2427
2428 RegI64 BaseCompiler::popI64RhsForShift() {
2429 #if defined(JS_CODEGEN_X86)
2430 // r1 must be ecx for a variable shift.
2431 needI32(specific_.ecx);
2432 return popI64ToSpecific(widenI32(specific_.ecx));
2433 #else
2434 # if defined(JS_CODEGEN_X64)
2435 // r1 must be rcx for a variable shift, unless BMI2 is available.
2436 if (!Assembler::HasBMI2()) {
2437 needI64(specific_.rcx);
2438 return popI64ToSpecific(specific_.rcx);
2439 }
2440 # endif
2441 // No masking is necessary on 64-bit platforms, and on arm32 the masm
2442 // implementation masks.
2443 return popI64();
2444 #endif
2445 }
2446
2447 RegI32 BaseCompiler::popI32RhsForRotate() {
2448 #if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
2449 // r1 must be ecx for a variable rotate.
2450 return popI32(specific_.ecx);
2451 #else
2452 return popI32();
2453 #endif
2454 }
2455
2456 RegI64 BaseCompiler::popI64RhsForRotate() {
2457 #if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
2458 // r1 must be ecx for a variable rotate.
2459 needI32(specific_.ecx);
2460 return popI64ToSpecific(widenI32(specific_.ecx));
2461 #else
2462 return popI64();
2463 #endif
2464 }
2465
2466 void BaseCompiler::popI32ForSignExtendI64(RegI64* r0) {
2467 #if defined(JS_CODEGEN_X86)
2468 // r0 must be edx:eax for cdq
2469 need2xI32(specific_.edx, specific_.eax);
2470 *r0 = specific_.edx_eax;
2471 popI32ToSpecific(specific_.eax);
2472 #else
2473 *r0 = widenI32(popI32());
2474 #endif
2475 }
2476
2477 void BaseCompiler::popI64ForSignExtendI64(RegI64* r0) {
2478 #if defined(JS_CODEGEN_X86)
2479 // r0 must be edx:eax for cdq
2480 need2xI32(specific_.edx, specific_.eax);
2481 // Low on top, high underneath
2482 *r0 = popI64ToSpecific(specific_.edx_eax);
2483 #else
2484 *r0 = popI64();
2485 #endif
2486 }
2487
2488 class OutOfLineTruncateCheckF32OrF64ToI32 : public OutOfLineCode {
2489 AnyReg src;
2490 RegI32 dest;
2491 TruncFlags flags;
2492 TrapSiteDesc trapSiteDesc;
2493
2494 public:
2495 OutOfLineTruncateCheckF32OrF64ToI32(AnyReg src, RegI32 dest, TruncFlags flags,
2496 TrapSiteDesc trapSiteDesc)
2497 : src(src), dest(dest), flags(flags), trapSiteDesc(trapSiteDesc) {}
2498
2499 virtual void generate(MacroAssembler* masm) override {
2500 if (src.tag == AnyReg::F32) {
2501 masm->oolWasmTruncateCheckF32ToI32(src.f32(), dest, flags, trapSiteDesc,
2502 rejoin());
2503 } else if (src.tag == AnyReg::F64) {
2504 masm->oolWasmTruncateCheckF64ToI32(src.f64(), dest, flags, trapSiteDesc,
2505 rejoin());
2506 } else {
2507 MOZ_CRASH("unexpected type");
2508 }
2509 }
2510 };
2511
2512 bool BaseCompiler::truncateF32ToI32(RegF32 src, RegI32 dest, TruncFlags flags) {
2513 OutOfLineCode* ool =
2514 addOutOfLineCode(new (alloc_) OutOfLineTruncateCheckF32OrF64ToI32(
2515 AnyReg(src), dest, flags, trapSiteDesc()));
2516 if (!ool) {
2517 return false;
2518 }
2519 bool isSaturating = flags & TRUNC_SATURATING;
2520 if (flags & TRUNC_UNSIGNED) {
2521 masm.wasmTruncateFloat32ToUInt32(src, dest, isSaturating, ool->entry());
2522 } else {
2523 masm.wasmTruncateFloat32ToInt32(src, dest, isSaturating, ool->entry());
2524 }
2525 masm.bind(ool->rejoin());
2526 return true;
2527 }
2528
2529 bool BaseCompiler::truncateF64ToI32(RegF64 src, RegI32 dest, TruncFlags flags) {
2530 OutOfLineCode* ool =
2531 addOutOfLineCode(new (alloc_) OutOfLineTruncateCheckF32OrF64ToI32(
2532 AnyReg(src), dest, flags, trapSiteDesc()));
2533 if (!ool) {
2534 return false;
2535 }
2536 bool isSaturating = flags & TRUNC_SATURATING;
2537 if (flags & TRUNC_UNSIGNED) {
2538 masm.wasmTruncateDoubleToUInt32(src, dest, isSaturating, ool->entry());
2539 } else {
2540 masm.wasmTruncateDoubleToInt32(src, dest, isSaturating, ool->entry());
2541 }
2542 masm.bind(ool->rejoin());
2543 return true;
2544 }
2545
2546 class OutOfLineTruncateCheckF32OrF64ToI64 : public OutOfLineCode {
2547 AnyReg src;
2548 RegI64 dest;
2549 TruncFlags flags;
2550 TrapSiteDesc trapSiteDesc;
2551
2552 public:
2553 OutOfLineTruncateCheckF32OrF64ToI64(AnyReg src, RegI64 dest, TruncFlags flags,
2554 TrapSiteDesc trapSiteDesc)
2555 : src(src), dest(dest), flags(flags), trapSiteDesc(trapSiteDesc) {}
2556
2557 virtual void generate(MacroAssembler* masm) override {
2558 if (src.tag == AnyReg::F32) {
2559 masm->oolWasmTruncateCheckF32ToI64(src.f32(), dest, flags, trapSiteDesc,
2560 rejoin());
2561 } else if (src.tag == AnyReg::F64) {
2562 masm->oolWasmTruncateCheckF64ToI64(src.f64(), dest, flags, trapSiteDesc,
2563 rejoin());
2564 } else {
2565 MOZ_CRASH("unexpected type");
2566 }
2567 }
2568 };
2569
2570 #ifndef RABALDR_FLOAT_TO_I64_CALLOUT
2571
2572 RegF64 BaseCompiler::needTempForFloatingToI64(TruncFlags flags) {
2573 # if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
2574 if (flags & TRUNC_UNSIGNED) {
2575 return needF64();
2576 }
2577 # endif
2578 return RegF64::Invalid();
2579 }
2580
2581 bool BaseCompiler::truncateF32ToI64(RegF32 src, RegI64 dest, TruncFlags flags,
2582 RegF64 temp) {
2583 OutOfLineCode* ool =
2584 addOutOfLineCode(new (alloc_) OutOfLineTruncateCheckF32OrF64ToI64(
2585 AnyReg(src), dest, flags, trapSiteDesc()));
2586 if (!ool) {
2587 return false;
2588 }
2589 bool isSaturating = flags & TRUNC_SATURATING;
2590 if (flags & TRUNC_UNSIGNED) {
2591 masm.wasmTruncateFloat32ToUInt64(src, dest, isSaturating, ool->entry(),
2592 ool->rejoin(), temp);
2593 } else {
2594 masm.wasmTruncateFloat32ToInt64(src, dest, isSaturating, ool->entry(),
2595 ool->rejoin(), temp);
2596 }
2597 return true;
2598 }
2599
2600 bool BaseCompiler::truncateF64ToI64(RegF64 src, RegI64 dest, TruncFlags flags,
2601 RegF64 temp) {
2602 OutOfLineCode* ool =
2603 addOutOfLineCode(new (alloc_) OutOfLineTruncateCheckF32OrF64ToI64(
2604 AnyReg(src), dest, flags, trapSiteDesc()));
2605 if (!ool) {
2606 return false;
2607 }
2608 bool isSaturating = flags & TRUNC_SATURATING;
2609 if (flags & TRUNC_UNSIGNED) {
2610 masm.wasmTruncateDoubleToUInt64(src, dest, isSaturating, ool->entry(),
2611 ool->rejoin(), temp);
2612 } else {
2613 masm.wasmTruncateDoubleToInt64(src, dest, isSaturating, ool->entry(),
2614 ool->rejoin(), temp);
2615 }
2616 return true;
2617 }
2618
2619 #endif // RABALDR_FLOAT_TO_I64_CALLOUT
2620
2621 #ifndef RABALDR_I64_TO_FLOAT_CALLOUT
2622
2623 RegI32 BaseCompiler::needConvertI64ToFloatTemp(ValType to, bool isUnsigned) {
2624 bool needs = false;
2625 if (to == ValType::F64) {
2626 needs = isUnsigned && masm.convertUInt64ToDoubleNeedsTemp();
2627 } else {
2628 # if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
2629 needs = true;
2630 # endif
2631 }
2632 return needs ? needI32() : RegI32::Invalid();
2633 }
2634
2635 void BaseCompiler::convertI64ToF32(RegI64 src, bool isUnsigned, RegF32 dest,
2636 RegI32 temp) {
2637 if (isUnsigned) {
2638 masm.convertUInt64ToFloat32(src, dest, temp);
2639 } else {
2640 masm.convertInt64ToFloat32(src, dest);
2641 }
2642 }
2643
2644 void BaseCompiler::convertI64ToF64(RegI64 src, bool isUnsigned, RegF64 dest,
2645 RegI32 temp) {
2646 if (isUnsigned) {
2647 masm.convertUInt64ToDouble(src, dest, temp);
2648 } else {
2649 masm.convertInt64ToDouble(src, dest);
2650 }
2651 }
2652
2653 #endif // RABALDR_I64_TO_FLOAT_CALLOUT
2654
2655 //////////////////////////////////////////////////////////////////////
2656 //
2657 // Global variable access.
2658
2659 Address BaseCompiler::addressOfGlobalVar(const GlobalDesc& global, RegPtr tmp) {
2660 uint32_t globalToInstanceOffset = Instance::offsetInData(global.offset());
2661 #ifdef RABALDR_PIN_INSTANCE
2662 movePtr(RegPtr(InstanceReg), tmp);
2663 #else
2664 fr.loadInstancePtr(tmp);
2665 #endif
2666 if (global.isIndirect()) {
2667 masm.loadPtr(Address(tmp, globalToInstanceOffset), tmp);
2668 return Address(tmp, 0);
2669 }
2670 return Address(tmp, globalToInstanceOffset);
2671 }
2672
2673 //////////////////////////////////////////////////////////////////////
2674 //
2675 // Table access.
2676
2677 Address BaseCompiler::addressOfTableField(uint32_t tableIndex,
2678 uint32_t fieldOffset,
2679 RegPtr instance) {
2680 uint32_t tableToInstanceOffset = wasm::Instance::offsetInData(
2681 codeMeta_.offsetOfTableInstanceData(tableIndex) + fieldOffset);
2682 return Address(instance, tableToInstanceOffset);
2683 }
2684
2685 void BaseCompiler::loadTableLength(uint32_t tableIndex, RegPtr instance,
2686 RegI32 length) {
2687 masm.load32(addressOfTableField(
2688 tableIndex, offsetof(TableInstanceData, length), instance),
2689 length);
2690 }
2691
2692 void BaseCompiler::loadTableElements(uint32_t tableIndex, RegPtr instance,
2693 RegPtr elements) {
2694 masm.loadPtr(addressOfTableField(
2695 tableIndex, offsetof(TableInstanceData, elements), instance),
2696 elements);
2697 }
2698
2699 //////////////////////////////////////////////////////////////////////////////
2700 //
2701 // Basic emitters for simple operators.
2702
2703 static void AddI32(MacroAssembler& masm, RegI32 rs, RegI32 rsd) {
2704 masm.add32(rs, rsd);
2705 }
2706
2707 static void AddImmI32(MacroAssembler& masm, int32_t c, RegI32 rsd) {
2708 masm.add32(Imm32(c), rsd);
2709 }
2710
2711 static void SubI32(MacroAssembler& masm, RegI32 rs, RegI32 rsd) {
2712 masm.sub32(rs, rsd);
2713 }
2714
2715 static void SubImmI32(MacroAssembler& masm, int32_t c, RegI32 rsd) {
2716 masm.sub32(Imm32(c), rsd);
2717 }
2718
2719 static void MulI32(MacroAssembler& masm, RegI32 rs, RegI32 rsd) {
2720 masm.mul32(rs, rsd);
2721 }
2722
2723 static void OrI32(MacroAssembler& masm, RegI32 rs, RegI32 rsd) {
2724 masm.or32(rs, rsd);
2725 }
2726
2727 static void OrImmI32(MacroAssembler& masm, int32_t c, RegI32 rsd) {
2728 masm.or32(Imm32(c), rsd);
2729 }
2730
2731 static void AndI32(MacroAssembler& masm, RegI32 rs, RegI32 rsd) {
2732 masm.and32(rs, rsd);
2733 }
2734
2735 static void AndImmI32(MacroAssembler& masm, int32_t c, RegI32 rsd) {
2736 masm.and32(Imm32(c), rsd);
2737 }
2738
2739 static void XorI32(MacroAssembler& masm, RegI32 rs, RegI32 rsd) {
2740 masm.xor32(rs, rsd);
2741 }
2742
2743 static void XorImmI32(MacroAssembler& masm, int32_t c, RegI32 rsd) {
2744 masm.xor32(Imm32(c), rsd);
2745 }
2746
2747 static void ClzI32(MacroAssembler& masm, RegI32 rsd) {
2748 masm.clz32(rsd, rsd, IsKnownNotZero(false));
2749 }
2750
2751 static void CtzI32(MacroAssembler& masm, RegI32 rsd) {
2752 masm.ctz32(rsd, rsd, IsKnownNotZero(false));
2753 }
2754
2755 // Currently common to PopcntI32 and PopcntI64
2756 static RegI32 PopcntTemp(BaseCompiler& bc) {
2757 #if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
2758 return AssemblerX86Shared::HasPOPCNT() ? RegI32::Invalid() : bc.needI32();
2759 #elif defined(JS_CODEGEN_ARM) || defined(JS_CODEGEN_ARM64) || \
2760 defined(JS_CODEGEN_MIPS64) || defined(JS_CODEGEN_LOONG64) || \
2761 defined(JS_CODEGEN_RISCV64)
2762 return bc.needI32();
2763 #else
2764 MOZ_CRASH("BaseCompiler platform hook: PopcntTemp");
2765 #endif
2766 }
2767
2768 static void PopcntI32(BaseCompiler& bc, RegI32 rsd, RegI32 temp) {
2769 bc.masm.popcnt32(rsd, rsd, temp);
2770 }
2771
2772 static void ShlI32(MacroAssembler& masm, RegI32 rs, RegI32 rsd) {
2773 masm.lshift32(rs, rsd);
2774 }
2775
2776 static void ShlImmI32(MacroAssembler& masm, int32_t c, RegI32 rsd) {
2777 masm.lshift32(Imm32(c & 31), rsd);
2778 }
2779
2780 static void ShrI32(MacroAssembler& masm, RegI32 rs, RegI32 rsd) {
2781 masm.rshift32Arithmetic(rs, rsd);
2782 }
2783
2784 static void ShrImmI32(MacroAssembler& masm, int32_t c, RegI32 rsd) {
2785 masm.rshift32Arithmetic(Imm32(c & 31), rsd);
2786 }
2787
2788 static void ShrUI32(MacroAssembler& masm, RegI32 rs, RegI32 rsd) {
2789 masm.rshift32(rs, rsd);
2790 }
2791
2792 static void ShrUImmI32(MacroAssembler& masm, int32_t c, RegI32 rsd) {
2793 masm.rshift32(Imm32(c & 31), rsd);
2794 }
2795
2796 static void RotlI32(MacroAssembler& masm, RegI32 rs, RegI32 rsd) {
2797 masm.rotateLeft(rs, rsd, rsd);
2798 }
2799
2800 static void RotlImmI32(MacroAssembler& masm, int32_t c, RegI32 rsd) {
2801 masm.rotateLeft(Imm32(c & 31), rsd, rsd);
2802 }
2803
2804 static void RotrI32(MacroAssembler& masm, RegI32 rs, RegI32 rsd) {
2805 masm.rotateRight(rs, rsd, rsd);
2806 }
2807
2808 static void RotrImmI32(MacroAssembler& masm, int32_t c, RegI32 rsd) {
2809 masm.rotateRight(Imm32(c & 31), rsd, rsd);
2810 }
2811
2812 static void EqzI32(MacroAssembler& masm, RegI32 rsd) {
2813 masm.cmp32Set(Assembler::Equal, rsd, Imm32(0), rsd);
2814 }
2815
2816 static void WrapI64ToI32(MacroAssembler& masm, RegI64 rs, RegI32 rd) {
2817 masm.move64To32(rs, rd);
2818 }
2819
2820 static void AddI64(MacroAssembler& masm, RegI64 rs, RegI64 rsd) {
2821 masm.add64(rs, rsd);
2822 }
2823
2824 static void AddImmI64(MacroAssembler& masm, int64_t c, RegI64 rsd) {
2825 masm.add64(Imm64(c), rsd);
2826 }
2827
2828 static void SubI64(MacroAssembler& masm, RegI64 rs, RegI64 rsd) {
2829 masm.sub64(rs, rsd);
2830 }
2831
2832 static void SubImmI64(MacroAssembler& masm, int64_t c, RegI64 rsd) {
2833 masm.sub64(Imm64(c), rsd);
2834 }
2835
2836 static void OrI64(MacroAssembler& masm, RegI64 rs, RegI64 rsd) {
2837 masm.or64(rs, rsd);
2838 }
2839
2840 static void OrImmI64(MacroAssembler& masm, int64_t c, RegI64 rsd) {
2841 masm.or64(Imm64(c), rsd);
2842 }
2843
2844 static void AndI64(MacroAssembler& masm, RegI64 rs, RegI64 rsd) {
2845 masm.and64(rs, rsd);
2846 }
2847
2848 static void AndImmI64(MacroAssembler& masm, int64_t c, RegI64 rsd) {
2849 masm.and64(Imm64(c), rsd);
2850 }
2851
2852 static void XorI64(MacroAssembler& masm, RegI64 rs, RegI64 rsd) {
2853 masm.xor64(rs, rsd);
2854 }
2855
2856 static void XorImmI64(MacroAssembler& masm, int64_t c, RegI64 rsd) {
2857 masm.xor64(Imm64(c), rsd);
2858 }
2859
2860 static void ClzI64(BaseCompiler& bc, RegI64 rsd) { bc.masm.clz64(rsd, rsd); }
2861
2862 static void CtzI64(BaseCompiler& bc, RegI64 rsd) { bc.masm.ctz64(rsd, rsd); }
2863
2864 static void PopcntI64(BaseCompiler& bc, RegI64 rsd, RegI32 temp) {
2865 bc.masm.popcnt64(rsd, rsd, temp);
2866 }
2867
2868 static void ShlI64(BaseCompiler& bc, RegI64 rs, RegI64 rsd) {
2869 bc.masm.lshift64(bc.lowPart(rs), rsd);
2870 }
2871
2872 static void ShlImmI64(MacroAssembler& masm, int64_t c, RegI64 rsd) {
2873 masm.lshift64(Imm32(c & 63), rsd);
2874 }
2875
2876 static void ShrI64(BaseCompiler& bc, RegI64 rs, RegI64 rsd) {
2877 bc.masm.rshift64Arithmetic(bc.lowPart(rs), rsd);
2878 }
2879
2880 static void ShrImmI64(MacroAssembler& masm, int64_t c, RegI64 rsd) {
2881 masm.rshift64Arithmetic(Imm32(c & 63), rsd);
2882 }
2883
2884 static void ShrUI64(BaseCompiler& bc, RegI64 rs, RegI64 rsd) {
2885 bc.masm.rshift64(bc.lowPart(rs), rsd);
2886 }
2887
2888 static void ShrUImmI64(MacroAssembler& masm, int64_t c, RegI64 rsd) {
2889 masm.rshift64(Imm32(c & 63), rsd);
2890 }
2891
2892 static void EqzI64(MacroAssembler& masm, RegI64 rs, RegI32 rd) {
2893 #ifdef JS_PUNBOX64
2894 masm.cmpPtrSet(Assembler::Equal, rs.reg, ImmWord(0), rd);
2895 #else
2896 MOZ_ASSERT(rs.low == rd);
2897 masm.or32(rs.high, rs.low);
2898 masm.cmp32Set(Assembler::Equal, rs.low, Imm32(0), rd);
2899 #endif
2900 }
2901
2902 static void AddF64(MacroAssembler& masm, RegF64 rs, RegF64 rsd) {
2903 masm.addDouble(rs, rsd);
2904 }
2905
2906 static void SubF64(MacroAssembler& masm, RegF64 rs, RegF64 rsd) {
2907 masm.subDouble(rs, rsd);
2908 }
2909
2910 static void MulF64(MacroAssembler& masm, RegF64 rs, RegF64 rsd) {
2911 masm.mulDouble(rs, rsd);
2912 }
2913
2914 static void DivF64(MacroAssembler& masm, RegF64 rs, RegF64 rsd) {
2915 masm.divDouble(rs, rsd);
2916 }
2917
2918 static void MinF64(BaseCompiler& bc, RegF64 rs, RegF64 rsd) {
2919 // Convert signaling NaN to quiet NaNs.
2920 //
2921 // TODO / OPTIMIZE (bug 1316824): see comment in MinF32.
2922 #ifdef RABALDR_SCRATCH_F64
2923 ScratchF64 zero(bc.ra);
2924 #else
2925 ScratchF64 zero(bc.masm);
2926 #endif
2927 bc.masm.loadConstantDouble(0, zero);
2928 bc.masm.subDouble(zero, rsd);
2929 bc.masm.subDouble(zero, rs);
2930 bc.masm.minDouble(rs, rsd, HandleNaNSpecially(true));
2931 }
2932
2933 static void MaxF64(BaseCompiler& bc, RegF64 rs, RegF64 rsd) {
2934 // Convert signaling NaN to quiet NaNs.
2935 //
2936 // TODO / OPTIMIZE (bug 1316824): see comment in MinF32.
2937 #ifdef RABALDR_SCRATCH_F64
2938 ScratchF64 zero(bc.ra);
2939 #else
2940 ScratchF64 zero(bc.masm);
2941 #endif
2942 bc.masm.loadConstantDouble(0, zero);
2943 bc.masm.subDouble(zero, rsd);
2944 bc.masm.subDouble(zero, rs);
2945 bc.masm.maxDouble(rs, rsd, HandleNaNSpecially(true));
2946 }
2947
2948 static void CopysignF64(MacroAssembler& masm, RegF64 rs, RegF64 rsd,
2949 RegI64 temp0, RegI64 temp1) {
2950 masm.moveDoubleToGPR64(rsd, temp0);
2951 masm.moveDoubleToGPR64(rs, temp1);
2952 masm.and64(Imm64(INT64_MAX), temp0);
2953 masm.and64(Imm64(INT64_MIN), temp1);
2954 masm.or64(temp1, temp0);
2955 masm.moveGPR64ToDouble(temp0, rsd);
2956 }
2957
2958 static void AbsF64(MacroAssembler& masm, RegF64 rsd) {
2959 masm.absDouble(rsd, rsd);
2960 }
2961
2962 static void NegateF64(MacroAssembler& masm, RegF64 rsd) {
2963 masm.negateDouble(rsd);
2964 }
2965
2966 static void SqrtF64(MacroAssembler& masm, RegF64 rsd) {
2967 masm.sqrtDouble(rsd, rsd);
2968 }
2969
2970 static void AddF32(MacroAssembler& masm, RegF32 rs, RegF32 rsd) {
2971 masm.addFloat32(rs, rsd);
2972 }
2973
2974 static void SubF32(MacroAssembler& masm, RegF32 rs, RegF32 rsd) {
2975 masm.subFloat32(rs, rsd);
2976 }
2977
2978 static void MulF32(MacroAssembler& masm, RegF32 rs, RegF32 rsd) {
2979 masm.mulFloat32(rs, rsd);
2980 }
2981
2982 static void DivF32(MacroAssembler& masm, RegF32 rs, RegF32 rsd) {
2983 masm.divFloat32(rs, rsd);
2984 }
2985
2986 static void MinF32(BaseCompiler& bc, RegF32 rs, RegF32 rsd) {
2987 // Convert signaling NaN to quiet NaNs.
2988 //
2989 // TODO / OPTIMIZE (bug 1316824): Don't do this if one of the operands
2990 // is known to be a constant.
2991 #ifdef RABALDR_SCRATCH_F32
2992 ScratchF32 zero(bc.ra);
2993 #else
2994 ScratchF32 zero(bc.masm);
2995 #endif
2996 bc.masm.loadConstantFloat32(0.f, zero);
2997 bc.masm.subFloat32(zero, rsd);
2998 bc.masm.subFloat32(zero, rs);
2999 bc.masm.minFloat32(rs, rsd, HandleNaNSpecially(true));
3000 }
3001
3002 static void MaxF32(BaseCompiler& bc, RegF32 rs, RegF32 rsd) {
3003 // Convert signaling NaN to quiet NaNs.
3004 //
3005 // TODO / OPTIMIZE (bug 1316824): see comment in MinF32.
3006 #ifdef RABALDR_SCRATCH_F32
3007 ScratchF32 zero(bc.ra);
3008 #else
3009 ScratchF32 zero(bc.masm);
3010 #endif
3011 bc.masm.loadConstantFloat32(0.f, zero);
3012 bc.masm.subFloat32(zero, rsd);
3013 bc.masm.subFloat32(zero, rs);
3014 bc.masm.maxFloat32(rs, rsd, HandleNaNSpecially(true));
3015 }
3016
3017 static void CopysignF32(MacroAssembler& masm, RegF32 rs, RegF32 rsd,
3018 RegI32 temp0, RegI32 temp1) {
3019 masm.moveFloat32ToGPR(rsd, temp0);
3020 masm.moveFloat32ToGPR(rs, temp1);
3021 masm.and32(Imm32(INT32_MAX), temp0);
3022 masm.and32(Imm32(INT32_MIN), temp1);
3023 masm.or32(temp1, temp0);
3024 masm.moveGPRToFloat32(temp0, rsd);
3025 }
3026
3027 static void AbsF32(MacroAssembler& masm, RegF32 rsd) {
3028 masm.absFloat32(rsd, rsd);
3029 }
3030
3031 static void NegateF32(MacroAssembler& masm, RegF32 rsd) {
3032 masm.negateFloat(rsd);
3033 }
3034
3035 static void SqrtF32(MacroAssembler& masm, RegF32 rsd) {
3036 masm.sqrtFloat32(rsd, rsd);
3037 }
3038
3039 #ifndef RABALDR_I64_TO_FLOAT_CALLOUT
3040 static void ConvertI64ToF32(MacroAssembler& masm, RegI64 rs, RegF32 rd) {
3041 masm.convertInt64ToFloat32(rs, rd);
3042 }
3043
3044 static void ConvertI64ToF64(MacroAssembler& masm, RegI64 rs, RegF64 rd) {
3045 masm.convertInt64ToDouble(rs, rd);
3046 }
3047 #endif
3048
3049 static void ReinterpretF32AsI32(MacroAssembler& masm, RegF32 rs, RegI32 rd) {
3050 masm.moveFloat32ToGPR(rs, rd);
3051 }
3052
3053 static void ReinterpretF64AsI64(MacroAssembler& masm, RegF64 rs, RegI64 rd) {
3054 masm.moveDoubleToGPR64(rs, rd);
3055 }
3056
3057 static void ConvertF64ToF32(MacroAssembler& masm, RegF64 rs, RegF32 rd) {
3058 masm.convertDoubleToFloat32(rs, rd);
3059 }
3060
3061 static void ConvertI32ToF32(MacroAssembler& masm, RegI32 rs, RegF32 rd) {
3062 masm.convertInt32ToFloat32(rs, rd);
3063 }
3064
3065 static void ConvertU32ToF32(MacroAssembler& masm, RegI32 rs, RegF32 rd) {
3066 masm.convertUInt32ToFloat32(rs, rd);
3067 }
3068
3069 static void ConvertF32ToF64(MacroAssembler& masm, RegF32 rs, RegF64 rd) {
3070 masm.convertFloat32ToDouble(rs, rd);
3071 }
3072
3073 static void ConvertI32ToF64(MacroAssembler& masm, RegI32 rs, RegF64 rd) {
3074 masm.convertInt32ToDouble(rs, rd);
3075 }
3076
3077 static void ConvertU32ToF64(MacroAssembler& masm, RegI32 rs, RegF64 rd) {
3078 masm.convertUInt32ToDouble(rs, rd);
3079 }
3080
3081 static void ReinterpretI32AsF32(MacroAssembler& masm, RegI32 rs, RegF32 rd) {
3082 masm.moveGPRToFloat32(rs, rd);
3083 }
3084
3085 static void ReinterpretI64AsF64(MacroAssembler& masm, RegI64 rs, RegF64 rd) {
3086 masm.moveGPR64ToDouble(rs, rd);
3087 }
3088
3089 static void ExtendI32_8(BaseCompiler& bc, RegI32 rsd) {
3090 #ifdef JS_CODEGEN_X86
3091 if (!bc.ra.isSingleByteI32(rsd)) {
3092 ScratchI8 scratch(bc.ra);
3093 bc.masm.move32(rsd, scratch);
3094 bc.masm.move8SignExtend(scratch, rsd);
3095 return;
3096 }
3097 #endif
3098 bc.masm.move8SignExtend(rsd, rsd);
3099 }
3100
3101 static void ExtendI32_16(MacroAssembler& masm, RegI32 rsd) {
3102 masm.move16SignExtend(rsd, rsd);
3103 }
3104
3105 void BaseCompiler::emitMultiplyI64() {
3106 RegI64 r, rs;
3107 RegI32 temp;
3108 popAndAllocateForMulI64(&r, &rs, &temp);
3109 masm.mul64(rs, r, temp);
3110 maybeFree(temp);
3111 freeI64(rs);
3112 pushI64(r);
3113 }
3114
3115 template <typename RegType, typename IntType>
3116 void BaseCompiler::quotientOrRemainder(
3117 RegType rs, RegType rsd, RegType reserved, IsUnsigned isUnsigned,
3118 ZeroOnOverflow zeroOnOverflow, bool isConst, IntType c,
3119 void (*operate)(MacroAssembler& masm, RegType rs, RegType rsd,
3120 RegType reserved, IsUnsigned isUnsigned)) {
3121 Label done;
3122 if (!isConst || c == 0) {
3123 checkDivideByZero(rs);
3124 }
3125 if (!isUnsigned && (!isConst || c == -1)) {
3126 checkDivideSignedOverflow(rs, rsd, &done, zeroOnOverflow);
3127 }
3128 operate(masm, rs, rsd, reserved, isUnsigned);
3129 masm.bind(&done);
3130 }
3131
3132 void BaseCompiler::emitQuotientI32() {
3133 int32_t c;
3134 uint_fast8_t power;
3135 if (popConstPositivePowerOfTwo(&c, &power, 0)) {
3136 if (power != 0) {
3137 RegI32 r = popI32();
3138 Label positive;
3139 masm.branchTest32(Assembler::NotSigned, r, r, &positive);
3140 masm.add32(Imm32(c - 1), r);
3141 masm.bind(&positive);
3142
3143 masm.rshift32Arithmetic(Imm32(power & 31), r);
3144 pushI32(r);
3145 }
3146 } else {
3147 bool isConst = peekConst(&c);
3148 RegI32 r, rs, reserved;
3149 popAndAllocateForDivAndRemI32(&r, &rs, &reserved);
3150 quotientOrRemainder(rs, r, reserved, IsUnsigned(false),
3151 ZeroOnOverflow(false), isConst, c, QuotientI32);
3152 maybeFree(reserved);
3153 freeI32(rs);
3154 pushI32(r);
3155 }
3156 }
3157
3158 void BaseCompiler::emitQuotientU32() {
3159 int32_t c;
3160 uint_fast8_t power;
3161 if (popConstPositivePowerOfTwo(&c, &power, 0)) {
3162 if (power != 0) {
3163 RegI32 r = popI32();
3164 masm.rshift32(Imm32(power & 31), r);
3165 pushI32(r);
3166 }
3167 } else {
3168 bool isConst = peekConst(&c);
3169 RegI32 r, rs, reserved;
3170 popAndAllocateForDivAndRemI32(&r, &rs, &reserved);
3171 quotientOrRemainder(rs, r, reserved, IsUnsigned(true),
3172 ZeroOnOverflow(false), isConst, c, QuotientI32);
3173 maybeFree(reserved);
3174 freeI32(rs);
3175 pushI32(r);
3176 }
3177 }
3178
3179 void BaseCompiler::emitRemainderI32() {
3180 int32_t c;
3181 uint_fast8_t power;
3182 if (popConstPositivePowerOfTwo(&c, &power, 1)) {
3183 RegI32 r = popI32();
3184 RegI32 temp = needI32();
3185 moveI32(r, temp);
3186
3187 Label positive;
3188 masm.branchTest32(Assembler::NotSigned, temp, temp, &positive);
3189 masm.add32(Imm32(c - 1), temp);
3190 masm.bind(&positive);
3191
3192 masm.rshift32Arithmetic(Imm32(power & 31), temp);
3193 masm.lshift32(Imm32(power & 31), temp);
3194 masm.sub32(temp, r);
3195 freeI32(temp);
3196
3197 pushI32(r);
3198 } else {
3199 bool isConst = peekConst(&c);
3200 RegI32 r, rs, reserved;
3201 popAndAllocateForDivAndRemI32(&r, &rs, &reserved);
3202 quotientOrRemainder(rs, r, reserved, IsUnsigned(false),
3203 ZeroOnOverflow(true), isConst, c, RemainderI32);
3204 maybeFree(reserved);
3205 freeI32(rs);
3206 pushI32(r);
3207 }
3208 }
3209
3210 void BaseCompiler::emitRemainderU32() {
3211 int32_t c;
3212 uint_fast8_t power;
3213 if (popConstPositivePowerOfTwo(&c, &power, 1)) {
3214 RegI32 r = popI32();
3215 masm.and32(Imm32(c - 1), r);
3216 pushI32(r);
3217 } else {
3218 bool isConst = peekConst(&c);
3219 RegI32 r, rs, reserved;
3220 popAndAllocateForDivAndRemI32(&r, &rs, &reserved);
3221 quotientOrRemainder(rs, r, reserved, IsUnsigned(true), ZeroOnOverflow(true),
3222 isConst, c, RemainderI32);
3223 maybeFree(reserved);
3224 freeI32(rs);
3225 pushI32(r);
3226 }
3227 }
3228
3229 #ifndef RABALDR_INT_DIV_I64_CALLOUT
3230 void BaseCompiler::emitQuotientI64() {
3231 int64_t c;
3232 uint_fast8_t power;
3233 if (popConstPositivePowerOfTwo(&c, &power, 0)) {
3234 if (power != 0) {
3235 RegI64 r = popI64();
3236 Label positive;
3237 masm.branchTest64(Assembler::NotSigned, r, r, &positive);
3238 masm.add64(Imm64(c - 1), r);
3239 masm.bind(&positive);
3240
3241 masm.rshift64Arithmetic(Imm32(power & 63), r);
3242 pushI64(r);
3243 }
3244 } else {
3245 bool isConst = peekConst(&c);
3246 RegI64 r, rs, reserved;
3247 popAndAllocateForDivAndRemI64(&r, &rs, &reserved, IsRemainder(false));
3248 quotientOrRemainder(rs, r, reserved, IsUnsigned(false),
3249 ZeroOnOverflow(false), isConst, c, QuotientI64);
3250 maybeFree(reserved);
3251 freeI64(rs);
3252 pushI64(r);
3253 }
3254 }
3255
3256 void BaseCompiler::emitQuotientU64() {
3257 int64_t c;
3258 uint_fast8_t power;
3259 if (popConstPositivePowerOfTwo(&c, &power, 0)) {
3260 if (power != 0) {
3261 RegI64 r = popI64();
3262 masm.rshift64(Imm32(power & 63), r);
3263 pushI64(r);
3264 }
3265 } else {
3266 bool isConst = peekConst(&c);
3267 RegI64 r, rs, reserved;
3268 popAndAllocateForDivAndRemI64(&r, &rs, &reserved, IsRemainder(false));
3269 quotientOrRemainder(rs, r, reserved, IsUnsigned(true),
3270 ZeroOnOverflow(false), isConst, c, QuotientI64);
3271 maybeFree(reserved);
3272 freeI64(rs);
3273 pushI64(r);
3274 }
3275 }
3276
3277 void BaseCompiler::emitRemainderI64() {
3278 int64_t c;
3279 uint_fast8_t power;
3280 if (popConstPositivePowerOfTwo(&c, &power, 1)) {
3281 RegI64 r = popI64();
3282 RegI64 temp = needI64();
3283 moveI64(r, temp);
3284
3285 Label positive;
3286 masm.branchTest64(Assembler::NotSigned, temp, temp, &positive);
3287 masm.add64(Imm64(c - 1), temp);
3288 masm.bind(&positive);
3289
3290 masm.rshift64Arithmetic(Imm32(power & 63), temp);
3291 masm.lshift64(Imm32(power & 63), temp);
3292 masm.sub64(temp, r);
3293 freeI64(temp);
3294
3295 pushI64(r);
3296 } else {
3297 bool isConst = peekConst(&c);
3298 RegI64 r, rs, reserved;
3299 popAndAllocateForDivAndRemI64(&r, &rs, &reserved, IsRemainder(true));
3300 quotientOrRemainder(rs, r, reserved, IsUnsigned(false),
3301 ZeroOnOverflow(true), isConst, c, RemainderI64);
3302 maybeFree(reserved);
3303 freeI64(rs);
3304 pushI64(r);
3305 }
3306 }
3307
3308 void BaseCompiler::emitRemainderU64() {
3309 int64_t c;
3310 uint_fast8_t power;
3311 if (popConstPositivePowerOfTwo(&c, &power, 1)) {
3312 RegI64 r = popI64();
3313 masm.and64(Imm64(c - 1), r);
3314 pushI64(r);
3315 } else {
3316 bool isConst = peekConst(&c);
3317 RegI64 r, rs, reserved;
3318 popAndAllocateForDivAndRemI64(&r, &rs, &reserved, IsRemainder(true));
3319 quotientOrRemainder(rs, r, reserved, IsUnsigned(true), ZeroOnOverflow(true),
3320 isConst, c, RemainderI64);
3321 maybeFree(reserved);
3322 freeI64(rs);
3323 pushI64(r);
3324 }
3325 }
3326 #endif // RABALDR_INT_DIV_I64_CALLOUT
3327
3328 void BaseCompiler::emitRotrI64() {
3329 int64_t c;
3330 if (popConst(&c)) {
3331 RegI64 r = popI64();
3332 RegI32 temp = needRotate64Temp();
3333 masm.rotateRight64(Imm32(c & 63), r, r, temp);
3334 maybeFree(temp);
3335 pushI64(r);
3336 } else {
3337 RegI64 rs = popI64RhsForRotate();
3338 RegI64 r = popI64();
3339 masm.rotateRight64(lowPart(rs), r, r, maybeHighPart(rs));
3340 freeI64(rs);
3341 pushI64(r);
3342 }
3343 }
3344
3345 void BaseCompiler::emitRotlI64() {
3346 int64_t c;
3347 if (popConst(&c)) {
3348 RegI64 r = popI64();
3349 RegI32 temp = needRotate64Temp();
3350 masm.rotateLeft64(Imm32(c & 63), r, r, temp);
3351 maybeFree(temp);
3352 pushI64(r);
3353 } else {
3354 RegI64 rs = popI64RhsForRotate();
3355 RegI64 r = popI64();
3356 masm.rotateLeft64(lowPart(rs), r, r, maybeHighPart(rs));
3357 freeI64(rs);
3358 pushI64(r);
3359 }
3360 }
3361
3362 void BaseCompiler::emitEqzI32() {
3363 if (sniffConditionalControlEqz(ValType::I32)) {
3364 return;
3365 }
3366 emitUnop(EqzI32);
3367 }
3368
3369 void BaseCompiler::emitEqzI64() {
3370 if (sniffConditionalControlEqz(ValType::I64)) {
3371 return;
3372 }
3373 emitUnop(EqzI64);
3374 }
3375
3376 template <TruncFlags flags>
3377 bool BaseCompiler::emitTruncateF32ToI32() {
3378 RegF32 rs = popF32();
3379 RegI32 rd = needI32();
3380 if (!truncateF32ToI32(rs, rd, flags)) {
3381 return false;
3382 }
3383 freeF32(rs);
3384 pushI32(rd);
3385 return true;
3386 }
3387
3388 template <TruncFlags flags>
3389 bool BaseCompiler::emitTruncateF64ToI32() {
3390 RegF64 rs = popF64();
3391 RegI32 rd = needI32();
3392 if (!truncateF64ToI32(rs, rd, flags)) {
3393 return false;
3394 }
3395 freeF64(rs);
3396 pushI32(rd);
3397 return true;
3398 }
3399
3400 #ifndef RABALDR_FLOAT_TO_I64_CALLOUT
3401 template <TruncFlags flags>
3402 bool BaseCompiler::emitTruncateF32ToI64() {
3403 RegF32 rs = popF32();
3404 RegI64 rd = needI64();
3405 RegF64 temp = needTempForFloatingToI64(flags);
3406 if (!truncateF32ToI64(rs, rd, flags, temp)) {
3407 return false;
3408 }
3409 maybeFree(temp);
3410 freeF32(rs);
3411 pushI64(rd);
3412 return true;
3413 }
3414
3415 template <TruncFlags flags>
3416 bool BaseCompiler::emitTruncateF64ToI64() {
3417 RegF64 rs = popF64();
3418 RegI64 rd = needI64();
3419 RegF64 temp = needTempForFloatingToI64(flags);
3420 if (!truncateF64ToI64(rs, rd, flags, temp)) {
3421 return false;
3422 }
3423 maybeFree(temp);
3424 freeF64(rs);
3425 pushI64(rd);
3426 return true;
3427 }
3428 #endif // RABALDR_FLOAT_TO_I64_CALLOUT
3429
3430 void BaseCompiler::emitExtendI64_8() {
3431 RegI64 r;
3432 popI64ForSignExtendI64(&r);
3433 masm.move8To64SignExtend(lowPart(r), r);
3434 pushI64(r);
3435 }
3436
3437 void BaseCompiler::emitExtendI64_16() {
3438 RegI64 r;
3439 popI64ForSignExtendI64(&r);
3440 masm.move16To64SignExtend(lowPart(r), r);
3441 pushI64(r);
3442 }
3443
3444 void BaseCompiler::emitExtendI64_32() {
3445 RegI64 r;
3446 popI64ForSignExtendI64(&r);
3447 masm.move32To64SignExtend(lowPart(r), r);
3448 pushI64(r);
3449 }
3450
3451 void BaseCompiler::emitExtendI32ToI64() {
3452 RegI64 r;
3453 popI32ForSignExtendI64(&r);
3454 masm.move32To64SignExtend(lowPart(r), r);
3455 pushI64(r);
3456 }
3457
3458 void BaseCompiler::emitExtendU32ToI64() {
3459 RegI32 rs = popI32();
3460 RegI64 rd = widenI32(rs);
3461 masm.move32To64ZeroExtend(rs, rd);
3462 pushI64(rd);
3463 }
3464
3465 #ifndef RABALDR_I64_TO_FLOAT_CALLOUT
3466 void BaseCompiler::emitConvertU64ToF32() {
3467 RegI64 rs = popI64();
3468 RegF32 rd = needF32();
3469 RegI32 temp = needConvertI64ToFloatTemp(ValType::F32, IsUnsigned(true));
3470 convertI64ToF32(rs, IsUnsigned(true), rd, temp);
3471 maybeFree(temp);
3472 freeI64(rs);
3473 pushF32(rd);
3474 }
3475
3476 void BaseCompiler::emitConvertU64ToF64() {
3477 RegI64 rs = popI64();
3478 RegF64 rd = needF64();
3479 RegI32 temp = needConvertI64ToFloatTemp(ValType::F64, IsUnsigned(true));
3480 convertI64ToF64(rs, IsUnsigned(true), rd, temp);
3481 maybeFree(temp);
3482 freeI64(rs);
3483 pushF64(rd);
3484 }
3485 #endif // RABALDR_I64_TO_FLOAT_CALLOUT
3486
3487 ////////////////////////////////////////////////////////////
3488 //
3489 // Machinery for optimized conditional branches.
3490 //
3491 // To disable this optimization it is enough always to return false from
3492 // sniffConditionalControl{Cmp,Eqz}.
3493
3494 struct BranchState {
3495 union {
3496 struct {
3497 RegI32 lhs;
3498 RegI32 rhs;
3499 int32_t imm;
3500 bool rhsImm;
3501 } i32;
3502 struct {
3503 RegI64 lhs;
3504 RegI64 rhs;
3505 int64_t imm;
3506 bool rhsImm;
3507 } i64;
3508 struct {
3509 RegF32 lhs;
3510 RegF32 rhs;
3511 } f32;
3512 struct {
3513 RegF64 lhs;
3514 RegF64 rhs;
3515 } f64;
3516 };
3517
3518 Label* const label; // The target of the branch, never NULL
3519 const StackHeight stackHeight; // The stack base above which to place
3520 // stack-spilled block results, if
3521 // hasBlockResults().
3522 const bool invertBranch; // If true, invert the sense of the branch
3523 const ResultType resultType; // The result propagated along the edges
3524
3525 explicit BranchState(Label* label)
3526 : label(label),
3527 stackHeight(StackHeight::Invalid()),
3528 invertBranch(false),
3529 resultType(ResultType::Empty()) {}
3530
3531 BranchState(Label* label, bool invertBranch)
3532 : label(label),
3533 stackHeight(StackHeight::Invalid()),
3534 invertBranch(invertBranch),
3535 resultType(ResultType::Empty()) {}
3536
3537 BranchState(Label* label, StackHeight stackHeight, bool invertBranch,
3538 ResultType resultType)
3539 : label(label),
3540 stackHeight(stackHeight),
3541 invertBranch(invertBranch),
3542 resultType(resultType) {}
3543
3544 bool hasBlockResults() const { return stackHeight.isValid(); }
3545 };
3546
3547 void BaseCompiler::setLatentCompare(Assembler::Condition compareOp,
3548 ValType operandType) {
3549 latentOp_ = LatentOp::Compare;
3550 latentType_ = operandType;
3551 latentIntCmp_ = compareOp;
3552 }
3553
3554 void BaseCompiler::setLatentCompare(Assembler::DoubleCondition compareOp,
3555 ValType operandType) {
3556 latentOp_ = LatentOp::Compare;
3557 latentType_ = operandType;
3558 latentDoubleCmp_ = compareOp;
3559 }
3560
3561 void BaseCompiler::setLatentEqz(ValType operandType) {
3562 latentOp_ = LatentOp::Eqz;
3563 latentType_ = operandType;
3564 }
3565
3566 bool BaseCompiler::hasLatentOp() const { return latentOp_ != LatentOp::None; }
3567
3568 void BaseCompiler::resetLatentOp() { latentOp_ = LatentOp::None; }
3569
3570 // Emit a conditional branch that optionally and optimally cleans up the CPU
3571 // stack before we branch.
3572 //
3573 // Cond is either Assembler::Condition or Assembler::DoubleCondition.
3574 //
3575 // Lhs is RegI32, RegI64, or RegF32, RegF64, or RegRef.
3576 //
3577 // Rhs is either the same as Lhs, or an immediate expression compatible with
3578 // Lhs "when applicable".
3579
3580 template <typename Cond, typename Lhs, typename Rhs>
3581 bool BaseCompiler::jumpConditionalWithResults(BranchState* b, Cond cond,
3582 Lhs lhs, Rhs rhs) {
3583 if (b->hasBlockResults()) {
3584 StackHeight resultsBase(0);
3585 if (!topBranchParams(b->resultType, &resultsBase)) {
3586 return false;
3587 }
3588 if (b->stackHeight != resultsBase) {
3589 Label notTaken;
3590 branchTo(b->invertBranch ? cond : Assembler::InvertCondition(cond), lhs,
3591 rhs, &notTaken);
3592
3593 // Shuffle stack args.
3594 shuffleStackResultsBeforeBranch(resultsBase, b->stackHeight,
3595 b->resultType);
3596 masm.jump(b->label);
3597 masm.bind(&notTaken);
3598 return true;
3599 }
3600 }
3601
3602 branchTo(b->invertBranch ? Assembler::InvertCondition(cond) : cond, lhs, rhs,
3603 b->label);
3604 return true;
3605 }
3606
3607 bool BaseCompiler::jumpConditionalWithResults(BranchState* b, RegRef object,
3608 MaybeRefType sourceType,
3609 RefType destType,
3610 bool onSuccess) {
3611 // Temporarily take the result registers so that branchIfRefSubtype
3612 // doesn't use them.
3613 needIntegerResultRegisters(b->resultType);
3614 BranchIfRefSubtypeRegisters regs =
3615 allocRegistersForBranchIfRefSubtype(destType);
3616 freeIntegerResultRegisters(b->resultType);
3617
3618 if (b->hasBlockResults()) {
3619 StackHeight resultsBase(0);
3620 if (!topBranchParams(b->resultType, &resultsBase)) {
3621 return false;
3622 }
3623 if (b->stackHeight != resultsBase) {
3624 Label notTaken;
3625
3626 masm.branchWasmRefIsSubtype(
3627 object, sourceType, destType, &notTaken,
3628 /*onSuccess=*/b->invertBranch ? onSuccess : !onSuccess, regs.superSTV,
3629 regs.scratch1, regs.scratch2);
3630 freeRegistersForBranchIfRefSubtype(regs);
3631
3632 // Shuffle stack args.
3633 shuffleStackResultsBeforeBranch(resultsBase, b->stackHeight,
3634 b->resultType);
3635 masm.jump(b->label);
3636 masm.bind(&notTaken);
3637 return true;
3638 }
3639 }
3640
3641 masm.branchWasmRefIsSubtype(
3642 object, sourceType, destType, b->label,
3643 /*onSuccess=*/b->invertBranch ? !onSuccess : onSuccess, regs.superSTV,
3644 regs.scratch1, regs.scratch2);
3645 freeRegistersForBranchIfRefSubtype(regs);
3646 return true;
3647 }
3648
3649 // sniffConditionalControl{Cmp,Eqz} may modify the latentWhatever_ state in
3650 // the BaseCompiler so that a subsequent conditional branch can be compiled
3651 // optimally. emitBranchSetup() and emitBranchPerform() will consume that
3652 // state. If the latter methods are not called because deadCode_ is true
3653 // then the compiler MUST instead call resetLatentOp() to reset the state.
3654
3655 template <typename Cond>
3656 bool BaseCompiler::sniffConditionalControlCmp(Cond compareOp,
3657 ValType operandType) {
3658 MOZ_ASSERT(latentOp_ == LatentOp::None,
3659 "Latent comparison state not properly reset");
3660
3661 #ifdef JS_CODEGEN_X86
3662 // On x86, latent i64 binary comparisons use too many registers: the
3663 // reserved join register and the lhs and rhs operands require six, but we
3664 // only have five.
3665 if (operandType == ValType::I64) {
3666 return false;
3667 }
3668 #endif
3669
3670 // No optimization for pointer compares yet.
3671 if (operandType.isRefRepr()) {
3672 return false;
3673 }
3674
3675 OpBytes op{};
3676 iter_.peekOp(&op);
3677 switch (op.b0) {
3678 case uint16_t(Op::BrIf):
3679 case uint16_t(Op::If):
3680 case uint16_t(Op::SelectNumeric):
3681 case uint16_t(Op::SelectTyped):
3682 setLatentCompare(compareOp, operandType);
3683 return true;
3684 default:
3685 return false;
3686 }
3687 }
3688
3689 bool BaseCompiler::sniffConditionalControlEqz(ValType operandType) {
3690 MOZ_ASSERT(latentOp_ == LatentOp::None,
3691 "Latent comparison state not properly reset");
3692
3693 OpBytes op{};
3694 iter_.peekOp(&op);
3695 switch (op.b0) {
3696 case uint16_t(Op::BrIf):
3697 case uint16_t(Op::SelectNumeric):
3698 case uint16_t(Op::SelectTyped):
3699 case uint16_t(Op::If):
3700 setLatentEqz(operandType);
3701 return true;
3702 default:
3703 return false;
3704 }
3705 }
3706
3707 void BaseCompiler::emitBranchSetup(BranchState* b) {
3708 // Avoid allocating operands to latentOp_ to result registers.
3709 if (b->hasBlockResults()) {
3710 needResultRegisters(b->resultType);
3711 }
3712
3713 // Set up fields so that emitBranchPerform() need not switch on latentOp_.
3714 switch (latentOp_) {
3715 case LatentOp::None: {
3716 latentIntCmp_ = Assembler::NotEqual;
3717 latentType_ = ValType::I32;
3718 b->i32.lhs = popI32();
3719 b->i32.rhsImm = true;
3720 b->i32.imm = 0;
3721 break;
3722 }
3723 case LatentOp::Compare: {
3724 switch (latentType_.kind()) {
3725 case ValType::I32: {
3726 if (popConst(&b->i32.imm)) {
3727 b->i32.lhs = popI32();
3728 b->i32.rhsImm = true;
3729 } else {
3730 pop2xI32(&b->i32.lhs, &b->i32.rhs);
3731 b->i32.rhsImm = false;
3732 }
3733 break;
3734 }
3735 case ValType::I64: {
3736 pop2xI64(&b->i64.lhs, &b->i64.rhs);
3737 b->i64.rhsImm = false;
3738 break;
3739 }
3740 case ValType::F32: {
3741 pop2xF32(&b->f32.lhs, &b->f32.rhs);
3742 break;
3743 }
3744 case ValType::F64: {
3745 pop2xF64(&b->f64.lhs, &b->f64.rhs);
3746 break;
3747 }
3748 default: {
3749 MOZ_CRASH("Unexpected type for LatentOp::Compare");
3750 }
3751 }
3752 break;
3753 }
3754 case LatentOp::Eqz: {
3755 switch (latentType_.kind()) {
3756 case ValType::I32: {
3757 latentIntCmp_ = Assembler::Equal;
3758 b->i32.lhs = popI32();
3759 b->i32.rhsImm = true;
3760 b->i32.imm = 0;
3761 break;
3762 }
3763 case ValType::I64: {
3764 latentIntCmp_ = Assembler::Equal;
3765 b->i64.lhs = popI64();
3766 b->i64.rhsImm = true;
3767 b->i64.imm = 0;
3768 break;
3769 }
3770 default: {
3771 MOZ_CRASH("Unexpected type for LatentOp::Eqz");
3772 }
3773 }
3774 break;
3775 }
3776 }
3777
3778 if (b->hasBlockResults()) {
3779 freeResultRegisters(b->resultType);
3780 }
3781 }
3782
3783 bool BaseCompiler::emitBranchPerform(BranchState* b) {
3784 switch (latentType_.kind()) {
3785 case ValType::I32: {
3786 if (b->i32.rhsImm) {
3787 if (!jumpConditionalWithResults(b, latentIntCmp_, b->i32.lhs,
3788 Imm32(b->i32.imm))) {
3789 return false;
3790 }
3791 } else {
3792 if (!jumpConditionalWithResults(b, latentIntCmp_, b->i32.lhs,
3793 b->i32.rhs)) {
3794 return false;
3795 }
3796 freeI32(b->i32.rhs);
3797 }
3798 freeI32(b->i32.lhs);
3799 break;
3800 }
3801 case ValType::I64: {
3802 if (b->i64.rhsImm) {
3803 if (!jumpConditionalWithResults(b, latentIntCmp_, b->i64.lhs,
3804 Imm64(b->i64.imm))) {
3805 return false;
3806 }
3807 } else {
3808 if (!jumpConditionalWithResults(b, latentIntCmp_, b->i64.lhs,
3809 b->i64.rhs)) {
3810 return false;
3811 }
3812 freeI64(b->i64.rhs);
3813 }
3814 freeI64(b->i64.lhs);
3815 break;
3816 }
3817 case ValType::F32: {
3818 if (!jumpConditionalWithResults(b, latentDoubleCmp_, b->f32.lhs,
3819 b->f32.rhs)) {
3820 return false;
3821 }
3822 freeF32(b->f32.lhs);
3823 freeF32(b->f32.rhs);
3824 break;
3825 }
3826 case ValType::F64: {
3827 if (!jumpConditionalWithResults(b, latentDoubleCmp_, b->f64.lhs,
3828 b->f64.rhs)) {
3829 return false;
3830 }
3831 freeF64(b->f64.lhs);
3832 freeF64(b->f64.rhs);
3833 break;
3834 }
3835 default: {
3836 MOZ_CRASH("Unexpected type for LatentOp::Compare");
3837 }
3838 }
3839 resetLatentOp();
3840 return true;
3841 }
3842
3843 // For blocks and loops and ifs:
3844 //
3845 // - Sync the value stack before going into the block in order to simplify exit
3846 // from the block: all exits from the block can assume that there are no
3847 // live registers except the one carrying the exit value.
3848 // - The block can accumulate a number of dead values on the stacks, so when
3849 // branching out of the block or falling out at the end be sure to
3850 // pop the appropriate stacks back to where they were on entry, while
3851 // preserving the exit value.
3852 // - A continue branch in a loop is much like an exit branch, but the branch
3853 // value must not be preserved.
3854 // - The exit value is always in a designated join register (type dependent).
3855
3856 bool BaseCompiler::emitBlock() {
3857 BlockType type;
3858 if (!iter_.readBlock(&type)) {
3859 return false;
3860 }
3861
3862 if (!deadCode_) {
3863 sync(); // Simplifies branching out from block
3864 }
3865
3866 initControl(controlItem(), type.params());
3867
3868 return true;
3869 }
3870
3871 bool BaseCompiler::endBlock(ResultType type) {
3872 Control& block = controlItem();
3873
3874 if (deadCode_) {
3875 // Block does not fall through; reset stack.
3876 fr.resetStackHeight(block.stackHeight, type);
3877 popValueStackTo(block.stackSize);
3878 } else {
3879 // If the block label is used, we have a control join, so we need to shuffle
3880 // fallthrough values into place. Otherwise if it's not a control join, we
3881 // can leave the value stack alone.
3882 MOZ_ASSERT(stk_.length() == block.stackSize + type.length());
3883 if (block.label.used()) {
3884 popBlockResults(type, block.stackHeight, ContinuationKind::Fallthrough);
3885 }
3886 block.bceSafeOnExit &= bceSafe_;
3887 }
3888
3889 // Bind after cleanup: branches out will have popped the stack.
3890 if (block.label.used()) {
3891 masm.bind(&block.label);
3892 if (deadCode_) {
3893 captureResultRegisters(type);
3894 deadCode_ = false;
3895 }
3896 if (!pushBlockResults(type)) {
3897 return false;
3898 }
3899 }
3900
3901 bceSafe_ = block.bceSafeOnExit;
3902
3903 return true;
3904 }
3905
3906 bool BaseCompiler::emitLoop() {
3907 BlockType type;
3908 if (!iter_.readLoop(&type)) {
3909 return false;
3910 }
3911
3912 if (!deadCode_) {
3913 sync(); // Simplifies branching out from block
3914 }
3915
3916 initControl(controlItem(), type.params());
3917 bceSafe_ = 0;
3918
3919 if (!deadCode_) {
3920 // Loop entry is a control join, so shuffle the entry parameters into the
3921 // well-known locations.
3922 if (!topBlockParams(type.params())) {
3923 return false;
3924 }
3925 masm.nopAlign(CodeAlignment);
3926 masm.bind(&controlItem(0).label);
3927 // The interrupt check barfs if there are live registers.
3928 sync();
3929 if (!addInterruptCheck()) {
3930 return false;
3931 }
3932
3933 if (compilerEnv_.mode() == CompileMode::LazyTiering) {
3934 // Create an unpatched hotness check and stash enough information that we
3935 // can patch it with a value related to the loop's size when we get to
3936 // the corresponding `end` opcode.
3937 Maybe<CodeOffset> ctrDecOffset = addHotnessCheck();
3938 if (ctrDecOffset.isNothing()) {
3939 return false;
3940 }
3941 controlItem().loopBytecodeStart = iter_.lastOpcodeOffset();
3942 controlItem().offsetOfCtrDec = ctrDecOffset.value();
3943 }
3944 }
3945
3946 return true;
3947 }
3948
3949 // The bodies of the "then" and "else" arms can be arbitrary sequences
3950 // of expressions, they push control and increment the nesting and can
3951 // even be targeted by jumps. A branch to the "if" block branches to
3952 // the exit of the if, ie, it's like "break". Consider:
3953 //
3954 // (func (result i32)
3955 // (if (i32.const 1)
3956 // (begin (br 1) (unreachable))
3957 // (begin (unreachable)))
3958 // (i32.const 1))
3959 //
3960 // The branch causes neither of the unreachable expressions to be
3961 // evaluated.
3962
3963 bool BaseCompiler::emitIf() {
3964 BlockType type;
3965 Nothing unused_cond;
3966 if (!iter_.readIf(&type, &unused_cond)) {
3967 return false;
3968 }
3969
3970 BranchState b(&controlItem().otherLabel, InvertBranch(true));
3971 if (!deadCode_) {
3972 needResultRegisters(type.params());
3973 emitBranchSetup(&b);
3974 freeResultRegisters(type.params());
3975 sync();
3976 } else {
3977 resetLatentOp();
3978 }
3979
3980 initControl(controlItem(), type.params());
3981
3982 if (!deadCode_) {
3983 // Because params can flow immediately to results in the case of an empty
3984 // "then" or "else" block, and the result of an if/then is a join in
3985 // general, we shuffle params eagerly to the result allocations.
3986 if (!topBlockParams(type.params())) {
3987 return false;
3988 }
3989 if (!emitBranchPerform(&b)) {
3990 return false;
3991 }
3992 }
3993
3994 return true;
3995 }
3996
3997 bool BaseCompiler::endIfThen(ResultType type) {
3998 Control& ifThen = controlItem();
3999
4000 // The parameters to the "if" logically flow to both the "then" and "else"
4001 // blocks, but the "else" block is empty. Since we know that the "if"
4002 // type-checks, that means that the "else" parameters are the "else" results,
4003 // and that the "if"'s result type is the same as its parameter type.
4004
4005 if (deadCode_) {
4006 // "then" arm does not fall through; reset stack.
4007 fr.resetStackHeight(ifThen.stackHeight, type);
4008 popValueStackTo(ifThen.stackSize);
4009 if (!ifThen.deadOnArrival) {
4010 captureResultRegisters(type);
4011 }
4012 } else {
4013 MOZ_ASSERT(stk_.length() == ifThen.stackSize + type.length());
4014 // Assume we have a control join, so place results in block result
4015 // allocations.
4016 popBlockResults(type, ifThen.stackHeight, ContinuationKind::Fallthrough);
4017 MOZ_ASSERT(!ifThen.deadOnArrival);
4018 }
4019
4020 if (ifThen.otherLabel.used()) {
4021 masm.bind(&ifThen.otherLabel);
4022 }
4023
4024 if (ifThen.label.used()) {
4025 masm.bind(&ifThen.label);
4026 }
4027
4028 if (!deadCode_) {
4029 ifThen.bceSafeOnExit &= bceSafe_;
4030 }
4031
4032 deadCode_ = ifThen.deadOnArrival;
4033 if (!deadCode_) {
4034 if (!pushBlockResults(type)) {
4035 return false;
4036 }
4037 }
4038
4039 bceSafe_ = ifThen.bceSafeOnExit & ifThen.bceSafeOnEntry;
4040
4041 return true;
4042 }
4043
4044 bool BaseCompiler::emitElse() {
4045 ResultType params, results;
4046 BaseNothingVector unused_thenValues{};
4047
4048 if (!iter_.readElse(&params, &results, &unused_thenValues)) {
4049 return false;
4050 }
4051
4052 Control& ifThenElse = controlItem(0);
4053
4054 // See comment in endIfThenElse, below.
4055
4056 // Exit the "then" branch.
4057
4058 ifThenElse.deadThenBranch = deadCode_;
4059
4060 if (deadCode_) {
4061 fr.resetStackHeight(ifThenElse.stackHeight, results);
4062 popValueStackTo(ifThenElse.stackSize);
4063 } else {
4064 MOZ_ASSERT(stk_.length() == ifThenElse.stackSize + results.length());
4065 popBlockResults(results, ifThenElse.stackHeight, ContinuationKind::Jump);
4066 freeResultRegisters(results);
4067 MOZ_ASSERT(!ifThenElse.deadOnArrival);
4068 }
4069
4070 if (!deadCode_) {
4071 masm.jump(&ifThenElse.label);
4072 }
4073
4074 if (ifThenElse.otherLabel.used()) {
4075 masm.bind(&ifThenElse.otherLabel);
4076 }
4077
4078 // Reset to the "else" branch.
4079
4080 if (!deadCode_) {
4081 ifThenElse.bceSafeOnExit &= bceSafe_;
4082 }
4083
4084 deadCode_ = ifThenElse.deadOnArrival;
4085 bceSafe_ = ifThenElse.bceSafeOnEntry;
4086
4087 fr.resetStackHeight(ifThenElse.stackHeight, params);
4088
4089 if (!deadCode_) {
4090 captureResultRegisters(params);
4091 if (!pushBlockResults(params)) {
4092 return false;
4093 }
4094 }
4095
4096 return true;
4097 }
4098
4099 bool BaseCompiler::endIfThenElse(ResultType type) {
4100 Control& ifThenElse = controlItem();
4101
4102 // The expression type is not a reliable guide to what we'll find
4103 // on the stack, we could have (if E (i32.const 1) (unreachable))
4104 // in which case the "else" arm is AnyType but the type of the
4105 // full expression is I32. So restore whatever's there, not what
4106 // we want to find there. The "then" arm has the same constraint.
4107
4108 if (deadCode_) {
4109 // "then" arm does not fall through; reset stack.
4110 fr.resetStackHeight(ifThenElse.stackHeight, type);
4111 popValueStackTo(ifThenElse.stackSize);
4112 } else {
4113 MOZ_ASSERT(stk_.length() == ifThenElse.stackSize + type.length());
4114 // Assume we have a control join, so place results in block result
4115 // allocations.
4116 popBlockResults(type, ifThenElse.stackHeight,
4117 ContinuationKind::Fallthrough);
4118 ifThenElse.bceSafeOnExit &= bceSafe_;
4119 MOZ_ASSERT(!ifThenElse.deadOnArrival);
4120 }
4121
4122 if (ifThenElse.label.used()) {
4123 masm.bind(&ifThenElse.label);
4124 }
4125
4126 bool joinLive =
4127 !ifThenElse.deadOnArrival &&
4128 (!ifThenElse.deadThenBranch || !deadCode_ || ifThenElse.label.bound());
4129
4130 if (joinLive) {
4131 // No values were provided by the "then" path, but capture the values
4132 // provided by the "else" path.
4133 if (deadCode_) {
4134 captureResultRegisters(type);
4135 }
4136 deadCode_ = false;
4137 }
4138
4139 bceSafe_ = ifThenElse.bceSafeOnExit;
4140
4141 if (!deadCode_) {
4142 if (!pushBlockResults(type)) {
4143 return false;
4144 }
4145 }
4146
4147 return true;
4148 }
4149
4150 bool BaseCompiler::emitEnd() {
4151 LabelKind kind;
4152 ResultType type;
4153 BaseNothingVector unused_values{};
4154 if (!iter_.readEnd(&kind, &type, &unused_values, &unused_values)) {
4155 return false;
4156 }
4157
4158 // Every label case is responsible to pop the control item at the appropriate
4159 // time for the label case
4160 switch (kind) {
4161 case LabelKind::Body: {
4162 if (!endBlock(type)) {
4163 return false;
4164 }
4165 doReturn(ContinuationKind::Fallthrough);
4166 iter_.popEnd();
4167 MOZ_ASSERT(iter_.controlStackEmpty());
4168 return iter_.endFunction(iter_.end());
4169 }
4170 case LabelKind::Block:
4171 if (!endBlock(type)) {
4172 return false;
4173 }
4174 iter_.popEnd();
4175 break;
4176 case LabelKind::Loop: {
4177 if (compilerEnv_.mode() == CompileMode::LazyTiering) {
4178 // These are set (or not set) together.
4179 MOZ_ASSERT((controlItem().loopBytecodeStart != UINTPTR_MAX) ==
4180 (controlItem().offsetOfCtrDec.bound()));
4181 if (controlItem().loopBytecodeStart != UINTPTR_MAX) {
4182 // If the above condition is false, the loop was in dead code and so
4183 // there is no loop-head hotness check that needs to be patched. See
4184 // ::emitLoop.
4185 MOZ_ASSERT(controlItem().loopBytecodeStart <=
4186 iter_.lastOpcodeOffset());
4187 size_t loopBytecodeSize =
4188 iter_.lastOpcodeOffset() - controlItem().loopBytecodeStart;
4189 uint32_t step = BlockSizeToDownwardsStep(loopBytecodeSize);
4190 // Don't try to patch the check if we've OOM'd, since the check might
4191 // not actually exist.
4192 if (masm.oom()) {
4193 return false;
4194 }
4195 patchHotnessCheck(controlItem().offsetOfCtrDec, step);
4196 }
4197 }
4198 // The end of a loop isn't a branch target, so we can just leave its
4199 // results on the expression stack to be consumed by the outer block.
4200 iter_.popEnd();
4201 break;
4202 }
4203 case LabelKind::Then:
4204 if (!endIfThen(type)) {
4205 return false;
4206 }
4207 iter_.popEnd();
4208 break;
4209 case LabelKind::Else:
4210 if (!endIfThenElse(type)) {
4211 return false;
4212 }
4213 iter_.popEnd();
4214 break;
4215 case LabelKind::Try:
4216 case LabelKind::Catch:
4217 case LabelKind::CatchAll:
4218 if (!endTryCatch(type)) {
4219 return false;
4220 }
4221 iter_.popEnd();
4222 break;
4223 case LabelKind::TryTable:
4224 if (!endTryTable(type)) {
4225 return false;
4226 }
4227 iter_.popEnd();
4228 break;
4229 }
4230
4231 return true;
4232 }
4233
4234 bool BaseCompiler::emitBr() {
4235 uint32_t relativeDepth;
4236 ResultType type;
4237 BaseNothingVector unused_values{};
4238 if (!iter_.readBr(&relativeDepth, &type, &unused_values)) {
4239 return false;
4240 }
4241
4242 if (deadCode_) {
4243 return true;
4244 }
4245
4246 Control& target = controlItem(relativeDepth);
4247 target.bceSafeOnExit &= bceSafe_;
4248
4249 // Save any values in the designated join registers, as if the target block
4250 // returned normally.
4251
4252 popBlockResults(type, target.stackHeight, ContinuationKind::Jump);
4253 masm.jump(&target.label);
4254
4255 // The registers holding the join values are free for the remainder of this
4256 // block.
4257
4258 freeResultRegisters(type);
4259
4260 deadCode_ = true;
4261
4262 return true;
4263 }
4264
4265 bool BaseCompiler::emitBrIf() {
4266 uint32_t relativeDepth;
4267 ResultType type;
4268 BaseNothingVector unused_values{};
4269 Nothing unused_condition;
4270 if (!iter_.readBrIf(&relativeDepth, &type, &unused_values,
4271 &unused_condition)) {
4272 return false;
4273 }
4274
4275 if (deadCode_) {
4276 resetLatentOp();
4277 return true;
4278 }
4279
4280 Control& target = controlItem(relativeDepth);
4281 target.bceSafeOnExit &= bceSafe_;
4282
4283 BranchState b(&target.label, target.stackHeight, InvertBranch(false), type);
4284 emitBranchSetup(&b);
4285 return emitBranchPerform(&b);
4286 }
4287
4288 bool BaseCompiler::emitBrOnNull() {
4289 MOZ_ASSERT(!hasLatentOp());
4290
4291 uint32_t relativeDepth;
4292 ResultType type;
4293 BaseNothingVector unused_values{};
4294 Nothing unused_condition;
4295 if (!iter_.readBrOnNull(&relativeDepth, &type, &unused_values,
4296 &unused_condition)) {
4297 return false;
4298 }
4299
4300 if (deadCode_) {
4301 return true;
4302 }
4303
4304 Control& target = controlItem(relativeDepth);
4305 target.bceSafeOnExit &= bceSafe_;
4306
4307 BranchState b(&target.label, target.stackHeight, InvertBranch(false), type);
4308 if (b.hasBlockResults()) {
4309 needResultRegisters(b.resultType);
4310 }
4311 RegRef ref = popRef();
4312 if (b.hasBlockResults()) {
4313 freeResultRegisters(b.resultType);
4314 }
4315 if (!jumpConditionalWithResults(&b, Assembler::Equal, ref,
4316 ImmWord(AnyRef::NullRefValue))) {
4317 return false;
4318 }
4319 pushRef(ref);
4320
4321 return true;
4322 }
4323
4324 bool BaseCompiler::emitBrOnNonNull() {
4325 MOZ_ASSERT(!hasLatentOp());
4326
4327 uint32_t relativeDepth;
4328 ResultType type;
4329 BaseNothingVector unused_values{};
4330 Nothing unused_condition;
4331 if (!iter_.readBrOnNonNull(&relativeDepth, &type, &unused_values,
4332 &unused_condition)) {
4333 return false;
4334 }
4335
4336 if (deadCode_) {
4337 return true;
4338 }
4339
4340 Control& target = controlItem(relativeDepth);
4341 target.bceSafeOnExit &= bceSafe_;
4342
4343 BranchState b(&target.label, target.stackHeight, InvertBranch(false), type);
4344 MOZ_ASSERT(b.hasBlockResults(), "br_on_non_null has block results");
4345
4346 // Don't allocate the result register used in the branch
4347 needIntegerResultRegisters(b.resultType);
4348
4349 // Get the ref from the top of the stack
4350 RegRef refCondition = popRef();
4351
4352 // Create a copy of the ref for passing to the on_non_null label,
4353 // the original ref is used in the condition.
4354 RegRef ref = needRef();
4355 moveRef(refCondition, ref);
4356 pushRef(ref);
4357
4358 freeIntegerResultRegisters(b.resultType);
4359
4360 if (!jumpConditionalWithResults(&b, Assembler::NotEqual, refCondition,
4361 ImmWord(AnyRef::NullRefValue))) {
4362 return false;
4363 }
4364
4365 freeRef(refCondition);
4366
4367 // Dropping null reference.
4368 dropValue();
4369
4370 return true;
4371 }
4372
4373 bool BaseCompiler::emitBrTable() {
4374 Uint32Vector depths;
4375 uint32_t defaultDepth;
4376 ResultType branchParams;
4377 BaseNothingVector unused_values{};
4378 Nothing unused_index;
4379 // N.B., `branchParams' gets set to the type of the default branch target. In
4380 // the presence of subtyping, it could be that the different branch targets
4381 // have different types. Here we rely on the assumption that the value
4382 // representations (e.g. Stk value types) of all branch target types are the
4383 // same, in the baseline compiler. Notably, this means that all Ref types
4384 // should be represented the same.
4385 if (!iter_.readBrTable(&depths, &defaultDepth, &branchParams, &unused_values,
4386 &unused_index)) {
4387 return false;
4388 }
4389
4390 if (deadCode_) {
4391 return true;
4392 }
4393
4394 // Don't use param registers for rc
4395 needIntegerResultRegisters(branchParams);
4396
4397 // Table switch value always on top.
4398 RegI32 rc = popI32();
4399
4400 freeIntegerResultRegisters(branchParams);
4401
4402 StackHeight resultsBase(0);
4403 if (!topBranchParams(branchParams, &resultsBase)) {
4404 return false;
4405 }
4406
4407 Label dispatchCode;
4408 masm.branch32(Assembler::Below, rc, Imm32(depths.length()), &dispatchCode);
4409
4410 // This is the out-of-range stub. rc is dead here but we don't need it.
4411
4412 shuffleStackResultsBeforeBranch(
4413 resultsBase, controlItem(defaultDepth).stackHeight, branchParams);
4414 controlItem(defaultDepth).bceSafeOnExit &= bceSafe_;
4415 masm.jump(&controlItem(defaultDepth).label);
4416
4417 // Emit stubs. rc is dead in all of these but we don't need it.
4418 //
4419 // The labels in the vector are in the TempAllocator and will
4420 // be freed by and by.
4421 //
4422 // TODO / OPTIMIZE (Bug 1316804): Branch directly to the case code if we
4423 // can, don't emit an intermediate stub.
4424
4425 LabelVector stubs;
4426 if (!stubs.reserve(depths.length())) {
4427 return false;
4428 }
4429
4430 for (uint32_t depth : depths) {
4431 stubs.infallibleEmplaceBack(NonAssertingLabel());
4432 masm.bind(&stubs.back());
4433 shuffleStackResultsBeforeBranch(resultsBase, controlItem(depth).stackHeight,
4434 branchParams);
4435 controlItem(depth).bceSafeOnExit &= bceSafe_;
4436 masm.jump(&controlItem(depth).label);
4437 }
4438
4439 // Emit table.
4440
4441 Label theTable;
4442 jumpTable(stubs, &theTable);
4443
4444 // Emit indirect jump. rc is live here.
4445
4446 tableSwitch(&theTable, rc, &dispatchCode);
4447
4448 deadCode_ = true;
4449
4450 // Clean up.
4451
4452 freeI32(rc);
4453 popValueStackBy(branchParams.length());
4454
4455 return true;
4456 }
4457
4458 bool BaseCompiler::emitTry() {
4459 BlockType type;
4460 if (!iter_.readTry(&type)) {
4461 return false;
4462 }
4463
4464 if (!deadCode_) {
4465 // Simplifies jumping out, but it is also necessary so that control
4466 // can re-enter the catch handler without restoring registers.
4467 sync();
4468 }
4469
4470 initControl(controlItem(), type.params());
4471
4472 if (!deadCode_) {
4473 // Be conservative for BCE due to complex control flow in try blocks.
4474 controlItem().bceSafeOnExit = 0;
4475 if (!startTryNote(&controlItem().tryNoteIndex)) {
4476 return false;
4477 }
4478 }
4479
4480 return true;
4481 }
4482
4483 bool BaseCompiler::emitTryTable() {
4484 BlockType type;
4485 TryTableCatchVector catches;
4486 if (!iter_.readTryTable(&type, &catches)) {
4487 return false;
4488 }
4489
4490 if (!deadCode_) {
4491 // Simplifies jumping out, but it is also necessary so that control
4492 // can re-enter the catch handler without restoring registers.
4493 sync();
4494 }
4495
4496 initControl(controlItem(), type.params());
4497 // Be conservative for BCE due to complex control flow in try blocks.
4498 controlItem().bceSafeOnExit = 0;
4499
4500 // Don't emit a landing pad if this whole try is dead code
4501 if (deadCode_) {
4502 return true;
4503 }
4504
4505 // The block params are consumed by the try body, so keep them off the value
4506 // stack while emitting the landing pad and restore them for the body, the way
4507 // endTryCatch does for its results. sync() above spilled them, so the saved
4508 // entries hold no registers.
4509 MOZ_ASSERT(stk_.length() >= controlItem().stackSize);
4510 StkVector savedParams;
4511 if (!savedParams.append(stk_.begin() + controlItem().stackSize, stk_.end())) {
4512 return false;
4513 }
4514 for (const Stk& v : savedParams) {
4515 MOZ_ASSERT(v.kind() < Stk::RegisterI32 || v.kind() > Stk::RegisterRef);
4516 if (v.kind() == Stk::MemRef) {
4517 stackMapGenerator_.memRefsOnStk--;
4518 }
4519 }
4520 stk_.shrinkTo(controlItem().stackSize);
4521 MOZ_ASSERT(stk_.length() == controlItem().stackSize);
4522
4523 // Emit a landing pad that exceptions will jump into. Jump over it for now.
4524 Label skipLandingPad;
4525 masm.jump(&skipLandingPad);
4526
4527 StackHeight prePadHeight = fr.stackHeight();
4528 uint32_t padOffset = masm.currentOffset();
4529 uint32_t padStackHeight = masm.framePushed();
4530
4531 // InstanceReg is live and contains this function's instance by the exception
4532 // handling resume method. We keep it alive for use in loading the tag for
4533 // each catch handler.
4534 RegPtr instance = RegPtr(InstanceReg);
4535 #ifndef RABALDR_PIN_INSTANCE
4536 needPtr(instance);
4537 #endif
4538
4539 // Load exception and tag from instance, clearing it in the process.
4540 RegRef exn;
4541 RegRef exnTag;
4542 consumePendingException(instance, &exn, &exnTag);
4543
4544 // Get a register to hold the tags for each catch
4545 RegRef catchTag = needRef();
4546
4547 bool hadCatchAll = false;
4548 for (const TryTableCatch& tryTableCatch : catches) {
4549 ResultType labelParams = ResultType::Vector(tryTableCatch.labelType);
4550
4551 Control& target = controlItem(tryTableCatch.labelRelativeDepth);
4552 target.bceSafeOnExit = 0;
4553
4554 // Handle a catch_all by jumping to the target block
4555 if (tryTableCatch.tagIndex == CatchAllIndex) {
4556 // Capture the exnref if it has been requested, or else free it.
4557 if (tryTableCatch.captureExnRef) {
4558 pushRef(exn);
4559 } else {
4560 freeRef(exn);
4561 }
4562 // Free all of the other registers
4563 freeRef(exnTag);
4564 freeRef(catchTag);
4565 #ifndef RABALDR_PIN_INSTANCE
4566 freePtr(instance);
4567 #endif
4568
4569 // Pop the results needed for the target branch and perform the jump
4570 popBlockResults(labelParams, target.stackHeight, ContinuationKind::Jump);
4571 masm.jump(&target.label);
4572 freeResultRegisters(labelParams);
4573
4574 // Break from the loop and skip the implicit rethrow that's needed
4575 // if we didn't have a catch_all
4576 hadCatchAll = true;
4577 break;
4578 }
4579
4580 // This is a `catch $t`, load the tag type we're trying to match
4581 const TagType& tagType = *codeMeta_.tags[tryTableCatch.tagIndex].type;
4582 const TagOffsetVector& tagOffsets = tagType.argOffsets();
4583 ResultType tagParams = tagType.resultType();
4584
4585 // Load the tag for this catch and compare it against the exception's tag.
4586 // If they don't match, skip to the next catch handler.
4587 Label skipCatch;
4588 loadTag(instance, tryTableCatch.tagIndex, catchTag);
4589 masm.branchPtr(Assembler::NotEqual, exnTag, catchTag, &skipCatch);
4590
4591 // The tags and instance are dead after we've had a match, free them
4592 freeRef(exnTag);
4593 freeRef(catchTag);
4594 #ifndef RABALDR_PIN_INSTANCE
4595 freePtr(instance);
4596 #endif
4597
4598 // Allocate a register to hold the exception data pointer
4599 RegPtr data = needPtr();
4600
4601 // Unpack the tag and jump to the block
4602 masm.loadPtr(Address(exn, (int32_t)WasmExceptionObject::offsetOfData()),
4603 data);
4604 // This method can increase stk_.length() by an unbounded amount, so we need
4605 // to perform an allocation here to accomodate the variable number of
4606 // values. There is enough headroom for the fixed number of values. The
4607 // general case is handled in emitBody.
4608 if (!stk_.reserve(stk_.length() + labelParams.length())) {
4609 return false;
4610 }
4611
4612 for (uint32_t i = 0; i < tagParams.length(); i++) {
4613 int32_t offset = tagOffsets[i];
4614 switch (tagParams[i].kind()) {
4615 case ValType::I32: {
4616 RegI32 reg = needI32();
4617 masm.load32(Address(data, offset), reg);
4618 pushI32(reg);
4619 break;
4620 }
4621 case ValType::I64: {
4622 RegI64 reg = needI64();
4623 masm.load64(Address(data, offset), reg);
4624 pushI64(reg);
4625 break;
4626 }
4627 case ValType::F32: {
4628 RegF32 reg = needF32();
4629 masm.loadFloat32(Address(data, offset), reg);
4630 pushF32(reg);
4631 break;
4632 }
4633 case ValType::F64: {
4634 RegF64 reg = needF64();
4635 masm.loadDouble(Address(data, offset), reg);
4636 pushF64(reg);
4637 break;
4638 }
4639 case ValType::V128: {
4640 #ifdef ENABLE_WASM_SIMD
4641 RegV128 reg = needV128();
4642 masm.loadUnalignedSimd128(Address(data, offset), reg);
4643 pushV128(reg);
4644 break;
4645 #else
4646 MOZ_CRASH("No SIMD support");
4647 #endif
4648 }
4649 case ValType::Ref: {
4650 RegRef reg = needRef();
4651 masm.loadPtr(Address(data, offset), reg);
4652 pushRef(reg);
4653 break;
4654 }
4655 }
4656 }
4657
4658 // The exception data pointer is no longer live after unpacking the
4659 // exception
4660 freePtr(data);
4661
4662 // Capture the exnref if it has been requested, or else free it.
4663 if (tryTableCatch.captureExnRef) {
4664 pushRef(exn);
4665 } else {
4666 freeRef(exn);
4667 }
4668
4669 // Pop the results needed for the target branch and perform the jump
4670 popBlockResults(labelParams, target.stackHeight, ContinuationKind::Jump);
4671 masm.jump(&target.label);
4672 freeResultRegisters(labelParams);
4673
4674 // Reset the stack height for the skip to the next catch handler
4675 fr.setStackHeight(prePadHeight);
4676 masm.bind(&skipCatch);
4677
4678 // Reset ownership of the registers for the next catch handler we emit
4679 needRef(exn);
4680 needRef(exnTag);
4681 needRef(catchTag);
4682 #ifndef RABALDR_PIN_INSTANCE
4683 needPtr(instance);
4684 #endif
4685 }
4686
4687 if (!hadCatchAll) {
4688 // Free all registers, except for the exception
4689 freeRef(exnTag);
4690 freeRef(catchTag);
4691 #ifndef RABALDR_PIN_INSTANCE
4692 freePtr(instance);
4693 #endif
4694
4695 // If none of the tag checks succeed and there is no catch_all,
4696 // then we rethrow the exception
4697 if (!throwFrom(exn)) {
4698 return false;
4699 }
4700 } else {
4701 // All registers should have been freed by the catch_all
4702 MOZ_ASSERT(isAvailableRef(exn));
4703 MOZ_ASSERT(isAvailableRef(exnTag));
4704 MOZ_ASSERT(isAvailableRef(catchTag));
4705 #ifndef RABALDR_PIN_INSTANCE
4706 MOZ_ASSERT(isAvailablePtr(instance));
4707 #endif
4708 }
4709
4710 // Reset stack height for skipLandingPad, and bind it
4711 fr.setStackHeight(prePadHeight);
4712 masm.bind(&skipLandingPad);
4713
4714 // Restore the block params removed above, for the try body.
4715 if (!stk_.appendAll(savedParams)) {
4716 return false;
4717 }
4718 for (const Stk& v : savedParams) {
4719 if (v.kind() == Stk::MemRef) {
4720 stackMapGenerator_.memRefsOnStk++;
4721 }
4722 }
4723
4724 // Start the try note for this try block, after the landing pad
4725 if (!startTryNote(&controlItem().tryNoteIndex)) {
4726 return false;
4727 }
4728
4729 // Mark the try note to start at the landing pad we created above
4730 TryNoteVector& tryNotes = masm.tryNotes();
4731 TryNote& tryNote = tryNotes[controlItem().tryNoteIndex];
4732 tryNote.setLandingPad(padOffset, padStackHeight);
4733
4734 return true;
4735 }
4736
4737 void BaseCompiler::emitCatchSetup(LabelKind kind, Control& tryCatch,
4738 const ResultType& resultType) {
4739 // Catch ends the try or last catch, so we finish this like endIfThen.
4740 if (deadCode_) {
4741 fr.resetStackHeight(tryCatch.stackHeight, resultType);
4742 popValueStackTo(tryCatch.stackSize);
4743 } else {
4744 // If the previous block is a catch, we need to handle the extra exception
4745 // reference on the stack (for rethrow) and thus the stack size is 1 more.
4746 MOZ_ASSERT(stk_.length() == tryCatch.stackSize + resultType.length() +
4747 (kind == LabelKind::Try ? 0 : 1));
4748 // Try jumps to the end of the try-catch block unless a throw is done.
4749 if (kind == LabelKind::Try) {
4750 popBlockResults(resultType, tryCatch.stackHeight, ContinuationKind::Jump);
4751 } else {
4752 popCatchResults(resultType, tryCatch.stackHeight);
4753 }
4754 MOZ_ASSERT(stk_.length() == tryCatch.stackSize);
4755 freeResultRegisters(resultType);
4756 MOZ_ASSERT(!tryCatch.deadOnArrival);
4757 }
4758
4759 // Reset to this "catch" branch.
4760 deadCode_ = tryCatch.deadOnArrival;
4761
4762 // We use the empty result type here because catch does *not* take the
4763 // try-catch block parameters.
4764 fr.resetStackHeight(tryCatch.stackHeight, ResultType::Empty());
4765
4766 if (deadCode_) {
4767 return;
4768 }
4769
4770 bceSafe_ = 0;
4771
4772 // The end of the previous try/catch jumps to the join point.
4773 masm.jump(&tryCatch.label);
4774
4775 // Note end of try block for finding the catch block target. This needs
4776 // to happen after the stack is reset to the correct height.
4777 if (kind == LabelKind::Try) {
4778 finishTryNote(controlItem().tryNoteIndex);
4779 }
4780 }
4781
4782 bool BaseCompiler::emitCatch() {
4783 LabelKind kind;
4784 uint32_t tagIndex;
4785 ResultType paramType, resultType;
4786 BaseNothingVector unused_tryValues{};
4787
4788 if (!iter_.readCatch(&kind, &tagIndex, &paramType, &resultType,
4789 &unused_tryValues)) {
4790 return false;
4791 }
4792
4793 Control& tryCatch = controlItem();
4794
4795 emitCatchSetup(kind, tryCatch, resultType);
4796
4797 if (deadCode_) {
4798 return true;
4799 }
4800
4801 // Construct info used for the exception landing pad.
4802 CatchInfo catchInfo(tagIndex);
4803 if (!tryCatch.catchInfos.emplaceBack(catchInfo)) {
4804 return false;
4805 }
4806
4807 masm.bind(&tryCatch.catchInfos.back().label);
4808
4809 // Extract the arguments in the exception package and push them.
4810 const SharedTagType& tagType = codeMeta_.tags[tagIndex].type;
4811 const ValTypeVector& params = tagType->argTypes();
4812 const TagOffsetVector& offsets = tagType->argOffsets();
4813
4814 // The landing pad uses the block return protocol to communicate the
4815 // exception object pointer to the catch block.
4816 ResultType exnResult = ResultType::Single(RefType::extern_());
4817 captureResultRegisters(exnResult);
4818 if (!pushBlockResults(exnResult)) {
4819 return false;
4820 }
4821 RegRef exn = popRef();
4822 RegPtr data = needPtr();
4823
4824 masm.loadPtr(Address(exn, (int32_t)WasmExceptionObject::offsetOfData()),
4825 data);
4826
4827 // This method can increase stk_.length() by an unbounded amount, so we need
4828 // to perform an allocation here to accomodate the variable number of values.
4829 // There is enough headroom for the fixed number of values. The general case
4830 // is handled in emitBody.
4831 if (!stk_.reserve(stk_.length() + params.length() + 1)) {
4832 return false;
4833 }
4834
4835 // This reference is pushed onto the stack because a potential rethrow
4836 // may need to access it. It is always popped at the end of the block.
4837 pushRef(exn);
4838
4839 for (uint32_t i = 0; i < params.length(); i++) {
4840 int32_t offset = offsets[i];
4841 switch (params[i].kind()) {
4842 case ValType::I32: {
4843 RegI32 reg = needI32();
4844 masm.load32(Address(data, offset), reg);
4845 pushI32(reg);
4846 break;
4847 }
4848 case ValType::I64: {
4849 RegI64 reg = needI64();
4850 masm.load64(Address(data, offset), reg);
4851 pushI64(reg);
4852 break;
4853 }
4854 case ValType::F32: {
4855 RegF32 reg = needF32();
4856 masm.loadFloat32(Address(data, offset), reg);
4857 pushF32(reg);
4858 break;
4859 }
4860 case ValType::F64: {
4861 RegF64 reg = needF64();
4862 masm.loadDouble(Address(data, offset), reg);
4863 pushF64(reg);
4864 break;
4865 }
4866 case ValType::V128: {
4867 #ifdef ENABLE_WASM_SIMD
4868 RegV128 reg = needV128();
4869 masm.loadUnalignedSimd128(Address(data, offset), reg);
4870 pushV128(reg);
4871 break;
4872 #else
4873 MOZ_CRASH("No SIMD support");
4874 #endif
4875 }
4876 case ValType::Ref: {
4877 RegRef reg = needRef();
4878 masm.loadPtr(Address(data, offset), reg);
4879 pushRef(reg);
4880 break;
4881 }
4882 }
4883 }
4884 freePtr(data);
4885
4886 return true;
4887 }
4888
4889 bool BaseCompiler::emitCatchAll() {
4890 LabelKind kind;
4891 ResultType paramType, resultType;
4892 BaseNothingVector unused_tryValues{};
4893
4894 if (!iter_.readCatchAll(&kind, &paramType, &resultType, &unused_tryValues)) {
4895 return false;
4896 }
4897
4898 Control& tryCatch = controlItem();
4899
4900 emitCatchSetup(kind, tryCatch, resultType);
4901
4902 if (deadCode_) {
4903 return true;
4904 }
4905
4906 CatchInfo catchInfo(CatchAllIndex);
4907 if (!tryCatch.catchInfos.emplaceBack(catchInfo)) {
4908 return false;
4909 }
4910
4911 masm.bind(&tryCatch.catchInfos.back().label);
4912
4913 // The landing pad uses the block return protocol to communicate the
4914 // exception object pointer to the catch block.
4915 ResultType exnResult = ResultType::Single(RefType::extern_());
4916 captureResultRegisters(exnResult);
4917 // This reference is pushed onto the stack because a potential rethrow
4918 // may need to access it. It is always popped at the end of the block.
4919 return pushBlockResults(exnResult);
4920 }
4921
4922 bool BaseCompiler::emitDelegate() {
4923 uint32_t relativeDepth;
4924 ResultType resultType;
4925 BaseNothingVector unused_tryValues{};
4926
4927 if (!iter_.readDelegate(&relativeDepth, &resultType, &unused_tryValues)) {
4928 return false;
4929 }
4930
4931 if (!endBlock(resultType)) {
4932 return false;
4933 }
4934
4935 if (controlItem().deadOnArrival) {
4936 return true;
4937 }
4938
4939 // Mark the end of the try body. This may insert a nop.
4940 finishTryNote(controlItem().tryNoteIndex);
4941
4942 // If the target block is a non-try block, skip over it and find the next
4943 // try block or the very last block (to re-throw out of the function).
4944 Control& lastBlock = controlOutermost();
4945 while (controlKind(relativeDepth) != LabelKind::Try &&
4946 controlKind(relativeDepth) != LabelKind::TryTable &&
4947 &controlItem(relativeDepth) != &lastBlock) {
4948 relativeDepth++;
4949 }
4950 Control& target = controlItem(relativeDepth);
4951 TryNoteVector& tryNotes = masm.tryNotes();
4952 TryNote& delegateTryNote = tryNotes[controlItem().tryNoteIndex];
4953
4954 if (&target == &lastBlock) {
4955 // A delegate targeting the function body block means that any exception
4956 // in this try needs to be propagated to the caller function. We use the
4957 // delegate code offset of `0` as that will be in the prologue and cannot
4958 // have a try note.
4959 delegateTryNote.setDelegate(0);
4960 } else {
4961 // Delegate to one byte inside the beginning of the target try note, as
4962 // that's when matches hit. Try notes are guaranteed to not be empty either
4963 // and so this will not miss either.
4964 const TryNote& targetTryNote = tryNotes[target.tryNoteIndex];
4965 delegateTryNote.setDelegate(targetTryNote.tryBodyBegin() + 1);
4966 }
4967
4968 return true;
4969 }
4970
4971 bool BaseCompiler::endTryCatch(ResultType type) {
4972 Control& tryCatch = controlItem();
4973 LabelKind tryKind = controlKind(0);
4974
4975 if (deadCode_) {
4976 fr.resetStackHeight(tryCatch.stackHeight, type);
4977 popValueStackTo(tryCatch.stackSize);
4978 } else {
4979 // If the previous block is a catch, we must handle the extra exception
4980 // reference on the stack (for rethrow) and thus the stack size is 1 more.
4981 MOZ_ASSERT(stk_.length() == tryCatch.stackSize + type.length() +
4982 (tryKind == LabelKind::Try ? 0 : 1));
4983 // Assume we have a control join, so place results in block result
4984 // allocations and also handle the implicit exception reference if needed.
4985 if (tryKind == LabelKind::Try) {
4986 popBlockResults(type, tryCatch.stackHeight, ContinuationKind::Jump);
4987 } else {
4988 popCatchResults(type, tryCatch.stackHeight);
4989 }
4990 MOZ_ASSERT(stk_.length() == tryCatch.stackSize);
4991 // Since we will emit a landing pad after this and jump over it to get to
4992 // the control join, we free these here and re-capture at the join.
4993 freeResultRegisters(type);
4994 masm.jump(&tryCatch.label);
4995 MOZ_ASSERT(!tryCatch.bceSafeOnExit);
4996 MOZ_ASSERT(!tryCatch.deadOnArrival);
4997 }
4998
4999 deadCode_ = tryCatch.deadOnArrival;
5000
5001 if (deadCode_) {
5002 return true;
5003 }
5004
5005 // Create landing pad for all catch handlers in this block.
5006 // When used for a catchless try block, this will generate a landing pad
5007 // with no handlers and only the fall-back rethrow.
5008
5009 // The stack height also needs to be set not for a block result, but for the
5010 // entry to the exception handlers. This is reset again below for the join.
5011 StackHeight prePadHeight = fr.stackHeight();
5012 fr.setStackHeight(tryCatch.stackHeight);
5013
5014 // If we are in a catchless try block, then there were no catch blocks to
5015 // mark the end of the try note, so we need to end it here.
5016 if (tryKind == LabelKind::Try) {
5017 // Mark the end of the try body. This may insert a nop.
5018 finishTryNote(controlItem().tryNoteIndex);
5019 }
5020
5021 // The landing pad begins at this point
5022 TryNoteVector& tryNotes = masm.tryNotes();
5023 TryNote& tryNote = tryNotes[controlItem().tryNoteIndex];
5024 tryNote.setLandingPad(masm.currentOffset(), masm.framePushed());
5025
5026 // Store the Instance that was left in InstanceReg by the exception
5027 // handling mechanism, that is this frame's Instance but with the exception
5028 // filled in Instance::pendingException.
5029 fr.storeInstancePtr(InstanceReg);
5030
5031 // Load exception pointer from Instance and make sure that it is
5032 // saved before the following call will clear it.
5033 RegRef exn;
5034 RegRef tag;
5035 consumePendingException(RegPtr(InstanceReg), &exn, &tag);
5036
5037 // Get a register to hold the tags for each catch
5038 RegRef catchTag = needRef();
5039
5040 // Ensure that the exception is assigned to the block return register
5041 // before branching to a handler.
5042 pushRef(exn);
5043 ResultType exnResult = ResultType::Single(RefType::extern_());
5044 popBlockResults(exnResult, tryCatch.stackHeight, ContinuationKind::Jump);
5045 freeResultRegisters(exnResult);
5046
5047 bool hasCatchAll = false;
5048 for (CatchInfo& info : tryCatch.catchInfos) {
5049 if (info.tagIndex != CatchAllIndex) {
5050 MOZ_ASSERT(!hasCatchAll);
5051 loadTag(RegPtr(InstanceReg), info.tagIndex, catchTag);
5052 masm.branchPtr(Assembler::Equal, tag, catchTag, &info.label);
5053 } else {
5054 masm.jump(&info.label);
5055 hasCatchAll = true;
5056 }
5057 }
5058 freeRef(catchTag);
5059 freeRef(tag);
5060
5061 // If none of the tag checks succeed and there is no catch_all,
5062 // then we rethrow the exception.
5063 if (!hasCatchAll) {
5064 captureResultRegisters(exnResult);
5065 if (!pushBlockResults(exnResult) || !throwFrom(popRef())) {
5066 return false;
5067 }
5068 }
5069
5070 // Reset stack height for join.
5071 fr.setStackHeight(prePadHeight);
5072
5073 // Create join point.
5074 if (tryCatch.label.used()) {
5075 masm.bind(&tryCatch.label);
5076 }
5077
5078 captureResultRegisters(type);
5079 deadCode_ = tryCatch.deadOnArrival;
5080 bceSafe_ = tryCatch.bceSafeOnExit;
5081
5082 return pushBlockResults(type);
5083 }
5084
5085 bool BaseCompiler::endTryTable(ResultType type) {
5086 if (!controlItem().deadOnArrival) {
5087 // Mark the end of the try body. This may insert a nop.
5088 finishTryNote(controlItem().tryNoteIndex);
5089 }
5090 return endBlock(type);
5091 }
5092
5093 bool BaseCompiler::emitThrow() {
5094 uint32_t tagIndex;
5095 BaseNothingVector unused_argValues{};
5096
5097 if (!iter_.readThrow(&tagIndex, &unused_argValues)) {
5098 return false;
5099 }
5100
5101 if (deadCode_) {
5102 return true;
5103 }
5104
5105 const TagDesc& tagDesc = codeMeta_.tags[tagIndex];
5106 const ResultType& params = tagDesc.type->resultType();
5107 const TagOffsetVector& offsets = tagDesc.type->argOffsets();
5108
5109 // Load the tag object
5110 #ifdef RABALDR_PIN_INSTANCE
5111 RegPtr instance(InstanceReg);
5112 #else
5113 RegPtr instance = needPtr();
5114 fr.loadInstancePtr(instance);
5115 #endif
5116 RegRef tag = needRef();
5117 loadTag(instance, tagIndex, tag);
5118 #ifndef RABALDR_PIN_INSTANCE
5119 freePtr(instance);
5120 #endif
5121
5122 // Create the new exception object that we will throw.
5123 pushRef(tag);
5124 if (!emitInstanceCall(SASigExceptionNew)) {
5125 return false;
5126 }
5127
5128 // Get registers for exn and data, excluding the prebarrier register
5129 needPtr(RegPtr(PreBarrierReg));
5130 RegRef exn = popRef();
5131 RegPtr data = needPtr();
5132 freePtr(RegPtr(PreBarrierReg));
5133
5134 masm.loadPtr(Address(exn, WasmExceptionObject::offsetOfData()), data);
5135
5136 for (int32_t i = params.length() - 1; i >= 0; i--) {
5137 uint32_t offset = offsets[i];
5138 switch (params[i].kind()) {
5139 case ValType::I32: {
5140 RegI32 reg = popI32();
5141 masm.store32(reg, Address(data, offset));
5142 freeI32(reg);
5143 break;
5144 }
5145 case ValType::I64: {
5146 RegI64 reg = popI64();
5147 masm.store64(reg, Address(data, offset));
5148 freeI64(reg);
5149 break;
5150 }
5151 case ValType::F32: {
5152 RegF32 reg = popF32();
5153 masm.storeFloat32(reg, Address(data, offset));
5154 freeF32(reg);
5155 break;
5156 }
5157 case ValType::F64: {
5158 RegF64 reg = popF64();
5159 masm.storeDouble(reg, Address(data, offset));
5160 freeF64(reg);
5161 break;
5162 }
5163 case ValType::V128: {
5164 #ifdef ENABLE_WASM_SIMD
5165 RegV128 reg = popV128();
5166 masm.storeUnalignedSimd128(reg, Address(data, offset));
5167 freeV128(reg);
5168 break;
5169 #else
5170 MOZ_CRASH("No SIMD support");
5171 #endif
5172 }
5173 case ValType::Ref: {
5174 RegPtr valueAddr(PreBarrierReg);
5175 needPtr(valueAddr);
5176 masm.computeEffectiveAddress(Address(data, offset), valueAddr);
5177 RegRef rv = popRef();
5178 pushPtr(data);
5179 // emitBarrieredStore preserves exn, rv
5180 if (!emitBarrieredStore(Some(exn), valueAddr, rv,
5181 PreBarrierKind::Normal,
5182 PostBarrierKind::Imprecise)) {
5183 return false;
5184 }
5185 popPtr(data);
5186 freeRef(rv);
5187 break;
5188 }
5189 }
5190 }
5191 freePtr(data);
5192
5193 deadCode_ = true;
5194
5195 return throwFrom(exn);
5196 }
5197
5198 bool BaseCompiler::emitThrowRef() {
5199 Nothing unused{};
5200
5201 if (!iter_.readThrowRef(&unused)) {
5202 return false;
5203 }
5204
5205 if (deadCode_) {
5206 return true;
5207 }
5208
5209 RegRef exn = popRef();
5210 Label ok;
5211 masm.branchWasmAnyRefIsNull(false, exn, &ok);
5212 trap(Trap::NullPointerDereference);
5213 masm.bind(&ok);
5214 deadCode_ = true;
5215 return throwFrom(exn);
5216 }
5217
5218 bool BaseCompiler::emitRethrow() {
5219 uint32_t relativeDepth;
5220 if (!iter_.readRethrow(&relativeDepth)) {
5221 return false;
5222 }
5223
5224 if (deadCode_) {
5225 return true;
5226 }
5227
5228 Control& tryCatch = controlItem(relativeDepth);
5229 RegRef exn = needRef();
5230 peekRefAt(tryCatch.stackSize, exn);
5231
5232 deadCode_ = true;
5233
5234 return throwFrom(exn);
5235 }
5236
5237 bool BaseCompiler::emitDrop() {
5238 if (!iter_.readDrop()) {
5239 return false;
5240 }
5241
5242 if (deadCode_) {
5243 return true;
5244 }
5245
5246 dropValue();
5247 return true;
5248 }
5249
5250 void BaseCompiler::doReturn(ContinuationKind kind) {
5251 if (deadCode_) {
5252 return;
5253 }
5254
5255 StackHeight height = controlOutermost().stackHeight;
5256 ResultType type = ResultType::Vector(funcType().results());
5257 popBlockResults(type, height, kind);
5258 masm.jump(&returnLabel_);
5259 freeResultRegisters(type);
5260 }
5261
5262 bool BaseCompiler::emitReturn() {
5263 BaseNothingVector unused_values{};
5264 if (!iter_.readReturn(&unused_values)) {
5265 return false;
5266 }
5267
5268 if (deadCode_) {
5269 return true;
5270 }
5271
5272 doReturn(ContinuationKind::Jump);
5273 deadCode_ = true;
5274
5275 return true;
5276 }
5277
5278 template <typename T>
5279 bool BaseCompiler::emitCallArgs(const ValTypeVector& argTypes, T results,
5280 FunctionCall* baselineCall,
5281 CalleeOnStack calleeOnStack) {
5282 MOZ_ASSERT(!deadCode_);
5283
5284 ArgTypeVector args(argTypes, results.stackResults());
5285 uint32_t naturalArgCount = argTypes.length();
5286 uint32_t abiArgCount = args.lengthWithStackResults();
5287 startCallArgs(StackArgAreaSizeUnaligned(args), baselineCall);
5288
5289 // Args are deeper on the stack than the stack result area, if any.
5290 size_t argsDepth = results.onStackCount();
5291 // They're deeper than the callee too, for callIndirect.
5292 if (calleeOnStack == CalleeOnStack::True) {
5293 argsDepth++;
5294 }
5295
5296 for (size_t i = 0; i < abiArgCount; ++i) {
5297 if (args.isNaturalArg(i)) {
5298 size_t naturalIndex = args.naturalIndex(i);
5299 size_t stackIndex = naturalArgCount - 1 - naturalIndex + argsDepth;
5300 passArg(argTypes[naturalIndex], peek(stackIndex), baselineCall);
5301 } else {
5302 // The synthetic stack result area pointer.
5303 ABIArg argLoc = baselineCall->abi.next(MIRType::Pointer);
5304 if (argLoc.kind() == ABIArg::Stack) {
5305 ScratchPtr scratch(*this);
5306 results.getStackResultArea(fr, scratch);
5307 masm.storePtr(scratch, Address(masm.getStackPointer(),
5308 argLoc.offsetFromArgBase()));
5309 } else {
5310 results.getStackResultArea(fr, RegPtr(argLoc.gpr()));
5311 }
5312 }
5313 }
5314
5315 #ifndef RABALDR_PIN_INSTANCE
5316 fr.loadInstancePtr(InstanceReg);
5317 #endif
5318 return true;
5319 }
5320
5321 void BaseCompiler::pushReturnValueOfCall(const FunctionCall& call,
5322 MIRType type) {
5323 switch (type) {
5324 case MIRType::Int32: {
5325 RegI32 rv = captureReturnedI32();
5326 pushI32(rv);
5327 break;
5328 }
5329 case MIRType::Int64: {
5330 RegI64 rv = captureReturnedI64();
5331 pushI64(rv);
5332 break;
5333 }
5334 case MIRType::Float32: {
5335 RegF32 rv = captureReturnedF32(call);
5336 pushF32(rv);
5337 break;
5338 }
5339 case MIRType::Double: {
5340 RegF64 rv = captureReturnedF64(call);
5341 pushF64(rv);
5342 break;
5343 }
5344 #ifdef ENABLE_WASM_SIMD
5345 case MIRType::Simd128: {
5346 RegV128 rv = captureReturnedV128(call);
5347 pushV128(rv);
5348 break;
5349 }
5350 #endif
5351 case MIRType::WasmAnyRef: {
5352 RegRef rv = captureReturnedRef();
5353 pushRef(rv);
5354 break;
5355 }
5356 default:
5357 // In particular, passing |type| as MIRType::Void or MIRType::Pointer to
5358 // this function is an error.
5359 MOZ_CRASH("Function return type");
5360 }
5361 }
5362
5363 bool BaseCompiler::pushStackResultsForCall(const ResultType& type, RegPtr temp,
5364 StackResultsLoc* loc) {
5365 if (!ABIResultIter::HasStackResults(type)) {
5366 return true;
5367 }
5368
5369 // This method can increase stk_.length() by an unbounded amount, so we need
5370 // to perform an allocation here to accomodate the variable number of values.
5371 // There is enough headroom for any fixed number of values. The general case
5372 // is handled in emitBody.
5373 if (!stk_.reserve(stk_.length() + type.length())) {
5374 return false;
5375 }
5376
5377 // Measure stack results.
5378 ABIResultIter i(type);
5379 size_t count = 0;
5380 for (; !i.done(); i.next()) {
5381 if (i.cur().onStack()) {
5382 count++;
5383 }
5384 }
5385 uint32_t bytes = i.stackBytesConsumedSoFar();
5386
5387 // Reserve space for the stack results.
5388 StackHeight resultsBase = fr.stackHeight();
5389 uint32_t height = fr.prepareStackResultArea(resultsBase, bytes);
5390
5391 // Push Stk values onto the value stack, and zero out Ref values.
5392 for (i.switchToPrev(); !i.done(); i.prev()) {
5393 const ABIResult& result = i.cur();
5394 if (result.onStack()) {
5395 Stk v = captureStackResult(result, resultsBase, bytes);
5396 push(v);
5397 if (v.kind() == Stk::MemRef) {
5398 stackMapGenerator_.memRefsOnStk++;
5399 fr.storeImmediatePtrToStack(intptr_t(0), v.offs(), temp);
5400 }
5401 }
5402 }
5403
5404 *loc = StackResultsLoc(bytes, count, height);
5405
5406 return true;
5407 }
5408
5409 // After a call, some results may be written to the stack result locations that
5410 // are pushed on the machine stack after any stack args. If there are stack
5411 // args and stack results, these results need to be shuffled down, as the args
5412 // are "consumed" by the call.
5413 void BaseCompiler::popStackResultsAfterCall(const StackResultsLoc& results,
5414 uint32_t stackArgBytes) {
5415 if (results.bytes() != 0) {
5416 popValueStackBy(results.count());
5417 if (stackArgBytes != 0) {
5418 uint32_t srcHeight = results.height();
5419 MOZ_ASSERT(srcHeight >= stackArgBytes + results.bytes());
5420 uint32_t destHeight = srcHeight - stackArgBytes;
5421
5422 fr.shuffleStackResultsTowardFP(srcHeight, destHeight, results.bytes(),
5423 ABINonArgReturnVolatileReg);
5424 }
5425 }
5426 }
5427
5428 // For now, always sync() at the beginning of the call to easily save live
5429 // values.
5430 //
5431 // TODO / OPTIMIZE (Bug 1316806): We may be able to avoid a full sync(), since
5432 // all we want is to save live registers that won't be saved by the callee or
5433 // that we need for outgoing args - we don't need to sync the locals. We can
5434 // just push the necessary registers, it'll be like a lightweight sync.
5435 //
5436 // Even some of the pushing may be unnecessary if the registers will be consumed
5437 // by the call, because then what we want is parallel assignment to the argument
5438 // registers or onto the stack for outgoing arguments. A sync() is just
5439 // simpler.
5440
5441 bool BaseCompiler::emitCall() {
5442 uint32_t funcIndex;
5443 BaseNothingVector args_{};
5444 if (!iter_.readCall(&funcIndex, &args_)) {
5445 return false;
5446 }
5447
5448 if (deadCode_) {
5449 return true;
5450 }
5451
5452 sync();
5453
5454 const FuncType& funcType = codeMeta_.getFuncType(funcIndex);
5455 bool import = codeMeta_.funcIsImport(funcIndex);
5456
5457 uint32_t numArgs = funcType.args().length();
5458 size_t stackArgBytes = stackConsumed(numArgs);
5459
5460 ResultType resultType(ResultType::Vector(funcType.results()));
5461 StackResultsLoc results;
5462 if (!pushStackResultsForCall(resultType, RegPtr(ABINonArgReg0), &results)) {
5463 return false;
5464 }
5465
5466 FunctionCall baselineCall{};
5467 beginCall(baselineCall, UseABI::Wasm,
5468 import ? RestoreRegisterStateAndRealm::True
5469 : RestoreRegisterStateAndRealm::False);
5470
5471 if (!emitCallArgs(funcType.args(), NormalCallResults(results), &baselineCall,
5472 CalleeOnStack::False)) {
5473 return false;
5474 }
5475
5476 CodeOffset raOffset;
5477 if (import) {
5478 raOffset = callImport(codeMeta_.offsetOfFuncImportInstanceData(funcIndex),
5479 baselineCall);
5480 } else {
5481 raOffset = callDefinition(funcIndex, baselineCall);
5482 }
5483
5484 if (!createStackMap("emitCall", raOffset)) {
5485 return false;
5486 }
5487
5488 popStackResultsAfterCall(results, stackArgBytes);
5489
5490 endCall(baselineCall, stackArgBytes);
5491
5492 popValueStackBy(numArgs);
5493
5494 captureCallResultRegisters(resultType);
5495 return pushCallResults(baselineCall, resultType, results);
5496 }
5497
5498 bool BaseCompiler::emitReturnCall() {
5499 uint32_t funcIndex;
5500 BaseNothingVector args_{};
5501 if (!iter_.readReturnCall(&funcIndex, &args_)) {
5502 return false;
5503 }
5504
5505 if (deadCode_) {
5506 return true;
5507 }
5508
5509 sync();
5510 if (!insertDebugCollapseFrame()) {
5511 return false;
5512 }
5513
5514 const FuncType& funcType = codeMeta_.getFuncType(funcIndex);
5515 bool import = codeMeta_.funcIsImport(funcIndex);
5516
5517 uint32_t numArgs = funcType.args().length();
5518
5519 FunctionCall baselineCall{};
5520 beginCall(baselineCall, UseABI::Wasm,
5521 import ? RestoreRegisterStateAndRealm::True
5522 : RestoreRegisterStateAndRealm::False);
5523
5524 if (!emitCallArgs(funcType.args(), TailCallResults(funcType), &baselineCall,
5525 CalleeOnStack::False)) {
5526 return false;
5527 }
5528
5529 ReturnCallAdjustmentInfo retCallInfo =
5530 BuildReturnCallAdjustmentInfo(this->funcType(), funcType);
5531
5532 if (import) {
5533 CallSiteDesc desc(bytecodeOffset(), CallSiteKind::Import);
5534 CalleeDesc callee =
5535 CalleeDesc::import(codeMeta_.offsetOfFuncImportInstanceData(funcIndex));
5536 masm.wasmReturnCallImport(desc, callee, retCallInfo);
5537 } else {
5538 CallSiteDesc desc(bytecodeOffset(), CallSiteKind::ReturnFunc);
5539 masm.wasmReturnCall(desc, funcIndex, retCallInfo);
5540 }
5541
5542 MOZ_ASSERT(stackMapGenerator_.framePushedExcludingOutboundCallArgs.isSome());
5543 stackMapGenerator_.framePushedExcludingOutboundCallArgs.reset();
5544
5545 popValueStackBy(numArgs);
5546
5547 deadCode_ = true;
5548 return true;
5549 }
5550
5551 bool BaseCompiler::emitCallIndirect() {
5552 uint32_t funcTypeIndex;
5553 uint32_t tableIndex;
5554 Nothing callee_;
5555 BaseNothingVector args_{};
5556 if (!iter_.readCallIndirect(&funcTypeIndex, &tableIndex, &callee_, &args_)) {
5557 return false;
5558 }
5559
5560 if (deadCode_) {
5561 return true;
5562 }
5563
5564 // Stack: ... arg1 .. argn callee
5565
5566 replaceTableAddressWithClampedInt32(
5567 codeMeta_.tables[tableIndex].addressType());
5568
5569 sync();
5570
5571 const FuncType& funcType = (*codeMeta_.types)[funcTypeIndex].funcType();
5572
5573 uint32_t numArgs = funcType.args().length() + 1;
5574 size_t stackArgBytes = stackConsumed(numArgs);
5575
5576 ResultType resultType(ResultType::Vector(funcType.results()));
5577 StackResultsLoc results;
5578 if (!pushStackResultsForCall(resultType, RegPtr(ABINonArgReg0), &results)) {
5579 return false;
5580 }
5581
5582 FunctionCall baselineCall{};
5583 // State and realm are restored as needed by by callIndirect (really by
5584 // MacroAssembler::wasmCallIndirect).
5585 beginCall(baselineCall, UseABI::Wasm, RestoreRegisterStateAndRealm::False);
5586
5587 if (!emitCallArgs(funcType.args(), NormalCallResults(results), &baselineCall,
5588 CalleeOnStack::True)) {
5589 return false;
5590 }
5591
5592 const Stk& callee = peek(results.count());
5593 CodeOffset fastCallOffset;
5594 CodeOffset slowCallOffset;
5595 if (!callIndirect(funcTypeIndex, tableIndex, callee, baselineCall,
5596 /*tailCall*/ false, &fastCallOffset, &slowCallOffset)) {
5597 return false;
5598 }
5599 if (!createStackMap("emitCallIndirect", fastCallOffset)) {
5600 return false;
5601 }
5602 if (!createStackMap("emitCallIndirect", slowCallOffset)) {
5603 return false;
5604 }
5605
5606 popStackResultsAfterCall(results, stackArgBytes);
5607
5608 endCall(baselineCall, stackArgBytes);
5609
5610 popValueStackBy(numArgs);
5611
5612 captureCallResultRegisters(resultType);
5613 return pushCallResults(baselineCall, resultType, results);
5614 }
5615
5616 bool BaseCompiler::emitReturnCallIndirect() {
5617 uint32_t funcTypeIndex;
5618 uint32_t tableIndex;
5619 Nothing callee_;
5620 BaseNothingVector args_{};
5621 if (!iter_.readReturnCallIndirect(&funcTypeIndex, &tableIndex, &callee_,
5622 &args_)) {
5623 return false;
5624 }
5625
5626 if (deadCode_) {
5627 return true;
5628 }
5629
5630 // Stack: ... arg1 .. argn callee
5631
5632 replaceTableAddressWithClampedInt32(
5633 codeMeta_.tables[tableIndex].addressType());
5634
5635 sync();
5636 if (!insertDebugCollapseFrame()) {
5637 return false;
5638 }
5639
5640 const FuncType& funcType = (*codeMeta_.types)[funcTypeIndex].funcType();
5641
5642 uint32_t numArgs = funcType.args().length() + 1;
5643
5644 FunctionCall baselineCall{};
5645 // State and realm are restored as needed by by callIndirect (really by
5646 // MacroAssembler::wasmCallIndirect).
5647 beginCall(baselineCall, UseABI::Wasm, RestoreRegisterStateAndRealm::False);
5648
5649 if (!emitCallArgs(funcType.args(), TailCallResults(funcType), &baselineCall,
5650 CalleeOnStack::True)) {
5651 return false;
5652 }
5653
5654 const Stk& callee = peek(0);
5655 CodeOffset fastCallOffset;
5656 CodeOffset slowCallOffset;
5657 if (!callIndirect(funcTypeIndex, tableIndex, callee, baselineCall,
5658 /*tailCall*/ true, &fastCallOffset, &slowCallOffset)) {
5659 return false;
5660 }
5661
5662 MOZ_ASSERT(stackMapGenerator_.framePushedExcludingOutboundCallArgs.isSome());
5663 stackMapGenerator_.framePushedExcludingOutboundCallArgs.reset();
5664
5665 popValueStackBy(numArgs);
5666
5667 deadCode_ = true;
5668 return true;
5669 }
5670
5671 bool BaseCompiler::emitCallRef() {
5672 uint32_t funcTypeIndex;
5673 Nothing unused_callee;
5674 BaseNothingVector unused_args{};
5675 if (!iter_.readCallRef(&funcTypeIndex, &unused_callee, &unused_args)) {
5676 return false;
5677 }
5678
5679 // Add a metrics entry to track this call_ref site. Do this even if we're in
5680 // 'dead code' to have easy consistency with ion, which consumes these.
5681 Maybe<size_t> callRefIndex;
5682 if (compilerEnv_.mode() == CompileMode::LazyTiering) {
5683 masm.append(wasm::CallRefMetricsPatch());
5684 if (masm.oom()) {
5685 return false;
5686 }
5687 callRefIndex = Some(masm.callRefMetricsPatches().length() - 1);
5688 }
5689
5690 if (deadCode_) {
5691 return true;
5692 }
5693
5694 const FuncType& funcType = codeMeta_.types->type(funcTypeIndex).funcType();
5695
5696 sync();
5697
5698 // Stack: ... arg1 .. argn callee
5699
5700 uint32_t numArgs = funcType.args().length() + 1;
5701 size_t stackArgBytes = stackConsumed(numArgs);
5702
5703 ResultType resultType(ResultType::Vector(funcType.results()));
5704 StackResultsLoc results;
5705 if (!pushStackResultsForCall(resultType, RegPtr(ABINonArgReg0), &results)) {
5706 return false;
5707 }
5708
5709 FunctionCall baselineCall{};
5710 // State and realm are restored as needed by by callRef (really by
5711 // MacroAssembler::wasmCallRef).
5712 beginCall(baselineCall, UseABI::Wasm, RestoreRegisterStateAndRealm::False);
5713
5714 if (!emitCallArgs(funcType.args(), NormalCallResults(results), &baselineCall,
5715 CalleeOnStack::True)) {
5716 return false;
5717 }
5718
5719 const Stk& callee = peek(results.count());
5720 CodeOffset fastCallOffset;
5721 CodeOffset slowCallOffset;
5722 if (!callRef(callee, baselineCall, callRefIndex, &fastCallOffset,
5723 &slowCallOffset)) {
5724 return false;
5725 }
5726 if (!createStackMap("emitCallRef", fastCallOffset)) {
5727 return false;
5728 }
5729 if (!createStackMap("emitCallRef", slowCallOffset)) {
5730 return false;
5731 }
5732
5733 popStackResultsAfterCall(results, stackArgBytes);
5734
5735 endCall(baselineCall, stackArgBytes);
5736
5737 popValueStackBy(numArgs);
5738
5739 captureCallResultRegisters(resultType);
5740 return pushCallResults(baselineCall, resultType, results);
5741 }
5742
5743 bool BaseCompiler::emitReturnCallRef() {
5744 uint32_t funcTypeIndex;
5745 Nothing unused_callee;
5746 BaseNothingVector unused_args{};
5747 if (!iter_.readReturnCallRef(&funcTypeIndex, &unused_callee, &unused_args)) {
5748 return false;
5749 }
5750
5751 if (deadCode_) {
5752 return true;
5753 }
5754
5755 const FuncType& funcType = codeMeta_.types->type(funcTypeIndex).funcType();
5756
5757 sync();
5758
5759 if (!insertDebugCollapseFrame()) {
5760 return false;
5761 }
5762
5763 // Stack: ... arg1 .. argn callee
5764
5765 uint32_t numArgs = funcType.args().length() + 1;
5766
5767 FunctionCall baselineCall{};
5768 // State and realm are restored as needed by by callRef (really by
5769 // MacroAssembler::wasmCallRef).
5770 beginCall(baselineCall, UseABI::Wasm, RestoreRegisterStateAndRealm::False);
5771
5772 if (!emitCallArgs(funcType.args(), TailCallResults(funcType), &baselineCall,
5773 CalleeOnStack::True)) {
5774 return false;
5775 }
5776
5777 const Stk& callee = peek(0);
5778 returnCallRef(callee, baselineCall, funcType);
5779
5780 MOZ_ASSERT(stackMapGenerator_.framePushedExcludingOutboundCallArgs.isSome());
5781 stackMapGenerator_.framePushedExcludingOutboundCallArgs.reset();
5782
5783 popValueStackBy(numArgs);
5784
5785 deadCode_ = true;
5786 return true;
5787 }
5788
5789 void BaseCompiler::emitRound(RoundingMode roundingMode, ValType operandType) {
5790 if (operandType == ValType::F32) {
5791 RegF32 f0 = popF32();
5792 roundF32(roundingMode, f0);
5793 pushF32(f0);
5794 } else if (operandType == ValType::F64) {
5795 RegF64 f0 = popF64();
5796 roundF64(roundingMode, f0);
5797 pushF64(f0);
5798 } else {
5799 MOZ_CRASH("unexpected type");
5800 }
5801 }
5802
5803 bool BaseCompiler::emitUnaryMathBuiltinCall(SymbolicAddress callee,
5804 ValType operandType) {
5805 Nothing operand_;
5806 if (!iter_.readUnary(operandType, &operand_)) {
5807 return false;
5808 }
5809
5810 if (deadCode_) {
5811 return true;
5812 }
5813
5814 RoundingMode roundingMode;
5815 if (IsRoundingFunction(callee, &roundingMode) &&
5816 supportsRoundInstruction(roundingMode)) {
5817 emitRound(roundingMode, operandType);
5818 return true;
5819 }
5820
5821 sync();
5822
5823 ValTypeVector& signature = operandType == ValType::F32 ? SigF_ : SigD_;
5824 ValType retType = operandType;
5825 uint32_t numArgs = signature.length();
5826 size_t stackSpace = stackConsumed(numArgs);
5827
5828 FunctionCall baselineCall{};
5829 beginCall(baselineCall, UseABI::Builtin, RestoreRegisterStateAndRealm::False);
5830
5831 if (!emitCallArgs(signature, NoCallResults(), &baselineCall,
5832 CalleeOnStack::False)) {
5833 return false;
5834 }
5835
5836 CodeOffset raOffset = builtinCall(callee, baselineCall);
5837 if (!createStackMap("emitUnaryMathBuiltin[..]", raOffset)) {
5838 return false;
5839 }
5840
5841 endCall(baselineCall, stackSpace);
5842
5843 popValueStackBy(numArgs);
5844
5845 pushReturnValueOfCall(baselineCall, retType.toMIRType());
5846
5847 return true;
5848 }
5849
5850 #ifdef RABALDR_INT_DIV_I64_CALLOUT
5851 bool BaseCompiler::emitDivOrModI64BuiltinCall(SymbolicAddress callee,
5852 ValType operandType) {
5853 MOZ_ASSERT(operandType == ValType::I64);
5854 MOZ_ASSERT(!deadCode_);
5855
5856 sync();
5857
5858 needI64(specific_.abiReturnRegI64);
5859
5860 RegI64 rhs = popI64();
5861 RegI64 srcDest = popI64ToSpecific(specific_.abiReturnRegI64);
5862
5863 Label done;
5864
5865 checkDivideByZero(rhs);
5866
5867 if (callee == SymbolicAddress::DivI64) {
5868 checkDivideSignedOverflow(rhs, srcDest, &done, ZeroOnOverflow(false));
5869 } else if (callee == SymbolicAddress::ModI64) {
5870 checkDivideSignedOverflow(rhs, srcDest, &done, ZeroOnOverflow(true));
5871 }
5872
5873 masm.setupWasmABICall();
5874 masm.passABIArg(srcDest.high);
5875 masm.passABIArg(srcDest.low);
5876 masm.passABIArg(rhs.high);
5877 masm.passABIArg(rhs.low);
5878 CodeOffset raOffset = masm.callWithABI(
5879 bytecodeOffset(), callee, mozilla::Some(fr.getInstancePtrOffset()));
5880 if (!createStackMap("emitDivOrModI64Bui[..]", raOffset)) {
5881 return false;
5882 }
5883
5884 masm.bind(&done);
5885
5886 freeI64(rhs);
5887 pushI64(srcDest);
5888 return true;
5889 }
5890 #endif // RABALDR_INT_DIV_I64_CALLOUT
5891
5892 #ifdef RABALDR_I64_TO_FLOAT_CALLOUT
5893 bool BaseCompiler::emitConvertInt64ToFloatingCallout(SymbolicAddress callee,
5894 ValType operandType,
5895 ValType resultType) {
5896 sync();
5897
5898 RegI64 input = popI64();
5899
5900 FunctionCall call{};
5901
5902 masm.setupWasmABICall();
5903 # ifdef JS_PUNBOX64
5904 MOZ_CRASH("BaseCompiler platform hook: emitConvertInt64ToFloatingCallout");
5905 # else
5906 masm.passABIArg(input.high);
5907 masm.passABIArg(input.low);
5908 # endif
5909 CodeOffset raOffset = masm.callWithABI(
5910 bytecodeOffset(), callee, mozilla::Some(fr.getInstancePtrOffset()),
5911 resultType == ValType::F32 ? ABIType::Float32 : ABIType::Float64);
5912 if (!createStackMap("emitConvertInt64To[..]", raOffset)) {
5913 return false;
5914 }
5915
5916 freeI64(input);
5917
5918 if (resultType == ValType::F32) {
5919 pushF32(captureReturnedF32(call));
5920 } else {
5921 pushF64(captureReturnedF64(call));
5922 }
5923
5924 return true;
5925 }
5926 #endif // RABALDR_I64_TO_FLOAT_CALLOUT
5927
5928 #ifdef RABALDR_FLOAT_TO_I64_CALLOUT
5929 // `Callee` always takes a double, so a float32 input must be converted.
5930 bool BaseCompiler::emitConvertFloatingToInt64Callout(SymbolicAddress callee,
5931 ValType operandType,
5932 ValType resultType) {
5933 RegF64 doubleInput;
5934 if (operandType == ValType::F32) {
5935 doubleInput = needF64();
5936 RegF32 input = popF32();
5937 masm.convertFloat32ToDouble(input, doubleInput);
5938 freeF32(input);
5939 } else {
5940 doubleInput = popF64();
5941 }
5942
5943 // We may need the value after the call for the ool check.
5944 RegF64 otherReg = needF64();
5945 moveF64(doubleInput, otherReg);
5946 pushF64(otherReg);
5947
5948 sync();
5949
5950 FunctionCall call{};
5951
5952 masm.setupWasmABICall();
5953 masm.passABIArg(doubleInput, ABIType::Float64);
5954 CodeOffset raOffset = masm.callWithABI(
5955 bytecodeOffset(), callee, mozilla::Some(fr.getInstancePtrOffset()));
5956 if (!createStackMap("emitConvertFloatin[..]", raOffset)) {
5957 return false;
5958 }
5959
5960 freeF64(doubleInput);
5961
5962 RegI64 rv = captureReturnedI64();
5963
5964 RegF64 inputVal = popF64();
5965
5966 TruncFlags flags = 0;
5967 if (callee == SymbolicAddress::TruncateDoubleToUint64) {
5968 flags |= TRUNC_UNSIGNED;
5969 }
5970 if (callee == SymbolicAddress::SaturatingTruncateDoubleToInt64 ||
5971 callee == SymbolicAddress::SaturatingTruncateDoubleToUint64) {
5972 flags |= TRUNC_SATURATING;
5973 }
5974
5975 // If we're saturating, the callout will always produce the final result
5976 // value. Otherwise, the callout value will return 0x8000000000000000
5977 // and we need to produce traps.
5978 OutOfLineCode* ool = nullptr;
5979 if (!(flags & TRUNC_SATURATING)) {
5980 // The OOL check just succeeds or fails, it does not generate a value.
5981 ool = addOutOfLineCode(new (alloc_) OutOfLineTruncateCheckF32OrF64ToI64(
5982 AnyReg(inputVal), rv, flags, trapSiteDesc()));
5983 if (!ool) {
5984 return false;
5985 }
5986
5987 masm.branch64(Assembler::Equal, rv, Imm64(0x8000000000000000),
5988 ool->entry());
5989 masm.bind(ool->rejoin());
5990 }
5991
5992 pushI64(rv);
5993 freeF64(inputVal);
5994
5995 return true;
5996 }
5997 #endif // RABALDR_FLOAT_TO_I64_CALLOUT
5998
5999 bool BaseCompiler::emitGetLocal() {
6000 uint32_t slot;
6001 if (!iter_.readGetLocal(&slot)) {
6002 return false;
6003 }
6004
6005 if (deadCode_) {
6006 return true;
6007 }
6008
6009 // Local loads are pushed unresolved, ie, they may be deferred
6010 // until needed, until they may be affected by a store, or until a
6011 // sync. This is intended to reduce register pressure.
6012
6013 switch (locals_[slot].kind()) {
6014 case ValType::I32:
6015 pushLocalI32(slot);
6016 break;
6017 case ValType::I64:
6018 pushLocalI64(slot);
6019 break;
6020 case ValType::V128:
6021 #ifdef ENABLE_WASM_SIMD
6022 pushLocalV128(slot);
6023 break;
6024 #else
6025 MOZ_CRASH("No SIMD support");
6026 #endif
6027 case ValType::F64:
6028 pushLocalF64(slot);
6029 break;
6030 case ValType::F32:
6031 pushLocalF32(slot);
6032 break;
6033 case ValType::Ref:
6034 pushLocalRef(slot);
6035 break;
6036 }
6037
6038 return true;
6039 }
6040
6041 template <bool isSetLocal>
6042 bool BaseCompiler::emitSetOrTeeLocal(uint32_t slot) {
6043 if (deadCode_) {
6044 return true;
6045 }
6046
6047 bceLocalIsUpdated(slot);
6048 switch (locals_[slot].kind()) {
6049 case ValType::I32: {
6050 RegI32 rv = popI32();
6051 syncLocal(slot);
6052 fr.storeLocalI32(rv, localFromSlot(slot, MIRType::Int32));
6053 if (isSetLocal) {
6054 freeI32(rv);
6055 } else {
6056 pushI32(rv);
6057 }
6058 break;
6059 }
6060 case ValType::I64: {
6061 RegI64 rv = popI64();
6062 syncLocal(slot);
6063 fr.storeLocalI64(rv, localFromSlot(slot, MIRType::Int64));
6064 if (isSetLocal) {
6065 freeI64(rv);
6066 } else {
6067 pushI64(rv);
6068 }
6069 break;
6070 }
6071 case ValType::F64: {
6072 RegF64 rv = popF64();
6073 syncLocal(slot);
6074 fr.storeLocalF64(rv, localFromSlot(slot, MIRType::Double));
6075 if (isSetLocal) {
6076 freeF64(rv);
6077 } else {
6078 pushF64(rv);
6079 }
6080 break;
6081 }
6082 case ValType::F32: {
6083 RegF32 rv = popF32();
6084 syncLocal(slot);
6085 fr.storeLocalF32(rv, localFromSlot(slot, MIRType::Float32));
6086 if (isSetLocal) {
6087 freeF32(rv);
6088 } else {
6089 pushF32(rv);
6090 }
6091 break;
6092 }
6093 case ValType::V128: {
6094 #ifdef ENABLE_WASM_SIMD
6095 RegV128 rv = popV128();
6096 syncLocal(slot);
6097 fr.storeLocalV128(rv, localFromSlot(slot, MIRType::Simd128));
6098 if (isSetLocal) {
6099 freeV128(rv);
6100 } else {
6101 pushV128(rv);
6102 }
6103 break;
6104 #else
6105 MOZ_CRASH("No SIMD support");
6106 #endif
6107 }
6108 case ValType::Ref: {
6109 RegRef rv = popRef();
6110 syncLocal(slot);
6111 fr.storeLocalRef(rv, localFromSlot(slot, MIRType::WasmAnyRef));
6112 if (isSetLocal) {
6113 freeRef(rv);
6114 } else {
6115 pushRef(rv);
6116 }
6117 break;
6118 }
6119 }
6120
6121 return true;
6122 }
6123
6124 bool BaseCompiler::emitSetLocal() {
6125 uint32_t slot;
6126 Nothing unused_value;
6127 if (!iter_.readSetLocal(&slot, &unused_value)) {
6128 return false;
6129 }
6130 return emitSetOrTeeLocal<true>(slot);
6131 }
6132
6133 bool BaseCompiler::emitTeeLocal() {
6134 uint32_t slot;
6135 Nothing unused_value;
6136 if (!iter_.readTeeLocal(&slot, &unused_value)) {
6137 return false;
6138 }
6139 return emitSetOrTeeLocal<false>(slot);
6140 }
6141
6142 bool BaseCompiler::emitGetGlobal() {
6143 uint32_t id;
6144 if (!iter_.readGetGlobal(&id)) {
6145 return false;
6146 }
6147
6148 if (deadCode_) {
6149 return true;
6150 }
6151
6152 const GlobalDesc& global = codeMeta_.globals[id];
6153
6154 if (global.isConstant()) {
6155 LitVal value = global.constantValue();
6156 switch (value.type().kind()) {
6157 case ValType::I32:
6158 pushI32(value.i32());
6159 break;
6160 case ValType::I64:
6161 pushI64(value.i64());
6162 break;
6163 case ValType::F32:
6164 pushF32(value.f32());
6165 break;
6166 case ValType::F64:
6167 pushF64(value.f64());
6168 break;
6169 case ValType::Ref:
6170 pushRef(intptr_t(value.ref().forCompiledCode()));
6171 break;
6172 #ifdef ENABLE_WASM_SIMD
6173 case ValType::V128:
6174 pushV128(value.v128());
6175 break;
6176 #endif
6177 default:
6178 MOZ_CRASH("Global constant type");
6179 }
6180 return true;
6181 }
6182
6183 switch (global.type().kind()) {
6184 case ValType::I32: {
6185 RegI32 rv = needI32();
6186 ScratchPtr tmp(*this);
6187 masm.load32(addressOfGlobalVar(global, tmp), rv);
6188 pushI32(rv);
6189 break;
6190 }
6191 case ValType::I64: {
6192 RegI64 rv = needI64();
6193 ScratchPtr tmp(*this);
6194 masm.load64(addressOfGlobalVar(global, tmp), rv);
6195 pushI64(rv);
6196 break;
6197 }
6198 case ValType::F32: {
6199 RegF32 rv = needF32();
6200 ScratchPtr tmp(*this);
6201 masm.loadFloat32(addressOfGlobalVar(global, tmp), rv);
6202 pushF32(rv);
6203 break;
6204 }
6205 case ValType::F64: {
6206 RegF64 rv = needF64();
6207 ScratchPtr tmp(*this);
6208 masm.loadDouble(addressOfGlobalVar(global, tmp), rv);
6209 pushF64(rv);
6210 break;
6211 }
6212 case ValType::Ref: {
6213 RegRef rv = needRef();
6214 ScratchPtr tmp(*this);
6215 masm.loadPtr(addressOfGlobalVar(global, tmp), rv);
6216 pushRef(rv);
6217 break;
6218 }
6219 #ifdef ENABLE_WASM_SIMD
6220 case ValType::V128: {
6221 RegV128 rv = needV128();
6222 ScratchPtr tmp(*this);
6223 masm.loadUnalignedSimd128(addressOfGlobalVar(global, tmp), rv);
6224 pushV128(rv);
6225 break;
6226 }
6227 #endif
6228 default:
6229 MOZ_CRASH("Global variable type");
6230 break;
6231 }
6232 return true;
6233 }
6234
6235 bool BaseCompiler::emitSetGlobal() {
6236 uint32_t id;
6237 Nothing unused_value;
6238 if (!iter_.readSetGlobal(&id, &unused_value)) {
6239 return false;
6240 }
6241
6242 if (deadCode_) {
6243 return true;
6244 }
6245
6246 const GlobalDesc& global = codeMeta_.globals[id];
6247
6248 switch (global.type().kind()) {
6249 case ValType::I32: {
6250 RegI32 rv = popI32();
6251 ScratchPtr tmp(*this);
6252 masm.store32(rv, addressOfGlobalVar(global, tmp));
6253 freeI32(rv);
6254 break;
6255 }
6256 case ValType::I64: {
6257 RegI64 rv = popI64();
6258 ScratchPtr tmp(*this);
6259 masm.store64(rv, addressOfGlobalVar(global, tmp));
6260 freeI64(rv);
6261 break;
6262 }
6263 case ValType::F32: {
6264 RegF32 rv = popF32();
6265 ScratchPtr tmp(*this);
6266 masm.storeFloat32(rv, addressOfGlobalVar(global, tmp));
6267 freeF32(rv);
6268 break;
6269 }
6270 case ValType::F64: {
6271 RegF64 rv = popF64();
6272 ScratchPtr tmp(*this);
6273 masm.storeDouble(rv, addressOfGlobalVar(global, tmp));
6274 freeF64(rv);
6275 break;
6276 }
6277 case ValType::Ref: {
6278 RegPtr valueAddr(PreBarrierReg);
6279 needPtr(valueAddr);
6280 {
6281 ScratchPtr tmp(*this);
6282 masm.computeEffectiveAddress(addressOfGlobalVar(global, tmp),
6283 valueAddr);
6284 }
6285 RegRef rv = popRef();
6286 // emitBarrieredStore preserves rv
6287 if (!emitBarrieredStore(Nothing(), valueAddr, rv, PreBarrierKind::Normal,
6288 PostBarrierKind::Imprecise)) {
6289 return false;
6290 }
6291 freeRef(rv);
6292 break;
6293 }
6294 #ifdef ENABLE_WASM_SIMD
6295 case ValType::V128: {
6296 RegV128 rv = popV128();
6297 ScratchPtr tmp(*this);
6298 masm.storeUnalignedSimd128(rv, addressOfGlobalVar(global, tmp));
6299 freeV128(rv);
6300 break;
6301 }
6302 #endif
6303 default:
6304 MOZ_CRASH("Global variable type");
6305 break;
6306 }
6307 return true;
6308 }
6309
6310 bool BaseCompiler::emitLoad(ValType type, Scalar::Type viewType) {
6311 LinearMemoryAddress<Nothing> addr;
6312 if (!iter_.readLoad(type, Scalar::byteSize(viewType), &addr)) {
6313 return false;
6314 }
6315 if (deadCode_) {
6316 return true;
6317 }
6318 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
6319 trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex));
6320 loadCommon(&access, AccessCheck(), type);
6321 return true;
6322 }
6323
6324 bool BaseCompiler::emitStore(ValType resultType, Scalar::Type viewType) {
6325 LinearMemoryAddress<Nothing> addr;
6326 Nothing unused_value;
6327 if (!iter_.readStore(resultType, Scalar::byteSize(viewType), &addr,
6328 &unused_value)) {
6329 return false;
6330 }
6331 if (deadCode_) {
6332 return true;
6333 }
6334 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
6335 trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex));
6336 storeCommon(&access, AccessCheck(), resultType);
6337 return true;
6338 }
6339
6340 bool BaseCompiler::emitSelect(bool typed) {
6341 StackType type;
6342 Nothing unused_trueValue;
6343 Nothing unused_falseValue;
6344 Nothing unused_condition;
6345 if (!iter_.readSelect(typed, &type, &unused_trueValue, &unused_falseValue,
6346 &unused_condition)) {
6347 return false;
6348 }
6349
6350 if (deadCode_) {
6351 resetLatentOp();
6352 return true;
6353 }
6354
6355 // I32 condition on top, then false, then true.
6356
6357 Label done;
6358 BranchState b(&done);
6359 emitBranchSetup(&b);
6360
6361 switch (type.valType().kind()) {
6362 case ValType::I32: {
6363 RegI32 r, rs;
6364 pop2xI32(&r, &rs);
6365 if (!emitBranchPerform(&b)) {
6366 return false;
6367 }
6368 moveI32(rs, r);
6369 masm.bind(&done);
6370 freeI32(rs);
6371 pushI32(r);
6372 break;
6373 }
6374 case ValType::I64: {
6375 #ifdef JS_CODEGEN_X86
6376 // There may be as many as four Int64 values in registers at a time: two
6377 // for the latent branch operands, and two for the true/false values we
6378 // normally pop before executing the branch. On x86 this is one value
6379 // too many, so we need to generate more complicated code here, and for
6380 // simplicity's sake we do so even if the branch operands are not Int64.
6381 // However, the resulting control flow diamond is complicated since the
6382 // arms of the diamond will have to stay synchronized with respect to
6383 // their evaluation stack and regalloc state. To simplify further, we
6384 // use a double branch and a temporary boolean value for now.
6385 RegI32 temp = needI32();
6386 moveImm32(0, temp);
6387 if (!emitBranchPerform(&b)) {
6388 return false;
6389 }
6390 moveImm32(1, temp);
6391 masm.bind(&done);
6392
6393 Label trueValue;
6394 RegI64 r, rs;
6395 pop2xI64(&r, &rs);
6396 masm.branch32(Assembler::Equal, temp, Imm32(0), &trueValue);
6397 moveI64(rs, r);
6398 masm.bind(&trueValue);
6399 freeI32(temp);
6400 freeI64(rs);
6401 pushI64(r);
6402 #else
6403 RegI64 r, rs;
6404 pop2xI64(&r, &rs);
6405 if (!emitBranchPerform(&b)) {
6406 return false;
6407 }
6408 moveI64(rs, r);
6409 masm.bind(&done);
6410 freeI64(rs);
6411 pushI64(r);
6412 #endif
6413 break;
6414 }
6415 case ValType::F32: {
6416 RegF32 r, rs;
6417 pop2xF32(&r, &rs);
6418 if (!emitBranchPerform(&b)) {
6419 return false;
6420 }
6421 moveF32(rs, r);
6422 masm.bind(&done);
6423 freeF32(rs);
6424 pushF32(r);
6425 break;
6426 }
6427 case ValType::F64: {
6428 RegF64 r, rs;
6429 pop2xF64(&r, &rs);
6430 if (!emitBranchPerform(&b)) {
6431 return false;
6432 }
6433 moveF64(rs, r);
6434 masm.bind(&done);
6435 freeF64(rs);
6436 pushF64(r);
6437 break;
6438 }
6439 #ifdef ENABLE_WASM_SIMD
6440 case ValType::V128: {
6441 RegV128 r, rs;
6442 pop2xV128(&r, &rs);
6443 if (!emitBranchPerform(&b)) {
6444 return false;
6445 }
6446 moveV128(rs, r);
6447 masm.bind(&done);
6448 freeV128(rs);
6449 pushV128(r);
6450 break;
6451 }
6452 #endif
6453 case ValType::Ref: {
6454 RegRef r, rs;
6455 pop2xRef(&r, &rs);
6456 if (!emitBranchPerform(&b)) {
6457 return false;
6458 }
6459 moveRef(rs, r);
6460 masm.bind(&done);
6461 freeRef(rs);
6462 pushRef(r);
6463 break;
6464 }
6465 default: {
6466 MOZ_CRASH("select type");
6467 }
6468 }
6469
6470 return true;
6471 }
6472
6473 void BaseCompiler::emitCompareI32(Assembler::Condition compareOp,
6474 ValType compareType) {
6475 MOZ_ASSERT(compareType == ValType::I32);
6476
6477 if (sniffConditionalControlCmp(compareOp, compareType)) {
6478 return;
6479 }
6480
6481 int32_t c;
6482 if (popConst(&c)) {
6483 RegI32 r = popI32();
6484 masm.cmp32Set(compareOp, r, Imm32(c), r);
6485 pushI32(r);
6486 } else {
6487 RegI32 r, rs;
6488 pop2xI32(&r, &rs);
6489 masm.cmp32Set(compareOp, r, rs, r);
6490 freeI32(rs);
6491 pushI32(r);
6492 }
6493 }
6494
6495 void BaseCompiler::emitCompareI64(Assembler::Condition compareOp,
6496 ValType compareType) {
6497 MOZ_ASSERT(compareType == ValType::I64);
6498
6499 if (sniffConditionalControlCmp(compareOp, compareType)) {
6500 return;
6501 }
6502
6503 RegI64 rs0, rs1;
6504 pop2xI64(&rs0, &rs1);
6505 RegI32 rd(fromI64(rs0));
6506 cmp64Set(compareOp, rs0, rs1, rd);
6507 freeI64(rs1);
6508 freeI64Except(rs0, rd);
6509 pushI32(rd);
6510 }
6511
6512 void BaseCompiler::emitCompareF32(Assembler::DoubleCondition compareOp,
6513 ValType compareType) {
6514 MOZ_ASSERT(compareType == ValType::F32);
6515
6516 if (sniffConditionalControlCmp(compareOp, compareType)) {
6517 return;
6518 }
6519
6520 Label across;
6521 RegF32 rs0, rs1;
6522 pop2xF32(&rs0, &rs1);
6523 RegI32 rd = needI32();
6524 moveImm32(1, rd);
6525 masm.branchFloat(compareOp, rs0, rs1, &across);
6526 moveImm32(0, rd);
6527 masm.bind(&across);
6528 freeF32(rs0);
6529 freeF32(rs1);
6530 pushI32(rd);
6531 }
6532
6533 void BaseCompiler::emitCompareF64(Assembler::DoubleCondition compareOp,
6534 ValType compareType) {
6535 MOZ_ASSERT(compareType == ValType::F64);
6536
6537 if (sniffConditionalControlCmp(compareOp, compareType)) {
6538 return;
6539 }
6540
6541 Label across;
6542 RegF64 rs0, rs1;
6543 pop2xF64(&rs0, &rs1);
6544 RegI32 rd = needI32();
6545 moveImm32(1, rd);
6546 masm.branchDouble(compareOp, rs0, rs1, &across);
6547 moveImm32(0, rd);
6548 masm.bind(&across);
6549 freeF64(rs0);
6550 freeF64(rs1);
6551 pushI32(rd);
6552 }
6553
6554 void BaseCompiler::emitCompareRef(Assembler::Condition compareOp,
6555 ValType compareType) {
6556 MOZ_ASSERT(!sniffConditionalControlCmp(compareOp, compareType));
6557
6558 RegRef rs1, rs2;
6559 pop2xRef(&rs1, &rs2);
6560 RegI32 rd = needI32();
6561 masm.cmpPtrSet(compareOp, rs1, rs2, rd);
6562 freeRef(rs1);
6563 freeRef(rs2);
6564 pushI32(rd);
6565 }
6566
6567 bool BaseCompiler::emitInstanceCall(const SymbolicAddressSignature& builtin) {
6568 // See declaration (WasmBCClass.h) for info on the relationship between the
6569 // compiler's value stack and the argument order for the to-be-called
6570 // function.
6571 const MIRType* argTypes = builtin.argTypes;
6572 MOZ_ASSERT(argTypes[0] == MIRType::Pointer);
6573
6574 sync();
6575
6576 uint32_t numNonInstanceArgs = builtin.numArgs - 1 /* instance */;
6577 size_t stackSpace = stackConsumed(numNonInstanceArgs);
6578
6579 FunctionCall baselineCall{};
6580 beginCall(baselineCall, UseABI::System, RestoreRegisterStateAndRealm::True);
6581
6582 ABIArg instanceArg = reservePointerArgument(&baselineCall);
6583
6584 startCallArgs(StackArgAreaSizeUnaligned(builtin), &baselineCall);
6585 for (uint32_t i = 1; i < builtin.numArgs; i++) {
6586 ValType t;
6587 switch (argTypes[i]) {
6588 case MIRType::Int32:
6589 t = ValType::I32;
6590 break;
6591 case MIRType::Int64:
6592 t = ValType::I64;
6593 break;
6594 case MIRType::Float32:
6595 t = ValType::F32;
6596 break;
6597 case MIRType::WasmAnyRef:
6598 t = RefType::extern_();
6599 break;
6600 case MIRType::Pointer:
6601 // Instance function args can now be uninterpreted pointers (eg, for
6602 // the cases PostBarrier and PostBarrierFilter) so we simply treat
6603 // them like the equivalently sized integer.
6604 t = ValType::fromMIRType(TargetWordMIRType());
6605 break;
6606 default:
6607 MOZ_CRASH("Unexpected type");
6608 }
6609 passArg(t, peek(numNonInstanceArgs - i), &baselineCall);
6610 }
6611 CodeOffset raOffset =
6612 builtinInstanceMethodCall(builtin, instanceArg, baselineCall);
6613 if (!createStackMap("emitInstanceCall", raOffset)) {
6614 return false;
6615 }
6616
6617 endCall(baselineCall, stackSpace);
6618
6619 popValueStackBy(numNonInstanceArgs);
6620
6621 // Note, many clients of emitInstanceCall currently assume that pushing the
6622 // result here does not destroy ReturnReg.
6623 //
6624 // Furthermore, clients assume that if builtin.retType != MIRType::None, the
6625 // callee will have returned a result and left it in ReturnReg for us to
6626 // find, and that that register will not be destroyed here (or above).
6627
6628 // For the return type only, MIRType::None is used to indicate that the
6629 // call doesn't return a result, that is, returns a C/C++ "void".
6630
6631 if (builtin.retType != MIRType::None) {
6632 pushReturnValueOfCall(baselineCall, builtin.retType);
6633 }
6634 return true;
6635 }
6636
6637 //////////////////////////////////////////////////////////////////////////////
6638 //
6639 // Reference types.
6640
6641 bool BaseCompiler::emitRefFunc() {
6642 return emitInstanceCallOp<uint32_t>(SASigRefFunc,
6643 [this](uint32_t* funcIndex) -> bool {
6644 return iter_.readRefFunc(funcIndex);
6645 });
6646 }
6647
6648 bool BaseCompiler::emitRefNull() {
6649 RefType type;
6650 if (!iter_.readRefNull(&type)) {
6651 return false;
6652 }
6653
6654 if (deadCode_) {
6655 return true;
6656 }
6657
6658 pushRef(AnyRef::NullRefValue);
6659 return true;
6660 }
6661
6662 bool BaseCompiler::emitRefIsNull() {
6663 Nothing nothing;
6664 if (!iter_.readRefIsNull(&nothing)) {
6665 return false;
6666 }
6667
6668 if (deadCode_) {
6669 return true;
6670 }
6671
6672 RegRef r = popRef();
6673 RegI32 rd = narrowRef(r);
6674
6675 masm.cmpPtrSet(Assembler::Equal, r, ImmWord(AnyRef::NullRefValue), rd);
6676 pushI32(rd);
6677 return true;
6678 }
6679
6680 bool BaseCompiler::emitRefAsNonNull() {
6681 Nothing nothing;
6682 if (!iter_.readRefAsNonNull(&nothing)) {
6683 return false;
6684 }
6685
6686 if (deadCode_) {
6687 return true;
6688 }
6689
6690 RegRef rp = popRef();
6691 Label ok;
6692 masm.branchWasmAnyRefIsNull(false, rp, &ok);
6693 trap(Trap::NullPointerDereference);
6694 masm.bind(&ok);
6695 pushRef(rp);
6696
6697 return true;
6698 }
6699
6700 //////////////////////////////////////////////////////////////////////////////
6701 //
6702 // Atomic operations.
6703
6704 bool BaseCompiler::emitAtomicCmpXchg(ValType type, Scalar::Type viewType) {
6705 LinearMemoryAddress<Nothing> addr;
6706 Nothing unused{};
6707 if (!iter_.readAtomicCmpXchg(&addr, type, Scalar::byteSize(viewType), &unused,
6708 &unused)) {
6709 return false;
6710 }
6711 if (deadCode_) {
6712 return true;
6713 }
6714 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
6715 trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex),
6716 Synchronization::Full());
6717 atomicCmpXchg(&access, type);
6718 return true;
6719 }
6720
6721 bool BaseCompiler::emitAtomicLoad(ValType type, Scalar::Type viewType) {
6722 LinearMemoryAddress<Nothing> addr;
6723 if (!iter_.readAtomicLoad(&addr, type, Scalar::byteSize(viewType))) {
6724 return false;
6725 }
6726 if (deadCode_) {
6727 return true;
6728 }
6729 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
6730 trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex),
6731 Synchronization::Load());
6732 atomicLoad(&access, type);
6733 return true;
6734 }
6735
6736 bool BaseCompiler::emitAtomicRMW(ValType type, Scalar::Type viewType,
6737 AtomicOp op) {
6738 LinearMemoryAddress<Nothing> addr;
6739 Nothing unused_value;
6740 if (!iter_.readAtomicRMW(&addr, type, Scalar::byteSize(viewType),
6741 &unused_value)) {
6742 return false;
6743 }
6744 if (deadCode_) {
6745 return true;
6746 }
6747 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
6748 trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex),
6749 Synchronization::Full());
6750 atomicRMW(&access, type, op);
6751 return true;
6752 }
6753
6754 bool BaseCompiler::emitAtomicStore(ValType type, Scalar::Type viewType) {
6755 LinearMemoryAddress<Nothing> addr;
6756 Nothing unused_value;
6757 if (!iter_.readAtomicStore(&addr, type, Scalar::byteSize(viewType),
6758 &unused_value)) {
6759 return false;
6760 }
6761 if (deadCode_) {
6762 return true;
6763 }
6764 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
6765 trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex),
6766 Synchronization::Store());
6767 atomicStore(&access, type);
6768 return true;
6769 }
6770
6771 bool BaseCompiler::emitAtomicXchg(ValType type, Scalar::Type viewType) {
6772 LinearMemoryAddress<Nothing> addr;
6773 Nothing unused_value;
6774 if (!iter_.readAtomicRMW(&addr, type, Scalar::byteSize(viewType),
6775 &unused_value)) {
6776 return false;
6777 }
6778 if (deadCode_) {
6779 return true;
6780 }
6781 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
6782 trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex),
6783 Synchronization::Full());
6784 atomicXchg(&access, type);
6785 return true;
6786 }
6787
6788 bool BaseCompiler::emitWait(ValType type, uint32_t byteSize) {
6789 Nothing nothing;
6790 LinearMemoryAddress<Nothing> addr;
6791 if (!iter_.readWait(&addr, type, byteSize, &nothing, &nothing)) {
6792 return false;
6793 }
6794 if (deadCode_) {
6795 return true;
6796 }
6797 MemoryAccessDesc access(
6798 addr.memoryIndex,
6799 type.kind() == ValType::I32 ? Scalar::Int32 : Scalar::Int64, addr.align,
6800 addr.offset, trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex));
6801 return atomicWait(type, &access);
6802 }
6803
6804 bool BaseCompiler::emitNotify() {
6805 Nothing nothing;
6806 LinearMemoryAddress<Nothing> addr;
6807 if (!iter_.readNotify(&addr, &nothing)) {
6808 return false;
6809 }
6810 if (deadCode_) {
6811 return true;
6812 }
6813 MemoryAccessDesc access(addr.memoryIndex, Scalar::Int32, addr.align,
6814 addr.offset, trapSiteDesc(),
6815 hugeMemoryEnabled(addr.memoryIndex));
6816 return atomicNotify(&access);
6817 }
6818
6819 bool BaseCompiler::emitFence() {
6820 if (!iter_.readFence()) {
6821 return false;
6822 }
6823 if (deadCode_) {
6824 return true;
6825 }
6826 masm.memoryBarrier(MemoryBarrier::Full());
6827 return true;
6828 }
6829
6830 //////////////////////////////////////////////////////////////////////////////
6831 //
6832 // Bulk memory operations.
6833
6834 bool BaseCompiler::emitMemoryGrow() {
6835 uint32_t memoryIndex;
6836 Nothing nothing;
6837 if (!iter_.readMemoryGrow(&memoryIndex, &nothing)) {
6838 return false;
6839 }
6840 if (deadCode_) {
6841 return true;
6842 }
6843
6844 pushI32(memoryIndex);
6845 return emitInstanceCall(isMem32(memoryIndex) ? SASigMemoryGrowM32
6846 : SASigMemoryGrowM64);
6847 }
6848
6849 bool BaseCompiler::emitMemorySize() {
6850 uint32_t memoryIndex;
6851 if (!iter_.readMemorySize(&memoryIndex)) {
6852 return false;
6853 }
6854 if (deadCode_) {
6855 return true;
6856 }
6857
6858 pushI32(memoryIndex);
6859 return emitInstanceCall(isMem32(memoryIndex) ? SASigMemorySizeM32
6860 : SASigMemorySizeM64);
6861 }
6862
6863 bool BaseCompiler::emitMemCopy() {
6864 uint32_t dstMemIndex = 0;
6865 uint32_t srcMemIndex = 0;
6866 Nothing nothing;
6867 if (!iter_.readMemOrTableCopy(true, &dstMemIndex, &nothing, &srcMemIndex,
6868 &nothing, &nothing)) {
6869 return false;
6870 }
6871 if (deadCode_) {
6872 return true;
6873 }
6874
6875 if (dstMemIndex == 0 && srcMemIndex == 0 && isMem32(dstMemIndex)) {
6876 int32_t signedLength;
6877 if (peekConst(&signedLength) && signedLength != 0 &&
6878 uint32_t(signedLength) <= MaxInlineMemoryCopyLength) {
6879 memCopyInlineM32();
6880 return true;
6881 }
6882 }
6883
6884 return memCopyCall(dstMemIndex, srcMemIndex);
6885 }
6886
6887 bool BaseCompiler::memCopyCall(uint32_t dstMemIndex, uint32_t srcMemIndex) {
6888 // Common and optimized path for when the src/dest memories are the same
6889 if (dstMemIndex == srcMemIndex) {
6890 bool mem32 = isMem32(dstMemIndex);
6891 pushHeapBase(dstMemIndex);
6892 return emitInstanceCall(
6893 usesSharedMemory(dstMemIndex)
6894 ? (mem32 ? SASigMemCopySharedM32 : SASigMemCopySharedM64)
6895 : (mem32 ? SASigMemCopyM32 : SASigMemCopyM64));
6896 }
6897
6898 // Do the general-purpose fallback for copying between any combination of
6899 // memories. This works by moving everything to the lowest-common denominator.
6900 // i32 addresses are promoted to i64, and non-shared memories are treated as
6901 // shared.
6902 AddressType dstAddressType = codeMeta_.memories[dstMemIndex].addressType();
6903 AddressType srcAddressType = codeMeta_.memories[srcMemIndex].addressType();
6904 AddressType lenAddressType = MinAddressType(dstAddressType, srcAddressType);
6905
6906 // Pop the operands off of the stack and widen them
6907 RegI64 len = popAddressToInt64(lenAddressType);
6908 #ifdef JS_CODEGEN_X86
6909 {
6910 // Stash the length value to prevent running out of registers
6911 ScratchPtr scratch(*this);
6912 stashI64(scratch, len);
6913 freeI64(len);
6914 }
6915 #endif
6916 RegI64 srcIndex = popAddressToInt64(srcAddressType);
6917 RegI64 dstIndex = popAddressToInt64(dstAddressType);
6918
6919 pushI64(dstIndex);
6920 pushI64(srcIndex);
6921 #ifdef JS_CODEGEN_X86
6922 {
6923 // Unstash the length value and push it back on the stack
6924 ScratchPtr scratch(*this);
6925 len = needI64();
6926 unstashI64(scratch, len);
6927 }
6928 #endif
6929 pushI64(len);
6930 pushI32(dstMemIndex);
6931 pushI32(srcMemIndex);
6932 return emitInstanceCall(SASigMemCopyAny);
6933 }
6934
6935 bool BaseCompiler::emitMemFill() {
6936 uint32_t memoryIndex;
6937 Nothing nothing;
6938 if (!iter_.readMemFill(&memoryIndex, &nothing, &nothing, &nothing)) {
6939 return false;
6940 }
6941 if (deadCode_) {
6942 return true;
6943 }
6944
6945 if (memoryIndex == 0 && isMem32(memoryIndex)) {
6946 int32_t signedLength;
6947 int32_t signedValue;
6948 if (peek2xConst(&signedLength, &signedValue) && signedLength != 0 &&
6949 uint32_t(signedLength) <= MaxInlineMemoryFillLength) {
6950 memFillInlineM32();
6951 return true;
6952 }
6953 }
6954 return memFillCall(memoryIndex);
6955 }
6956
6957 bool BaseCompiler::memFillCall(uint32_t memoryIndex) {
6958 pushHeapBase(memoryIndex);
6959 return emitInstanceCall(
6960 usesSharedMemory(memoryIndex)
6961 ? (isMem32(memoryIndex) ? SASigMemFillSharedM32
6962 : SASigMemFillSharedM64)
6963 : (isMem32(memoryIndex) ? SASigMemFillM32 : SASigMemFillM64));
6964 }
6965
6966 bool BaseCompiler::emitMemInit() {
6967 uint32_t segIndex;
6968 uint32_t memIndex;
6969 Nothing nothing;
6970 if (!iter_.readMemOrTableInit(/*isMem*/ true, &segIndex, &memIndex, &nothing,
6971 &nothing, &nothing)) {
6972 return false;
6973 }
6974 if (deadCode_) {
6975 return true;
6976 }
6977
6978 pushI32(segIndex);
6979 pushI32(memIndex);
6980 return emitInstanceCall(isMem32(memIndex) ? SASigMemInitM32
6981 : SASigMemInitM64);
6982 }
6983
6984 //////////////////////////////////////////////////////////////////////////////
6985 //
6986 // Bulk table operations.
6987
6988 bool BaseCompiler::emitTableCopy() {
6989 uint32_t dstTable = 0;
6990 uint32_t srcTable = 0;
6991 Nothing nothing;
6992 if (!iter_.readMemOrTableCopy(false, &dstTable, &nothing, &srcTable, &nothing,
6993 &nothing)) {
6994 return false;
6995 }
6996
6997 if (deadCode_) {
6998 return true;
6999 }
7000
7001 AddressType dstAddressType = codeMeta_.tables[dstTable].addressType();
7002 AddressType srcAddressType = codeMeta_.tables[srcTable].addressType();
7003 AddressType lenAddressType = MinAddressType(dstAddressType, srcAddressType);
7004
7005 // Instance::tableCopy(dstOffset:u32, srcOffset:u32, len:u32, dstTable:u32,
7006 // srcTable:u32)
7007 RegI32 len = popTableAddressToClampedInt32(lenAddressType);
7008 RegI32 src = popTableAddressToClampedInt32(srcAddressType);
7009 replaceTableAddressWithClampedInt32(dstAddressType);
7010 pushI32(src);
7011 pushI32(len);
7012 pushI32(dstTable);
7013 pushI32(srcTable);
7014 return emitInstanceCall(SASigTableCopy);
7015 }
7016
7017 bool BaseCompiler::emitTableInit() {
7018 uint32_t segIndex = 0;
7019 uint32_t dstTable = 0;
7020 Nothing nothing;
7021 if (!iter_.readMemOrTableInit(false, &segIndex, &dstTable, &nothing, &nothing,
7022 &nothing)) {
7023 return false;
7024 }
7025
7026 if (deadCode_) {
7027 return true;
7028 }
7029
7030 // Instance::tableInit(dst:u32, src:u32, len:u32, seg:u32, table:u32)
7031 RegI32 len = popI32();
7032 RegI32 src = popI32();
7033 replaceTableAddressWithClampedInt32(codeMeta_.tables[dstTable].addressType());
7034 pushI32(src);
7035 pushI32(len);
7036 pushI32(segIndex);
7037 pushI32(dstTable);
7038 return emitInstanceCall(SASigTableInit);
7039 }
7040
7041 bool BaseCompiler::emitTableFill() {
7042 uint32_t tableIndex;
7043 Nothing nothing;
7044 if (!iter_.readTableFill(&tableIndex, &nothing, &nothing, &nothing)) {
7045 return false;
7046 }
7047 if (deadCode_) {
7048 return true;
7049 }
7050
7051 AddressType addressType = codeMeta_.tables[tableIndex].addressType();
7052
7053 // Instance::tableFill(start:u32, val:ref, len:u32, table:u32) -> void
7054 RegI32 len = popTableAddressToClampedInt32(addressType);
7055 AnyReg val = popAny();
7056 replaceTableAddressWithClampedInt32(addressType);
7057 pushAny(val);
7058 pushI32(len);
7059 pushI32(tableIndex);
7060 return emitInstanceCall(SASigTableFill);
7061 }
7062
7063 bool BaseCompiler::emitMemDiscard() {
7064 uint32_t memoryIndex;
7065 Nothing nothing;
7066 if (!iter_.readMemDiscard(&memoryIndex, &nothing, &nothing)) {
7067 return false;
7068 }
7069 if (deadCode_) {
7070 return true;
7071 }
7072
7073 pushHeapBase(memoryIndex);
7074 return emitInstanceCall(
7075 usesSharedMemory(memoryIndex)
7076 ? (isMem32(memoryIndex) ? SASigMemDiscardSharedM32
7077 : SASigMemDiscardSharedM64)
7078 : (isMem32(memoryIndex) ? SASigMemDiscardM32 : SASigMemDiscardM64));
7079 }
7080
7081 bool BaseCompiler::emitTableGet() {
7082 uint32_t tableIndex;
7083 Nothing nothing;
7084 if (!iter_.readTableGet(&tableIndex, &nothing)) {
7085 return false;
7086 }
7087 if (deadCode_) {
7088 return true;
7089 }
7090
7091 replaceTableAddressWithClampedInt32(
7092 codeMeta_.tables[tableIndex].addressType());
7093 if (codeMeta_.tables[tableIndex].elemType.tableRepr() == TableRepr::Ref) {
7094 return emitTableGetAnyRef(tableIndex);
7095 }
7096 pushI32(tableIndex);
7097 // Instance::tableGet(index:u32, table:u32) -> AnyRef
7098 return emitInstanceCall(SASigTableGet);
7099 }
7100
7101 bool BaseCompiler::emitTableGrow() {
7102 uint32_t tableIndex;
7103 Nothing nothing;
7104 if (!iter_.readTableGrow(&tableIndex, &nothing, &nothing)) {
7105 return false;
7106 }
7107 if (deadCode_) {
7108 return true;
7109 }
7110
7111 AddressType addressType = codeMeta_.tables[tableIndex].addressType();
7112
7113 // Instance::tableGrow(initValue:anyref, delta:u32, table:u32) -> u32
7114 replaceTableAddressWithClampedInt32(addressType);
7115 pushI32(tableIndex);
7116 if (!emitInstanceCall(SASigTableGrow)) {
7117 return false;
7118 }
7119
7120 if (addressType == AddressType::I64) {
7121 RegI64 r;
7122 popI32ForSignExtendI64(&r);
7123 masm.move32To64SignExtend(lowPart(r), r);
7124 pushI64(r);
7125 }
7126
7127 return true;
7128 }
7129
7130 bool BaseCompiler::emitTableSet() {
7131 uint32_t tableIndex;
7132 Nothing nothing;
7133 if (!iter_.readTableSet(&tableIndex, &nothing, &nothing)) {
7134 return false;
7135 }
7136 if (deadCode_) {
7137 return true;
7138 }
7139 if (codeMeta_.tables[tableIndex].addressType() == AddressType::I64) {
7140 AnyReg value = popAny();
7141 replaceTableAddressWithClampedInt32(AddressType::I64);
7142 pushAny(value);
7143 }
7144 if (codeMeta_.tables[tableIndex].elemType.tableRepr() == TableRepr::Ref) {
7145 return emitTableSetAnyRef(tableIndex);
7146 }
7147 pushI32(tableIndex);
7148 // Instance::tableSet(address:u32, value:ref, table:u32) -> void
7149 return emitInstanceCall(SASigTableSet);
7150 }
7151
7152 bool BaseCompiler::emitTableSize() {
7153 uint32_t tableIndex;
7154 if (!iter_.readTableSize(&tableIndex)) {
7155 return false;
7156 }
7157 if (deadCode_) {
7158 return true;
7159 }
7160
7161 RegPtr instance = needPtr();
7162 RegI32 length = needI32();
7163
7164 fr.loadInstancePtr(instance);
7165 loadTableLength(tableIndex, instance, length);
7166
7167 if (codeMeta_.tables[tableIndex].addressType() == AddressType::I64) {
7168 pushU32AsI64(length);
7169 } else {
7170 pushI32(length);
7171 }
7172 freePtr(instance);
7173 return true;
7174 }
7175
7176 void BaseCompiler::emitTableBoundsCheck(uint32_t tableIndex, RegI32 address,
7177 RegPtr instance) {
7178 Label ok;
7179 masm.wasmBoundsCheck32(
7180 Assembler::Condition::Below, address,
7181 addressOfTableField(tableIndex, offsetof(TableInstanceData, length),
7182 instance),
7183 &ok);
7184 trap(wasm::Trap::OutOfBounds);
7185 masm.bind(&ok);
7186 }
7187
7188 bool BaseCompiler::emitTableGetAnyRef(uint32_t tableIndex) {
7189 RegPtr instance = needPtr();
7190 RegPtr elements = needPtr();
7191 RegI32 address = popI32();
7192
7193 fr.loadInstancePtr(instance);
7194 emitTableBoundsCheck(tableIndex, address, instance);
7195 loadTableElements(tableIndex, instance, elements);
7196 masm.loadPtr(BaseIndex(elements, address, ScalePointer), elements);
7197
7198 pushRef(RegRef(elements));
7199 freeI32(address);
7200 freePtr(instance);
7201
7202 return true;
7203 }
7204
7205 bool BaseCompiler::emitTableSetAnyRef(uint32_t tableIndex) {
7206 // Create temporaries for valueAddr that is not in the prebarrier register
7207 // and can be consumed by the barrier operation
7208 RegPtr valueAddr = RegPtr(PreBarrierReg);
7209 needPtr(valueAddr);
7210
7211 RegPtr instance = needPtr();
7212 RegPtr elements = needPtr();
7213 RegRef value = popRef();
7214 RegI32 address = popI32();
7215
7216 // x86 is one register too short for this operation, shuffle `value` back
7217 // onto the stack until it is needed.
7218 #ifdef JS_CODEGEN_X86
7219 pushRef(value);
7220 #endif
7221
7222 fr.loadInstancePtr(instance);
7223 emitTableBoundsCheck(tableIndex, address, instance);
7224 loadTableElements(tableIndex, instance, elements);
7225 masm.computeEffectiveAddress(BaseIndex(elements, address, ScalePointer),
7226 valueAddr);
7227
7228 freeI32(address);
7229 freePtr(elements);
7230 freePtr(instance);
7231
7232 #ifdef JS_CODEGEN_X86
7233 value = popRef();
7234 #endif
7235
7236 if (!emitBarrieredStore(Nothing(), valueAddr, value, PreBarrierKind::Normal,
7237 PostBarrierKind::Precise)) {
7238 return false;
7239 }
7240 freeRef(value);
7241 return true;
7242 }
7243
7244 //////////////////////////////////////////////////////////////////////////////
7245 //
7246 // Data and element segment management.
7247
7248 bool BaseCompiler::emitDataOrElemDrop(bool isData) {
7249 return emitInstanceCallOp<uint32_t>(
7250 isData ? SASigDataDrop : SASigElemDrop, [&](uint32_t* segIndex) -> bool {
7251 return iter_.readDataOrElemDrop(isData, segIndex);
7252 });
7253 }
7254
7255 //////////////////////////////////////////////////////////////////////////////
7256 //
7257 // General object support.
7258
7259 void BaseCompiler::emitPreBarrier(RegPtr valueAddr) {
7260 Label skipBarrier;
7261 ScratchPtr scratch(*this);
7262
7263 #ifdef RABALDR_PIN_INSTANCE
7264 Register instance(InstanceReg);
7265 #else
7266 Register instance(scratch);
7267 fr.loadInstancePtr(instance);
7268 #endif
7269
7270 EmitWasmPreBarrierGuard(masm, instance, scratch, Address(valueAddr, 0),
7271 &skipBarrier, mozilla::Nothing());
7272
7273 #ifndef RABALDR_PIN_INSTANCE
7274 fr.loadInstancePtr(instance);
7275 #endif
7276 #ifdef JS_CODEGEN_ARM64
7277 // The prebarrier stub assumes the PseudoStackPointer is set up. It is OK
7278 // to just move the sp to x28 here because x28 is not being used by the
7279 // baseline compiler and need not be saved or restored.
7280 MOZ_ASSERT(!GeneralRegisterSet::All().hasRegisterIndex(x28.asUnsized()));
7281 masm.Mov(x28, sp);
7282 #endif
7283 // The prebarrier call preserves all volatile registers
7284 EmitWasmPreBarrierCallImmediate(masm, instance, scratch, valueAddr,
7285 /*valueOffset=*/0);
7286
7287 masm.bind(&skipBarrier);
7288 }
7289
7290 bool BaseCompiler::emitPostBarrierWholeCell(RegRef object, RegRef value,
7291 RegPtr temp) {
7292 // We must force a sync before the guard so that locals are in a consistent
7293 // location for whether or not the post-barrier call is taken.
7294 sync();
7295
7296 // Emit guards to skip the post-barrier call if it is not needed.
7297 Label skipBarrier;
7298 EmitWasmPostBarrierGuard(masm, mozilla::Some(object), temp, value,
7299 &skipBarrier);
7300
7301 #ifdef RABALDR_PIN_INSTANCE
7302 Register instance(InstanceReg);
7303 #else
7304 Register instance(temp);
7305 fr.loadInstancePtr(instance);
7306 #endif
7307 CheckWholeCellLastElementCache(masm, instance, object, temp, &skipBarrier);
7308
7309 movePtr(RegPtr(object), temp);
7310
7311 // Push `object` and `value` to preserve them across the call.
7312 pushRef(object);
7313 pushRef(value);
7314
7315 pushPtr(temp);
7316 if (!emitInstanceCall(SASigPostBarrierWholeCell)) {
7317 return false;
7318 }
7319
7320 // Restore `object` and `value`.
7321 popRef(value);
7322 popRef(object);
7323
7324 masm.bind(&skipBarrier);
7325 return true;
7326 }
7327
7328 bool BaseCompiler::emitPostBarrierEdgeImprecise(const Maybe<RegRef>& object,
7329 RegPtr valueAddr,
7330 RegRef value) {
7331 // We must force a sync before the guard so that locals are in a consistent
7332 // location for whether or not the post-barrier call is taken.
7333 sync();
7334
7335 // Emit a guard to skip the post-barrier call if it is not needed.
7336 Label skipBarrier;
7337 RegPtr otherScratch = needPtr();
7338 EmitWasmPostBarrierGuard(masm, object, otherScratch, value, &skipBarrier);
7339 freePtr(otherScratch);
7340
7341 // Push `object` and `value` to preserve them across the call.
7342 if (object) {
7343 pushRef(*object);
7344 }
7345 pushRef(value);
7346
7347 // The `valueAddr` is a raw pointer to the cell within some GC object or
7348 // instance area, and we are careful so that the GC will not run while the
7349 // post-barrier call is active, so push a uintptr_t value.
7350 pushPtr(valueAddr);
7351 if (!emitInstanceCall(SASigPostBarrierEdge)) {
7352 return false;
7353 }
7354
7355 // Restore `object` and `value`.
7356 popRef(value);
7357 if (object) {
7358 popRef(*object);
7359 }
7360
7361 masm.bind(&skipBarrier);
7362 return true;
7363 }
7364
7365 bool BaseCompiler::emitPostBarrierEdgePrecise(const Maybe<RegRef>& object,
7366 RegPtr valueAddr,
7367 RegRef prevValue, RegRef value) {
7368 // Push `object` and `value` to preserve them across the call.
7369 if (object) {
7370 pushRef(*object);
7371 }
7372 pushRef(value);
7373
7374 // Push the arguments and call the precise post-barrier
7375 pushPtr(valueAddr);
7376 pushRef(prevValue);
7377 if (!emitInstanceCall(SASigPostBarrierEdgePrecise)) {
7378 return false;
7379 }
7380
7381 // Restore `object` and `value`.
7382 popRef(value);
7383 if (object) {
7384 popRef(*object);
7385 }
7386
7387 return true;
7388 }
7389
7390 bool BaseCompiler::emitBarrieredStore(const Maybe<RegRef>& object,
7391 RegPtr valueAddr, RegRef value,
7392 PreBarrierKind preBarrierKind,
7393 PostBarrierKind postBarrierKind) {
7394 // The pre-barrier preserves all allocated registers.
7395 if (preBarrierKind == PreBarrierKind::Normal) {
7396 emitPreBarrier(valueAddr);
7397 }
7398
7399 // The precise post-barrier requires the previous value stored in the field,
7400 // in order to know if the previous store buffer entry needs to be removed.
7401 RegRef prevValue;
7402 if (postBarrierKind == PostBarrierKind::Precise) {
7403 prevValue = needRef();
7404 masm.loadPtr(Address(valueAddr, 0), prevValue);
7405 }
7406
7407 // Store the value
7408 masm.storePtr(value, Address(valueAddr, 0));
7409
7410 // The post-barrier preserves object and value.
7411 if (postBarrierKind == PostBarrierKind::Imprecise) {
7412 return emitPostBarrierEdgeImprecise(object, valueAddr, value);
7413 }
7414 if (postBarrierKind == PostBarrierKind::Precise) {
7415 return emitPostBarrierEdgePrecise(object, valueAddr, prevValue, value);
7416 }
7417 if (postBarrierKind == PostBarrierKind::WholeCell) {
7418 // valueAddr is reused as a temp register.
7419 return emitPostBarrierWholeCell(object.value(), value, valueAddr);
7420 }
7421 MOZ_CRASH("unknown barrier kind");
7422 }
7423
7424 void BaseCompiler::emitBarrieredClear(RegPtr valueAddr) {
7425 // The pre-barrier preserves all allocated registers.
7426 emitPreBarrier(valueAddr);
7427
7428 // Store null
7429 masm.storePtr(ImmWord(AnyRef::NullRefValue), Address(valueAddr, 0));
7430
7431 // No post-barrier is needed, as null does not require a store buffer entry
7432 }
7433
7434 //////////////////////////////////////////////////////////////////////////////
7435 //
7436 // GC proposal.
7437
7438 RegPtr BaseCompiler::loadAllocSiteInstanceData(uint32_t allocSiteIndex) {
7439 RegPtr rp = needPtr();
7440 RegPtr instance;
7441 #ifndef RABALDR_PIN_INSTANCE
7442 instance = rp;
7443 fr.loadInstancePtr(instance);
7444 #else
7445 // We can use the pinned instance register.
7446 instance = RegPtr(InstanceReg);
7447 #endif
7448 masm.loadPtr(Address(instance, Instance::offsetOfAllocSites()), rp);
7449
7450 ScratchI32 scratch(*this);
7451 CodeOffset offset = masm.move32WithPatch(scratch);
7452 masm.allocSitesPatches()[allocSiteIndex].setPatchOffset(offset.offset());
7453 masm.addPtr(scratch, rp);
7454 return rp;
7455 }
7456
7457 bool BaseCompiler::readAllocSiteIndex(uint32_t* index) {
7458 *index = masm.allocSitesPatches().length();
7459 masm.append(wasm::AllocSitePatch());
7460 return !masm.oom();
7461 }
7462
7463 RegPtr BaseCompiler::loadSuperTypeVector(uint32_t typeIndex) {
7464 RegPtr rp = needPtr();
7465 RegPtr instance;
7466 #ifndef RABALDR_PIN_INSTANCE
7467 // We need to load the instance register, but can use the destination
7468 // register as a temporary.
7469 instance = rp;
7470 fr.loadInstancePtr(rp);
7471 #else
7472 // We can use the pinned instance register.
7473 instance = RegPtr(InstanceReg);
7474 #endif
7475 masm.loadPtr(
7476 Address(instance, Instance::offsetInData(
7477 codeMeta_.offsetOfSuperTypeVector(typeIndex))),
7478 rp);
7479 return rp;
7480 }
7481
7482 /* static */
7483 void BaseCompiler::SignalNullCheck::emitNullCheck(BaseCompiler* bc, RegRef rp) {
7484 Label ok;
7485 MacroAssembler& masm = bc->masm;
7486 masm.branchTestPtr(Assembler::NonZero, rp, rp, &ok);
7487 bc->trap(Trap::NullPointerDereference);
7488 masm.bind(&ok);
7489 }
7490
7491 /* static */
7492 void BaseCompiler::SignalNullCheck::emitTrapSite(BaseCompiler* bc,
7493 FaultingCodeOffset fco,
7494 TrapMachineInsn tmi) {
7495 MacroAssembler& masm = bc->masm;
7496 masm.append(wasm::Trap::NullPointerDereference, tmi, fco.get(),
7497 bc->trapSiteDesc());
7498 }
7499
7500 template <typename NullCheckPolicy>
7501 RegPtr BaseCompiler::emitGcArrayGetData(RegRef rp) {
7502 // `rp` points at a WasmArrayObject. Return a reg holding the value of its
7503 // `data_` field.
7504 RegPtr rdata = needPtr();
7505 FaultingCodeOffset fco =
7506 masm.loadPtr(Address(rp, WasmArrayObject::offsetOfData()), rdata);
7507 NullCheckPolicy::emitTrapSite(this, fco, TrapMachineInsnForLoadWord());
7508 return rdata;
7509 }
7510
7511 template <typename NullCheckPolicy>
7512 RegI32 BaseCompiler::emitGcArrayGetNumElements(RegRef rp) {
7513 // `rp` points at a WasmArrayObject. Return a reg holding the value of its
7514 // `numElements_` field.
7515 STATIC_ASSERT_WASMARRAYELEMENTS_NUMELEMENTS_IS_U32;
7516 RegI32 numElements = needI32();
7517 FaultingCodeOffset fco = masm.load32(
7518 Address(rp, WasmArrayObject::offsetOfNumElements()), numElements);
7519 NullCheckPolicy::emitTrapSite(this, fco, TrapMachineInsn::Load32);
7520 return numElements;
7521 }
7522
7523 void BaseCompiler::emitGcArrayBoundsCheck(RegI32 index, RegI32 numElements) {
7524 Label inBounds;
7525 masm.branch32(Assembler::Below, index, numElements, &inBounds);
7526 trap(Trap::OutOfBounds);
7527 masm.bind(&inBounds);
7528 }
7529
7530 template <typename T, typename NullCheckPolicy>
7531 void BaseCompiler::emitGcGet(StorageType type, FieldWideningOp wideningOp,
7532 const T& src) {
7533 switch (type.kind()) {
7534 case StorageType::I8: {
7535 MOZ_ASSERT(wideningOp != FieldWideningOp::None);
7536 RegI32 r = needI32();
7537 FaultingCodeOffset fco;
7538 if (wideningOp == FieldWideningOp::Unsigned) {
7539 fco = masm.load8ZeroExtend(src, r);
7540 } else {
7541 fco = masm.load8SignExtend(src, r);
7542 }
7543 NullCheckPolicy::emitTrapSite(this, fco, TrapMachineInsn::Load8);
7544 pushI32(r);
7545 break;
7546 }
7547 case StorageType::I16: {
7548 MOZ_ASSERT(wideningOp != FieldWideningOp::None);
7549 RegI32 r = needI32();
7550 FaultingCodeOffset fco;
7551 if (wideningOp == FieldWideningOp::Unsigned) {
7552 fco = masm.load16ZeroExtend(src, r);
7553 } else {
7554 fco = masm.load16SignExtend(src, r);
7555 }
7556 NullCheckPolicy::emitTrapSite(this, fco, TrapMachineInsn::Load16);
7557 pushI32(r);
7558 break;
7559 }
7560 case StorageType::I32: {
7561 MOZ_ASSERT(wideningOp == FieldWideningOp::None);
7562 RegI32 r = needI32();
7563 FaultingCodeOffset fco = masm.load32(src, r);
7564 NullCheckPolicy::emitTrapSite(this, fco, TrapMachineInsn::Load32);
7565 pushI32(r);
7566 break;
7567 }
7568 case StorageType::I64: {
7569 MOZ_ASSERT(wideningOp == FieldWideningOp::None);
7570 RegI64 r = needI64();
7571 #ifdef JS_64BIT
7572 FaultingCodeOffset fco = masm.load64(src, r);
7573 NullCheckPolicy::emitTrapSite(this, fco, TrapMachineInsn::Load64);
7574 #else
7575 FaultingCodeOffsetPair fcop = masm.load64(src, r);
7576 NullCheckPolicy::emitTrapSite(this, fcop.first, TrapMachineInsn::Load32);
7577 NullCheckPolicy::emitTrapSite(this, fcop.second, TrapMachineInsn::Load32);
7578 #endif
7579 pushI64(r);
7580 break;
7581 }
7582 case StorageType::F32: {
7583 MOZ_ASSERT(wideningOp == FieldWideningOp::None);
7584 RegF32 r = needF32();
7585 FaultingCodeOffset fco = masm.loadFloat32(src, r);
7586 NullCheckPolicy::emitTrapSite(this, fco, TrapMachineInsn::Load32);
7587 pushF32(r);
7588 break;
7589 }
7590 case StorageType::F64: {
7591 MOZ_ASSERT(wideningOp == FieldWideningOp::None);
7592 RegF64 r = needF64();
7593 FaultingCodeOffset fco = masm.loadDouble(src, r);
7594 NullCheckPolicy::emitTrapSite(this, fco, TrapMachineInsn::Load64);
7595 pushF64(r);
7596 break;
7597 }
7598 #ifdef ENABLE_WASM_SIMD
7599 case StorageType::V128: {
7600 MOZ_ASSERT(wideningOp == FieldWideningOp::None);
7601 RegV128 r = needV128();
7602 FaultingCodeOffset fco = masm.loadUnalignedSimd128(src, r);
7603 NullCheckPolicy::emitTrapSite(this, fco, TrapMachineInsn::Load128);
7604 pushV128(r);
7605 break;
7606 }
7607 #endif
7608 case StorageType::Ref: {
7609 MOZ_ASSERT(wideningOp == FieldWideningOp::None);
7610 RegRef r = needRef();
7611 FaultingCodeOffset fco = masm.loadPtr(src, r);
7612 NullCheckPolicy::emitTrapSite(this, fco, TrapMachineInsnForLoadWord());
7613 pushRef(r);
7614 break;
7615 }
7616 default: {
7617 MOZ_CRASH("Unexpected field type");
7618 }
7619 }
7620 }
7621
7622 template <typename T, typename NullCheckPolicy>
7623 void BaseCompiler::emitGcSetScalar(const T& dst, StorageType type,
7624 AnyReg value) {
7625 switch (type.kind()) {
7626 case StorageType::I8: {
7627 FaultingCodeOffset fco = masm.store8(value.i32(), dst);
7628 NullCheckPolicy::emitTrapSite(this, fco, TrapMachineInsn::Store8);
7629 break;
7630 }
7631 case StorageType::I16: {
7632 FaultingCodeOffset fco = masm.store16(value.i32(), dst);
7633 NullCheckPolicy::emitTrapSite(this, fco, TrapMachineInsn::Store16);
7634 break;
7635 }
7636 case StorageType::I32: {
7637 FaultingCodeOffset fco = masm.store32(value.i32(), dst);
7638 NullCheckPolicy::emitTrapSite(this, fco, TrapMachineInsn::Store32);
7639 break;
7640 }
7641 case StorageType::I64: {
7642 #ifdef JS_64BIT
7643 FaultingCodeOffset fco = masm.store64(value.i64(), dst);
7644 NullCheckPolicy::emitTrapSite(this, fco, TrapMachineInsn::Store64);
7645 #else
7646 FaultingCodeOffsetPair fcop = masm.store64(value.i64(), dst);
7647 NullCheckPolicy::emitTrapSite(this, fcop.first, TrapMachineInsn::Store32);
7648 NullCheckPolicy::emitTrapSite(this, fcop.second,
7649 TrapMachineInsn::Store32);
7650 #endif
7651 break;
7652 }
7653 case StorageType::F32: {
7654 FaultingCodeOffset fco = masm.storeFloat32(value.f32(), dst);
7655 NullCheckPolicy::emitTrapSite(this, fco, TrapMachineInsn::Store32);
7656 break;
7657 }
7658 case StorageType::F64: {
7659 FaultingCodeOffset fco = masm.storeDouble(value.f64(), dst);
7660 NullCheckPolicy::emitTrapSite(this, fco, TrapMachineInsn::Store64);
7661 break;
7662 }
7663 #ifdef ENABLE_WASM_SIMD
7664 case StorageType::V128: {
7665 FaultingCodeOffset fco = masm.storeUnalignedSimd128(value.v128(), dst);
7666 NullCheckPolicy::emitTrapSite(this, fco, TrapMachineInsn::Store128);
7667 break;
7668 }
7669 #endif
7670 default: {
7671 MOZ_CRASH("Unexpected field type");
7672 }
7673 }
7674 }
7675
7676 template <typename NullCheckPolicy>
7677 bool BaseCompiler::emitGcStructSet(RegRef object, RegPtr areaBase,
7678 uint32_t areaOffset, StorageType type,
7679 AnyReg value,
7680 PreBarrierKind preBarrierKind) {
7681 // Easy path if the field is a scalar
7682 if (!type.isRefRepr()) {
7683 emitGcSetScalar<Address, NullCheckPolicy>(Address(areaBase, areaOffset),
7684 type, value);
7685 freeAny(value);
7686 return true;
7687 }
7688
7689 // Create temporary for the valueAddr that is not in the prebarrier register
7690 // and can be consumed by the barrier operation
7691 RegPtr valueAddr = RegPtr(PreBarrierReg);
7692 needPtr(valueAddr);
7693 masm.computeEffectiveAddress(Address(areaBase, areaOffset), valueAddr);
7694
7695 NullCheckPolicy::emitNullCheck(this, object);
7696
7697 // emitBarrieredStore preserves object and value
7698 if (!emitBarrieredStore(Some(object), valueAddr, value.ref(), preBarrierKind,
7699 PostBarrierKind::WholeCell)) {
7700 return false;
7701 }
7702 freeRef(value.ref());
7703
7704 return true;
7705 }
7706
7707 bool BaseCompiler::emitGcArraySet(RegRef object, RegPtr data, RegI32 index,
7708 const ArrayType& arrayType, AnyReg value,
7709 PreBarrierKind preBarrierKind) {
7710 // Try to use a base index store instruction if the field type fits in a
7711 // shift immediate. If not we shift the index manually and then unshift
7712 // it after the store. We don't use an extra register for this because we
7713 // don't have any to spare on x86.
7714 uint32_t shift = arrayType.elementType().indexingShift();
7715 Scale scale;
7716 bool shiftedIndex = false;
7717 if (IsShiftInScaleRange(shift)) {
7718 scale = ShiftToScale(shift);
7719 } else {
7720 masm.lshiftPtr(Imm32(shift), index);
7721 scale = TimesOne;
7722 shiftedIndex = true;
7723 }
7724 auto unshiftIndex = mozilla::MakeScopeExit([&] {
7725 if (shiftedIndex) {
7726 masm.rshiftPtr(Imm32(shift), index);
7727 }
7728 });
7729
7730 // Easy path if the field is a scalar
7731 if (!arrayType.elementType().isRefRepr()) {
7732 emitGcSetScalar<BaseIndex, NoNullCheck>(BaseIndex(data, index, scale, 0),
7733 arrayType.elementType(), value);
7734 return true;
7735 }
7736
7737 // Create temporaries for valueAddr that is not in the prebarrier register
7738 // and can be consumed by the barrier operation
7739 RegPtr valueAddr = RegPtr(PreBarrierReg);
7740 needPtr(valueAddr);
7741 masm.computeEffectiveAddress(BaseIndex(data, index, scale, 0), valueAddr);
7742
7743 // Save state for after barriered write
7744 pushPtr(data);
7745 pushI32(index);
7746
7747 // emitBarrieredStore preserves object and value
7748 if (!emitBarrieredStore(Some(object), valueAddr, value.ref(), preBarrierKind,
7749 PostBarrierKind::Imprecise)) {
7750 return false;
7751 }
7752
7753 // Restore state
7754 popI32(index);
7755 popPtr(data);
7756
7757 return true;
7758 }
7759
7760 template <bool ZeroFields>
7761 bool BaseCompiler::emitStructAlloc(uint32_t typeIndex, RegRef* object,
7762 bool* isOutlineStruct, RegPtr* outlineBase,
7763 uint32_t allocSiteIndex) {
7764 const TypeDef& typeDef = (*codeMeta_.types)[typeIndex];
7765 const StructType& structType = typeDef.structType();
7766 gc::AllocKind allocKind = WasmStructObject::allocKindForTypeDef(&typeDef);
7767
7768 *isOutlineStruct = WasmStructObject::requiresOutlineBytes(structType.size_);
7769
7770 // Reserve this register early if we will need it so that it is not taken by
7771 // any register used in this function.
7772 needPtr(RegPtr(PreBarrierReg));
7773
7774 *object = RegRef();
7775
7776 // Allocate an uninitialized struct. This requires the type definition
7777 // for the struct to be pushed on the stack. This will trap on OOM.
7778 if (*isOutlineStruct) {
7779 pushI32(int32_t(typeIndex));
7780 pushPtr(loadAllocSiteInstanceData(allocSiteIndex));
7781 if (!emitInstanceCall(ZeroFields ? SASigStructNewOOL_true
7782 : SASigStructNewOOL_false)) {
7783 return false;
7784 }
7785 *object = popRef();
7786 } else {
7787 // We eagerly sync the value stack to the machine stack here so as not to
7788 // confuse things with the conditional instance call below.
7789 sync();
7790
7791 RegPtr instance;
7792 *object = RegRef(ReturnReg);
7793 needRef(*object);
7794 #ifndef RABALDR_PIN_INSTANCE
7795 // We reuse the result register for the instance.
7796 instance = needPtr();
7797 fr.loadInstancePtr(instance);
7798 #else
7799 // We can use the pinned instance register.
7800 instance = RegPtr(InstanceReg);
7801 #endif
7802
7803 RegPtr allocSite = loadAllocSiteInstanceData(allocSiteIndex);
7804
7805 size_t offsetOfTypeDefData = wasm::Instance::offsetInData(
7806 codeMeta_.offsetOfTypeDefInstanceData(typeIndex));
7807
7808 Label success;
7809 Label fail;
7810 {
7811 ScratchPtr scratch(*this);
7812
7813 masm.wasmNewStructObject(instance, *object, allocSite, scratch,
7814 offsetOfTypeDefData, &fail, allocKind,
7815 ZeroFields);
7816 }
7817 masm.jump(&success);
7818
7819 masm.bind(&fail);
7820 #ifndef RABALDR_PIN_INSTANCE
7821 freePtr(instance);
7822 #endif
7823 freeRef(*object);
7824 pushI32(int32_t(typeIndex));
7825 pushPtr(allocSite);
7826 if (!emitInstanceCall(ZeroFields ? SASigStructNewIL_true
7827 : SASigStructNewIL_false)) {
7828 return false;
7829 }
7830 *object = popRef();
7831 MOZ_ASSERT(*object == RegRef(ReturnReg));
7832
7833 masm.bind(&success);
7834 }
7835
7836 *outlineBase = *isOutlineStruct ? needPtr() : RegPtr();
7837
7838 // Free the barrier reg for later use
7839 freePtr(RegPtr(PreBarrierReg));
7840
7841 return true;
7842 }
7843
7844 bool BaseCompiler::emitStructNew() {
7845 uint32_t typeIndex;
7846 BaseNothingVector args{};
7847 if (!iter_.readStructNew(&typeIndex, &args)) {
7848 return false;
7849 }
7850
7851 uint32_t allocSiteIndex;
7852 if (!readAllocSiteIndex(&allocSiteIndex)) {
7853 return false;
7854 }
7855
7856 if (deadCode_) {
7857 return true;
7858 }
7859
7860 const TypeDef& typeDef = (*codeMeta_.types)[typeIndex];
7861 const StructType& structType = typeDef.structType();
7862
7863 RegRef object;
7864 RegPtr outlineBase;
7865 bool isOutlineStruct;
7866 if (!emitStructAlloc<false>(typeIndex, &object, &isOutlineStruct,
7867 &outlineBase, allocSiteIndex)) {
7868 return false;
7869 }
7870
7871 // Optimization opportunity: Iterate backward to pop arguments off the
7872 // stack. This will generate more instructions than we want, since we
7873 // really only need to pop the stack once at the end, not for every element,
7874 // but to do better we need a bit more machinery to load elements off the
7875 // stack into registers.
7876
7877 // Optimization opportunity: when the value being stored is a known
7878 // zero/null we need store nothing. This case may be somewhat common
7879 // because struct.new forces a value to be specified for every field.
7880
7881 // Optimization opportunity: this loop reestablishes the outline base pointer
7882 // every iteration, which really isn't very clever. It would be better to
7883 // establish it once before we start, then re-set it if/when we transition
7884 // from the out-of-line area back to the in-line area. That would however
7885 // require making ::emitGcStructSet preserve that register, which it
7886 // currently doesn't.
7887
7888 uint32_t fieldIndex = structType.fields_.length();
7889 while (fieldIndex-- > 0) {
7890 const FieldType& field = structType.fields_[fieldIndex];
7891 StorageType type = field.type;
7892 uint32_t fieldOffset = structType.fieldOffset(fieldIndex);
7893
7894 bool areaIsOutline;
7895 uint32_t areaOffset;
7896 WasmStructObject::fieldOffsetToAreaAndOffset(type, fieldOffset,
7897 &areaIsOutline, &areaOffset);
7898
7899 // Reserve the barrier reg if we might need it for this store
7900 if (type.isRefRepr()) {
7901 needPtr(RegPtr(PreBarrierReg));
7902 }
7903 AnyReg value = popAny();
7904 // Free the barrier reg now that we've loaded the value
7905 if (type.isRefRepr()) {
7906 freePtr(RegPtr(PreBarrierReg));
7907 }
7908
7909 if (areaIsOutline) {
7910 // Load the outline data pointer
7911 masm.loadPtr(Address(object, WasmStructObject::offsetOfOutlineData()),
7912 outlineBase);
7913
7914 // Consumes value and outline data, object is preserved by this call.
7915 if (!emitGcStructSet<NoNullCheck>(object, outlineBase, areaOffset, type,
7916 value, PreBarrierKind::None)) {
7917 return false;
7918 }
7919 } else {
7920 // Consumes value. object is unchanged by this call.
7921 if (!emitGcStructSet<NoNullCheck>(
7922 object, RegPtr(object),
7923 WasmStructObject::offsetOfInlineData() + areaOffset, type, value,
7924 PreBarrierKind::None)) {
7925 return false;
7926 }
7927 }
7928 }
7929
7930 if (isOutlineStruct) {
7931 freePtr(outlineBase);
7932 }
7933 pushRef(object);
7934
7935 return true;
7936 }
7937
7938 bool BaseCompiler::emitStructNewDefault() {
7939 uint32_t typeIndex;
7940 if (!iter_.readStructNewDefault(&typeIndex)) {
7941 return false;
7942 }
7943
7944 uint32_t allocSiteIndex;
7945 if (!readAllocSiteIndex(&allocSiteIndex)) {
7946 return false;
7947 }
7948
7949 if (deadCode_) {
7950 return true;
7951 }
7952
7953 RegRef object;
7954 bool isOutlineStruct;
7955 RegPtr outlineBase;
7956 if (!emitStructAlloc<true>(typeIndex, &object, &isOutlineStruct, &outlineBase,
7957 allocSiteIndex)) {
7958 return false;
7959 }
7960
7961 if (isOutlineStruct) {
7962 freePtr(outlineBase);
7963 }
7964 pushRef(object);
7965
7966 return true;
7967 }
7968
7969 bool BaseCompiler::emitStructGet(FieldWideningOp wideningOp) {
7970 uint32_t typeIndex;
7971 uint32_t fieldIndex;
7972 Nothing nothing;
7973 if (!iter_.readStructGet(&typeIndex, &fieldIndex, wideningOp, &nothing)) {
7974 return false;
7975 }
7976
7977 if (deadCode_) {
7978 return true;
7979 }
7980
7981 const StructType& structType = (*codeMeta_.types)[typeIndex].structType();
7982
7983 // Decide whether we're accessing inline or outline, and at what offset
7984 StorageType fieldType = structType.fields_[fieldIndex].type;
7985 uint32_t fieldOffset = structType.fieldOffset(fieldIndex);
7986
7987 bool areaIsOutline;
7988 uint32_t areaOffset;
7989 WasmStructObject::fieldOffsetToAreaAndOffset(fieldType, fieldOffset,
7990 &areaIsOutline, &areaOffset);
7991
7992 RegRef object = popRef();
7993 if (areaIsOutline) {
7994 RegPtr outlineBase = needPtr();
7995 FaultingCodeOffset fco = masm.loadPtr(
7996 Address(object, WasmStructObject::offsetOfOutlineData()), outlineBase);
7997 SignalNullCheck::emitTrapSite(this, fco, TrapMachineInsnForLoadWord());
7998 // Load the value
7999 emitGcGet<Address, NoNullCheck>(fieldType, wideningOp,
8000 Address(outlineBase, areaOffset));
8001 freePtr(outlineBase);
8002 } else {
8003 // Load the value
8004 emitGcGet<Address, SignalNullCheck>(
8005 fieldType, wideningOp,
8006 Address(object, WasmStructObject::offsetOfInlineData() + areaOffset));
8007 }
8008 freeRef(object);
8009
8010 return true;
8011 }
8012
8013 bool BaseCompiler::emitStructSet() {
8014 uint32_t typeIndex;
8015 uint32_t fieldIndex;
8016 Nothing nothing;
8017 if (!iter_.readStructSet(&typeIndex, &fieldIndex, &nothing, &nothing)) {
8018 return false;
8019 }
8020
8021 if (deadCode_) {
8022 return true;
8023 }
8024
8025 const StructType& structType = (*codeMeta_.types)[typeIndex].structType();
8026 const FieldType& structField = structType.fields_[fieldIndex];
8027
8028 // Decide whether we're accessing inline or outline, and at what offset
8029 StorageType fieldType = structType.fields_[fieldIndex].type;
8030 uint32_t fieldOffset = structType.fieldOffset(fieldIndex);
8031
8032 bool areaIsOutline;
8033 uint32_t areaOffset;
8034 WasmStructObject::fieldOffsetToAreaAndOffset(fieldType, fieldOffset,
8035 &areaIsOutline, &areaOffset);
8036
8037 // Reserve this register early if we will need it so that it is not taken by
8038 // any register used in this function.
8039 if (structField.type.isRefRepr()) {
8040 needPtr(RegPtr(PreBarrierReg));
8041 }
8042
8043 RegPtr outlineBase = areaIsOutline ? needPtr() : RegPtr();
8044 AnyReg value = popAny();
8045 RegRef object = popRef();
8046
8047 // Free the barrier reg after we've allocated all registers
8048 if (structField.type.isRefRepr()) {
8049 freePtr(RegPtr(PreBarrierReg));
8050 }
8051
8052 // Make outlineBase point at the first byte of the relevant area
8053 if (areaIsOutline) {
8054 FaultingCodeOffset fco = masm.loadPtr(
8055 Address(object, WasmStructObject::offsetOfOutlineData()), outlineBase);
8056 SignalNullCheck::emitTrapSite(this, fco, TrapMachineInsnForLoadWord());
8057 if (!emitGcStructSet<NoNullCheck>(object, outlineBase, areaOffset,
8058 fieldType, value,
8059 PreBarrierKind::Normal)) {
8060 return false;
8061 }
8062 } else {
8063 // Consumes value. object is unchanged by this call.
8064 if (!emitGcStructSet<SignalNullCheck>(
8065 object, RegPtr(object),
8066 WasmStructObject::offsetOfInlineData() + areaOffset, fieldType,
8067 value, PreBarrierKind::Normal)) {
8068 return false;
8069 }
8070 }
8071
8072 if (areaIsOutline) {
8073 freePtr(outlineBase);
8074 }
8075 freeRef(object);
8076
8077 return true;
8078 }
8079
8080 template <bool ZeroFields>
8081 bool BaseCompiler::emitArrayAlloc(uint32_t typeIndex, RegRef object,
8082 RegI32 numElements, uint32_t elemSize,
8083 uint32_t allocSiteIndex) {
8084 // We eagerly sync the value stack to the machine stack here so as not to
8085 // confuse things with the conditional instance call below.
8086 sync();
8087
8088 RegPtr instance;
8089 #ifndef RABALDR_PIN_INSTANCE
8090 // We reuse the object register for the instance. This is ok because object is
8091 // not live until instance is dead.
8092 instance = needPtr();
8093 fr.loadInstancePtr(instance);
8094 #else
8095 // We can use the pinned instance register.
8096 instance = RegPtr(InstanceReg);
8097 #endif
8098
8099 RegPtr allocSite = loadAllocSiteInstanceData(allocSiteIndex);
8100
8101 size_t offsetOfTypeDefData = wasm::Instance::offsetInData(
8102 codeMeta_.offsetOfTypeDefInstanceData(typeIndex));
8103
8104 Label success;
8105 Label fail;
8106 {
8107 ScratchPtr scratch(*this);
8108 masm.wasmNewArrayObject(instance, object, numElements, allocSite, scratch,
8109 offsetOfTypeDefData, &fail, elemSize, ZeroFields);
8110 }
8111 masm.jump(&success);
8112
8113 masm.bind(&fail);
8114 #ifndef RABALDR_PIN_INSTANCE
8115 freePtr(instance);
8116 #endif
8117 freeRef(object);
8118 pushI32(numElements);
8119 pushI32(int32_t(typeIndex));
8120 pushPtr(allocSite);
8121 if (!emitInstanceCall(ZeroFields ? SASigArrayNew_true
8122 : SASigArrayNew_false)) {
8123 return false;
8124 }
8125 popRef(object);
8126
8127 masm.bind(&success);
8128 return true;
8129 }
8130
8131 template <bool ZeroFields>
8132 bool BaseCompiler::emitArrayAllocFixed(uint32_t typeIndex, RegRef object,
8133 uint32_t numElements, uint32_t elemSize,
8134 uint32_t allocSiteIndex) {
8135 SymbolicAddressSignature fun =
8136 ZeroFields ? SASigArrayNew_true : SASigArrayNew_false;
8137
8138 // The maximum number of elements for array.new_fixed enforced in validation
8139 // should always prevent overflow here.
8140 static_assert(MaxArrayNewFixedElements * sizeof(wasm::LitVal) <
8141 MaxArrayPayloadBytes);
8142 uint32_t storageBytes =
8143 WasmArrayObject::calcStorageBytesUnchecked(elemSize, numElements);
8144 if (storageBytes > WasmArrayObject_MaxInlineBytes) {
8145 freeRef(object);
8146 pushI32(numElements);
8147 pushI32(int32_t(typeIndex));
8148 pushPtr(loadAllocSiteInstanceData(allocSiteIndex));
8149 if (!emitInstanceCall(fun)) {
8150 return false;
8151 }
8152 popRef(object);
8153
8154 return true;
8155 }
8156
8157 // We eagerly sync the value stack to the machine stack here so as not to
8158 // confuse things with the conditional instance call below.
8159 sync();
8160
8161 RegPtr instance;
8162 #ifndef RABALDR_PIN_INSTANCE
8163 // We reuse the object register for the instance. This is ok because object is
8164 // not live until instance is dead.
8165 instance = needPtr();
8166 fr.loadInstancePtr(instance);
8167 #else
8168 // We can use the pinned instance register.
8169 instance = RegPtr(InstanceReg);
8170 #endif
8171
8172 RegPtr allocSite = loadAllocSiteInstanceData(allocSiteIndex);
8173 RegPtr temp1 = needPtr();
8174
8175 size_t offsetOfTypeDefData = wasm::Instance::offsetInData(
8176 codeMeta_.offsetOfTypeDefInstanceData(typeIndex));
8177
8178 Label success;
8179 Label fail;
8180 {
8181 ScratchPtr scratch(*this);
8182 masm.wasmNewArrayObjectFixed(instance, object, allocSite, temp1, scratch,
8183 offsetOfTypeDefData, &fail, numElements,
8184 storageBytes, ZeroFields);
8185 }
8186 freePtr(temp1);
8187 masm.jump(&success);
8188
8189 masm.bind(&fail);
8190 #ifndef RABALDR_PIN_INSTANCE
8191 freePtr(instance);
8192 #endif
8193 freeRef(object);
8194 pushI32(numElements);
8195 pushI32(int32_t(typeIndex));
8196 pushPtr(allocSite);
8197 if (!emitInstanceCall(fun)) {
8198 return false;
8199 }
8200 popRef(object);
8201
8202 masm.bind(&success);
8203
8204 return true;
8205 }
8206
8207 bool BaseCompiler::emitArrayNew() {
8208 uint32_t typeIndex;
8209 Nothing nothing;
8210 if (!iter_.readArrayNew(&typeIndex, &nothing, &nothing)) {
8211 return false;
8212 }
8213
8214 uint32_t allocSiteIndex;
8215 if (!readAllocSiteIndex(&allocSiteIndex)) {
8216 return false;
8217 }
8218
8219 if (deadCode_) {
8220 return true;
8221 }
8222
8223 const ArrayType& arrayType = (*codeMeta_.types)[typeIndex].arrayType();
8224
8225 // Reserve this register early if we will need it so that it is not taken by
8226 // any register used in this function.
8227 if (arrayType.elementType().isRefRepr()) {
8228 needPtr(RegPtr(PreBarrierReg));
8229 }
8230
8231 RegRef object = needRef();
8232 RegI32 numElements = popI32();
8233 if (!emitArrayAlloc<false>(typeIndex, object, numElements,
8234 arrayType.elementType().size(), allocSiteIndex)) {
8235 return false;
8236 }
8237
8238 AnyReg value = popAny();
8239
8240 // Acquire the data pointer from the object
8241 RegPtr rdata = emitGcArrayGetData<NoNullCheck>(object);
8242
8243 // Acquire the number of elements again
8244 numElements = emitGcArrayGetNumElements<NoNullCheck>(object);
8245
8246 // Free the barrier reg after we've allocated all registers
8247 if (arrayType.elementType().isRefRepr()) {
8248 freePtr(RegPtr(PreBarrierReg));
8249 }
8250
8251 // Perform an initialization loop using `numElements` as the loop variable,
8252 // counting down to zero.
8253 Label done;
8254 Label loop;
8255 // Skip initialization if numElements = 0
8256 masm.branch32(Assembler::Equal, numElements, Imm32(0), &done);
8257 masm.bind(&loop);
8258
8259 // Move to the next element
8260 masm.sub32(Imm32(1), numElements);
8261
8262 // Assign value to array[numElements]. All registers are preserved
8263 if (!emitGcArraySet(object, rdata, numElements, arrayType, value,
8264 PreBarrierKind::None)) {
8265 return false;
8266 }
8267
8268 // Loop back if there are still elements to initialize
8269 masm.branch32(Assembler::GreaterThan, numElements, Imm32(0), &loop);
8270 masm.bind(&done);
8271
8272 freeI32(numElements);
8273 freeAny(value);
8274 freePtr(rdata);
8275 pushRef(object);
8276
8277 return true;
8278 }
8279
8280 bool BaseCompiler::emitArrayNewFixed() {
8281 uint32_t typeIndex, numElements;
8282 BaseNothingVector nothings{};
8283 if (!iter_.readArrayNewFixed(&typeIndex, &numElements, &nothings)) {
8284 return false;
8285 }
8286
8287 uint32_t allocSiteIndex;
8288 if (!readAllocSiteIndex(&allocSiteIndex)) {
8289 return false;
8290 }
8291
8292 if (deadCode_) {
8293 return true;
8294 }
8295
8296 const ArrayType& arrayType = (*codeMeta_.types)[typeIndex].arrayType();
8297
8298 // Reserve this register early if we will need it so that it is not taken by
8299 // any register used in this function.
8300 bool avoidPreBarrierReg = arrayType.elementType().isRefRepr();
8301 if (avoidPreBarrierReg) {
8302 needPtr(RegPtr(PreBarrierReg));
8303 }
8304
8305 RegRef object = needRef();
8306 if (!emitArrayAllocFixed<false>(typeIndex, object, numElements,
8307 arrayType.elementType().size(),
8308 allocSiteIndex)) {
8309 return false;
8310 }
8311
8312 // Acquire the data pointer from the object
8313 RegPtr rdata = emitGcArrayGetData<NoNullCheck>(object);
8314
8315 // Free the barrier reg if we previously reserved it.
8316 if (avoidPreBarrierReg) {
8317 freePtr(RegPtr(PreBarrierReg));
8318 }
8319
8320 // These together ensure that the max value of `index` in the loop below
8321 // remains comfortably below the 2^31 boundary. See comments on equivalent
8322 // assertions in EmitArrayNewFixed in WasmIonCompile.cpp for explanation.
8323 static_assert(16 /* sizeof v128 */ * MaxFunctionBytes <=
8324 MaxArrayPayloadBytes);
8325 MOZ_RELEASE_ASSERT(numElements <= MaxFunctionBytes);
8326
8327 // Generate straight-line initialization code. We could do better here if
8328 // there was a version of ::emitGcArraySet that took `index` as a `uint32_t`
8329 // rather than a general value-in-a-reg.
8330 for (uint32_t forwardIndex = 0; forwardIndex < numElements; forwardIndex++) {
8331 uint32_t reverseIndex = numElements - forwardIndex - 1;
8332 if (avoidPreBarrierReg) {
8333 needPtr(RegPtr(PreBarrierReg));
8334 }
8335 AnyReg value = popAny();
8336 pushI32(reverseIndex);
8337 RegI32 index = popI32();
8338 if (avoidPreBarrierReg) {
8339 freePtr(RegPtr(PreBarrierReg));
8340 }
8341 if (!emitGcArraySet(object, rdata, index, arrayType, value,
8342 PreBarrierKind::None)) {
8343 return false;
8344 }
8345 freeI32(index);
8346 freeAny(value);
8347 }
8348
8349 freePtr(rdata);
8350
8351 pushRef(object);
8352 return true;
8353 }
8354
8355 bool BaseCompiler::emitArrayNewDefault() {
8356 uint32_t typeIndex;
8357 Nothing nothing;
8358 if (!iter_.readArrayNewDefault(&typeIndex, &nothing)) {
8359 return false;
8360 }
8361
8362 uint32_t allocSiteIndex;
8363 if (!readAllocSiteIndex(&allocSiteIndex)) {
8364 return false;
8365 }
8366
8367 if (deadCode_) {
8368 return true;
8369 }
8370
8371 const ArrayType& arrayType = (*codeMeta_.types)[typeIndex].arrayType();
8372
8373 RegRef object = needRef();
8374 RegI32 numElements = popI32();
8375 if (!emitArrayAlloc<true>(typeIndex, object, numElements,
8376 arrayType.elementType().size(), allocSiteIndex)) {
8377 return false;
8378 }
8379
8380 pushRef(object);
8381 return true;
8382 }
8383
8384 bool BaseCompiler::emitArrayNewData() {
8385 uint32_t typeIndex, segIndex;
8386 Nothing nothing;
8387 if (!iter_.readArrayNewData(&typeIndex, &segIndex, &nothing, &nothing)) {
8388 return false;
8389 }
8390
8391 uint32_t allocSiteIndex;
8392 if (!readAllocSiteIndex(&allocSiteIndex)) {
8393 return false;
8394 }
8395
8396 if (deadCode_) {
8397 return true;
8398 }
8399
8400 pushI32(int32_t(typeIndex));
8401 pushPtr(loadAllocSiteInstanceData(allocSiteIndex));
8402 pushI32(int32_t(segIndex));
8403
8404 // The call removes 4 items from the stack: the segment byte offset and
8405 // number of elements (operands to array.new_data), and the type data and
8406 // seg index as pushed above.
8407 return emitInstanceCall(SASigArrayNewData);
8408 }
8409
8410 bool BaseCompiler::emitArrayNewElem() {
8411 uint32_t typeIndex, segIndex;
8412 Nothing nothing;
8413 if (!iter_.readArrayNewElem(&typeIndex, &segIndex, &nothing, &nothing)) {
8414 return false;
8415 }
8416
8417 uint32_t allocSiteIndex;
8418 if (!readAllocSiteIndex(&allocSiteIndex)) {
8419 return false;
8420 }
8421
8422 if (deadCode_) {
8423 return true;
8424 }
8425
8426 pushI32(int32_t(typeIndex));
8427 pushPtr(loadAllocSiteInstanceData(allocSiteIndex));
8428 pushI32(int32_t(segIndex));
8429
8430 // The call removes 4 items from the stack: the segment element offset and
8431 // number of elements (operands to array.new_elem), and the type data and
8432 // seg index as pushed above.
8433 return emitInstanceCall(SASigArrayNewElem);
8434 }
8435
8436 bool BaseCompiler::emitArrayInitData() {
8437 uint32_t unusedTypeIndex, segIndex;
8438 Nothing nothing;
8439 if (!iter_.readArrayInitData(&unusedTypeIndex, &segIndex, &nothing, &nothing,
8440 &nothing, &nothing)) {
8441 return false;
8442 }
8443
8444 if (deadCode_) {
8445 return true;
8446 }
8447
8448 pushI32(int32_t(segIndex));
8449
8450 // The call removes 5 items from the stack: the array, array index, segment
8451 // byte offset, and number of elements (operands to array.init_data), and the
8452 // seg index as pushed above. TypeDefInstanceData is not necessary for this
8453 // call because the array object has a reference to its type.
8454 return emitInstanceCall(SASigArrayInitData);
8455 }
8456
8457 bool BaseCompiler::emitArrayInitElem() {
8458 uint32_t typeIndex, segIndex;
8459 Nothing nothing;
8460 if (!iter_.readArrayInitElem(&typeIndex, &segIndex, &nothing, &nothing,
8461 &nothing, &nothing)) {
8462 return false;
8463 }
8464
8465 if (deadCode_) {
8466 return true;
8467 }
8468
8469 pushI32(int32_t(typeIndex));
8470 pushI32(int32_t(segIndex));
8471
8472 // The call removes 6 items from the stack: the array, array index, segment
8473 // offset, and number of elements (operands to array.init_elem), and the type
8474 // data and seg index as pushed above.
8475 return emitInstanceCall(SASigArrayInitElem);
8476 }
8477
8478 bool BaseCompiler::emitArrayGet(FieldWideningOp wideningOp) {
8479 uint32_t typeIndex;
8480 Nothing nothing;
8481 if (!iter_.readArrayGet(&typeIndex, wideningOp, &nothing, &nothing)) {
8482 return false;
8483 }
8484
8485 if (deadCode_) {
8486 return true;
8487 }
8488
8489 const ArrayType& arrayType = (*codeMeta_.types)[typeIndex].arrayType();
8490
8491 RegI32 index = popI32();
8492 RegRef rp = popRef();
8493
8494 // Acquire the number of elements
8495 RegI32 numElements = emitGcArrayGetNumElements<SignalNullCheck>(rp);
8496
8497 // Bounds check the index
8498 emitGcArrayBoundsCheck(index, numElements);
8499 freeI32(numElements);
8500
8501 // Acquire the data pointer from the object
8502 RegPtr rdata = emitGcArrayGetData<NoNullCheck>(rp);
8503
8504 // Load the value
8505 uint32_t shift = arrayType.elementType().indexingShift();
8506 if (IsShiftInScaleRange(shift)) {
8507 emitGcGet<BaseIndex, NoNullCheck>(
8508 arrayType.elementType(), wideningOp,
8509 BaseIndex(rdata, index, ShiftToScale(shift), 0));
8510 } else {
8511 masm.lshiftPtr(Imm32(shift), index);
8512 emitGcGet<BaseIndex, NoNullCheck>(arrayType.elementType(), wideningOp,
8513 BaseIndex(rdata, index, TimesOne, 0));
8514 }
8515
8516 freePtr(rdata);
8517 freeRef(rp);
8518 freeI32(index);
8519
8520 return true;
8521 }
8522
8523 bool BaseCompiler::emitArraySet() {
8524 uint32_t typeIndex;
8525 Nothing nothing;
8526 if (!iter_.readArraySet(&typeIndex, &nothing, &nothing, &nothing)) {
8527 return false;
8528 }
8529
8530 if (deadCode_) {
8531 return true;
8532 }
8533
8534 const ArrayType& arrayType = (*codeMeta_.types)[typeIndex].arrayType();
8535
8536 // Reserve this register early if we will need it so that it is not taken by
8537 // any register used in this function.
8538 if (arrayType.elementType().isRefRepr()) {
8539 needPtr(RegPtr(PreBarrierReg));
8540 }
8541
8542 AnyReg value = popAny();
8543 RegI32 index = popI32();
8544 RegRef rp = popRef();
8545
8546 // Acquire the number of elements
8547 RegI32 numElements = emitGcArrayGetNumElements<SignalNullCheck>(rp);
8548
8549 // Bounds check the index
8550 emitGcArrayBoundsCheck(index, numElements);
8551 freeI32(numElements);
8552
8553 // Acquire the data pointer from the object
8554 RegPtr rdata = emitGcArrayGetData<NoNullCheck>(rp);
8555
8556 // Free the barrier reg after we've allocated all registers
8557 if (arrayType.elementType().isRefRepr()) {
8558 freePtr(RegPtr(PreBarrierReg));
8559 }
8560
8561 // All registers are preserved. This isn't strictly necessary, as we'll just
8562 // be freeing them all after this is done. But this is needed for repeated
8563 // assignments used in array.new/new_default.
8564 if (!emitGcArraySet(rp, rdata, index, arrayType, value,
8565 PreBarrierKind::Normal)) {
8566 return false;
8567 }
8568
8569 freePtr(rdata);
8570 freeRef(rp);
8571 freeI32(index);
8572 freeAny(value);
8573
8574 return true;
8575 }
8576
8577 bool BaseCompiler::emitArrayLen() {
8578 Nothing nothing;
8579 if (!iter_.readArrayLen(&nothing)) {
8580 return false;
8581 }
8582
8583 if (deadCode_) {
8584 return true;
8585 }
8586
8587 RegRef rp = popRef();
8588
8589 // Acquire the number of elements
8590 RegI32 numElements = emitGcArrayGetNumElements<SignalNullCheck>(rp);
8591 pushI32(numElements);
8592
8593 freeRef(rp);
8594
8595 return true;
8596 }
8597
8598 bool BaseCompiler::emitArrayCopy() {
8599 uint32_t dstArrayTypeIndex;
8600 uint32_t srcArrayTypeIndex;
8601 Nothing nothing;
8602 if (!iter_.readArrayCopy(&dstArrayTypeIndex, &srcArrayTypeIndex, &nothing,
8603 &nothing, &nothing, &nothing, &nothing)) {
8604 return false;
8605 }
8606
8607 if (deadCode_) {
8608 return true;
8609 }
8610
8611 const ArrayType& dstArrayType =
8612 codeMeta_.types->type(dstArrayTypeIndex).arrayType();
8613 StorageType dstElemType = dstArrayType.elementType();
8614 int32_t elemSize = int32_t(dstElemType.size());
8615 bool elemsAreRefTyped = dstElemType.isRefType();
8616
8617 // The helper needs to know the element size. If copying ref values, the size
8618 // is negated to signal to the helper that it needs to do GC barriers and
8619 // such.
8620 pushI32(elemsAreRefTyped ? -elemSize : elemSize);
8621
8622 return emitInstanceCall(SASigArrayCopy);
8623 }
8624
8625 bool BaseCompiler::emitArrayFill() {
8626 AutoCreatedBy acb(masm, "(wasm)BaseCompiler::emitArrayFill");
8627 uint32_t typeIndex;
8628 Nothing nothing;
8629 if (!iter_.readArrayFill(&typeIndex, &nothing, &nothing, &nothing,
8630 &nothing)) {
8631 return false;
8632 }
8633
8634 if (deadCode_) {
8635 return true;
8636 }
8637
8638 const TypeDef& typeDef = codeMeta_.types->type(typeIndex);
8639 const ArrayType& arrayType = typeDef.arrayType();
8640 StorageType elementType = arrayType.elementType();
8641
8642 // On x86 (32-bit), we are very short of registers, hence the code
8643 // generation scheme is less straightforward than it might otherwise be.
8644 //
8645 // Comment lines below of the form
8646 //
8647 // 3: foo bar xyzzy
8648 //
8649 // mean "at this point there are 3 integer regs in use (not including the
8650 // possible 2 needed for `value` in the worst case), and those 3 regs hold
8651 // the values for `foo`, `bar` and `xyzzy`.
8652 //
8653 // On x86, the worst case, we only have 3 int regs available (not including
8654 // `value`), thusly:
8655 //
8656 // - as a basis, we have: eax ebx ecx edx esi edi
8657 //
8658 // - ebx is "kind of" not available, since it is reserved as a wasm-baseline
8659 // scratch register (called `RabaldrScratchI32` on most targets, but
8660 // acquired below using `ScratchI32(..)`).
8661 //
8662 // - `value` isn't needed till the initialisation loop itself, hence it
8663 // would seem attractive to spill it across the range-check and setup code
8664 // that precedes the loop. However, it has variable type and regclass
8665 // (eg, it could be v128 or f32 or f64), which make spilling it somewhat
8666 // complex, so we bite the bullet and just allocate it at the start of the
8667 // routine.
8668 //
8669 // - Consequently we have the following two cases as worst-cases:
8670 //
8671 // * `value` is I64, so uses two registers on x86.
8672 // * `value` is reftyped, using one register, but also making
8673 // PreBarrierReg unavailable.
8674 //
8675 // - As a result of all of the above, we have only three registers, and
8676 // RabaldrScratchI32, to work with. And 4 spill-slot words; however ..
8677 //
8678 // - .. to spill/reload from a spill slot, we need a register to point at
8679 // the instance. That makes it even worse on x86 since there's no
8680 // reserved instance reg; hence we have to use one of our 3 for it. This
8681 // is indicated explicitly in the code below.
8682 //
8683 // There are many comment lines indicating the current disposition of the 3
8684 // regs.
8685 //
8686 // This generates somewhat clunky code for the setup and bounds test, but
8687 // the actual initialisation loop still has everything in registers, so
8688 // should run fast.
8689 //
8690 // The same scheme is used for all targets. Hence they all get clunky setup
8691 // code. Considering that this is a baseline compiler and also that the
8692 // loop itself is all-in-regs, this seems like a not-bad compromise compared
8693 // to having two different implementations for x86 vs everything else.
8694
8695 // Reserve this register early if we will need it so that it is not taken by
8696 // any register used in this function.
8697 if (elementType.isRefRepr()) {
8698 needPtr(RegPtr(PreBarrierReg));
8699 }
8700
8701 // Set up a pointer to the Instance, so we can do manual spills/reloads
8702 #ifdef RABALDR_PIN_INSTANCE
8703 RegPtr instancePtr = RegPtr(InstanceReg);
8704 #else
8705 RegPtr instancePtr = needPtr();
8706 fr.loadInstancePtr(instancePtr);
8707 #endif
8708
8709 // Pull operands off the instance stack and stash the non-Any ones
8710 RegI32 numElements = popI32();
8711 stashWord(instancePtr, 0, RegPtr(numElements));
8712 freeI32(numElements);
8713 numElements = RegI32::Invalid();
8714
8715 AnyReg value = popAny();
8716
8717 RegI32 index = popI32();
8718 stashWord(instancePtr, 1, RegPtr(index));
8719 freeI32(index);
8720 index = RegI32::Invalid();
8721
8722 RegRef rp = popRef();
8723 stashWord(instancePtr, 2, RegPtr(rp));
8724 // 2: instancePtr rp
8725
8726 // Acquire the actual length of the array
8727 RegI32 arrayNumElements = emitGcArrayGetNumElements<SignalNullCheck>(rp);
8728 // 3: instancePtr rp arrayNumElements
8729
8730 // Drop rp
8731 freeRef(rp);
8732 rp = RegRef::Invalid();
8733 // 2: instancePtr arrayNumElements
8734
8735 // Reload index
8736 index = needI32();
8737 unstashWord(instancePtr, 1, RegPtr(index));
8738 // 3: instancePtr arrayNumElements index
8739
8740 // Reload numElements into the reg that currently holds instancePtr
8741 #ifdef RABALDR_PIN_INSTANCE
8742 numElements = needI32();
8743 #else
8744 numElements = RegI32(instancePtr);
8745 #endif
8746 unstashWord(instancePtr, 0, RegPtr(numElements));
8747 instancePtr = RegPtr::Invalid();
8748 // 3: arrayNumElements index numElements
8749
8750 // Do the bounds check. For this we will need to get hold of the
8751 // wasm-baseline's scratch register.
8752 {
8753 ScratchI32 scratch(*this);
8754 MOZ_ASSERT(RegI32(scratch) != arrayNumElements);
8755 MOZ_ASSERT(RegI32(scratch) != index);
8756 MOZ_ASSERT(RegI32(scratch) != numElements);
8757 masm.wasmBoundsCheckRange32(index, numElements, arrayNumElements, scratch,
8758 trapSiteDesc());
8759 }
8760 // 3: arrayNumElements index numElements
8761
8762 // Drop arrayNumElements and numElements
8763 freeI32(arrayNumElements);
8764 arrayNumElements = RegI32::Invalid();
8765 freeI32(numElements);
8766 numElements = RegI32::Invalid();
8767 // 1: index
8768
8769 // Re-set-up the instance pointer; we had to ditch it earlier.
8770 #ifdef RABALDR_PIN_INSTANCE
8771 instancePtr = RegPtr(InstanceReg);
8772 #else
8773 instancePtr = needPtr();
8774 fr.loadInstancePtr(instancePtr);
8775 #endif
8776 // 2: index instancePtr
8777
8778 // Reload rp
8779 rp = needRef();
8780 unstashWord(instancePtr, 2, RegPtr(rp));
8781 // 3: index instancePtr rp
8782
8783 // Drop instancePtr
8784 #ifdef RABALDR_PIN_INSTANCE
8785 instancePtr = RegPtr::Invalid();
8786 #else
8787 freePtr(instancePtr);
8788 instancePtr = RegPtr::Invalid();
8789 #endif
8790 // 2: index rp
8791
8792 // Acquire the data pointer from the object
8793 RegPtr rdata = emitGcArrayGetData<NoNullCheck>(rp);
8794 // 3: index rp rdata
8795
8796 // Currently `rdata` points at the start of the array data area. Move it
8797 // forwards by `index` units so as to make it point at the start of the area
8798 // to be filled.
8799 uint32_t shift = arrayType.elementType().indexingShift();
8800 if (shift > 0) {
8801 masm.lshift32(Imm32(shift), index);
8802 // `index` is a 32 bit value, so we must zero-extend it to 64 bits before
8803 // adding it on to `rdata`.
8804 #ifdef JS_64BIT
8805 masm.move32To64ZeroExtend(index, widenI32(index));
8806 #endif
8807 }
8808 masm.addPtr(index, rdata);
8809 // `index` is not used after this point.
8810
8811 // 3: index rp rdata
8812 // index is now (more or less) meaningless
8813 // rdata now points exactly at the start of the fill area
8814 // rp points at the array object
8815
8816 // Drop `index`; we no longer need it.
8817 freeI32(index);
8818 index = RegI32::Invalid();
8819 // 2: rp rdata
8820
8821 // Re-re-set-up the instance pointer; we had to ditch it earlier.
8822 #ifdef RABALDR_PIN_INSTANCE
8823 instancePtr = RegPtr(InstanceReg);
8824 #else
8825 instancePtr = needPtr();
8826 fr.loadInstancePtr(instancePtr);
8827 #endif
8828 // 3: rp rdata instancePtr
8829
8830 // And reload numElements.
8831 #ifdef RABALDR_PIN_INSTANCE
8832 numElements = needI32();
8833 unstashWord(instancePtr, 0, RegPtr(numElements));
8834 instancePtr = RegPtr::Invalid();
8835 #else
8836 numElements = RegI32(instancePtr);
8837 unstashWord(instancePtr, 0, RegPtr(numElements));
8838 instancePtr = RegPtr::Invalid();
8839 #endif
8840 // 3: numElements rp rdata
8841
8842 // Free the barrier reg after we've allocated all registers
8843 if (elementType.isRefRepr()) {
8844 freePtr(RegPtr(PreBarrierReg));
8845 }
8846
8847 sync();
8848
8849 // Perform the fill loop using `numElements` as the loop variable, counting
8850 // down to zero.
8851 Label done;
8852 Label loop;
8853 masm.branch32(Assembler::Equal, numElements, Imm32(0), &done);
8854
8855 masm.bind(&loop);
8856 masm.sub32(Imm32(1), numElements);
8857
8858 // Assign value to rdata[numElements]. All registers are preserved.
8859 if (!emitGcArraySet(rp, rdata, numElements, arrayType, value,
8860 PreBarrierKind::Normal)) {
8861 return false;
8862 }
8863
8864 masm.branch32(Assembler::NotEqual, numElements, Imm32(0), &loop);
8865 masm.bind(&done);
8866
8867 // Clean up
8868 freePtr(rdata);
8869 freeRef(rp);
8870 freeI32(numElements);
8871 freeAny(value);
8872 MOZ_ASSERT(index == RegPtr::Invalid());
8873 MOZ_ASSERT(instancePtr == RegPtr::Invalid());
8874 MOZ_ASSERT(arrayNumElements == RegI32::Invalid());
8875
8876 return true;
8877 }
8878
8879 bool BaseCompiler::emitRefI31() {
8880 Nothing value;
8881 if (!iter_.readConversion(ValType::I32,
8882 ValType(RefType::i31().asNonNullable()), &value)) {
8883 return false;
8884 }
8885
8886 if (deadCode_) {
8887 return true;
8888 }
8889
8890 RegI32 intValue = popI32();
8891 RegRef i31Value = needRef();
8892 masm.truncate32ToWasmI31Ref(intValue, i31Value);
8893 freeI32(intValue);
8894 pushRef(i31Value);
8895 return true;
8896 }
8897
8898 bool BaseCompiler::emitI31Get(FieldWideningOp wideningOp) {
8899 MOZ_ASSERT(wideningOp != FieldWideningOp::None);
8900
8901 Nothing value;
8902 if (!iter_.readConversion(ValType(RefType::i31()), ValType::I32, &value)) {
8903 return false;
8904 }
8905
8906 if (deadCode_) {
8907 return true;
8908 }
8909
8910 RegRef i31Value = popRef();
8911 RegI32 intValue = needI32();
8912
8913 Label success;
8914 masm.branchWasmAnyRefIsNull(false, i31Value, &success);
8915 trap(Trap::NullPointerDereference);
8916 masm.bind(&success);
8917
8918 if (wideningOp == FieldWideningOp::Signed) {
8919 masm.convertWasmI31RefTo32Signed(i31Value, intValue);
8920 } else {
8921 masm.convertWasmI31RefTo32Unsigned(i31Value, intValue);
8922 }
8923 freeRef(i31Value);
8924 pushI32(intValue);
8925 return true;
8926 }
8927
8928 BranchIfRefSubtypeRegisters BaseCompiler::allocRegistersForBranchIfRefSubtype(
8929 RefType destType) {
8930 BranchWasmRefIsSubtypeRegisters needs =
8931 MacroAssembler::regsForBranchWasmRefIsSubtype(destType);
8932 return BranchIfRefSubtypeRegisters{
8933 .superSTV = needs.needSuperSTV
8934 ? loadSuperTypeVector(
8935 codeMeta_.types->indexOf(*destType.typeDef()))
8936 : RegPtr::Invalid(),
8937 .scratch1 = needs.needScratch1 ? needI32() : RegI32::Invalid(),
8938 .scratch2 = needs.needScratch2 ? needI32() : RegI32::Invalid(),
8939 };
8940 }
8941
8942 void BaseCompiler::freeRegistersForBranchIfRefSubtype(
8943 const BranchIfRefSubtypeRegisters& regs) {
8944 if (regs.superSTV.isValid()) {
8945 freePtr(regs.superSTV);
8946 }
8947 if (regs.scratch1.isValid()) {
8948 freeI32(regs.scratch1);
8949 }
8950 if (regs.scratch2.isValid()) {
8951 freeI32(regs.scratch2);
8952 }
8953 }
8954
8955 bool BaseCompiler::emitRefTest(bool nullable) {
8956 Nothing nothing;
8957 RefType sourceType;
8958 RefType destType;
8959 if (!iter_.readRefTest(nullable, &sourceType, &destType, &nothing)) {
8960 return false;
8961 }
8962
8963 if (deadCode_) {
8964 return true;
8965 }
8966
8967 Label success;
8968 Label join;
8969 RegRef ref = popRef();
8970 RegI32 result = needI32();
8971
8972 BranchIfRefSubtypeRegisters regs =
8973 allocRegistersForBranchIfRefSubtype(destType);
8974 masm.branchWasmRefIsSubtype(ref, MaybeRefType(sourceType), destType, &success,
8975 /*onSuccess=*/true, regs.superSTV, regs.scratch1,
8976 regs.scratch2);
8977 freeRegistersForBranchIfRefSubtype(regs);
8978
8979 masm.xor32(result, result);
8980 masm.jump(&join);
8981 masm.bind(&success);
8982 masm.move32(Imm32(1), result);
8983 masm.bind(&join);
8984
8985 pushI32(result);
8986 freeRef(ref);
8987
8988 return true;
8989 }
8990
8991 bool BaseCompiler::emitRefCast(bool nullable) {
8992 Nothing nothing;
8993 RefType sourceType;
8994 RefType destType;
8995 if (!iter_.readRefCast(nullable, &sourceType, &destType, &nothing)) {
8996 return false;
8997 }
8998
8999 if (deadCode_) {
9000 return true;
9001 }
9002
9003 RegRef ref = popRef();
9004
9005 Label success;
9006 BranchIfRefSubtypeRegisters regs =
9007 allocRegistersForBranchIfRefSubtype(destType);
9008 masm.branchWasmRefIsSubtype(ref, MaybeRefType(sourceType), destType, &success,
9009 /*onSuccess=*/true, regs.superSTV, regs.scratch1,
9010 regs.scratch2);
9011 freeRegistersForBranchIfRefSubtype(regs);
9012
9013 trap(Trap::BadCast);
9014 masm.bind(&success);
9015 pushRef(ref);
9016
9017 return true;
9018 }
9019
9020 bool BaseCompiler::emitBrOnCastCommon(bool onSuccess,
9021 uint32_t labelRelativeDepth,
9022 const ResultType& labelType,
9023 MaybeRefType sourceType,
9024 RefType destType) {
9025 Control& target = controlItem(labelRelativeDepth);
9026 target.bceSafeOnExit &= bceSafe_;
9027
9028 // 3. br_if $l : [T*, ref] -> [T*, ref]
9029 BranchState b(&target.label, target.stackHeight, InvertBranch(false),
9030 labelType);
9031
9032 // Don't allocate the result register used in the branch
9033 if (b.hasBlockResults()) {
9034 needIntegerResultRegisters(b.resultType);
9035 }
9036
9037 // Get the ref from the top of the stack
9038 RegRef refCondition = popRef();
9039
9040 // Create a copy of the ref for passing to the on_cast label,
9041 // the original ref is used in the condition.
9042 RegRef ref = needRef();
9043 moveRef(refCondition, ref);
9044 pushRef(ref);
9045
9046 if (b.hasBlockResults()) {
9047 freeIntegerResultRegisters(b.resultType);
9048 }
9049
9050 if (!jumpConditionalWithResults(&b, refCondition, sourceType, destType,
9051 onSuccess)) {
9052 return false;
9053 }
9054 freeRef(refCondition);
9055
9056 return true;
9057 }
9058
9059 bool BaseCompiler::emitBrOnCast(bool onSuccess) {
9060 MOZ_ASSERT(!hasLatentOp());
9061
9062 uint32_t labelRelativeDepth;
9063 RefType sourceType;
9064 RefType destType;
9065 ResultType labelType;
9066 BaseNothingVector unused_values{};
9067 if (!iter_.readBrOnCast(onSuccess, &labelRelativeDepth, &sourceType,
9068 &destType, &labelType, &unused_values)) {
9069 return false;
9070 }
9071
9072 if (deadCode_) {
9073 return true;
9074 }
9075
9076 return emitBrOnCastCommon(onSuccess, labelRelativeDepth, labelType,
9077 MaybeRefType(sourceType), destType);
9078 }
9079
9080 bool BaseCompiler::emitAnyConvertExtern() {
9081 // any.convert_extern is a no-op because anyref and extern share the same
9082 // representation
9083 Nothing nothing;
9084 return iter_.readRefConversion(RefType::extern_(), RefType::any(), &nothing);
9085 }
9086
9087 bool BaseCompiler::emitExternConvertAny() {
9088 // extern.convert_any is a no-op because anyref and extern share the same
9089 // representation
9090 Nothing nothing;
9091 return iter_.readRefConversion(RefType::any(), RefType::extern_(), &nothing);
9092 }
9093
9094 //////////////////////////////////////////////////////////////////////////////
9095 //
9096 // SIMD and Relaxed SIMD.
9097
9098 #ifdef ENABLE_WASM_SIMD
9099
9100 // Emitter trampolines used by abstracted SIMD operations. Naming here follows
9101 // the SIMD spec pretty closely.
9102
9103 static void AndV128(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9104 masm.bitwiseAndSimd128(rs, rsd);
9105 }
9106
9107 static void OrV128(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9108 masm.bitwiseOrSimd128(rs, rsd);
9109 }
9110
9111 static void XorV128(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9112 masm.bitwiseXorSimd128(rs, rsd);
9113 }
9114
9115 static void AddI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9116 masm.addInt8x16(rsd, rs, rsd);
9117 }
9118
9119 static void AddI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9120 masm.addInt16x8(rsd, rs, rsd);
9121 }
9122
9123 static void AddI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9124 masm.addInt32x4(rsd, rs, rsd);
9125 }
9126
9127 static void AddF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9128 masm.addFloat32x4(rsd, rs, rsd);
9129 }
9130
9131 static void AddI64x2(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9132 masm.addInt64x2(rsd, rs, rsd);
9133 }
9134
9135 static void AddF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9136 masm.addFloat64x2(rsd, rs, rsd);
9137 }
9138
9139 static void AddSatI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9140 masm.addSatInt8x16(rsd, rs, rsd);
9141 }
9142
9143 static void AddSatUI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9144 masm.unsignedAddSatInt8x16(rsd, rs, rsd);
9145 }
9146
9147 static void AddSatI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9148 masm.addSatInt16x8(rsd, rs, rsd);
9149 }
9150
9151 static void AddSatUI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9152 masm.unsignedAddSatInt16x8(rsd, rs, rsd);
9153 }
9154
9155 static void SubI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9156 masm.subInt8x16(rsd, rs, rsd);
9157 }
9158
9159 static void SubI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9160 masm.subInt16x8(rsd, rs, rsd);
9161 }
9162
9163 static void SubI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9164 masm.subInt32x4(rsd, rs, rsd);
9165 }
9166
9167 static void SubF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9168 masm.subFloat32x4(rsd, rs, rsd);
9169 }
9170
9171 static void SubI64x2(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9172 masm.subInt64x2(rsd, rs, rsd);
9173 }
9174
9175 static void SubF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9176 masm.subFloat64x2(rsd, rs, rsd);
9177 }
9178
9179 static void SubSatI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9180 masm.subSatInt8x16(rsd, rs, rsd);
9181 }
9182
9183 static void SubSatUI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9184 masm.unsignedSubSatInt8x16(rsd, rs, rsd);
9185 }
9186
9187 static void SubSatI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9188 masm.subSatInt16x8(rsd, rs, rsd);
9189 }
9190
9191 static void SubSatUI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9192 masm.unsignedSubSatInt16x8(rsd, rs, rsd);
9193 }
9194
9195 static void MulI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9196 masm.mulInt16x8(rsd, rs, rsd);
9197 }
9198
9199 static void MulI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9200 masm.mulInt32x4(rsd, rs, rsd);
9201 }
9202
9203 static void MulF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9204 masm.mulFloat32x4(rsd, rs, rsd);
9205 }
9206
9207 # if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
9208 static void MulI64x2(MacroAssembler& masm, RegV128 rs, RegV128 rsd,
9209 RegV128 temp) {
9210 masm.mulInt64x2(rsd, rs, rsd, temp);
9211 }
9212 # elif defined(JS_CODEGEN_ARM64)
9213 static void MulI64x2(MacroAssembler& masm, RegV128 rs, RegV128 rsd,
9214 RegV128 temp1, RegV128 temp2) {
9215 masm.mulInt64x2(rsd, rs, rsd, temp1, temp2);
9216 }
9217 # endif
9218
9219 static void MulF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9220 masm.mulFloat64x2(rsd, rs, rsd);
9221 }
9222
9223 static void DivF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9224 masm.divFloat32x4(rsd, rs, rsd);
9225 }
9226
9227 static void DivF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9228 masm.divFloat64x2(rsd, rs, rsd);
9229 }
9230
9231 # if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
9232 static void MinF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd,
9233 RegV128 temp1, RegV128 temp2) {
9234 masm.minFloat32x4(rsd, rs, rsd, temp1, temp2);
9235 }
9236
9237 static void MinF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rsd,
9238 RegV128 temp1, RegV128 temp2) {
9239 masm.minFloat64x2(rsd, rs, rsd, temp1, temp2);
9240 }
9241
9242 static void MaxF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd,
9243 RegV128 temp1, RegV128 temp2) {
9244 masm.maxFloat32x4(rsd, rs, rsd, temp1, temp2);
9245 }
9246
9247 static void MaxF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rsd,
9248 RegV128 temp1, RegV128 temp2) {
9249 masm.maxFloat64x2(rsd, rs, rsd, temp1, temp2);
9250 }
9251
9252 static void PMinF32x4(MacroAssembler& masm, RegV128 rsd, RegV128 rs,
9253 RhsDestOp) {
9254 masm.pseudoMinFloat32x4(rsd, rs);
9255 }
9256
9257 static void PMinF64x2(MacroAssembler& masm, RegV128 rsd, RegV128 rs,
9258 RhsDestOp) {
9259 masm.pseudoMinFloat64x2(rsd, rs);
9260 }
9261
9262 static void PMaxF32x4(MacroAssembler& masm, RegV128 rsd, RegV128 rs,
9263 RhsDestOp) {
9264 masm.pseudoMaxFloat32x4(rsd, rs);
9265 }
9266
9267 static void PMaxF64x2(MacroAssembler& masm, RegV128 rsd, RegV128 rs,
9268 RhsDestOp) {
9269 masm.pseudoMaxFloat64x2(rsd, rs);
9270 }
9271 # elif defined(JS_CODEGEN_ARM64)
9272 static void MinF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9273 masm.minFloat32x4(rs, rsd);
9274 }
9275
9276 static void MinF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9277 masm.minFloat64x2(rs, rsd);
9278 }
9279
9280 static void MaxF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9281 masm.maxFloat32x4(rs, rsd);
9282 }
9283
9284 static void MaxF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9285 masm.maxFloat64x2(rs, rsd);
9286 }
9287
9288 static void PMinF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9289 masm.pseudoMinFloat32x4(rs, rsd);
9290 }
9291
9292 static void PMinF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9293 masm.pseudoMinFloat64x2(rs, rsd);
9294 }
9295
9296 static void PMaxF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9297 masm.pseudoMaxFloat32x4(rs, rsd);
9298 }
9299
9300 static void PMaxF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9301 masm.pseudoMaxFloat64x2(rs, rsd);
9302 }
9303 # endif
9304
9305 static void DotI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9306 masm.widenDotInt16x8(rsd, rs, rsd);
9307 }
9308
9309 static void ExtMulLowI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9310 masm.extMulLowInt8x16(rsd, rs, rsd);
9311 }
9312
9313 static void ExtMulHighI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9314 masm.extMulHighInt8x16(rsd, rs, rsd);
9315 }
9316
9317 static void ExtMulLowUI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9318 masm.unsignedExtMulLowInt8x16(rsd, rs, rsd);
9319 }
9320
9321 static void ExtMulHighUI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9322 masm.unsignedExtMulHighInt8x16(rsd, rs, rsd);
9323 }
9324
9325 static void ExtMulLowI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9326 masm.extMulLowInt16x8(rsd, rs, rsd);
9327 }
9328
9329 static void ExtMulHighI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9330 masm.extMulHighInt16x8(rsd, rs, rsd);
9331 }
9332
9333 static void ExtMulLowUI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9334 masm.unsignedExtMulLowInt16x8(rsd, rs, rsd);
9335 }
9336
9337 static void ExtMulHighUI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9338 masm.unsignedExtMulHighInt16x8(rsd, rs, rsd);
9339 }
9340
9341 static void ExtMulLowI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9342 masm.extMulLowInt32x4(rsd, rs, rsd);
9343 }
9344
9345 static void ExtMulHighI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9346 masm.extMulHighInt32x4(rsd, rs, rsd);
9347 }
9348
9349 static void ExtMulLowUI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9350 masm.unsignedExtMulLowInt32x4(rsd, rs, rsd);
9351 }
9352
9353 static void ExtMulHighUI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9354 masm.unsignedExtMulHighInt32x4(rsd, rs, rsd);
9355 }
9356
9357 static void Q15MulrSatS(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9358 masm.q15MulrSatInt16x8(rsd, rs, rsd);
9359 }
9360
9361 static void CmpI8x16(MacroAssembler& masm, Assembler::Condition cond,
9362 RegV128 rs, RegV128 rsd) {
9363 masm.compareInt8x16(cond, rs, rsd);
9364 }
9365
9366 static void CmpI16x8(MacroAssembler& masm, Assembler::Condition cond,
9367 RegV128 rs, RegV128 rsd) {
9368 masm.compareInt16x8(cond, rs, rsd);
9369 }
9370
9371 static void CmpI32x4(MacroAssembler& masm, Assembler::Condition cond,
9372 RegV128 rs, RegV128 rsd) {
9373 masm.compareInt32x4(cond, rs, rsd);
9374 }
9375
9376 # if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
9377 static void CmpI64x2ForEquality(MacroAssembler& masm, Assembler::Condition cond,
9378 RegV128 rs, RegV128 rsd) {
9379 masm.compareForEqualityInt64x2(cond, rsd, rs, rsd);
9380 }
9381
9382 static void CmpI64x2ForOrdering(MacroAssembler& masm, Assembler::Condition cond,
9383 RegV128 rs, RegV128 rsd, RegV128 temp1,
9384 RegV128 temp2) {
9385 masm.compareForOrderingInt64x2(cond, rsd, rs, rsd, temp1, temp2);
9386 }
9387 # else
9388 static void CmpI64x2ForEquality(MacroAssembler& masm, Assembler::Condition cond,
9389 RegV128 rs, RegV128 rsd) {
9390 masm.compareInt64x2(cond, rs, rsd);
9391 }
9392
9393 static void CmpI64x2ForOrdering(MacroAssembler& masm, Assembler::Condition cond,
9394 RegV128 rs, RegV128 rsd) {
9395 masm.compareInt64x2(cond, rs, rsd);
9396 }
9397 # endif // JS_CODEGEN_X86 || JS_CODEGEN_X64
9398
9399 static void CmpUI8x16(MacroAssembler& masm, Assembler::Condition cond,
9400 RegV128 rs, RegV128 rsd) {
9401 masm.compareInt8x16(cond, rs, rsd);
9402 }
9403
9404 static void CmpUI16x8(MacroAssembler& masm, Assembler::Condition cond,
9405 RegV128 rs, RegV128 rsd) {
9406 masm.compareInt16x8(cond, rs, rsd);
9407 }
9408
9409 static void CmpUI32x4(MacroAssembler& masm, Assembler::Condition cond,
9410 RegV128 rs, RegV128 rsd) {
9411 masm.compareInt32x4(cond, rs, rsd);
9412 }
9413
9414 static void CmpF32x4(MacroAssembler& masm, Assembler::Condition cond,
9415 RegV128 rs, RegV128 rsd) {
9416 masm.compareFloat32x4(cond, rs, rsd);
9417 }
9418
9419 static void CmpF64x2(MacroAssembler& masm, Assembler::Condition cond,
9420 RegV128 rs, RegV128 rsd) {
9421 masm.compareFloat64x2(cond, rs, rsd);
9422 }
9423
9424 static void NegI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9425 masm.negInt8x16(rs, rd);
9426 }
9427
9428 static void NegI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9429 masm.negInt16x8(rs, rd);
9430 }
9431
9432 static void NegI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9433 masm.negInt32x4(rs, rd);
9434 }
9435
9436 static void NegI64x2(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9437 masm.negInt64x2(rs, rd);
9438 }
9439
9440 static void NegF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9441 masm.negFloat32x4(rs, rd);
9442 }
9443
9444 static void NegF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9445 masm.negFloat64x2(rs, rd);
9446 }
9447
9448 static void AbsF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9449 masm.absFloat32x4(rs, rd);
9450 }
9451
9452 static void AbsF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9453 masm.absFloat64x2(rs, rd);
9454 }
9455
9456 static void SqrtF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9457 masm.sqrtFloat32x4(rs, rd);
9458 }
9459
9460 static void SqrtF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9461 masm.sqrtFloat64x2(rs, rd);
9462 }
9463
9464 static void CeilF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9465 masm.ceilFloat32x4(rs, rd);
9466 }
9467
9468 static void FloorF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9469 masm.floorFloat32x4(rs, rd);
9470 }
9471
9472 static void TruncF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9473 masm.truncFloat32x4(rs, rd);
9474 }
9475
9476 static void NearestF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9477 masm.nearestFloat32x4(rs, rd);
9478 }
9479
9480 static void CeilF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9481 masm.ceilFloat64x2(rs, rd);
9482 }
9483
9484 static void FloorF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9485 masm.floorFloat64x2(rs, rd);
9486 }
9487
9488 static void TruncF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9489 masm.truncFloat64x2(rs, rd);
9490 }
9491
9492 static void NearestF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9493 masm.nearestFloat64x2(rs, rd);
9494 }
9495
9496 static void NotV128(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9497 masm.bitwiseNotSimd128(rs, rd);
9498 }
9499
9500 static void ExtAddPairwiseI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9501 masm.extAddPairwiseInt8x16(rs, rsd);
9502 }
9503
9504 static void ExtAddPairwiseUI8x16(MacroAssembler& masm, RegV128 rs,
9505 RegV128 rsd) {
9506 masm.unsignedExtAddPairwiseInt8x16(rs, rsd);
9507 }
9508
9509 static void ExtAddPairwiseI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9510 masm.extAddPairwiseInt16x8(rs, rsd);
9511 }
9512
9513 static void ExtAddPairwiseUI16x8(MacroAssembler& masm, RegV128 rs,
9514 RegV128 rsd) {
9515 masm.unsignedExtAddPairwiseInt16x8(rs, rsd);
9516 }
9517
9518 static void ShiftOpMask(MacroAssembler& masm, SimdOp op, RegI32 in,
9519 RegI32 out) {
9520 int32_t maskBits;
9521
9522 masm.mov(in, out);
9523 if (MacroAssembler::MustMaskShiftCountSimd128(op, &maskBits)) {
9524 masm.and32(Imm32(maskBits), out);
9525 }
9526 }
9527
9528 # if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
9529 static void ShiftLeftI8x16(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9530 RegI32 temp1, RegV128 temp2) {
9531 ShiftOpMask(masm, SimdOp::I8x16Shl, rs, temp1);
9532 masm.leftShiftInt8x16(temp1, rsd, temp2);
9533 }
9534
9535 static void ShiftLeftI16x8(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9536 RegI32 temp) {
9537 ShiftOpMask(masm, SimdOp::I16x8Shl, rs, temp);
9538 masm.leftShiftInt16x8(temp, rsd);
9539 }
9540
9541 static void ShiftLeftI32x4(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9542 RegI32 temp) {
9543 ShiftOpMask(masm, SimdOp::I32x4Shl, rs, temp);
9544 masm.leftShiftInt32x4(temp, rsd);
9545 }
9546
9547 static void ShiftLeftI64x2(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9548 RegI32 temp) {
9549 ShiftOpMask(masm, SimdOp::I64x2Shl, rs, temp);
9550 masm.leftShiftInt64x2(temp, rsd);
9551 }
9552
9553 static void ShiftRightI8x16(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9554 RegI32 temp1, RegV128 temp2) {
9555 ShiftOpMask(masm, SimdOp::I8x16ShrS, rs, temp1);
9556 masm.rightShiftInt8x16(temp1, rsd, temp2);
9557 }
9558
9559 static void ShiftRightUI8x16(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9560 RegI32 temp1, RegV128 temp2) {
9561 ShiftOpMask(masm, SimdOp::I8x16ShrU, rs, temp1);
9562 masm.unsignedRightShiftInt8x16(temp1, rsd, temp2);
9563 }
9564
9565 static void ShiftRightI16x8(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9566 RegI32 temp) {
9567 ShiftOpMask(masm, SimdOp::I16x8ShrS, rs, temp);
9568 masm.rightShiftInt16x8(temp, rsd);
9569 }
9570
9571 static void ShiftRightUI16x8(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9572 RegI32 temp) {
9573 ShiftOpMask(masm, SimdOp::I16x8ShrU, rs, temp);
9574 masm.unsignedRightShiftInt16x8(temp, rsd);
9575 }
9576
9577 static void ShiftRightI32x4(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9578 RegI32 temp) {
9579 ShiftOpMask(masm, SimdOp::I32x4ShrS, rs, temp);
9580 masm.rightShiftInt32x4(temp, rsd);
9581 }
9582
9583 static void ShiftRightUI32x4(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9584 RegI32 temp) {
9585 ShiftOpMask(masm, SimdOp::I32x4ShrU, rs, temp);
9586 masm.unsignedRightShiftInt32x4(temp, rsd);
9587 }
9588
9589 static void ShiftRightUI64x2(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9590 RegI32 temp) {
9591 ShiftOpMask(masm, SimdOp::I64x2ShrU, rs, temp);
9592 masm.unsignedRightShiftInt64x2(temp, rsd);
9593 }
9594 # elif defined(JS_CODEGEN_ARM64)
9595 static void ShiftLeftI8x16(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9596 RegI32 temp) {
9597 ShiftOpMask(masm, SimdOp::I8x16Shl, rs, temp);
9598 masm.leftShiftInt8x16(rsd, temp, rsd);
9599 }
9600
9601 static void ShiftLeftI16x8(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9602 RegI32 temp) {
9603 ShiftOpMask(masm, SimdOp::I16x8Shl, rs, temp);
9604 masm.leftShiftInt16x8(rsd, temp, rsd);
9605 }
9606
9607 static void ShiftLeftI32x4(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9608 RegI32 temp) {
9609 ShiftOpMask(masm, SimdOp::I32x4Shl, rs, temp);
9610 masm.leftShiftInt32x4(rsd, temp, rsd);
9611 }
9612
9613 static void ShiftLeftI64x2(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9614 RegI32 temp) {
9615 ShiftOpMask(masm, SimdOp::I64x2Shl, rs, temp);
9616 masm.leftShiftInt64x2(rsd, temp, rsd);
9617 }
9618
9619 static void ShiftRightI8x16(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9620 RegI32 temp) {
9621 ShiftOpMask(masm, SimdOp::I8x16ShrS, rs, temp);
9622 masm.rightShiftInt8x16(rsd, temp, rsd);
9623 }
9624
9625 static void ShiftRightUI8x16(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9626 RegI32 temp) {
9627 ShiftOpMask(masm, SimdOp::I8x16ShrU, rs, temp);
9628 masm.unsignedRightShiftInt8x16(rsd, temp, rsd);
9629 }
9630
9631 static void ShiftRightI16x8(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9632 RegI32 temp) {
9633 ShiftOpMask(masm, SimdOp::I16x8ShrS, rs, temp);
9634 masm.rightShiftInt16x8(rsd, temp, rsd);
9635 }
9636
9637 static void ShiftRightUI16x8(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9638 RegI32 temp) {
9639 ShiftOpMask(masm, SimdOp::I16x8ShrU, rs, temp);
9640 masm.unsignedRightShiftInt16x8(rsd, temp, rsd);
9641 }
9642
9643 static void ShiftRightI32x4(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9644 RegI32 temp) {
9645 ShiftOpMask(masm, SimdOp::I32x4ShrS, rs, temp);
9646 masm.rightShiftInt32x4(rsd, temp, rsd);
9647 }
9648
9649 static void ShiftRightUI32x4(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9650 RegI32 temp) {
9651 ShiftOpMask(masm, SimdOp::I32x4ShrU, rs, temp);
9652 masm.unsignedRightShiftInt32x4(rsd, temp, rsd);
9653 }
9654
9655 static void ShiftRightI64x2(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9656 RegI32 temp) {
9657 ShiftOpMask(masm, SimdOp::I64x2ShrS, rs, temp);
9658 masm.rightShiftInt64x2(rsd, temp, rsd);
9659 }
9660
9661 static void ShiftRightUI64x2(MacroAssembler& masm, RegI32 rs, RegV128 rsd,
9662 RegI32 temp) {
9663 ShiftOpMask(masm, SimdOp::I64x2ShrU, rs, temp);
9664 masm.unsignedRightShiftInt64x2(rsd, temp, rsd);
9665 }
9666 # endif
9667
9668 static void AverageUI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9669 masm.unsignedAverageInt8x16(rsd, rs, rsd);
9670 }
9671
9672 static void AverageUI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9673 masm.unsignedAverageInt16x8(rsd, rs, rsd);
9674 }
9675
9676 static void MinI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9677 masm.minInt8x16(rsd, rs, rsd);
9678 }
9679
9680 static void MinUI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9681 masm.unsignedMinInt8x16(rsd, rs, rsd);
9682 }
9683
9684 static void MaxI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9685 masm.maxInt8x16(rsd, rs, rsd);
9686 }
9687
9688 static void MaxUI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9689 masm.unsignedMaxInt8x16(rsd, rs, rsd);
9690 }
9691
9692 static void MinI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9693 masm.minInt16x8(rsd, rs, rsd);
9694 }
9695
9696 static void MinUI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9697 masm.unsignedMinInt16x8(rsd, rs, rsd);
9698 }
9699
9700 static void MaxI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9701 masm.maxInt16x8(rsd, rs, rsd);
9702 }
9703
9704 static void MaxUI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9705 masm.unsignedMaxInt16x8(rsd, rs, rsd);
9706 }
9707
9708 static void MinI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9709 masm.minInt32x4(rsd, rs, rsd);
9710 }
9711
9712 static void MinUI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9713 masm.unsignedMinInt32x4(rsd, rs, rsd);
9714 }
9715
9716 static void MaxI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9717 masm.maxInt32x4(rsd, rs, rsd);
9718 }
9719
9720 static void MaxUI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9721 masm.unsignedMaxInt32x4(rsd, rs, rsd);
9722 }
9723
9724 static void NarrowI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9725 masm.narrowInt16x8(rsd, rs, rsd);
9726 }
9727
9728 static void NarrowUI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9729 masm.unsignedNarrowInt16x8(rsd, rs, rsd);
9730 }
9731
9732 static void NarrowI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9733 masm.narrowInt32x4(rsd, rs, rsd);
9734 }
9735
9736 static void NarrowUI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9737 masm.unsignedNarrowInt32x4(rsd, rs, rsd);
9738 }
9739
9740 static void WidenLowI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9741 masm.widenLowInt8x16(rs, rd);
9742 }
9743
9744 static void WidenHighI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9745 masm.widenHighInt8x16(rs, rd);
9746 }
9747
9748 static void WidenLowUI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9749 masm.unsignedWidenLowInt8x16(rs, rd);
9750 }
9751
9752 static void WidenHighUI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9753 masm.unsignedWidenHighInt8x16(rs, rd);
9754 }
9755
9756 static void WidenLowI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9757 masm.widenLowInt16x8(rs, rd);
9758 }
9759
9760 static void WidenHighI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9761 masm.widenHighInt16x8(rs, rd);
9762 }
9763
9764 static void WidenLowUI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9765 masm.unsignedWidenLowInt16x8(rs, rd);
9766 }
9767
9768 static void WidenHighUI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9769 masm.unsignedWidenHighInt16x8(rs, rd);
9770 }
9771
9772 static void WidenLowI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9773 masm.widenLowInt32x4(rs, rd);
9774 }
9775
9776 static void WidenHighI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9777 masm.widenHighInt32x4(rs, rd);
9778 }
9779
9780 static void WidenLowUI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9781 masm.unsignedWidenLowInt32x4(rs, rd);
9782 }
9783
9784 static void WidenHighUI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9785 masm.unsignedWidenHighInt32x4(rs, rd);
9786 }
9787
9788 # if defined(JS_CODEGEN_ARM64)
9789 static void PopcntI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9790 masm.popcntInt8x16(rs, rd);
9791 }
9792 # else
9793 static void PopcntI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rd,
9794 RegV128 temp) {
9795 masm.popcntInt8x16(rs, rd, temp);
9796 }
9797 # endif // JS_CODEGEN_ARM64
9798
9799 static void AbsI8x16(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9800 masm.absInt8x16(rs, rd);
9801 }
9802
9803 static void AbsI16x8(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9804 masm.absInt16x8(rs, rd);
9805 }
9806
9807 static void AbsI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9808 masm.absInt32x4(rs, rd);
9809 }
9810
9811 static void AbsI64x2(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9812 masm.absInt64x2(rs, rd);
9813 }
9814
9815 static void ExtractLaneI8x16(MacroAssembler& masm, uint32_t laneIndex,
9816 RegV128 rs, RegI32 rd) {
9817 masm.extractLaneInt8x16(laneIndex, rs, rd);
9818 }
9819
9820 static void ExtractLaneUI8x16(MacroAssembler& masm, uint32_t laneIndex,
9821 RegV128 rs, RegI32 rd) {
9822 masm.unsignedExtractLaneInt8x16(laneIndex, rs, rd);
9823 }
9824
9825 static void ExtractLaneI16x8(MacroAssembler& masm, uint32_t laneIndex,
9826 RegV128 rs, RegI32 rd) {
9827 masm.extractLaneInt16x8(laneIndex, rs, rd);
9828 }
9829
9830 static void ExtractLaneUI16x8(MacroAssembler& masm, uint32_t laneIndex,
9831 RegV128 rs, RegI32 rd) {
9832 masm.unsignedExtractLaneInt16x8(laneIndex, rs, rd);
9833 }
9834
9835 static void ExtractLaneI32x4(MacroAssembler& masm, uint32_t laneIndex,
9836 RegV128 rs, RegI32 rd) {
9837 masm.extractLaneInt32x4(laneIndex, rs, rd);
9838 }
9839
9840 static void ExtractLaneI64x2(MacroAssembler& masm, uint32_t laneIndex,
9841 RegV128 rs, RegI64 rd) {
9842 masm.extractLaneInt64x2(laneIndex, rs, rd);
9843 }
9844
9845 static void ExtractLaneF32x4(MacroAssembler& masm, uint32_t laneIndex,
9846 RegV128 rs, RegF32 rd) {
9847 masm.extractLaneFloat32x4(laneIndex, rs, rd);
9848 }
9849
9850 static void ExtractLaneF64x2(MacroAssembler& masm, uint32_t laneIndex,
9851 RegV128 rs, RegF64 rd) {
9852 masm.extractLaneFloat64x2(laneIndex, rs, rd);
9853 }
9854
9855 static void ReplaceLaneI8x16(MacroAssembler& masm, uint32_t laneIndex,
9856 RegI32 rs, RegV128 rsd) {
9857 masm.replaceLaneInt8x16(laneIndex, rs, rsd);
9858 }
9859
9860 static void ReplaceLaneI16x8(MacroAssembler& masm, uint32_t laneIndex,
9861 RegI32 rs, RegV128 rsd) {
9862 masm.replaceLaneInt16x8(laneIndex, rs, rsd);
9863 }
9864
9865 static void ReplaceLaneI32x4(MacroAssembler& masm, uint32_t laneIndex,
9866 RegI32 rs, RegV128 rsd) {
9867 masm.replaceLaneInt32x4(laneIndex, rs, rsd);
9868 }
9869
9870 static void ReplaceLaneI64x2(MacroAssembler& masm, uint32_t laneIndex,
9871 RegI64 rs, RegV128 rsd) {
9872 masm.replaceLaneInt64x2(laneIndex, rs, rsd);
9873 }
9874
9875 static void ReplaceLaneF32x4(MacroAssembler& masm, uint32_t laneIndex,
9876 RegF32 rs, RegV128 rsd) {
9877 masm.replaceLaneFloat32x4(laneIndex, rs, rsd);
9878 }
9879
9880 static void ReplaceLaneF64x2(MacroAssembler& masm, uint32_t laneIndex,
9881 RegF64 rs, RegV128 rsd) {
9882 masm.replaceLaneFloat64x2(laneIndex, rs, rsd);
9883 }
9884
9885 static void SplatI8x16(MacroAssembler& masm, RegI32 rs, RegV128 rd) {
9886 masm.splatX16(rs, rd);
9887 }
9888
9889 static void SplatI16x8(MacroAssembler& masm, RegI32 rs, RegV128 rd) {
9890 masm.splatX8(rs, rd);
9891 }
9892
9893 static void SplatI32x4(MacroAssembler& masm, RegI32 rs, RegV128 rd) {
9894 masm.splatX4(rs, rd);
9895 }
9896
9897 static void SplatI64x2(MacroAssembler& masm, RegI64 rs, RegV128 rd) {
9898 masm.splatX2(rs, rd);
9899 }
9900
9901 static void SplatF32x4(MacroAssembler& masm, RegF32 rs, RegV128 rd) {
9902 masm.splatX4(rs, rd);
9903 }
9904
9905 static void SplatF64x2(MacroAssembler& masm, RegF64 rs, RegV128 rd) {
9906 masm.splatX2(rs, rd);
9907 }
9908
9909 // This is the same op independent of lanes: it tests for any nonzero bit.
9910 static void AnyTrue(MacroAssembler& masm, RegV128 rs, RegI32 rd) {
9911 masm.anyTrueSimd128(rs, rd);
9912 }
9913
9914 static void AllTrueI8x16(MacroAssembler& masm, RegV128 rs, RegI32 rd) {
9915 masm.allTrueInt8x16(rs, rd);
9916 }
9917
9918 static void AllTrueI16x8(MacroAssembler& masm, RegV128 rs, RegI32 rd) {
9919 masm.allTrueInt16x8(rs, rd);
9920 }
9921
9922 static void AllTrueI32x4(MacroAssembler& masm, RegV128 rs, RegI32 rd) {
9923 masm.allTrueInt32x4(rs, rd);
9924 }
9925
9926 static void AllTrueI64x2(MacroAssembler& masm, RegV128 rs, RegI32 rd) {
9927 masm.allTrueInt64x2(rs, rd);
9928 }
9929
9930 # if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
9931 static void BitmaskI8x16(MacroAssembler& masm, RegV128 rs, RegI32 rd) {
9932 masm.bitmaskInt8x16(rs, rd);
9933 }
9934
9935 static void BitmaskI16x8(MacroAssembler& masm, RegV128 rs, RegI32 rd) {
9936 masm.bitmaskInt16x8(rs, rd);
9937 }
9938
9939 static void BitmaskI32x4(MacroAssembler& masm, RegV128 rs, RegI32 rd) {
9940 masm.bitmaskInt32x4(rs, rd);
9941 }
9942
9943 static void BitmaskI64x2(MacroAssembler& masm, RegV128 rs, RegI32 rd) {
9944 masm.bitmaskInt64x2(rs, rd);
9945 }
9946 # elif defined(JS_CODEGEN_ARM64)
9947 static void BitmaskI8x16(MacroAssembler& masm, RegV128 rs, RegI32 rd,
9948 RegV128 temp) {
9949 masm.bitmaskInt8x16(rs, rd, temp);
9950 }
9951
9952 static void BitmaskI16x8(MacroAssembler& masm, RegV128 rs, RegI32 rd,
9953 RegV128 temp) {
9954 masm.bitmaskInt16x8(rs, rd, temp);
9955 }
9956
9957 static void BitmaskI32x4(MacroAssembler& masm, RegV128 rs, RegI32 rd,
9958 RegV128 temp) {
9959 masm.bitmaskInt32x4(rs, rd, temp);
9960 }
9961
9962 static void BitmaskI64x2(MacroAssembler& masm, RegV128 rs, RegI32 rd,
9963 RegV128 temp) {
9964 masm.bitmaskInt64x2(rs, rd, temp);
9965 }
9966 # endif
9967
9968 static void Swizzle(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
9969 masm.swizzleInt8x16(rsd, rs, rsd);
9970 }
9971
9972 static void ConvertI32x4ToF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9973 masm.convertInt32x4ToFloat32x4(rs, rd);
9974 }
9975
9976 static void ConvertUI32x4ToF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9977 masm.unsignedConvertInt32x4ToFloat32x4(rs, rd);
9978 }
9979
9980 static void ConvertF32x4ToI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9981 masm.truncSatFloat32x4ToInt32x4(rs, rd);
9982 }
9983
9984 # if defined(JS_CODEGEN_ARM64)
9985 static void ConvertF32x4ToUI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9986 masm.unsignedTruncSatFloat32x4ToInt32x4(rs, rd);
9987 }
9988 # else
9989 static void ConvertF32x4ToUI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd,
9990 RegV128 temp) {
9991 masm.unsignedTruncSatFloat32x4ToInt32x4(rs, rd, temp);
9992 }
9993 # endif // JS_CODEGEN_ARM64
9994
9995 static void ConvertI32x4ToF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
9996 masm.convertInt32x4ToFloat64x2(rs, rd);
9997 }
9998
9999 static void ConvertUI32x4ToF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
10000 masm.unsignedConvertInt32x4ToFloat64x2(rs, rd);
10001 }
10002
10003 static void ConvertF64x2ToI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd,
10004 RegV128 temp) {
10005 masm.truncSatFloat64x2ToInt32x4(rs, rd, temp);
10006 }
10007
10008 static void ConvertF64x2ToUI32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd,
10009 RegV128 temp) {
10010 masm.unsignedTruncSatFloat64x2ToInt32x4(rs, rd, temp);
10011 }
10012
10013 static void DemoteF64x2ToF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
10014 masm.convertFloat64x2ToFloat32x4(rs, rd);
10015 }
10016
10017 static void PromoteF32x4ToF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rd) {
10018 masm.convertFloat32x4ToFloat64x2(rs, rd);
10019 }
10020
10021 # if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
10022 static void BitselectV128(MacroAssembler& masm, RegV128 rhs, RegV128 control,
10023 RegV128 lhsDest, RegV128 temp) {
10024 // Ideally, we would have temp=control, and we can probably get away with
10025 // just doing that, but don't worry about it yet.
10026 masm.bitwiseSelectSimd128(control, lhsDest, rhs, lhsDest, temp);
10027 }
10028 # elif defined(JS_CODEGEN_ARM64)
10029 static void BitselectV128(MacroAssembler& masm, RegV128 rhs, RegV128 control,
10030 RegV128 lhsDest, RegV128 temp) {
10031 // The masm interface is not great for the baseline compiler here, but it's
10032 // optimal for Ion, so just work around it.
10033 masm.moveSimd128(control, temp);
10034 masm.bitwiseSelectSimd128(lhsDest, rhs, temp);
10035 masm.moveSimd128(temp, lhsDest);
10036 }
10037 # endif
10038
10039 # ifdef ENABLE_WASM_RELAXED_SIMD
10040 static void RelaxedMaddF32x4(MacroAssembler& masm, RegV128 rs1, RegV128 rs2,
10041 RegV128 rsd) {
10042 masm.fmaFloat32x4(rs1, rs2, rsd);
10043 }
10044
10045 static void RelaxedNmaddF32x4(MacroAssembler& masm, RegV128 rs1, RegV128 rs2,
10046 RegV128 rsd) {
10047 masm.fnmaFloat32x4(rs1, rs2, rsd);
10048 }
10049
10050 static void RelaxedMaddF64x2(MacroAssembler& masm, RegV128 rs1, RegV128 rs2,
10051 RegV128 rsd) {
10052 masm.fmaFloat64x2(rs1, rs2, rsd);
10053 }
10054
10055 static void RelaxedNmaddF64x2(MacroAssembler& masm, RegV128 rs1, RegV128 rs2,
10056 RegV128 rsd) {
10057 masm.fnmaFloat64x2(rs1, rs2, rsd);
10058 }
10059
10060 static void RelaxedSwizzle(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
10061 masm.swizzleInt8x16Relaxed(rsd, rs, rsd);
10062 }
10063
10064 static void RelaxedMinF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
10065 masm.minFloat32x4Relaxed(rs, rsd);
10066 }
10067
10068 static void RelaxedMaxF32x4(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
10069 masm.maxFloat32x4Relaxed(rs, rsd);
10070 }
10071
10072 static void RelaxedMinF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
10073 masm.minFloat64x2Relaxed(rs, rsd);
10074 }
10075
10076 static void RelaxedMaxF64x2(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
10077 masm.maxFloat64x2Relaxed(rs, rsd);
10078 }
10079
10080 static void RelaxedConvertF32x4ToI32x4(MacroAssembler& masm, RegV128 rs,
10081 RegV128 rd) {
10082 masm.truncFloat32x4ToInt32x4Relaxed(rs, rd);
10083 }
10084
10085 static void RelaxedConvertF32x4ToUI32x4(MacroAssembler& masm, RegV128 rs,
10086 RegV128 rd) {
10087 masm.unsignedTruncFloat32x4ToInt32x4Relaxed(rs, rd);
10088 }
10089
10090 static void RelaxedConvertF64x2ToI32x4(MacroAssembler& masm, RegV128 rs,
10091 RegV128 rd) {
10092 masm.truncFloat64x2ToInt32x4Relaxed(rs, rd);
10093 }
10094
10095 static void RelaxedConvertF64x2ToUI32x4(MacroAssembler& masm, RegV128 rs,
10096 RegV128 rd) {
10097 masm.unsignedTruncFloat64x2ToInt32x4Relaxed(rs, rd);
10098 }
10099
10100 static void RelaxedQ15MulrS(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
10101 masm.q15MulrInt16x8Relaxed(rsd, rs, rsd);
10102 }
10103
10104 static void DotI8x16I7x16S(MacroAssembler& masm, RegV128 rs, RegV128 rsd) {
10105 masm.dotInt8x16Int7x16(rsd, rs, rsd);
10106 }
10107
10108 void BaseCompiler::emitDotI8x16I7x16AddS() {
10109 RegV128 rsd = popV128();
10110 RegV128 rs0, rs1;
10111 pop2xV128(&rs0, &rs1);
10112 # if defined(JS_CODEGEN_ARM64)
10113 RegV128 temp = needV128();
10114 masm.dotInt8x16Int7x16ThenAdd(rs0, rs1, rsd, temp);
10115 freeV128(temp);
10116 # else
10117 masm.dotInt8x16Int7x16ThenAdd(rs0, rs1, rsd);
10118 # endif
10119 freeV128(rs1);
10120 freeV128(rs0);
10121 pushV128(rsd);
10122 }
10123 # endif // ENABLE_WASM_RELAXED_SIMD
10124
10125 void BaseCompiler::emitVectorAndNot() {
10126 // We want x & ~y but the available operation is ~x & y, so reverse the
10127 // operands.
10128 RegV128 r, rs;
10129 pop2xV128(&r, &rs);
10130 masm.bitwiseNotAndSimd128(r, rs);
10131 freeV128(r);
10132 pushV128(rs);
10133 }
10134
10135 bool BaseCompiler::emitLoadSplat(Scalar::Type viewType) {
10136 LinearMemoryAddress<Nothing> addr;
10137 if (!iter_.readLoadSplat(Scalar::byteSize(viewType), &addr)) {
10138 return false;
10139 }
10140 if (deadCode_) {
10141 return true;
10142 }
10143 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
10144 trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex));
10145 loadSplat(&access);
10146 return true;
10147 }
10148
10149 bool BaseCompiler::emitLoadZero(Scalar::Type viewType) {
10150 // LoadZero has the structure of LoadSplat, so reuse the reader.
10151 LinearMemoryAddress<Nothing> addr;
10152 if (!iter_.readLoadSplat(Scalar::byteSize(viewType), &addr)) {
10153 return false;
10154 }
10155 if (deadCode_) {
10156 return true;
10157 }
10158 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
10159 trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex));
10160 loadZero(&access);
10161 return true;
10162 }
10163
10164 bool BaseCompiler::emitLoadExtend(Scalar::Type viewType) {
10165 LinearMemoryAddress<Nothing> addr;
10166 if (!iter_.readLoadExtend(&addr)) {
10167 return false;
10168 }
10169 if (deadCode_) {
10170 return true;
10171 }
10172 MemoryAccessDesc access(addr.memoryIndex, Scalar::Int64, addr.align,
10173 addr.offset, trapSiteDesc(),
10174 hugeMemoryEnabled(addr.memoryIndex));
10175 loadExtend(&access, viewType);
10176 return true;
10177 }
10178
10179 bool BaseCompiler::emitLoadLane(uint32_t laneSize) {
10180 Nothing nothing;
10181 LinearMemoryAddress<Nothing> addr;
10182 uint32_t laneIndex;
10183 if (!iter_.readLoadLane(laneSize, &addr, &laneIndex, &nothing)) {
10184 return false;
10185 }
10186 if (deadCode_) {
10187 return true;
10188 }
10189 Scalar::Type viewType;
10190 switch (laneSize) {
10191 case 1:
10192 viewType = Scalar::Uint8;
10193 break;
10194 case 2:
10195 viewType = Scalar::Uint16;
10196 break;
10197 case 4:
10198 viewType = Scalar::Int32;
10199 break;
10200 case 8:
10201 viewType = Scalar::Int64;
10202 break;
10203 default:
10204 MOZ_CRASH("unsupported laneSize");
10205 }
10206 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
10207 trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex));
10208 loadLane(&access, laneIndex);
10209 return true;
10210 }
10211
10212 bool BaseCompiler::emitStoreLane(uint32_t laneSize) {
10213 Nothing nothing;
10214 LinearMemoryAddress<Nothing> addr;
10215 uint32_t laneIndex;
10216 if (!iter_.readStoreLane(laneSize, &addr, &laneIndex, &nothing)) {
10217 return false;
10218 }
10219 if (deadCode_) {
10220 return true;
10221 }
10222 Scalar::Type viewType;
10223 switch (laneSize) {
10224 case 1:
10225 viewType = Scalar::Uint8;
10226 break;
10227 case 2:
10228 viewType = Scalar::Uint16;
10229 break;
10230 case 4:
10231 viewType = Scalar::Int32;
10232 break;
10233 case 8:
10234 viewType = Scalar::Int64;
10235 break;
10236 default:
10237 MOZ_CRASH("unsupported laneSize");
10238 }
10239 MemoryAccessDesc access(addr.memoryIndex, viewType, addr.align, addr.offset,
10240 trapSiteDesc(), hugeMemoryEnabled(addr.memoryIndex));
10241 storeLane(&access, laneIndex);
10242 return true;
10243 }
10244
10245 bool BaseCompiler::emitVectorShuffle() {
10246 Nothing unused_a, unused_b;
10247 V128 shuffleMask;
10248
10249 if (!iter_.readVectorShuffle(&unused_a, &unused_b, &shuffleMask)) {
10250 return false;
10251 }
10252
10253 if (deadCode_) {
10254 return true;
10255 }
10256
10257 RegV128 rd, rs;
10258 pop2xV128(&rd, &rs);
10259
10260 masm.shuffleInt8x16(shuffleMask.bytes, rs, rd);
10261
10262 freeV128(rs);
10263 pushV128(rd);
10264
10265 return true;
10266 }
10267
10268 # if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
10269 bool BaseCompiler::emitVectorShiftRightI64x2() {
10270 Nothing unused_a, unused_b;
10271
10272 if (!iter_.readVectorShift(&unused_a, &unused_b)) {
10273 return false;
10274 }
10275
10276 if (deadCode_) {
10277 return true;
10278 }
10279
10280 RegI32 count = popI32RhsForShiftI64();
10281 RegV128 lhsDest = popV128();
10282 RegI64 tmp = needI64();
10283 masm.and32(Imm32(63), count);
10284 masm.extractLaneInt64x2(0, lhsDest, tmp);
10285 masm.rshift64Arithmetic(count, tmp);
10286 masm.replaceLaneInt64x2(0, tmp, lhsDest);
10287 masm.extractLaneInt64x2(1, lhsDest, tmp);
10288 masm.rshift64Arithmetic(count, tmp);
10289 masm.replaceLaneInt64x2(1, tmp, lhsDest);
10290 freeI64(tmp);
10291 freeI32(count);
10292 pushV128(lhsDest);
10293
10294 return true;
10295 }
10296 # endif
10297 #endif // ENABLE_WASM_SIMD
10298
10299 #ifdef ENABLE_WASM_RELAXED_SIMD
10300 bool BaseCompiler::emitVectorLaneSelect() {
10301 Nothing unused_a, unused_b, unused_c;
10302
10303 if (!iter_.readTernary(ValType::V128, &unused_a, &unused_b, &unused_c)) {
10304 return false;
10305 }
10306
10307 if (deadCode_) {
10308 return true;
10309 }
10310
10311 # if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
10312 RegV128 mask = popV128(RegV128(vmm0));
10313 RegV128 rhsDest = popV128();
10314 RegV128 lhs = popV128();
10315 masm.laneSelectSimd128(mask, lhs, rhsDest, rhsDest);
10316 freeV128(lhs);
10317 freeV128(mask);
10318 pushV128(rhsDest);
10319 # elif defined(JS_CODEGEN_ARM64)
10320 RegV128 maskDest = popV128();
10321 RegV128 rhs = popV128();
10322 RegV128 lhs = popV128();
10323 masm.laneSelectSimd128(maskDest, lhs, rhs, maskDest);
10324 freeV128(lhs);
10325 freeV128(rhs);
10326 pushV128(maskDest);
10327 # endif
10328
10329 return true;
10330 }
10331 #endif // ENABLE_WASM_RELAXED_SIMD
10332
10333 //////////////////////////////////////////////////////////////////////////////
10334 //
10335 // "Builtin module funcs" - magically imported functions for internal use.
10336
10337 bool BaseCompiler::emitCallBuiltinModuleFunc() {
10338 const BuiltinModuleFunc* builtinModuleFunc;
10339
10340 BaseNothingVector params;
10341 if (!iter_.readCallBuiltinModuleFunc(&builtinModuleFunc, &params)) {
10342 return false;
10343 }
10344
10345 if (deadCode_) {
10346 return true;
10347 }
10348
10349 if (builtinModuleFunc->usesMemory()) {
10350 // The final parameter of an builtinModuleFunc is implicitly the heap base
10351 pushHeapBase(0);
10352 }
10353
10354 // Call the builtinModuleFunc
10355 return emitInstanceCall(*builtinModuleFunc->sig());
10356 }
10357
10358 //////////////////////////////////////////////////////////////////////////////
10359 //
10360 // Function bodies - main opcode dispatch loop.
10361
10362 bool BaseCompiler::emitBody() {
10363 AutoCreatedBy acb(masm, "(wasm)BaseCompiler::emitBody");
10364
10365 MOZ_ASSERT(stackMapGenerator_.framePushedAtEntryToBody.isSome());
10366
10367 if (!iter_.startFunction(func_.index)) {
10368 return false;
10369 }
10370
10371 initControl(controlItem(), ResultType::Empty());
10372
10373 #ifdef JS_ION_PERF
10374 bool spewerEnabled = perfSpewer_.needsToRecordInstruction();
10375 #else
10376 bool spewerEnabled = false;
10377 #endif
10378 bool debugEnabled = compilerEnv_.debugEnabled();
10379 // Fold the debug and profiler checks into a single bool.
10380 bool hasPerInstrCheck = spewerEnabled || debugEnabled;
10381
10382 for (;;) {
10383 Nothing unused_a, unused_b, unused_c;
10384 (void)unused_a;
10385 (void)unused_b;
10386 (void)unused_c;
10387
10388 #ifdef DEBUG
10389 performRegisterLeakCheck();
10390 assertStackInvariants();
10391 #endif
10392
10393 #define dispatchBinary0(doEmit, type) \
10394 iter_.readBinary(type, &unused_a, &unused_b) && \
10395 (deadCode_ || (doEmit(), true))
10396
10397 #define dispatchBinary1(arg1, type) \
10398 iter_.readBinary(type, &unused_a, &unused_b) && \
10399 (deadCode_ || (emitBinop(arg1), true))
10400
10401 #define dispatchBinary2(arg1, arg2, type) \
10402 iter_.readBinary(type, &unused_a, &unused_b) && \
10403 (deadCode_ || (emitBinop(arg1, arg2), true))
10404
10405 #define dispatchBinary3(arg1, arg2, arg3, type) \
10406 iter_.readBinary(type, &unused_a, &unused_b) && \
10407 (deadCode_ || (emitBinop(arg1, arg2, arg3), true))
10408
10409 #define dispatchUnary0(doEmit, type) \
10410 iter_.readUnary(type, &unused_a) && (deadCode_ || (doEmit(), true))
10411
10412 #define dispatchUnary1(arg1, type) \
10413 iter_.readUnary(type, &unused_a) && (deadCode_ || (emitUnop(arg1), true))
10414
10415 #define dispatchUnary2(arg1, arg2, type) \
10416 iter_.readUnary(type, &unused_a) && \
10417 (deadCode_ || (emitUnop(arg1, arg2), true))
10418
10419 #define dispatchTernary0(doEmit, type) \
10420 iter_.readTernary(type, &unused_a, &unused_b, &unused_c) && \
10421 (deadCode_ || (doEmit(), true))
10422
10423 #define dispatchTernary1(arg1, type) \
10424 iter_.readTernary(type, &unused_a, &unused_b, &unused_c) && \
10425 (deadCode_ || (emitTernary(arg1), true))
10426
10427 #define dispatchTernary2(arg1, type) \
10428 iter_.readTernary(type, &unused_a, &unused_b, &unused_c) && \
10429 (deadCode_ || (emitTernaryResultLast(arg1), true))
10430
10431 #define dispatchComparison0(doEmit, operandType, compareOp) \
10432 iter_.readComparison(operandType, &unused_a, &unused_b) && \
10433 (deadCode_ || (doEmit(compareOp, operandType), true))
10434
10435 #define dispatchConversion0(doEmit, inType, outType) \
10436 iter_.readConversion(inType, outType, &unused_a) && \
10437 (deadCode_ || (doEmit(), true))
10438
10439 #define dispatchConversion1(arg1, inType, outType) \
10440 iter_.readConversion(inType, outType, &unused_a) && \
10441 (deadCode_ || (emitUnop(arg1), true))
10442
10443 #define dispatchConversionOOM(doEmit, inType, outType) \
10444 iter_.readConversion(inType, outType, &unused_a) && (deadCode_ || doEmit())
10445
10446 #define dispatchCalloutConversionOOM(doEmit, symbol, inType, outType) \
10447 iter_.readConversion(inType, outType, &unused_a) && \
10448 (deadCode_ || doEmit(symbol, inType, outType))
10449
10450 #define dispatchIntDivCallout(doEmit, symbol, type) \
10451 iter_.readBinary(type, &unused_a, &unused_b) && \
10452 (deadCode_ || doEmit(symbol, type))
10453
10454 #define dispatchVectorBinary(op) \
10455 iter_.readBinary(ValType::V128, &unused_a, &unused_b) && \
10456 (deadCode_ || (emitBinop(op), true))
10457
10458 #define dispatchVectorUnary(op) \
10459 iter_.readUnary(ValType::V128, &unused_a) && \
10460 (deadCode_ || (emitUnop(op), true))
10461
10462 #define dispatchVectorComparison(op, compareOp) \
10463 iter_.readBinary(ValType::V128, &unused_a, &unused_b) && \
10464 (deadCode_ || (emitBinop(compareOp, op), true))
10465
10466 #define dispatchVectorVariableShift(op) \
10467 iter_.readVectorShift(&unused_a, &unused_b) && \
10468 (deadCode_ || (emitBinop(op), true))
10469
10470 #define dispatchExtractLane(op, outType, laneLimit) \
10471 iter_.readExtractLane(outType, laneLimit, &laneIndex, &unused_a) && \
10472 (deadCode_ || (emitUnop(laneIndex, op), true))
10473
10474 #define dispatchReplaceLane(op, inType, laneLimit) \
10475 iter_.readReplaceLane(inType, laneLimit, &laneIndex, &unused_a, \
10476 &unused_b) && \
10477 (deadCode_ || (emitBinop(laneIndex, op), true))
10478
10479 #define dispatchSplat(op, inType) \
10480 iter_.readConversion(inType, ValType::V128, &unused_a) && \
10481 (deadCode_ || (emitUnop(op), true))
10482
10483 #define dispatchVectorReduction(op) \
10484 iter_.readConversion(ValType::V128, ValType::I32, &unused_a) && \
10485 (deadCode_ || (emitUnop(op), true))
10486
10487 #ifdef DEBUG
10488 // Check that the number of ref-typed entries in the operand stack matches
10489 // reality.
10490 # define CHECK_POINTER_COUNT \
10491 do { \
10492 MOZ_ASSERT(countMemRefsOnStk() == stackMapGenerator_.memRefsOnStk); \
10493 } while (0)
10494 #else
10495 # define CHECK_POINTER_COUNT \
10496 do { \
10497 } while (0)
10498 #endif
10499
10500 #define CHECK(E) \
10501 if (!(E)) return false
10502 #define NEXT() \
10503 { \
10504 CHECK_POINTER_COUNT; \
10505 continue; \
10506 }
10507 #define CHECK_NEXT(E) \
10508 if (!(E)) return false; \
10509 { \
10510 CHECK_POINTER_COUNT; \
10511 continue; \
10512 }
10513
10514 // Opcodes that push more than MaxPushesPerOpcode (anything with multiple
10515 // results) will perform additional reservation.
10516 CHECK(stk_.reserve(stk_.length() + MaxPushesPerOpcode));
10517
10518 OpBytes op{};
10519 CHECK(iter_.readOp(&op));
10520
10521 if (MOZ_UNLIKELY(hasPerInstrCheck)) {
10522 // When compilerEnv_.debugEnabled(), some operators get a breakpoint site.
10523 if (debugEnabled && op.shouldHaveBreakpoint() && !deadCode_) {
10524 if (previousBreakablePoint_ != masm.currentOffset()) {
10525 // TODO sync only registers that can be clobbered by the exit
10526 // prologue/epilogue or disable these registers for use in
10527 // baseline compiler when compilerEnv_.debugEnabled() is set.
10528 sync();
10529
10530 insertBreakablePoint(CallSiteKind::Breakpoint);
10531 if (!createStackMap("debug: per-insn breakpoint")) {
10532 return false;
10533 }
10534 previousBreakablePoint_ = masm.currentOffset();
10535 }
10536 }
10537
10538 #ifdef JS_ION_PERF
10539 if (spewerEnabled) {
10540 perfSpewer_.recordInstruction(masm, op);
10541 }
10542 #endif
10543 }
10544
10545 // Going below framePushedAtEntryToBody would imply that we've
10546 // popped off the machine stack, part of the frame created by
10547 // beginFunction().
10548 MOZ_ASSERT(masm.framePushed() >=
10549 stackMapGenerator_.framePushedAtEntryToBody.value());
10550
10551 // At this point we're definitely not generating code for a function call.
10552 MOZ_ASSERT(
10553 stackMapGenerator_.framePushedExcludingOutboundCallArgs.isNothing());
10554
10555 switch (op.b0) {
10556 case uint16_t(Op::End):
10557 if (!emitEnd()) {
10558 return false;
10559 }
10560 if (iter_.controlStackEmpty()) {
10561 return true;
10562 }
10563 NEXT();
10564
10565 // Control opcodes
10566 case uint16_t(Op::Nop):
10567 CHECK_NEXT(iter_.readNop());
10568 case uint16_t(Op::Drop):
10569 CHECK_NEXT(emitDrop());
10570 case uint16_t(Op::Block):
10571 CHECK_NEXT(emitBlock());
10572 case uint16_t(Op::Loop):
10573 CHECK_NEXT(emitLoop());
10574 case uint16_t(Op::If):
10575 CHECK_NEXT(emitIf());
10576 case uint16_t(Op::Else):
10577 CHECK_NEXT(emitElse());
10578 case uint16_t(Op::Try):
10579 CHECK_NEXT(emitTry());
10580 case uint16_t(Op::Catch):
10581 CHECK_NEXT(emitCatch());
10582 case uint16_t(Op::CatchAll):
10583 CHECK_NEXT(emitCatchAll());
10584 case uint16_t(Op::Delegate):
10585 CHECK(emitDelegate());
10586 iter_.popDelegate();
10587 NEXT();
10588 case uint16_t(Op::Throw):
10589 CHECK_NEXT(emitThrow());
10590 case uint16_t(Op::Rethrow):
10591 CHECK_NEXT(emitRethrow());
10592 case uint16_t(Op::ThrowRef):
10593 if (!codeMeta_.exnrefEnabled()) {
10594 return iter_.unrecognizedOpcode(&op);
10595 }
10596 CHECK_NEXT(emitThrowRef());
10597 case uint16_t(Op::TryTable):
10598 if (!codeMeta_.exnrefEnabled()) {
10599 return iter_.unrecognizedOpcode(&op);
10600 }
10601 CHECK_NEXT(emitTryTable());
10602 case uint16_t(Op::Br):
10603 CHECK_NEXT(emitBr());
10604 case uint16_t(Op::BrIf):
10605 CHECK_NEXT(emitBrIf());
10606 case uint16_t(Op::BrTable):
10607 CHECK_NEXT(emitBrTable());
10608 case uint16_t(Op::Return):
10609 CHECK_NEXT(emitReturn());
10610 case uint16_t(Op::Unreachable):
10611 CHECK(iter_.readUnreachable());
10612 if (!deadCode_) {
10613 trap(Trap::Unreachable);
10614 deadCode_ = true;
10615 }
10616 NEXT();
10617
10618 // Calls
10619 case uint16_t(Op::Call):
10620 CHECK_NEXT(emitCall());
10621 case uint16_t(Op::CallIndirect):
10622 CHECK_NEXT(emitCallIndirect());
10623 case uint16_t(Op::ReturnCall):
10624 CHECK_NEXT(emitReturnCall());
10625 case uint16_t(Op::ReturnCallIndirect):
10626 CHECK_NEXT(emitReturnCallIndirect());
10627 case uint16_t(Op::CallRef):
10628 CHECK_NEXT(emitCallRef());
10629 case uint16_t(Op::ReturnCallRef):
10630 CHECK_NEXT(emitReturnCallRef());
10631
10632 // Locals and globals
10633 case uint16_t(Op::LocalGet):
10634 CHECK_NEXT(emitGetLocal());
10635 case uint16_t(Op::LocalSet):
10636 CHECK_NEXT(emitSetLocal());
10637 case uint16_t(Op::LocalTee):
10638 CHECK_NEXT(emitTeeLocal());
10639 case uint16_t(Op::GlobalGet):
10640 CHECK_NEXT(emitGetGlobal());
10641 case uint16_t(Op::GlobalSet):
10642 CHECK_NEXT(emitSetGlobal());
10643 case uint16_t(Op::TableGet):
10644 CHECK_NEXT(emitTableGet());
10645 case uint16_t(Op::TableSet):
10646 CHECK_NEXT(emitTableSet());
10647
10648 // Select
10649 case uint16_t(Op::SelectNumeric):
10650 CHECK_NEXT(emitSelect(/*typed*/ false));
10651 case uint16_t(Op::SelectTyped):
10652 CHECK_NEXT(emitSelect(/*typed*/ true));
10653
10654 // I32
10655 case uint16_t(Op::I32Const): {
10656 int32_t i32;
10657 CHECK(iter_.readI32Const(&i32));
10658 if (!deadCode_) {
10659 pushI32(i32);
10660 }
10661 NEXT();
10662 }
10663 case uint16_t(Op::I32Add):
10664 CHECK_NEXT(dispatchBinary2(AddI32, AddImmI32, ValType::I32));
10665 case uint16_t(Op::I32Sub):
10666 CHECK_NEXT(dispatchBinary2(SubI32, SubImmI32, ValType::I32));
10667 case uint16_t(Op::I32Mul):
10668 CHECK_NEXT(dispatchBinary1(MulI32, ValType::I32));
10669 case uint16_t(Op::I32DivS):
10670 CHECK_NEXT(dispatchBinary0(emitQuotientI32, ValType::I32));
10671 case uint16_t(Op::I32DivU):
10672 CHECK_NEXT(dispatchBinary0(emitQuotientU32, ValType::I32));
10673 case uint16_t(Op::I32RemS):
10674 CHECK_NEXT(dispatchBinary0(emitRemainderI32, ValType::I32));
10675 case uint16_t(Op::I32RemU):
10676 CHECK_NEXT(dispatchBinary0(emitRemainderU32, ValType::I32));
10677 case uint16_t(Op::I32Eqz):
10678 CHECK_NEXT(dispatchConversion0(emitEqzI32, ValType::I32, ValType::I32));
10679 case uint16_t(Op::I32TruncF32S):
10680 CHECK_NEXT(dispatchConversionOOM(emitTruncateF32ToI32<0>, ValType::F32,
10681 ValType::I32));
10682 case uint16_t(Op::I32TruncF32U):
10683 CHECK_NEXT(dispatchConversionOOM(emitTruncateF32ToI32<TRUNC_UNSIGNED>,
10684 ValType::F32, ValType::I32));
10685 case uint16_t(Op::I32TruncF64S):
10686 CHECK_NEXT(dispatchConversionOOM(emitTruncateF64ToI32<0>, ValType::F64,
10687 ValType::I32));
10688 case uint16_t(Op::I32TruncF64U):
10689 CHECK_NEXT(dispatchConversionOOM(emitTruncateF64ToI32<TRUNC_UNSIGNED>,
10690 ValType::F64, ValType::I32));
10691 case uint16_t(Op::I32WrapI64):
10692 CHECK_NEXT(
10693 dispatchConversion1(WrapI64ToI32, ValType::I64, ValType::I32));
10694 case uint16_t(Op::I32ReinterpretF32):
10695 CHECK_NEXT(dispatchConversion1(ReinterpretF32AsI32, ValType::F32,
10696 ValType::I32));
10697 case uint16_t(Op::I32Clz):
10698 CHECK_NEXT(dispatchUnary1(ClzI32, ValType::I32));
10699 case uint16_t(Op::I32Ctz):
10700 CHECK_NEXT(dispatchUnary1(CtzI32, ValType::I32));
10701 case uint16_t(Op::I32Popcnt):
10702 CHECK_NEXT(dispatchUnary2(PopcntI32, PopcntTemp, ValType::I32));
10703 case uint16_t(Op::I32Or):
10704 CHECK_NEXT(dispatchBinary2(OrI32, OrImmI32, ValType::I32));
10705 case uint16_t(Op::I32And):
10706 CHECK_NEXT(dispatchBinary2(AndI32, AndImmI32, ValType::I32));
10707 case uint16_t(Op::I32Xor):
10708 CHECK_NEXT(dispatchBinary2(XorI32, XorImmI32, ValType::I32));
10709 case uint16_t(Op::I32Shl):
10710 CHECK_NEXT(dispatchBinary3(
10711 ShlI32, ShlImmI32, &BaseCompiler::popI32RhsForShift, ValType::I32));
10712 case uint16_t(Op::I32ShrS):
10713 CHECK_NEXT(dispatchBinary3(
10714 ShrI32, ShrImmI32, &BaseCompiler::popI32RhsForShift, ValType::I32));
10715 case uint16_t(Op::I32ShrU):
10716 CHECK_NEXT(dispatchBinary3(ShrUI32, ShrUImmI32,
10717 &BaseCompiler::popI32RhsForShift,
10718 ValType::I32));
10719 case uint16_t(Op::I32Load8S):
10720 CHECK_NEXT(emitLoad(ValType::I32, Scalar::Int8));
10721 case uint16_t(Op::I32Load8U):
10722 CHECK_NEXT(emitLoad(ValType::I32, Scalar::Uint8));
10723 case uint16_t(Op::I32Load16S):
10724 CHECK_NEXT(emitLoad(ValType::I32, Scalar::Int16));
10725 case uint16_t(Op::I32Load16U):
10726 CHECK_NEXT(emitLoad(ValType::I32, Scalar::Uint16));
10727 case uint16_t(Op::I32Load):
10728 CHECK_NEXT(emitLoad(ValType::I32, Scalar::Int32));
10729 case uint16_t(Op::I32Store8):
10730 CHECK_NEXT(emitStore(ValType::I32, Scalar::Int8));
10731 case uint16_t(Op::I32Store16):
10732 CHECK_NEXT(emitStore(ValType::I32, Scalar::Int16));
10733 case uint16_t(Op::I32Store):
10734 CHECK_NEXT(emitStore(ValType::I32, Scalar::Int32));
10735 case uint16_t(Op::I32Rotr):
10736 CHECK_NEXT(dispatchBinary3(RotrI32, RotrImmI32,
10737 &BaseCompiler::popI32RhsForRotate,
10738 ValType::I32));
10739 case uint16_t(Op::I32Rotl):
10740 CHECK_NEXT(dispatchBinary3(RotlI32, RotlImmI32,
10741 &BaseCompiler::popI32RhsForRotate,
10742 ValType::I32));
10743
10744 // I64
10745 case uint16_t(Op::I64Const): {
10746 int64_t i64;
10747 CHECK(iter_.readI64Const(&i64));
10748 if (!deadCode_) {
10749 pushI64(i64);
10750 }
10751 NEXT();
10752 }
10753 case uint16_t(Op::I64Add):
10754 CHECK_NEXT(dispatchBinary2(AddI64, AddImmI64, ValType::I64));
10755 case uint16_t(Op::I64Sub):
10756 CHECK_NEXT(dispatchBinary2(SubI64, SubImmI64, ValType::I64));
10757 case uint16_t(Op::I64Mul):
10758 CHECK_NEXT(dispatchBinary0(emitMultiplyI64, ValType::I64));
10759 case uint16_t(Op::I64DivS):
10760 #ifdef RABALDR_INT_DIV_I64_CALLOUT
10761 CHECK_NEXT(dispatchIntDivCallout(
10762 emitDivOrModI64BuiltinCall, SymbolicAddress::DivI64, ValType::I64));
10763 #else
10764 CHECK_NEXT(dispatchBinary0(emitQuotientI64, ValType::I64));
10765 #endif
10766 case uint16_t(Op::I64DivU):
10767 #ifdef RABALDR_INT_DIV_I64_CALLOUT
10768 CHECK_NEXT(dispatchIntDivCallout(emitDivOrModI64BuiltinCall,
10769 SymbolicAddress::UDivI64,
10770 ValType::I64));
10771 #else
10772 CHECK_NEXT(dispatchBinary0(emitQuotientU64, ValType::I64));
10773 #endif
10774 case uint16_t(Op::I64RemS):
10775 #ifdef RABALDR_INT_DIV_I64_CALLOUT
10776 CHECK_NEXT(dispatchIntDivCallout(
10777 emitDivOrModI64BuiltinCall, SymbolicAddress::ModI64, ValType::I64));
10778 #else
10779 CHECK_NEXT(dispatchBinary0(emitRemainderI64, ValType::I64));
10780 #endif
10781 case uint16_t(Op::I64RemU):
10782 #ifdef RABALDR_INT_DIV_I64_CALLOUT
10783 CHECK_NEXT(dispatchIntDivCallout(emitDivOrModI64BuiltinCall,
10784 SymbolicAddress::UModI64,
10785 ValType::I64));
10786 #else
10787 CHECK_NEXT(dispatchBinary0(emitRemainderU64, ValType::I64));
10788 #endif
10789 case uint16_t(Op::I64TruncF32S):
10790 #ifdef RABALDR_FLOAT_TO_I64_CALLOUT
10791 CHECK_NEXT(
10792 dispatchCalloutConversionOOM(emitConvertFloatingToInt64Callout,
10793 SymbolicAddress::TruncateDoubleToInt64,
10794 ValType::F32, ValType::I64));
10795 #else
10796 CHECK_NEXT(dispatchConversionOOM(emitTruncateF32ToI64<0>, ValType::F32,
10797 ValType::I64));
10798 #endif
10799 case uint16_t(Op::I64TruncF32U):
10800 #ifdef RABALDR_FLOAT_TO_I64_CALLOUT
10801 CHECK_NEXT(dispatchCalloutConversionOOM(
10802 emitConvertFloatingToInt64Callout,
10803 SymbolicAddress::TruncateDoubleToUint64, ValType::F32,
10804 ValType::I64));
10805 #else
10806 CHECK_NEXT(dispatchConversionOOM(emitTruncateF32ToI64<TRUNC_UNSIGNED>,
10807 ValType::F32, ValType::I64));
10808 #endif
10809 case uint16_t(Op::I64TruncF64S):
10810 #ifdef RABALDR_FLOAT_TO_I64_CALLOUT
10811 CHECK_NEXT(
10812 dispatchCalloutConversionOOM(emitConvertFloatingToInt64Callout,
10813 SymbolicAddress::TruncateDoubleToInt64,
10814 ValType::F64, ValType::I64));
10815 #else
10816 CHECK_NEXT(dispatchConversionOOM(emitTruncateF64ToI64<0>, ValType::F64,
10817 ValType::I64));
10818 #endif
10819 case uint16_t(Op::I64TruncF64U):
10820 #ifdef RABALDR_FLOAT_TO_I64_CALLOUT
10821 CHECK_NEXT(dispatchCalloutConversionOOM(
10822 emitConvertFloatingToInt64Callout,
10823 SymbolicAddress::TruncateDoubleToUint64, ValType::F64,
10824 ValType::I64));
10825 #else
10826 CHECK_NEXT(dispatchConversionOOM(emitTruncateF64ToI64<TRUNC_UNSIGNED>,
10827 ValType::F64, ValType::I64));
10828 #endif
10829 case uint16_t(Op::I64ExtendI32S):
10830 CHECK_NEXT(dispatchConversion0(emitExtendI32ToI64, ValType::I32,
10831 ValType::I64));
10832 case uint16_t(Op::I64ExtendI32U):
10833 CHECK_NEXT(dispatchConversion0(emitExtendU32ToI64, ValType::I32,
10834 ValType::I64));
10835 case uint16_t(Op::I64ReinterpretF64):
10836 CHECK_NEXT(dispatchConversion1(ReinterpretF64AsI64, ValType::F64,
10837 ValType::I64));
10838 case uint16_t(Op::I64Or):
10839 CHECK_NEXT(dispatchBinary2(OrI64, OrImmI64, ValType::I64));
10840 case uint16_t(Op::I64And):
10841 CHECK_NEXT(dispatchBinary2(AndI64, AndImmI64, ValType::I64));
10842 case uint16_t(Op::I64Xor):
10843 CHECK_NEXT(dispatchBinary2(XorI64, XorImmI64, ValType::I64));
10844 case uint16_t(Op::I64Shl):
10845 CHECK_NEXT(dispatchBinary3(
10846 ShlI64, ShlImmI64, &BaseCompiler::popI64RhsForShift, ValType::I64));
10847 case uint16_t(Op::I64ShrS):
10848 CHECK_NEXT(dispatchBinary3(
10849 ShrI64, ShrImmI64, &BaseCompiler::popI64RhsForShift, ValType::I64));
10850 case uint16_t(Op::I64ShrU):
10851 CHECK_NEXT(dispatchBinary3(ShrUI64, ShrUImmI64,
10852 &BaseCompiler::popI64RhsForShift,
10853 ValType::I64));
10854 case uint16_t(Op::I64Rotr):
10855 CHECK_NEXT(dispatchBinary0(emitRotrI64, ValType::I64));
10856 case uint16_t(Op::I64Rotl):
10857 CHECK_NEXT(dispatchBinary0(emitRotlI64, ValType::I64));
10858 case uint16_t(Op::I64Clz):
10859 CHECK_NEXT(dispatchUnary1(ClzI64, ValType::I64));
10860 case uint16_t(Op::I64Ctz):
10861 CHECK_NEXT(dispatchUnary1(CtzI64, ValType::I64));
10862 case uint16_t(Op::I64Popcnt):
10863 CHECK_NEXT(dispatchUnary2(PopcntI64, PopcntTemp, ValType::I64));
10864 case uint16_t(Op::I64Eqz):
10865 CHECK_NEXT(dispatchConversion0(emitEqzI64, ValType::I64, ValType::I32));
10866 case uint16_t(Op::I64Load8S):
10867 CHECK_NEXT(emitLoad(ValType::I64, Scalar::Int8));
10868 case uint16_t(Op::I64Load16S):
10869 CHECK_NEXT(emitLoad(ValType::I64, Scalar::Int16));
10870 case uint16_t(Op::I64Load32S):
10871 CHECK_NEXT(emitLoad(ValType::I64, Scalar::Int32));
10872 case uint16_t(Op::I64Load8U):
10873 CHECK_NEXT(emitLoad(ValType::I64, Scalar::Uint8));
10874 case uint16_t(Op::I64Load16U):
10875 CHECK_NEXT(emitLoad(ValType::I64, Scalar::Uint16));
10876 case uint16_t(Op::I64Load32U):
10877 CHECK_NEXT(emitLoad(ValType::I64, Scalar::Uint32));
10878 case uint16_t(Op::I64Load):
10879 CHECK_NEXT(emitLoad(ValType::I64, Scalar::Int64));
10880 case uint16_t(Op::I64Store8):
10881 CHECK_NEXT(emitStore(ValType::I64, Scalar::Int8));
10882 case uint16_t(Op::I64Store16):
10883 CHECK_NEXT(emitStore(ValType::I64, Scalar::Int16));
10884 case uint16_t(Op::I64Store32):
10885 CHECK_NEXT(emitStore(ValType::I64, Scalar::Int32));
10886 case uint16_t(Op::I64Store):
10887 CHECK_NEXT(emitStore(ValType::I64, Scalar::Int64));
10888
10889 // F32
10890 case uint16_t(Op::F32Const): {
10891 float f32;
10892 CHECK(iter_.readF32Const(&f32));
10893 if (!deadCode_) {
10894 pushF32(f32);
10895 }
10896 NEXT();
10897 }
10898 case uint16_t(Op::F32Add):
10899 CHECK_NEXT(dispatchBinary1(AddF32, ValType::F32))
10900 case uint16_t(Op::F32Sub):
10901 CHECK_NEXT(dispatchBinary1(SubF32, ValType::F32));
10902 case uint16_t(Op::F32Mul):
10903 CHECK_NEXT(dispatchBinary1(MulF32, ValType::F32));
10904 case uint16_t(Op::F32Div):
10905 CHECK_NEXT(dispatchBinary1(DivF32, ValType::F32));
10906 case uint16_t(Op::F32Min):
10907 CHECK_NEXT(dispatchBinary1(MinF32, ValType::F32));
10908 case uint16_t(Op::F32Max):
10909 CHECK_NEXT(dispatchBinary1(MaxF32, ValType::F32));
10910 case uint16_t(Op::F32Neg):
10911 CHECK_NEXT(dispatchUnary1(NegateF32, ValType::F32));
10912 case uint16_t(Op::F32Abs):
10913 CHECK_NEXT(dispatchUnary1(AbsF32, ValType::F32));
10914 case uint16_t(Op::F32Sqrt):
10915 CHECK_NEXT(dispatchUnary1(SqrtF32, ValType::F32));
10916 case uint16_t(Op::F32Ceil):
10917 CHECK_NEXT(
10918 emitUnaryMathBuiltinCall(SymbolicAddress::CeilF, ValType::F32));
10919 case uint16_t(Op::F32Floor):
10920 CHECK_NEXT(
10921 emitUnaryMathBuiltinCall(SymbolicAddress::FloorF, ValType::F32));
10922 case uint16_t(Op::F32DemoteF64):
10923 CHECK_NEXT(
10924 dispatchConversion1(ConvertF64ToF32, ValType::F64, ValType::F32));
10925 case uint16_t(Op::F32ConvertI32S):
10926 CHECK_NEXT(
10927 dispatchConversion1(ConvertI32ToF32, ValType::I32, ValType::F32));
10928 case uint16_t(Op::F32ConvertI32U):
10929 CHECK_NEXT(
10930 dispatchConversion1(ConvertU32ToF32, ValType::I32, ValType::F32));
10931 case uint16_t(Op::F32ConvertI64S):
10932 #ifdef RABALDR_I64_TO_FLOAT_CALLOUT
10933 CHECK_NEXT(dispatchCalloutConversionOOM(
10934 emitConvertInt64ToFloatingCallout, SymbolicAddress::Int64ToFloat32,
10935 ValType::I64, ValType::F32));
10936 #else
10937 CHECK_NEXT(
10938 dispatchConversion1(ConvertI64ToF32, ValType::I64, ValType::F32));
10939 #endif
10940 case uint16_t(Op::F32ConvertI64U):
10941 #ifdef RABALDR_I64_TO_FLOAT_CALLOUT
10942 CHECK_NEXT(dispatchCalloutConversionOOM(
10943 emitConvertInt64ToFloatingCallout, SymbolicAddress::Uint64ToFloat32,
10944 ValType::I64, ValType::F32));
10945 #else
10946 CHECK_NEXT(dispatchConversion0(emitConvertU64ToF32, ValType::I64,
10947 ValType::F32));
10948 #endif
10949 case uint16_t(Op::F32ReinterpretI32):
10950 CHECK_NEXT(dispatchConversion1(ReinterpretI32AsF32, ValType::I32,
10951 ValType::F32));
10952 case uint16_t(Op::F32Load):
10953 CHECK_NEXT(emitLoad(ValType::F32, Scalar::Float32));
10954 case uint16_t(Op::F32Store):
10955 CHECK_NEXT(emitStore(ValType::F32, Scalar::Float32));
10956 case uint16_t(Op::F32CopySign):
10957 CHECK_NEXT(dispatchBinary1(CopysignF32, ValType::F32));
10958 case uint16_t(Op::F32Nearest):
10959 CHECK_NEXT(emitUnaryMathBuiltinCall(SymbolicAddress::NearbyIntF,
10960 ValType::F32));
10961 case uint16_t(Op::F32Trunc):
10962 CHECK_NEXT(
10963 emitUnaryMathBuiltinCall(SymbolicAddress::TruncF, ValType::F32));
10964
10965 // F64
10966 case uint16_t(Op::F64Const): {
10967 double f64;
10968 CHECK(iter_.readF64Const(&f64));
10969 if (!deadCode_) {
10970 pushF64(f64);
10971 }
10972 NEXT();
10973 }
10974 case uint16_t(Op::F64Add):
10975 CHECK_NEXT(dispatchBinary1(AddF64, ValType::F64))
10976 case uint16_t(Op::F64Sub):
10977 CHECK_NEXT(dispatchBinary1(SubF64, ValType::F64));
10978 case uint16_t(Op::F64Mul):
10979 CHECK_NEXT(dispatchBinary1(MulF64, ValType::F64));
10980 case uint16_t(Op::F64Div):
10981 CHECK_NEXT(dispatchBinary1(DivF64, ValType::F64));
10982 case uint16_t(Op::F64Min):
10983 CHECK_NEXT(dispatchBinary1(MinF64, ValType::F64));
10984 case uint16_t(Op::F64Max):
10985 CHECK_NEXT(dispatchBinary1(MaxF64, ValType::F64));
10986 case uint16_t(Op::F64Neg):
10987 CHECK_NEXT(dispatchUnary1(NegateF64, ValType::F64));
10988 case uint16_t(Op::F64Abs):
10989 CHECK_NEXT(dispatchUnary1(AbsF64, ValType::F64));
10990 case uint16_t(Op::F64Sqrt):
10991 CHECK_NEXT(dispatchUnary1(SqrtF64, ValType::F64));
10992 case uint16_t(Op::F64Ceil):
10993 CHECK_NEXT(
10994 emitUnaryMathBuiltinCall(SymbolicAddress::CeilD, ValType::F64));
10995 case uint16_t(Op::F64Floor):
10996 CHECK_NEXT(
10997 emitUnaryMathBuiltinCall(SymbolicAddress::FloorD, ValType::F64));
10998 case uint16_t(Op::F64PromoteF32):
10999 CHECK_NEXT(
11000 dispatchConversion1(ConvertF32ToF64, ValType::F32, ValType::F64));
11001 case uint16_t(Op::F64ConvertI32S):
11002 CHECK_NEXT(
11003 dispatchConversion1(ConvertI32ToF64, ValType::I32, ValType::F64));
11004 case uint16_t(Op::F64ConvertI32U):
11005 CHECK_NEXT(
11006 dispatchConversion1(ConvertU32ToF64, ValType::I32, ValType::F64));
11007 case uint16_t(Op::F64ConvertI64S):
11008 #ifdef RABALDR_I64_TO_FLOAT_CALLOUT
11009 CHECK_NEXT(dispatchCalloutConversionOOM(
11010 emitConvertInt64ToFloatingCallout, SymbolicAddress::Int64ToDouble,
11011 ValType::I64, ValType::F64));
11012 #else
11013 CHECK_NEXT(
11014 dispatchConversion1(ConvertI64ToF64, ValType::I64, ValType::F64));
11015 #endif
11016 case uint16_t(Op::F64ConvertI64U):
11017 #ifdef RABALDR_I64_TO_FLOAT_CALLOUT
11018 CHECK_NEXT(dispatchCalloutConversionOOM(
11019 emitConvertInt64ToFloatingCallout, SymbolicAddress::Uint64ToDouble,
11020 ValType::I64, ValType::F64));
11021 #else
11022 CHECK_NEXT(dispatchConversion0(emitConvertU64ToF64, ValType::I64,
11023 ValType::F64));
11024 #endif
11025 case uint16_t(Op::F64Load):
11026 CHECK_NEXT(emitLoad(ValType::F64, Scalar::Float64));
11027 case uint16_t(Op::F64Store):
11028 CHECK_NEXT(emitStore(ValType::F64, Scalar::Float64));
11029 case uint16_t(Op::F64ReinterpretI64):
11030 CHECK_NEXT(dispatchConversion1(ReinterpretI64AsF64, ValType::I64,
11031 ValType::F64));
11032 case uint16_t(Op::F64CopySign):
11033 CHECK_NEXT(dispatchBinary1(CopysignF64, ValType::F64));
11034 case uint16_t(Op::F64Nearest):
11035 CHECK_NEXT(emitUnaryMathBuiltinCall(SymbolicAddress::NearbyIntD,
11036 ValType::F64));
11037 case uint16_t(Op::F64Trunc):
11038 CHECK_NEXT(
11039 emitUnaryMathBuiltinCall(SymbolicAddress::TruncD, ValType::F64));
11040
11041 // Comparisons
11042 case uint16_t(Op::I32Eq):
11043 CHECK_NEXT(dispatchComparison0(emitCompareI32, ValType::I32,
11044 Assembler::Equal));
11045 case uint16_t(Op::I32Ne):
11046 CHECK_NEXT(dispatchComparison0(emitCompareI32, ValType::I32,
11047 Assembler::NotEqual));
11048 case uint16_t(Op::I32LtS):
11049 CHECK_NEXT(dispatchComparison0(emitCompareI32, ValType::I32,
11050 Assembler::LessThan));
11051 case uint16_t(Op::I32LeS):
11052 CHECK_NEXT(dispatchComparison0(emitCompareI32, ValType::I32,
11053 Assembler::LessThanOrEqual));
11054 case uint16_t(Op::I32GtS):
11055 CHECK_NEXT(dispatchComparison0(emitCompareI32, ValType::I32,
11056 Assembler::GreaterThan));
11057 case uint16_t(Op::I32GeS):
11058 CHECK_NEXT(dispatchComparison0(emitCompareI32, ValType::I32,
11059 Assembler::GreaterThanOrEqual));
11060 case uint16_t(Op::I32LtU):
11061 CHECK_NEXT(dispatchComparison0(emitCompareI32, ValType::I32,
11062 Assembler::Below));
11063 case uint16_t(Op::I32LeU):
11064 CHECK_NEXT(dispatchComparison0(emitCompareI32, ValType::I32,
11065 Assembler::BelowOrEqual));
11066 case uint16_t(Op::I32GtU):
11067 CHECK_NEXT(dispatchComparison0(emitCompareI32, ValType::I32,
11068 Assembler::Above));
11069 case uint16_t(Op::I32GeU):
11070 CHECK_NEXT(dispatchComparison0(emitCompareI32, ValType::I32,
11071 Assembler::AboveOrEqual));
11072 case uint16_t(Op::I64Eq):
11073 CHECK_NEXT(dispatchComparison0(emitCompareI64, ValType::I64,
11074 Assembler::Equal));
11075 case uint16_t(Op::I64Ne):
11076 CHECK_NEXT(dispatchComparison0(emitCompareI64, ValType::I64,
11077 Assembler::NotEqual));
11078 case uint16_t(Op::I64LtS):
11079 CHECK_NEXT(dispatchComparison0(emitCompareI64, ValType::I64,
11080 Assembler::LessThan));
11081 case uint16_t(Op::I64LeS):
11082 CHECK_NEXT(dispatchComparison0(emitCompareI64, ValType::I64,
11083 Assembler::LessThanOrEqual));
11084 case uint16_t(Op::I64GtS):
11085 CHECK_NEXT(dispatchComparison0(emitCompareI64, ValType::I64,
11086 Assembler::GreaterThan));
11087 case uint16_t(Op::I64GeS):
11088 CHECK_NEXT(dispatchComparison0(emitCompareI64, ValType::I64,
11089 Assembler::GreaterThanOrEqual));
11090 case uint16_t(Op::I64LtU):
11091 CHECK_NEXT(dispatchComparison0(emitCompareI64, ValType::I64,
11092 Assembler::Below));
11093 case uint16_t(Op::I64LeU):
11094 CHECK_NEXT(dispatchComparison0(emitCompareI64, ValType::I64,
11095 Assembler::BelowOrEqual));
11096 case uint16_t(Op::I64GtU):
11097 CHECK_NEXT(dispatchComparison0(emitCompareI64, ValType::I64,
11098 Assembler::Above));
11099 case uint16_t(Op::I64GeU):
11100 CHECK_NEXT(dispatchComparison0(emitCompareI64, ValType::I64,
11101 Assembler::AboveOrEqual));
11102 case uint16_t(Op::F32Eq):
11103 CHECK_NEXT(dispatchComparison0(emitCompareF32, ValType::F32,
11104 Assembler::DoubleEqual));
11105 case uint16_t(Op::F32Ne):
11106 CHECK_NEXT(dispatchComparison0(emitCompareF32, ValType::F32,
11107 Assembler::DoubleNotEqualOrUnordered));
11108 case uint16_t(Op::F32Lt):
11109 CHECK_NEXT(dispatchComparison0(emitCompareF32, ValType::F32,
11110 Assembler::DoubleLessThan));
11111 case uint16_t(Op::F32Le):
11112 CHECK_NEXT(dispatchComparison0(emitCompareF32, ValType::F32,
11113 Assembler::DoubleLessThanOrEqual));
11114 case uint16_t(Op::F32Gt):
11115 CHECK_NEXT(dispatchComparison0(emitCompareF32, ValType::F32,
11116 Assembler::DoubleGreaterThan));
11117 case uint16_t(Op::F32Ge):
11118 CHECK_NEXT(dispatchComparison0(emitCompareF32, ValType::F32,
11119 Assembler::DoubleGreaterThanOrEqual));
11120 case uint16_t(Op::F64Eq):
11121 CHECK_NEXT(dispatchComparison0(emitCompareF64, ValType::F64,
11122 Assembler::DoubleEqual));
11123 case uint16_t(Op::F64Ne):
11124 CHECK_NEXT(dispatchComparison0(emitCompareF64, ValType::F64,
11125 Assembler::DoubleNotEqualOrUnordered));
11126 case uint16_t(Op::F64Lt):
11127 CHECK_NEXT(dispatchComparison0(emitCompareF64, ValType::F64,
11128 Assembler::DoubleLessThan));
11129 case uint16_t(Op::F64Le):
11130 CHECK_NEXT(dispatchComparison0(emitCompareF64, ValType::F64,
11131 Assembler::DoubleLessThanOrEqual));
11132 case uint16_t(Op::F64Gt):
11133 CHECK_NEXT(dispatchComparison0(emitCompareF64, ValType::F64,
11134 Assembler::DoubleGreaterThan));
11135 case uint16_t(Op::F64Ge):
11136 CHECK_NEXT(dispatchComparison0(emitCompareF64, ValType::F64,
11137 Assembler::DoubleGreaterThanOrEqual));
11138
11139 // Sign extensions
11140 case uint16_t(Op::I32Extend8S):
11141 CHECK_NEXT(
11142 dispatchConversion1(ExtendI32_8, ValType::I32, ValType::I32));
11143 case uint16_t(Op::I32Extend16S):
11144 CHECK_NEXT(
11145 dispatchConversion1(ExtendI32_16, ValType::I32, ValType::I32));
11146 case uint16_t(Op::I64Extend8S):
11147 CHECK_NEXT(
11148 dispatchConversion0(emitExtendI64_8, ValType::I64, ValType::I64));
11149 case uint16_t(Op::I64Extend16S):
11150 CHECK_NEXT(
11151 dispatchConversion0(emitExtendI64_16, ValType::I64, ValType::I64));
11152 case uint16_t(Op::I64Extend32S):
11153 CHECK_NEXT(
11154 dispatchConversion0(emitExtendI64_32, ValType::I64, ValType::I64));
11155
11156 // Memory Related
11157 case uint16_t(Op::MemoryGrow):
11158 CHECK_NEXT(emitMemoryGrow());
11159 case uint16_t(Op::MemorySize):
11160 CHECK_NEXT(emitMemorySize());
11161
11162 case uint16_t(Op::RefAsNonNull):
11163 CHECK_NEXT(emitRefAsNonNull());
11164 case uint16_t(Op::BrOnNull):
11165 CHECK_NEXT(emitBrOnNull());
11166 case uint16_t(Op::BrOnNonNull):
11167 CHECK_NEXT(emitBrOnNonNull());
11168 case uint16_t(Op::RefEq):
11169 CHECK_NEXT(dispatchComparison0(emitCompareRef, RefType::eq(),
11170 Assembler::Equal));
11171 case uint16_t(Op::RefFunc):
11172 CHECK_NEXT(emitRefFunc());
11173 break;
11174 case uint16_t(Op::RefNull):
11175 CHECK_NEXT(emitRefNull());
11176 break;
11177 case uint16_t(Op::RefIsNull):
11178 CHECK_NEXT(emitRefIsNull());
11179 break;
11180
11181 // "GC" operations
11182 case uint16_t(Op::GcPrefix): {
11183 switch (op.b1) {
11184 case uint32_t(GcOp::StructNew):
11185 CHECK_NEXT(emitStructNew());
11186 case uint32_t(GcOp::StructNewDefault):
11187 CHECK_NEXT(emitStructNewDefault());
11188 case uint32_t(GcOp::StructGet):
11189 CHECK_NEXT(emitStructGet(FieldWideningOp::None));
11190 case uint32_t(GcOp::StructGetS):
11191 CHECK_NEXT(emitStructGet(FieldWideningOp::Signed));
11192 case uint32_t(GcOp::StructGetU):
11193 CHECK_NEXT(emitStructGet(FieldWideningOp::Unsigned));
11194 case uint32_t(GcOp::StructSet):
11195 CHECK_NEXT(emitStructSet());
11196 case uint32_t(GcOp::ArrayNew):
11197 CHECK_NEXT(emitArrayNew());
11198 case uint32_t(GcOp::ArrayNewFixed):
11199 CHECK_NEXT(emitArrayNewFixed());
11200 case uint32_t(GcOp::ArrayNewDefault):
11201 CHECK_NEXT(emitArrayNewDefault());
11202 case uint32_t(GcOp::ArrayNewData):
11203 CHECK_NEXT(emitArrayNewData());
11204 case uint32_t(GcOp::ArrayNewElem):
11205 CHECK_NEXT(emitArrayNewElem());
11206 case uint32_t(GcOp::ArrayInitData):
11207 CHECK_NEXT(emitArrayInitData());
11208 case uint32_t(GcOp::ArrayInitElem):
11209 CHECK_NEXT(emitArrayInitElem());
11210 case uint32_t(GcOp::ArrayGet):
11211 CHECK_NEXT(emitArrayGet(FieldWideningOp::None));
11212 case uint32_t(GcOp::ArrayGetS):
11213 CHECK_NEXT(emitArrayGet(FieldWideningOp::Signed));
11214 case uint32_t(GcOp::ArrayGetU):
11215 CHECK_NEXT(emitArrayGet(FieldWideningOp::Unsigned));
11216 case uint32_t(GcOp::ArraySet):
11217 CHECK_NEXT(emitArraySet());
11218 case uint32_t(GcOp::ArrayLen):
11219 CHECK_NEXT(emitArrayLen());
11220 case uint32_t(GcOp::ArrayCopy):
11221 CHECK_NEXT(emitArrayCopy());
11222 case uint32_t(GcOp::ArrayFill):
11223 CHECK_NEXT(emitArrayFill());
11224 case uint32_t(GcOp::RefI31):
11225 CHECK_NEXT(emitRefI31());
11226 case uint32_t(GcOp::I31GetS):
11227 CHECK_NEXT(emitI31Get(FieldWideningOp::Signed));
11228 case uint32_t(GcOp::I31GetU):
11229 CHECK_NEXT(emitI31Get(FieldWideningOp::Unsigned));
11230 case uint32_t(GcOp::RefTest):
11231 CHECK_NEXT(emitRefTest(/*nullable=*/false));
11232 case uint32_t(GcOp::RefTestNull):
11233 CHECK_NEXT(emitRefTest(/*nullable=*/true));
11234 case uint32_t(GcOp::RefCast):
11235 CHECK_NEXT(emitRefCast(/*nullable=*/false));
11236 case uint32_t(GcOp::RefCastNull):
11237 CHECK_NEXT(emitRefCast(/*nullable=*/true));
11238 case uint32_t(GcOp::BrOnCast):
11239 CHECK_NEXT(emitBrOnCast(/*onSuccess=*/true));
11240 case uint32_t(GcOp::BrOnCastFail):
11241 CHECK_NEXT(emitBrOnCast(/*onSuccess=*/false));
11242 case uint16_t(GcOp::AnyConvertExtern):
11243 CHECK_NEXT(emitAnyConvertExtern());
11244 case uint16_t(GcOp::ExternConvertAny):
11245 CHECK_NEXT(emitExternConvertAny());
11246 default:
11247 break;
11248 } // switch (op.b1)
11249 return iter_.unrecognizedOpcode(&op);
11250 }
11251
11252 #ifdef ENABLE_WASM_SIMD
11253 // SIMD operations
11254 case uint16_t(Op::SimdPrefix): {
11255 uint32_t laneIndex;
11256 if (!codeMeta_.simdAvailable()) {
11257 return iter_.unrecognizedOpcode(&op);
11258 }
11259 switch (op.b1) {
11260 case uint32_t(SimdOp::I8x16ExtractLaneS):
11261 CHECK_NEXT(dispatchExtractLane(ExtractLaneI8x16, ValType::I32, 16));
11262 case uint32_t(SimdOp::I8x16ExtractLaneU):
11263 CHECK_NEXT(
11264 dispatchExtractLane(ExtractLaneUI8x16, ValType::I32, 16));
11265 case uint32_t(SimdOp::I16x8ExtractLaneS):
11266 CHECK_NEXT(dispatchExtractLane(ExtractLaneI16x8, ValType::I32, 8));
11267 case uint32_t(SimdOp::I16x8ExtractLaneU):
11268 CHECK_NEXT(dispatchExtractLane(ExtractLaneUI16x8, ValType::I32, 8));
11269 case uint32_t(SimdOp::I32x4ExtractLane):
11270 CHECK_NEXT(dispatchExtractLane(ExtractLaneI32x4, ValType::I32, 4));
11271 case uint32_t(SimdOp::I64x2ExtractLane):
11272 CHECK_NEXT(dispatchExtractLane(ExtractLaneI64x2, ValType::I64, 2));
11273 case uint32_t(SimdOp::F32x4ExtractLane):
11274 CHECK_NEXT(dispatchExtractLane(ExtractLaneF32x4, ValType::F32, 4));
11275 case uint32_t(SimdOp::F64x2ExtractLane):
11276 CHECK_NEXT(dispatchExtractLane(ExtractLaneF64x2, ValType::F64, 2));
11277 case uint32_t(SimdOp::I8x16Splat):
11278 CHECK_NEXT(dispatchSplat(SplatI8x16, ValType::I32));
11279 case uint32_t(SimdOp::I16x8Splat):
11280 CHECK_NEXT(dispatchSplat(SplatI16x8, ValType::I32));
11281 case uint32_t(SimdOp::I32x4Splat):
11282 CHECK_NEXT(dispatchSplat(SplatI32x4, ValType::I32));
11283 case uint32_t(SimdOp::I64x2Splat):
11284 CHECK_NEXT(dispatchSplat(SplatI64x2, ValType::I64));
11285 case uint32_t(SimdOp::F32x4Splat):
11286 CHECK_NEXT(dispatchSplat(SplatF32x4, ValType::F32));
11287 case uint32_t(SimdOp::F64x2Splat):
11288 CHECK_NEXT(dispatchSplat(SplatF64x2, ValType::F64));
11289 case uint32_t(SimdOp::V128AnyTrue):
11290 CHECK_NEXT(dispatchVectorReduction(AnyTrue));
11291 case uint32_t(SimdOp::I8x16AllTrue):
11292 CHECK_NEXT(dispatchVectorReduction(AllTrueI8x16));
11293 case uint32_t(SimdOp::I16x8AllTrue):
11294 CHECK_NEXT(dispatchVectorReduction(AllTrueI16x8));
11295 case uint32_t(SimdOp::I32x4AllTrue):
11296 CHECK_NEXT(dispatchVectorReduction(AllTrueI32x4));
11297 case uint32_t(SimdOp::I64x2AllTrue):
11298 CHECK_NEXT(dispatchVectorReduction(AllTrueI64x2));
11299 case uint32_t(SimdOp::I8x16Bitmask):
11300 CHECK_NEXT(dispatchVectorReduction(BitmaskI8x16));
11301 case uint32_t(SimdOp::I16x8Bitmask):
11302 CHECK_NEXT(dispatchVectorReduction(BitmaskI16x8));
11303 case uint32_t(SimdOp::I32x4Bitmask):
11304 CHECK_NEXT(dispatchVectorReduction(BitmaskI32x4));
11305 case uint32_t(SimdOp::I64x2Bitmask):
11306 CHECK_NEXT(dispatchVectorReduction(BitmaskI64x2));
11307 case uint32_t(SimdOp::I8x16ReplaceLane):
11308 CHECK_NEXT(dispatchReplaceLane(ReplaceLaneI8x16, ValType::I32, 16));
11309 case uint32_t(SimdOp::I16x8ReplaceLane):
11310 CHECK_NEXT(dispatchReplaceLane(ReplaceLaneI16x8, ValType::I32, 8));
11311 case uint32_t(SimdOp::I32x4ReplaceLane):
11312 CHECK_NEXT(dispatchReplaceLane(ReplaceLaneI32x4, ValType::I32, 4));
11313 case uint32_t(SimdOp::I64x2ReplaceLane):
11314 CHECK_NEXT(dispatchReplaceLane(ReplaceLaneI64x2, ValType::I64, 2));
11315 case uint32_t(SimdOp::F32x4ReplaceLane):
11316 CHECK_NEXT(dispatchReplaceLane(ReplaceLaneF32x4, ValType::F32, 4));
11317 case uint32_t(SimdOp::F64x2ReplaceLane):
11318 CHECK_NEXT(dispatchReplaceLane(ReplaceLaneF64x2, ValType::F64, 2));
11319 case uint32_t(SimdOp::I8x16Eq):
11320 CHECK_NEXT(dispatchVectorComparison(CmpI8x16, Assembler::Equal));
11321 case uint32_t(SimdOp::I8x16Ne):
11322 CHECK_NEXT(dispatchVectorComparison(CmpI8x16, Assembler::NotEqual));
11323 case uint32_t(SimdOp::I8x16LtS):
11324 CHECK_NEXT(dispatchVectorComparison(CmpI8x16, Assembler::LessThan));
11325 case uint32_t(SimdOp::I8x16LtU):
11326 CHECK_NEXT(dispatchVectorComparison(CmpUI8x16, Assembler::Below));
11327 case uint32_t(SimdOp::I8x16GtS):
11328 CHECK_NEXT(
11329 dispatchVectorComparison(CmpI8x16, Assembler::GreaterThan));
11330 case uint32_t(SimdOp::I8x16GtU):
11331 CHECK_NEXT(dispatchVectorComparison(CmpUI8x16, Assembler::Above));
11332 case uint32_t(SimdOp::I8x16LeS):
11333 CHECK_NEXT(
11334 dispatchVectorComparison(CmpI8x16, Assembler::LessThanOrEqual));
11335 case uint32_t(SimdOp::I8x16LeU):
11336 CHECK_NEXT(
11337 dispatchVectorComparison(CmpUI8x16, Assembler::BelowOrEqual));
11338 case uint32_t(SimdOp::I8x16GeS):
11339 CHECK_NEXT(dispatchVectorComparison(CmpI8x16,
11340 Assembler::GreaterThanOrEqual));
11341 case uint32_t(SimdOp::I8x16GeU):
11342 CHECK_NEXT(
11343 dispatchVectorComparison(CmpUI8x16, Assembler::AboveOrEqual));
11344 case uint32_t(SimdOp::I16x8Eq):
11345 CHECK_NEXT(dispatchVectorComparison(CmpI16x8, Assembler::Equal));
11346 case uint32_t(SimdOp::I16x8Ne):
11347 CHECK_NEXT(dispatchVectorComparison(CmpI16x8, Assembler::NotEqual));
11348 case uint32_t(SimdOp::I16x8LtS):
11349 CHECK_NEXT(dispatchVectorComparison(CmpI16x8, Assembler::LessThan));
11350 case uint32_t(SimdOp::I16x8LtU):
11351 CHECK_NEXT(dispatchVectorComparison(CmpUI16x8, Assembler::Below));
11352 case uint32_t(SimdOp::I16x8GtS):
11353 CHECK_NEXT(
11354 dispatchVectorComparison(CmpI16x8, Assembler::GreaterThan));
11355 case uint32_t(SimdOp::I16x8GtU):
11356 CHECK_NEXT(dispatchVectorComparison(CmpUI16x8, Assembler::Above));
11357 case uint32_t(SimdOp::I16x8LeS):
11358 CHECK_NEXT(
11359 dispatchVectorComparison(CmpI16x8, Assembler::LessThanOrEqual));
11360 case uint32_t(SimdOp::I16x8LeU):
11361 CHECK_NEXT(
11362 dispatchVectorComparison(CmpUI16x8, Assembler::BelowOrEqual));
11363 case uint32_t(SimdOp::I16x8GeS):
11364 CHECK_NEXT(dispatchVectorComparison(CmpI16x8,
11365 Assembler::GreaterThanOrEqual));
11366 case uint32_t(SimdOp::I16x8GeU):
11367 CHECK_NEXT(
11368 dispatchVectorComparison(CmpUI16x8, Assembler::AboveOrEqual));
11369 case uint32_t(SimdOp::I32x4Eq):
11370 CHECK_NEXT(dispatchVectorComparison(CmpI32x4, Assembler::Equal));
11371 case uint32_t(SimdOp::I32x4Ne):
11372 CHECK_NEXT(dispatchVectorComparison(CmpI32x4, Assembler::NotEqual));
11373 case uint32_t(SimdOp::I32x4LtS):
11374 CHECK_NEXT(dispatchVectorComparison(CmpI32x4, Assembler::LessThan));
11375 case uint32_t(SimdOp::I32x4LtU):
11376 CHECK_NEXT(dispatchVectorComparison(CmpUI32x4, Assembler::Below));
11377 case uint32_t(SimdOp::I32x4GtS):
11378 CHECK_NEXT(
11379 dispatchVectorComparison(CmpI32x4, Assembler::GreaterThan));
11380 case uint32_t(SimdOp::I32x4GtU):
11381 CHECK_NEXT(dispatchVectorComparison(CmpUI32x4, Assembler::Above));
11382 case uint32_t(SimdOp::I32x4LeS):
11383 CHECK_NEXT(
11384 dispatchVectorComparison(CmpI32x4, Assembler::LessThanOrEqual));
11385 case uint32_t(SimdOp::I32x4LeU):
11386 CHECK_NEXT(
11387 dispatchVectorComparison(CmpUI32x4, Assembler::BelowOrEqual));
11388 case uint32_t(SimdOp::I32x4GeS):
11389 CHECK_NEXT(dispatchVectorComparison(CmpI32x4,
11390 Assembler::GreaterThanOrEqual));
11391 case uint32_t(SimdOp::I32x4GeU):
11392 CHECK_NEXT(
11393 dispatchVectorComparison(CmpUI32x4, Assembler::AboveOrEqual));
11394 case uint32_t(SimdOp::I64x2Eq):
11395 CHECK_NEXT(dispatchVectorComparison(CmpI64x2ForEquality,
11396 Assembler::Equal));
11397 case uint32_t(SimdOp::I64x2Ne):
11398 CHECK_NEXT(dispatchVectorComparison(CmpI64x2ForEquality,
11399 Assembler::NotEqual));
11400 case uint32_t(SimdOp::I64x2LtS):
11401 CHECK_NEXT(dispatchVectorComparison(CmpI64x2ForOrdering,
11402 Assembler::LessThan));
11403 case uint32_t(SimdOp::I64x2GtS):
11404 CHECK_NEXT(dispatchVectorComparison(CmpI64x2ForOrdering,
11405 Assembler::GreaterThan));
11406 case uint32_t(SimdOp::I64x2LeS):
11407 CHECK_NEXT(dispatchVectorComparison(CmpI64x2ForOrdering,
11408 Assembler::LessThanOrEqual));
11409 case uint32_t(SimdOp::I64x2GeS):
11410 CHECK_NEXT(dispatchVectorComparison(CmpI64x2ForOrdering,
11411 Assembler::GreaterThanOrEqual));
11412 case uint32_t(SimdOp::F32x4Eq):
11413 CHECK_NEXT(dispatchVectorComparison(CmpF32x4, Assembler::Equal));
11414 case uint32_t(SimdOp::F32x4Ne):
11415 CHECK_NEXT(dispatchVectorComparison(CmpF32x4, Assembler::NotEqual));
11416 case uint32_t(SimdOp::F32x4Lt):
11417 CHECK_NEXT(dispatchVectorComparison(CmpF32x4, Assembler::LessThan));
11418 case uint32_t(SimdOp::F32x4Gt):
11419 CHECK_NEXT(
11420 dispatchVectorComparison(CmpF32x4, Assembler::GreaterThan));
11421 case uint32_t(SimdOp::F32x4Le):
11422 CHECK_NEXT(
11423 dispatchVectorComparison(CmpF32x4, Assembler::LessThanOrEqual));
11424 case uint32_t(SimdOp::F32x4Ge):
11425 CHECK_NEXT(dispatchVectorComparison(CmpF32x4,
11426 Assembler::GreaterThanOrEqual));
11427 case uint32_t(SimdOp::F64x2Eq):
11428 CHECK_NEXT(dispatchVectorComparison(CmpF64x2, Assembler::Equal));
11429 case uint32_t(SimdOp::F64x2Ne):
11430 CHECK_NEXT(dispatchVectorComparison(CmpF64x2, Assembler::NotEqual));
11431 case uint32_t(SimdOp::F64x2Lt):
11432 CHECK_NEXT(dispatchVectorComparison(CmpF64x2, Assembler::LessThan));
11433 case uint32_t(SimdOp::F64x2Gt):
11434 CHECK_NEXT(
11435 dispatchVectorComparison(CmpF64x2, Assembler::GreaterThan));
11436 case uint32_t(SimdOp::F64x2Le):
11437 CHECK_NEXT(
11438 dispatchVectorComparison(CmpF64x2, Assembler::LessThanOrEqual));
11439 case uint32_t(SimdOp::F64x2Ge):
11440 CHECK_NEXT(dispatchVectorComparison(CmpF64x2,
11441 Assembler::GreaterThanOrEqual));
11442 case uint32_t(SimdOp::V128And):
11443 CHECK_NEXT(dispatchVectorBinary(AndV128));
11444 case uint32_t(SimdOp::V128Or):
11445 CHECK_NEXT(dispatchVectorBinary(OrV128));
11446 case uint32_t(SimdOp::V128Xor):
11447 CHECK_NEXT(dispatchVectorBinary(XorV128));
11448 case uint32_t(SimdOp::V128AndNot):
11449 CHECK_NEXT(dispatchBinary0(emitVectorAndNot, ValType::V128));
11450 case uint32_t(SimdOp::I8x16AvgrU):
11451 CHECK_NEXT(dispatchVectorBinary(AverageUI8x16));
11452 case uint32_t(SimdOp::I16x8AvgrU):
11453 CHECK_NEXT(dispatchVectorBinary(AverageUI16x8));
11454 case uint32_t(SimdOp::I8x16Add):
11455 CHECK_NEXT(dispatchVectorBinary(AddI8x16));
11456 case uint32_t(SimdOp::I8x16AddSatS):
11457 CHECK_NEXT(dispatchVectorBinary(AddSatI8x16));
11458 case uint32_t(SimdOp::I8x16AddSatU):
11459 CHECK_NEXT(dispatchVectorBinary(AddSatUI8x16));
11460 case uint32_t(SimdOp::I8x16Sub):
11461 CHECK_NEXT(dispatchVectorBinary(SubI8x16));
11462 case uint32_t(SimdOp::I8x16SubSatS):
11463 CHECK_NEXT(dispatchVectorBinary(SubSatI8x16));
11464 case uint32_t(SimdOp::I8x16SubSatU):
11465 CHECK_NEXT(dispatchVectorBinary(SubSatUI8x16));
11466 case uint32_t(SimdOp::I8x16MinS):
11467 CHECK_NEXT(dispatchVectorBinary(MinI8x16));
11468 case uint32_t(SimdOp::I8x16MinU):
11469 CHECK_NEXT(dispatchVectorBinary(MinUI8x16));
11470 case uint32_t(SimdOp::I8x16MaxS):
11471 CHECK_NEXT(dispatchVectorBinary(MaxI8x16));
11472 case uint32_t(SimdOp::I8x16MaxU):
11473 CHECK_NEXT(dispatchVectorBinary(MaxUI8x16));
11474 case uint32_t(SimdOp::I16x8Add):
11475 CHECK_NEXT(dispatchVectorBinary(AddI16x8));
11476 case uint32_t(SimdOp::I16x8AddSatS):
11477 CHECK_NEXT(dispatchVectorBinary(AddSatI16x8));
11478 case uint32_t(SimdOp::I16x8AddSatU):
11479 CHECK_NEXT(dispatchVectorBinary(AddSatUI16x8));
11480 case uint32_t(SimdOp::I16x8Sub):
11481 CHECK_NEXT(dispatchVectorBinary(SubI16x8));
11482 case uint32_t(SimdOp::I16x8SubSatS):
11483 CHECK_NEXT(dispatchVectorBinary(SubSatI16x8));
11484 case uint32_t(SimdOp::I16x8SubSatU):
11485 CHECK_NEXT(dispatchVectorBinary(SubSatUI16x8));
11486 case uint32_t(SimdOp::I16x8Mul):
11487 CHECK_NEXT(dispatchVectorBinary(MulI16x8));
11488 case uint32_t(SimdOp::I16x8MinS):
11489 CHECK_NEXT(dispatchVectorBinary(MinI16x8));
11490 case uint32_t(SimdOp::I16x8MinU):
11491 CHECK_NEXT(dispatchVectorBinary(MinUI16x8));
11492 case uint32_t(SimdOp::I16x8MaxS):
11493 CHECK_NEXT(dispatchVectorBinary(MaxI16x8));
11494 case uint32_t(SimdOp::I16x8MaxU):
11495 CHECK_NEXT(dispatchVectorBinary(MaxUI16x8));
11496 case uint32_t(SimdOp::I32x4Add):
11497 CHECK_NEXT(dispatchVectorBinary(AddI32x4));
11498 case uint32_t(SimdOp::I32x4Sub):
11499 CHECK_NEXT(dispatchVectorBinary(SubI32x4));
11500 case uint32_t(SimdOp::I32x4Mul):
11501 CHECK_NEXT(dispatchVectorBinary(MulI32x4));
11502 case uint32_t(SimdOp::I32x4MinS):
11503 CHECK_NEXT(dispatchVectorBinary(MinI32x4));
11504 case uint32_t(SimdOp::I32x4MinU):
11505 CHECK_NEXT(dispatchVectorBinary(MinUI32x4));
11506 case uint32_t(SimdOp::I32x4MaxS):
11507 CHECK_NEXT(dispatchVectorBinary(MaxI32x4));
11508 case uint32_t(SimdOp::I32x4MaxU):
11509 CHECK_NEXT(dispatchVectorBinary(MaxUI32x4));
11510 case uint32_t(SimdOp::I64x2Add):
11511 CHECK_NEXT(dispatchVectorBinary(AddI64x2));
11512 case uint32_t(SimdOp::I64x2Sub):
11513 CHECK_NEXT(dispatchVectorBinary(SubI64x2));
11514 case uint32_t(SimdOp::I64x2Mul):
11515 CHECK_NEXT(dispatchVectorBinary(MulI64x2));
11516 case uint32_t(SimdOp::F32x4Add):
11517 CHECK_NEXT(dispatchVectorBinary(AddF32x4));
11518 case uint32_t(SimdOp::F32x4Sub):
11519 CHECK_NEXT(dispatchVectorBinary(SubF32x4));
11520 case uint32_t(SimdOp::F32x4Mul):
11521 CHECK_NEXT(dispatchVectorBinary(MulF32x4));
11522 case uint32_t(SimdOp::F32x4Div):
11523 CHECK_NEXT(dispatchVectorBinary(DivF32x4));
11524 case uint32_t(SimdOp::F32x4Min):
11525 CHECK_NEXT(dispatchVectorBinary(MinF32x4));
11526 case uint32_t(SimdOp::F32x4Max):
11527 CHECK_NEXT(dispatchVectorBinary(MaxF32x4));
11528 case uint32_t(SimdOp::F64x2Add):
11529 CHECK_NEXT(dispatchVectorBinary(AddF64x2));
11530 case uint32_t(SimdOp::F64x2Sub):
11531 CHECK_NEXT(dispatchVectorBinary(SubF64x2));
11532 case uint32_t(SimdOp::F64x2Mul):
11533 CHECK_NEXT(dispatchVectorBinary(MulF64x2));
11534 case uint32_t(SimdOp::F64x2Div):
11535 CHECK_NEXT(dispatchVectorBinary(DivF64x2));
11536 case uint32_t(SimdOp::F64x2Min):
11537 CHECK_NEXT(dispatchVectorBinary(MinF64x2));
11538 case uint32_t(SimdOp::F64x2Max):
11539 CHECK_NEXT(dispatchVectorBinary(MaxF64x2));
11540 case uint32_t(SimdOp::I8x16NarrowI16x8S):
11541 CHECK_NEXT(dispatchVectorBinary(NarrowI16x8));
11542 case uint32_t(SimdOp::I8x16NarrowI16x8U):
11543 CHECK_NEXT(dispatchVectorBinary(NarrowUI16x8));
11544 case uint32_t(SimdOp::I16x8NarrowI32x4S):
11545 CHECK_NEXT(dispatchVectorBinary(NarrowI32x4));
11546 case uint32_t(SimdOp::I16x8NarrowI32x4U):
11547 CHECK_NEXT(dispatchVectorBinary(NarrowUI32x4));
11548 case uint32_t(SimdOp::I8x16Swizzle):
11549 CHECK_NEXT(dispatchVectorBinary(Swizzle));
11550 case uint32_t(SimdOp::F32x4PMax):
11551 CHECK_NEXT(dispatchVectorBinary(PMaxF32x4));
11552 case uint32_t(SimdOp::F32x4PMin):
11553 CHECK_NEXT(dispatchVectorBinary(PMinF32x4));
11554 case uint32_t(SimdOp::F64x2PMax):
11555 CHECK_NEXT(dispatchVectorBinary(PMaxF64x2));
11556 case uint32_t(SimdOp::F64x2PMin):
11557 CHECK_NEXT(dispatchVectorBinary(PMinF64x2));
11558 case uint32_t(SimdOp::I32x4DotI16x8S):
11559 CHECK_NEXT(dispatchVectorBinary(DotI16x8));
11560 case uint32_t(SimdOp::I16x8ExtmulLowI8x16S):
11561 CHECK_NEXT(dispatchVectorBinary(ExtMulLowI8x16));
11562 case uint32_t(SimdOp::I16x8ExtmulHighI8x16S):
11563 CHECK_NEXT(dispatchVectorBinary(ExtMulHighI8x16));
11564 case uint32_t(SimdOp::I16x8ExtmulLowI8x16U):
11565 CHECK_NEXT(dispatchVectorBinary(ExtMulLowUI8x16));
11566 case uint32_t(SimdOp::I16x8ExtmulHighI8x16U):
11567 CHECK_NEXT(dispatchVectorBinary(ExtMulHighUI8x16));
11568 case uint32_t(SimdOp::I32x4ExtmulLowI16x8S):
11569 CHECK_NEXT(dispatchVectorBinary(ExtMulLowI16x8));
11570 case uint32_t(SimdOp::I32x4ExtmulHighI16x8S):
11571 CHECK_NEXT(dispatchVectorBinary(ExtMulHighI16x8));
11572 case uint32_t(SimdOp::I32x4ExtmulLowI16x8U):
11573 CHECK_NEXT(dispatchVectorBinary(ExtMulLowUI16x8));
11574 case uint32_t(SimdOp::I32x4ExtmulHighI16x8U):
11575 CHECK_NEXT(dispatchVectorBinary(ExtMulHighUI16x8));
11576 case uint32_t(SimdOp::I64x2ExtmulLowI32x4S):
11577 CHECK_NEXT(dispatchVectorBinary(ExtMulLowI32x4));
11578 case uint32_t(SimdOp::I64x2ExtmulHighI32x4S):
11579 CHECK_NEXT(dispatchVectorBinary(ExtMulHighI32x4));
11580 case uint32_t(SimdOp::I64x2ExtmulLowI32x4U):
11581 CHECK_NEXT(dispatchVectorBinary(ExtMulLowUI32x4));
11582 case uint32_t(SimdOp::I64x2ExtmulHighI32x4U):
11583 CHECK_NEXT(dispatchVectorBinary(ExtMulHighUI32x4));
11584 case uint32_t(SimdOp::I16x8Q15MulrSatS):
11585 CHECK_NEXT(dispatchVectorBinary(Q15MulrSatS));
11586 case uint32_t(SimdOp::I8x16Neg):
11587 CHECK_NEXT(dispatchVectorUnary(NegI8x16));
11588 case uint32_t(SimdOp::I16x8Neg):
11589 CHECK_NEXT(dispatchVectorUnary(NegI16x8));
11590 case uint32_t(SimdOp::I16x8ExtendLowI8x16S):
11591 CHECK_NEXT(dispatchVectorUnary(WidenLowI8x16));
11592 case uint32_t(SimdOp::I16x8ExtendHighI8x16S):
11593 CHECK_NEXT(dispatchVectorUnary(WidenHighI8x16));
11594 case uint32_t(SimdOp::I16x8ExtendLowI8x16U):
11595 CHECK_NEXT(dispatchVectorUnary(WidenLowUI8x16));
11596 case uint32_t(SimdOp::I16x8ExtendHighI8x16U):
11597 CHECK_NEXT(dispatchVectorUnary(WidenHighUI8x16));
11598 case uint32_t(SimdOp::I32x4Neg):
11599 CHECK_NEXT(dispatchVectorUnary(NegI32x4));
11600 case uint32_t(SimdOp::I32x4ExtendLowI16x8S):
11601 CHECK_NEXT(dispatchVectorUnary(WidenLowI16x8));
11602 case uint32_t(SimdOp::I32x4ExtendHighI16x8S):
11603 CHECK_NEXT(dispatchVectorUnary(WidenHighI16x8));
11604 case uint32_t(SimdOp::I32x4ExtendLowI16x8U):
11605 CHECK_NEXT(dispatchVectorUnary(WidenLowUI16x8));
11606 case uint32_t(SimdOp::I32x4ExtendHighI16x8U):
11607 CHECK_NEXT(dispatchVectorUnary(WidenHighUI16x8));
11608 case uint32_t(SimdOp::I32x4TruncSatF32x4S):
11609 CHECK_NEXT(dispatchVectorUnary(ConvertF32x4ToI32x4));
11610 case uint32_t(SimdOp::I32x4TruncSatF32x4U):
11611 CHECK_NEXT(dispatchVectorUnary(ConvertF32x4ToUI32x4));
11612 case uint32_t(SimdOp::I64x2Neg):
11613 CHECK_NEXT(dispatchVectorUnary(NegI64x2));
11614 case uint32_t(SimdOp::I64x2ExtendLowI32x4S):
11615 CHECK_NEXT(dispatchVectorUnary(WidenLowI32x4));
11616 case uint32_t(SimdOp::I64x2ExtendHighI32x4S):
11617 CHECK_NEXT(dispatchVectorUnary(WidenHighI32x4));
11618 case uint32_t(SimdOp::I64x2ExtendLowI32x4U):
11619 CHECK_NEXT(dispatchVectorUnary(WidenLowUI32x4));
11620 case uint32_t(SimdOp::I64x2ExtendHighI32x4U):
11621 CHECK_NEXT(dispatchVectorUnary(WidenHighUI32x4));
11622 case uint32_t(SimdOp::F32x4Abs):
11623 CHECK_NEXT(dispatchVectorUnary(AbsF32x4));
11624 case uint32_t(SimdOp::F32x4Neg):
11625 CHECK_NEXT(dispatchVectorUnary(NegF32x4));
11626 case uint32_t(SimdOp::F32x4Sqrt):
11627 CHECK_NEXT(dispatchVectorUnary(SqrtF32x4));
11628 case uint32_t(SimdOp::F32x4ConvertI32x4S):
11629 CHECK_NEXT(dispatchVectorUnary(ConvertI32x4ToF32x4));
11630 case uint32_t(SimdOp::F32x4ConvertI32x4U):
11631 CHECK_NEXT(dispatchVectorUnary(ConvertUI32x4ToF32x4));
11632 case uint32_t(SimdOp::F32x4DemoteF64x2Zero):
11633 CHECK_NEXT(dispatchVectorUnary(DemoteF64x2ToF32x4));
11634 case uint32_t(SimdOp::F64x2PromoteLowF32x4):
11635 CHECK_NEXT(dispatchVectorUnary(PromoteF32x4ToF64x2));
11636 case uint32_t(SimdOp::F64x2ConvertLowI32x4S):
11637 CHECK_NEXT(dispatchVectorUnary(ConvertI32x4ToF64x2));
11638 case uint32_t(SimdOp::F64x2ConvertLowI32x4U):
11639 CHECK_NEXT(dispatchVectorUnary(ConvertUI32x4ToF64x2));
11640 case uint32_t(SimdOp::I32x4TruncSatF64x2SZero):
11641 CHECK_NEXT(dispatchVectorUnary(ConvertF64x2ToI32x4));
11642 case uint32_t(SimdOp::I32x4TruncSatF64x2UZero):
11643 CHECK_NEXT(dispatchVectorUnary(ConvertF64x2ToUI32x4));
11644 case uint32_t(SimdOp::F64x2Abs):
11645 CHECK_NEXT(dispatchVectorUnary(AbsF64x2));
11646 case uint32_t(SimdOp::F64x2Neg):
11647 CHECK_NEXT(dispatchVectorUnary(NegF64x2));
11648 case uint32_t(SimdOp::F64x2Sqrt):
11649 CHECK_NEXT(dispatchVectorUnary(SqrtF64x2));
11650 case uint32_t(SimdOp::V128Not):
11651 CHECK_NEXT(dispatchVectorUnary(NotV128));
11652 case uint32_t(SimdOp::I8x16Popcnt):
11653 CHECK_NEXT(dispatchVectorUnary(PopcntI8x16));
11654 case uint32_t(SimdOp::I8x16Abs):
11655 CHECK_NEXT(dispatchVectorUnary(AbsI8x16));
11656 case uint32_t(SimdOp::I16x8Abs):
11657 CHECK_NEXT(dispatchVectorUnary(AbsI16x8));
11658 case uint32_t(SimdOp::I32x4Abs):
11659 CHECK_NEXT(dispatchVectorUnary(AbsI32x4));
11660 case uint32_t(SimdOp::I64x2Abs):
11661 CHECK_NEXT(dispatchVectorUnary(AbsI64x2));
11662 case uint32_t(SimdOp::F32x4Ceil):
11663 CHECK_NEXT(dispatchVectorUnary(CeilF32x4));
11664 case uint32_t(SimdOp::F32x4Floor):
11665 CHECK_NEXT(dispatchVectorUnary(FloorF32x4));
11666 case uint32_t(SimdOp::F32x4Trunc):
11667 CHECK_NEXT(dispatchVectorUnary(TruncF32x4));
11668 case uint32_t(SimdOp::F32x4Nearest):
11669 CHECK_NEXT(dispatchVectorUnary(NearestF32x4));
11670 case uint32_t(SimdOp::F64x2Ceil):
11671 CHECK_NEXT(dispatchVectorUnary(CeilF64x2));
11672 case uint32_t(SimdOp::F64x2Floor):
11673 CHECK_NEXT(dispatchVectorUnary(FloorF64x2));
11674 case uint32_t(SimdOp::F64x2Trunc):
11675 CHECK_NEXT(dispatchVectorUnary(TruncF64x2));
11676 case uint32_t(SimdOp::F64x2Nearest):
11677 CHECK_NEXT(dispatchVectorUnary(NearestF64x2));
11678 case uint32_t(SimdOp::I16x8ExtaddPairwiseI8x16S):
11679 CHECK_NEXT(dispatchVectorUnary(ExtAddPairwiseI8x16));
11680 case uint32_t(SimdOp::I16x8ExtaddPairwiseI8x16U):
11681 CHECK_NEXT(dispatchVectorUnary(ExtAddPairwiseUI8x16));
11682 case uint32_t(SimdOp::I32x4ExtaddPairwiseI16x8S):
11683 CHECK_NEXT(dispatchVectorUnary(ExtAddPairwiseI16x8));
11684 case uint32_t(SimdOp::I32x4ExtaddPairwiseI16x8U):
11685 CHECK_NEXT(dispatchVectorUnary(ExtAddPairwiseUI16x8));
11686 case uint32_t(SimdOp::I8x16Shl):
11687 CHECK_NEXT(dispatchVectorVariableShift(ShiftLeftI8x16));
11688 case uint32_t(SimdOp::I8x16ShrS):
11689 CHECK_NEXT(dispatchVectorVariableShift(ShiftRightI8x16));
11690 case uint32_t(SimdOp::I8x16ShrU):
11691 CHECK_NEXT(dispatchVectorVariableShift(ShiftRightUI8x16));
11692 case uint32_t(SimdOp::I16x8Shl):
11693 CHECK_NEXT(dispatchVectorVariableShift(ShiftLeftI16x8));
11694 case uint32_t(SimdOp::I16x8ShrS):
11695 CHECK_NEXT(dispatchVectorVariableShift(ShiftRightI16x8));
11696 case uint32_t(SimdOp::I16x8ShrU):
11697 CHECK_NEXT(dispatchVectorVariableShift(ShiftRightUI16x8));
11698 case uint32_t(SimdOp::I32x4Shl):
11699 CHECK_NEXT(dispatchVectorVariableShift(ShiftLeftI32x4));
11700 case uint32_t(SimdOp::I32x4ShrS):
11701 CHECK_NEXT(dispatchVectorVariableShift(ShiftRightI32x4));
11702 case uint32_t(SimdOp::I32x4ShrU):
11703 CHECK_NEXT(dispatchVectorVariableShift(ShiftRightUI32x4));
11704 case uint32_t(SimdOp::I64x2Shl):
11705 CHECK_NEXT(dispatchVectorVariableShift(ShiftLeftI64x2));
11706 case uint32_t(SimdOp::I64x2ShrS):
11707 # if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)
11708 CHECK_NEXT(emitVectorShiftRightI64x2());
11709 # else
11710 CHECK_NEXT(dispatchVectorVariableShift(ShiftRightI64x2));
11711 # endif
11712 case uint32_t(SimdOp::I64x2ShrU):
11713 CHECK_NEXT(dispatchVectorVariableShift(ShiftRightUI64x2));
11714 case uint32_t(SimdOp::V128Bitselect):
11715 CHECK_NEXT(dispatchTernary1(BitselectV128, ValType::V128));
11716 case uint32_t(SimdOp::I8x16Shuffle):
11717 CHECK_NEXT(emitVectorShuffle());
11718 case uint32_t(SimdOp::V128Const): {
11719 V128 v128;
11720 CHECK(iter_.readV128Const(&v128));
11721 if (!deadCode_) {
11722 pushV128(v128);
11723 }
11724 NEXT();
11725 }
11726 case uint32_t(SimdOp::V128Load):
11727 CHECK_NEXT(emitLoad(ValType::V128, Scalar::Simd128));
11728 case uint32_t(SimdOp::V128Load8Splat):
11729 CHECK_NEXT(emitLoadSplat(Scalar::Uint8));
11730 case uint32_t(SimdOp::V128Load16Splat):
11731 CHECK_NEXT(emitLoadSplat(Scalar::Uint16));
11732 case uint32_t(SimdOp::V128Load32Splat):
11733 CHECK_NEXT(emitLoadSplat(Scalar::Uint32));
11734 case uint32_t(SimdOp::V128Load64Splat):
11735 CHECK_NEXT(emitLoadSplat(Scalar::Int64));
11736 case uint32_t(SimdOp::V128Load8x8S):
11737 CHECK_NEXT(emitLoadExtend(Scalar::Int8));
11738 case uint32_t(SimdOp::V128Load8x8U):
11739 CHECK_NEXT(emitLoadExtend(Scalar::Uint8));
11740 case uint32_t(SimdOp::V128Load16x4S):
11741 CHECK_NEXT(emitLoadExtend(Scalar::Int16));
11742 case uint32_t(SimdOp::V128Load16x4U):
11743 CHECK_NEXT(emitLoadExtend(Scalar::Uint16));
11744 case uint32_t(SimdOp::V128Load32x2S):
11745 CHECK_NEXT(emitLoadExtend(Scalar::Int32));
11746 case uint32_t(SimdOp::V128Load32x2U):
11747 CHECK_NEXT(emitLoadExtend(Scalar::Uint32));
11748 case uint32_t(SimdOp::V128Load32Zero):
11749 CHECK_NEXT(emitLoadZero(Scalar::Float32));
11750 case uint32_t(SimdOp::V128Load64Zero):
11751 CHECK_NEXT(emitLoadZero(Scalar::Float64));
11752 case uint32_t(SimdOp::V128Store):
11753 CHECK_NEXT(emitStore(ValType::V128, Scalar::Simd128));
11754 case uint32_t(SimdOp::V128Load8Lane):
11755 CHECK_NEXT(emitLoadLane(1));
11756 case uint32_t(SimdOp::V128Load16Lane):
11757 CHECK_NEXT(emitLoadLane(2));
11758 case uint32_t(SimdOp::V128Load32Lane):
11759 CHECK_NEXT(emitLoadLane(4));
11760 case uint32_t(SimdOp::V128Load64Lane):
11761 CHECK_NEXT(emitLoadLane(8));
11762 case uint32_t(SimdOp::V128Store8Lane):
11763 CHECK_NEXT(emitStoreLane(1));
11764 case uint32_t(SimdOp::V128Store16Lane):
11765 CHECK_NEXT(emitStoreLane(2));
11766 case uint32_t(SimdOp::V128Store32Lane):
11767 CHECK_NEXT(emitStoreLane(4));
11768 case uint32_t(SimdOp::V128Store64Lane):
11769 CHECK_NEXT(emitStoreLane(8));
11770 # ifdef ENABLE_WASM_RELAXED_SIMD
11771 case uint32_t(SimdOp::F32x4RelaxedMadd):
11772 if (!codeMeta_.v128RelaxedEnabled()) {
11773 return iter_.unrecognizedOpcode(&op);
11774 }
11775 CHECK_NEXT(dispatchTernary2(RelaxedMaddF32x4, ValType::V128));
11776 case uint32_t(SimdOp::F32x4RelaxedNmadd):
11777 if (!codeMeta_.v128RelaxedEnabled()) {
11778 return iter_.unrecognizedOpcode(&op);
11779 }
11780 CHECK_NEXT(dispatchTernary2(RelaxedNmaddF32x4, ValType::V128));
11781 case uint32_t(SimdOp::F64x2RelaxedMadd):
11782 if (!codeMeta_.v128RelaxedEnabled()) {
11783 return iter_.unrecognizedOpcode(&op);
11784 }
11785 CHECK_NEXT(dispatchTernary2(RelaxedMaddF64x2, ValType::V128));
11786 case uint32_t(SimdOp::F64x2RelaxedNmadd):
11787 if (!codeMeta_.v128RelaxedEnabled()) {
11788 return iter_.unrecognizedOpcode(&op);
11789 }
11790 CHECK_NEXT(dispatchTernary2(RelaxedNmaddF64x2, ValType::V128));
11791 break;
11792 case uint32_t(SimdOp::I8x16RelaxedLaneSelect):
11793 case uint32_t(SimdOp::I16x8RelaxedLaneSelect):
11794 case uint32_t(SimdOp::I32x4RelaxedLaneSelect):
11795 case uint32_t(SimdOp::I64x2RelaxedLaneSelect):
11796 if (!codeMeta_.v128RelaxedEnabled()) {
11797 return iter_.unrecognizedOpcode(&op);
11798 }
11799 CHECK_NEXT(emitVectorLaneSelect());
11800 case uint32_t(SimdOp::F32x4RelaxedMin):
11801 if (!codeMeta_.v128RelaxedEnabled()) {
11802 return iter_.unrecognizedOpcode(&op);
11803 }
11804 CHECK_NEXT(dispatchVectorBinary(RelaxedMinF32x4));
11805 case uint32_t(SimdOp::F32x4RelaxedMax):
11806 if (!codeMeta_.v128RelaxedEnabled()) {
11807 return iter_.unrecognizedOpcode(&op);
11808 }
11809 CHECK_NEXT(dispatchVectorBinary(RelaxedMaxF32x4));
11810 case uint32_t(SimdOp::F64x2RelaxedMin):
11811 if (!codeMeta_.v128RelaxedEnabled()) {
11812 return iter_.unrecognizedOpcode(&op);
11813 }
11814 CHECK_NEXT(dispatchVectorBinary(RelaxedMinF64x2));
11815 case uint32_t(SimdOp::F64x2RelaxedMax):
11816 if (!codeMeta_.v128RelaxedEnabled()) {
11817 return iter_.unrecognizedOpcode(&op);
11818 }
11819 CHECK_NEXT(dispatchVectorBinary(RelaxedMaxF64x2));
11820 case uint32_t(SimdOp::I32x4RelaxedTruncF32x4S):
11821 if (!codeMeta_.v128RelaxedEnabled()) {
11822 return iter_.unrecognizedOpcode(&op);
11823 }
11824 CHECK_NEXT(dispatchVectorUnary(RelaxedConvertF32x4ToI32x4));
11825 case uint32_t(SimdOp::I32x4RelaxedTruncF32x4U):
11826 if (!codeMeta_.v128RelaxedEnabled()) {
11827 return iter_.unrecognizedOpcode(&op);
11828 }
11829 CHECK_NEXT(dispatchVectorUnary(RelaxedConvertF32x4ToUI32x4));
11830 case uint32_t(SimdOp::I32x4RelaxedTruncF64x2SZero):
11831 if (!codeMeta_.v128RelaxedEnabled()) {
11832 return iter_.unrecognizedOpcode(&op);
11833 }
11834 CHECK_NEXT(dispatchVectorUnary(RelaxedConvertF64x2ToI32x4));
11835 case uint32_t(SimdOp::I32x4RelaxedTruncF64x2UZero):
11836 if (!codeMeta_.v128RelaxedEnabled()) {
11837 return iter_.unrecognizedOpcode(&op);
11838 }
11839 CHECK_NEXT(dispatchVectorUnary(RelaxedConvertF64x2ToUI32x4));
11840 case uint32_t(SimdOp::I8x16RelaxedSwizzle):
11841 if (!codeMeta_.v128RelaxedEnabled()) {
11842 return iter_.unrecognizedOpcode(&op);
11843 }
11844 CHECK_NEXT(dispatchVectorBinary(RelaxedSwizzle));
11845 case uint32_t(SimdOp::I16x8RelaxedQ15MulrS):
11846 if (!codeMeta_.v128RelaxedEnabled()) {
11847 return iter_.unrecognizedOpcode(&op);
11848 }
11849 CHECK_NEXT(dispatchVectorBinary(RelaxedQ15MulrS));
11850 case uint32_t(SimdOp::I16x8RelaxedDotI8x16I7x16S):
11851 if (!codeMeta_.v128RelaxedEnabled()) {
11852 return iter_.unrecognizedOpcode(&op);
11853 }
11854 CHECK_NEXT(dispatchVectorBinary(DotI8x16I7x16S));
11855 case uint32_t(SimdOp::I32x4RelaxedDotI8x16I7x16AddS):
11856 if (!codeMeta_.v128RelaxedEnabled()) {
11857 return iter_.unrecognizedOpcode(&op);
11858 }
11859 CHECK_NEXT(dispatchTernary0(emitDotI8x16I7x16AddS, ValType::V128));
11860 # endif
11861 default:
11862 break;
11863 } // switch (op.b1)
11864 return iter_.unrecognizedOpcode(&op);
11865 }
11866 #endif // ENABLE_WASM_SIMD
11867
11868 // "Miscellaneous" operations
11869 case uint16_t(Op::MiscPrefix): {
11870 switch (op.b1) {
11871 case uint32_t(MiscOp::I32TruncSatF32S):
11872 CHECK_NEXT(
11873 dispatchConversionOOM(emitTruncateF32ToI32<TRUNC_SATURATING>,
11874 ValType::F32, ValType::I32));
11875 case uint32_t(MiscOp::I32TruncSatF32U):
11876 CHECK_NEXT(dispatchConversionOOM(
11877 emitTruncateF32ToI32 < TRUNC_UNSIGNED | TRUNC_SATURATING >,
11878 ValType::F32, ValType::I32));
11879 case uint32_t(MiscOp::I32TruncSatF64S):
11880 CHECK_NEXT(
11881 dispatchConversionOOM(emitTruncateF64ToI32<TRUNC_SATURATING>,
11882 ValType::F64, ValType::I32));
11883 case uint32_t(MiscOp::I32TruncSatF64U):
11884 CHECK_NEXT(dispatchConversionOOM(
11885 emitTruncateF64ToI32 < TRUNC_UNSIGNED | TRUNC_SATURATING >,
11886 ValType::F64, ValType::I32));
11887 case uint32_t(MiscOp::I64TruncSatF32S):
11888 #ifdef RABALDR_FLOAT_TO_I64_CALLOUT
11889 CHECK_NEXT(dispatchCalloutConversionOOM(
11890 emitConvertFloatingToInt64Callout,
11891 SymbolicAddress::SaturatingTruncateDoubleToInt64, ValType::F32,
11892 ValType::I64));
11893 #else
11894 CHECK_NEXT(
11895 dispatchConversionOOM(emitTruncateF32ToI64<TRUNC_SATURATING>,
11896 ValType::F32, ValType::I64));
11897 #endif
11898 case uint32_t(MiscOp::I64TruncSatF32U):
11899 #ifdef RABALDR_FLOAT_TO_I64_CALLOUT
11900 CHECK_NEXT(dispatchCalloutConversionOOM(
11901 emitConvertFloatingToInt64Callout,
11902 SymbolicAddress::SaturatingTruncateDoubleToUint64, ValType::F32,
11903 ValType::I64));
11904 #else
11905 CHECK_NEXT(dispatchConversionOOM(
11906 emitTruncateF32ToI64 < TRUNC_UNSIGNED | TRUNC_SATURATING >,
11907 ValType::F32, ValType::I64));
11908 #endif
11909 case uint32_t(MiscOp::I64TruncSatF64S):
11910 #ifdef RABALDR_FLOAT_TO_I64_CALLOUT
11911 CHECK_NEXT(dispatchCalloutConversionOOM(
11912 emitConvertFloatingToInt64Callout,
11913 SymbolicAddress::SaturatingTruncateDoubleToInt64, ValType::F64,
11914 ValType::I64));
11915 #else
11916 CHECK_NEXT(
11917 dispatchConversionOOM(emitTruncateF64ToI64<TRUNC_SATURATING>,
11918 ValType::F64, ValType::I64));
11919 #endif
11920 case uint32_t(MiscOp::I64TruncSatF64U):
11921 #ifdef RABALDR_FLOAT_TO_I64_CALLOUT
11922 CHECK_NEXT(dispatchCalloutConversionOOM(
11923 emitConvertFloatingToInt64Callout,
11924 SymbolicAddress::SaturatingTruncateDoubleToUint64, ValType::F64,
11925 ValType::I64));
11926 #else
11927 CHECK_NEXT(dispatchConversionOOM(
11928 emitTruncateF64ToI64 < TRUNC_UNSIGNED | TRUNC_SATURATING >,
11929 ValType::F64, ValType::I64));
11930 #endif
11931 case uint32_t(MiscOp::MemoryCopy):
11932 CHECK_NEXT(emitMemCopy());
11933 case uint32_t(MiscOp::DataDrop):
11934 CHECK_NEXT(emitDataOrElemDrop(/*isData=*/true));
11935 case uint32_t(MiscOp::MemoryFill):
11936 CHECK_NEXT(emitMemFill());
11937 #ifdef ENABLE_WASM_MEMORY_CONTROL
11938 case uint32_t(MiscOp::MemoryDiscard): {
11939 if (!codeMeta_.memoryControlEnabled()) {
11940 return iter_.unrecognizedOpcode(&op);
11941 }
11942 CHECK_NEXT(emitMemDiscard());
11943 }
11944 #endif
11945 case uint32_t(MiscOp::MemoryInit):
11946 CHECK_NEXT(emitMemInit());
11947 case uint32_t(MiscOp::TableCopy):
11948 CHECK_NEXT(emitTableCopy());
11949 case uint32_t(MiscOp::ElemDrop):
11950 CHECK_NEXT(emitDataOrElemDrop(/*isData=*/false));
11951 case uint32_t(MiscOp::TableInit):
11952 CHECK_NEXT(emitTableInit());
11953 case uint32_t(MiscOp::TableFill):
11954 CHECK_NEXT(emitTableFill());
11955 case uint32_t(MiscOp::TableGrow):
11956 CHECK_NEXT(emitTableGrow());
11957 case uint32_t(MiscOp::TableSize):
11958 CHECK_NEXT(emitTableSize());
11959 default:
11960 break;
11961 } // switch (op.b1)
11962 return iter_.unrecognizedOpcode(&op);
11963 }
11964
11965 // Thread operations
11966 case uint16_t(Op::ThreadPrefix): {
11967 // Though thread ops can be used on nonshared memories, we make them
11968 // unavailable if shared memory has been disabled in the prefs, for
11969 // maximum predictability and safety and consistency with JS.
11970 if (codeMeta_.sharedMemoryEnabled() == Shareable::False) {
11971 return iter_.unrecognizedOpcode(&op);
11972 }
11973 switch (op.b1) {
11974 case uint32_t(ThreadOp::Notify):
11975 CHECK_NEXT(emitNotify());
11976
11977 case uint32_t(ThreadOp::I32Wait):
11978 CHECK_NEXT(emitWait(ValType::I32, 4));
11979 case uint32_t(ThreadOp::I64Wait):
11980 CHECK_NEXT(emitWait(ValType::I64, 8));
11981 case uint32_t(ThreadOp::Fence):
11982 CHECK_NEXT(emitFence());
11983
11984 case uint32_t(ThreadOp::I32AtomicLoad):
11985 CHECK_NEXT(emitAtomicLoad(ValType::I32, Scalar::Int32));
11986 case uint32_t(ThreadOp::I64AtomicLoad):
11987 CHECK_NEXT(emitAtomicLoad(ValType::I64, Scalar::Int64));
11988 case uint32_t(ThreadOp::I32AtomicLoad8U):
11989 CHECK_NEXT(emitAtomicLoad(ValType::I32, Scalar::Uint8));
11990 case uint32_t(ThreadOp::I32AtomicLoad16U):
11991 CHECK_NEXT(emitAtomicLoad(ValType::I32, Scalar::Uint16));
11992 case uint32_t(ThreadOp::I64AtomicLoad8U):
11993 CHECK_NEXT(emitAtomicLoad(ValType::I64, Scalar::Uint8));
11994 case uint32_t(ThreadOp::I64AtomicLoad16U):
11995 CHECK_NEXT(emitAtomicLoad(ValType::I64, Scalar::Uint16));
11996 case uint32_t(ThreadOp::I64AtomicLoad32U):
11997 CHECK_NEXT(emitAtomicLoad(ValType::I64, Scalar::Uint32));
11998
11999 case uint32_t(ThreadOp::I32AtomicStore):
12000 CHECK_NEXT(emitAtomicStore(ValType::I32, Scalar::Int32));
12001 case uint32_t(ThreadOp::I64AtomicStore):
12002 CHECK_NEXT(emitAtomicStore(ValType::I64, Scalar::Int64));
12003 case uint32_t(ThreadOp::I32AtomicStore8U):
12004 CHECK_NEXT(emitAtomicStore(ValType::I32, Scalar::Uint8));
12005 case uint32_t(ThreadOp::I32AtomicStore16U):
12006 CHECK_NEXT(emitAtomicStore(ValType::I32, Scalar::Uint16));
12007 case uint32_t(ThreadOp::I64AtomicStore8U):
12008 CHECK_NEXT(emitAtomicStore(ValType::I64, Scalar::Uint8));
12009 case uint32_t(ThreadOp::I64AtomicStore16U):
12010 CHECK_NEXT(emitAtomicStore(ValType::I64, Scalar::Uint16));
12011 case uint32_t(ThreadOp::I64AtomicStore32U):
12012 CHECK_NEXT(emitAtomicStore(ValType::I64, Scalar::Uint32));
12013
12014 case uint32_t(ThreadOp::I32AtomicAdd):
12015 CHECK_NEXT(
12016 emitAtomicRMW(ValType::I32, Scalar::Int32, AtomicOp::Add));
12017 case uint32_t(ThreadOp::I64AtomicAdd):
12018 CHECK_NEXT(
12019 emitAtomicRMW(ValType::I64, Scalar::Int64, AtomicOp::Add));
12020 case uint32_t(ThreadOp::I32AtomicAdd8U):
12021 CHECK_NEXT(
12022 emitAtomicRMW(ValType::I32, Scalar::Uint8, AtomicOp::Add));
12023 case uint32_t(ThreadOp::I32AtomicAdd16U):
12024 CHECK_NEXT(
12025 emitAtomicRMW(ValType::I32, Scalar::Uint16, AtomicOp::Add));
12026 case uint32_t(ThreadOp::I64AtomicAdd8U):
12027 CHECK_NEXT(
12028 emitAtomicRMW(ValType::I64, Scalar::Uint8, AtomicOp::Add));
12029 case uint32_t(ThreadOp::I64AtomicAdd16U):
12030 CHECK_NEXT(
12031 emitAtomicRMW(ValType::I64, Scalar::Uint16, AtomicOp::Add));
12032 case uint32_t(ThreadOp::I64AtomicAdd32U):
12033 CHECK_NEXT(
12034 emitAtomicRMW(ValType::I64, Scalar::Uint32, AtomicOp::Add));
12035
12036 case uint32_t(ThreadOp::I32AtomicSub):
12037 CHECK_NEXT(
12038 emitAtomicRMW(ValType::I32, Scalar::Int32, AtomicOp::Sub));
12039 case uint32_t(ThreadOp::I64AtomicSub):
12040 CHECK_NEXT(
12041 emitAtomicRMW(ValType::I64, Scalar::Int64, AtomicOp::Sub));
12042 case uint32_t(ThreadOp::I32AtomicSub8U):
12043 CHECK_NEXT(
12044 emitAtomicRMW(ValType::I32, Scalar::Uint8, AtomicOp::Sub));
12045 case uint32_t(ThreadOp::I32AtomicSub16U):
12046 CHECK_NEXT(
12047 emitAtomicRMW(ValType::I32, Scalar::Uint16, AtomicOp::Sub));
12048 case uint32_t(ThreadOp::I64AtomicSub8U):
12049 CHECK_NEXT(
12050 emitAtomicRMW(ValType::I64, Scalar::Uint8, AtomicOp::Sub));
12051 case uint32_t(ThreadOp::I64AtomicSub16U):
12052 CHECK_NEXT(
12053 emitAtomicRMW(ValType::I64, Scalar::Uint16, AtomicOp::Sub));
12054 case uint32_t(ThreadOp::I64AtomicSub32U):
12055 CHECK_NEXT(
12056 emitAtomicRMW(ValType::I64, Scalar::Uint32, AtomicOp::Sub));
12057
12058 case uint32_t(ThreadOp::I32AtomicAnd):
12059 CHECK_NEXT(
12060 emitAtomicRMW(ValType::I32, Scalar::Int32, AtomicOp::And));
12061 case uint32_t(ThreadOp::I64AtomicAnd):
12062 CHECK_NEXT(
12063 emitAtomicRMW(ValType::I64, Scalar::Int64, AtomicOp::And));
12064 case uint32_t(ThreadOp::I32AtomicAnd8U):
12065 CHECK_NEXT(
12066 emitAtomicRMW(ValType::I32, Scalar::Uint8, AtomicOp::And));
12067 case uint32_t(ThreadOp::I32AtomicAnd16U):
12068 CHECK_NEXT(
12069 emitAtomicRMW(ValType::I32, Scalar::Uint16, AtomicOp::And));
12070 case uint32_t(ThreadOp::I64AtomicAnd8U):
12071 CHECK_NEXT(
12072 emitAtomicRMW(ValType::I64, Scalar::Uint8, AtomicOp::And));
12073 case uint32_t(ThreadOp::I64AtomicAnd16U):
12074 CHECK_NEXT(
12075 emitAtomicRMW(ValType::I64, Scalar::Uint16, AtomicOp::And));
12076 case uint32_t(ThreadOp::I64AtomicAnd32U):
12077 CHECK_NEXT(
12078 emitAtomicRMW(ValType::I64, Scalar::Uint32, AtomicOp::And));
12079
12080 case uint32_t(ThreadOp::I32AtomicOr):
12081 CHECK_NEXT(
12082 emitAtomicRMW(ValType::I32, Scalar::Int32, AtomicOp::Or));
12083 case uint32_t(ThreadOp::I64AtomicOr):
12084 CHECK_NEXT(
12085 emitAtomicRMW(ValType::I64, Scalar::Int64, AtomicOp::Or));
12086 case uint32_t(ThreadOp::I32AtomicOr8U):
12087 CHECK_NEXT(
12088 emitAtomicRMW(ValType::I32, Scalar::Uint8, AtomicOp::Or));
12089 case uint32_t(ThreadOp::I32AtomicOr16U):
12090 CHECK_NEXT(
12091 emitAtomicRMW(ValType::I32, Scalar::Uint16, AtomicOp::Or));
12092 case uint32_t(ThreadOp::I64AtomicOr8U):
12093 CHECK_NEXT(
12094 emitAtomicRMW(ValType::I64, Scalar::Uint8, AtomicOp::Or));
12095 case uint32_t(ThreadOp::I64AtomicOr16U):
12096 CHECK_NEXT(
12097 emitAtomicRMW(ValType::I64, Scalar::Uint16, AtomicOp::Or));
12098 case uint32_t(ThreadOp::I64AtomicOr32U):
12099 CHECK_NEXT(
12100 emitAtomicRMW(ValType::I64, Scalar::Uint32, AtomicOp::Or));
12101
12102 case uint32_t(ThreadOp::I32AtomicXor):
12103 CHECK_NEXT(
12104 emitAtomicRMW(ValType::I32, Scalar::Int32, AtomicOp::Xor));
12105 case uint32_t(ThreadOp::I64AtomicXor):
12106 CHECK_NEXT(
12107 emitAtomicRMW(ValType::I64, Scalar::Int64, AtomicOp::Xor));
12108 case uint32_t(ThreadOp::I32AtomicXor8U):
12109 CHECK_NEXT(
12110 emitAtomicRMW(ValType::I32, Scalar::Uint8, AtomicOp::Xor));
12111 case uint32_t(ThreadOp::I32AtomicXor16U):
12112 CHECK_NEXT(
12113 emitAtomicRMW(ValType::I32, Scalar::Uint16, AtomicOp::Xor));
12114 case uint32_t(ThreadOp::I64AtomicXor8U):
12115 CHECK_NEXT(
12116 emitAtomicRMW(ValType::I64, Scalar::Uint8, AtomicOp::Xor));
12117 case uint32_t(ThreadOp::I64AtomicXor16U):
12118 CHECK_NEXT(
12119 emitAtomicRMW(ValType::I64, Scalar::Uint16, AtomicOp::Xor));
12120 case uint32_t(ThreadOp::I64AtomicXor32U):
12121 CHECK_NEXT(
12122 emitAtomicRMW(ValType::I64, Scalar::Uint32, AtomicOp::Xor));
12123
12124 case uint32_t(ThreadOp::I32AtomicXchg):
12125 CHECK_NEXT(emitAtomicXchg(ValType::I32, Scalar::Int32));
12126 case uint32_t(ThreadOp::I64AtomicXchg):
12127 CHECK_NEXT(emitAtomicXchg(ValType::I64, Scalar::Int64));
12128 case uint32_t(ThreadOp::I32AtomicXchg8U):
12129 CHECK_NEXT(emitAtomicXchg(ValType::I32, Scalar::Uint8));
12130 case uint32_t(ThreadOp::I32AtomicXchg16U):
12131 CHECK_NEXT(emitAtomicXchg(ValType::I32, Scalar::Uint16));
12132 case uint32_t(ThreadOp::I64AtomicXchg8U):
12133 CHECK_NEXT(emitAtomicXchg(ValType::I64, Scalar::Uint8));
12134 case uint32_t(ThreadOp::I64AtomicXchg16U):
12135 CHECK_NEXT(emitAtomicXchg(ValType::I64, Scalar::Uint16));
12136 case uint32_t(ThreadOp::I64AtomicXchg32U):
12137 CHECK_NEXT(emitAtomicXchg(ValType::I64, Scalar::Uint32));
12138
12139 case uint32_t(ThreadOp::I32AtomicCmpXchg):
12140 CHECK_NEXT(emitAtomicCmpXchg(ValType::I32, Scalar::Int32));
12141 case uint32_t(ThreadOp::I64AtomicCmpXchg):
12142 CHECK_NEXT(emitAtomicCmpXchg(ValType::I64, Scalar::Int64));
12143 case uint32_t(ThreadOp::I32AtomicCmpXchg8U):
12144 CHECK_NEXT(emitAtomicCmpXchg(ValType::I32, Scalar::Uint8));
12145 case uint32_t(ThreadOp::I32AtomicCmpXchg16U):
12146 CHECK_NEXT(emitAtomicCmpXchg(ValType::I32, Scalar::Uint16));
12147 case uint32_t(ThreadOp::I64AtomicCmpXchg8U):
12148 CHECK_NEXT(emitAtomicCmpXchg(ValType::I64, Scalar::Uint8));
12149 case uint32_t(ThreadOp::I64AtomicCmpXchg16U):
12150 CHECK_NEXT(emitAtomicCmpXchg(ValType::I64, Scalar::Uint16));
12151 case uint32_t(ThreadOp::I64AtomicCmpXchg32U):
12152 CHECK_NEXT(emitAtomicCmpXchg(ValType::I64, Scalar::Uint32));
12153
12154 default:
12155 return iter_.unrecognizedOpcode(&op);
12156 }
12157 break;
12158 }
12159
12160 // asm.js and other private operations
12161 case uint16_t(Op::MozPrefix): {
12162 if (op.b1 != uint32_t(MozOp::CallBuiltinModuleFunc) ||
12163 !codeMeta_.isBuiltinModule()) {
12164 return iter_.unrecognizedOpcode(&op);
12165 }
12166 // Call a private builtin module func
12167 CHECK_NEXT(emitCallBuiltinModuleFunc());
12168 }
12169
12170 default:
12171 return iter_.unrecognizedOpcode(&op);
12172 }
12173
12174 #undef CHECK
12175 #undef NEXT
12176 #undef CHECK_NEXT
12177 #undef CHECK_POINTER_COUNT
12178 #undef dispatchBinary0
12179 #undef dispatchBinary1
12180 #undef dispatchBinary2
12181 #undef dispatchBinary3
12182 #undef dispatchUnary0
12183 #undef dispatchUnary1
12184 #undef dispatchUnary2
12185 #undef dispatchComparison0
12186 #undef dispatchConversion0
12187 #undef dispatchConversion1
12188 #undef dispatchConversionOOM
12189 #undef dispatchCalloutConversionOOM
12190 #undef dispatchIntDivCallout
12191 #undef dispatchVectorBinary
12192 #undef dispatchVectorUnary
12193 #undef dispatchVectorComparison
12194 #undef dispatchExtractLane
12195 #undef dispatchReplaceLane
12196 #undef dispatchSplat
12197 #undef dispatchVectorReduction
12198
12199 MOZ_CRASH("unreachable");
12200 }
12201
12202 MOZ_CRASH("unreachable");
12203 }
12204
12205 //////////////////////////////////////////////////////////////////////////////
12206 //
12207 // Various helpers.
12208
12209 void BaseCompiler::assertResultRegistersAvailable(ResultType type) {
12210 #ifdef DEBUG
12211 for (ABIResultIter iter(type); !iter.done(); iter.next()) {
12212 ABIResult result = iter.cur();
12213 if (!result.inRegister()) {
12214 return;
12215 }
12216 switch (result.type().kind()) {
12217 case ValType::I32:
12218 MOZ_ASSERT(isAvailableI32(RegI32(result.gpr())));
12219 break;
12220 case ValType::I64:
12221 MOZ_ASSERT(isAvailableI64(RegI64(result.gpr64())));
12222 break;
12223 case ValType::V128:
12224 # ifdef ENABLE_WASM_SIMD
12225 MOZ_ASSERT(isAvailableV128(RegV128(result.fpr())));
12226 break;
12227 # else
12228 MOZ_CRASH("No SIMD support");
12229 # endif
12230 case ValType::F32:
12231 MOZ_ASSERT(isAvailableF32(RegF32(result.fpr())));
12232 break;
12233 case ValType::F64:
12234 MOZ_ASSERT(isAvailableF64(RegF64(result.fpr())));
12235 break;
12236 case ValType::Ref:
12237 MOZ_ASSERT(isAvailableRef(RegRef(result.gpr())));
12238 break;
12239 }
12240 }
12241 #endif
12242 }
12243
12244 void BaseCompiler::saveTempPtr(const RegPtr& r) {
12245 MOZ_ASSERT(!ra.isAvailablePtr(r));
12246 fr.pushGPR(r);
12247 ra.freePtr(r);
12248 MOZ_ASSERT(ra.isAvailablePtr(r));
12249 }
12250
12251 void BaseCompiler::restoreTempPtr(const RegPtr& r) {
12252 MOZ_ASSERT(ra.isAvailablePtr(r));
12253 ra.needPtr(r);
12254 fr.popGPR(r);
12255 MOZ_ASSERT(!ra.isAvailablePtr(r));
12256 }
12257
12258 #ifdef DEBUG
12259 void BaseCompiler::performRegisterLeakCheck() {
12260 BaseRegAlloc::LeakCheck check(ra);
12261 for (auto& item : stk_) {
12262 switch (item.kind_) {
12263 case Stk::RegisterI32:
12264 check.addKnownI32(item.i32reg());
12265 break;
12266 case Stk::RegisterI64:
12267 check.addKnownI64(item.i64reg());
12268 break;
12269 case Stk::RegisterF32:
12270 check.addKnownF32(item.f32reg());
12271 break;
12272 case Stk::RegisterF64:
12273 check.addKnownF64(item.f64reg());
12274 break;
12275 # ifdef ENABLE_WASM_SIMD
12276 case Stk::RegisterV128:
12277 check.addKnownV128(item.v128reg());
12278 break;
12279 # endif
12280 case Stk::RegisterRef:
12281 check.addKnownRef(item.refReg());
12282 break;
12283 default:
12284 break;
12285 }
12286 }
12287 }
12288
12289 void BaseCompiler::assertStackInvariants() const {
12290 if (deadCode_) {
12291 // Nonlocal control flow can pass values in stack locations in a way that
12292 // isn't accounted for by the value stack. In dead code, which occurs
12293 // after unconditional non-local control flow, there is no invariant to
12294 // assert.
12295 return;
12296 }
12297 size_t size = 0;
12298 for (const Stk& v : stk_) {
12299 switch (v.kind()) {
12300 case Stk::MemRef:
12301 size += BaseStackFrame::StackSizeOfPtr;
12302 break;
12303 case Stk::MemI32:
12304 size += BaseStackFrame::StackSizeOfPtr;
12305 break;
12306 case Stk::MemI64:
12307 size += BaseStackFrame::StackSizeOfInt64;
12308 break;
12309 case Stk::MemF64:
12310 size += BaseStackFrame::StackSizeOfDouble;
12311 break;
12312 case Stk::MemF32:
12313 size += BaseStackFrame::StackSizeOfFloat;
12314 break;
12315 # ifdef ENABLE_WASM_SIMD
12316 case Stk::MemV128:
12317 size += BaseStackFrame::StackSizeOfV128;
12318 break;
12319 # endif
12320 default:
12321 MOZ_ASSERT(!v.isMem());
12322 break;
12323 }
12324 }
12325 MOZ_ASSERT(size == fr.dynamicHeight());
12326 }
12327
12328 void BaseCompiler::showStack(const char* who) const {
12329 fprintf(stderr, "Stack at %s {{\n", who);
12330 size_t n = 0;
12331 for (const Stk& elem : stk_) {
12332 fprintf(stderr, " [%zu] ", n++);
12333 elem.showStackElem();
12334 fprintf(stderr, "\n");
12335 }
12336 fprintf(stderr, "}}\n");
12337 }
12338 #endif
12339
12340 //////////////////////////////////////////////////////////////////////////////
12341 //
12342 // Main compilation logic.
12343
12344 bool BaseCompiler::emitFunction() {
12345 AutoCreatedBy acb(masm, "(wasm)BaseCompiler::emitFunction");
12346
12347 if (!beginFunction()) {
12348 return false;
12349 }
12350
12351 if (!emitBody()) {
12352 return false;
12353 }
12354
12355 return endFunction();
12356 }
12357
12358 BaseCompiler::BaseCompiler(const CodeMetadata& codeMeta,
12359 const CompilerEnvironment& compilerEnv,
12360 const FuncCompileInput& func,
12361 const ValTypeVector& locals,
12362 const RegisterOffsets& trapExitLayout,
12363 size_t trapExitLayoutNumWords, Decoder& decoder,
12364 StkVector& stkSource, TempAllocator* alloc,
12365 MacroAssembler* masm, StackMaps* stackMaps)
12366 : // Environment
12367 codeMeta_(codeMeta),
12368 compilerEnv_(compilerEnv),
12369 func_(func),
12370 locals_(locals),
12371 previousBreakablePoint_(UINT32_MAX),
12372 stkSource_(stkSource),
12373 // Output-only data structures
12374 alloc_(alloc->fallible()),
12375 masm(*masm),
12376 // Compilation state
12377 decoder_(decoder),
12378 iter_(codeMeta, decoder, locals),
12379 fr(*masm),
12380 stackMapGenerator_(stackMaps, trapExitLayout, trapExitLayoutNumWords,
12381 *masm),
12382 deadCode_(false),
12383 // Init value is selected to ensure proper logic in finishTryNote.
12384 mostRecentFinishedTryNoteIndex_(0),
12385 bceSafe_(0),
12386 latentOp_(LatentOp::None),
12387 latentType_(ValType::I32),
12388 latentIntCmp_(Assembler::Equal),
12389 latentDoubleCmp_(Assembler::DoubleEqual) {
12390 // Our caller, BaselineCompileFunctions, will lend us the vector contents to
12391 // use for the eval stack. To get hold of those contents, we'll temporarily
12392 // installing an empty one in its place.
12393 MOZ_ASSERT(stk_.empty());
12394 stk_.swap(stkSource_);
12395
12396 // Assuming that previously processed wasm functions are well formed, the
12397 // eval stack should now be empty. But empty it anyway; any non-emptyness
12398 // at this point will cause chaos.
12399 stk_.clear();
12400 }
12401
12402 BaseCompiler::~BaseCompiler() {
12403 stk_.swap(stkSource_);
12404 // We've returned the eval stack vector contents to our caller,
12405 // BaselineCompileFunctions. We expect the vector we get in return to be
12406 // empty since that's what we swapped for the stack vector in our
12407 // constructor.
12408 MOZ_ASSERT(stk_.empty());
12409 }
12410
12411 bool BaseCompiler::init() {
12412 // We may lift this restriction in the future.
12413 for (uint32_t memoryIndex = 0; memoryIndex < codeMeta_.memories.length();
12414 memoryIndex++) {
12415 MOZ_ASSERT_IF(isMem64(memoryIndex),
12416 !codeMeta_.hugeMemoryEnabled(memoryIndex));
12417 }
12418 // asm.js is not supported in baseline
12419 MOZ_ASSERT(!codeMeta_.isAsmJS());
12420 // Only asm.js modules have call site line numbers
12421 MOZ_ASSERT(func_.callSiteLineNums.empty());
12422
12423 ra.init(this);
12424
12425 if (!SigD_.append(ValType::F64)) {
12426 return false;
12427 }
12428 if (!SigF_.append(ValType::F32)) {
12429 return false;
12430 }
12431
12432 ArgTypeVector args(funcType());
12433 return fr.setupLocals(locals_, args, compilerEnv_.debugEnabled(),
12434 &localInfo_);
12435 }
12436
12437 FuncOffsets BaseCompiler::finish() {
12438 MOZ_ASSERT(iter_.done());
12439 MOZ_ASSERT(stk_.empty());
12440 MOZ_ASSERT(stackMapGenerator_.memRefsOnStk == 0);
12441
12442 masm.flushBuffer();
12443
12444 return offsets_;
12445 }
12446
12447 } // namespace wasm
12448 } // namespace js
12449
12450 bool js::wasm::BaselinePlatformSupport() {
12451 #if defined(JS_CODEGEN_ARM)
12452 // Simplifying assumption: require SDIV and UDIV.
12453 //
12454 // I have no good data on ARM populations allowing me to say that
12455 // X% of devices in the market implement SDIV and UDIV. However,
12456 // they are definitely implemented on the Cortex-A7 and Cortex-A15
12457 // and on all ARMv8 systems.
12458 if (!ARMFlags::HasIDIV()) {
12459 return false;
12460 }
12461 #endif
12462 #if defined(JS_CODEGEN_X64) || defined(JS_CODEGEN_X86) || \
12463 defined(JS_CODEGEN_ARM) || defined(JS_CODEGEN_ARM64) || \
12464 defined(JS_CODEGEN_MIPS64) || defined(JS_CODEGEN_LOONG64) || \
12465 defined(JS_CODEGEN_RISCV64)
12466 return true;
12467 #else
12468 return false;
12469 #endif
12470 }
12471
12472 bool js::wasm::BaselineCompileFunctions(const CodeMetadata& codeMeta,
12473 const CompilerEnvironment& compilerEnv,
12474 LifoAlloc& lifo,
12475 const FuncCompileInputVector& inputs,
12476 CompiledCode* code,
12477 UniqueChars* error) {
12478 MOZ_ASSERT(compilerEnv.tier() == Tier::Baseline);
12479 MOZ_ASSERT(codeMeta.kind == ModuleKind::Wasm);
12480
12481 // The MacroAssembler will sometimes access the jitContext.
12482
12483 TempAllocator alloc(&lifo);
12484 JitContext jitContext;
12485 MOZ_ASSERT(IsCompilingWasm());
12486 WasmMacroAssembler masm(alloc);
12487
12488 // Swap in already-allocated empty vectors to avoid malloc/free.
12489 MOZ_ASSERT(code->empty());
12490 if (!code->swap(masm)) {
12491 return false;
12492 }
12493
12494 // Create a description of the stack layout created by GenerateTrapExit().
12495 RegisterOffsets trapExitLayout;
12496 size_t trapExitLayoutNumWords;
12497 GenerateTrapExitRegisterOffsets(&trapExitLayout, &trapExitLayoutNumWords);
12498
12499 // The compiler's operand stack. We reuse it across all functions so as to
12500 // avoid malloc/free. Presize it to 128 elements in the hope of avoiding
12501 // reallocation later.
12502 StkVector stk;
12503 if (!stk.reserve(128)) {
12504 return false;
12505 }
12506
12507 for (const FuncCompileInput& func : inputs) {
12508 Decoder d(func.begin, func.end, func.lineOrBytecode, error);
12509
12510 // Build the local types vector.
12511
12512 ValTypeVector locals;
12513 if (!DecodeLocalEntriesWithParams(d, codeMeta, func.index, &locals)) {
12514 return false;
12515 }
12516
12517 size_t unwindInfoBefore = masm.codeRangeUnwindInfos().length();
12518 size_t callRefMetricsBefore = masm.callRefMetricsPatches().length();
12519 size_t allocSitesBefore = masm.allocSitesPatches().length();
12520
12521 // One-pass baseline compilation.
12522
12523 BaseCompiler f(codeMeta, compilerEnv, func, locals, trapExitLayout,
12524 trapExitLayoutNumWords, d, stk, &alloc, &masm,
12525 &code->stackMaps);
12526 if (!f.init()) {
12527 return false;
12528 }
12529 if (!f.emitFunction()) {
12530 return false;
12531 }
12532 FuncOffsets offsets(f.finish());
12533 bool hasUnwindInfo =
12534 unwindInfoBefore != masm.codeRangeUnwindInfos().length();
12535 size_t callRefMetricsAfter = masm.callRefMetricsPatches().length();
12536 size_t callRefMetricsLength = callRefMetricsAfter - callRefMetricsBefore;
12537 size_t allocSitesAfter = masm.allocSitesPatches().length();
12538 size_t allocSitesLength = allocSitesAfter - allocSitesBefore;
12539
12540 // Record this function's code range
12541 if (!code->codeRanges.emplaceBack(func.index, offsets, hasUnwindInfo)) {
12542 return false;
12543 }
12544
12545 // Record this function's specific feature usage
12546 if (!code->funcs.emplaceBack(
12547 func.index, f.iter_.featureUsage(),
12548 CallRefMetricsRange(callRefMetricsBefore, callRefMetricsLength),
12549 AllocSitesRange(allocSitesBefore, allocSitesLength))) {
12550 return false;
12551 }
12552
12553 if (PerfEnabled()) {
12554 if (!code->funcBaselineSpewers.emplaceBack(func.index,
12555 std::move(f.perfSpewer_))) {
12556 return false;
12557 }
12558 }
12559
12560 // Accumulate observed feature usage
12561 code->featureUsage |= f.iter_.featureUsage();
12562 }
12563
12564 masm.finish();
12565 if (masm.oom()) {
12566 return false;
12567 }
12568
12569 return code->swap(masm);
12570 }