Debian Codegraph @

js/src/jit/CodeGenerator.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 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "jit/CodeGenerator.h"
8
9 #include "mozilla/Assertions.h"
10 #include "mozilla/Casting.h"
11 #include "mozilla/DebugOnly.h"
12 #include "mozilla/EndianUtils.h"
13 #include "mozilla/EnumeratedArray.h"
14 #include "mozilla/EnumeratedRange.h"
15 #include "mozilla/EnumSet.h"
16 #include "mozilla/IntegerTypeTraits.h"
17 #include "mozilla/Latin1.h"
18 #include "mozilla/MathAlgorithms.h"
19 #include "mozilla/ScopeExit.h"
20 #include "mozilla/SIMD.h"
21
22 #include <limits>
23 #include <type_traits>
24 #include <utility>
25
26 #include "jslibmath.h"
27 #include "jsmath.h"
28 #include "jsnum.h"
29
30 #include "builtin/MapObject.h"
31 #include "builtin/RegExp.h"
32 #include "builtin/String.h"
33 #include "irregexp/RegExpTypes.h"
34 #include "jit/ABIArgGenerator.h"
35 #include "jit/CompileInfo.h"
36 #include "jit/InlineScriptTree.h"
37 #include "jit/Invalidation.h"
38 #include "jit/IonGenericCallStub.h"
39 #include "jit/IonIC.h"
40 #include "jit/IonScript.h"
41 #include "jit/JitcodeMap.h"
42 #include "jit/JitFrames.h"
43 #include "jit/JitRuntime.h"
44 #include "jit/JitSpewer.h"
45 #include "jit/JitZone.h"
46 #include "jit/Linker.h"
47 #include "jit/MIRGenerator.h"
48 #include "jit/MoveEmitter.h"
49 #include "jit/RangeAnalysis.h"
50 #include "jit/RegExpStubConstants.h"
51 #include "jit/SafepointIndex.h"
52 #include "jit/SharedICHelpers.h"
53 #include "jit/SharedICRegisters.h"
54 #include "jit/VMFunctions.h"
55 #include "jit/WarpSnapshot.h"
56 #include "js/ColumnNumber.h" // JS::LimitedColumnNumberOneOrigin
57 #include "js/experimental/JitInfo.h" // JSJit{Getter,Setter}CallArgs, JSJitMethodCallArgsTraits, JSJitInfo
58 #include "js/friend/DOMProxy.h" // JS::ExpandoAndGeneration
59 #include "js/RegExpFlags.h" // JS::RegExpFlag
60 #include "js/ScalarType.h" // js::Scalar::Type
61 #include "proxy/DOMProxy.h"
62 #include "proxy/ScriptedProxyHandler.h"
63 #include "util/CheckedArithmetic.h"
64 #include "util/DifferentialTesting.h"
65 #include "util/Unicode.h"
66 #include "vm/ArrayBufferViewObject.h"
67 #include "vm/AsyncFunction.h"
68 #include "vm/AsyncIteration.h"
69 #include "vm/BuiltinObjectKind.h"
70 #include "vm/ConstantCompareOperand.h"
71 #include "vm/FunctionFlags.h" // js::FunctionFlags
72 #include "vm/Interpreter.h"
73 #include "vm/JSAtomUtils.h" // AtomizeString
74 #include "vm/MatchPairs.h"
75 #include "vm/RegExpObject.h"
76 #include "vm/RegExpStatics.h"
77 #include "vm/StaticStrings.h"
78 #include "vm/StringObject.h"
79 #include "vm/StringType.h"
80 #include "vm/TypedArrayObject.h"
81 #include "wasm/WasmCodegenConstants.h"
82 #include "wasm/WasmPI.h"
83 #include "wasm/WasmValType.h"
84 #ifdef MOZ_VTUNE
85 # include "vtune/VTuneWrapper.h"
86 #endif
87 #include "wasm/WasmBinary.h"
88 #include "wasm/WasmGC.h"
89 #include "wasm/WasmGcObject.h"
90 #include "wasm/WasmStubs.h"
91
92 #include "builtin/Boolean-inl.h"
93 #include "jit/MacroAssembler-inl.h"
94 #include "jit/shared/CodeGenerator-shared-inl.h"
95 #include "jit/TemplateObject-inl.h"
96 #include "jit/VMFunctionList-inl.h"
97 #include "vm/BytecodeUtil-inl.h"
98 #include "vm/JSScript-inl.h"
99 #include "wasm/WasmInstance-inl.h"
100
101 using namespace js;
102 using namespace js::jit;
103
104 using mozilla::CheckedUint32;
105 using mozilla::DebugOnly;
106 using mozilla::FloatingPoint;
107 using mozilla::NegativeInfinity;
108 using mozilla::PositiveInfinity;
109
110 using JS::ExpandoAndGeneration;
111
112 namespace js {
113 namespace jit {
114
115 #ifdef CHECK_OSIPOINT_REGISTERS
116 template <class Op>
117 static void HandleRegisterDump(Op op, MacroAssembler& masm,
118 LiveRegisterSet liveRegs, Register activation,
119 Register scratch) {
120 const size_t baseOffset = JitActivation::offsetOfRegs();
121
122 // Handle live GPRs.
123 for (GeneralRegisterIterator iter(liveRegs.gprs()); iter.more(); ++iter) {
124 Register reg = *iter;
125 Address dump(activation, baseOffset + RegisterDump::offsetOfRegister(reg));
126
127 if (reg == activation) {
128 // To use the original value of the activation register (that's
129 // now on top of the stack), we need the scratch register.
130 masm.push(scratch);
131 masm.loadPtr(Address(masm.getStackPointer(), sizeof(uintptr_t)), scratch);
132 op(scratch, dump);
133 masm.pop(scratch);
134 } else {
135 op(reg, dump);
136 }
137 }
138
139 // Handle live FPRs.
140 for (FloatRegisterIterator iter(liveRegs.fpus()); iter.more(); ++iter) {
141 FloatRegister reg = *iter;
142 Address dump(activation, baseOffset + RegisterDump::offsetOfRegister(reg));
143 op(reg, dump);
144 }
145 }
146
147 class StoreOp {
148 MacroAssembler& masm;
149
150 public:
151 explicit StoreOp(MacroAssembler& masm) : masm(masm) {}
152
153 void operator()(Register reg, Address dump) { masm.storePtr(reg, dump); }
154 void operator()(FloatRegister reg, Address dump) {
155 if (reg.isDouble()) {
156 masm.storeDouble(reg, dump);
157 } else if (reg.isSingle()) {
158 masm.storeFloat32(reg, dump);
159 } else if (reg.isSimd128()) {
160 MOZ_CRASH("Unexpected case for SIMD");
161 } else {
162 MOZ_CRASH("Unexpected register type.");
163 }
164 }
165 };
166
167 class VerifyOp {
168 MacroAssembler& masm;
169 Label* failure_;
170
171 public:
172 VerifyOp(MacroAssembler& masm, Label* failure)
173 : masm(masm), failure_(failure) {}
174
175 void operator()(Register reg, Address dump) {
176 masm.branchPtr(Assembler::NotEqual, dump, reg, failure_);
177 }
178 void operator()(FloatRegister reg, Address dump) {
179 if (reg.isDouble()) {
180 ScratchDoubleScope scratch(masm);
181 masm.loadDouble(dump, scratch);
182 masm.branchDouble(Assembler::DoubleNotEqual, scratch, reg, failure_);
183 } else if (reg.isSingle()) {
184 ScratchFloat32Scope scratch(masm);
185 masm.loadFloat32(dump, scratch);
186 masm.branchFloat(Assembler::DoubleNotEqual, scratch, reg, failure_);
187 } else if (reg.isSimd128()) {
188 MOZ_CRASH("Unexpected case for SIMD");
189 } else {
190 MOZ_CRASH("Unexpected register type.");
191 }
192 }
193 };
194
195 void CodeGenerator::verifyOsiPointRegs(LSafepoint* safepoint) {
196 // Ensure the live registers stored by callVM did not change between
197 // the call and this OsiPoint. Try-catch relies on this invariant.
198
199 // Load pointer to the JitActivation in a scratch register.
200 AllocatableGeneralRegisterSet allRegs(GeneralRegisterSet::All());
201 Register scratch = allRegs.takeAny();
202 masm.push(scratch);
203 masm.loadJitActivation(scratch);
204
205 // If we should not check registers (because the instruction did not call
206 // into the VM, or a GC happened), we're done.
207 Label failure, done;
208 Address checkRegs(scratch, JitActivation::offsetOfCheckRegs());
209 masm.branch32(Assembler::Equal, checkRegs, Imm32(0), &done);
210
211 // Having more than one VM function call made in one visit function at
212 // runtime is a sec-ciritcal error, because if we conservatively assume that
213 // one of the function call can re-enter Ion, then the invalidation process
214 // will potentially add a call at a random location, by patching the code
215 // before the return address.
216 masm.branch32(Assembler::NotEqual, checkRegs, Imm32(1), &failure);
217
218 // Set checkRegs to 0, so that we don't try to verify registers after we
219 // return from this script to the caller.
220 masm.store32(Imm32(0), checkRegs);
221
222 // Ignore clobbered registers. Some instructions (like LValueToInt32) modify
223 // temps after calling into the VM. This is fine because no other
224 // instructions (including this OsiPoint) will depend on them. Also
225 // backtracking can also use the same register for an input and an output.
226 // These are marked as clobbered and shouldn't get checked.
227 LiveRegisterSet liveRegs;
228 liveRegs.set() = RegisterSet::Intersect(
229 safepoint->liveRegs().set(),
230 RegisterSet::Not(safepoint->clobberedRegs().set()));
231
232 VerifyOp op(masm, &failure);
233 HandleRegisterDump<VerifyOp>(op, masm, liveRegs, scratch, allRegs.getAny());
234
235 masm.jump(&done);
236
237 // Do not profile the callWithABI that occurs below. This is to avoid a
238 // rare corner case that occurs when profiling interacts with itself:
239 //
240 // When slow profiling assertions are turned on, FunctionBoundary ops
241 // (which update the profiler pseudo-stack) may emit a callVM, which
242 // forces them to have an osi point associated with them. The
243 // FunctionBoundary for inline function entry is added to the caller's
244 // graph with a PC from the caller's code, but during codegen it modifies
245 // Gecko Profiler instrumentation to add the callee as the current top-most
246 // script. When codegen gets to the OSIPoint, and the callWithABI below is
247 // emitted, the codegen thinks that the current frame is the callee, but
248 // the PC it's using from the OSIPoint refers to the caller. This causes
249 // the profiler instrumentation of the callWithABI below to ASSERT, since
250 // the script and pc are mismatched. To avoid this, we simply omit
251 // instrumentation for these callWithABIs.
252
253 // Any live register captured by a safepoint (other than temp registers)
254 // must remain unchanged between the call and the OsiPoint instruction.
255 masm.bind(&failure);
256 masm.assumeUnreachable("Modified registers between VM call and OsiPoint");
257
258 masm.bind(&done);
259 masm.pop(scratch);
260 }
261
262 bool CodeGenerator::shouldVerifyOsiPointRegs(LSafepoint* safepoint) {
263 if (!checkOsiPointRegisters) {
264 return false;
265 }
266
267 if (safepoint->liveRegs().emptyGeneral() &&
268 safepoint->liveRegs().emptyFloat()) {
269 return false; // No registers to check.
270 }
271
272 return true;
273 }
274
275 void CodeGenerator::resetOsiPointRegs(LSafepoint* safepoint) {
276 if (!shouldVerifyOsiPointRegs(safepoint)) {
277 return;
278 }
279
280 // Set checkRegs to 0. If we perform a VM call, the instruction
281 // will set it to 1.
282 AllocatableGeneralRegisterSet allRegs(GeneralRegisterSet::All());
283 Register scratch = allRegs.takeAny();
284 masm.push(scratch);
285 masm.loadJitActivation(scratch);
286 Address checkRegs(scratch, JitActivation::offsetOfCheckRegs());
287 masm.store32(Imm32(0), checkRegs);
288 masm.pop(scratch);
289 }
290
291 static void StoreAllLiveRegs(MacroAssembler& masm, LiveRegisterSet liveRegs) {
292 // Store a copy of all live registers before performing the call.
293 // When we reach the OsiPoint, we can use this to check nothing
294 // modified them in the meantime.
295
296 // Load pointer to the JitActivation in a scratch register.
297 AllocatableGeneralRegisterSet allRegs(GeneralRegisterSet::All());
298 Register scratch = allRegs.takeAny();
299 masm.push(scratch);
300 masm.loadJitActivation(scratch);
301
302 Address checkRegs(scratch, JitActivation::offsetOfCheckRegs());
303 masm.add32(Imm32(1), checkRegs);
304
305 StoreOp op(masm);
306 HandleRegisterDump<StoreOp>(op, masm, liveRegs, scratch, allRegs.getAny());
307
308 masm.pop(scratch);
309 }
310 #endif // CHECK_OSIPOINT_REGISTERS
311
312 // Before doing any call to Cpp, you should ensure that volatile
313 // registers are evicted by the register allocator.
314 void CodeGenerator::callVMInternal(VMFunctionId id, LInstruction* ins) {
315 TrampolinePtr code = gen->jitRuntime()->getVMWrapper(id);
316 const VMFunctionData& fun = GetVMFunction(id);
317
318 // Stack is:
319 // ... frame ...
320 // [args]
321 #ifdef DEBUG
322 MOZ_ASSERT(pushedArgs_ == fun.explicitArgs);
323 pushedArgs_ = 0;
324 #endif
325
326 #ifdef CHECK_OSIPOINT_REGISTERS
327 if (shouldVerifyOsiPointRegs(ins->safepoint())) {
328 StoreAllLiveRegs(masm, ins->safepoint()->liveRegs());
329 }
330 #endif
331
332 #ifdef DEBUG
333 if (ins->mirRaw()) {
334 MOZ_ASSERT(ins->mirRaw()->isInstruction());
335 MInstruction* mir = ins->mirRaw()->toInstruction();
336 MOZ_ASSERT_IF(mir->needsResumePoint(), mir->resumePoint());
337
338 // If this MIR instruction has an overridden AliasSet, set the JitRuntime's
339 // disallowArbitraryCode_ flag so we can assert this VMFunction doesn't call
340 // RunScript. Whitelist MInterruptCheck and MCheckOverRecursed because
341 // interrupt callbacks can call JS (chrome JS or shell testing functions).
342 bool isWhitelisted = mir->isInterruptCheck() || mir->isCheckOverRecursed();
343 if (!mir->hasDefaultAliasSet() && !isWhitelisted) {
344 const void* addr = gen->jitRuntime()->addressOfDisallowArbitraryCode();
345 masm.move32(Imm32(1), ReturnReg);
346 masm.store32(ReturnReg, AbsoluteAddress(addr));
347 }
348 }
349 #endif
350
351 // Push an exit frame descriptor.
352 masm.PushFrameDescriptor(FrameType::IonJS);
353
354 // Call the wrapper function. The wrapper is in charge to unwind the stack
355 // when returning from the call. Failures are handled with exceptions based
356 // on the return value of the C functions. To guard the outcome of the
357 // returned value, use another LIR instruction.
358 ensureOsiSpace();
359 uint32_t callOffset = masm.callJit(code);
360 markSafepointAt(callOffset, ins);
361
362 #ifdef DEBUG
363 // Reset the disallowArbitraryCode flag after the call.
364 {
365 const void* addr = gen->jitRuntime()->addressOfDisallowArbitraryCode();
366 masm.push(ReturnReg);
367 masm.move32(Imm32(0), ReturnReg);
368 masm.store32(ReturnReg, AbsoluteAddress(addr));
369 masm.pop(ReturnReg);
370 }
371 #endif
372
373 // Pop rest of the exit frame and the arguments left on the stack.
374 int framePop =
375 sizeof(ExitFrameLayout) - ExitFrameLayout::bytesPoppedAfterCall();
376 masm.implicitPop(fun.explicitStackSlots() * sizeof(void*) + framePop);
377
378 // Stack is:
379 // ... frame ...
380 }
381
382 template <typename Fn, Fn fn>
383 void CodeGenerator::callVM(LInstruction* ins) {
384 VMFunctionId id = VMFunctionToId<Fn, fn>::id;
385 callVMInternal(id, ins);
386 }
387
388 // ArgSeq store arguments for OutOfLineCallVM.
389 //
390 // OutOfLineCallVM are created with "oolCallVM" function. The third argument of
391 // this function is an instance of a class which provides a "generate" in charge
392 // of pushing the argument, with "pushArg", for a VMFunction.
393 //
394 // Such list of arguments can be created by using the "ArgList" function which
395 // creates one instance of "ArgSeq", where the type of the arguments are
396 // inferred from the type of the arguments.
397 //
398 // The list of arguments must be written in the same order as if you were
399 // calling the function in C++.
400 //
401 // Example:
402 // ArgList(ToRegister(lir->lhs()), ToRegister(lir->rhs()))
403
404 template <typename... ArgTypes>
405 class ArgSeq {
406 std::tuple<std::remove_reference_t<ArgTypes>...> args_;
407
408 template <std::size_t... ISeq>
409 inline void generate(CodeGenerator* codegen,
410 std::index_sequence<ISeq...>) const {
411 // Arguments are pushed in reverse order, from last argument to first
412 // argument.
413 (codegen->pushArg(std::get<sizeof...(ISeq) - 1 - ISeq>(args_)), ...);
414 }
415
416 public:
417 explicit ArgSeq(ArgTypes&&... args)
418 : args_(std::forward<ArgTypes>(args)...) {}
419
420 inline void generate(CodeGenerator* codegen) const {
421 generate(codegen, std::index_sequence_for<ArgTypes...>{});
422 }
423
424 #ifdef DEBUG
425 static constexpr size_t numArgs = sizeof...(ArgTypes);
426 #endif
427 };
428
429 template <typename... ArgTypes>
430 inline ArgSeq<ArgTypes...> ArgList(ArgTypes&&... args) {
431 return ArgSeq<ArgTypes...>(std::forward<ArgTypes>(args)...);
432 }
433
434 // Store wrappers, to generate the right move of data after the VM call.
435
436 struct StoreNothing {
437 inline void generate(CodeGenerator* codegen) const {}
438 inline LiveRegisterSet clobbered() const {
439 return LiveRegisterSet(); // No register gets clobbered
440 }
441 };
442
443 class StoreRegisterTo {
444 private:
445 Register out_;
446
447 public:
448 explicit StoreRegisterTo(Register out) : out_(out) {}
449
450 inline void generate(CodeGenerator* codegen) const {
451 // It's okay to use storePointerResultTo here - the VMFunction wrapper
452 // ensures the upper bytes are zero for bool/int32 return values.
453 codegen->storePointerResultTo(out_);
454 }
455 inline LiveRegisterSet clobbered() const {
456 LiveRegisterSet set;
457 set.add(out_);
458 return set;
459 }
460 };
461
462 class StoreFloatRegisterTo {
463 private:
464 FloatRegister out_;
465
466 public:
467 explicit StoreFloatRegisterTo(FloatRegister out) : out_(out) {}
468
469 inline void generate(CodeGenerator* codegen) const {
470 codegen->storeFloatResultTo(out_);
471 }
472 inline LiveRegisterSet clobbered() const {
473 LiveRegisterSet set;
474 set.add(out_);
475 return set;
476 }
477 };
478
479 template <typename Output>
480 class StoreValueTo_ {
481 private:
482 Output out_;
483
484 public:
485 explicit StoreValueTo_(const Output& out) : out_(out) {}
486
487 inline void generate(CodeGenerator* codegen) const {
488 codegen->storeResultValueTo(out_);
489 }
490 inline LiveRegisterSet clobbered() const {
491 LiveRegisterSet set;
492 set.add(out_);
493 return set;
494 }
495 };
496
497 template <typename Output>
498 StoreValueTo_<Output> StoreValueTo(const Output& out) {
499 return StoreValueTo_<Output>(out);
500 }
501
502 template <typename Fn, Fn fn, class ArgSeq, class StoreOutputTo>
503 class OutOfLineCallVM : public OutOfLineCodeBase<CodeGenerator> {
504 private:
505 LInstruction* lir_;
506 ArgSeq args_;
507 StoreOutputTo out_;
508
509 public:
510 OutOfLineCallVM(LInstruction* lir, const ArgSeq& args,
511 const StoreOutputTo& out)
512 : lir_(lir), args_(args), out_(out) {}
513
514 void accept(CodeGenerator* codegen) override {
515 codegen->visitOutOfLineCallVM(this);
516 }
517
518 LInstruction* lir() const { return lir_; }
519 const ArgSeq& args() const { return args_; }
520 const StoreOutputTo& out() const { return out_; }
521 };
522
523 template <typename Fn, Fn fn, class ArgSeq, class StoreOutputTo>
524 OutOfLineCode* CodeGenerator::oolCallVM(LInstruction* lir, const ArgSeq& args,
525 const StoreOutputTo& out) {
526 MOZ_ASSERT(lir->mirRaw());
527 MOZ_ASSERT(lir->mirRaw()->isInstruction());
528
529 #ifdef DEBUG
530 VMFunctionId id = VMFunctionToId<Fn, fn>::id;
531 const VMFunctionData& fun = GetVMFunction(id);
532 MOZ_ASSERT(fun.explicitArgs == args.numArgs);
533 MOZ_ASSERT(fun.returnsData() !=
534 (std::is_same_v<StoreOutputTo, StoreNothing>));
535 #endif
536
537 OutOfLineCode* ool = new (alloc())
538 OutOfLineCallVM<Fn, fn, ArgSeq, StoreOutputTo>(lir, args, out);
539 addOutOfLineCode(ool, lir->mirRaw()->toInstruction());
540 return ool;
541 }
542
543 template <typename Fn, Fn fn, class ArgSeq, class StoreOutputTo>
544 void CodeGenerator::visitOutOfLineCallVM(
545 OutOfLineCallVM<Fn, fn, ArgSeq, StoreOutputTo>* ool) {
546 LInstruction* lir = ool->lir();
547
548 #ifdef JS_JITSPEW
549 JitSpewStart(JitSpew_Codegen, " # LIR=%s",
550 lir->opName());
551 if (const char* extra = lir->getExtraName()) {
552 JitSpewCont(JitSpew_Codegen, ":%s", extra);
553 }
554 JitSpewFin(JitSpew_Codegen);
555 #endif
556 perfSpewer_.recordInstruction(masm, lir);
557 saveLive(lir);
558 ool->args().generate(this);
559 callVM<Fn, fn>(lir);
560 ool->out().generate(this);
561 restoreLiveIgnore(lir, ool->out().clobbered());
562 masm.jump(ool->rejoin());
563 }
564
565 class OutOfLineICFallback : public OutOfLineCodeBase<CodeGenerator> {
566 private:
567 LInstruction* lir_;
568 size_t cacheIndex_;
569 size_t cacheInfoIndex_;
570
571 public:
572 OutOfLineICFallback(LInstruction* lir, size_t cacheIndex,
573 size_t cacheInfoIndex)
574 : lir_(lir), cacheIndex_(cacheIndex), cacheInfoIndex_(cacheInfoIndex) {}
575
576 void bind(MacroAssembler* masm) override {
577 // The binding of the initial jump is done in
578 // CodeGenerator::visitOutOfLineICFallback.
579 }
580
581 size_t cacheIndex() const { return cacheIndex_; }
582 size_t cacheInfoIndex() const { return cacheInfoIndex_; }
583 LInstruction* lir() const { return lir_; }
584
585 void accept(CodeGenerator* codegen) override {
586 codegen->visitOutOfLineICFallback(this);
587 }
588 };
589
590 void CodeGeneratorShared::addIC(LInstruction* lir, size_t cacheIndex) {
591 if (cacheIndex == SIZE_MAX) {
592 masm.setOOM();
593 return;
594 }
595
596 DataPtr<IonIC> cache(this, cacheIndex);
597 MInstruction* mir = lir->mirRaw()->toInstruction();
598 cache->setScriptedLocation(mir->block()->info().script(),
599 mir->resumePoint()->pc());
600
601 Register temp = cache->scratchRegisterForEntryJump();
602 icInfo_.back().icOffsetForJump = masm.movWithPatch(ImmWord(-1), temp);
603 masm.jump(Address(temp, 0));
604
605 MOZ_ASSERT(!icInfo_.empty());
606
607 OutOfLineICFallback* ool =
608 new (alloc()) OutOfLineICFallback(lir, cacheIndex, icInfo_.length() - 1);
609 addOutOfLineCode(ool, mir);
610
611 masm.bind(ool->rejoin());
612 cache->setRejoinOffset(CodeOffset(ool->rejoin()->offset()));
613 }
614
615 void CodeGenerator::visitOutOfLineICFallback(OutOfLineICFallback* ool) {
616 LInstruction* lir = ool->lir();
617 size_t cacheIndex = ool->cacheIndex();
618 size_t cacheInfoIndex = ool->cacheInfoIndex();
619
620 DataPtr<IonIC> ic(this, cacheIndex);
621
622 // Register the location of the OOL path in the IC.
623 ic->setFallbackOffset(CodeOffset(masm.currentOffset()));
624
625 switch (ic->kind()) {
626 case CacheKind::GetProp:
627 case CacheKind::GetElem: {
628 IonGetPropertyIC* getPropIC = ic->asGetPropertyIC();
629
630 saveLive(lir);
631
632 pushArg(getPropIC->id());
633 pushArg(getPropIC->value());
634 icInfo_[cacheInfoIndex].icOffsetForPush = pushArgWithPatch(ImmWord(-1));
635 pushArg(ImmGCPtr(gen->outerInfo().script()));
636
637 using Fn = bool (*)(JSContext*, HandleScript, IonGetPropertyIC*,
638 HandleValue, HandleValue, MutableHandleValue);
639 callVM<Fn, IonGetPropertyIC::update>(lir);
640
641 StoreValueTo(getPropIC->output()).generate(this);
642 restoreLiveIgnore(lir, StoreValueTo(getPropIC->output()).clobbered());
643
644 masm.jump(ool->rejoin());
645 return;
646 }
647 case CacheKind::GetPropSuper:
648 case CacheKind::GetElemSuper: {
649 IonGetPropSuperIC* getPropSuperIC = ic->asGetPropSuperIC();
650
651 saveLive(lir);
652
653 pushArg(getPropSuperIC->id());
654 pushArg(getPropSuperIC->receiver());
655 pushArg(getPropSuperIC->object());
656 icInfo_[cacheInfoIndex].icOffsetForPush = pushArgWithPatch(ImmWord(-1));
657 pushArg(ImmGCPtr(gen->outerInfo().script()));
658
659 using Fn =
660 bool (*)(JSContext*, HandleScript, IonGetPropSuperIC*, HandleObject,
661 HandleValue, HandleValue, MutableHandleValue);
662 callVM<Fn, IonGetPropSuperIC::update>(lir);
663
664 StoreValueTo(getPropSuperIC->output()).generate(this);
665 restoreLiveIgnore(lir,
666 StoreValueTo(getPropSuperIC->output()).clobbered());
667
668 masm.jump(ool->rejoin());
669 return;
670 }
671 case CacheKind::SetProp:
672 case CacheKind::SetElem: {
673 IonSetPropertyIC* setPropIC = ic->asSetPropertyIC();
674
675 saveLive(lir);
676
677 pushArg(setPropIC->rhs());
678 pushArg(setPropIC->id());
679 pushArg(setPropIC->object());
680 icInfo_[cacheInfoIndex].icOffsetForPush = pushArgWithPatch(ImmWord(-1));
681 pushArg(ImmGCPtr(gen->outerInfo().script()));
682
683 using Fn = bool (*)(JSContext*, HandleScript, IonSetPropertyIC*,
684 HandleObject, HandleValue, HandleValue);
685 callVM<Fn, IonSetPropertyIC::update>(lir);
686
687 restoreLive(lir);
688
689 masm.jump(ool->rejoin());
690 return;
691 }
692 case CacheKind::GetName: {
693 IonGetNameIC* getNameIC = ic->asGetNameIC();
694
695 saveLive(lir);
696
697 pushArg(getNameIC->environment());
698 icInfo_[cacheInfoIndex].icOffsetForPush = pushArgWithPatch(ImmWord(-1));
699 pushArg(ImmGCPtr(gen->outerInfo().script()));
700
701 using Fn = bool (*)(JSContext*, HandleScript, IonGetNameIC*, HandleObject,
702 MutableHandleValue);
703 callVM<Fn, IonGetNameIC::update>(lir);
704
705 StoreValueTo(getNameIC->output()).generate(this);
706 restoreLiveIgnore(lir, StoreValueTo(getNameIC->output()).clobbered());
707
708 masm.jump(ool->rejoin());
709 return;
710 }
711 case CacheKind::BindName: {
712 IonBindNameIC* bindNameIC = ic->asBindNameIC();
713
714 saveLive(lir);
715
716 pushArg(bindNameIC->environment());
717 icInfo_[cacheInfoIndex].icOffsetForPush = pushArgWithPatch(ImmWord(-1));
718 pushArg(ImmGCPtr(gen->outerInfo().script()));
719
720 using Fn =
721 JSObject* (*)(JSContext*, HandleScript, IonBindNameIC*, HandleObject);
722 callVM<Fn, IonBindNameIC::update>(lir);
723
724 StoreRegisterTo(bindNameIC->output()).generate(this);
725 restoreLiveIgnore(lir, StoreRegisterTo(bindNameIC->output()).clobbered());
726
727 masm.jump(ool->rejoin());
728 return;
729 }
730 case CacheKind::GetIterator: {
731 IonGetIteratorIC* getIteratorIC = ic->asGetIteratorIC();
732
733 saveLive(lir);
734
735 pushArg(getIteratorIC->value());
736 icInfo_[cacheInfoIndex].icOffsetForPush = pushArgWithPatch(ImmWord(-1));
737 pushArg(ImmGCPtr(gen->outerInfo().script()));
738
739 using Fn = JSObject* (*)(JSContext*, HandleScript, IonGetIteratorIC*,
740 HandleValue);
741 callVM<Fn, IonGetIteratorIC::update>(lir);
742
743 StoreRegisterTo(getIteratorIC->output()).generate(this);
744 restoreLiveIgnore(lir,
745 StoreRegisterTo(getIteratorIC->output()).clobbered());
746
747 masm.jump(ool->rejoin());
748 return;
749 }
750 case CacheKind::OptimizeSpreadCall: {
751 auto* optimizeSpreadCallIC = ic->asOptimizeSpreadCallIC();
752
753 saveLive(lir);
754
755 pushArg(optimizeSpreadCallIC->value());
756 icInfo_[cacheInfoIndex].icOffsetForPush = pushArgWithPatch(ImmWord(-1));
757 pushArg(ImmGCPtr(gen->outerInfo().script()));
758
759 using Fn = bool (*)(JSContext*, HandleScript, IonOptimizeSpreadCallIC*,
760 HandleValue, MutableHandleValue);
761 callVM<Fn, IonOptimizeSpreadCallIC::update>(lir);
762
763 StoreValueTo(optimizeSpreadCallIC->output()).generate(this);
764 restoreLiveIgnore(
765 lir, StoreValueTo(optimizeSpreadCallIC->output()).clobbered());
766
767 masm.jump(ool->rejoin());
768 return;
769 }
770 case CacheKind::In: {
771 IonInIC* inIC = ic->asInIC();
772
773 saveLive(lir);
774
775 pushArg(inIC->object());
776 pushArg(inIC->key());
777 icInfo_[cacheInfoIndex].icOffsetForPush = pushArgWithPatch(ImmWord(-1));
778 pushArg(ImmGCPtr(gen->outerInfo().script()));
779
780 using Fn = bool (*)(JSContext*, HandleScript, IonInIC*, HandleValue,
781 HandleObject, bool*);
782 callVM<Fn, IonInIC::update>(lir);
783
784 StoreRegisterTo(inIC->output()).generate(this);
785 restoreLiveIgnore(lir, StoreRegisterTo(inIC->output()).clobbered());
786
787 masm.jump(ool->rejoin());
788 return;
789 }
790 case CacheKind::HasOwn: {
791 IonHasOwnIC* hasOwnIC = ic->asHasOwnIC();
792
793 saveLive(lir);
794
795 pushArg(hasOwnIC->id());
796 pushArg(hasOwnIC->value());
797 icInfo_[cacheInfoIndex].icOffsetForPush = pushArgWithPatch(ImmWord(-1));
798 pushArg(ImmGCPtr(gen->outerInfo().script()));
799
800 using Fn = bool (*)(JSContext*, HandleScript, IonHasOwnIC*, HandleValue,
801 HandleValue, int32_t*);
802 callVM<Fn, IonHasOwnIC::update>(lir);
803
804 StoreRegisterTo(hasOwnIC->output()).generate(this);
805 restoreLiveIgnore(lir, StoreRegisterTo(hasOwnIC->output()).clobbered());
806
807 masm.jump(ool->rejoin());
808 return;
809 }
810 case CacheKind::CheckPrivateField: {
811 IonCheckPrivateFieldIC* checkPrivateFieldIC = ic->asCheckPrivateFieldIC();
812
813 saveLive(lir);
814
815 pushArg(checkPrivateFieldIC->id());
816 pushArg(checkPrivateFieldIC->value());
817
818 icInfo_[cacheInfoIndex].icOffsetForPush = pushArgWithPatch(ImmWord(-1));
819 pushArg(ImmGCPtr(gen->outerInfo().script()));
820
821 using Fn = bool (*)(JSContext*, HandleScript, IonCheckPrivateFieldIC*,
822 HandleValue, HandleValue, bool*);
823 callVM<Fn, IonCheckPrivateFieldIC::update>(lir);
824
825 StoreRegisterTo(checkPrivateFieldIC->output()).generate(this);
826 restoreLiveIgnore(
827 lir, StoreRegisterTo(checkPrivateFieldIC->output()).clobbered());
828
829 masm.jump(ool->rejoin());
830 return;
831 }
832 case CacheKind::InstanceOf: {
833 IonInstanceOfIC* hasInstanceOfIC = ic->asInstanceOfIC();
834
835 saveLive(lir);
836
837 pushArg(hasInstanceOfIC->rhs());
838 pushArg(hasInstanceOfIC->lhs());
839 icInfo_[cacheInfoIndex].icOffsetForPush = pushArgWithPatch(ImmWord(-1));
840 pushArg(ImmGCPtr(gen->outerInfo().script()));
841
842 using Fn = bool (*)(JSContext*, HandleScript, IonInstanceOfIC*,
843 HandleValue lhs, HandleObject rhs, bool* res);
844 callVM<Fn, IonInstanceOfIC::update>(lir);
845
846 StoreRegisterTo(hasInstanceOfIC->output()).generate(this);
847 restoreLiveIgnore(lir,
848 StoreRegisterTo(hasInstanceOfIC->output()).clobbered());
849
850 masm.jump(ool->rejoin());
851 return;
852 }
853 case CacheKind::UnaryArith: {
854 IonUnaryArithIC* unaryArithIC = ic->asUnaryArithIC();
855
856 saveLive(lir);
857
858 pushArg(unaryArithIC->input());
859 icInfo_[cacheInfoIndex].icOffsetForPush = pushArgWithPatch(ImmWord(-1));
860 pushArg(ImmGCPtr(gen->outerInfo().script()));
861
862 using Fn = bool (*)(JSContext* cx, HandleScript outerScript,
863 IonUnaryArithIC* stub, HandleValue val,
864 MutableHandleValue res);
865 callVM<Fn, IonUnaryArithIC::update>(lir);
866
867 StoreValueTo(unaryArithIC->output()).generate(this);
868 restoreLiveIgnore(lir, StoreValueTo(unaryArithIC->output()).clobbered());
869
870 masm.jump(ool->rejoin());
871 return;
872 }
873 case CacheKind::ToPropertyKey: {
874 IonToPropertyKeyIC* toPropertyKeyIC = ic->asToPropertyKeyIC();
875
876 saveLive(lir);
877
878 pushArg(toPropertyKeyIC->input());
879 icInfo_[cacheInfoIndex].icOffsetForPush = pushArgWithPatch(ImmWord(-1));
880 pushArg(ImmGCPtr(gen->outerInfo().script()));
881
882 using Fn = bool (*)(JSContext* cx, HandleScript outerScript,
883 IonToPropertyKeyIC* ic, HandleValue val,
884 MutableHandleValue res);
885 callVM<Fn, IonToPropertyKeyIC::update>(lir);
886
887 StoreValueTo(toPropertyKeyIC->output()).generate(this);
888 restoreLiveIgnore(lir,
889 StoreValueTo(toPropertyKeyIC->output()).clobbered());
890
891 masm.jump(ool->rejoin());
892 return;
893 }
894 case CacheKind::BinaryArith: {
895 IonBinaryArithIC* binaryArithIC = ic->asBinaryArithIC();
896
897 saveLive(lir);
898
899 pushArg(binaryArithIC->rhs());
900 pushArg(binaryArithIC->lhs());
901 icInfo_[cacheInfoIndex].icOffsetForPush = pushArgWithPatch(ImmWord(-1));
902 pushArg(ImmGCPtr(gen->outerInfo().script()));
903
904 using Fn = bool (*)(JSContext* cx, HandleScript outerScript,
905 IonBinaryArithIC* stub, HandleValue lhs,
906 HandleValue rhs, MutableHandleValue res);
907 callVM<Fn, IonBinaryArithIC::update>(lir);
908
909 StoreValueTo(binaryArithIC->output()).generate(this);
910 restoreLiveIgnore(lir, StoreValueTo(binaryArithIC->output()).clobbered());
911
912 masm.jump(ool->rejoin());
913 return;
914 }
915 case CacheKind::Compare: {
916 IonCompareIC* compareIC = ic->asCompareIC();
917
918 saveLive(lir);
919
920 pushArg(compareIC->rhs());
921 pushArg(compareIC->lhs());
922 icInfo_[cacheInfoIndex].icOffsetForPush = pushArgWithPatch(ImmWord(-1));
923 pushArg(ImmGCPtr(gen->outerInfo().script()));
924
925 using Fn =
926 bool (*)(JSContext* cx, HandleScript outerScript, IonCompareIC* stub,
927 HandleValue lhs, HandleValue rhs, bool* res);
928 callVM<Fn, IonCompareIC::update>(lir);
929
930 StoreRegisterTo(compareIC->output()).generate(this);
931 restoreLiveIgnore(lir, StoreRegisterTo(compareIC->output()).clobbered());
932
933 masm.jump(ool->rejoin());
934 return;
935 }
936 case CacheKind::CloseIter: {
937 IonCloseIterIC* closeIterIC = ic->asCloseIterIC();
938
939 saveLive(lir);
940
941 pushArg(closeIterIC->iter());
942 icInfo_[cacheInfoIndex].icOffsetForPush = pushArgWithPatch(ImmWord(-1));
943 pushArg(ImmGCPtr(gen->outerInfo().script()));
944
945 using Fn =
946 bool (*)(JSContext*, HandleScript, IonCloseIterIC*, HandleObject);
947 callVM<Fn, IonCloseIterIC::update>(lir);
948
949 restoreLive(lir);
950
951 masm.jump(ool->rejoin());
952 return;
953 }
954 case CacheKind::OptimizeGetIterator: {
955 auto* optimizeGetIteratorIC = ic->asOptimizeGetIteratorIC();
956
957 saveLive(lir);
958
959 pushArg(optimizeGetIteratorIC->value());
960 icInfo_[cacheInfoIndex].icOffsetForPush = pushArgWithPatch(ImmWord(-1));
961 pushArg(ImmGCPtr(gen->outerInfo().script()));
962
963 using Fn = bool (*)(JSContext*, HandleScript, IonOptimizeGetIteratorIC*,
964 HandleValue, bool* res);
965 callVM<Fn, IonOptimizeGetIteratorIC::update>(lir);
966
967 StoreRegisterTo(optimizeGetIteratorIC->output()).generate(this);
968 restoreLiveIgnore(
969 lir, StoreRegisterTo(optimizeGetIteratorIC->output()).clobbered());
970
971 masm.jump(ool->rejoin());
972 return;
973 }
974 case CacheKind::Call:
975 case CacheKind::TypeOf:
976 case CacheKind::TypeOfEq:
977 case CacheKind::ToBool:
978 case CacheKind::LazyConstant:
979 case CacheKind::NewArray:
980 case CacheKind::NewObject:
981 case CacheKind::Lambda:
982 case CacheKind::GetImport:
983 MOZ_CRASH("Unsupported IC");
984 }
985 MOZ_CRASH();
986 }
987
988 StringObject* MNewStringObject::templateObj() const {
989 return &templateObj_->as<StringObject>();
990 }
991
992 CodeGenerator::CodeGenerator(MIRGenerator* gen, LIRGraph* graph,
993 MacroAssembler* masm,
994 const wasm::CodeMetadata* wasmCodeMeta)
995 : CodeGeneratorSpecific(gen, graph, masm, wasmCodeMeta),
996 ionScriptLabels_(gen->alloc()),
997 ionNurseryObjectLabels_(gen->alloc()),
998 scriptCounts_(nullptr) {}
999
1000 CodeGenerator::~CodeGenerator() { js_delete(scriptCounts_); }
1001
1002 void CodeGenerator::visitValueToNumberInt32(LValueToNumberInt32* lir) {
1003 ValueOperand operand = ToValue(lir->input());
1004 Register output = ToRegister(lir->output());
1005 FloatRegister temp = ToFloatRegister(lir->temp0());
1006
1007 Label fails;
1008 masm.convertValueToInt32(operand, temp, output, &fails,
1009 lir->mir()->needsNegativeZeroCheck(),
1010 lir->mir()->conversion());
1011
1012 bailoutFrom(&fails, lir->snapshot());
1013 }
1014
1015 void CodeGenerator::visitValueTruncateToInt32(LValueTruncateToInt32* lir) {
1016 ValueOperand operand = ToValue(lir->input());
1017 Register output = ToRegister(lir->output());
1018 FloatRegister temp = ToFloatRegister(lir->temp0());
1019 Register stringReg = ToRegister(lir->temp1());
1020
1021 auto* oolDouble = oolTruncateDouble(temp, output, lir->mir());
1022
1023 using Fn = bool (*)(JSContext*, JSString*, double*);
1024 auto* oolString = oolCallVM<Fn, StringToNumber>(lir, ArgList(stringReg),
1025 StoreFloatRegisterTo(temp));
1026 Label* stringEntry = oolString->entry();
1027 Label* stringRejoin = oolString->rejoin();
1028
1029 Label fails;
1030 masm.truncateValueToInt32(operand, stringEntry, stringRejoin,
1031 oolDouble->entry(), stringReg, temp, output,
1032 &fails);
1033 masm.bind(oolDouble->rejoin());
1034
1035 bailoutFrom(&fails, lir->snapshot());
1036 }
1037
1038 void CodeGenerator::visitValueToDouble(LValueToDouble* lir) {
1039 ValueOperand operand = ToValue(lir->input());
1040 FloatRegister output = ToFloatRegister(lir->output());
1041
1042 Label fail;
1043 masm.convertValueToDouble(operand, output, &fail);
1044 bailoutFrom(&fail, lir->snapshot());
1045 }
1046
1047 void CodeGenerator::visitValueToFloat32(LValueToFloat32* lir) {
1048 ValueOperand operand = ToValue(lir->input());
1049 FloatRegister output = ToFloatRegister(lir->output());
1050
1051 Label fail;
1052 masm.convertValueToFloat32(operand, output, &fail);
1053 bailoutFrom(&fail, lir->snapshot());
1054 }
1055
1056 void CodeGenerator::visitValueToFloat16(LValueToFloat16* lir) {
1057 ValueOperand operand = ToValue(lir->input());
1058 Register temp = ToTempRegisterOrInvalid(lir->temp0());
1059 FloatRegister output = ToFloatRegister(lir->output());
1060
1061 LiveRegisterSet volatileRegs;
1062 if (!MacroAssembler::SupportsFloat64To16()) {
1063 volatileRegs = liveVolatileRegs(lir);
1064 }
1065
1066 Label fail;
1067 masm.convertValueToFloat16(operand, output, temp, volatileRegs, &fail);
1068 bailoutFrom(&fail, lir->snapshot());
1069 }
1070
1071 void CodeGenerator::visitValueToBigInt(LValueToBigInt* lir) {
1072 ValueOperand operand = ToValue(lir->input());
1073 Register output = ToRegister(lir->output());
1074
1075 using Fn = BigInt* (*)(JSContext*, HandleValue);
1076 auto* ool =
1077 oolCallVM<Fn, ToBigInt>(lir, ArgList(operand), StoreRegisterTo(output));
1078
1079 Register tag = masm.extractTag(operand, output);
1080
1081 Label notBigInt, done;
1082 masm.branchTestBigInt(Assembler::NotEqual, tag, &notBigInt);
1083 masm.unboxBigInt(operand, output);
1084 masm.jump(&done);
1085 masm.bind(&notBigInt);
1086
1087 masm.branchTestBoolean(Assembler::Equal, tag, ool->entry());
1088 masm.branchTestString(Assembler::Equal, tag, ool->entry());
1089
1090 // ToBigInt(object) can have side-effects; all other types throw a TypeError.
1091 bailout(lir->snapshot());
1092
1093 masm.bind(ool->rejoin());
1094 masm.bind(&done);
1095 }
1096
1097 void CodeGenerator::visitInt32ToDouble(LInt32ToDouble* lir) {
1098 masm.convertInt32ToDouble(ToRegister(lir->input()),
1099 ToFloatRegister(lir->output()));
1100 }
1101
1102 void CodeGenerator::visitFloat32ToDouble(LFloat32ToDouble* lir) {
1103 masm.convertFloat32ToDouble(ToFloatRegister(lir->input()),
1104 ToFloatRegister(lir->output()));
1105 }
1106
1107 void CodeGenerator::visitDoubleToFloat32(LDoubleToFloat32* lir) {
1108 masm.convertDoubleToFloat32(ToFloatRegister(lir->input()),
1109 ToFloatRegister(lir->output()));
1110 }
1111
1112 void CodeGenerator::visitInt32ToFloat32(LInt32ToFloat32* lir) {
1113 masm.convertInt32ToFloat32(ToRegister(lir->input()),
1114 ToFloatRegister(lir->output()));
1115 }
1116
1117 void CodeGenerator::visitDoubleToFloat16(LDoubleToFloat16* lir) {
1118 LiveRegisterSet volatileRegs;
1119 if (!MacroAssembler::SupportsFloat64To16()) {
1120 volatileRegs = liveVolatileRegs(lir);
1121 }
1122 masm.convertDoubleToFloat16(
1123 ToFloatRegister(lir->input()), ToFloatRegister(lir->output()),
1124 ToTempRegisterOrInvalid(lir->temp0()), volatileRegs);
1125 }
1126
1127 void CodeGenerator::visitDoubleToFloat32ToFloat16(
1128 LDoubleToFloat32ToFloat16* lir) {
1129 masm.convertDoubleToFloat16(
1130 ToFloatRegister(lir->input()), ToFloatRegister(lir->output()),
1131 ToRegister(lir->temp0()), ToRegister(lir->temp1()));
1132 }
1133
1134 void CodeGenerator::visitFloat32ToFloat16(LFloat32ToFloat16* lir) {
1135 LiveRegisterSet volatileRegs;
1136 if (!MacroAssembler::SupportsFloat32To16()) {
1137 volatileRegs = liveVolatileRegs(lir);
1138 }
1139 masm.convertFloat32ToFloat16(
1140 ToFloatRegister(lir->input()), ToFloatRegister(lir->output()),
1141 ToTempRegisterOrInvalid(lir->temp0()), volatileRegs);
1142 }
1143
1144 void CodeGenerator::visitInt32ToFloat16(LInt32ToFloat16* lir) {
1145 LiveRegisterSet volatileRegs;
1146 if (!MacroAssembler::SupportsFloat32To16()) {
1147 volatileRegs = liveVolatileRegs(lir);
1148 }
1149 masm.convertInt32ToFloat16(
1150 ToRegister(lir->input()), ToFloatRegister(lir->output()),
1151 ToTempRegisterOrInvalid(lir->temp0()), volatileRegs);
1152 }
1153
1154 void CodeGenerator::visitDoubleToInt32(LDoubleToInt32* lir) {
1155 Label fail;
1156 FloatRegister input = ToFloatRegister(lir->input());
1157 Register output = ToRegister(lir->output());
1158 masm.convertDoubleToInt32(input, output, &fail,
1159 lir->mir()->needsNegativeZeroCheck());
1160 bailoutFrom(&fail, lir->snapshot());
1161 }
1162
1163 void CodeGenerator::visitFloat32ToInt32(LFloat32ToInt32* lir) {
1164 Label fail;
1165 FloatRegister input = ToFloatRegister(lir->input());
1166 Register output = ToRegister(lir->output());
1167 masm.convertFloat32ToInt32(input, output, &fail,
1168 lir->mir()->needsNegativeZeroCheck());
1169 bailoutFrom(&fail, lir->snapshot());
1170 }
1171
1172 void CodeGenerator::visitInt32ToIntPtr(LInt32ToIntPtr* lir) {
1173 #ifdef JS_64BIT
1174 Register output = ToRegister(lir->output());
1175 const LAllocation* input = lir->input();
1176 if (input->isGeneralReg()) {
1177 masm.move32SignExtendToPtr(ToRegister(input), output);
1178 } else {
1179 masm.load32SignExtendToPtr(ToAddress(input), output);
1180 }
1181 #else
1182 MOZ_CRASH("Not used on 32-bit platforms");
1183 #endif
1184 }
1185
1186 void CodeGenerator::visitNonNegativeIntPtrToInt32(
1187 LNonNegativeIntPtrToInt32* lir) {
1188 #ifdef JS_64BIT
1189 Register output = ToRegister(lir->output());
1190 MOZ_ASSERT(ToRegister(lir->input()) == output);
1191
1192 Label bail;
1193 masm.guardNonNegativeIntPtrToInt32(output, &bail);
1194 bailoutFrom(&bail, lir->snapshot());
1195 #else
1196 MOZ_CRASH("Not used on 32-bit platforms");
1197 #endif
1198 }
1199
1200 void CodeGenerator::visitIntPtrToDouble(LIntPtrToDouble* lir) {
1201 Register input = ToRegister(lir->input());
1202 FloatRegister output = ToFloatRegister(lir->output());
1203 masm.convertIntPtrToDouble(input, output);
1204 }
1205
1206 void CodeGenerator::visitAdjustDataViewLength(LAdjustDataViewLength* lir) {
1207 Register output = ToRegister(lir->output());
1208 MOZ_ASSERT(ToRegister(lir->input()) == output);
1209
1210 uint32_t byteSize = lir->mir()->byteSize();
1211
1212 #ifdef DEBUG
1213 Label ok;
1214 masm.branchTestPtr(Assembler::NotSigned, output, output, &ok);
1215 masm.assumeUnreachable("Unexpected negative value in LAdjustDataViewLength");
1216 masm.bind(&ok);
1217 #endif
1218
1219 Label bail;
1220 masm.branchSubPtr(Assembler::Signed, Imm32(byteSize - 1), output, &bail);
1221 bailoutFrom(&bail, lir->snapshot());
1222 }
1223
1224 void CodeGenerator::emitOOLTestObject(Register objreg,
1225 Label* ifEmulatesUndefined,
1226 Label* ifDoesntEmulateUndefined,
1227 Register scratch) {
1228 saveVolatile(scratch);
1229 #if defined(DEBUG) || defined(FUZZING)
1230 masm.loadPtr(AbsoluteAddress(
1231 gen->runtime->addressOfHasSeenObjectEmulateUndefinedFuse()),
1232 scratch);
1233 using Fn = bool (*)(JSObject* obj, size_t fuseValue);
1234 masm.setupAlignedABICall();
1235 masm.passABIArg(objreg);
1236 masm.passABIArg(scratch);
1237 masm.callWithABI<Fn, js::EmulatesUndefinedCheckFuse>();
1238 #else
1239 using Fn = bool (*)(JSObject* obj);
1240 masm.setupAlignedABICall();
1241 masm.passABIArg(objreg);
1242 masm.callWithABI<Fn, js::EmulatesUndefined>();
1243 #endif
1244 masm.storeCallPointerResult(scratch);
1245 restoreVolatile(scratch);
1246
1247 masm.branchIfTrueBool(scratch, ifEmulatesUndefined);
1248 masm.jump(ifDoesntEmulateUndefined);
1249 }
1250
1251 // Base out-of-line code generator for all tests of the truthiness of an
1252 // object, where the object might not be truthy. (Recall that per spec all
1253 // objects are truthy, but we implement the JSCLASS_EMULATES_UNDEFINED class
1254 // flag to permit objects to look like |undefined| in certain contexts,
1255 // including in object truthiness testing.) We check truthiness inline except
1256 // when we're testing it on a proxy, in which case out-of-line code will call
1257 // EmulatesUndefined for a conclusive answer.
1258 class OutOfLineTestObject : public OutOfLineCodeBase<CodeGenerator> {
1259 Register objreg_;
1260 Register scratch_;
1261
1262 Label* ifEmulatesUndefined_;
1263 Label* ifDoesntEmulateUndefined_;
1264
1265 #ifdef DEBUG
1266 bool initialized() { return ifEmulatesUndefined_ != nullptr; }
1267 #endif
1268
1269 public:
1270 OutOfLineTestObject()
1271 : ifEmulatesUndefined_(nullptr), ifDoesntEmulateUndefined_(nullptr) {}
1272
1273 void accept(CodeGenerator* codegen) final {
1274 MOZ_ASSERT(initialized());
1275 codegen->emitOOLTestObject(objreg_, ifEmulatesUndefined_,
1276 ifDoesntEmulateUndefined_, scratch_);
1277 }
1278
1279 // Specify the register where the object to be tested is found, labels to
1280 // jump to if the object is truthy or falsy, and a scratch register for
1281 // use in the out-of-line path.
1282 void setInputAndTargets(Register objreg, Label* ifEmulatesUndefined,
1283 Label* ifDoesntEmulateUndefined, Register scratch) {
1284 MOZ_ASSERT(!initialized());
1285 MOZ_ASSERT(ifEmulatesUndefined);
1286 objreg_ = objreg;
1287 scratch_ = scratch;
1288 ifEmulatesUndefined_ = ifEmulatesUndefined;
1289 ifDoesntEmulateUndefined_ = ifDoesntEmulateUndefined;
1290 }
1291 };
1292
1293 // A subclass of OutOfLineTestObject containing two extra labels, for use when
1294 // the ifTruthy/ifFalsy labels are needed in inline code as well as out-of-line
1295 // code. The user should bind these labels in inline code, and specify them as
1296 // targets via setInputAndTargets, as appropriate.
1297 class OutOfLineTestObjectWithLabels : public OutOfLineTestObject {
1298 Label label1_;
1299 Label label2_;
1300
1301 public:
1302 OutOfLineTestObjectWithLabels() = default;
1303
1304 Label* label1() { return &label1_; }
1305 Label* label2() { return &label2_; }
1306 };
1307
1308 void CodeGenerator::testObjectEmulatesUndefinedKernel(
1309 Register objreg, Label* ifEmulatesUndefined,
1310 Label* ifDoesntEmulateUndefined, Register scratch,
1311 OutOfLineTestObject* ool) {
1312 ool->setInputAndTargets(objreg, ifEmulatesUndefined, ifDoesntEmulateUndefined,
1313 scratch);
1314
1315 // Perform a fast-path check of the object's class flags if the object's
1316 // not a proxy. Let out-of-line code handle the slow cases that require
1317 // saving registers, making a function call, and restoring registers.
1318 masm.branchIfObjectEmulatesUndefined(objreg, scratch, ool->entry(),
1319 ifEmulatesUndefined);
1320 }
1321
1322 void CodeGenerator::branchTestObjectEmulatesUndefined(
1323 Register objreg, Label* ifEmulatesUndefined,
1324 Label* ifDoesntEmulateUndefined, Register scratch,
1325 OutOfLineTestObject* ool) {
1326 MOZ_ASSERT(!ifDoesntEmulateUndefined->bound(),
1327 "ifDoesntEmulateUndefined will be bound to the fallthrough path");
1328
1329 testObjectEmulatesUndefinedKernel(objreg, ifEmulatesUndefined,
1330 ifDoesntEmulateUndefined, scratch, ool);
1331 masm.bind(ifDoesntEmulateUndefined);
1332 }
1333
1334 void CodeGenerator::testObjectEmulatesUndefined(Register objreg,
1335 Label* ifEmulatesUndefined,
1336 Label* ifDoesntEmulateUndefined,
1337 Register scratch,
1338 OutOfLineTestObject* ool) {
1339 testObjectEmulatesUndefinedKernel(objreg, ifEmulatesUndefined,
1340 ifDoesntEmulateUndefined, scratch, ool);
1341 masm.jump(ifDoesntEmulateUndefined);
1342 }
1343
1344 void CodeGenerator::testValueTruthyForType(
1345 JSValueType type, ScratchTagScope& tag, const ValueOperand& value,
1346 Register tempToUnbox, Register temp, FloatRegister floatTemp,
1347 Label* ifTruthy, Label* ifFalsy, OutOfLineTestObject* ool,
1348 bool skipTypeTest) {
1349 #ifdef DEBUG
1350 if (skipTypeTest) {
1351 Label expected;
1352 masm.branchTestType(Assembler::Equal, tag, type, &expected);
1353 masm.assumeUnreachable("Unexpected Value type in testValueTruthyForType");
1354 masm.bind(&expected);
1355 }
1356 #endif
1357
1358 // Handle irregular types first.
1359 switch (type) {
1360 case JSVAL_TYPE_UNDEFINED:
1361 case JSVAL_TYPE_NULL:
1362 // Undefined and null are falsy.
1363 if (!skipTypeTest) {
1364 masm.branchTestType(Assembler::Equal, tag, type, ifFalsy);
1365 } else {
1366 masm.jump(ifFalsy);
1367 }
1368 return;
1369 case JSVAL_TYPE_SYMBOL:
1370 // Symbols are truthy.
1371 if (!skipTypeTest) {
1372 masm.branchTestSymbol(Assembler::Equal, tag, ifTruthy);
1373 } else {
1374 masm.jump(ifTruthy);
1375 }
1376 return;
1377 case JSVAL_TYPE_OBJECT: {
1378 Label notObject;
1379 if (!skipTypeTest) {
1380 masm.branchTestObject(Assembler::NotEqual, tag, &notObject);
1381 }
1382 ScratchTagScopeRelease _(&tag);
1383 Register objreg = masm.extractObject(value, tempToUnbox);
1384 testObjectEmulatesUndefined(objreg, ifFalsy, ifTruthy, temp, ool);
1385 masm.bind(&notObject);
1386 return;
1387 }
1388 default:
1389 break;
1390 }
1391
1392 // Check the type of the value (unless this is the last possible type).
1393 Label differentType;
1394 if (!skipTypeTest) {
1395 masm.branchTestType(Assembler::NotEqual, tag, type, &differentType);
1396 }
1397
1398 // Branch if the value is falsy.
1399 ScratchTagScopeRelease _(&tag);
1400 switch (type) {
1401 case JSVAL_TYPE_BOOLEAN: {
1402 masm.branchTestBooleanTruthy(false, value, ifFalsy);
1403 break;
1404 }
1405 case JSVAL_TYPE_INT32: {
1406 masm.branchTestInt32Truthy(false, value, ifFalsy);
1407 break;
1408 }
1409 case JSVAL_TYPE_STRING: {
1410 masm.branchTestStringTruthy(false, value, ifFalsy);
1411 break;
1412 }
1413 case JSVAL_TYPE_BIGINT: {
1414 masm.branchTestBigIntTruthy(false, value, ifFalsy);
1415 break;
1416 }
1417 case JSVAL_TYPE_DOUBLE: {
1418 masm.unboxDouble(value, floatTemp);
1419 masm.branchTestDoubleTruthy(false, floatTemp, ifFalsy);
1420 break;
1421 }
1422 default:
1423 MOZ_CRASH("Unexpected value type");
1424 }
1425
1426 // If we reach this point, the value is truthy. We fall through for
1427 // truthy on the last test; otherwise, branch.
1428 if (!skipTypeTest) {
1429 masm.jump(ifTruthy);
1430 }
1431
1432 masm.bind(&differentType);
1433 }
1434
1435 void CodeGenerator::testValueTruthy(const ValueOperand& value,
1436 Register tempToUnbox, Register temp,
1437 FloatRegister floatTemp,
1438 const TypeDataList& observedTypes,
1439 Label* ifTruthy, Label* ifFalsy,
1440 OutOfLineTestObject* ool) {
1441 ScratchTagScope tag(masm, value);
1442 masm.splitTagForTest(value, tag);
1443
1444 const std::initializer_list<JSValueType> defaultOrder = {
1445 JSVAL_TYPE_UNDEFINED, JSVAL_TYPE_NULL, JSVAL_TYPE_BOOLEAN,
1446 JSVAL_TYPE_INT32, JSVAL_TYPE_OBJECT, JSVAL_TYPE_STRING,
1447 JSVAL_TYPE_DOUBLE, JSVAL_TYPE_SYMBOL, JSVAL_TYPE_BIGINT};
1448
1449 mozilla::EnumSet<JSValueType, uint32_t> remaining(defaultOrder);
1450
1451 // Generate tests for previously observed types first.
1452 // The TypeDataList is sorted by descending frequency.
1453 for (auto& observed : observedTypes) {
1454 JSValueType type = observed.type();
1455 remaining -= type;
1456
1457 testValueTruthyForType(type, tag, value, tempToUnbox, temp, floatTemp,
1458 ifTruthy, ifFalsy, ool, /*skipTypeTest*/ false);
1459 }
1460
1461 // Generate tests for remaining types.
1462 for (auto type : defaultOrder) {
1463 if (!remaining.contains(type)) {
1464 continue;
1465 }
1466 remaining -= type;
1467
1468 // We don't need a type test for the last possible type.
1469 bool skipTypeTest = remaining.isEmpty();
1470 testValueTruthyForType(type, tag, value, tempToUnbox, temp, floatTemp,
1471 ifTruthy, ifFalsy, ool, skipTypeTest);
1472 }
1473 MOZ_ASSERT(remaining.isEmpty());
1474
1475 // We fall through if the final test is truthy.
1476 }
1477
1478 void CodeGenerator::visitTestIAndBranch(LTestIAndBranch* test) {
1479 Register input = ToRegister(test->input());
1480 MBasicBlock* ifTrue = test->ifTrue();
1481 MBasicBlock* ifFalse = test->ifFalse();
1482
1483 if (isNextBlock(ifFalse->lir())) {
1484 masm.branchTest32(Assembler::NonZero, input, input,
1485 getJumpLabelForBranch(ifTrue));
1486 } else {
1487 masm.branchTest32(Assembler::Zero, input, input,
1488 getJumpLabelForBranch(ifFalse));
1489 jumpToBlock(ifTrue);
1490 }
1491 }
1492
1493 void CodeGenerator::visitTestIPtrAndBranch(LTestIPtrAndBranch* test) {
1494 Register input = ToRegister(test->input());
1495 MBasicBlock* ifTrue = test->ifTrue();
1496 MBasicBlock* ifFalse = test->ifFalse();
1497
1498 if (isNextBlock(ifFalse->lir())) {
1499 masm.branchTestPtr(Assembler::NonZero, input, input,
1500 getJumpLabelForBranch(ifTrue));
1501 } else {
1502 masm.branchTestPtr(Assembler::Zero, input, input,
1503 getJumpLabelForBranch(ifFalse));
1504 jumpToBlock(ifTrue);
1505 }
1506 }
1507
1508 void CodeGenerator::visitTestI64AndBranch(LTestI64AndBranch* test) {
1509 Register64 input = ToRegister64(test->input());
1510 MBasicBlock* ifTrue = test->ifTrue();
1511 MBasicBlock* ifFalse = test->ifFalse();
1512
1513 if (isNextBlock(ifFalse->lir())) {
1514 masm.branchTest64(Assembler::NonZero, input, input,
1515 getJumpLabelForBranch(ifTrue));
1516 } else if (isNextBlock(ifTrue->lir())) {
1517 masm.branchTest64(Assembler::Zero, input, input,
1518 getJumpLabelForBranch(ifFalse));
1519 } else {
1520 masm.branchTest64(Assembler::NonZero, input, input,
1521 getJumpLabelForBranch(ifTrue),
1522 getJumpLabelForBranch(ifFalse));
1523 }
1524 }
1525
1526 void CodeGenerator::visitTestBIAndBranch(LTestBIAndBranch* lir) {
1527 Register input = ToRegister(lir->input());
1528 MBasicBlock* ifTrue = lir->ifTrue();
1529 MBasicBlock* ifFalse = lir->ifFalse();
1530
1531 if (isNextBlock(ifFalse->lir())) {
1532 masm.branchIfBigIntIsNonZero(input, getJumpLabelForBranch(ifTrue));
1533 } else {
1534 masm.branchIfBigIntIsZero(input, getJumpLabelForBranch(ifFalse));
1535 jumpToBlock(ifTrue);
1536 }
1537 }
1538
1539 static Assembler::Condition ReverseCondition(Assembler::Condition condition) {
1540 switch (condition) {
1541 case Assembler::Equal:
1542 case Assembler::NotEqual:
1543 return condition;
1544 case Assembler::Above:
1545 return Assembler::Below;
1546 case Assembler::AboveOrEqual:
1547 return Assembler::BelowOrEqual;
1548 case Assembler::Below:
1549 return Assembler::Above;
1550 case Assembler::BelowOrEqual:
1551 return Assembler::AboveOrEqual;
1552 case Assembler::GreaterThan:
1553 return Assembler::LessThan;
1554 case Assembler::GreaterThanOrEqual:
1555 return Assembler::LessThanOrEqual;
1556 case Assembler::LessThan:
1557 return Assembler::GreaterThan;
1558 case Assembler::LessThanOrEqual:
1559 return Assembler::GreaterThanOrEqual;
1560 default:
1561 break;
1562 }
1563 MOZ_CRASH("unhandled condition");
1564 }
1565
1566 void CodeGenerator::visitCompare(LCompare* comp) {
1567 MCompare::CompareType compareType = comp->mir()->compareType();
1568 Assembler::Condition cond = JSOpToCondition(compareType, comp->jsop());
1569 Register left = ToRegister(comp->left());
1570 const LAllocation* right = comp->right();
1571 Register output = ToRegister(comp->output());
1572
1573 if (compareType == MCompare::Compare_Object ||
1574 compareType == MCompare::Compare_Symbol ||
1575 compareType == MCompare::Compare_IntPtr ||
1576 compareType == MCompare::Compare_UIntPtr ||
1577 compareType == MCompare::Compare_WasmAnyRef) {
1578 if (right->isConstant()) {
1579 MOZ_ASSERT(compareType == MCompare::Compare_IntPtr ||
1580 compareType == MCompare::Compare_UIntPtr);
1581 masm.cmpPtrSet(cond, left, ImmWord(ToInt32(right)), output);
1582 } else if (right->isGeneralReg()) {
1583 masm.cmpPtrSet(cond, left, ToRegister(right), output);
1584 } else {
1585 masm.cmpPtrSet(ReverseCondition(cond), ToAddress(right), left, output);
1586 }
1587 return;
1588 }
1589
1590 MOZ_ASSERT(compareType == MCompare::Compare_Int32 ||
1591 compareType == MCompare::Compare_UInt32);
1592
1593 if (right->isConstant()) {
1594 masm.cmp32Set(cond, left, Imm32(ToInt32(right)), output);
1595 } else if (right->isGeneralReg()) {
1596 masm.cmp32Set(cond, left, ToRegister(right), output);
1597 } else {
1598 masm.cmp32Set(ReverseCondition(cond), ToAddress(right), left, output);
1599 }
1600 }
1601
1602 void CodeGenerator::visitStrictConstantCompareInt32(
1603 LStrictConstantCompareInt32* comp) {
1604 ValueOperand value = ToValue(comp->value());
1605 int32_t constantVal = comp->mir()->constant();
1606 JSOp op = comp->mir()->jsop();
1607 Register output = ToRegister(comp->output());
1608
1609 Label fail, pass, done, maybeDouble;
1610 masm.branchTestInt32(Assembler::NotEqual, value, &maybeDouble);
1611 masm.branch32(JSOpToCondition(op, true), value.payloadOrValueReg(),
1612 Imm32(constantVal), &pass,
1613 MacroAssembler::LhsHighBitsAreClean::No);
1614 masm.jump(&fail);
1615
1616 masm.bind(&maybeDouble);
1617 {
1618 FloatRegister unboxedValue = ToFloatRegister(comp->temp0());
1619 FloatRegister floatPayload = ToFloatRegister(comp->temp1());
1620
1621 masm.branchTestDouble(Assembler::NotEqual, value,
1622 op == JSOp::StrictEq ? &fail : &pass);
1623
1624 masm.unboxDouble(value, unboxedValue);
1625 masm.loadConstantDouble(double(constantVal), floatPayload);
1626 masm.branchDouble(JSOpToDoubleCondition(op), unboxedValue, floatPayload,
1627 &pass);
1628 }
1629
1630 masm.bind(&fail);
1631 masm.move32(Imm32(0), output);
1632 masm.jump(&done);
1633
1634 masm.bind(&pass);
1635 masm.move32(Imm32(1), output);
1636
1637 masm.bind(&done);
1638 }
1639
1640 void CodeGenerator::visitStrictConstantCompareBoolean(
1641 LStrictConstantCompareBoolean* comp) {
1642 ValueOperand value = ToValue(comp->value());
1643 bool constantVal = comp->mir()->constant();
1644 JSOp op = comp->mir()->jsop();
1645 Register output = ToRegister(comp->output());
1646
1647 Label fail, pass, done;
1648 Register boolUnboxed = ToRegister(comp->temp0());
1649 masm.fallibleUnboxBoolean(value, boolUnboxed,
1650 op == JSOp::StrictEq ? &fail : &pass);
1651 masm.branch32(JSOpToCondition(op, true), boolUnboxed, Imm32(constantVal),
1652 &pass);
1653
1654 masm.bind(&fail);
1655 masm.move32(Imm32(0), output);
1656 masm.jump(&done);
1657
1658 masm.bind(&pass);
1659 masm.move32(Imm32(1), output);
1660
1661 masm.bind(&done);
1662 }
1663
1664 void CodeGenerator::visitCompareAndBranch(LCompareAndBranch* comp) {
1665 MCompare::CompareType compareType = comp->cmpMir()->compareType();
1666 Assembler::Condition cond = JSOpToCondition(compareType, comp->jsop());
1667 Register left = ToRegister(comp->left());
1668 const LAllocation* right = comp->right();
1669
1670 MBasicBlock* ifTrue = comp->ifTrue();
1671 MBasicBlock* ifFalse = comp->ifFalse();
1672
1673 // If the next block is the true case, invert the condition to fall through.
1674 Label* label;
1675 if (isNextBlock(ifTrue->lir())) {
1676 cond = Assembler::InvertCondition(cond);
1677 label = getJumpLabelForBranch(ifFalse);
1678 } else {
1679 label = getJumpLabelForBranch(ifTrue);
1680 }
1681
1682 if (compareType == MCompare::Compare_Object ||
1683 compareType == MCompare::Compare_Symbol ||
1684 compareType == MCompare::Compare_IntPtr ||
1685 compareType == MCompare::Compare_UIntPtr ||
1686 compareType == MCompare::Compare_WasmAnyRef) {
1687 if (right->isConstant()) {
1688 MOZ_ASSERT(compareType == MCompare::Compare_IntPtr ||
1689 compareType == MCompare::Compare_UIntPtr);
1690 masm.branchPtr(cond, left, ImmWord(ToInt32(right)), label);
1691 } else if (right->isGeneralReg()) {
1692 masm.branchPtr(cond, left, ToRegister(right), label);
1693 } else {
1694 masm.branchPtr(ReverseCondition(cond), ToAddress(right), left, label);
1695 }
1696 } else {
1697 MOZ_ASSERT(compareType == MCompare::Compare_Int32 ||
1698 compareType == MCompare::Compare_UInt32);
1699
1700 if (right->isConstant()) {
1701 masm.branch32(cond, left, Imm32(ToInt32(right)), label);
1702 } else if (right->isGeneralReg()) {
1703 masm.branch32(cond, left, ToRegister(right), label);
1704 } else {
1705 masm.branch32(ReverseCondition(cond), ToAddress(right), left, label);
1706 }
1707 }
1708
1709 if (!isNextBlock(ifTrue->lir())) {
1710 jumpToBlock(ifFalse);
1711 }
1712 }
1713
1714 void CodeGenerator::visitCompareI64(LCompareI64* lir) {
1715 MCompare::CompareType compareType = lir->mir()->compareType();
1716 MOZ_ASSERT(compareType == MCompare::Compare_Int64 ||
1717 compareType == MCompare::Compare_UInt64);
1718 bool isSigned = compareType == MCompare::Compare_Int64;
1719 Assembler::Condition cond = JSOpToCondition(lir->jsop(), isSigned);
1720 Register64 left = ToRegister64(lir->left());
1721 LInt64Allocation right = lir->right();
1722 Register output = ToRegister(lir->output());
1723
1724 if (IsConstant(right)) {
1725 masm.cmp64Set(cond, left, Imm64(ToInt64(right)), output);
1726 } else if (IsRegister64(right)) {
1727 masm.cmp64Set(cond, left, ToRegister64(right), output);
1728 } else {
1729 masm.cmp64Set(ReverseCondition(cond), ToAddress(right), left, output);
1730 }
1731 }
1732
1733 void CodeGenerator::visitCompareI64AndBranch(LCompareI64AndBranch* lir) {
1734 MCompare::CompareType compareType = lir->cmpMir()->compareType();
1735 MOZ_ASSERT(compareType == MCompare::Compare_Int64 ||
1736 compareType == MCompare::Compare_UInt64);
1737 bool isSigned = compareType == MCompare::Compare_Int64;
1738 Assembler::Condition cond = JSOpToCondition(lir->jsop(), isSigned);
1739 Register64 left = ToRegister64(lir->left());
1740 LInt64Allocation right = lir->right();
1741
1742 MBasicBlock* ifTrue = lir->ifTrue();
1743 MBasicBlock* ifFalse = lir->ifFalse();
1744
1745 Label* trueLabel = getJumpLabelForBranch(ifTrue);
1746 Label* falseLabel = getJumpLabelForBranch(ifFalse);
1747
1748 // If the next block is the true case, invert the condition to fall through.
1749 if (isNextBlock(ifTrue->lir())) {
1750 cond = Assembler::InvertCondition(cond);
1751 trueLabel = falseLabel;
1752 falseLabel = nullptr;
1753 } else if (isNextBlock(ifFalse->lir())) {
1754 falseLabel = nullptr;
1755 }
1756
1757 if (IsConstant(right)) {
1758 masm.branch64(cond, left, Imm64(ToInt64(right)), trueLabel, falseLabel);
1759 } else if (IsRegister64(right)) {
1760 masm.branch64(cond, left, ToRegister64(right), trueLabel, falseLabel);
1761 } else {
1762 masm.branch64(ReverseCondition(cond), ToAddress(right), left, trueLabel,
1763 falseLabel);
1764 }
1765 }
1766
1767 void CodeGenerator::visitBitAndAndBranch(LBitAndAndBranch* baab) {
1768 Assembler::Condition cond = baab->cond();
1769 MOZ_ASSERT(cond == Assembler::Zero || cond == Assembler::NonZero);
1770
1771 Register left = ToRegister(baab->left());
1772 const LAllocation* right = baab->right();
1773
1774 MBasicBlock* ifTrue = baab->ifTrue();
1775 MBasicBlock* ifFalse = baab->ifFalse();
1776
1777 // If the next block is the true case, invert the condition to fall through.
1778 Label* label;
1779 if (isNextBlock(ifTrue->lir())) {
1780 cond = Assembler::InvertCondition(cond);
1781 label = getJumpLabelForBranch(ifFalse);
1782 } else {
1783 label = getJumpLabelForBranch(ifTrue);
1784 }
1785
1786 if (right->isConstant()) {
1787 masm.branchTest32(cond, left, Imm32(ToInt32(right)), label);
1788 } else {
1789 masm.branchTest32(cond, left, ToRegister(right), label);
1790 }
1791
1792 if (!isNextBlock(ifTrue->lir())) {
1793 jumpToBlock(ifFalse);
1794 }
1795 }
1796
1797 void CodeGenerator::visitBitAnd64AndBranch(LBitAnd64AndBranch* baab) {
1798 Assembler::Condition cond = baab->cond();
1799 MOZ_ASSERT(cond == Assembler::Zero || cond == Assembler::NonZero);
1800
1801 Register64 left = ToRegister64(baab->left());
1802 LInt64Allocation right = baab->right();
1803
1804 MBasicBlock* ifTrue = baab->ifTrue();
1805 MBasicBlock* ifFalse = baab->ifFalse();
1806
1807 Label* trueLabel = getJumpLabelForBranch(ifTrue);
1808 Label* falseLabel = getJumpLabelForBranch(ifFalse);
1809
1810 // If the next block is the true case, invert the condition to fall through.
1811 if (isNextBlock(ifTrue->lir())) {
1812 cond = Assembler::InvertCondition(cond);
1813 trueLabel = falseLabel;
1814 falseLabel = nullptr;
1815 } else if (isNextBlock(ifFalse->lir())) {
1816 falseLabel = nullptr;
1817 }
1818
1819 if (IsConstant(right)) {
1820 masm.branchTest64(cond, left, Imm64(ToInt64(right)), trueLabel, falseLabel);
1821 } else {
1822 masm.branchTest64(cond, left, ToRegister64(right), trueLabel, falseLabel);
1823 }
1824 }
1825
1826 void CodeGenerator::assertObjectDoesNotEmulateUndefined(
1827 Register input, Register temp, const MInstruction* mir) {
1828 #if defined(DEBUG) || defined(FUZZING)
1829 // Validate that the object indeed doesn't have the emulates undefined flag.
1830 auto* ool = new (alloc()) OutOfLineTestObjectWithLabels();
1831 addOutOfLineCode(ool, mir);
1832
1833 Label* doesNotEmulateUndefined = ool->label1();
1834 Label* emulatesUndefined = ool->label2();
1835
1836 testObjectEmulatesUndefined(input, emulatesUndefined, doesNotEmulateUndefined,
1837 temp, ool);
1838 masm.bind(emulatesUndefined);
1839 masm.assumeUnreachable(
1840 "Found an object emulating undefined while the fuse is intact");
1841 masm.bind(doesNotEmulateUndefined);
1842 #endif
1843 }
1844
1845 void CodeGenerator::visitTestOAndBranch(LTestOAndBranch* lir) {
1846 Label* truthy = getJumpLabelForBranch(lir->ifTruthy());
1847 Label* falsy = getJumpLabelForBranch(lir->ifFalsy());
1848 Register input = ToRegister(lir->input());
1849 Register temp = ToRegister(lir->temp0());
1850
1851 bool intact = hasSeenObjectEmulateUndefinedFuseIntactAndDependencyNoted();
1852 if (intact) {
1853 assertObjectDoesNotEmulateUndefined(input, temp, lir->mir());
1854 // Bug 1874905: It would be fantastic if this could be optimized out
1855 masm.jump(truthy);
1856 } else {
1857 auto* ool = new (alloc()) OutOfLineTestObject();
1858 addOutOfLineCode(ool, lir->mir());
1859
1860 testObjectEmulatesUndefined(input, falsy, truthy, temp, ool);
1861 }
1862 }
1863
1864 void CodeGenerator::visitTestVAndBranch(LTestVAndBranch* lir) {
1865 auto* ool = new (alloc()) OutOfLineTestObject();
1866 addOutOfLineCode(ool, lir->mir());
1867
1868 Label* truthy = getJumpLabelForBranch(lir->ifTruthy());
1869 Label* falsy = getJumpLabelForBranch(lir->ifFalsy());
1870
1871 ValueOperand input = ToValue(lir->input());
1872 Register tempToUnbox = ToTempUnboxRegister(lir->temp1());
1873 Register temp = ToRegister(lir->temp2());
1874 FloatRegister floatTemp = ToFloatRegister(lir->temp0());
1875 const TypeDataList& observedTypes = lir->mir()->observedTypes();
1876
1877 testValueTruthy(input, tempToUnbox, temp, floatTemp, observedTypes, truthy,
1878 falsy, ool);
1879 masm.jump(truthy);
1880 }
1881
1882 void CodeGenerator::visitBooleanToString(LBooleanToString* lir) {
1883 Register input = ToRegister(lir->input());
1884 Register output = ToRegister(lir->output());
1885 const JSAtomState& names = gen->runtime->names();
1886 Label true_, done;
1887
1888 masm.branchTest32(Assembler::NonZero, input, input, &true_);
1889 masm.movePtr(ImmGCPtr(names.false_), output);
1890 masm.jump(&done);
1891
1892 masm.bind(&true_);
1893 masm.movePtr(ImmGCPtr(names.true_), output);
1894
1895 masm.bind(&done);
1896 }
1897
1898 void CodeGenerator::visitIntToString(LIntToString* lir) {
1899 Register input = ToRegister(lir->input());
1900 Register output = ToRegister(lir->output());
1901
1902 using Fn = JSLinearString* (*)(JSContext*, int);
1903 OutOfLineCode* ool = oolCallVM<Fn, Int32ToString<CanGC>>(
1904 lir, ArgList(input), StoreRegisterTo(output));
1905
1906 masm.lookupStaticIntString(input, output, gen->runtime->staticStrings(),
1907 ool->entry());
1908
1909 masm.bind(ool->rejoin());
1910 }
1911
1912 void CodeGenerator::visitDoubleToString(LDoubleToString* lir) {
1913 FloatRegister input = ToFloatRegister(lir->input());
1914 Register temp = ToRegister(lir->temp0());
1915 Register output = ToRegister(lir->output());
1916
1917 using Fn = JSString* (*)(JSContext*, double);
1918 OutOfLineCode* ool = oolCallVM<Fn, NumberToString<CanGC>>(
1919 lir, ArgList(input), StoreRegisterTo(output));
1920
1921 // Try double to integer conversion and run integer to string code.
1922 masm.convertDoubleToInt32(input, temp, ool->entry(), false);
1923 masm.lookupStaticIntString(temp, output, gen->runtime->staticStrings(),
1924 ool->entry());
1925
1926 masm.bind(ool->rejoin());
1927 }
1928
1929 void CodeGenerator::visitValueToString(LValueToString* lir) {
1930 ValueOperand input = ToValue(lir->input());
1931 Register output = ToRegister(lir->output());
1932
1933 using Fn = JSString* (*)(JSContext*, HandleValue);
1934 OutOfLineCode* ool = oolCallVM<Fn, ToStringSlow<CanGC>>(
1935 lir, ArgList(input), StoreRegisterTo(output));
1936
1937 Label done;
1938 Register tag = masm.extractTag(input, output);
1939 const JSAtomState& names = gen->runtime->names();
1940
1941 // String
1942 {
1943 Label notString;
1944 masm.branchTestString(Assembler::NotEqual, tag, &notString);
1945 masm.unboxString(input, output);
1946 masm.jump(&done);
1947 masm.bind(&notString);
1948 }
1949
1950 // Integer
1951 {
1952 Label notInteger;
1953 masm.branchTestInt32(Assembler::NotEqual, tag, &notInteger);
1954 Register unboxed = ToTempUnboxRegister(lir->temp0());
1955 unboxed = masm.extractInt32(input, unboxed);
1956 masm.lookupStaticIntString(unboxed, output, gen->runtime->staticStrings(),
1957 ool->entry());
1958 masm.jump(&done);
1959 masm.bind(&notInteger);
1960 }
1961
1962 // Double
1963 {
1964 // Note: no fastpath. Need two extra registers and can only convert doubles
1965 // that fit integers and are smaller than StaticStrings::INT_STATIC_LIMIT.
1966 masm.branchTestDouble(Assembler::Equal, tag, ool->entry());
1967 }
1968
1969 // Undefined
1970 {
1971 Label notUndefined;
1972 masm.branchTestUndefined(Assembler::NotEqual, tag, &notUndefined);
1973 masm.movePtr(ImmGCPtr(names.undefined), output);
1974 masm.jump(&done);
1975 masm.bind(&notUndefined);
1976 }
1977
1978 // Null
1979 {
1980 Label notNull;
1981 masm.branchTestNull(Assembler::NotEqual, tag, &notNull);
1982 masm.movePtr(ImmGCPtr(names.null), output);
1983 masm.jump(&done);
1984 masm.bind(&notNull);
1985 }
1986
1987 // Boolean
1988 {
1989 Label notBoolean, true_;
1990 masm.branchTestBoolean(Assembler::NotEqual, tag, &notBoolean);
1991 masm.branchTestBooleanTruthy(true, input, &true_);
1992 masm.movePtr(ImmGCPtr(names.false_), output);
1993 masm.jump(&done);
1994 masm.bind(&true_);
1995 masm.movePtr(ImmGCPtr(names.true_), output);
1996 masm.jump(&done);
1997 masm.bind(&notBoolean);
1998 }
1999
2000 // Objects/symbols are only possible when |mir->mightHaveSideEffects()|.
2001 if (lir->mir()->mightHaveSideEffects()) {
2002 // Object
2003 if (lir->mir()->supportSideEffects()) {
2004 masm.branchTestObject(Assembler::Equal, tag, ool->entry());
2005 } else {
2006 // Bail.
2007 MOZ_ASSERT(lir->mir()->needsSnapshot());
2008 Label bail;
2009 masm.branchTestObject(Assembler::Equal, tag, &bail);
2010 bailoutFrom(&bail, lir->snapshot());
2011 }
2012
2013 // Symbol
2014 if (lir->mir()->supportSideEffects()) {
2015 masm.branchTestSymbol(Assembler::Equal, tag, ool->entry());
2016 } else {
2017 // Bail.
2018 MOZ_ASSERT(lir->mir()->needsSnapshot());
2019 Label bail;
2020 masm.branchTestSymbol(Assembler::Equal, tag, &bail);
2021 bailoutFrom(&bail, lir->snapshot());
2022 }
2023 }
2024
2025 // BigInt
2026 {
2027 // No fastpath currently implemented.
2028 masm.branchTestBigInt(Assembler::Equal, tag, ool->entry());
2029 }
2030
2031 masm.assumeUnreachable("Unexpected type for LValueToString.");
2032
2033 masm.bind(&done);
2034 masm.bind(ool->rejoin());
2035 }
2036
2037 using StoreBufferMutationFn = void (*)(js::gc::StoreBuffer*, js::gc::Cell**);
2038
2039 static void EmitStoreBufferMutation(MacroAssembler& masm, Register holder,
2040 size_t offset, Register buffer,
2041 LiveGeneralRegisterSet& liveVolatiles,
2042 StoreBufferMutationFn fun) {
2043 Label callVM;
2044 Label exit;
2045
2046 // Call into the VM to barrier the write. The only registers that need to
2047 // be preserved are those in liveVolatiles, so once they are saved on the
2048 // stack all volatile registers are available for use.
2049 masm.bind(&callVM);
2050 masm.PushRegsInMask(liveVolatiles);
2051
2052 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::Volatile());
2053 regs.takeUnchecked(buffer);
2054 regs.takeUnchecked(holder);
2055 Register addrReg = regs.takeAny();
2056
2057 masm.computeEffectiveAddress(Address(holder, offset), addrReg);
2058
2059 bool needExtraReg = !regs.hasAny<GeneralRegisterSet::DefaultType>();
2060 if (needExtraReg) {
2061 masm.push(holder);
2062 masm.setupUnalignedABICall(holder);
2063 } else {
2064 masm.setupUnalignedABICall(regs.takeAny());
2065 }
2066 masm.passABIArg(buffer);
2067 masm.passABIArg(addrReg);
2068 masm.callWithABI(DynamicFunction<StoreBufferMutationFn>(fun),
2069 ABIType::General, CheckUnsafeCallWithABI::DontCheckOther);
2070
2071 if (needExtraReg) {
2072 masm.pop(holder);
2073 }
2074 masm.PopRegsInMask(liveVolatiles);
2075 masm.bind(&exit);
2076 }
2077
2078 // Warning: this function modifies prev and next.
2079 static void EmitPostWriteBarrierS(MacroAssembler& masm, Register holder,
2080 size_t offset, Register prev, Register next,
2081 LiveGeneralRegisterSet& liveVolatiles) {
2082 Label exit;
2083 Label checkRemove, putCell;
2084
2085 // if (next && (buffer = next->storeBuffer()))
2086 // but we never pass in nullptr for next.
2087 Register storebuffer = next;
2088 masm.loadStoreBuffer(next, storebuffer);
2089 masm.branchPtr(Assembler::Equal, storebuffer, ImmWord(0), &checkRemove);
2090
2091 // if (prev && prev->storeBuffer())
2092 masm.branchPtr(Assembler::Equal, prev, ImmWord(0), &putCell);
2093 masm.loadStoreBuffer(prev, prev);
2094 masm.branchPtr(Assembler::NotEqual, prev, ImmWord(0), &exit);
2095
2096 // buffer->putCell(cellp)
2097 masm.bind(&putCell);
2098 EmitStoreBufferMutation(masm, holder, offset, storebuffer, liveVolatiles,
2099 JSString::addCellAddressToStoreBuffer);
2100 masm.jump(&exit);
2101
2102 // if (prev && (buffer = prev->storeBuffer()))
2103 masm.bind(&checkRemove);
2104 masm.branchPtr(Assembler::Equal, prev, ImmWord(0), &exit);
2105 masm.loadStoreBuffer(prev, storebuffer);
2106 masm.branchPtr(Assembler::Equal, storebuffer, ImmWord(0), &exit);
2107 EmitStoreBufferMutation(masm, holder, offset, storebuffer, liveVolatiles,
2108 JSString::removeCellAddressFromStoreBuffer);
2109
2110 masm.bind(&exit);
2111 }
2112
2113 void CodeGenerator::visitRegExp(LRegExp* lir) {
2114 Register output = ToRegister(lir->output());
2115 Register temp = ToRegister(lir->temp0());
2116 JSObject* source = lir->mir()->source();
2117
2118 using Fn = JSObject* (*)(JSContext*, Handle<RegExpObject*>);
2119 OutOfLineCode* ool = oolCallVM<Fn, CloneRegExpObject>(
2120 lir, ArgList(ImmGCPtr(source)), StoreRegisterTo(output));
2121 if (lir->mir()->hasShared()) {
2122 TemplateObject templateObject(source);
2123 masm.createGCObject(output, temp, templateObject, gc::Heap::Default,
2124 ool->entry());
2125 } else {
2126 masm.jump(ool->entry());
2127 }
2128 masm.bind(ool->rejoin());
2129 }
2130
2131 static constexpr int32_t RegExpPairsVectorStartOffset(
2132 int32_t inputOutputDataStartOffset) {
2133 return inputOutputDataStartOffset + int32_t(InputOutputDataSize) +
2134 int32_t(sizeof(MatchPairs));
2135 }
2136
2137 static Address RegExpPairCountAddress(MacroAssembler& masm,
2138 int32_t inputOutputDataStartOffset) {
2139 return Address(FramePointer, inputOutputDataStartOffset +
2140 int32_t(InputOutputDataSize) +
2141 MatchPairs::offsetOfPairCount());
2142 }
2143
2144 static void UpdateRegExpStatics(MacroAssembler& masm, Register regexp,
2145 Register input, Register lastIndex,
2146 Register staticsReg, Register temp1,
2147 Register temp2, gc::Heap initialStringHeap,
2148 LiveGeneralRegisterSet& volatileRegs) {
2149 Address pendingInputAddress(staticsReg,
2150 RegExpStatics::offsetOfPendingInput());
2151 Address matchesInputAddress(staticsReg,
2152 RegExpStatics::offsetOfMatchesInput());
2153 Address lazySourceAddress(staticsReg, RegExpStatics::offsetOfLazySource());
2154 Address lazyIndexAddress(staticsReg, RegExpStatics::offsetOfLazyIndex());
2155
2156 masm.guardedCallPreBarrier(pendingInputAddress, MIRType::String);
2157 masm.guardedCallPreBarrier(matchesInputAddress, MIRType::String);
2158 masm.guardedCallPreBarrier(lazySourceAddress, MIRType::String);
2159
2160 if (initialStringHeap == gc::Heap::Default) {
2161 // Writing into RegExpStatics tenured memory; must post-barrier.
2162 if (staticsReg.volatile_()) {
2163 volatileRegs.add(staticsReg);
2164 }
2165
2166 masm.loadPtr(pendingInputAddress, temp1);
2167 masm.storePtr(input, pendingInputAddress);
2168 masm.movePtr(input, temp2);
2169 EmitPostWriteBarrierS(masm, staticsReg,
2170 RegExpStatics::offsetOfPendingInput(),
2171 temp1 /* prev */, temp2 /* next */, volatileRegs);
2172
2173 masm.loadPtr(matchesInputAddress, temp1);
2174 masm.storePtr(input, matchesInputAddress);
2175 masm.movePtr(input, temp2);
2176 EmitPostWriteBarrierS(masm, staticsReg,
2177 RegExpStatics::offsetOfMatchesInput(),
2178 temp1 /* prev */, temp2 /* next */, volatileRegs);
2179 } else {
2180 masm.debugAssertGCThingIsTenured(input, temp1);
2181 masm.storePtr(input, pendingInputAddress);
2182 masm.storePtr(input, matchesInputAddress);
2183 }
2184
2185 masm.storePtr(lastIndex,
2186 Address(staticsReg, RegExpStatics::offsetOfLazyIndex()));
2187 masm.store32(
2188 Imm32(1),
2189 Address(staticsReg, RegExpStatics::offsetOfPendingLazyEvaluation()));
2190
2191 masm.unboxNonDouble(Address(regexp, NativeObject::getFixedSlotOffset(
2192 RegExpObject::SHARED_SLOT)),
2193 temp1, JSVAL_TYPE_PRIVATE_GCTHING);
2194 masm.loadPtr(Address(temp1, RegExpShared::offsetOfSource()), temp2);
2195 masm.storePtr(temp2, lazySourceAddress);
2196 static_assert(sizeof(JS::RegExpFlags) == 1, "load size must match flag size");
2197 masm.load8ZeroExtend(Address(temp1, RegExpShared::offsetOfFlags()), temp2);
2198 masm.store8(temp2, Address(staticsReg, RegExpStatics::offsetOfLazyFlags()));
2199 }
2200
2201 // Prepare an InputOutputData and optional MatchPairs which space has been
2202 // allocated for on the stack, and try to execute a RegExp on a string input.
2203 // If the RegExp was successfully executed and matched the input, fallthrough.
2204 // Otherwise, jump to notFound or failure.
2205 //
2206 // inputOutputDataStartOffset is the offset relative to the frame pointer
2207 // register. This offset is negative for the RegExpExecTest stub.
2208 static bool PrepareAndExecuteRegExp(MacroAssembler& masm, Register regexp,
2209 Register input, Register lastIndex,
2210 Register temp1, Register temp2,
2211 Register temp3,
2212 int32_t inputOutputDataStartOffset,
2213 gc::Heap initialStringHeap, Label* notFound,
2214 Label* failure) {
2215 JitSpew(JitSpew_Codegen, "# Emitting PrepareAndExecuteRegExp");
2216
2217 using irregexp::InputOutputData;
2218
2219 /*
2220 * [SMDOC] Stack layout for PrepareAndExecuteRegExp
2221 *
2222 * Before this function is called, the caller is responsible for
2223 * allocating enough stack space for the following data:
2224 *
2225 * inputOutputDataStartOffset +-----> +---------------+
2226 * |InputOutputData|
2227 * inputStartAddress +----------> inputStart|
2228 * inputEndAddress +----------> inputEnd|
2229 * startIndexAddress +----------> startIndex|
2230 * matchesAddress +----------> matches|-----+
2231 * +---------------+ |
2232 * matchPairs(Address|Offset) +-----> +---------------+ <--+
2233 * | MatchPairs |
2234 * pairCountAddress +----------> count |
2235 * pairsPointerAddress +----------> pairs |-----+
2236 * +---------------+ |
2237 * pairsArray(Address|Offset) +-----> +---------------+ <--+
2238 * | MatchPair |
2239 * firstMatchStartAddress +----------> start | <--+
2240 * | limit | |
2241 * +---------------+ |
2242 * . |
2243 * . Reserved space for
2244 * . RegExpObject::MaxPairCount
2245 * . MatchPair objects
2246 * . |
2247 * +---------------+ |
2248 * | MatchPair | |
2249 * | start | |
2250 * | limit | <--+
2251 * +---------------+
2252 */
2253
2254 int32_t ioOffset = inputOutputDataStartOffset;
2255 int32_t matchPairsOffset = ioOffset + int32_t(sizeof(InputOutputData));
2256 int32_t pairsArrayOffset = matchPairsOffset + int32_t(sizeof(MatchPairs));
2257
2258 Address inputStartAddress(FramePointer,
2259 ioOffset + InputOutputData::offsetOfInputStart());
2260 Address inputEndAddress(FramePointer,
2261 ioOffset + InputOutputData::offsetOfInputEnd());
2262 Address startIndexAddress(FramePointer,
2263 ioOffset + InputOutputData::offsetOfStartIndex());
2264 Address matchesAddress(FramePointer,
2265 ioOffset + InputOutputData::offsetOfMatches());
2266
2267 Address matchPairsAddress(FramePointer, matchPairsOffset);
2268 Address pairCountAddress(FramePointer,
2269 matchPairsOffset + MatchPairs::offsetOfPairCount());
2270 Address pairsPointerAddress(FramePointer,
2271 matchPairsOffset + MatchPairs::offsetOfPairs());
2272
2273 Address pairsArrayAddress(FramePointer, pairsArrayOffset);
2274 Address firstMatchStartAddress(FramePointer,
2275 pairsArrayOffset + MatchPair::offsetOfStart());
2276
2277 // First, fill in a skeletal MatchPairs instance on the stack. This will be
2278 // passed to the OOL stub in the caller if we aren't able to execute the
2279 // RegExp inline, and that stub needs to be able to determine whether the
2280 // execution finished successfully.
2281
2282 // Initialize MatchPairs::pairCount to 1. The correct value can only
2283 // be determined after loading the RegExpShared. If the RegExpShared
2284 // has Kind::Atom, this is the correct pairCount.
2285 masm.store32(Imm32(1), pairCountAddress);
2286
2287 // Initialize MatchPairs::pairs pointer
2288 masm.computeEffectiveAddress(pairsArrayAddress, temp1);
2289 masm.storePtr(temp1, pairsPointerAddress);
2290
2291 // Initialize MatchPairs::pairs[0]::start to MatchPair::NoMatch
2292 masm.store32(Imm32(MatchPair::NoMatch), firstMatchStartAddress);
2293
2294 // Determine the set of volatile inputs to save when calling into C++ or
2295 // regexp code.
2296 LiveGeneralRegisterSet volatileRegs;
2297 if (lastIndex.volatile_()) {
2298 volatileRegs.add(lastIndex);
2299 }
2300 if (input.volatile_()) {
2301 volatileRegs.add(input);
2302 }
2303 if (regexp.volatile_()) {
2304 volatileRegs.add(regexp);
2305 }
2306
2307 // Ensure the input string is not a rope.
2308 Label isLinear;
2309 masm.branchIfNotRope(input, &isLinear);
2310 {
2311 masm.PushRegsInMask(volatileRegs);
2312
2313 using Fn = JSLinearString* (*)(JSString*);
2314 masm.setupUnalignedABICall(temp1);
2315 masm.passABIArg(input);
2316 masm.callWithABI<Fn, js::jit::LinearizeForCharAccessPure>();
2317
2318 MOZ_ASSERT(!volatileRegs.has(temp1));
2319 masm.storeCallPointerResult(temp1);
2320 masm.PopRegsInMask(volatileRegs);
2321
2322 masm.branchTestPtr(Assembler::Zero, temp1, temp1, failure);
2323 }
2324 masm.bind(&isLinear);
2325
2326 // Load the RegExpShared.
2327 Register regexpReg = temp1;
2328 Address sharedSlot = Address(
2329 regexp, NativeObject::getFixedSlotOffset(RegExpObject::SHARED_SLOT));
2330 masm.branchTestUndefined(Assembler::Equal, sharedSlot, failure);
2331 masm.unboxNonDouble(sharedSlot, regexpReg, JSVAL_TYPE_PRIVATE_GCTHING);
2332
2333 // Handle Atom matches
2334 Label notAtom, checkSuccess;
2335 masm.branchPtr(Assembler::Equal,
2336 Address(regexpReg, RegExpShared::offsetOfPatternAtom()),
2337 ImmWord(0), &notAtom);
2338 {
2339 masm.computeEffectiveAddress(matchPairsAddress, temp3);
2340
2341 masm.PushRegsInMask(volatileRegs);
2342 using Fn =
2343 RegExpRunStatus (*)(RegExpShared* re, const JSLinearString* input,
2344 size_t start, MatchPairs* matchPairs);
2345 masm.setupUnalignedABICall(temp2);
2346 masm.passABIArg(regexpReg);
2347 masm.passABIArg(input);
2348 masm.passABIArg(lastIndex);
2349 masm.passABIArg(temp3);
2350 masm.callWithABI<Fn, js::ExecuteRegExpAtomRaw>();
2351
2352 MOZ_ASSERT(!volatileRegs.has(temp1));
2353 masm.storeCallInt32Result(temp1);
2354 masm.PopRegsInMask(volatileRegs);
2355
2356 masm.jump(&checkSuccess);
2357 }
2358 masm.bind(&notAtom);
2359
2360 // Don't handle regexps with too many capture pairs.
2361 masm.load32(Address(regexpReg, RegExpShared::offsetOfPairCount()), temp2);
2362 masm.branch32(Assembler::Above, temp2, Imm32(RegExpObject::MaxPairCount),
2363 failure);
2364
2365 // Fill in the pair count in the MatchPairs on the stack.
2366 masm.store32(temp2, pairCountAddress);
2367
2368 // Load code pointer and length of input (in bytes).
2369 // Store the input start in the InputOutputData.
2370 Register codePointer = temp1; // Note: temp1 was previously regexpReg.
2371 Register byteLength = temp3;
2372 {
2373 Label isLatin1, done;
2374 masm.loadStringLength(input, byteLength);
2375
2376 masm.branchLatin1String(input, &isLatin1);
2377
2378 // Two-byte input
2379 masm.loadStringChars(input, temp2, CharEncoding::TwoByte);
2380 masm.storePtr(temp2, inputStartAddress);
2381 masm.loadPtr(
2382 Address(regexpReg, RegExpShared::offsetOfJitCode(/*latin1 =*/false)),
2383 codePointer);
2384 masm.lshiftPtr(Imm32(1), byteLength);
2385 masm.jump(&done);
2386
2387 // Latin1 input
2388 masm.bind(&isLatin1);
2389 masm.loadStringChars(input, temp2, CharEncoding::Latin1);
2390 masm.storePtr(temp2, inputStartAddress);
2391 masm.loadPtr(
2392 Address(regexpReg, RegExpShared::offsetOfJitCode(/*latin1 =*/true)),
2393 codePointer);
2394
2395 masm.bind(&done);
2396
2397 // Store end pointer
2398 masm.addPtr(byteLength, temp2);
2399 masm.storePtr(temp2, inputEndAddress);
2400 }
2401
2402 // Guard that the RegExpShared has been compiled for this type of input.
2403 // If it has not been compiled, we fall back to the OOL case, which will
2404 // do a VM call into the interpreter.
2405 // TODO: add an interpreter trampoline?
2406 masm.branchPtr(Assembler::Equal, codePointer, ImmWord(0), failure);
2407 masm.loadPtr(Address(codePointer, JitCode::offsetOfCode()), codePointer);
2408
2409 // Finish filling in the InputOutputData instance on the stack
2410 masm.computeEffectiveAddress(matchPairsAddress, temp2);
2411 masm.storePtr(temp2, matchesAddress);
2412 masm.storePtr(lastIndex, startIndexAddress);
2413
2414 // Execute the RegExp.
2415 masm.computeEffectiveAddress(
2416 Address(FramePointer, inputOutputDataStartOffset), temp2);
2417 masm.PushRegsInMask(volatileRegs);
2418 masm.setupUnalignedABICall(temp3);
2419 masm.passABIArg(temp2);
2420 masm.callWithABI(codePointer);
2421 masm.storeCallInt32Result(temp1);
2422 masm.PopRegsInMask(volatileRegs);
2423
2424 masm.bind(&checkSuccess);
2425 masm.branch32(Assembler::Equal, temp1,
2426 Imm32(int32_t(RegExpRunStatus::Success_NotFound)), notFound);
2427 masm.branch32(Assembler::Equal, temp1, Imm32(int32_t(RegExpRunStatus::Error)),
2428 failure);
2429
2430 // Lazily update the RegExpStatics.
2431 size_t offset = GlobalObjectData::offsetOfRegExpRealm() +
2432 RegExpRealm::offsetOfRegExpStatics();
2433 masm.loadGlobalObjectData(temp1);
2434 masm.loadPtr(Address(temp1, offset), temp1);
2435 UpdateRegExpStatics(masm, regexp, input, lastIndex, temp1, temp2, temp3,
2436 initialStringHeap, volatileRegs);
2437
2438 return true;
2439 }
2440
2441 static void EmitInitDependentStringBase(MacroAssembler& masm,
2442 Register dependent, Register base,
2443 Register temp1, Register temp2,
2444 bool needsPostBarrier) {
2445 // Determine the base string to use and store it in temp2.
2446 Label notDependent, markedDependedOn;
2447 masm.load32(Address(base, JSString::offsetOfFlags()), temp1);
2448 masm.branchTest32(Assembler::Zero, temp1, Imm32(JSString::DEPENDENT_BIT),
2449 &notDependent);
2450 {
2451 // The base is also a dependent string. Load its base to prevent chains of
2452 // dependent strings in most cases. This must either be an atom or already
2453 // have the DEPENDED_ON_BIT set.
2454 masm.loadDependentStringBase(base, temp2);
2455 masm.jump(&markedDependedOn);
2456 }
2457 masm.bind(&notDependent);
2458 {
2459 // The base is not a dependent string. Set the DEPENDED_ON_BIT if it's not
2460 // an atom.
2461 masm.movePtr(base, temp2);
2462 masm.branchTest32(Assembler::NonZero, temp1, Imm32(JSString::ATOM_BIT),
2463 &markedDependedOn);
2464 masm.or32(Imm32(JSString::DEPENDED_ON_BIT), temp1);
2465 masm.store32(temp1, Address(temp2, JSString::offsetOfFlags()));
2466 }
2467 masm.bind(&markedDependedOn);
2468
2469 #ifdef DEBUG
2470 // Assert the base has the DEPENDED_ON_BIT set or is an atom.
2471 Label isAppropriatelyMarked;
2472 masm.branchTest32(Assembler::NonZero,
2473 Address(temp2, JSString::offsetOfFlags()),
2474 Imm32(JSString::ATOM_BIT | JSString::DEPENDED_ON_BIT),
2475 &isAppropriatelyMarked);
2476 masm.assumeUnreachable("Base string is missing DEPENDED_ON_BIT");
2477 masm.bind(&isAppropriatelyMarked);
2478 #endif
2479 masm.storeDependentStringBase(temp2, dependent);
2480
2481 // Post-barrier the base store. The base is still in temp2.
2482 if (needsPostBarrier) {
2483 Label done;
2484 masm.branchPtrInNurseryChunk(Assembler::Equal, dependent, temp1, &done);
2485 masm.branchPtrInNurseryChunk(Assembler::NotEqual, temp2, temp1, &done);
2486
2487 LiveRegisterSet regsToSave(RegisterSet::Volatile());
2488 regsToSave.takeUnchecked(temp1);
2489 regsToSave.takeUnchecked(temp2);
2490
2491 masm.PushRegsInMask(regsToSave);
2492
2493 masm.mov(ImmPtr(masm.runtime()), temp1);
2494
2495 using Fn = void (*)(JSRuntime* rt, js::gc::Cell* cell);
2496 masm.setupUnalignedABICall(temp2);
2497 masm.passABIArg(temp1);
2498 masm.passABIArg(dependent);
2499 masm.callWithABI<Fn, PostWriteBarrier>();
2500
2501 masm.PopRegsInMask(regsToSave);
2502
2503 masm.bind(&done);
2504 } else {
2505 #ifdef DEBUG
2506 Label done;
2507 masm.branchPtrInNurseryChunk(Assembler::Equal, dependent, temp1, &done);
2508 masm.branchPtrInNurseryChunk(Assembler::NotEqual, temp2, temp1, &done);
2509 masm.assumeUnreachable("Missing post barrier for dependent string base");
2510 masm.bind(&done);
2511 #endif
2512 }
2513 }
2514
2515 static void CopyStringChars(MacroAssembler& masm, Register to, Register from,
2516 Register len, Register byteOpScratch,
2517 CharEncoding encoding,
2518 size_t maximumLength = SIZE_MAX);
2519
2520 class CreateDependentString {
2521 CharEncoding encoding_;
2522 Register string_;
2523 Register temp1_;
2524 Register temp2_;
2525 Label* failure_;
2526
2527 enum class FallbackKind : uint8_t {
2528 InlineString,
2529 FatInlineString,
2530 NotInlineString,
2531 Count
2532 };
2533 mozilla::EnumeratedArray<FallbackKind, Label, size_t(FallbackKind::Count)>
2534 fallbacks_, joins_;
2535
2536 public:
2537 CreateDependentString(CharEncoding encoding, Register string, Register temp1,
2538 Register temp2, Label* failure)
2539 : encoding_(encoding),
2540 string_(string),
2541 temp1_(temp1),
2542 temp2_(temp2),
2543 failure_(failure) {}
2544
2545 Register string() const { return string_; }
2546 CharEncoding encoding() const { return encoding_; }
2547
2548 // Generate code that creates DependentString.
2549 // Caller should call generateFallback after masm.ret(), to generate
2550 // fallback path.
2551 void generate(MacroAssembler& masm, const JSAtomState& names,
2552 CompileRuntime* runtime, Register base,
2553 BaseIndex startIndexAddress, BaseIndex limitIndexAddress,
2554 gc::Heap initialStringHeap);
2555
2556 // Generate fallback path for creating DependentString.
2557 void generateFallback(MacroAssembler& masm);
2558 };
2559
2560 void CreateDependentString::generate(MacroAssembler& masm,
2561 const JSAtomState& names,
2562 CompileRuntime* runtime, Register base,
2563 BaseIndex startIndexAddress,
2564 BaseIndex limitIndexAddress,
2565 gc::Heap initialStringHeap) {
2566 JitSpew(JitSpew_Codegen, "# Emitting CreateDependentString (encoding=%s)",
2567 (encoding_ == CharEncoding::Latin1 ? "Latin-1" : "Two-Byte"));
2568
2569 auto newGCString = [&](FallbackKind kind) {
2570 uint32_t flags = kind == FallbackKind::InlineString
2571 ? JSString::INIT_THIN_INLINE_FLAGS
2572 : kind == FallbackKind::FatInlineString
2573 ? JSString::INIT_FAT_INLINE_FLAGS
2574 : JSString::INIT_DEPENDENT_FLAGS;
2575 if (encoding_ == CharEncoding::Latin1) {
2576 flags |= JSString::LATIN1_CHARS_BIT;
2577 }
2578
2579 if (kind != FallbackKind::FatInlineString) {
2580 masm.newGCString(string_, temp2_, initialStringHeap, &fallbacks_[kind]);
2581 } else {
2582 masm.newGCFatInlineString(string_, temp2_, initialStringHeap,
2583 &fallbacks_[kind]);
2584 }
2585 masm.bind(&joins_[kind]);
2586 masm.store32(Imm32(flags), Address(string_, JSString::offsetOfFlags()));
2587 };
2588
2589 // Compute the string length.
2590 masm.load32(startIndexAddress, temp2_);
2591 masm.load32(limitIndexAddress, temp1_);
2592 masm.sub32(temp2_, temp1_);
2593
2594 Label done, nonEmpty;
2595
2596 // Zero length matches use the empty string.
2597 masm.branchTest32(Assembler::NonZero, temp1_, temp1_, &nonEmpty);
2598 masm.movePtr(ImmGCPtr(names.empty_), string_);
2599 masm.jump(&done);
2600
2601 masm.bind(&nonEmpty);
2602
2603 // Complete matches use the base string.
2604 Label nonBaseStringMatch;
2605 masm.branchTest32(Assembler::NonZero, temp2_, temp2_, &nonBaseStringMatch);
2606 masm.branch32(Assembler::NotEqual, Address(base, JSString::offsetOfLength()),
2607 temp1_, &nonBaseStringMatch);
2608 masm.movePtr(base, string_);
2609 masm.jump(&done);
2610
2611 masm.bind(&nonBaseStringMatch);
2612
2613 Label notInline;
2614
2615 int32_t maxInlineLength = encoding_ == CharEncoding::Latin1
2616 ? JSFatInlineString::MAX_LENGTH_LATIN1
2617 : JSFatInlineString::MAX_LENGTH_TWO_BYTE;
2618 masm.branch32(Assembler::Above, temp1_, Imm32(maxInlineLength), &notInline);
2619 {
2620 // Make a thin or fat inline string.
2621 Label stringAllocated, fatInline;
2622
2623 int32_t maxThinInlineLength = encoding_ == CharEncoding::Latin1
2624 ? JSThinInlineString::MAX_LENGTH_LATIN1
2625 : JSThinInlineString::MAX_LENGTH_TWO_BYTE;
2626 masm.branch32(Assembler::Above, temp1_, Imm32(maxThinInlineLength),
2627 &fatInline);
2628 if (encoding_ == CharEncoding::Latin1) {
2629 // One character Latin-1 strings can be loaded directly from the
2630 // static strings table.
2631 Label thinInline;
2632 masm.branch32(Assembler::Above, temp1_, Imm32(1), &thinInline);
2633 {
2634 static_assert(
2635 StaticStrings::UNIT_STATIC_LIMIT - 1 == JSString::MAX_LATIN1_CHAR,
2636 "Latin-1 strings can be loaded from static strings");
2637
2638 masm.loadStringChars(base, temp1_, encoding_);
2639 masm.loadChar(temp1_, temp2_, temp1_, encoding_);
2640
2641 masm.lookupStaticString(temp1_, string_, runtime->staticStrings());
2642
2643 masm.jump(&done);
2644 }
2645 masm.bind(&thinInline);
2646 }
2647 {
2648 newGCString(FallbackKind::InlineString);
2649 masm.jump(&stringAllocated);
2650 }
2651 masm.bind(&fatInline);
2652 {
2653 newGCString(FallbackKind::FatInlineString);
2654 }
2655 masm.bind(&stringAllocated);
2656
2657 masm.store32(temp1_, Address(string_, JSString::offsetOfLength()));
2658
2659 masm.push(string_);
2660 masm.push(base);
2661
2662 MOZ_ASSERT(startIndexAddress.base == FramePointer,
2663 "startIndexAddress is still valid after stack pushes");
2664
2665 // Load chars pointer for the new string.
2666 masm.loadInlineStringCharsForStore(string_, string_);
2667
2668 // Load the source characters pointer.
2669 masm.loadStringChars(base, temp2_, encoding_);
2670 masm.load32(startIndexAddress, base);
2671 masm.addToCharPtr(temp2_, base, encoding_);
2672
2673 CopyStringChars(masm, string_, temp2_, temp1_, base, encoding_);
2674
2675 masm.pop(base);
2676 masm.pop(string_);
2677
2678 masm.jump(&done);
2679 }
2680
2681 masm.bind(&notInline);
2682
2683 {
2684 // Make a dependent string.
2685 // Warning: string may be tenured (if the fallback case is hit), so
2686 // stores into it must be post barriered.
2687 newGCString(FallbackKind::NotInlineString);
2688
2689 masm.store32(temp1_, Address(string_, JSString::offsetOfLength()));
2690
2691 masm.loadNonInlineStringChars(base, temp1_, encoding_);
2692 masm.load32(startIndexAddress, temp2_);
2693 masm.addToCharPtr(temp1_, temp2_, encoding_);
2694 masm.storeNonInlineStringChars(temp1_, string_);
2695
2696 EmitInitDependentStringBase(masm, string_, base, temp1_, temp2_,
2697 /* needsPostBarrier = */ true);
2698 }
2699
2700 masm.bind(&done);
2701 }
2702
2703 void CreateDependentString::generateFallback(MacroAssembler& masm) {
2704 JitSpew(JitSpew_Codegen,
2705 "# Emitting CreateDependentString fallback (encoding=%s)",
2706 (encoding_ == CharEncoding::Latin1 ? "Latin-1" : "Two-Byte"));
2707
2708 LiveRegisterSet regsToSave(RegisterSet::Volatile());
2709 regsToSave.takeUnchecked(string_);
2710 regsToSave.takeUnchecked(temp2_);
2711
2712 for (FallbackKind kind : mozilla::MakeEnumeratedRange(FallbackKind::Count)) {
2713 masm.bind(&fallbacks_[kind]);
2714
2715 masm.PushRegsInMask(regsToSave);
2716
2717 using Fn = void* (*)(JSContext* cx);
2718 masm.setupUnalignedABICall(string_);
2719 masm.loadJSContext(string_);
2720 masm.passABIArg(string_);
2721 if (kind == FallbackKind::FatInlineString) {
2722 masm.callWithABI<Fn, AllocateFatInlineString>();
2723 } else {
2724 masm.callWithABI<Fn, AllocateDependentString>();
2725 }
2726 masm.storeCallPointerResult(string_);
2727
2728 masm.PopRegsInMask(regsToSave);
2729
2730 masm.branchPtr(Assembler::Equal, string_, ImmWord(0), failure_);
2731
2732 masm.jump(&joins_[kind]);
2733 }
2734 }
2735
2736 // Generate the RegExpMatcher and RegExpExecMatch stubs. These are very similar,
2737 // but RegExpExecMatch also has to load and update .lastIndex for global/sticky
2738 // regular expressions.
2739 static JitCode* GenerateRegExpMatchStubShared(JSContext* cx,
2740 gc::Heap initialStringHeap,
2741 bool isExecMatch) {
2742 if (isExecMatch) {
2743 JitSpew(JitSpew_Codegen, "# Emitting RegExpExecMatch stub");
2744 } else {
2745 JitSpew(JitSpew_Codegen, "# Emitting RegExpMatcher stub");
2746 }
2747
2748 // |initialStringHeap| could be stale after a GC.
2749 JS::AutoCheckCannotGC nogc(cx);
2750
2751 Register regexp = RegExpMatcherRegExpReg;
2752 Register input = RegExpMatcherStringReg;
2753 Register lastIndex = RegExpMatcherLastIndexReg;
2754 ValueOperand result = JSReturnOperand;
2755
2756 // We are free to clobber all registers, as LRegExpMatcher is a call
2757 // instruction.
2758 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
2759 regs.take(input);
2760 regs.take(regexp);
2761 regs.take(lastIndex);
2762
2763 Register temp1 = regs.takeAny();
2764 Register temp2 = regs.takeAny();
2765 Register temp3 = regs.takeAny();
2766 Register maybeTemp4 = InvalidReg;
2767 if (!regs.empty()) {
2768 // There are not enough registers on x86.
2769 maybeTemp4 = regs.takeAny();
2770 }
2771 Register maybeTemp5 = InvalidReg;
2772 if (!regs.empty()) {
2773 // There are not enough registers on x86.
2774 maybeTemp5 = regs.takeAny();
2775 }
2776
2777 Address flagsSlot(regexp, RegExpObject::offsetOfFlags());
2778 Address lastIndexSlot(regexp, RegExpObject::offsetOfLastIndex());
2779
2780 TempAllocator temp(&cx->tempLifoAlloc());
2781 JitContext jcx(cx);
2782 StackMacroAssembler masm(cx, temp);
2783 AutoCreatedBy acb(masm, "GenerateRegExpMatchStubShared");
2784
2785 #ifdef JS_USE_LINK_REGISTER
2786 masm.pushReturnAddress();
2787 #endif
2788 masm.push(FramePointer);
2789 masm.moveStackPtrTo(FramePointer);
2790
2791 Label notFoundZeroLastIndex;
2792 if (isExecMatch) {
2793 masm.loadRegExpLastIndex(regexp, input, lastIndex, &notFoundZeroLastIndex);
2794 }
2795
2796 // The InputOutputData is placed above the frame pointer and return address on
2797 // the stack.
2798 int32_t inputOutputDataStartOffset = 2 * sizeof(void*);
2799
2800 Label notFound, oolEntry;
2801 if (!PrepareAndExecuteRegExp(masm, regexp, input, lastIndex, temp1, temp2,
2802 temp3, inputOutputDataStartOffset,
2803 initialStringHeap, &notFound, &oolEntry)) {
2804 return nullptr;
2805 }
2806
2807 // If a regexp has named captures, fall back to the OOL stub, which
2808 // will end up calling CreateRegExpMatchResults.
2809 Register shared = temp2;
2810 masm.unboxNonDouble(Address(regexp, NativeObject::getFixedSlotOffset(
2811 RegExpObject::SHARED_SLOT)),
2812 shared, JSVAL_TYPE_PRIVATE_GCTHING);
2813 masm.branchPtr(Assembler::NotEqual,
2814 Address(shared, RegExpShared::offsetOfGroupsTemplate()),
2815 ImmWord(0), &oolEntry);
2816
2817 // Similarly, if the |hasIndices| flag is set, fall back to the OOL stub.
2818 masm.branchTest32(Assembler::NonZero,
2819 Address(shared, RegExpShared::offsetOfFlags()),
2820 Imm32(int32_t(JS::RegExpFlag::HasIndices)), &oolEntry);
2821
2822 Address pairCountAddress =
2823 RegExpPairCountAddress(masm, inputOutputDataStartOffset);
2824
2825 // Construct the result.
2826 Register object = temp1;
2827 {
2828 // In most cases, the array will have just 1-2 elements, so we optimize for
2829 // that by emitting separate code paths for capacity 2/6/14 (= 4/8/16 slots
2830 // because two slots are used for the elements header).
2831
2832 // Load the array length in temp2 and the shape in temp3.
2833 Label allocated;
2834 masm.load32(pairCountAddress, temp2);
2835 size_t offset = GlobalObjectData::offsetOfRegExpRealm() +
2836 RegExpRealm::offsetOfNormalMatchResultShape();
2837 masm.loadGlobalObjectData(temp3);
2838 masm.loadPtr(Address(temp3, offset), temp3);
2839
2840 auto emitAllocObject = [&](size_t elementCapacity) {
2841 gc::AllocKind kind = GuessArrayGCKind(elementCapacity);
2842 MOZ_ASSERT(gc::GetObjectFinalizeKind(&ArrayObject::class_) ==
2843 gc::FinalizeKind::None);
2844 MOZ_ASSERT(!IsFinalizedKind(kind));
2845
2846 #ifdef DEBUG
2847 // Assert all of the available slots are used for |elementCapacity|
2848 // elements.
2849 size_t usedSlots = ObjectElements::VALUES_PER_HEADER + elementCapacity;
2850 MOZ_ASSERT(usedSlots == GetGCKindSlots(kind));
2851 #endif
2852
2853 constexpr size_t numUsedDynamicSlots =
2854 RegExpRealm::MatchResultObjectSlotSpan;
2855 constexpr size_t numDynamicSlots =
2856 RegExpRealm::MatchResultObjectNumDynamicSlots;
2857 constexpr size_t arrayLength = 1;
2858 masm.createArrayWithFixedElements(object, temp3, temp2, temp3,
2859 arrayLength, elementCapacity,
2860 numUsedDynamicSlots, numDynamicSlots,
2861 kind, gc::Heap::Default, &oolEntry);
2862 };
2863
2864 Label moreThan2;
2865 masm.branch32(Assembler::Above, temp2, Imm32(2), &moreThan2);
2866 emitAllocObject(2);
2867 masm.jump(&allocated);
2868
2869 Label moreThan6;
2870 masm.bind(&moreThan2);
2871 masm.branch32(Assembler::Above, temp2, Imm32(6), &moreThan6);
2872 emitAllocObject(6);
2873 masm.jump(&allocated);
2874
2875 masm.bind(&moreThan6);
2876 static_assert(RegExpObject::MaxPairCount == 14);
2877 emitAllocObject(RegExpObject::MaxPairCount);
2878
2879 masm.bind(&allocated);
2880 }
2881
2882 // clang-format off
2883 /*
2884 * [SMDOC] Stack layout for the RegExpMatcher stub
2885 *
2886 * +---------------+
2887 * FramePointer +-----> |Caller-FramePtr|
2888 * +---------------+
2889 * |Return-Address |
2890 * +---------------+
2891 * inputOutputDataStartOffset +-----> +---------------+
2892 * |InputOutputData|
2893 * +---------------+
2894 * +---------------+
2895 * | MatchPairs |
2896 * pairsCountAddress +-----------> count |
2897 * | pairs |
2898 * | |
2899 * +---------------+
2900 * pairsVectorStartOffset +-----> +---------------+
2901 * | MatchPair |
2902 * matchPairStart +------------> start | <-------+
2903 * matchPairLimit +------------> limit | | Reserved space for
2904 * +---------------+ | `RegExpObject::MaxPairCount`
2905 * . | MatchPair objects.
2906 * . |
2907 * . | `count` objects will be
2908 * +---------------+ | initialized and can be
2909 * | MatchPair | | accessed below.
2910 * | start | <-------+
2911 * | limit |
2912 * +---------------+
2913 */
2914 // clang-format on
2915
2916 static_assert(sizeof(MatchPair) == 2 * sizeof(int32_t),
2917 "MatchPair consists of two int32 values representing the start"
2918 "and the end offset of the match");
2919
2920 int32_t pairsVectorStartOffset =
2921 RegExpPairsVectorStartOffset(inputOutputDataStartOffset);
2922
2923 // Incremented by one below for each match pair.
2924 Register matchIndex = temp2;
2925 masm.move32(Imm32(0), matchIndex);
2926
2927 // The element in which to store the result of the current match.
2928 size_t elementsOffset = NativeObject::offsetOfFixedElements();
2929 BaseObjectElementIndex objectMatchElement(object, matchIndex, elementsOffset);
2930
2931 // The current match pair's "start" and "limit" member.
2932 BaseIndex matchPairStart(FramePointer, matchIndex, TimesEight,
2933 pairsVectorStartOffset + MatchPair::offsetOfStart());
2934 BaseIndex matchPairLimit(FramePointer, matchIndex, TimesEight,
2935 pairsVectorStartOffset + MatchPair::offsetOfLimit());
2936
2937 Label* depStrFailure = &oolEntry;
2938 Label restoreRegExpAndLastIndex;
2939
2940 Register temp4;
2941 if (maybeTemp4 == InvalidReg) {
2942 depStrFailure = &restoreRegExpAndLastIndex;
2943
2944 // We don't have enough registers for a fourth temporary. Reuse |regexp|
2945 // as a temporary. We restore its value at |restoreRegExpAndLastIndex|.
2946 masm.push(regexp);
2947 temp4 = regexp;
2948 } else {
2949 temp4 = maybeTemp4;
2950 }
2951
2952 Register temp5;
2953 if (maybeTemp5 == InvalidReg) {
2954 depStrFailure = &restoreRegExpAndLastIndex;
2955
2956 // We don't have enough registers for a fifth temporary. Reuse |lastIndex|
2957 // as a temporary. We restore its value at |restoreRegExpAndLastIndex|.
2958 masm.push(lastIndex);
2959 temp5 = lastIndex;
2960 } else {
2961 temp5 = maybeTemp5;
2962 }
2963
2964 auto maybeRestoreRegExpAndLastIndex = [&]() {
2965 if (maybeTemp5 == InvalidReg) {
2966 masm.pop(lastIndex);
2967 }
2968 if (maybeTemp4 == InvalidReg) {
2969 masm.pop(regexp);
2970 }
2971 };
2972
2973 // Loop to construct the match strings. There are two different loops,
2974 // depending on whether the input is a Two-Byte or a Latin-1 string.
2975 CreateDependentString depStrs[]{
2976 {CharEncoding::TwoByte, temp3, temp4, temp5, depStrFailure},
2977 {CharEncoding::Latin1, temp3, temp4, temp5, depStrFailure},
2978 };
2979
2980 {
2981 Label isLatin1, done;
2982 masm.branchLatin1String(input, &isLatin1);
2983
2984 for (auto& depStr : depStrs) {
2985 if (depStr.encoding() == CharEncoding::Latin1) {
2986 masm.bind(&isLatin1);
2987 }
2988
2989 Label matchLoop;
2990 masm.bind(&matchLoop);
2991
2992 static_assert(MatchPair::NoMatch == -1,
2993 "MatchPair::start is negative if no match was found");
2994
2995 Label isUndefined, storeDone;
2996 masm.branch32(Assembler::LessThan, matchPairStart, Imm32(0),
2997 &isUndefined);
2998 {
2999 depStr.generate(masm, cx->names(), CompileRuntime::get(cx->runtime()),
3000 input, matchPairStart, matchPairLimit,
3001 initialStringHeap);
3002
3003 // Storing into nursery-allocated results object's elements; no post
3004 // barrier.
3005 masm.storeValue(JSVAL_TYPE_STRING, depStr.string(), objectMatchElement);
3006 masm.jump(&storeDone);
3007 }
3008 masm.bind(&isUndefined);
3009 {
3010 masm.storeValue(UndefinedValue(), objectMatchElement);
3011 }
3012 masm.bind(&storeDone);
3013
3014 masm.add32(Imm32(1), matchIndex);
3015 masm.branch32(Assembler::LessThanOrEqual, pairCountAddress, matchIndex,
3016 &done);
3017 masm.jump(&matchLoop);
3018 }
3019
3020 #ifdef DEBUG
3021 masm.assumeUnreachable("The match string loop doesn't fall through.");
3022 #endif
3023
3024 masm.bind(&done);
3025 }
3026
3027 maybeRestoreRegExpAndLastIndex();
3028
3029 // Fill in the rest of the output object.
3030 masm.store32(
3031 matchIndex,
3032 Address(object,
3033 elementsOffset + ObjectElements::offsetOfInitializedLength()));
3034 masm.store32(
3035 matchIndex,
3036 Address(object, elementsOffset + ObjectElements::offsetOfLength()));
3037
3038 Address firstMatchPairStartAddress(
3039 FramePointer, pairsVectorStartOffset + MatchPair::offsetOfStart());
3040 Address firstMatchPairLimitAddress(
3041 FramePointer, pairsVectorStartOffset + MatchPair::offsetOfLimit());
3042
3043 static_assert(RegExpRealm::MatchResultObjectIndexSlot == 0,
3044 "First slot holds the 'index' property");
3045 static_assert(RegExpRealm::MatchResultObjectInputSlot == 1,
3046 "Second slot holds the 'input' property");
3047
3048 masm.loadPtr(Address(object, NativeObject::offsetOfSlots()), temp2);
3049
3050 masm.load32(firstMatchPairStartAddress, temp3);
3051 masm.storeValue(JSVAL_TYPE_INT32, temp3, Address(temp2, 0));
3052
3053 // No post barrier needed (address is within nursery object.)
3054 masm.storeValue(JSVAL_TYPE_STRING, input, Address(temp2, sizeof(Value)));
3055
3056 // For the ExecMatch stub, if the regular expression is global or sticky, we
3057 // have to update its .lastIndex slot.
3058 if (isExecMatch) {
3059 MOZ_ASSERT(object != lastIndex);
3060 Label notGlobalOrSticky;
3061 masm.branchTest32(Assembler::Zero, flagsSlot,
3062 Imm32(JS::RegExpFlag::Global | JS::RegExpFlag::Sticky),
3063 &notGlobalOrSticky);
3064 masm.load32(firstMatchPairLimitAddress, lastIndex);
3065 masm.storeValue(JSVAL_TYPE_INT32, lastIndex, lastIndexSlot);
3066 masm.bind(&notGlobalOrSticky);
3067 }
3068
3069 // All done!
3070 masm.tagValue(JSVAL_TYPE_OBJECT, object, result);
3071 masm.pop(FramePointer);
3072 masm.ret();
3073
3074 masm.bind(&notFound);
3075 if (isExecMatch) {
3076 Label notGlobalOrSticky;
3077 masm.branchTest32(Assembler::Zero, flagsSlot,
3078 Imm32(JS::RegExpFlag::Global | JS::RegExpFlag::Sticky),
3079 &notGlobalOrSticky);
3080 masm.bind(&notFoundZeroLastIndex);
3081 masm.storeValue(Int32Value(0), lastIndexSlot);
3082 masm.bind(&notGlobalOrSticky);
3083 }
3084 masm.moveValue(NullValue(), result);
3085 masm.pop(FramePointer);
3086 masm.ret();
3087
3088 // Fallback paths for CreateDependentString.
3089 for (auto& depStr : depStrs) {
3090 depStr.generateFallback(masm);
3091 }
3092
3093 // Fall-through to the ool entry after restoring the registers.
3094 masm.bind(&restoreRegExpAndLastIndex);
3095 maybeRestoreRegExpAndLastIndex();
3096
3097 // Use an undefined value to signal to the caller that the OOL stub needs to
3098 // be called.
3099 masm.bind(&oolEntry);
3100 masm.moveValue(UndefinedValue(), result);
3101 masm.pop(FramePointer);
3102 masm.ret();
3103
3104 Linker linker(masm);
3105 JitCode* code = linker.newCode(cx, CodeKind::Other);
3106 if (!code) {
3107 return nullptr;
3108 }
3109
3110 const char* name = isExecMatch ? "RegExpExecMatchStub" : "RegExpMatcherStub";
3111 CollectPerfSpewerJitCodeProfile(code, name);
3112 #ifdef MOZ_VTUNE
3113 vtune::MarkStub(code, name);
3114 #endif
3115
3116 return code;
3117 }
3118
3119 JitCode* JitZone::generateRegExpMatcherStub(JSContext* cx) {
3120 return GenerateRegExpMatchStubShared(cx, initialStringHeap,
3121 /* isExecMatch = */ false);
3122 }
3123
3124 JitCode* JitZone::generateRegExpExecMatchStub(JSContext* cx) {
3125 return GenerateRegExpMatchStubShared(cx, initialStringHeap,
3126 /* isExecMatch = */ true);
3127 }
3128
3129 void CodeGenerator::visitRegExpMatcher(LRegExpMatcher* lir) {
3130 MOZ_ASSERT(ToRegister(lir->regexp()) == RegExpMatcherRegExpReg);
3131 MOZ_ASSERT(ToRegister(lir->string()) == RegExpMatcherStringReg);
3132 MOZ_ASSERT(ToRegister(lir->lastIndex()) == RegExpMatcherLastIndexReg);
3133 MOZ_ASSERT(ToOutValue(lir) == JSReturnOperand);
3134
3135 #if defined(JS_NUNBOX32)
3136 static_assert(RegExpMatcherRegExpReg != JSReturnReg_Type);
3137 static_assert(RegExpMatcherRegExpReg != JSReturnReg_Data);
3138 static_assert(RegExpMatcherStringReg != JSReturnReg_Type);
3139 static_assert(RegExpMatcherStringReg != JSReturnReg_Data);
3140 static_assert(RegExpMatcherLastIndexReg != JSReturnReg_Type);
3141 static_assert(RegExpMatcherLastIndexReg != JSReturnReg_Data);
3142 #elif defined(JS_PUNBOX64)
3143 static_assert(RegExpMatcherRegExpReg != JSReturnReg);
3144 static_assert(RegExpMatcherStringReg != JSReturnReg);
3145 static_assert(RegExpMatcherLastIndexReg != JSReturnReg);
3146 #endif
3147
3148 masm.reserveStack(RegExpReservedStack);
3149
3150 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
3151 Register lastIndex = ToRegister(lir->lastIndex());
3152 Register input = ToRegister(lir->string());
3153 Register regexp = ToRegister(lir->regexp());
3154
3155 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
3156 regs.take(lastIndex);
3157 regs.take(input);
3158 regs.take(regexp);
3159 Register temp = regs.takeAny();
3160
3161 masm.computeEffectiveAddress(
3162 Address(masm.getStackPointer(), InputOutputDataSize), temp);
3163
3164 pushArg(temp);
3165 pushArg(lastIndex);
3166 pushArg(input);
3167 pushArg(regexp);
3168
3169 // We are not using oolCallVM because we are in a Call, and that live
3170 // registers are already saved by the the register allocator.
3171 using Fn = bool (*)(JSContext*, HandleObject regexp, HandleString input,
3172 int32_t lastIndex, MatchPairs* pairs,
3173 MutableHandleValue output);
3174 callVM<Fn, RegExpMatcherRaw>(lir);
3175
3176 masm.jump(ool.rejoin());
3177 });
3178 addOutOfLineCode(ool, lir->mir());
3179
3180 JitCode* regExpMatcherStub =
3181 snapshot_->getZoneStub(JitZone::StubKind::RegExpMatcher);
3182 masm.call(regExpMatcherStub);
3183 masm.branchTestUndefined(Assembler::Equal, JSReturnOperand, ool->entry());
3184 masm.bind(ool->rejoin());
3185
3186 masm.freeStack(RegExpReservedStack);
3187 }
3188
3189 void CodeGenerator::visitRegExpExecMatch(LRegExpExecMatch* lir) {
3190 MOZ_ASSERT(ToRegister(lir->regexp()) == RegExpMatcherRegExpReg);
3191 MOZ_ASSERT(ToRegister(lir->string()) == RegExpMatcherStringReg);
3192 MOZ_ASSERT(ToOutValue(lir) == JSReturnOperand);
3193
3194 #if defined(JS_NUNBOX32)
3195 static_assert(RegExpMatcherRegExpReg != JSReturnReg_Type);
3196 static_assert(RegExpMatcherRegExpReg != JSReturnReg_Data);
3197 static_assert(RegExpMatcherStringReg != JSReturnReg_Type);
3198 static_assert(RegExpMatcherStringReg != JSReturnReg_Data);
3199 #elif defined(JS_PUNBOX64)
3200 static_assert(RegExpMatcherRegExpReg != JSReturnReg);
3201 static_assert(RegExpMatcherStringReg != JSReturnReg);
3202 #endif
3203
3204 masm.reserveStack(RegExpReservedStack);
3205
3206 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
3207 Register input = ToRegister(lir->string());
3208 Register regexp = ToRegister(lir->regexp());
3209
3210 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
3211 regs.take(input);
3212 regs.take(regexp);
3213 Register temp = regs.takeAny();
3214
3215 masm.computeEffectiveAddress(
3216 Address(masm.getStackPointer(), InputOutputDataSize), temp);
3217
3218 pushArg(temp);
3219 pushArg(input);
3220 pushArg(regexp);
3221
3222 // We are not using oolCallVM because we are in a Call and live registers
3223 // have already been saved by the register allocator.
3224 using Fn =
3225 bool (*)(JSContext*, Handle<RegExpObject*> regexp, HandleString input,
3226 MatchPairs* pairs, MutableHandleValue output);
3227 callVM<Fn, RegExpBuiltinExecMatchFromJit>(lir);
3228 masm.jump(ool.rejoin());
3229 });
3230 addOutOfLineCode(ool, lir->mir());
3231
3232 JitCode* regExpExecMatchStub =
3233 snapshot_->getZoneStub(JitZone::StubKind::RegExpExecMatch);
3234 masm.call(regExpExecMatchStub);
3235 masm.branchTestUndefined(Assembler::Equal, JSReturnOperand, ool->entry());
3236
3237 masm.bind(ool->rejoin());
3238 masm.freeStack(RegExpReservedStack);
3239 }
3240
3241 JitCode* JitZone::generateRegExpSearcherStub(JSContext* cx) {
3242 JitSpew(JitSpew_Codegen, "# Emitting RegExpSearcher stub");
3243
3244 Register regexp = RegExpSearcherRegExpReg;
3245 Register input = RegExpSearcherStringReg;
3246 Register lastIndex = RegExpSearcherLastIndexReg;
3247 Register result = ReturnReg;
3248
3249 // We are free to clobber all registers, as LRegExpSearcher is a call
3250 // instruction.
3251 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
3252 regs.take(input);
3253 regs.take(regexp);
3254 regs.take(lastIndex);
3255
3256 Register temp1 = regs.takeAny();
3257 Register temp2 = regs.takeAny();
3258 Register temp3 = regs.takeAny();
3259
3260 TempAllocator temp(&cx->tempLifoAlloc());
3261 JitContext jcx(cx);
3262 StackMacroAssembler masm(cx, temp);
3263 AutoCreatedBy acb(masm, "JitZone::generateRegExpSearcherStub");
3264
3265 #ifdef JS_USE_LINK_REGISTER
3266 masm.pushReturnAddress();
3267 #endif
3268 masm.push(FramePointer);
3269 masm.moveStackPtrTo(FramePointer);
3270
3271 #ifdef DEBUG
3272 // Store sentinel value to cx->regExpSearcherLastLimit.
3273 // See comment in RegExpSearcherImpl.
3274 masm.loadJSContext(temp1);
3275 masm.store32(Imm32(RegExpSearcherLastLimitSentinel),
3276 Address(temp1, JSContext::offsetOfRegExpSearcherLastLimit()));
3277 #endif
3278
3279 // The InputOutputData is placed above the frame pointer and return address on
3280 // the stack.
3281 int32_t inputOutputDataStartOffset = 2 * sizeof(void*);
3282
3283 Label notFound, oolEntry;
3284 if (!PrepareAndExecuteRegExp(masm, regexp, input, lastIndex, temp1, temp2,
3285 temp3, inputOutputDataStartOffset,
3286 initialStringHeap, &notFound, &oolEntry)) {
3287 return nullptr;
3288 }
3289
3290 // clang-format off
3291 /*
3292 * [SMDOC] Stack layout for the RegExpSearcher stub
3293 *
3294 * +---------------+
3295 * FramePointer +-----> |Caller-FramePtr|
3296 * +---------------+
3297 * |Return-Address |
3298 * +---------------+
3299 * inputOutputDataStartOffset +-----> +---------------+
3300 * |InputOutputData|
3301 * +---------------+
3302 * +---------------+
3303 * | MatchPairs |
3304 * | count |
3305 * | pairs |
3306 * | |
3307 * +---------------+
3308 * pairsVectorStartOffset +-----> +---------------+
3309 * | MatchPair |
3310 * matchPairStart +------------> start | <-------+
3311 * matchPairLimit +------------> limit | | Reserved space for
3312 * +---------------+ | `RegExpObject::MaxPairCount`
3313 * . | MatchPair objects.
3314 * . |
3315 * . | Only a single object will
3316 * +---------------+ | be initialized and can be
3317 * | MatchPair | | accessed below.
3318 * | start | <-------+
3319 * | limit |
3320 * +---------------+
3321 */
3322 // clang-format on
3323
3324 int32_t pairsVectorStartOffset =
3325 RegExpPairsVectorStartOffset(inputOutputDataStartOffset);
3326 Address matchPairStart(FramePointer,
3327 pairsVectorStartOffset + MatchPair::offsetOfStart());
3328 Address matchPairLimit(FramePointer,
3329 pairsVectorStartOffset + MatchPair::offsetOfLimit());
3330
3331 // Store match limit to cx->regExpSearcherLastLimit and return the index.
3332 masm.load32(matchPairLimit, result);
3333 masm.loadJSContext(input);
3334 masm.store32(result,
3335 Address(input, JSContext::offsetOfRegExpSearcherLastLimit()));
3336 masm.load32(matchPairStart, result);
3337 masm.pop(FramePointer);
3338 masm.ret();
3339
3340 masm.bind(&notFound);
3341 masm.move32(Imm32(RegExpSearcherResultNotFound), result);
3342 masm.pop(FramePointer);
3343 masm.ret();
3344
3345 masm.bind(&oolEntry);
3346 masm.move32(Imm32(RegExpSearcherResultFailed), result);
3347 masm.pop(FramePointer);
3348 masm.ret();
3349
3350 Linker linker(masm);
3351 JitCode* code = linker.newCode(cx, CodeKind::Other);
3352 if (!code) {
3353 return nullptr;
3354 }
3355
3356 CollectPerfSpewerJitCodeProfile(code, "RegExpSearcherStub");
3357 #ifdef MOZ_VTUNE
3358 vtune::MarkStub(code, "RegExpSearcherStub");
3359 #endif
3360
3361 return code;
3362 }
3363
3364 void CodeGenerator::visitRegExpSearcher(LRegExpSearcher* lir) {
3365 MOZ_ASSERT(ToRegister(lir->regexp()) == RegExpSearcherRegExpReg);
3366 MOZ_ASSERT(ToRegister(lir->string()) == RegExpSearcherStringReg);
3367 MOZ_ASSERT(ToRegister(lir->lastIndex()) == RegExpSearcherLastIndexReg);
3368 MOZ_ASSERT(ToRegister(lir->output()) == ReturnReg);
3369
3370 static_assert(RegExpSearcherRegExpReg != ReturnReg);
3371 static_assert(RegExpSearcherStringReg != ReturnReg);
3372 static_assert(RegExpSearcherLastIndexReg != ReturnReg);
3373
3374 masm.reserveStack(RegExpReservedStack);
3375
3376 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
3377 Register lastIndex = ToRegister(lir->lastIndex());
3378 Register input = ToRegister(lir->string());
3379 Register regexp = ToRegister(lir->regexp());
3380
3381 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
3382 regs.take(lastIndex);
3383 regs.take(input);
3384 regs.take(regexp);
3385 Register temp = regs.takeAny();
3386
3387 masm.computeEffectiveAddress(
3388 Address(masm.getStackPointer(), InputOutputDataSize), temp);
3389
3390 pushArg(temp);
3391 pushArg(lastIndex);
3392 pushArg(input);
3393 pushArg(regexp);
3394
3395 // We are not using oolCallVM because we are in a Call, and that live
3396 // registers are already saved by the the register allocator.
3397 using Fn = bool (*)(JSContext* cx, HandleObject regexp, HandleString input,
3398 int32_t lastIndex, MatchPairs* pairs, int32_t* result);
3399 callVM<Fn, RegExpSearcherRaw>(lir);
3400
3401 masm.jump(ool.rejoin());
3402 });
3403 addOutOfLineCode(ool, lir->mir());
3404
3405 JitCode* regExpSearcherStub =
3406 snapshot_->getZoneStub(JitZone::StubKind::RegExpSearcher);
3407 masm.call(regExpSearcherStub);
3408 masm.branch32(Assembler::Equal, ReturnReg, Imm32(RegExpSearcherResultFailed),
3409 ool->entry());
3410 masm.bind(ool->rejoin());
3411
3412 masm.freeStack(RegExpReservedStack);
3413 }
3414
3415 void CodeGenerator::visitRegExpSearcherLastLimit(
3416 LRegExpSearcherLastLimit* lir) {
3417 Register result = ToRegister(lir->output());
3418 Register scratch = ToRegister(lir->temp0());
3419
3420 masm.loadAndClearRegExpSearcherLastLimit(result, scratch);
3421 }
3422
3423 JitCode* JitZone::generateRegExpExecTestStub(JSContext* cx) {
3424 JitSpew(JitSpew_Codegen, "# Emitting RegExpExecTest stub");
3425
3426 Register regexp = RegExpExecTestRegExpReg;
3427 Register input = RegExpExecTestStringReg;
3428 Register result = ReturnReg;
3429
3430 TempAllocator temp(&cx->tempLifoAlloc());
3431 JitContext jcx(cx);
3432 StackMacroAssembler masm(cx, temp);
3433 AutoCreatedBy acb(masm, "JitZone::generateRegExpExecTestStub");
3434
3435 #ifdef JS_USE_LINK_REGISTER
3436 masm.pushReturnAddress();
3437 #endif
3438 masm.push(FramePointer);
3439 masm.moveStackPtrTo(FramePointer);
3440
3441 // We are free to clobber all registers, as LRegExpExecTest is a call
3442 // instruction.
3443 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
3444 regs.take(input);
3445 regs.take(regexp);
3446
3447 // Ensure lastIndex != result.
3448 regs.take(result);
3449 Register lastIndex = regs.takeAny();
3450 regs.add(result);
3451 Register temp1 = regs.takeAny();
3452 Register temp2 = regs.takeAny();
3453 Register temp3 = regs.takeAny();
3454
3455 Address flagsSlot(regexp, RegExpObject::offsetOfFlags());
3456 Address lastIndexSlot(regexp, RegExpObject::offsetOfLastIndex());
3457
3458 masm.reserveStack(RegExpReservedStack);
3459
3460 // Load lastIndex and skip RegExp execution if needed.
3461 Label notFoundZeroLastIndex;
3462 masm.loadRegExpLastIndex(regexp, input, lastIndex, &notFoundZeroLastIndex);
3463
3464 // In visitRegExpMatcher and visitRegExpSearcher, we reserve stack space
3465 // before calling the stub. For RegExpExecTest we call the stub before
3466 // reserving stack space, so the offset of the InputOutputData relative to the
3467 // frame pointer is negative.
3468 constexpr int32_t inputOutputDataStartOffset = -int32_t(RegExpReservedStack);
3469
3470 // On ARM64, load/store instructions can encode an immediate offset in the
3471 // range [-256, 4095]. If we ever fail this assertion, it would be more
3472 // efficient to store the data above the frame pointer similar to
3473 // RegExpMatcher and RegExpSearcher.
3474 static_assert(inputOutputDataStartOffset >= -256);
3475
3476 Label notFound, oolEntry;
3477 if (!PrepareAndExecuteRegExp(masm, regexp, input, lastIndex, temp1, temp2,
3478 temp3, inputOutputDataStartOffset,
3479 initialStringHeap, &notFound, &oolEntry)) {
3480 return nullptr;
3481 }
3482
3483 // Set `result` to true/false to indicate found/not-found, or to
3484 // RegExpExecTestResultFailed if we have to retry in C++. If the regular
3485 // expression is global or sticky, we also have to update its .lastIndex slot.
3486
3487 Label done;
3488 int32_t pairsVectorStartOffset =
3489 RegExpPairsVectorStartOffset(inputOutputDataStartOffset);
3490 Address matchPairLimit(FramePointer,
3491 pairsVectorStartOffset + MatchPair::offsetOfLimit());
3492
3493 masm.move32(Imm32(1), result);
3494 masm.branchTest32(Assembler::Zero, flagsSlot,
3495 Imm32(JS::RegExpFlag::Global | JS::RegExpFlag::Sticky),
3496 &done);
3497 masm.load32(matchPairLimit, lastIndex);
3498 masm.storeValue(JSVAL_TYPE_INT32, lastIndex, lastIndexSlot);
3499 masm.jump(&done);
3500
3501 masm.bind(&notFound);
3502 masm.move32(Imm32(0), result);
3503 masm.branchTest32(Assembler::Zero, flagsSlot,
3504 Imm32(JS::RegExpFlag::Global | JS::RegExpFlag::Sticky),
3505 &done);
3506 masm.storeValue(Int32Value(0), lastIndexSlot);
3507 masm.jump(&done);
3508
3509 masm.bind(&notFoundZeroLastIndex);
3510 masm.move32(Imm32(0), result);
3511 masm.storeValue(Int32Value(0), lastIndexSlot);
3512 masm.jump(&done);
3513
3514 masm.bind(&oolEntry);
3515 masm.move32(Imm32(RegExpExecTestResultFailed), result);
3516
3517 masm.bind(&done);
3518 masm.freeStack(RegExpReservedStack);
3519 masm.pop(FramePointer);
3520 masm.ret();
3521
3522 Linker linker(masm);
3523 JitCode* code = linker.newCode(cx, CodeKind::Other);
3524 if (!code) {
3525 return nullptr;
3526 }
3527
3528 CollectPerfSpewerJitCodeProfile(code, "RegExpExecTestStub");
3529 #ifdef MOZ_VTUNE
3530 vtune::MarkStub(code, "RegExpExecTestStub");
3531 #endif
3532
3533 return code;
3534 }
3535
3536 void CodeGenerator::visitRegExpExecTest(LRegExpExecTest* lir) {
3537 MOZ_ASSERT(ToRegister(lir->regexp()) == RegExpExecTestRegExpReg);
3538 MOZ_ASSERT(ToRegister(lir->string()) == RegExpExecTestStringReg);
3539 MOZ_ASSERT(ToRegister(lir->output()) == ReturnReg);
3540
3541 static_assert(RegExpExecTestRegExpReg != ReturnReg);
3542 static_assert(RegExpExecTestStringReg != ReturnReg);
3543
3544 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
3545 Register input = ToRegister(lir->string());
3546 Register regexp = ToRegister(lir->regexp());
3547
3548 pushArg(input);
3549 pushArg(regexp);
3550
3551 // We are not using oolCallVM because we are in a Call and live registers
3552 // have already been saved by the register allocator.
3553 using Fn = bool (*)(JSContext* cx, Handle<RegExpObject*> regexp,
3554 HandleString input, bool* result);
3555 callVM<Fn, RegExpBuiltinExecTestFromJit>(lir);
3556
3557 masm.jump(ool.rejoin());
3558 });
3559 addOutOfLineCode(ool, lir->mir());
3560
3561 JitCode* regExpExecTestStub =
3562 snapshot_->getZoneStub(JitZone::StubKind::RegExpExecTest);
3563 masm.call(regExpExecTestStub);
3564
3565 masm.branch32(Assembler::Equal, ReturnReg, Imm32(RegExpExecTestResultFailed),
3566 ool->entry());
3567
3568 masm.bind(ool->rejoin());
3569 }
3570
3571 void CodeGenerator::visitRegExpHasCaptureGroups(LRegExpHasCaptureGroups* ins) {
3572 Register regexp = ToRegister(ins->regexp());
3573 Register input = ToRegister(ins->input());
3574 Register output = ToRegister(ins->output());
3575
3576 using Fn =
3577 bool (*)(JSContext*, Handle<RegExpObject*>, Handle<JSString*>, bool*);
3578 auto* ool = oolCallVM<Fn, js::RegExpHasCaptureGroups>(
3579 ins, ArgList(regexp, input), StoreRegisterTo(output));
3580
3581 // Load RegExpShared in |output|.
3582 Label vmCall;
3583 masm.loadParsedRegExpShared(regexp, output, ool->entry());
3584
3585 // Return true iff pairCount > 1.
3586 Label returnTrue;
3587 masm.branch32(Assembler::Above,
3588 Address(output, RegExpShared::offsetOfPairCount()), Imm32(1),
3589 &returnTrue);
3590 masm.move32(Imm32(0), output);
3591 masm.jump(ool->rejoin());
3592
3593 masm.bind(&returnTrue);
3594 masm.move32(Imm32(1), output);
3595
3596 masm.bind(ool->rejoin());
3597 }
3598
3599 static void FindFirstDollarIndex(MacroAssembler& masm, Register str,
3600 Register len, Register temp0, Register temp1,
3601 Register output, CharEncoding encoding) {
3602 #ifdef DEBUG
3603 Label ok;
3604 masm.branch32(Assembler::GreaterThan, len, Imm32(0), &ok);
3605 masm.assumeUnreachable("Length should be greater than 0.");
3606 masm.bind(&ok);
3607 #endif
3608
3609 Register chars = temp0;
3610 masm.loadStringChars(str, chars, encoding);
3611
3612 masm.move32(Imm32(0), output);
3613
3614 Label start, done;
3615 masm.bind(&start);
3616
3617 Register currentChar = temp1;
3618 masm.loadChar(chars, output, currentChar, encoding);
3619 masm.branch32(Assembler::Equal, currentChar, Imm32('$'), &done);
3620
3621 masm.add32(Imm32(1), output);
3622 masm.branch32(Assembler::NotEqual, output, len, &start);
3623
3624 masm.move32(Imm32(-1), output);
3625
3626 masm.bind(&done);
3627 }
3628
3629 void CodeGenerator::visitGetFirstDollarIndex(LGetFirstDollarIndex* ins) {
3630 Register str = ToRegister(ins->str());
3631 Register output = ToRegister(ins->output());
3632 Register temp0 = ToRegister(ins->temp0());
3633 Register temp1 = ToRegister(ins->temp1());
3634 Register len = ToRegister(ins->temp2());
3635
3636 using Fn = bool (*)(JSContext*, JSString*, int32_t*);
3637 OutOfLineCode* ool = oolCallVM<Fn, GetFirstDollarIndexRaw>(
3638 ins, ArgList(str), StoreRegisterTo(output));
3639
3640 masm.branchIfRope(str, ool->entry());
3641 masm.loadStringLength(str, len);
3642
3643 Label isLatin1, done;
3644 masm.branchLatin1String(str, &isLatin1);
3645 {
3646 FindFirstDollarIndex(masm, str, len, temp0, temp1, output,
3647 CharEncoding::TwoByte);
3648 masm.jump(&done);
3649 }
3650 masm.bind(&isLatin1);
3651 {
3652 FindFirstDollarIndex(masm, str, len, temp0, temp1, output,
3653 CharEncoding::Latin1);
3654 }
3655 masm.bind(&done);
3656 masm.bind(ool->rejoin());
3657 }
3658
3659 void CodeGenerator::visitStringReplace(LStringReplace* lir) {
3660 if (lir->replacement()->isConstant()) {
3661 pushArg(ImmGCPtr(lir->replacement()->toConstant()->toString()));
3662 } else {
3663 pushArg(ToRegister(lir->replacement()));
3664 }
3665
3666 if (lir->pattern()->isConstant()) {
3667 pushArg(ImmGCPtr(lir->pattern()->toConstant()->toString()));
3668 } else {
3669 pushArg(ToRegister(lir->pattern()));
3670 }
3671
3672 if (lir->string()->isConstant()) {
3673 pushArg(ImmGCPtr(lir->string()->toConstant()->toString()));
3674 } else {
3675 pushArg(ToRegister(lir->string()));
3676 }
3677
3678 using Fn =
3679 JSString* (*)(JSContext*, HandleString, HandleString, HandleString);
3680 if (lir->mir()->isFlatReplacement()) {
3681 callVM<Fn, StringFlatReplaceString>(lir);
3682 } else {
3683 callVM<Fn, StringReplace>(lir);
3684 }
3685 }
3686
3687 void CodeGenerator::visitBinaryValueCache(LBinaryValueCache* lir) {
3688 LiveRegisterSet liveRegs = lir->safepoint()->liveRegs();
3689 TypedOrValueRegister lhs = TypedOrValueRegister(ToValue(lir->lhs()));
3690 TypedOrValueRegister rhs = TypedOrValueRegister(ToValue(lir->rhs()));
3691 ValueOperand output = ToOutValue(lir);
3692
3693 JSOp jsop = JSOp(*lir->mirRaw()->toInstruction()->resumePoint()->pc());
3694
3695 switch (jsop) {
3696 case JSOp::Add:
3697 case JSOp::Sub:
3698 case JSOp::Mul:
3699 case JSOp::Div:
3700 case JSOp::Mod:
3701 case JSOp::Pow:
3702 case JSOp::BitAnd:
3703 case JSOp::BitOr:
3704 case JSOp::BitXor:
3705 case JSOp::Lsh:
3706 case JSOp::Rsh:
3707 case JSOp::Ursh: {
3708 IonBinaryArithIC ic(liveRegs, lhs, rhs, output);
3709 addIC(lir, allocateIC(ic));
3710 return;
3711 }
3712 default:
3713 MOZ_CRASH("Unsupported jsop in MBinaryValueCache");
3714 }
3715 }
3716
3717 void CodeGenerator::visitBinaryBoolCache(LBinaryBoolCache* lir) {
3718 LiveRegisterSet liveRegs = lir->safepoint()->liveRegs();
3719 TypedOrValueRegister lhs = TypedOrValueRegister(ToValue(lir->lhs()));
3720 TypedOrValueRegister rhs = TypedOrValueRegister(ToValue(lir->rhs()));
3721 Register output = ToRegister(lir->output());
3722
3723 JSOp jsop = JSOp(*lir->mirRaw()->toInstruction()->resumePoint()->pc());
3724
3725 switch (jsop) {
3726 case JSOp::Lt:
3727 case JSOp::Le:
3728 case JSOp::Gt:
3729 case JSOp::Ge:
3730 case JSOp::Eq:
3731 case JSOp::Ne:
3732 case JSOp::StrictEq:
3733 case JSOp::StrictNe: {
3734 IonCompareIC ic(liveRegs, lhs, rhs, output);
3735 addIC(lir, allocateIC(ic));
3736 return;
3737 }
3738 default:
3739 MOZ_CRASH("Unsupported jsop in MBinaryBoolCache");
3740 }
3741 }
3742
3743 void CodeGenerator::visitUnaryCache(LUnaryCache* lir) {
3744 LiveRegisterSet liveRegs = lir->safepoint()->liveRegs();
3745 TypedOrValueRegister input = TypedOrValueRegister(ToValue(lir->input()));
3746 ValueOperand output = ToOutValue(lir);
3747
3748 IonUnaryArithIC ic(liveRegs, input, output);
3749 addIC(lir, allocateIC(ic));
3750 }
3751
3752 void CodeGenerator::visitModuleMetadata(LModuleMetadata* lir) {
3753 pushArg(ImmPtr(lir->mir()->module()));
3754
3755 using Fn = JSObject* (*)(JSContext*, HandleObject);
3756 callVM<Fn, js::GetOrCreateModuleMetaObject>(lir);
3757 }
3758
3759 void CodeGenerator::visitDynamicImport(LDynamicImport* lir) {
3760 pushArg(ToValue(lir->options()));
3761 pushArg(ToValue(lir->specifier()));
3762 pushArg(ImmGCPtr(current->mir()->info().script()));
3763
3764 using Fn = JSObject* (*)(JSContext*, HandleScript, HandleValue, HandleValue);
3765 callVM<Fn, js::StartDynamicModuleImport>(lir);
3766 }
3767
3768 void CodeGenerator::visitLambda(LLambda* lir) {
3769 Register envChain = ToRegister(lir->environmentChain());
3770 Register output = ToRegister(lir->output());
3771 Register tempReg = ToRegister(lir->temp0());
3772 gc::Heap heap = lir->mir()->initialHeap();
3773
3774 JSFunction* fun = lir->mir()->templateFunction();
3775 MOZ_ASSERT(fun->isTenured());
3776
3777 using Fn = JSObject* (*)(JSContext*, HandleFunction, HandleObject, gc::Heap);
3778 OutOfLineCode* ool = oolCallVM<Fn, js::LambdaOptimizedFallback>(
3779 lir, ArgList(ImmGCPtr(fun), envChain, Imm32(uint32_t(heap))),
3780 StoreRegisterTo(output));
3781
3782 TemplateObject templateObject(fun);
3783 masm.createGCObject(output, tempReg, templateObject, heap, ool->entry(),
3784 /* initContents = */ true,
3785 AllocSiteInput(gc::CatchAllAllocSite::Optimized));
3786
3787 masm.storeValue(JSVAL_TYPE_OBJECT, envChain,
3788 Address(output, JSFunction::offsetOfEnvironment()));
3789
3790 // If we specified the tenured heap then we need a post barrier. Otherwise no
3791 // post barrier needed as the output is guaranteed to be allocated in the
3792 // nursery.
3793 if (heap == gc::Heap::Tenured) {
3794 Label skipBarrier;
3795 masm.branchPtrInNurseryChunk(Assembler::NotEqual, envChain, tempReg,
3796 &skipBarrier);
3797 saveVolatile(tempReg);
3798 emitPostWriteBarrier(output);
3799 restoreVolatile(tempReg);
3800 masm.bind(&skipBarrier);
3801 }
3802
3803 masm.bind(ool->rejoin());
3804 }
3805
3806 void CodeGenerator::visitFunctionWithProto(LFunctionWithProto* lir) {
3807 Register envChain = ToRegister(lir->envChain());
3808 Register prototype = ToRegister(lir->prototype());
3809
3810 pushArg(prototype);
3811 pushArg(envChain);
3812 pushArg(ImmGCPtr(lir->mir()->function()));
3813
3814 using Fn =
3815 JSObject* (*)(JSContext*, HandleFunction, HandleObject, HandleObject);
3816 callVM<Fn, js::FunWithProtoOperation>(lir);
3817 }
3818
3819 void CodeGenerator::visitSetFunName(LSetFunName* lir) {
3820 pushArg(Imm32(lir->mir()->prefixKind()));
3821 pushArg(ToValue(lir->name()));
3822 pushArg(ToRegister(lir->fun()));
3823
3824 using Fn =
3825 bool (*)(JSContext*, HandleFunction, HandleValue, FunctionPrefixKind);
3826 callVM<Fn, js::SetFunctionName>(lir);
3827 }
3828
3829 void CodeGenerator::visitOsiPoint(LOsiPoint* lir) {
3830 // Note: markOsiPoint ensures enough space exists between the last
3831 // LOsiPoint and this one to patch adjacent call instructions.
3832
3833 MOZ_ASSERT(masm.framePushed() == frameSize());
3834
3835 uint32_t osiCallPointOffset = markOsiPoint(lir);
3836
3837 LSafepoint* safepoint = lir->associatedSafepoint();
3838 MOZ_ASSERT(!safepoint->osiCallPointOffset());
3839 safepoint->setOsiCallPointOffset(osiCallPointOffset);
3840
3841 #ifdef DEBUG
3842 // There should be no movegroups or other instructions between
3843 // an instruction and its OsiPoint. This is necessary because
3844 // we use the OsiPoint's snapshot from within VM calls.
3845 for (LInstructionReverseIterator iter(current->rbegin(lir));
3846 iter != current->rend(); iter++) {
3847 if (*iter == lir) {
3848 continue;
3849 }
3850 MOZ_ASSERT(!iter->isMoveGroup());
3851 MOZ_ASSERT(iter->safepoint() == safepoint);
3852 break;
3853 }
3854 #endif
3855
3856 #ifdef CHECK_OSIPOINT_REGISTERS
3857 if (shouldVerifyOsiPointRegs(safepoint)) {
3858 verifyOsiPointRegs(safepoint);
3859 }
3860 #endif
3861 }
3862
3863 void CodeGenerator::visitPhi(LPhi* lir) {
3864 MOZ_CRASH("Unexpected LPhi in CodeGenerator");
3865 }
3866
3867 void CodeGenerator::visitGoto(LGoto* lir) { jumpToBlock(lir->target()); }
3868
3869 void CodeGenerator::visitTableSwitch(LTableSwitch* ins) {
3870 MTableSwitch* mir = ins->mir();
3871 Label* defaultcase = skipTrivialBlocks(mir->getDefault())->lir()->label();
3872
3873 Register intIndex;
3874 if (mir->getOperand(0)->type() != MIRType::Int32) {
3875 intIndex = ToRegister(ins->temp0());
3876
3877 // The input is a double, so try and convert it to an integer.
3878 // If it does not fit in an integer, take the default case.
3879 masm.convertDoubleToInt32(ToFloatRegister(ins->index()), intIndex,
3880 defaultcase, false);
3881 } else {
3882 intIndex = ToRegister(ins->index());
3883 }
3884
3885 emitTableSwitchDispatch(mir, intIndex, ToTempRegisterOrInvalid(ins->temp1()));
3886 }
3887
3888 void CodeGenerator::visitTableSwitchV(LTableSwitchV* ins) {
3889 MTableSwitch* mir = ins->mir();
3890 Label* defaultcase = skipTrivialBlocks(mir->getDefault())->lir()->label();
3891
3892 Register index = ToRegister(ins->temp0());
3893 ValueOperand value = ToValue(ins->input());
3894 Register tag = masm.extractTag(value, index);
3895 masm.branchTestNumber(Assembler::NotEqual, tag, defaultcase);
3896
3897 Label unboxInt, isInt;
3898 masm.branchTestInt32(Assembler::Equal, tag, &unboxInt);
3899 {
3900 FloatRegister floatIndex = ToFloatRegister(ins->temp1());
3901 masm.unboxDouble(value, floatIndex);
3902 masm.convertDoubleToInt32(floatIndex, index, defaultcase, false);
3903 masm.jump(&isInt);
3904 }
3905
3906 masm.bind(&unboxInt);
3907 masm.unboxInt32(value, index);
3908
3909 masm.bind(&isInt);
3910
3911 emitTableSwitchDispatch(mir, index, ToTempRegisterOrInvalid(ins->temp2()));
3912 }
3913
3914 void CodeGenerator::visitParameter(LParameter* lir) {}
3915
3916 void CodeGenerator::visitCallee(LCallee* lir) {
3917 Register callee = ToRegister(lir->output());
3918 Address ptr(FramePointer, JitFrameLayout::offsetOfCalleeToken());
3919
3920 masm.loadFunctionFromCalleeToken(ptr, callee);
3921 }
3922
3923 void CodeGenerator::visitIsConstructing(LIsConstructing* lir) {
3924 Register output = ToRegister(lir->output());
3925 Address calleeToken(FramePointer, JitFrameLayout::offsetOfCalleeToken());
3926 masm.loadPtr(calleeToken, output);
3927
3928 // We must be inside a function.
3929 MOZ_ASSERT(current->mir()->info().script()->function());
3930
3931 // The low bit indicates whether this call is constructing, just clear the
3932 // other bits.
3933 static_assert(CalleeToken_Function == 0x0,
3934 "CalleeTokenTag value should match");
3935 static_assert(CalleeToken_FunctionConstructing == 0x1,
3936 "CalleeTokenTag value should match");
3937 masm.andPtr(Imm32(0x1), output);
3938 }
3939
3940 void CodeGenerator::visitReturn(LReturn* lir) {
3941 #if defined(JS_NUNBOX32)
3942 DebugOnly<LAllocation*> type = lir->getOperand(TYPE_INDEX);
3943 DebugOnly<LAllocation*> payload = lir->getOperand(PAYLOAD_INDEX);
3944 MOZ_ASSERT(ToRegister(type) == JSReturnReg_Type);
3945 MOZ_ASSERT(ToRegister(payload) == JSReturnReg_Data);
3946 #elif defined(JS_PUNBOX64)
3947 DebugOnly<LAllocation*> result = lir->getOperand(0);
3948 MOZ_ASSERT(ToRegister(result) == JSReturnReg);
3949 #endif
3950 // Don't emit a jump to the return label if this is the last block, as
3951 // it'll fall through to the epilogue.
3952 //
3953 // This is -not- true however for a Generator-return, which may appear in the
3954 // middle of the last block, so we should always emit the jump there.
3955 if (current->mir() != *gen->graph().poBegin() || lir->isGenerator()) {
3956 masm.jump(&returnLabel_);
3957 }
3958 }
3959
3960 void CodeGenerator::visitOsrEntry(LOsrEntry* lir) {
3961 Register temp = ToRegister(lir->temp());
3962
3963 // Remember the OSR entry offset into the code buffer.
3964 masm.flushBuffer();
3965 setOsrEntryOffset(masm.size());
3966
3967 // Allocate the full frame for this function
3968 // Note we have a new entry here. So we reset MacroAssembler::framePushed()
3969 // to 0, before reserving the stack.
3970 MOZ_ASSERT(masm.framePushed() == frameSize());
3971 masm.setFramePushed(0);
3972
3973 // The Baseline code ensured both the frame pointer and stack pointer point to
3974 // the JitFrameLayout on the stack.
3975
3976 // If profiling, save the current frame pointer to a per-thread global field.
3977 if (isProfilerInstrumentationEnabled()) {
3978 masm.profilerEnterFrame(FramePointer, temp);
3979 }
3980
3981 masm.reserveStack(frameSize());
3982 MOZ_ASSERT(masm.framePushed() == frameSize());
3983
3984 // Ensure that the Ion frames is properly aligned.
3985 masm.assertStackAlignment(JitStackAlignment, 0);
3986 }
3987
3988 void CodeGenerator::visitOsrEnvironmentChain(LOsrEnvironmentChain* lir) {
3989 const LAllocation* frame = lir->entry();
3990 const LDefinition* object = lir->output();
3991
3992 const ptrdiff_t frameOffset =
3993 BaselineFrame::reverseOffsetOfEnvironmentChain();
3994
3995 masm.loadPtr(Address(ToRegister(frame), frameOffset), ToRegister(object));
3996 }
3997
3998 void CodeGenerator::visitOsrArgumentsObject(LOsrArgumentsObject* lir) {
3999 const LAllocation* frame = lir->entry();
4000 const LDefinition* object = lir->output();
4001
4002 const ptrdiff_t frameOffset = BaselineFrame::reverseOffsetOfArgsObj();
4003
4004 masm.loadPtr(Address(ToRegister(frame), frameOffset), ToRegister(object));
4005 }
4006
4007 void CodeGenerator::visitOsrValue(LOsrValue* value) {
4008 const LAllocation* frame = value->entry();
4009 const ValueOperand out = ToOutValue(value);
4010
4011 const ptrdiff_t frameOffset = value->mir()->frameOffset();
4012
4013 masm.loadValue(Address(ToRegister(frame), frameOffset), out);
4014 }
4015
4016 void CodeGenerator::visitOsrReturnValue(LOsrReturnValue* lir) {
4017 const LAllocation* frame = lir->entry();
4018 const ValueOperand out = ToOutValue(lir);
4019
4020 Address flags =
4021 Address(ToRegister(frame), BaselineFrame::reverseOffsetOfFlags());
4022 Address retval =
4023 Address(ToRegister(frame), BaselineFrame::reverseOffsetOfReturnValue());
4024
4025 masm.moveValue(UndefinedValue(), out);
4026
4027 Label done;
4028 masm.branchTest32(Assembler::Zero, flags, Imm32(BaselineFrame::HAS_RVAL),
4029 &done);
4030 masm.loadValue(retval, out);
4031 masm.bind(&done);
4032 }
4033
4034 void CodeGenerator::visitStackArgT(LStackArgT* lir) {
4035 const LAllocation* arg = lir->arg();
4036 MIRType argType = lir->type();
4037 uint32_t argslot = lir->argslot();
4038 MOZ_ASSERT(argslot - 1u < graph.argumentSlotCount());
4039
4040 Address dest = AddressOfPassedArg(argslot);
4041
4042 if (arg->isFloatReg()) {
4043 masm.boxDouble(ToFloatRegister(arg), dest);
4044 } else if (arg->isGeneralReg()) {
4045 masm.storeValue(ValueTypeFromMIRType(argType), ToRegister(arg), dest);
4046 } else {
4047 masm.storeValue(arg->toConstant()->toJSValue(), dest);
4048 }
4049 }
4050
4051 void CodeGenerator::visitStackArgV(LStackArgV* lir) {
4052 ValueOperand val = ToValue(lir->value());
4053 uint32_t argslot = lir->argslot();
4054 MOZ_ASSERT(argslot - 1u < graph.argumentSlotCount());
4055
4056 masm.storeValue(val, AddressOfPassedArg(argslot));
4057 }
4058
4059 void CodeGenerator::visitMoveGroup(LMoveGroup* group) {
4060 if (!group->numMoves()) {
4061 return;
4062 }
4063
4064 MoveResolver& resolver = masm.moveResolver();
4065
4066 for (size_t i = 0; i < group->numMoves(); i++) {
4067 const LMove& move = group->getMove(i);
4068
4069 LAllocation from = move.from();
4070 LAllocation to = move.to();
4071 LDefinition::Type type = move.type();
4072
4073 // No bogus moves.
4074 MOZ_ASSERT(from != to);
4075 MOZ_ASSERT(!from.isConstant());
4076 MoveOp::Type moveType;
4077 switch (type) {
4078 case LDefinition::OBJECT:
4079 case LDefinition::SLOTS:
4080 case LDefinition::WASM_ANYREF:
4081 #ifdef JS_NUNBOX32
4082 case LDefinition::TYPE:
4083 case LDefinition::PAYLOAD:
4084 #else
4085 case LDefinition::BOX:
4086 #endif
4087 case LDefinition::GENERAL:
4088 case LDefinition::STACKRESULTS:
4089 moveType = MoveOp::GENERAL;
4090 break;
4091 case LDefinition::INT32:
4092 moveType = MoveOp::INT32;
4093 break;
4094 case LDefinition::FLOAT32:
4095 moveType = MoveOp::FLOAT32;
4096 break;
4097 case LDefinition::DOUBLE:
4098 moveType = MoveOp::DOUBLE;
4099 break;
4100 case LDefinition::SIMD128:
4101 moveType = MoveOp::SIMD128;
4102 break;
4103 default:
4104 MOZ_CRASH("Unexpected move type");
4105 }
4106
4107 masm.propagateOOM(
4108 resolver.addMove(toMoveOperand(from), toMoveOperand(to), moveType));
4109 }
4110
4111 masm.propagateOOM(resolver.resolve());
4112 if (masm.oom()) {
4113 return;
4114 }
4115
4116 MoveEmitter emitter(masm);
4117
4118 #ifdef JS_CODEGEN_X86
4119 if (group->maybeScratchRegister().isGeneralReg()) {
4120 emitter.setScratchRegister(
4121 group->maybeScratchRegister().toGeneralReg()->reg());
4122 } else {
4123 resolver.sortMemoryToMemoryMoves();
4124 }
4125 #endif
4126
4127 emitter.emit(resolver);
4128 emitter.finish();
4129 }
4130
4131 void CodeGenerator::visitInteger(LInteger* lir) {
4132 masm.move32(Imm32(lir->i32()), ToRegister(lir->output()));
4133 }
4134
4135 void CodeGenerator::visitInteger64(LInteger64* lir) {
4136 masm.move64(Imm64(lir->i64()), ToOutRegister64(lir));
4137 }
4138
4139 void CodeGenerator::visitPointer(LPointer* lir) {
4140 masm.movePtr(ImmGCPtr(lir->gcptr()), ToRegister(lir->output()));
4141 }
4142
4143 void CodeGenerator::visitDouble(LDouble* ins) {
4144 masm.loadConstantDouble(ins->value(), ToFloatRegister(ins->output()));
4145 }
4146
4147 void CodeGenerator::visitFloat32(LFloat32* ins) {
4148 masm.loadConstantFloat32(ins->value(), ToFloatRegister(ins->output()));
4149 }
4150
4151 void CodeGenerator::visitValue(LValue* value) {
4152 ValueOperand result = ToOutValue(value);
4153 masm.moveValue(value->value(), result);
4154 }
4155
4156 void CodeGenerator::visitNurseryObject(LNurseryObject* lir) {
4157 Register output = ToRegister(lir->output());
4158 uint32_t nurseryIndex = lir->mir()->nurseryIndex();
4159
4160 // Load a pointer to the entry in IonScript's nursery objects list.
4161 CodeOffset label = masm.movWithPatch(ImmWord(uintptr_t(-1)), output);
4162 masm.propagateOOM(ionNurseryObjectLabels_.emplaceBack(label, nurseryIndex));
4163
4164 // Load the JSObject*.
4165 masm.loadPtr(Address(output, 0), output);
4166 }
4167
4168 void CodeGenerator::visitKeepAliveObject(LKeepAliveObject* lir) {
4169 // No-op.
4170 }
4171
4172 void CodeGenerator::visitDebugEnterGCUnsafeRegion(
4173 LDebugEnterGCUnsafeRegion* lir) {
4174 Register temp = ToRegister(lir->temp0());
4175
4176 masm.loadJSContext(temp);
4177
4178 Address inUnsafeRegion(temp, JSContext::offsetOfInUnsafeRegion());
4179 masm.add32(Imm32(1), inUnsafeRegion);
4180
4181 Label ok;
4182 masm.branch32(Assembler::GreaterThan, inUnsafeRegion, Imm32(0), &ok);
4183 masm.assumeUnreachable("unbalanced enter/leave GC unsafe region");
4184 masm.bind(&ok);
4185 }
4186
4187 void CodeGenerator::visitDebugLeaveGCUnsafeRegion(
4188 LDebugLeaveGCUnsafeRegion* lir) {
4189 Register temp = ToRegister(lir->temp0());
4190
4191 masm.loadJSContext(temp);
4192
4193 Address inUnsafeRegion(temp, JSContext::offsetOfInUnsafeRegion());
4194 masm.add32(Imm32(-1), inUnsafeRegion);
4195
4196 Label ok;
4197 masm.branch32(Assembler::GreaterThanOrEqual, inUnsafeRegion, Imm32(0), &ok);
4198 masm.assumeUnreachable("unbalanced enter/leave GC unsafe region");
4199 masm.bind(&ok);
4200 }
4201
4202 void CodeGenerator::visitSlots(LSlots* lir) {
4203 Address slots(ToRegister(lir->object()), NativeObject::offsetOfSlots());
4204 masm.loadPtr(slots, ToRegister(lir->output()));
4205 }
4206
4207 void CodeGenerator::visitLoadDynamicSlotV(LLoadDynamicSlotV* lir) {
4208 ValueOperand dest = ToOutValue(lir);
4209 Register base = ToRegister(lir->input());
4210 int32_t offset = lir->mir()->slot() * sizeof(js::Value);
4211
4212 masm.loadValue(Address(base, offset), dest);
4213 }
4214
4215 static ConstantOrRegister ToConstantOrRegister(const LAllocation* value,
4216 MIRType valueType) {
4217 if (value->isConstant()) {
4218 return ConstantOrRegister(value->toConstant()->toJSValue());
4219 }
4220 return TypedOrValueRegister(valueType, ToAnyRegister(value));
4221 }
4222
4223 void CodeGenerator::visitStoreDynamicSlotT(LStoreDynamicSlotT* lir) {
4224 Register base = ToRegister(lir->slots());
4225 int32_t offset = lir->mir()->slot() * sizeof(js::Value);
4226 Address dest(base, offset);
4227
4228 if (lir->mir()->needsBarrier()) {
4229 emitPreBarrier(dest);
4230 }
4231
4232 MIRType valueType = lir->mir()->value()->type();
4233 ConstantOrRegister value = ToConstantOrRegister(lir->value(), valueType);
4234 masm.storeUnboxedValue(value, valueType, dest);
4235 }
4236
4237 void CodeGenerator::visitStoreDynamicSlotV(LStoreDynamicSlotV* lir) {
4238 Register base = ToRegister(lir->slots());
4239 int32_t offset = lir->mir()->slot() * sizeof(Value);
4240
4241 ValueOperand value = ToValue(lir->value());
4242
4243 if (lir->mir()->needsBarrier()) {
4244 emitPreBarrier(Address(base, offset));
4245 }
4246
4247 masm.storeValue(value, Address(base, offset));
4248 }
4249
4250 void CodeGenerator::visitElements(LElements* lir) {
4251 Address elements(ToRegister(lir->object()), NativeObject::offsetOfElements());
4252 masm.loadPtr(elements, ToRegister(lir->output()));
4253 }
4254
4255 void CodeGenerator::visitFunctionEnvironment(LFunctionEnvironment* lir) {
4256 Address environment(ToRegister(lir->function()),
4257 JSFunction::offsetOfEnvironment());
4258 masm.unboxObject(environment, ToRegister(lir->output()));
4259 }
4260
4261 void CodeGenerator::visitHomeObject(LHomeObject* lir) {
4262 Register func = ToRegister(lir->function());
4263 Address homeObject(func, FunctionExtended::offsetOfMethodHomeObjectSlot());
4264
4265 masm.assertFunctionIsExtended(func);
4266 #ifdef DEBUG
4267 Label isObject;
4268 masm.branchTestObject(Assembler::Equal, homeObject, &isObject);
4269 masm.assumeUnreachable("[[HomeObject]] must be Object");
4270 masm.bind(&isObject);
4271 #endif
4272
4273 masm.unboxObject(homeObject, ToRegister(lir->output()));
4274 }
4275
4276 void CodeGenerator::visitHomeObjectSuperBase(LHomeObjectSuperBase* lir) {
4277 Register homeObject = ToRegister(lir->homeObject());
4278 ValueOperand output = ToOutValue(lir);
4279 Register temp = output.scratchReg();
4280
4281 masm.loadObjProto(homeObject, temp);
4282
4283 #ifdef DEBUG
4284 // We won't encounter a lazy proto, because the prototype is guaranteed to
4285 // either be a JSFunction or a PlainObject, and only proxy objects can have a
4286 // lazy proto.
4287 MOZ_ASSERT(uintptr_t(TaggedProto::LazyProto) == 1);
4288
4289 Label proxyCheckDone;
4290 masm.branchPtr(Assembler::NotEqual, temp, ImmWord(1), &proxyCheckDone);
4291 masm.assumeUnreachable("Unexpected lazy proto in JSOp::SuperBase");
4292 masm.bind(&proxyCheckDone);
4293 #endif
4294
4295 Label nullProto, done;
4296 masm.branchPtr(Assembler::Equal, temp, ImmWord(0), &nullProto);
4297
4298 // Box prototype and return
4299 masm.tagValue(JSVAL_TYPE_OBJECT, temp, output);
4300 masm.jump(&done);
4301
4302 masm.bind(&nullProto);
4303 masm.moveValue(NullValue(), output);
4304
4305 masm.bind(&done);
4306 }
4307
4308 template <class T>
4309 static T* ToConstantObject(MDefinition* def) {
4310 MOZ_ASSERT(def->isConstant());
4311 return &def->toConstant()->toObject().as<T>();
4312 }
4313
4314 void CodeGenerator::visitNewLexicalEnvironmentObject(
4315 LNewLexicalEnvironmentObject* lir) {
4316 Register output = ToRegister(lir->output());
4317 Register temp = ToRegister(lir->temp0());
4318
4319 auto* templateObj = ToConstantObject<BlockLexicalEnvironmentObject>(
4320 lir->mir()->templateObj());
4321 auto* scope = &templateObj->scope();
4322 gc::Heap initialHeap = gc::Heap::Default;
4323
4324 using Fn =
4325 BlockLexicalEnvironmentObject* (*)(JSContext*, Handle<LexicalScope*>);
4326 auto* ool =
4327 oolCallVM<Fn, BlockLexicalEnvironmentObject::createWithoutEnclosing>(
4328 lir, ArgList(ImmGCPtr(scope)), StoreRegisterTo(output));
4329
4330 TemplateObject templateObject(templateObj);
4331 masm.createGCObject(output, temp, templateObject, initialHeap, ool->entry());
4332
4333 masm.bind(ool->rejoin());
4334 }
4335
4336 void CodeGenerator::visitNewClassBodyEnvironmentObject(
4337 LNewClassBodyEnvironmentObject* lir) {
4338 Register output = ToRegister(lir->output());
4339 Register temp = ToRegister(lir->temp0());
4340
4341 auto* templateObj = ToConstantObject<ClassBodyLexicalEnvironmentObject>(
4342 lir->mir()->templateObj());
4343 auto* scope = &templateObj->scope();
4344 gc::Heap initialHeap = gc::Heap::Default;
4345
4346 using Fn = ClassBodyLexicalEnvironmentObject* (*)(JSContext*,
4347 Handle<ClassBodyScope*>);
4348 auto* ool =
4349 oolCallVM<Fn, ClassBodyLexicalEnvironmentObject::createWithoutEnclosing>(
4350 lir, ArgList(ImmGCPtr(scope)), StoreRegisterTo(output));
4351
4352 TemplateObject templateObject(templateObj);
4353 masm.createGCObject(output, temp, templateObject, initialHeap, ool->entry());
4354
4355 masm.bind(ool->rejoin());
4356 }
4357
4358 void CodeGenerator::visitNewVarEnvironmentObject(
4359 LNewVarEnvironmentObject* lir) {
4360 Register output = ToRegister(lir->output());
4361 Register temp = ToRegister(lir->temp0());
4362
4363 auto* templateObj =
4364 ToConstantObject<VarEnvironmentObject>(lir->mir()->templateObj());
4365 auto* scope = &templateObj->scope().as<VarScope>();
4366 gc::Heap initialHeap = gc::Heap::Default;
4367
4368 using Fn = VarEnvironmentObject* (*)(JSContext*, Handle<VarScope*>);
4369 auto* ool = oolCallVM<Fn, VarEnvironmentObject::createWithoutEnclosing>(
4370 lir, ArgList(ImmGCPtr(scope)), StoreRegisterTo(output));
4371
4372 TemplateObject templateObject(templateObj);
4373 masm.createGCObject(output, temp, templateObject, initialHeap, ool->entry());
4374
4375 masm.bind(ool->rejoin());
4376 }
4377
4378 void CodeGenerator::visitGuardShape(LGuardShape* guard) {
4379 Register obj = ToRegister(guard->object());
4380 Register temp = ToTempRegisterOrInvalid(guard->temp0());
4381 Label bail;
4382 masm.branchTestObjShape(Assembler::NotEqual, obj, guard->mir()->shape(), temp,
4383 obj, &bail);
4384 bailoutFrom(&bail, guard->snapshot());
4385 }
4386
4387 void CodeGenerator::visitGuardFuse(LGuardFuse* guard) {
4388 auto fuseIndex = guard->mir()->fuseIndex();
4389
4390 Register temp = ToRegister(guard->temp0());
4391 Label bail;
4392
4393 // Bake specific fuse address for Ion code, because we won't share this code
4394 // across realms.
4395 GuardFuse* fuse = mirGen().realm->realmFuses().getFuseByIndex(fuseIndex);
4396 masm.loadPtr(AbsoluteAddress(fuse->fuseRef()), temp);
4397 masm.branchPtr(Assembler::NotEqual, temp, ImmPtr(nullptr), &bail);
4398
4399 bailoutFrom(&bail, guard->snapshot());
4400 }
4401
4402 void CodeGenerator::visitGuardMultipleShapes(LGuardMultipleShapes* guard) {
4403 Register obj = ToRegister(guard->object());
4404 Register shapeList = ToRegister(guard->shapeList());
4405 Register temp = ToRegister(guard->temp0());
4406 Register temp2 = ToRegister(guard->temp1());
4407 Register temp3 = ToRegister(guard->temp2());
4408 Register spectre = ToTempRegisterOrInvalid(guard->temp3());
4409
4410 Label bail;
4411 masm.loadPtr(Address(shapeList, NativeObject::offsetOfElements()), temp);
4412 masm.branchTestObjShapeList(Assembler::NotEqual, obj, temp, temp2, temp3,
4413 spectre, &bail);
4414 bailoutFrom(&bail, guard->snapshot());
4415 }
4416
4417 void CodeGenerator::visitGuardProto(LGuardProto* guard) {
4418 Register obj = ToRegister(guard->object());
4419 Register expected = ToRegister(guard->expected());
4420 Register temp = ToRegister(guard->temp0());
4421
4422 masm.loadObjProto(obj, temp);
4423
4424 Label bail;
4425 masm.branchPtr(Assembler::NotEqual, temp, expected, &bail);
4426 bailoutFrom(&bail, guard->snapshot());
4427 }
4428
4429 void CodeGenerator::visitGuardNullProto(LGuardNullProto* guard) {
4430 Register obj = ToRegister(guard->object());
4431 Register temp = ToRegister(guard->temp0());
4432
4433 masm.loadObjProto(obj, temp);
4434
4435 Label bail;
4436 masm.branchTestPtr(Assembler::NonZero, temp, temp, &bail);
4437 bailoutFrom(&bail, guard->snapshot());
4438 }
4439
4440 void CodeGenerator::visitGuardIsNativeObject(LGuardIsNativeObject* guard) {
4441 Register obj = ToRegister(guard->object());
4442 Register temp = ToRegister(guard->temp0());
4443
4444 Label bail;
4445 masm.branchIfNonNativeObj(obj, temp, &bail);
4446 bailoutFrom(&bail, guard->snapshot());
4447 }
4448
4449 void CodeGenerator::visitGuardGlobalGeneration(LGuardGlobalGeneration* guard) {
4450 Register temp = ToRegister(guard->temp0());
4451 Label bail;
4452
4453 masm.load32(AbsoluteAddress(guard->mir()->generationAddr()), temp);
4454 masm.branch32(Assembler::NotEqual, temp, Imm32(guard->mir()->expected()),
4455 &bail);
4456 bailoutFrom(&bail, guard->snapshot());
4457 }
4458
4459 void CodeGenerator::visitGuardIsProxy(LGuardIsProxy* guard) {
4460 Register obj = ToRegister(guard->object());
4461 Register temp = ToRegister(guard->temp0());
4462
4463 Label bail;
4464 masm.branchTestObjectIsProxy(false, obj, temp, &bail);
4465 bailoutFrom(&bail, guard->snapshot());
4466 }
4467
4468 void CodeGenerator::visitGuardIsNotProxy(LGuardIsNotProxy* guard) {
4469 Register obj = ToRegister(guard->object());
4470 Register temp = ToRegister(guard->temp0());
4471
4472 Label bail;
4473 masm.branchTestObjectIsProxy(true, obj, temp, &bail);
4474 bailoutFrom(&bail, guard->snapshot());
4475 }
4476
4477 void CodeGenerator::visitGuardIsNotDOMProxy(LGuardIsNotDOMProxy* guard) {
4478 Register proxy = ToRegister(guard->proxy());
4479 Register temp = ToRegister(guard->temp0());
4480
4481 Label bail;
4482 masm.branchTestProxyHandlerFamily(Assembler::Equal, proxy, temp,
4483 GetDOMProxyHandlerFamily(), &bail);
4484 bailoutFrom(&bail, guard->snapshot());
4485 }
4486
4487 void CodeGenerator::visitProxyGet(LProxyGet* lir) {
4488 Register proxy = ToRegister(lir->proxy());
4489 Register temp = ToRegister(lir->temp0());
4490
4491 pushArg(lir->mir()->id(), temp);
4492 pushArg(proxy);
4493
4494 using Fn = bool (*)(JSContext*, HandleObject, HandleId, MutableHandleValue);
4495 callVM<Fn, ProxyGetProperty>(lir);
4496 }
4497
4498 void CodeGenerator::visitProxyGetByValue(LProxyGetByValue* lir) {
4499 Register proxy = ToRegister(lir->proxy());
4500 ValueOperand idVal = ToValue(lir->idVal());
4501
4502 pushArg(idVal);
4503 pushArg(proxy);
4504
4505 using Fn =
4506 bool (*)(JSContext*, HandleObject, HandleValue, MutableHandleValue);
4507 callVM<Fn, ProxyGetPropertyByValue>(lir);
4508 }
4509
4510 void CodeGenerator::visitProxyHasProp(LProxyHasProp* lir) {
4511 Register proxy = ToRegister(lir->proxy());
4512 ValueOperand idVal = ToValue(lir->id());
4513
4514 pushArg(idVal);
4515 pushArg(proxy);
4516
4517 using Fn = bool (*)(JSContext*, HandleObject, HandleValue, bool*);
4518 if (lir->mir()->hasOwn()) {
4519 callVM<Fn, ProxyHasOwn>(lir);
4520 } else {
4521 callVM<Fn, ProxyHas>(lir);
4522 }
4523 }
4524
4525 void CodeGenerator::visitProxySet(LProxySet* lir) {
4526 Register proxy = ToRegister(lir->proxy());
4527 ValueOperand rhs = ToValue(lir->rhs());
4528 Register temp = ToRegister(lir->temp0());
4529
4530 pushArg(Imm32(lir->mir()->strict()));
4531 pushArg(rhs);
4532 pushArg(lir->mir()->id(), temp);
4533 pushArg(proxy);
4534
4535 using Fn = bool (*)(JSContext*, HandleObject, HandleId, HandleValue, bool);
4536 callVM<Fn, ProxySetProperty>(lir);
4537 }
4538
4539 void CodeGenerator::visitProxySetByValue(LProxySetByValue* lir) {
4540 Register proxy = ToRegister(lir->proxy());
4541 ValueOperand idVal = ToValue(lir->idVal());
4542 ValueOperand rhs = ToValue(lir->rhs());
4543
4544 pushArg(Imm32(lir->mir()->strict()));
4545 pushArg(rhs);
4546 pushArg(idVal);
4547 pushArg(proxy);
4548
4549 using Fn = bool (*)(JSContext*, HandleObject, HandleValue, HandleValue, bool);
4550 callVM<Fn, ProxySetPropertyByValue>(lir);
4551 }
4552
4553 void CodeGenerator::visitCallSetArrayLength(LCallSetArrayLength* lir) {
4554 Register obj = ToRegister(lir->obj());
4555 ValueOperand rhs = ToValue(lir->rhs());
4556
4557 pushArg(Imm32(lir->mir()->strict()));
4558 pushArg(rhs);
4559 pushArg(obj);
4560
4561 using Fn = bool (*)(JSContext*, HandleObject, HandleValue, bool);
4562 callVM<Fn, jit::SetArrayLength>(lir);
4563 }
4564
4565 void CodeGenerator::visitMegamorphicLoadSlot(LMegamorphicLoadSlot* lir) {
4566 Register obj = ToRegister(lir->object());
4567 Register temp0 = ToRegister(lir->temp0());
4568 Register temp1 = ToRegister(lir->temp1());
4569 Register temp2 = ToRegister(lir->temp2());
4570 Register temp3 = ToRegister(lir->temp3());
4571 ValueOperand output = ToOutValue(lir);
4572
4573 Label cacheHit;
4574 masm.emitMegamorphicCacheLookup(lir->mir()->name(), obj, temp0, temp1, temp2,
4575 output, &cacheHit);
4576
4577 Label bail;
4578 masm.branchIfNonNativeObj(obj, temp0, &bail);
4579
4580 masm.Push(UndefinedValue());
4581 masm.moveStackPtrTo(temp3);
4582
4583 using Fn = bool (*)(JSContext* cx, JSObject* obj, PropertyKey id,
4584 MegamorphicCache::Entry* cacheEntry, Value* vp);
4585 masm.setupAlignedABICall();
4586 masm.loadJSContext(temp0);
4587 masm.passABIArg(temp0);
4588 masm.passABIArg(obj);
4589 masm.movePropertyKey(lir->mir()->name(), temp1);
4590 masm.passABIArg(temp1);
4591 masm.passABIArg(temp2);
4592 masm.passABIArg(temp3);
4593
4594 masm.callWithABI<Fn, GetNativeDataPropertyPure>();
4595
4596 MOZ_ASSERT(!output.aliases(ReturnReg));
4597 masm.Pop(output);
4598
4599 masm.branchIfFalseBool(ReturnReg, &bail);
4600 masm.bind(&cacheHit);
4601
4602 bailoutFrom(&bail, lir->snapshot());
4603 }
4604
4605 void CodeGenerator::visitMegamorphicLoadSlotPermissive(
4606 LMegamorphicLoadSlotPermissive* lir) {
4607 Register obj = ToRegister(lir->object());
4608 Register temp0 = ToRegister(lir->temp0());
4609 Register temp1 = ToRegister(lir->temp1());
4610 Register temp2 = ToRegister(lir->temp2());
4611 Register temp3 = ToRegister(lir->temp3());
4612 ValueOperand output = ToOutValue(lir);
4613
4614 masm.movePtr(obj, temp3);
4615
4616 Label done, getter, nullGetter;
4617 masm.emitMegamorphicCacheLookup(lir->mir()->name(), obj, temp0, temp1, temp2,
4618 output, &done, &getter);
4619
4620 masm.movePropertyKey(lir->mir()->name(), temp1);
4621 pushArg(temp2);
4622 pushArg(temp1);
4623 pushArg(obj);
4624
4625 using Fn = bool (*)(JSContext*, HandleObject, HandleId,
4626 MegamorphicCacheEntry*, MutableHandleValue);
4627 callVM<Fn, GetPropMaybeCached>(lir);
4628
4629 masm.jump(&done);
4630
4631 masm.bind(&getter);
4632
4633 emitCallMegamorphicGetter(lir, output, temp3, temp1, temp2, &nullGetter);
4634 masm.jump(&done);
4635
4636 masm.bind(&nullGetter);
4637 masm.moveValue(UndefinedValue(), output);
4638
4639 masm.bind(&done);
4640 }
4641
4642 void CodeGenerator::visitMegamorphicLoadSlotByValue(
4643 LMegamorphicLoadSlotByValue* lir) {
4644 Register obj = ToRegister(lir->object());
4645 ValueOperand idVal = ToValue(lir->idVal());
4646 Register temp0 = ToRegister(lir->temp0());
4647 Register temp1 = ToRegister(lir->temp1());
4648 Register temp2 = ToRegister(lir->temp2());
4649 ValueOperand output = ToOutValue(lir);
4650
4651 Label cacheHit, bail;
4652 masm.emitMegamorphicCacheLookupByValue(idVal, obj, temp0, temp1, temp2,
4653 output, &cacheHit);
4654
4655 masm.branchIfNonNativeObj(obj, temp0, &bail);
4656
4657 // idVal will be in vp[0], result will be stored in vp[1].
4658 masm.reserveStack(sizeof(Value));
4659 masm.Push(idVal);
4660 masm.moveStackPtrTo(temp0);
4661
4662 using Fn = bool (*)(JSContext* cx, JSObject* obj,
4663 MegamorphicCache::Entry* cacheEntry, Value* vp);
4664 masm.setupAlignedABICall();
4665 masm.loadJSContext(temp1);
4666 masm.passABIArg(temp1);
4667 masm.passABIArg(obj);
4668 masm.passABIArg(temp2);
4669 masm.passABIArg(temp0);
4670 masm.callWithABI<Fn, GetNativeDataPropertyByValuePure>();
4671
4672 MOZ_ASSERT(!idVal.aliases(temp0));
4673 masm.storeCallPointerResult(temp0);
4674 masm.Pop(idVal);
4675
4676 uint32_t framePushed = masm.framePushed();
4677 Label ok;
4678 masm.branchIfTrueBool(temp0, &ok);
4679 masm.freeStack(sizeof(Value)); // Discard result Value.
4680 masm.jump(&bail);
4681
4682 masm.bind(&ok);
4683 masm.setFramePushed(framePushed);
4684 masm.Pop(output);
4685
4686 masm.bind(&cacheHit);
4687
4688 bailoutFrom(&bail, lir->snapshot());
4689 }
4690
4691 void CodeGenerator::visitMegamorphicLoadSlotByValuePermissive(
4692 LMegamorphicLoadSlotByValuePermissive* lir) {
4693 Register obj = ToRegister(lir->object());
4694 ValueOperand idVal = ToValue(lir->idVal());
4695 Register temp0 = ToRegister(lir->temp0());
4696 Register temp1 = ToRegister(lir->temp1());
4697 Register temp2 = ToRegister(lir->temp2());
4698 ValueOperand output = ToOutValue(lir);
4699
4700 // If we have enough registers available, we can call getters directly from
4701 // jitcode. On x86, we have to call into the VM.
4702 #ifndef JS_CODEGEN_X86
4703 Label done, getter, nullGetter;
4704 Register temp3 = ToRegister(lir->temp3());
4705 masm.movePtr(obj, temp3);
4706
4707 masm.emitMegamorphicCacheLookupByValue(idVal, obj, temp0, temp1, temp2,
4708 output, &done, &getter);
4709 #else
4710 Label done;
4711 masm.emitMegamorphicCacheLookupByValue(idVal, obj, temp0, temp1, temp2,
4712 output, &done);
4713 #endif
4714
4715 pushArg(temp2);
4716 pushArg(idVal);
4717 pushArg(obj);
4718
4719 using Fn = bool (*)(JSContext*, HandleObject, HandleValue,
4720 MegamorphicCacheEntry*, MutableHandleValue);
4721 callVM<Fn, GetElemMaybeCached>(lir);
4722
4723 #ifndef JS_CODEGEN_X86
4724 masm.jump(&done);
4725 masm.bind(&getter);
4726
4727 emitCallMegamorphicGetter(lir, output, temp3, temp1, temp2, &nullGetter);
4728 masm.jump(&done);
4729
4730 masm.bind(&nullGetter);
4731 masm.moveValue(UndefinedValue(), output);
4732 #endif
4733
4734 masm.bind(&done);
4735 }
4736
4737 void CodeGenerator::visitMegamorphicStoreSlot(LMegamorphicStoreSlot* lir) {
4738 Register obj = ToRegister(lir->object());
4739 ValueOperand value = ToValue(lir->rhs());
4740
4741 Register temp0 = ToRegister(lir->temp0());
4742 #ifndef JS_CODEGEN_X86
4743 Register temp1 = ToRegister(lir->temp1());
4744 Register temp2 = ToRegister(lir->temp2());
4745 #endif
4746
4747 // The instruction is marked as call-instruction so only these registers are
4748 // live.
4749 LiveRegisterSet liveRegs;
4750 liveRegs.addUnchecked(obj);
4751 liveRegs.addUnchecked(value);
4752 liveRegs.addUnchecked(temp0);
4753 #ifndef JS_CODEGEN_X86
4754 liveRegs.addUnchecked(temp1);
4755 liveRegs.addUnchecked(temp2);
4756 #endif
4757
4758 Label cacheHit, done;
4759 #ifdef JS_CODEGEN_X86
4760 masm.emitMegamorphicCachedSetSlot(
4761 lir->mir()->name(), obj, temp0, value, liveRegs, &cacheHit,
4762 [](MacroAssembler& masm, const Address& addr, MIRType mirType) {
4763 EmitPreBarrier(masm, addr, mirType);
4764 });
4765 #else
4766 masm.emitMegamorphicCachedSetSlot(
4767 lir->mir()->name(), obj, temp0, temp1, temp2, value, liveRegs, &cacheHit,
4768 [](MacroAssembler& masm, const Address& addr, MIRType mirType) {
4769 EmitPreBarrier(masm, addr, mirType);
4770 });
4771 #endif
4772
4773 pushArg(Imm32(lir->mir()->strict()));
4774 pushArg(value);
4775 pushArg(lir->mir()->name(), temp0);
4776 pushArg(obj);
4777
4778 using Fn = bool (*)(JSContext*, HandleObject, HandleId, HandleValue, bool);
4779 callVM<Fn, SetPropertyMegamorphic<true>>(lir);
4780
4781 masm.jump(&done);
4782 masm.bind(&cacheHit);
4783
4784 masm.branchPtrInNurseryChunk(Assembler::Equal, obj, temp0, &done);
4785 masm.branchValueIsNurseryCell(Assembler::NotEqual, value, temp0, &done);
4786
4787 // Note: because this is a call-instruction, no registers need to be saved.
4788 MOZ_ASSERT(lir->isCall());
4789 emitPostWriteBarrier(obj);
4790
4791 masm.bind(&done);
4792 }
4793
4794 void CodeGenerator::visitMegamorphicHasProp(LMegamorphicHasProp* lir) {
4795 Register obj = ToRegister(lir->object());
4796 ValueOperand idVal = ToValue(lir->idVal());
4797 Register temp0 = ToRegister(lir->temp0());
4798 Register temp1 = ToRegister(lir->temp1());
4799 Register temp2 = ToRegister(lir->temp2());
4800 Register output = ToRegister(lir->output());
4801
4802 Label bail, cacheHit;
4803 masm.emitMegamorphicCacheLookupExists(idVal, obj, temp0, temp1, temp2, output,
4804 &cacheHit, lir->mir()->hasOwn());
4805
4806 masm.branchIfNonNativeObj(obj, temp0, &bail);
4807
4808 // idVal will be in vp[0], result will be stored in vp[1].
4809 masm.reserveStack(sizeof(Value));
4810 masm.Push(idVal);
4811 masm.moveStackPtrTo(temp0);
4812
4813 using Fn = bool (*)(JSContext* cx, JSObject* obj,
4814 MegamorphicCache::Entry* cacheEntry, Value* vp);
4815 masm.setupAlignedABICall();
4816 masm.loadJSContext(temp1);
4817 masm.passABIArg(temp1);
4818 masm.passABIArg(obj);
4819 masm.passABIArg(temp2);
4820 masm.passABIArg(temp0);
4821 if (lir->mir()->hasOwn()) {
4822 masm.callWithABI<Fn, HasNativeDataPropertyPure<true>>();
4823 } else {
4824 masm.callWithABI<Fn, HasNativeDataPropertyPure<false>>();
4825 }
4826
4827 MOZ_ASSERT(!idVal.aliases(temp0));
4828 masm.storeCallPointerResult(temp0);
4829 masm.Pop(idVal);
4830
4831 uint32_t framePushed = masm.framePushed();
4832 Label ok;
4833 masm.branchIfTrueBool(temp0, &ok);
4834 masm.freeStack(sizeof(Value)); // Discard result Value.
4835 masm.jump(&bail);
4836
4837 masm.bind(&ok);
4838 masm.setFramePushed(framePushed);
4839 masm.unboxBoolean(Address(masm.getStackPointer(), 0), output);
4840 masm.freeStack(sizeof(Value));
4841 masm.bind(&cacheHit);
4842
4843 bailoutFrom(&bail, lir->snapshot());
4844 }
4845
4846 void CodeGenerator::visitSmallObjectVariableKeyHasProp(
4847 LSmallObjectVariableKeyHasProp* lir) {
4848 Register id = ToRegister(lir->idStr());
4849 Register output = ToRegister(lir->output());
4850
4851 #ifdef DEBUG
4852 Label isAtom;
4853 masm.branchTest32(Assembler::NonZero, Address(id, JSString::offsetOfFlags()),
4854 Imm32(JSString::ATOM_BIT), &isAtom);
4855 masm.assumeUnreachable("Expected atom input");
4856 masm.bind(&isAtom);
4857 #endif
4858
4859 SharedShape* shape = &lir->mir()->shape()->asShared();
4860
4861 Label done, success;
4862 for (SharedShapePropertyIter<NoGC> iter(shape); !iter.done(); iter++) {
4863 masm.branchPtr(Assembler::Equal, id, ImmGCPtr(iter->key().toAtom()),
4864 &success);
4865 }
4866 masm.move32(Imm32(0), output);
4867 masm.jump(&done);
4868 masm.bind(&success);
4869 masm.move32(Imm32(1), output);
4870 masm.bind(&done);
4871 }
4872
4873 void CodeGenerator::visitGuardIsNotArrayBufferMaybeShared(
4874 LGuardIsNotArrayBufferMaybeShared* guard) {
4875 Register obj = ToRegister(guard->object());
4876 Register temp = ToRegister(guard->temp0());
4877
4878 Label bail;
4879 masm.loadObjClassUnsafe(obj, temp);
4880 masm.branchPtr(Assembler::Equal, temp,
4881 ImmPtr(&FixedLengthArrayBufferObject::class_), &bail);
4882 masm.branchPtr(Assembler::Equal, temp,
4883 ImmPtr(&FixedLengthSharedArrayBufferObject::class_), &bail);
4884 masm.branchPtr(Assembler::Equal, temp,
4885 ImmPtr(&ResizableArrayBufferObject::class_), &bail);
4886 masm.branchPtr(Assembler::Equal, temp,
4887 ImmPtr(&GrowableSharedArrayBufferObject::class_), &bail);
4888 bailoutFrom(&bail, guard->snapshot());
4889 }
4890
4891 void CodeGenerator::visitGuardIsTypedArray(LGuardIsTypedArray* guard) {
4892 Register obj = ToRegister(guard->object());
4893 Register temp = ToRegister(guard->temp0());
4894
4895 Label bail;
4896 masm.loadObjClassUnsafe(obj, temp);
4897 masm.branchIfClassIsNotTypedArray(temp, &bail);
4898 bailoutFrom(&bail, guard->snapshot());
4899 }
4900
4901 void CodeGenerator::visitGuardIsFixedLengthTypedArray(
4902 LGuardIsFixedLengthTypedArray* guard) {
4903 Register obj = ToRegister(guard->object());
4904 Register temp = ToRegister(guard->temp0());
4905
4906 Label bail;
4907 masm.loadObjClassUnsafe(obj, temp);
4908 masm.branchIfClassIsNotFixedLengthTypedArray(temp, &bail);
4909 bailoutFrom(&bail, guard->snapshot());
4910 }
4911
4912 void CodeGenerator::visitGuardIsResizableTypedArray(
4913 LGuardIsResizableTypedArray* guard) {
4914 Register obj = ToRegister(guard->object());
4915 Register temp = ToRegister(guard->temp0());
4916
4917 Label bail;
4918 masm.loadObjClassUnsafe(obj, temp);
4919 masm.branchIfClassIsNotResizableTypedArray(temp, &bail);
4920 bailoutFrom(&bail, guard->snapshot());
4921 }
4922
4923 void CodeGenerator::visitGuardHasProxyHandler(LGuardHasProxyHandler* guard) {
4924 Register obj = ToRegister(guard->object());
4925
4926 Label bail;
4927
4928 Address handlerAddr(obj, ProxyObject::offsetOfHandler());
4929 masm.branchPtr(Assembler::NotEqual, handlerAddr,
4930 ImmPtr(guard->mir()->handler()), &bail);
4931
4932 bailoutFrom(&bail, guard->snapshot());
4933 }
4934
4935 void CodeGenerator::visitGuardObjectIdentity(LGuardObjectIdentity* guard) {
4936 Register input = ToRegister(guard->input());
4937 Register expected = ToRegister(guard->expected());
4938
4939 Assembler::Condition cond =
4940 guard->mir()->bailOnEquality() ? Assembler::Equal : Assembler::NotEqual;
4941 bailoutCmpPtr(cond, input, expected, guard->snapshot());
4942 }
4943
4944 void CodeGenerator::visitGuardSpecificFunction(LGuardSpecificFunction* guard) {
4945 Register input = ToRegister(guard->input());
4946 Register expected = ToRegister(guard->expected());
4947
4948 bailoutCmpPtr(Assembler::NotEqual, input, expected, guard->snapshot());
4949 }
4950
4951 void CodeGenerator::visitGuardSpecificAtom(LGuardSpecificAtom* guard) {
4952 Register str = ToRegister(guard->str());
4953 Register scratch = ToRegister(guard->temp0());
4954
4955 LiveRegisterSet volatileRegs = liveVolatileRegs(guard);
4956 volatileRegs.takeUnchecked(scratch);
4957
4958 Label bail;
4959 masm.guardSpecificAtom(str, guard->mir()->atom(), scratch, volatileRegs,
4960 &bail);
4961 bailoutFrom(&bail, guard->snapshot());
4962 }
4963
4964 void CodeGenerator::visitGuardSpecificSymbol(LGuardSpecificSymbol* guard) {
4965 Register symbol = ToRegister(guard->symbol());
4966
4967 bailoutCmpPtr(Assembler::NotEqual, symbol, ImmGCPtr(guard->mir()->expected()),
4968 guard->snapshot());
4969 }
4970
4971 void CodeGenerator::visitGuardSpecificInt32(LGuardSpecificInt32* guard) {
4972 Register num = ToRegister(guard->num());
4973
4974 bailoutCmp32(Assembler::NotEqual, num, Imm32(guard->mir()->expected()),
4975 guard->snapshot());
4976 }
4977
4978 void CodeGenerator::visitGuardStringToIndex(LGuardStringToIndex* lir) {
4979 Register str = ToRegister(lir->string());
4980 Register output = ToRegister(lir->output());
4981
4982 Label vmCall, done;
4983 masm.loadStringIndexValue(str, output, &vmCall);
4984 masm.jump(&done);
4985
4986 {
4987 masm.bind(&vmCall);
4988
4989 LiveRegisterSet volatileRegs = liveVolatileRegs(lir);
4990 volatileRegs.takeUnchecked(output);
4991 masm.PushRegsInMask(volatileRegs);
4992
4993 using Fn = int32_t (*)(JSString* str);
4994 masm.setupAlignedABICall();
4995 masm.passABIArg(str);
4996 masm.callWithABI<Fn, GetIndexFromString>();
4997 masm.storeCallInt32Result(output);
4998
4999 masm.PopRegsInMask(volatileRegs);
5000
5001 // GetIndexFromString returns a negative value on failure.
5002 bailoutTest32(Assembler::Signed, output, output, lir->snapshot());
5003 }
5004
5005 masm.bind(&done);
5006 }
5007
5008 void CodeGenerator::visitGuardStringToInt32(LGuardStringToInt32* lir) {
5009 Register str = ToRegister(lir->string());
5010 Register output = ToRegister(lir->output());
5011 Register temp = ToRegister(lir->temp0());
5012
5013 LiveRegisterSet volatileRegs = liveVolatileRegs(lir);
5014
5015 Label bail;
5016 masm.guardStringToInt32(str, output, temp, volatileRegs, &bail);
5017 bailoutFrom(&bail, lir->snapshot());
5018 }
5019
5020 void CodeGenerator::visitGuardStringToDouble(LGuardStringToDouble* lir) {
5021 Register str = ToRegister(lir->string());
5022 FloatRegister output = ToFloatRegister(lir->output());
5023 Register temp0 = ToRegister(lir->temp0());
5024 Register temp1 = ToRegister(lir->temp1());
5025
5026 Label vmCall, done;
5027 // Use indexed value as fast path if possible.
5028 masm.loadStringIndexValue(str, temp0, &vmCall);
5029 masm.convertInt32ToDouble(temp0, output);
5030 masm.jump(&done);
5031 {
5032 masm.bind(&vmCall);
5033
5034 // Reserve stack for holding the result value of the call.
5035 masm.reserveStack(sizeof(double));
5036 masm.moveStackPtrTo(temp0);
5037
5038 LiveRegisterSet volatileRegs = liveVolatileRegs(lir);
5039 volatileRegs.takeUnchecked(temp0);
5040 volatileRegs.takeUnchecked(temp1);
5041 masm.PushRegsInMask(volatileRegs);
5042
5043 using Fn = bool (*)(JSContext* cx, JSString* str, double* result);
5044 masm.setupAlignedABICall();
5045 masm.loadJSContext(temp1);
5046 masm.passABIArg(temp1);
5047 masm.passABIArg(str);
5048 masm.passABIArg(temp0);
5049 masm.callWithABI<Fn, StringToNumberPure>();
5050 masm.storeCallPointerResult(temp0);
5051
5052 masm.PopRegsInMask(volatileRegs);
5053
5054 Label ok;
5055 masm.branchIfTrueBool(temp0, &ok);
5056 {
5057 // OOM path, recovered by StringToNumberPure.
5058 //
5059 // Use addToStackPtr instead of freeStack as freeStack tracks stack height
5060 // flow-insensitively, and using it here would confuse the stack height
5061 // tracking.
5062 masm.addToStackPtr(Imm32(sizeof(double)));
5063 bailout(lir->snapshot());
5064 }
5065 masm.bind(&ok);
5066 masm.Pop(output);
5067 }
5068 masm.bind(&done);
5069 }
5070
5071 void CodeGenerator::visitGuardNoDenseElements(LGuardNoDenseElements* guard) {
5072 Register obj = ToRegister(guard->input());
5073 Register temp = ToRegister(guard->temp0());
5074
5075 // Load obj->elements.
5076 masm.loadPtr(Address(obj, NativeObject::offsetOfElements()), temp);
5077
5078 // Make sure there are no dense elements.
5079 Address initLength(temp, ObjectElements::offsetOfInitializedLength());
5080 bailoutCmp32(Assembler::NotEqual, initLength, Imm32(0), guard->snapshot());
5081 }
5082
5083 void CodeGenerator::visitBooleanToInt64(LBooleanToInt64* lir) {
5084 Register input = ToRegister(lir->input());
5085 Register64 output = ToOutRegister64(lir);
5086
5087 masm.move32To64ZeroExtend(input, output);
5088 }
5089
5090 void CodeGenerator::emitStringToInt64(LInstruction* lir, Register input,
5091 Register64 output) {
5092 Register temp = output.scratchReg();
5093
5094 saveLive(lir);
5095
5096 masm.reserveStack(sizeof(uint64_t));
5097 masm.moveStackPtrTo(temp);
5098 pushArg(temp);
5099 pushArg(input);
5100
5101 using Fn = bool (*)(JSContext*, HandleString, uint64_t*);
5102 callVM<Fn, DoStringToInt64>(lir);
5103
5104 masm.load64(Address(masm.getStackPointer(), 0), output);
5105 masm.freeStack(sizeof(uint64_t));
5106
5107 restoreLiveIgnore(lir, StoreValueTo(output).clobbered());
5108 }
5109
5110 void CodeGenerator::visitStringToInt64(LStringToInt64* lir) {
5111 Register input = ToRegister(lir->input());
5112 Register64 output = ToOutRegister64(lir);
5113
5114 emitStringToInt64(lir, input, output);
5115 }
5116
5117 void CodeGenerator::visitValueToInt64(LValueToInt64* lir) {
5118 ValueOperand input = ToValue(lir->input());
5119 Register temp = ToRegister(lir->temp0());
5120 Register64 output = ToOutRegister64(lir);
5121
5122 int checks = 3;
5123
5124 Label fail, done;
5125 // Jump to fail if this is the last check and we fail it,
5126 // otherwise to the next test.
5127 auto emitTestAndUnbox = [&](auto testAndUnbox) {
5128 MOZ_ASSERT(checks > 0);
5129
5130 checks--;
5131 Label notType;
5132 Label* target = checks ? &notType : &fail;
5133
5134 testAndUnbox(target);
5135
5136 if (checks) {
5137 masm.jump(&done);
5138 masm.bind(&notType);
5139 }
5140 };
5141
5142 Register tag = masm.extractTag(input, temp);
5143
5144 // BigInt.
5145 emitTestAndUnbox([&](Label* target) {
5146 masm.branchTestBigInt(Assembler::NotEqual, tag, target);
5147 masm.unboxBigInt(input, temp);
5148 masm.loadBigInt64(temp, output);
5149 });
5150
5151 // Boolean
5152 emitTestAndUnbox([&](Label* target) {
5153 masm.branchTestBoolean(Assembler::NotEqual, tag, target);
5154 masm.unboxBoolean(input, temp);
5155 masm.move32To64ZeroExtend(temp, output);
5156 });
5157
5158 // String
5159 emitTestAndUnbox([&](Label* target) {
5160 masm.branchTestString(Assembler::NotEqual, tag, target);
5161 masm.unboxString(input, temp);
5162 emitStringToInt64(lir, temp, output);
5163 });
5164
5165 MOZ_ASSERT(checks == 0);
5166
5167 bailoutFrom(&fail, lir->snapshot());
5168 masm.bind(&done);
5169 }
5170
5171 void CodeGenerator::visitTruncateBigIntToInt64(LTruncateBigIntToInt64* lir) {
5172 Register operand = ToRegister(lir->input());
5173 Register64 output = ToOutRegister64(lir);
5174
5175 masm.loadBigInt64(operand, output);
5176 }
5177
5178 OutOfLineCode* CodeGenerator::createBigIntOutOfLine(LInstruction* lir,
5179 Scalar::Type type,
5180 Register64 input,
5181 Register output) {
5182 #if JS_BITS_PER_WORD == 32
5183 using Fn = BigInt* (*)(JSContext*, uint32_t, uint32_t);
5184 auto args = ArgList(input.low, input.high);
5185 #else
5186 using Fn = BigInt* (*)(JSContext*, uint64_t);
5187 auto args = ArgList(input);
5188 #endif
5189
5190 if (type == Scalar::BigInt64) {
5191 return oolCallVM<Fn, jit::CreateBigIntFromInt64>(lir, args,
5192 StoreRegisterTo(output));
5193 }
5194 MOZ_ASSERT(type == Scalar::BigUint64);
5195 return oolCallVM<Fn, jit::CreateBigIntFromUint64>(lir, args,
5196 StoreRegisterTo(output));
5197 }
5198
5199 void CodeGenerator::emitCreateBigInt(LInstruction* lir, Scalar::Type type,
5200 Register64 input, Register output,
5201 Register maybeTemp,
5202 Register64 maybeTemp64) {
5203 OutOfLineCode* ool = createBigIntOutOfLine(lir, type, input, output);
5204
5205 if (maybeTemp != InvalidReg) {
5206 masm.newGCBigInt(output, maybeTemp, initialBigIntHeap(), ool->entry());
5207 } else {
5208 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
5209 regs.take(input);
5210 regs.take(output);
5211
5212 Register temp = regs.takeAny();
5213
5214 masm.push(temp);
5215
5216 Label fail, ok;
5217 masm.newGCBigInt(output, temp, initialBigIntHeap(), &fail);
5218 masm.pop(temp);
5219 masm.jump(&ok);
5220 masm.bind(&fail);
5221 masm.pop(temp);
5222 masm.jump(ool->entry());
5223 masm.bind(&ok);
5224 }
5225 masm.initializeBigInt64(type, output, input, maybeTemp64);
5226 masm.bind(ool->rejoin());
5227 }
5228
5229 void CodeGenerator::emitCallMegamorphicGetter(
5230 LInstruction* lir, ValueOperand accessorAndOutput, Register obj,
5231 Register calleeScratch, Register argcScratch, Label* nullGetter) {
5232 MOZ_ASSERT(calleeScratch == IonGenericCallCalleeReg);
5233 MOZ_ASSERT(argcScratch == IonGenericCallArgcReg);
5234
5235 masm.unboxNonDouble(accessorAndOutput, calleeScratch,
5236 JSVAL_TYPE_PRIVATE_GCTHING);
5237
5238 masm.loadPtr(Address(calleeScratch, GetterSetter::offsetOfGetter()),
5239 calleeScratch);
5240 masm.branchTestPtr(Assembler::Zero, calleeScratch, calleeScratch, nullGetter);
5241 masm.loadPtr(Address(calleeScratch, JSFunction::offsetOfJitInfoOrScript()),
5242 argcScratch);
5243
5244 if (JitStackValueAlignment > 1) {
5245 masm.reserveStack(sizeof(Value) * (JitStackValueAlignment - 1));
5246 }
5247 masm.pushValue(JSVAL_TYPE_OBJECT, obj);
5248
5249 masm.checkStackAlignment();
5250
5251 masm.move32(Imm32(0), argcScratch);
5252 ensureOsiSpace();
5253
5254 TrampolinePtr genericCallStub =
5255 gen->jitRuntime()->getIonGenericCallStub(IonGenericCallKind::Call);
5256 uint32_t callOffset = masm.callJit(genericCallStub);
5257 markSafepointAt(callOffset, lir);
5258
5259 masm.switchToRealm(gen->realm->realmPtr(), ReturnReg);
5260
5261 masm.moveValue(JSReturnOperand, accessorAndOutput);
5262
5263 masm.setFramePushed(frameSize());
5264 emitRestoreStackPointerFromFP();
5265 }
5266
5267 void CodeGenerator::visitInt64ToBigInt(LInt64ToBigInt* lir) {
5268 Register64 input = ToRegister64(lir->input());
5269 Register64 temp = ToRegister64(lir->temp0());
5270 Register output = ToRegister(lir->output());
5271
5272 emitCreateBigInt(lir, Scalar::BigInt64, input, output, temp.scratchReg(),
5273 temp);
5274 }
5275
5276 void CodeGenerator::visitUint64ToBigInt(LUint64ToBigInt* lir) {
5277 Register64 input = ToRegister64(lir->input());
5278 Register temp = ToRegister(lir->temp0());
5279 Register output = ToRegister(lir->output());
5280
5281 emitCreateBigInt(lir, Scalar::BigUint64, input, output, temp);
5282 }
5283
5284 void CodeGenerator::visitInt64ToIntPtr(LInt64ToIntPtr* lir) {
5285 Register64 input = ToRegister64(lir->input());
5286 #ifdef JS_64BIT
5287 MOZ_ASSERT(input.reg == ToRegister(lir->output()));
5288 #else
5289 Register output = ToRegister(lir->output());
5290 #endif
5291
5292 Label bail;
5293 if (lir->mir()->isSigned()) {
5294 masm.branchInt64NotInPtrRange(input, &bail);
5295 } else {
5296 masm.branchUInt64NotInPtrRange(input, &bail);
5297 }
5298 bailoutFrom(&bail, lir->snapshot());
5299
5300 #ifndef JS_64BIT
5301 masm.move64To32(input, output);
5302 #endif
5303 }
5304
5305 void CodeGenerator::visitIntPtrToInt64(LIntPtrToInt64* lir) {
5306 #ifdef JS_64BIT
5307 MOZ_CRASH("Not used on 64-bit platforms");
5308 #else
5309 Register input = ToRegister(lir->input());
5310 Register64 output = ToOutRegister64(lir);
5311
5312 masm.move32To64SignExtend(input, output);
5313 #endif
5314 }
5315
5316 void CodeGenerator::visitGuardValue(LGuardValue* lir) {
5317 ValueOperand input = ToValue(lir->input());
5318 Register nanTemp = ToTempRegisterOrInvalid(lir->temp0());
5319 Value expected = lir->mir()->expected();
5320 Label bail;
5321
5322 if (expected.isNaN()) {
5323 masm.branchTestNaNValue(Assembler::NotEqual, input, nanTemp, &bail);
5324 } else {
5325 MOZ_ASSERT(nanTemp == InvalidReg);
5326 masm.branchTestValue(Assembler::NotEqual, input, expected, &bail);
5327 }
5328
5329 bailoutFrom(&bail, lir->snapshot());
5330 }
5331
5332 void CodeGenerator::visitGuardNullOrUndefined(LGuardNullOrUndefined* lir) {
5333 ValueOperand input = ToValue(lir->input());
5334
5335 ScratchTagScope tag(masm, input);
5336 masm.splitTagForTest(input, tag);
5337
5338 Label done;
5339 masm.branchTestNull(Assembler::Equal, tag, &done);
5340
5341 Label bail;
5342 masm.branchTestUndefined(Assembler::NotEqual, tag, &bail);
5343 bailoutFrom(&bail, lir->snapshot());
5344
5345 masm.bind(&done);
5346 }
5347
5348 void CodeGenerator::visitGuardIsNotObject(LGuardIsNotObject* lir) {
5349 ValueOperand input = ToValue(lir->input());
5350
5351 Label bail;
5352 masm.branchTestObject(Assembler::Equal, input, &bail);
5353 bailoutFrom(&bail, lir->snapshot());
5354 }
5355
5356 void CodeGenerator::visitGuardFunctionFlags(LGuardFunctionFlags* lir) {
5357 Register function = ToRegister(lir->function());
5358
5359 Label bail;
5360 if (uint16_t flags = lir->mir()->expectedFlags()) {
5361 masm.branchTestFunctionFlags(function, flags, Assembler::Zero, &bail);
5362 }
5363 if (uint16_t flags = lir->mir()->unexpectedFlags()) {
5364 masm.branchTestFunctionFlags(function, flags, Assembler::NonZero, &bail);
5365 }
5366 bailoutFrom(&bail, lir->snapshot());
5367 }
5368
5369 void CodeGenerator::visitGuardFunctionIsNonBuiltinCtor(
5370 LGuardFunctionIsNonBuiltinCtor* lir) {
5371 Register function = ToRegister(lir->function());
5372 Register temp = ToRegister(lir->temp0());
5373
5374 Label bail;
5375 masm.branchIfNotFunctionIsNonBuiltinCtor(function, temp, &bail);
5376 bailoutFrom(&bail, lir->snapshot());
5377 }
5378
5379 void CodeGenerator::visitGuardFunctionKind(LGuardFunctionKind* lir) {
5380 Register function = ToRegister(lir->function());
5381 Register temp = ToRegister(lir->temp0());
5382
5383 Assembler::Condition cond =
5384 lir->mir()->bailOnEquality() ? Assembler::Equal : Assembler::NotEqual;
5385
5386 Label bail;
5387 masm.branchFunctionKind(cond, lir->mir()->expected(), function, temp, &bail);
5388 bailoutFrom(&bail, lir->snapshot());
5389 }
5390
5391 void CodeGenerator::visitGuardFunctionScript(LGuardFunctionScript* lir) {
5392 Register function = ToRegister(lir->function());
5393
5394 Address scriptAddr(function, JSFunction::offsetOfJitInfoOrScript());
5395 bailoutCmpPtr(Assembler::NotEqual, scriptAddr,
5396 ImmGCPtr(lir->mir()->expected()), lir->snapshot());
5397 }
5398
5399 // Out-of-line path to update the store buffer.
5400 class OutOfLineCallPostWriteBarrier : public OutOfLineCodeBase<CodeGenerator> {
5401 LInstruction* lir_;
5402 const LAllocation* object_;
5403
5404 public:
5405 OutOfLineCallPostWriteBarrier(LInstruction* lir, const LAllocation* object)
5406 : lir_(lir), object_(object) {}
5407
5408 void accept(CodeGenerator* codegen) override {
5409 codegen->visitOutOfLineCallPostWriteBarrier(this);
5410 }
5411
5412 LInstruction* lir() const { return lir_; }
5413 const LAllocation* object() const { return object_; }
5414 };
5415
5416 static void EmitStoreBufferCheckForConstant(MacroAssembler& masm,
5417 const gc::TenuredCell* cell,
5418 AllocatableGeneralRegisterSet& regs,
5419 Label* exit, Label* callVM) {
5420 Register temp = regs.takeAny();
5421
5422 gc::Arena* arena = cell->arena();
5423
5424 Register cells = temp;
5425 masm.loadPtr(AbsoluteAddress(&arena->bufferedCells()), cells);
5426
5427 size_t index = gc::ArenaCellSet::getCellIndex(cell);
5428 size_t word;
5429 uint32_t mask;
5430 gc::ArenaCellSet::getWordIndexAndMask(index, &word, &mask);
5431 size_t offset = gc::ArenaCellSet::offsetOfBits() + word * sizeof(uint32_t);
5432
5433 masm.branchTest32(Assembler::NonZero, Address(cells, offset), Imm32(mask),
5434 exit);
5435
5436 // Check whether this is the sentinel set and if so call the VM to allocate
5437 // one for this arena.
5438 masm.branchPtr(Assembler::Equal,
5439 Address(cells, gc::ArenaCellSet::offsetOfArena()),
5440 ImmPtr(nullptr), callVM);
5441
5442 // Add the cell to the set.
5443 masm.or32(Imm32(mask), Address(cells, offset));
5444 masm.jump(exit);
5445
5446 regs.add(temp);
5447 }
5448
5449 static void EmitPostWriteBarrier(MacroAssembler& masm, CompileRuntime* runtime,
5450 Register objreg, JSObject* maybeConstant,
5451 bool isGlobal,
5452 AllocatableGeneralRegisterSet& regs) {
5453 MOZ_ASSERT_IF(isGlobal, maybeConstant);
5454
5455 Label callVM;
5456 Label exit;
5457
5458 Register temp = regs.takeAny();
5459
5460 // We already have a fast path to check whether a global is in the store
5461 // buffer.
5462 if (!isGlobal) {
5463 if (maybeConstant) {
5464 // Check store buffer bitmap directly for known object.
5465 EmitStoreBufferCheckForConstant(masm, &maybeConstant->asTenured(), regs,
5466 &exit, &callVM);
5467 } else {
5468 // Check one element cache to avoid VM call.
5469 masm.branchPtr(Assembler::Equal,
5470 AbsoluteAddress(runtime->addressOfLastBufferedWholeCell()),
5471 objreg, &exit);
5472 }
5473 }
5474
5475 // Call into the VM to barrier the write.
5476 masm.bind(&callVM);
5477
5478 Register runtimereg = temp;
5479 masm.mov(ImmPtr(runtime), runtimereg);
5480
5481 masm.setupAlignedABICall();
5482 masm.passABIArg(runtimereg);
5483 masm.passABIArg(objreg);
5484 if (isGlobal) {
5485 using Fn = void (*)(JSRuntime* rt, GlobalObject* obj);
5486 masm.callWithABI<Fn, PostGlobalWriteBarrier>();
5487 } else {
5488 using Fn = void (*)(JSRuntime* rt, js::gc::Cell* obj);
5489 masm.callWithABI<Fn, PostWriteBarrier>();
5490 }
5491
5492 masm.bind(&exit);
5493 }
5494
5495 void CodeGenerator::emitPostWriteBarrier(const LAllocation* obj) {
5496 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::Volatile());
5497
5498 Register objreg;
5499 JSObject* object = nullptr;
5500 bool isGlobal = false;
5501 if (obj->isConstant()) {
5502 object = &obj->toConstant()->toObject();
5503 isGlobal = isGlobalObject(object);
5504 objreg = regs.takeAny();
5505 masm.movePtr(ImmGCPtr(object), objreg);
5506 } else {
5507 objreg = ToRegister(obj);
5508 regs.takeUnchecked(objreg);
5509 }
5510
5511 EmitPostWriteBarrier(masm, gen->runtime, objreg, object, isGlobal, regs);
5512 }
5513
5514 // Returns true if `def` might be allocated in the nursery.
5515 static bool ValueNeedsPostBarrier(MDefinition* def) {
5516 if (def->isBox()) {
5517 def = def->toBox()->input();
5518 }
5519 if (def->type() == MIRType::Value) {
5520 return true;
5521 }
5522 return NeedsPostBarrier(def->type());
5523 }
5524
5525 void CodeGenerator::emitElementPostWriteBarrier(
5526 MInstruction* mir, const LiveRegisterSet& liveVolatileRegs, Register obj,
5527 const LAllocation* index, Register scratch, const ConstantOrRegister& val,
5528 int32_t indexDiff) {
5529 if (val.constant()) {
5530 MOZ_ASSERT_IF(val.value().isGCThing(),
5531 !IsInsideNursery(val.value().toGCThing()));
5532 return;
5533 }
5534
5535 TypedOrValueRegister reg = val.reg();
5536 if (reg.hasTyped() && !NeedsPostBarrier(reg.type())) {
5537 return;
5538 }
5539
5540 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
5541 masm.PushRegsInMask(liveVolatileRegs);
5542
5543 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::Volatile());
5544 regs.takeUnchecked(obj);
5545 regs.takeUnchecked(scratch);
5546
5547 Register indexReg;
5548 if (index->isConstant()) {
5549 indexReg = regs.takeAny();
5550 masm.move32(Imm32(ToInt32(index) + indexDiff), indexReg);
5551 } else {
5552 indexReg = ToRegister(index);
5553 regs.takeUnchecked(indexReg);
5554 if (indexDiff != 0) {
5555 masm.add32(Imm32(indexDiff), indexReg);
5556 }
5557 }
5558
5559 masm.setupUnalignedABICall(scratch);
5560 masm.movePtr(ImmPtr(gen->runtime), scratch);
5561 masm.passABIArg(scratch);
5562 masm.passABIArg(obj);
5563 masm.passABIArg(indexReg);
5564 using Fn = void (*)(JSRuntime* rt, JSObject* obj, int32_t index);
5565 masm.callWithABI<Fn, PostWriteElementBarrier>();
5566
5567 // We don't need a sub32 here because indexReg must be in liveVolatileRegs
5568 // if indexDiff is not zero, so it will be restored below.
5569 MOZ_ASSERT_IF(indexDiff != 0, liveVolatileRegs.has(indexReg));
5570
5571 masm.PopRegsInMask(liveVolatileRegs);
5572
5573 masm.jump(ool.rejoin());
5574 });
5575 addOutOfLineCode(ool, mir);
5576
5577 masm.branchPtrInNurseryChunk(Assembler::Equal, obj, scratch, ool->rejoin());
5578
5579 if (reg.hasValue()) {
5580 masm.branchValueIsNurseryCell(Assembler::Equal, reg.valueReg(), scratch,
5581 ool->entry());
5582 } else {
5583 masm.branchPtrInNurseryChunk(Assembler::Equal, reg.typedReg().gpr(),
5584 scratch, ool->entry());
5585 }
5586
5587 masm.bind(ool->rejoin());
5588 }
5589
5590 void CodeGenerator::emitPostWriteBarrier(Register objreg) {
5591 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::Volatile());
5592 regs.takeUnchecked(objreg);
5593 EmitPostWriteBarrier(masm, gen->runtime, objreg, nullptr, false, regs);
5594 }
5595
5596 void CodeGenerator::visitOutOfLineCallPostWriteBarrier(
5597 OutOfLineCallPostWriteBarrier* ool) {
5598 saveLiveVolatile(ool->lir());
5599 const LAllocation* obj = ool->object();
5600 emitPostWriteBarrier(obj);
5601 restoreLiveVolatile(ool->lir());
5602
5603 masm.jump(ool->rejoin());
5604 }
5605
5606 void CodeGenerator::maybeEmitGlobalBarrierCheck(const LAllocation* maybeGlobal,
5607 OutOfLineCode* ool) {
5608 // Check whether an object is a global that we have already barriered before
5609 // calling into the VM.
5610 //
5611 // We only check for the script's global, not other globals within the same
5612 // compartment, because we bake in a pointer to realm->globalWriteBarriered
5613 // and doing that would be invalid for other realms because they could be
5614 // collected before the Ion code is discarded.
5615
5616 if (!maybeGlobal->isConstant()) {
5617 return;
5618 }
5619
5620 JSObject* obj = &maybeGlobal->toConstant()->toObject();
5621 if (gen->realm->maybeGlobal() != obj) {
5622 return;
5623 }
5624
5625 const uint32_t* addr = gen->realm->addressOfGlobalWriteBarriered();
5626 masm.branch32(Assembler::NotEqual, AbsoluteAddress(addr), Imm32(0),
5627 ool->rejoin());
5628 }
5629
5630 template <class LPostBarrierType, MIRType nurseryType>
5631 void CodeGenerator::visitPostWriteBarrierCommon(LPostBarrierType* lir,
5632 OutOfLineCode* ool) {
5633 static_assert(NeedsPostBarrier(nurseryType));
5634
5635 addOutOfLineCode(ool, lir->mir());
5636
5637 Register temp = ToTempRegisterOrInvalid(lir->temp0());
5638
5639 if (lir->object()->isConstant()) {
5640 // Constant nursery objects cannot appear here, see
5641 // LIRGenerator::visitPostWriteElementBarrier.
5642 MOZ_ASSERT(!IsInsideNursery(&lir->object()->toConstant()->toObject()));
5643 } else {
5644 masm.branchPtrInNurseryChunk(Assembler::Equal, ToRegister(lir->object()),
5645 temp, ool->rejoin());
5646 }
5647
5648 maybeEmitGlobalBarrierCheck(lir->object(), ool);
5649
5650 Register value = ToRegister(lir->value());
5651 if constexpr (nurseryType == MIRType::Object) {
5652 MOZ_ASSERT(lir->mir()->value()->type() == MIRType::Object);
5653 } else if constexpr (nurseryType == MIRType::String) {
5654 MOZ_ASSERT(lir->mir()->value()->type() == MIRType::String);
5655 } else {
5656 static_assert(nurseryType == MIRType::BigInt);
5657 MOZ_ASSERT(lir->mir()->value()->type() == MIRType::BigInt);
5658 }
5659 masm.branchPtrInNurseryChunk(Assembler::Equal, value, temp, ool->entry());
5660
5661 masm.bind(ool->rejoin());
5662 }
5663
5664 template <class LPostBarrierType>
5665 void CodeGenerator::visitPostWriteBarrierCommonV(LPostBarrierType* lir,
5666 OutOfLineCode* ool) {
5667 addOutOfLineCode(ool, lir->mir());
5668
5669 Register temp = ToTempRegisterOrInvalid(lir->temp0());
5670
5671 if (lir->object()->isConstant()) {
5672 // Constant nursery objects cannot appear here, see
5673 // LIRGenerator::visitPostWriteElementBarrier.
5674 MOZ_ASSERT(!IsInsideNursery(&lir->object()->toConstant()->toObject()));
5675 } else {
5676 masm.branchPtrInNurseryChunk(Assembler::Equal, ToRegister(lir->object()),
5677 temp, ool->rejoin());
5678 }
5679
5680 maybeEmitGlobalBarrierCheck(lir->object(), ool);
5681
5682 ValueOperand value = ToValue(lir->value());
5683 masm.branchValueIsNurseryCell(Assembler::Equal, value, temp, ool->entry());
5684
5685 masm.bind(ool->rejoin());
5686 }
5687
5688 void CodeGenerator::visitPostWriteBarrierO(LPostWriteBarrierO* lir) {
5689 auto ool = new (alloc()) OutOfLineCallPostWriteBarrier(lir, lir->object());
5690 visitPostWriteBarrierCommon<LPostWriteBarrierO, MIRType::Object>(lir, ool);
5691 }
5692
5693 void CodeGenerator::visitPostWriteBarrierS(LPostWriteBarrierS* lir) {
5694 auto ool = new (alloc()) OutOfLineCallPostWriteBarrier(lir, lir->object());
5695 visitPostWriteBarrierCommon<LPostWriteBarrierS, MIRType::String>(lir, ool);
5696 }
5697
5698 void CodeGenerator::visitPostWriteBarrierBI(LPostWriteBarrierBI* lir) {
5699 auto ool = new (alloc()) OutOfLineCallPostWriteBarrier(lir, lir->object());
5700 visitPostWriteBarrierCommon<LPostWriteBarrierBI, MIRType::BigInt>(lir, ool);
5701 }
5702
5703 void CodeGenerator::visitPostWriteBarrierV(LPostWriteBarrierV* lir) {
5704 auto ool = new (alloc()) OutOfLineCallPostWriteBarrier(lir, lir->object());
5705 visitPostWriteBarrierCommonV(lir, ool);
5706 }
5707
5708 // Out-of-line path to update the store buffer.
5709 class OutOfLineCallPostWriteElementBarrier
5710 : public OutOfLineCodeBase<CodeGenerator> {
5711 LInstruction* lir_;
5712 const LAllocation* object_;
5713 const LAllocation* index_;
5714
5715 public:
5716 OutOfLineCallPostWriteElementBarrier(LInstruction* lir,
5717 const LAllocation* object,
5718 const LAllocation* index)
5719 : lir_(lir), object_(object), index_(index) {}
5720
5721 void accept(CodeGenerator* codegen) override {
5722 codegen->visitOutOfLineCallPostWriteElementBarrier(this);
5723 }
5724
5725 LInstruction* lir() const { return lir_; }
5726
5727 const LAllocation* object() const { return object_; }
5728
5729 const LAllocation* index() const { return index_; }
5730 };
5731
5732 void CodeGenerator::visitOutOfLineCallPostWriteElementBarrier(
5733 OutOfLineCallPostWriteElementBarrier* ool) {
5734 saveLiveVolatile(ool->lir());
5735
5736 const LAllocation* obj = ool->object();
5737 const LAllocation* index = ool->index();
5738
5739 Register objreg = obj->isConstant() ? InvalidReg : ToRegister(obj);
5740 Register indexreg = ToRegister(index);
5741
5742 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::Volatile());
5743 regs.takeUnchecked(indexreg);
5744
5745 if (obj->isConstant()) {
5746 objreg = regs.takeAny();
5747 masm.movePtr(ImmGCPtr(&obj->toConstant()->toObject()), objreg);
5748 } else {
5749 regs.takeUnchecked(objreg);
5750 }
5751
5752 Register runtimereg = regs.takeAny();
5753 using Fn = void (*)(JSRuntime* rt, JSObject* obj, int32_t index);
5754 masm.setupAlignedABICall();
5755 masm.mov(ImmPtr(gen->runtime), runtimereg);
5756 masm.passABIArg(runtimereg);
5757 masm.passABIArg(objreg);
5758 masm.passABIArg(indexreg);
5759 masm.callWithABI<Fn, PostWriteElementBarrier>();
5760
5761 restoreLiveVolatile(ool->lir());
5762
5763 masm.jump(ool->rejoin());
5764 }
5765
5766 void CodeGenerator::visitPostWriteElementBarrierO(
5767 LPostWriteElementBarrierO* lir) {
5768 auto ool = new (alloc())
5769 OutOfLineCallPostWriteElementBarrier(lir, lir->object(), lir->index());
5770 visitPostWriteBarrierCommon<LPostWriteElementBarrierO, MIRType::Object>(lir,
5771 ool);
5772 }
5773
5774 void CodeGenerator::visitPostWriteElementBarrierS(
5775 LPostWriteElementBarrierS* lir) {
5776 auto ool = new (alloc())
5777 OutOfLineCallPostWriteElementBarrier(lir, lir->object(), lir->index());
5778 visitPostWriteBarrierCommon<LPostWriteElementBarrierS, MIRType::String>(lir,
5779 ool);
5780 }
5781
5782 void CodeGenerator::visitPostWriteElementBarrierBI(
5783 LPostWriteElementBarrierBI* lir) {
5784 auto ool = new (alloc())
5785 OutOfLineCallPostWriteElementBarrier(lir, lir->object(), lir->index());
5786 visitPostWriteBarrierCommon<LPostWriteElementBarrierBI, MIRType::BigInt>(lir,
5787 ool);
5788 }
5789
5790 void CodeGenerator::visitPostWriteElementBarrierV(
5791 LPostWriteElementBarrierV* lir) {
5792 auto ool = new (alloc())
5793 OutOfLineCallPostWriteElementBarrier(lir, lir->object(), lir->index());
5794 visitPostWriteBarrierCommonV(lir, ool);
5795 }
5796
5797 void CodeGenerator::visitAssertCanElidePostWriteBarrier(
5798 LAssertCanElidePostWriteBarrier* lir) {
5799 Register object = ToRegister(lir->object());
5800 ValueOperand value = ToValue(lir->value());
5801 Register temp = ToRegister(lir->temp0());
5802
5803 Label ok;
5804 masm.branchPtrInNurseryChunk(Assembler::Equal, object, temp, &ok);
5805 masm.branchValueIsNurseryCell(Assembler::NotEqual, value, temp, &ok);
5806
5807 masm.assumeUnreachable("Unexpected missing post write barrier");
5808
5809 masm.bind(&ok);
5810 }
5811
5812 template <typename LCallIns>
5813 void CodeGenerator::emitCallNative(LCallIns* call, JSNative native,
5814 Register argContextReg, Register argUintNReg,
5815 Register argVpReg, Register tempReg,
5816 uint32_t unusedStack) {
5817 masm.checkStackAlignment();
5818
5819 // Native functions have the signature:
5820 // bool (*)(JSContext*, unsigned, Value* vp)
5821 // Where vp[0] is space for an outparam, vp[1] is |this|, and vp[2] onward
5822 // are the function arguments.
5823
5824 // Allocate space for the outparam, moving the StackPointer to what will be
5825 // &vp[1].
5826 masm.adjustStack(unusedStack);
5827
5828 // Push a Value containing the callee object: natives are allowed to access
5829 // their callee before setting the return value. The StackPointer is moved
5830 // to &vp[0].
5831 //
5832 // Also reserves the space for |NativeExitFrameLayout::{lo,hi}CalleeResult_|.
5833 if constexpr (std::is_same_v<LCallIns, LCallClassHook>) {
5834 Register calleeReg = ToRegister(call->getCallee());
5835 masm.Push(TypedOrValueRegister(MIRType::Object, AnyRegister(calleeReg)));
5836
5837 // Enter the callee realm.
5838 if (call->mir()->maybeCrossRealm()) {
5839 masm.switchToObjectRealm(calleeReg, tempReg);
5840 }
5841 } else {
5842 WrappedFunction* target = call->mir()->getSingleTarget();
5843 masm.Push(ObjectValue(*target->rawNativeJSFunction()));
5844
5845 // Enter the callee realm.
5846 if (call->mir()->maybeCrossRealm()) {
5847 masm.movePtr(ImmGCPtr(target->rawNativeJSFunction()), tempReg);
5848 masm.switchToObjectRealm(tempReg, tempReg);
5849 }
5850 }
5851
5852 // Preload arguments into registers.
5853 masm.loadJSContext(argContextReg);
5854 masm.moveStackPtrTo(argVpReg);
5855
5856 // Initialize |NativeExitFrameLayout::argc_|.
5857 masm.Push(argUintNReg);
5858
5859 // Construct native exit frame.
5860 //
5861 // |buildFakeExitFrame| initializes |NativeExitFrameLayout::exit_| and
5862 // |enterFakeExitFrameForNative| initializes |NativeExitFrameLayout::footer_|.
5863 //
5864 // The NativeExitFrameLayout is now fully initialized.
5865 uint32_t safepointOffset = masm.buildFakeExitFrame(tempReg);
5866 masm.enterFakeExitFrameForNative(argContextReg, tempReg,
5867 call->mir()->isConstructing());
5868
5869 markSafepointAt(safepointOffset, call);
5870
5871 // Construct and execute call.
5872 masm.setupAlignedABICall();
5873 masm.passABIArg(argContextReg);
5874 masm.passABIArg(argUintNReg);
5875 masm.passABIArg(argVpReg);
5876
5877 ensureOsiSpace();
5878 // If we're using a simulator build, `native` will already point to the
5879 // simulator's call-redirection code for LCallClassHook. Load the address in
5880 // a register first so that we don't try to redirect it a second time.
5881 bool emittedCall = false;
5882 #ifdef JS_SIMULATOR
5883 if constexpr (std::is_same_v<LCallIns, LCallClassHook>) {
5884 masm.movePtr(ImmPtr(native), tempReg);
5885 masm.callWithABI(tempReg);
5886 emittedCall = true;
5887 }
5888 #endif
5889 if (!emittedCall) {
5890 masm.callWithABI(DynamicFunction<JSNative>(native), ABIType::General,
5891 CheckUnsafeCallWithABI::DontCheckHasExitFrame);
5892 }
5893
5894 // Test for failure.
5895 masm.branchIfFalseBool(ReturnReg, masm.failureLabel());
5896
5897 // Exit the callee realm.
5898 if (call->mir()->maybeCrossRealm()) {
5899 masm.switchToRealm(gen->realm->realmPtr(), ReturnReg);
5900 }
5901
5902 // Load the outparam vp[0] into output register(s).
5903 masm.loadValue(
5904 Address(masm.getStackPointer(), NativeExitFrameLayout::offsetOfResult()),
5905 JSReturnOperand);
5906
5907 // Until C++ code is instrumented against Spectre, prevent speculative
5908 // execution from returning any private data.
5909 if (JitOptions.spectreJitToCxxCalls && !call->mir()->ignoresReturnValue() &&
5910 call->mir()->hasLiveDefUses()) {
5911 masm.speculationBarrier();
5912 }
5913
5914 #ifdef DEBUG
5915 // Native constructors are guaranteed to return an Object value.
5916 if (call->mir()->isConstructing()) {
5917 Label notPrimitive;
5918 masm.branchTestPrimitive(Assembler::NotEqual, JSReturnOperand,
5919 &notPrimitive);
5920 masm.assumeUnreachable("native constructors don't return primitives");
5921 masm.bind(&notPrimitive);
5922 }
5923 #endif
5924 }
5925
5926 template <typename LCallIns>
5927 void CodeGenerator::emitCallNative(LCallIns* call, JSNative native) {
5928 uint32_t unusedStack =
5929 UnusedStackBytesForCall(call->mir()->paddedNumStackArgs());
5930
5931 // Registers used for callWithABI() argument-passing.
5932 const Register argContextReg = ToRegister(call->getArgContextReg());
5933 const Register argUintNReg = ToRegister(call->getArgUintNReg());
5934 const Register argVpReg = ToRegister(call->getArgVpReg());
5935
5936 // Misc. temporary registers.
5937 const Register tempReg = ToRegister(call->getTempReg());
5938
5939 DebugOnly<uint32_t> initialStack = masm.framePushed();
5940
5941 // Initialize the argc register.
5942 masm.move32(Imm32(call->mir()->numActualArgs()), argUintNReg);
5943
5944 // Create the exit frame and call the native.
5945 emitCallNative(call, native, argContextReg, argUintNReg, argVpReg, tempReg,
5946 unusedStack);
5947
5948 // The next instruction is removing the footer of the exit frame, so there
5949 // is no need for leaveFakeExitFrame.
5950
5951 // Move the StackPointer back to its original location, unwinding the native
5952 // exit frame.
5953 masm.adjustStack(NativeExitFrameLayout::Size() - unusedStack);
5954 MOZ_ASSERT(masm.framePushed() == initialStack);
5955 }
5956
5957 void CodeGenerator::visitCallNative(LCallNative* call) {
5958 WrappedFunction* target = call->getSingleTarget();
5959 MOZ_ASSERT(target);
5960 MOZ_ASSERT(target->isNativeWithoutJitEntry());
5961
5962 JSNative native = target->native();
5963 if (call->ignoresReturnValue() && target->hasJitInfo()) {
5964 const JSJitInfo* jitInfo = target->jitInfo();
5965 if (jitInfo->type() == JSJitInfo::IgnoresReturnValueNative) {
5966 native = jitInfo->ignoresReturnValueMethod;
5967 }
5968 }
5969 emitCallNative(call, native);
5970 }
5971
5972 void CodeGenerator::visitCallClassHook(LCallClassHook* call) {
5973 emitCallNative(call, call->mir()->target());
5974 }
5975
5976 static void LoadDOMPrivate(MacroAssembler& masm, Register obj, Register priv,
5977 DOMObjectKind kind) {
5978 // Load the value in DOM_OBJECT_SLOT for a native or proxy DOM object. This
5979 // will be in the first slot but may be fixed or non-fixed.
5980 MOZ_ASSERT(obj != priv);
5981
5982 switch (kind) {
5983 case DOMObjectKind::Native:
5984 // If it's a native object, the value must be in a fixed slot.
5985 // See CanAttachDOMCall in CacheIR.cpp.
5986 masm.debugAssertObjHasFixedSlots(obj, priv);
5987 masm.loadPrivate(Address(obj, NativeObject::getFixedSlotOffset(0)), priv);
5988 break;
5989 case DOMObjectKind::Proxy: {
5990 #ifdef DEBUG
5991 // Sanity check: it must be a DOM proxy.
5992 Label isDOMProxy;
5993 masm.branchTestProxyHandlerFamily(
5994 Assembler::Equal, obj, priv, GetDOMProxyHandlerFamily(), &isDOMProxy);
5995 masm.assumeUnreachable("Expected a DOM proxy");
5996 masm.bind(&isDOMProxy);
5997 #endif
5998 masm.loadPtr(Address(obj, ProxyObject::offsetOfReservedSlots()), priv);
5999 masm.loadPrivate(
6000 Address(priv, js::detail::ProxyReservedSlots::offsetOfSlot(0)), priv);
6001 break;
6002 }
6003 }
6004 }
6005
6006 void CodeGenerator::visitCallDOMNative(LCallDOMNative* call) {
6007 WrappedFunction* target = call->getSingleTarget();
6008 MOZ_ASSERT(target);
6009 MOZ_ASSERT(target->isNativeWithoutJitEntry());
6010 MOZ_ASSERT(target->hasJitInfo());
6011 MOZ_ASSERT(call->mir()->isCallDOMNative());
6012
6013 int unusedStack = UnusedStackBytesForCall(call->mir()->paddedNumStackArgs());
6014
6015 // Registers used for callWithABI() argument-passing.
6016 const Register argJSContext = ToRegister(call->getArgJSContext());
6017 const Register argObj = ToRegister(call->getArgObj());
6018 const Register argPrivate = ToRegister(call->getArgPrivate());
6019 const Register argArgs = ToRegister(call->getArgArgs());
6020
6021 DebugOnly<uint32_t> initialStack = masm.framePushed();
6022
6023 masm.checkStackAlignment();
6024
6025 // DOM methods have the signature:
6026 // bool (*)(JSContext*, HandleObject, void* private, const
6027 // JSJitMethodCallArgs& args)
6028 // Where args is initialized from an argc and a vp, vp[0] is space for an
6029 // outparam and the callee, vp[1] is |this|, and vp[2] onward are the
6030 // function arguments. Note that args stores the argv, not the vp, and
6031 // argv == vp + 2.
6032
6033 // Nestle the stack up against the pushed arguments, leaving StackPointer at
6034 // &vp[1]
6035 masm.adjustStack(unusedStack);
6036 // argObj is filled with the extracted object, then returned.
6037 Register obj = masm.extractObject(Address(masm.getStackPointer(), 0), argObj);
6038 MOZ_ASSERT(obj == argObj);
6039
6040 // Push a Value containing the callee object: natives are allowed to access
6041 // their callee before setting the return value. After this the StackPointer
6042 // points to &vp[0].
6043 masm.Push(ObjectValue(*target->rawNativeJSFunction()));
6044
6045 // Now compute the argv value. Since StackPointer is pointing to &vp[0] and
6046 // argv is &vp[2] we just need to add 2*sizeof(Value) to the current
6047 // StackPointer.
6048 static_assert(JSJitMethodCallArgsTraits::offsetOfArgv == 0);
6049 static_assert(JSJitMethodCallArgsTraits::offsetOfArgc ==
6050 IonDOMMethodExitFrameLayoutTraits::offsetOfArgcFromArgv);
6051 masm.computeEffectiveAddress(
6052 Address(masm.getStackPointer(), 2 * sizeof(Value)), argArgs);
6053
6054 LoadDOMPrivate(masm, obj, argPrivate,
6055 static_cast<MCallDOMNative*>(call->mir())->objectKind());
6056
6057 // Push argc from the call instruction into what will become the IonExitFrame
6058 masm.Push(Imm32(call->numActualArgs()));
6059
6060 // Push our argv onto the stack
6061 masm.Push(argArgs);
6062 // And store our JSJitMethodCallArgs* in argArgs.
6063 masm.moveStackPtrTo(argArgs);
6064
6065 // Push |this| object for passing HandleObject. We push after argc to
6066 // maintain the same sp-relative location of the object pointer with other
6067 // DOMExitFrames.
6068 masm.Push(argObj);
6069 masm.moveStackPtrTo(argObj);
6070
6071 if (call->mir()->maybeCrossRealm()) {
6072 // We use argJSContext as scratch register here.
6073 masm.movePtr(ImmGCPtr(target->rawNativeJSFunction()), argJSContext);
6074 masm.switchToObjectRealm(argJSContext, argJSContext);
6075 }
6076
6077 bool preTenureWrapperAllocation =
6078 call->mir()->to<MCallDOMNative>()->initialHeap() == gc::Heap::Tenured;
6079 if (preTenureWrapperAllocation) {
6080 auto ptr = ImmPtr(mirGen().realm->zone()->tenuringAllocSite());
6081 masm.storeLocalAllocSite(ptr, argJSContext);
6082 }
6083
6084 // Construct native exit frame.
6085 uint32_t safepointOffset = masm.buildFakeExitFrame(argJSContext);
6086
6087 masm.loadJSContext(argJSContext);
6088 masm.enterFakeExitFrame(argJSContext, argJSContext,
6089 ExitFrameType::IonDOMMethod);
6090
6091 markSafepointAt(safepointOffset, call);
6092
6093 // Construct and execute call.
6094 masm.setupAlignedABICall();
6095 masm.loadJSContext(argJSContext);
6096 masm.passABIArg(argJSContext);
6097 masm.passABIArg(argObj);
6098 masm.passABIArg(argPrivate);
6099 masm.passABIArg(argArgs);
6100 ensureOsiSpace();
6101 masm.callWithABI(DynamicFunction<JSJitMethodOp>(target->jitInfo()->method),
6102 ABIType::General,
6103 CheckUnsafeCallWithABI::DontCheckHasExitFrame);
6104
6105 if (target->jitInfo()->isInfallible) {
6106 masm.loadValue(Address(masm.getStackPointer(),
6107 IonDOMMethodExitFrameLayout::offsetOfResult()),
6108 JSReturnOperand);
6109 } else {
6110 // Test for failure.
6111 masm.branchIfFalseBool(ReturnReg, masm.exceptionLabel());
6112
6113 // Load the outparam vp[0] into output register(s).
6114 masm.loadValue(Address(masm.getStackPointer(),
6115 IonDOMMethodExitFrameLayout::offsetOfResult()),
6116 JSReturnOperand);
6117 }
6118
6119 static_assert(!JSReturnOperand.aliases(ReturnReg),
6120 "Clobbering ReturnReg should not affect the return value");
6121
6122 // Switch back to the current realm if needed. Note: if the DOM method threw
6123 // an exception, the exception handler will do this.
6124 if (call->mir()->maybeCrossRealm()) {
6125 masm.switchToRealm(gen->realm->realmPtr(), ReturnReg);
6126 }
6127
6128 // Wipe out the preTenuring bit from the local alloc site
6129 // On exception we handle this in C++
6130 if (preTenureWrapperAllocation) {
6131 masm.storeLocalAllocSite(ImmPtr(nullptr), ReturnReg);
6132 }
6133
6134 // Until C++ code is instrumented against Spectre, prevent speculative
6135 // execution from returning any private data.
6136 if (JitOptions.spectreJitToCxxCalls && call->mir()->hasLiveDefUses()) {
6137 masm.speculationBarrier();
6138 }
6139
6140 // The next instruction is removing the footer of the exit frame, so there
6141 // is no need for leaveFakeExitFrame.
6142
6143 // Move the StackPointer back to its original location, unwinding the native
6144 // exit frame.
6145 masm.adjustStack(IonDOMMethodExitFrameLayout::Size() - unusedStack);
6146 MOZ_ASSERT(masm.framePushed() == initialStack);
6147 }
6148
6149 void CodeGenerator::visitCallGetIntrinsicValue(LCallGetIntrinsicValue* lir) {
6150 pushArg(ImmGCPtr(lir->mir()->name()));
6151
6152 using Fn = bool (*)(JSContext* cx, Handle<PropertyName*>, MutableHandleValue);
6153 callVM<Fn, GetIntrinsicValue>(lir);
6154 }
6155
6156 void CodeGenerator::emitCallInvokeFunction(
6157 LInstruction* call, Register calleereg, bool constructing,
6158 bool ignoresReturnValue, uint32_t argc, uint32_t unusedStack) {
6159 // Nestle %esp up to the argument vector.
6160 // Each path must account for framePushed_ separately, for callVM to be valid.
6161 masm.freeStack(unusedStack);
6162
6163 pushArg(masm.getStackPointer()); // argv.
6164 pushArg(Imm32(argc)); // argc.
6165 pushArg(Imm32(ignoresReturnValue));
6166 pushArg(Imm32(constructing)); // constructing.
6167 pushArg(calleereg); // JSFunction*.
6168
6169 using Fn = bool (*)(JSContext*, HandleObject, bool, bool, uint32_t, Value*,
6170 MutableHandleValue);
6171 callVM<Fn, jit::InvokeFunction>(call);
6172
6173 // Un-nestle %esp from the argument vector. No prefix was pushed.
6174 masm.reserveStack(unusedStack);
6175 }
6176
6177 void CodeGenerator::visitCallGeneric(LCallGeneric* call) {
6178 // The callee is passed straight through to the trampoline.
6179 MOZ_ASSERT(ToRegister(call->getCallee()) == IonGenericCallCalleeReg);
6180
6181 Register argcReg = ToRegister(call->getArgc());
6182 uint32_t unusedStack =
6183 UnusedStackBytesForCall(call->mir()->paddedNumStackArgs());
6184
6185 // Known-target case is handled by LCallKnown.
6186 MOZ_ASSERT(!call->hasSingleTarget());
6187
6188 masm.checkStackAlignment();
6189
6190 masm.move32(Imm32(call->numActualArgs()), argcReg);
6191
6192 // Nestle the StackPointer up to the argument vector.
6193 masm.freeStack(unusedStack);
6194 ensureOsiSpace();
6195
6196 auto kind = call->mir()->isConstructing() ? IonGenericCallKind::Construct
6197 : IonGenericCallKind::Call;
6198
6199 TrampolinePtr genericCallStub =
6200 gen->jitRuntime()->getIonGenericCallStub(kind);
6201 uint32_t callOffset = masm.callJit(genericCallStub);
6202 markSafepointAt(callOffset, call);
6203
6204 if (call->mir()->maybeCrossRealm()) {
6205 static_assert(!JSReturnOperand.aliases(ReturnReg),
6206 "ReturnReg available as scratch after scripted calls");
6207 masm.switchToRealm(gen->realm->realmPtr(), ReturnReg);
6208 }
6209
6210 // Restore stack pointer.
6211 masm.setFramePushed(frameSize());
6212 emitRestoreStackPointerFromFP();
6213
6214 // If the return value of the constructing function is Primitive,
6215 // replace the return value with the Object from CreateThis.
6216 if (call->mir()->isConstructing()) {
6217 Label notPrimitive;
6218 masm.branchTestPrimitive(Assembler::NotEqual, JSReturnOperand,
6219 &notPrimitive);
6220 masm.loadValue(Address(masm.getStackPointer(), unusedStack),
6221 JSReturnOperand);
6222 #ifdef DEBUG
6223 masm.branchTestPrimitive(Assembler::NotEqual, JSReturnOperand,
6224 &notPrimitive);
6225 masm.assumeUnreachable("CreateThis creates an object");
6226 #endif
6227 masm.bind(&notPrimitive);
6228 }
6229 }
6230
6231 void JitRuntime::generateIonGenericCallArgumentsShift(
6232 MacroAssembler& masm, Register argc, Register curr, Register end,
6233 Register scratch, Label* done) {
6234 static_assert(sizeof(Value) == 8);
6235 // There are |argc| Values on the stack. Shift them all down by 8 bytes,
6236 // overwriting the first value.
6237
6238 // Initialize `curr` to the destination of the first copy, and `end` to the
6239 // final value of curr.
6240 masm.moveStackPtrTo(curr);
6241 masm.computeEffectiveAddress(BaseValueIndex(curr, argc), end);
6242
6243 Label loop;
6244 masm.bind(&loop);
6245 masm.branchPtr(Assembler::Equal, curr, end, done);
6246 masm.loadPtr(Address(curr, 8), scratch);
6247 masm.storePtr(scratch, Address(curr, 0));
6248 masm.addPtr(Imm32(sizeof(uintptr_t)), curr);
6249 masm.jump(&loop);
6250 }
6251
6252 void JitRuntime::generateIonGenericCallStub(MacroAssembler& masm,
6253 IonGenericCallKind kind) {
6254 AutoCreatedBy acb(masm, "JitRuntime::generateIonGenericCallStub");
6255 ionGenericCallStubOffset_[kind] = startTrampolineCode(masm);
6256
6257 // This code is tightly coupled with visitCallGeneric.
6258 //
6259 // Upon entry:
6260 // IonGenericCallCalleeReg contains a pointer to the callee object.
6261 // IonGenericCallArgcReg contains the number of actual args.
6262 // The arguments have been pushed onto the stack:
6263 // [newTarget] (iff isConstructing)
6264 // [argN]
6265 // ...
6266 // [arg1]
6267 // [arg0]
6268 // [this]
6269 // <return address> (if not JS_USE_LINK_REGISTER)
6270 //
6271 // This trampoline is responsible for entering the callee's realm,
6272 // massaging the stack into the right shape, and then performing a
6273 // tail call. We will return directly to the Ion code from the
6274 // callee.
6275 //
6276 // To do a tail call, we keep the return address in a register, even
6277 // on platforms that don't normally use a link register, and push it
6278 // just before jumping to the callee, after we are done setting up
6279 // the stack.
6280 //
6281 // The caller is responsible for switching back to the caller's
6282 // realm and cleaning up the stack.
6283
6284 Register calleeReg = IonGenericCallCalleeReg;
6285 Register argcReg = IonGenericCallArgcReg;
6286 Register scratch = IonGenericCallScratch;
6287 Register scratch2 = IonGenericCallScratch2;
6288
6289 #ifndef JS_USE_LINK_REGISTER
6290 Register returnAddrReg = IonGenericCallReturnAddrReg;
6291 masm.pop(returnAddrReg);
6292 #endif
6293
6294 #ifdef JS_CODEGEN_ARM
6295 // The default second scratch register on arm is lr, which we need
6296 // preserved for tail calls.
6297 AutoNonDefaultSecondScratchRegister andssr(masm, IonGenericSecondScratchReg);
6298 #endif
6299
6300 bool isConstructing = kind == IonGenericCallKind::Construct;
6301
6302 Label entry, notFunction, noJitEntry, vmCall;
6303 masm.bind(&entry);
6304
6305 // Guard that the callee is actually a function.
6306 masm.branchTestObjIsFunction(Assembler::NotEqual, calleeReg, scratch,
6307 calleeReg, &notFunction);
6308
6309 // Guard that the callee supports the [[Call]] or [[Construct]] operation.
6310 // If these tests fail, we will call into the VM to throw an exception.
6311 if (isConstructing) {
6312 masm.branchTestFunctionFlags(calleeReg, FunctionFlags::CONSTRUCTOR,
6313 Assembler::Zero, &vmCall);
6314 } else {
6315 masm.branchFunctionKind(Assembler::Equal, FunctionFlags::ClassConstructor,
6316 calleeReg, scratch, &vmCall);
6317 }
6318
6319 if (isConstructing) {
6320 // Use the slow path if CreateThis was unable to create the |this| object.
6321 Address thisAddr(masm.getStackPointer(), 0);
6322 masm.branchTestNull(Assembler::Equal, thisAddr, &vmCall);
6323 }
6324
6325 masm.switchToObjectRealm(calleeReg, scratch);
6326
6327 // Load jitCodeRaw for callee if it exists.
6328 masm.branchIfFunctionHasNoJitEntry(calleeReg, &noJitEntry);
6329
6330 // ****************************
6331 // * Functions with jit entry *
6332 // ****************************
6333 masm.loadJitCodeRaw(calleeReg, scratch2);
6334
6335 // Construct the JitFrameLayout.
6336 masm.PushCalleeToken(calleeReg, isConstructing);
6337 masm.PushFrameDescriptorForJitCall(FrameType::IonJS, argcReg, scratch);
6338 #ifndef JS_USE_LINK_REGISTER
6339 masm.push(returnAddrReg);
6340 #endif
6341
6342 // Check whether we need a rectifier frame.
6343 Label noRectifier;
6344 masm.loadFunctionArgCount(calleeReg, scratch);
6345 masm.branch32(Assembler::BelowOrEqual, scratch, argcReg, &noRectifier);
6346 {
6347 // Tail-call the arguments rectifier.
6348 // Because all trampolines are created at the same time,
6349 // we can't create a TrampolinePtr for the arguments rectifier,
6350 // because it hasn't been linked yet. We can, however, directly
6351 // encode its offset.
6352 Label rectifier;
6353 bindLabelToOffset(&rectifier, argumentsRectifierOffset_);
6354
6355 masm.jump(&rectifier);
6356 }
6357
6358 // Tail call the jit entry.
6359 masm.bind(&noRectifier);
6360 masm.jump(scratch2);
6361
6362 // ********************
6363 // * Native functions *
6364 // ********************
6365 masm.bind(&noJitEntry);
6366 if (!isConstructing) {
6367 generateIonGenericCallFunCall(masm, &entry, &vmCall);
6368 }
6369 generateIonGenericCallNativeFunction(masm, isConstructing);
6370
6371 // *******************
6372 // * Bound functions *
6373 // *******************
6374 // TODO: support class hooks?
6375 masm.bind(&notFunction);
6376 if (!isConstructing) {
6377 // TODO: support generic bound constructors?
6378 generateIonGenericCallBoundFunction(masm, &entry, &vmCall);
6379 }
6380
6381 // ********************
6382 // * Fallback VM call *
6383 // ********************
6384 masm.bind(&vmCall);
6385
6386 masm.push(masm.getStackPointer()); // argv
6387 masm.push(argcReg); // argc
6388 masm.push(Imm32(false)); // ignores return value
6389 masm.push(Imm32(isConstructing)); // constructing
6390 masm.push(calleeReg); // callee
6391
6392 using Fn = bool (*)(JSContext*, HandleObject, bool, bool, uint32_t, Value*,
6393 MutableHandleValue);
6394 VMFunctionId id = VMFunctionToId<Fn, jit::InvokeFunction>::id;
6395 uint32_t invokeFunctionOffset = functionWrapperOffsets_[size_t(id)];
6396 Label invokeFunctionVMEntry;
6397 bindLabelToOffset(&invokeFunctionVMEntry, invokeFunctionOffset);
6398
6399 masm.pushFrameDescriptor(FrameType::IonJS);
6400 #ifndef JS_USE_LINK_REGISTER
6401 masm.push(returnAddrReg);
6402 #endif
6403 masm.jump(&invokeFunctionVMEntry);
6404 }
6405
6406 void JitRuntime::generateIonGenericCallNativeFunction(MacroAssembler& masm,
6407 bool isConstructing) {
6408 Register calleeReg = IonGenericCallCalleeReg;
6409 Register argcReg = IonGenericCallArgcReg;
6410 Register scratch = IonGenericCallScratch;
6411 Register scratch2 = IonGenericCallScratch2;
6412 Register contextReg = IonGenericCallScratch3;
6413 #ifndef JS_USE_LINK_REGISTER
6414 Register returnAddrReg = IonGenericCallReturnAddrReg;
6415 #endif
6416
6417 // Push a value containing the callee, which will become argv[0].
6418 masm.pushValue(JSVAL_TYPE_OBJECT, calleeReg);
6419
6420 // Load the callee address into calleeReg.
6421 #ifdef JS_SIMULATOR
6422 masm.movePtr(ImmPtr(RedirectedCallAnyNative()), calleeReg);
6423 #else
6424 masm.loadPrivate(Address(calleeReg, JSFunction::offsetOfNativeOrEnv()),
6425 calleeReg);
6426 #endif
6427
6428 // Load argv into scratch2.
6429 masm.moveStackPtrTo(scratch2);
6430
6431 // Push argc.
6432 masm.push(argcReg);
6433
6434 masm.loadJSContext(contextReg);
6435
6436 // Construct native exit frame. Note that unlike other cases in this
6437 // trampoline, this code does not use a tail call.
6438 masm.pushFrameDescriptor(FrameType::IonJS);
6439 #ifdef JS_USE_LINK_REGISTER
6440 masm.pushReturnAddress();
6441 #else
6442 masm.push(returnAddrReg);
6443 #endif
6444
6445 masm.push(FramePointer);
6446 masm.moveStackPtrTo(FramePointer);
6447 masm.enterFakeExitFrameForNative(contextReg, scratch, isConstructing);
6448
6449 masm.setupUnalignedABICall(scratch);
6450 masm.passABIArg(contextReg); // cx
6451 masm.passABIArg(argcReg); // argc
6452 masm.passABIArg(scratch2); // argv
6453
6454 masm.callWithABI(calleeReg);
6455
6456 // Test for failure.
6457 masm.branchIfFalseBool(ReturnReg, masm.exceptionLabel());
6458
6459 masm.loadValue(
6460 Address(masm.getStackPointer(), NativeExitFrameLayout::offsetOfResult()),
6461 JSReturnOperand);
6462
6463 // Leave the exit frame.
6464 masm.moveToStackPtr(FramePointer);
6465 masm.pop(FramePointer);
6466
6467 // Return.
6468 masm.ret();
6469 }
6470
6471 void JitRuntime::generateIonGenericCallFunCall(MacroAssembler& masm,
6472 Label* entry, Label* vmCall) {
6473 Register calleeReg = IonGenericCallCalleeReg;
6474 Register argcReg = IonGenericCallArgcReg;
6475 Register scratch = IonGenericCallScratch;
6476 Register scratch2 = IonGenericCallScratch2;
6477 Register scratch3 = IonGenericCallScratch3;
6478
6479 Label notFunCall;
6480 masm.branchPtr(Assembler::NotEqual,
6481 Address(calleeReg, JSFunction::offsetOfNativeOrEnv()),
6482 ImmPtr(js::fun_call), &notFunCall);
6483
6484 // In general, we can implement fun_call by replacing calleeReg with
6485 // |this|, sliding all the other arguments down, and decrementing argc.
6486 //
6487 // *BEFORE* *AFTER*
6488 // [argN] argc = N+1 <padding>
6489 // ... [argN] argc = N
6490 // [arg1] ...
6491 // [arg0] [arg1] <- now arg0
6492 // [this] <- top of stack (aligned) [arg0] <- now this
6493 //
6494 // The only exception is when argc is already 0, in which case instead
6495 // of shifting arguments down we replace [this] with UndefinedValue():
6496 //
6497 // *BEFORE* *AFTER*
6498 // [this] argc = 0 [undef] argc = 0
6499 //
6500 // After making this transformation, we can jump back to the beginning
6501 // of this trampoline to handle the inner call.
6502
6503 // Guard that |this| is an object. If it is, replace calleeReg.
6504 masm.fallibleUnboxObject(Address(masm.getStackPointer(), 0), scratch, vmCall);
6505 masm.movePtr(scratch, calleeReg);
6506
6507 Label hasArgs;
6508 masm.branch32(Assembler::NotEqual, argcReg, Imm32(0), &hasArgs);
6509
6510 // No arguments. Replace |this| with |undefined| and start from the top.
6511 masm.storeValue(UndefinedValue(), Address(masm.getStackPointer(), 0));
6512 masm.jump(entry);
6513
6514 masm.bind(&hasArgs);
6515
6516 Label doneSliding;
6517 generateIonGenericCallArgumentsShift(masm, argcReg, scratch, scratch2,
6518 scratch3, &doneSliding);
6519 masm.bind(&doneSliding);
6520 masm.sub32(Imm32(1), argcReg);
6521
6522 masm.jump(entry);
6523
6524 masm.bind(&notFunCall);
6525 }
6526
6527 void JitRuntime::generateIonGenericCallBoundFunction(MacroAssembler& masm,
6528 Label* entry,
6529 Label* vmCall) {
6530 Register calleeReg = IonGenericCallCalleeReg;
6531 Register argcReg = IonGenericCallArgcReg;
6532 Register scratch = IonGenericCallScratch;
6533 Register scratch2 = IonGenericCallScratch2;
6534 Register scratch3 = IonGenericCallScratch3;
6535
6536 masm.branchTestObjClass(Assembler::NotEqual, calleeReg,
6537 &BoundFunctionObject::class_, scratch, calleeReg,
6538 vmCall);
6539
6540 Address targetSlot(calleeReg, BoundFunctionObject::offsetOfTargetSlot());
6541 Address flagsSlot(calleeReg, BoundFunctionObject::offsetOfFlagsSlot());
6542 Address thisSlot(calleeReg, BoundFunctionObject::offsetOfBoundThisSlot());
6543 Address firstInlineArgSlot(
6544 calleeReg, BoundFunctionObject::offsetOfFirstInlineBoundArg());
6545
6546 // Check that we won't be pushing too many arguments.
6547 masm.load32(flagsSlot, scratch);
6548 masm.rshift32(Imm32(BoundFunctionObject::NumBoundArgsShift), scratch);
6549 masm.add32(argcReg, scratch);
6550 masm.branch32(Assembler::Above, scratch, Imm32(JIT_ARGS_LENGTH_MAX), vmCall);
6551
6552 // The stack is currently correctly aligned for a jit call. We will
6553 // be updating the `this` value and potentially adding additional
6554 // arguments. On platforms with 16-byte alignment, if the number of
6555 // bound arguments is odd, we have to move the arguments that are
6556 // currently on the stack. For example, with one bound argument:
6557 //
6558 // *BEFORE* *AFTER*
6559 // [argN] <padding>
6560 // ... [argN] |
6561 // [arg1] ... | These arguments have been
6562 // [arg0] [arg1] | shifted down 8 bytes.
6563 // [this] <- top of stack (aligned) [arg0] v
6564 // [bound0] <- one bound argument (odd)
6565 // [boundThis] <- top of stack (aligned)
6566 //
6567 Label poppedThis;
6568 if (JitStackValueAlignment > 1) {
6569 Label alreadyAligned;
6570 masm.branchTest32(Assembler::Zero, flagsSlot,
6571 Imm32(1 << BoundFunctionObject::NumBoundArgsShift),
6572 &alreadyAligned);
6573
6574 // We have an odd number of bound arguments. Shift the existing arguments
6575 // down by 8 bytes.
6576 generateIonGenericCallArgumentsShift(masm, argcReg, scratch, scratch2,
6577 scratch3, &poppedThis);
6578 masm.bind(&alreadyAligned);
6579 }
6580
6581 // Pop the current `this`. It will be replaced with the bound `this`.
6582 masm.freeStack(sizeof(Value));
6583 masm.bind(&poppedThis);
6584
6585 // Load the number of bound arguments in scratch
6586 masm.load32(flagsSlot, scratch);
6587 masm.rshift32(Imm32(BoundFunctionObject::NumBoundArgsShift), scratch);
6588
6589 Label donePushingBoundArguments;
6590 masm.branch32(Assembler::Equal, scratch, Imm32(0),
6591 &donePushingBoundArguments);
6592
6593 // Update argc to include bound arguments.
6594 masm.add32(scratch, argcReg);
6595
6596 // Load &boundArgs[0] in scratch2.
6597 Label outOfLineBoundArguments, haveBoundArguments;
6598 masm.branch32(Assembler::Above, scratch,
6599 Imm32(BoundFunctionObject::MaxInlineBoundArgs),
6600 &outOfLineBoundArguments);
6601 masm.computeEffectiveAddress(firstInlineArgSlot, scratch2);
6602 masm.jump(&haveBoundArguments);
6603
6604 masm.bind(&outOfLineBoundArguments);
6605 masm.unboxObject(firstInlineArgSlot, scratch2);
6606 masm.loadPtr(Address(scratch2, NativeObject::offsetOfElements()), scratch2);
6607
6608 masm.bind(&haveBoundArguments);
6609
6610 // Load &boundArgs[numBoundArgs] in scratch.
6611 BaseObjectElementIndex lastBoundArg(scratch2, scratch);
6612 masm.computeEffectiveAddress(lastBoundArg, scratch);
6613
6614 // Push the bound arguments, starting with the last one.
6615 // Copying pre-decrements scratch until scratch2 is reached.
6616 Label boundArgumentsLoop;
6617 masm.bind(&boundArgumentsLoop);
6618 masm.subPtr(Imm32(sizeof(Value)), scratch);
6619 masm.pushValue(Address(scratch, 0));
6620 masm.branchPtr(Assembler::Above, scratch, scratch2, &boundArgumentsLoop);
6621 masm.bind(&donePushingBoundArguments);
6622
6623 // Push the bound `this`.
6624 masm.pushValue(thisSlot);
6625
6626 // Load the target in calleeReg.
6627 masm.unboxObject(targetSlot, calleeReg);
6628
6629 // At this point, all preconditions for entering the trampoline are met:
6630 // - calleeReg contains a pointer to the callee object
6631 // - argcReg contains the number of actual args (now including bound args)
6632 // - the arguments are on the stack with the correct alignment.
6633 // Instead of generating more code, we can jump back to the entry point
6634 // of the trampoline to call the bound target.
6635 masm.jump(entry);
6636 }
6637
6638 void CodeGenerator::visitCallKnown(LCallKnown* call) {
6639 Register calleereg = ToRegister(call->getFunction());
6640 Register objreg = ToRegister(call->getTempObject());
6641 uint32_t unusedStack =
6642 UnusedStackBytesForCall(call->mir()->paddedNumStackArgs());
6643 WrappedFunction* target = call->getSingleTarget();
6644
6645 // Native single targets (except Wasm and TrampolineNative functions) are
6646 // handled by LCallNative.
6647 MOZ_ASSERT(target->hasJitEntry());
6648
6649 // Missing arguments must have been explicitly appended by WarpBuilder.
6650 DebugOnly<unsigned> numNonArgsOnStack = 1 + call->isConstructing();
6651 MOZ_ASSERT(target->nargs() <=
6652 call->mir()->numStackArgs() - numNonArgsOnStack);
6653
6654 MOZ_ASSERT_IF(call->isConstructing(), target->isConstructor());
6655
6656 masm.checkStackAlignment();
6657
6658 if (target->isClassConstructor() && !call->isConstructing()) {
6659 emitCallInvokeFunction(call, calleereg, call->isConstructing(),
6660 call->ignoresReturnValue(), call->numActualArgs(),
6661 unusedStack);
6662 return;
6663 }
6664
6665 MOZ_ASSERT_IF(target->isClassConstructor(), call->isConstructing());
6666
6667 MOZ_ASSERT(!call->mir()->needsThisCheck());
6668
6669 if (call->mir()->maybeCrossRealm()) {
6670 masm.switchToObjectRealm(calleereg, objreg);
6671 }
6672
6673 masm.loadJitCodeRaw(calleereg, objreg);
6674
6675 // Nestle the StackPointer up to the argument vector.
6676 masm.freeStack(unusedStack);
6677
6678 // Construct the JitFrameLayout.
6679 masm.PushCalleeToken(calleereg, call->mir()->isConstructing());
6680 masm.PushFrameDescriptorForJitCall(FrameType::IonJS, call->numActualArgs());
6681
6682 // Finally call the function in objreg.
6683 ensureOsiSpace();
6684 uint32_t callOffset = masm.callJit(objreg);
6685 markSafepointAt(callOffset, call);
6686
6687 if (call->mir()->maybeCrossRealm()) {
6688 static_assert(!JSReturnOperand.aliases(ReturnReg),
6689 "ReturnReg available as scratch after scripted calls");
6690 masm.switchToRealm(gen->realm->realmPtr(), ReturnReg);
6691 }
6692
6693 // Restore stack pointer: pop JitFrameLayout fields still left on the stack
6694 // and undo the earlier |freeStack(unusedStack)|.
6695 int prefixGarbage =
6696 sizeof(JitFrameLayout) - JitFrameLayout::bytesPoppedAfterCall();
6697 masm.adjustStack(prefixGarbage - unusedStack);
6698
6699 // If the return value of the constructing function is Primitive,
6700 // replace the return value with the Object from CreateThis.
6701 if (call->mir()->isConstructing()) {
6702 Label notPrimitive;
6703 masm.branchTestPrimitive(Assembler::NotEqual, JSReturnOperand,
6704 &notPrimitive);
6705 masm.loadValue(Address(masm.getStackPointer(), unusedStack),
6706 JSReturnOperand);
6707 #ifdef DEBUG
6708 masm.branchTestPrimitive(Assembler::NotEqual, JSReturnOperand,
6709 &notPrimitive);
6710 masm.assumeUnreachable("CreateThis creates an object");
6711 #endif
6712 masm.bind(&notPrimitive);
6713 }
6714 }
6715
6716 template <typename T>
6717 void CodeGenerator::emitCallInvokeFunction(T* apply) {
6718 pushArg(masm.getStackPointer()); // argv.
6719 pushArg(ToRegister(apply->getArgc())); // argc.
6720 pushArg(Imm32(apply->mir()->ignoresReturnValue())); // ignoresReturnValue.
6721 pushArg(Imm32(apply->mir()->isConstructing())); // isConstructing.
6722 pushArg(ToRegister(apply->getFunction())); // JSFunction*.
6723
6724 using Fn = bool (*)(JSContext*, HandleObject, bool, bool, uint32_t, Value*,
6725 MutableHandleValue);
6726 callVM<Fn, jit::InvokeFunction>(apply);
6727 }
6728
6729 // Do not bailout after the execution of this function since the stack no longer
6730 // correspond to what is expected by the snapshots.
6731 void CodeGenerator::emitAllocateSpaceForApply(Register argcreg,
6732 Register scratch) {
6733 // Use scratch register to calculate stack space (including padding).
6734 masm.movePtr(argcreg, scratch);
6735
6736 // Align the JitFrameLayout on the JitStackAlignment.
6737 if (JitStackValueAlignment > 1) {
6738 MOZ_ASSERT(frameSize() % JitStackAlignment == 0,
6739 "Stack padding assumes that the frameSize is correct");
6740 MOZ_ASSERT(JitStackValueAlignment == 2);
6741 Label noPaddingNeeded;
6742 // If the number of arguments is odd, then we do not need any padding.
6743 //
6744 // Note: The |JitStackValueAlignment == 2| condition requires that the
6745 // overall number of values on the stack is even. When we have an odd number
6746 // of arguments, we don't need any padding, because the |thisValue| is
6747 // pushed after the arguments, so the overall number of values on the stack
6748 // is even.
6749 masm.branchTestPtr(Assembler::NonZero, argcreg, Imm32(1), &noPaddingNeeded);
6750 masm.addPtr(Imm32(1), scratch);
6751 masm.bind(&noPaddingNeeded);
6752 }
6753
6754 // Reserve space for copying the arguments.
6755 NativeObject::elementsSizeMustNotOverflow();
6756 masm.lshiftPtr(Imm32(ValueShift), scratch);
6757 masm.subFromStackPtr(scratch);
6758
6759 #ifdef DEBUG
6760 // Put a magic value in the space reserved for padding. Note, this code cannot
6761 // be merged with the previous test, as not all architectures can write below
6762 // their stack pointers.
6763 if (JitStackValueAlignment > 1) {
6764 MOZ_ASSERT(JitStackValueAlignment == 2);
6765 Label noPaddingNeeded;
6766 // If the number of arguments is odd, then we do not need any padding.
6767 masm.branchTestPtr(Assembler::NonZero, argcreg, Imm32(1), &noPaddingNeeded);
6768 BaseValueIndex dstPtr(masm.getStackPointer(), argcreg);
6769 masm.storeValue(MagicValue(JS_ARG_POISON), dstPtr);
6770 masm.bind(&noPaddingNeeded);
6771 }
6772 #endif
6773 }
6774
6775 // Do not bailout after the execution of this function since the stack no longer
6776 // correspond to what is expected by the snapshots.
6777 void CodeGenerator::emitAllocateSpaceForConstructAndPushNewTarget(
6778 Register argcreg, Register newTargetAndScratch) {
6779 // Align the JitFrameLayout on the JitStackAlignment. Contrary to
6780 // |emitAllocateSpaceForApply()|, we're always pushing a magic value, because
6781 // we can't write to |newTargetAndScratch| before |new.target| has been pushed
6782 // onto the stack.
6783 if (JitStackValueAlignment > 1) {
6784 MOZ_ASSERT(frameSize() % JitStackAlignment == 0,
6785 "Stack padding assumes that the frameSize is correct");
6786 MOZ_ASSERT(JitStackValueAlignment == 2);
6787
6788 Label noPaddingNeeded;
6789 // If the number of arguments is even, then we do not need any padding.
6790 //
6791 // Note: The |JitStackValueAlignment == 2| condition requires that the
6792 // overall number of values on the stack is even. When we have an even
6793 // number of arguments, we don't need any padding, because |new.target| is
6794 // is pushed before the arguments and |thisValue| is pushed after all
6795 // arguments, so the overall number of values on the stack is even.
6796 masm.branchTestPtr(Assembler::Zero, argcreg, Imm32(1), &noPaddingNeeded);
6797 masm.pushValue(MagicValue(JS_ARG_POISON));
6798 masm.bind(&noPaddingNeeded);
6799 }
6800
6801 // Push |new.target| after the padding value, but before any arguments.
6802 masm.pushValue(JSVAL_TYPE_OBJECT, newTargetAndScratch);
6803
6804 // Use newTargetAndScratch to calculate stack space (including padding).
6805 masm.movePtr(argcreg, newTargetAndScratch);
6806
6807 // Reserve space for copying the arguments.
6808 NativeObject::elementsSizeMustNotOverflow();
6809 masm.lshiftPtr(Imm32(ValueShift), newTargetAndScratch);
6810 masm.subFromStackPtr(newTargetAndScratch);
6811 }
6812
6813 // Destroys argvIndex and copyreg.
6814 void CodeGenerator::emitCopyValuesForApply(Register argvSrcBase,
6815 Register argvIndex, Register copyreg,
6816 size_t argvSrcOffset,
6817 size_t argvDstOffset) {
6818 Label loop;
6819 masm.bind(&loop);
6820
6821 // As argvIndex is off by 1, and we use the decBranchPtr instruction to loop
6822 // back, we have to substract the size of the word which are copied.
6823 BaseValueIndex srcPtr(argvSrcBase, argvIndex,
6824 int32_t(argvSrcOffset) - sizeof(void*));
6825 BaseValueIndex dstPtr(masm.getStackPointer(), argvIndex,
6826 int32_t(argvDstOffset) - sizeof(void*));
6827 masm.loadPtr(srcPtr, copyreg);
6828 masm.storePtr(copyreg, dstPtr);
6829
6830 // Handle 32 bits architectures.
6831 if (sizeof(Value) == 2 * sizeof(void*)) {
6832 BaseValueIndex srcPtrLow(argvSrcBase, argvIndex,
6833 int32_t(argvSrcOffset) - 2 * sizeof(void*));
6834 BaseValueIndex dstPtrLow(masm.getStackPointer(), argvIndex,
6835 int32_t(argvDstOffset) - 2 * sizeof(void*));
6836 masm.loadPtr(srcPtrLow, copyreg);
6837 masm.storePtr(copyreg, dstPtrLow);
6838 }
6839
6840 masm.decBranchPtr(Assembler::NonZero, argvIndex, Imm32(1), &loop);
6841 }
6842
6843 void CodeGenerator::emitRestoreStackPointerFromFP() {
6844 // This is used to restore the stack pointer after a call with a dynamic
6845 // number of arguments.
6846
6847 MOZ_ASSERT(masm.framePushed() == frameSize());
6848
6849 int32_t offset = -int32_t(frameSize());
6850 masm.computeEffectiveAddress(Address(FramePointer, offset),
6851 masm.getStackPointer());
6852 #if JS_CODEGEN_ARM64
6853 masm.syncStackPtr();
6854 #endif
6855 }
6856
6857 void CodeGenerator::emitPushArguments(Register argcreg, Register scratch,
6858 Register copyreg, uint32_t extraFormals) {
6859 Label end;
6860
6861 // Skip the copy of arguments if there are none.
6862 masm.branchTestPtr(Assembler::Zero, argcreg, argcreg, &end);
6863
6864 // clang-format off
6865 //
6866 // We are making a copy of the arguments which are above the JitFrameLayout
6867 // of the current Ion frame.
6868 //
6869 // [arg1] [arg0] <- src [this] [JitFrameLayout] [.. frameSize ..] [pad] [arg1] [arg0] <- dst
6870 //
6871 // clang-format on
6872
6873 // Compute the source and destination offsets into the stack.
6874 //
6875 // The |extraFormals| parameter is used when copying rest-parameters and
6876 // allows to skip the initial parameters before the actual rest-parameters.
6877 Register argvSrcBase = FramePointer;
6878 size_t argvSrcOffset =
6879 JitFrameLayout::offsetOfActualArgs() + extraFormals * sizeof(JS::Value);
6880 size_t argvDstOffset = 0;
6881
6882 Register argvIndex = scratch;
6883 masm.move32(argcreg, argvIndex);
6884
6885 // Copy arguments.
6886 emitCopyValuesForApply(argvSrcBase, argvIndex, copyreg, argvSrcOffset,
6887 argvDstOffset);
6888
6889 // Join with all arguments copied.
6890 masm.bind(&end);
6891 }
6892
6893 void CodeGenerator::emitPushArguments(LApplyArgsGeneric* apply) {
6894 // Holds the function nargs.
6895 Register argcreg = ToRegister(apply->getArgc());
6896 Register copyreg = ToRegister(apply->getTempObject());
6897 Register scratch = ToRegister(apply->getTempForArgCopy());
6898 uint32_t extraFormals = apply->numExtraFormals();
6899
6900 // Allocate space on the stack for arguments.
6901 emitAllocateSpaceForApply(argcreg, scratch);
6902
6903 emitPushArguments(argcreg, scratch, copyreg, extraFormals);
6904
6905 // Push |this|.
6906 masm.pushValue(ToValue(apply->thisValue()));
6907 }
6908
6909 void CodeGenerator::emitPushArguments(LApplyArgsObj* apply) {
6910 Register argsObj = ToRegister(apply->getArgsObj());
6911 Register tmpArgc = ToRegister(apply->getTempObject());
6912 Register scratch = ToRegister(apply->getTempForArgCopy());
6913
6914 // argc and argsObj are mapped to the same calltemp register.
6915 MOZ_ASSERT(argsObj == ToRegister(apply->getArgc()));
6916
6917 // Load argc into tmpArgc.
6918 masm.loadArgumentsObjectLength(argsObj, tmpArgc);
6919
6920 // Allocate space on the stack for arguments.
6921 emitAllocateSpaceForApply(tmpArgc, scratch);
6922
6923 // Load arguments data.
6924 masm.loadPrivate(Address(argsObj, ArgumentsObject::getDataSlotOffset()),
6925 argsObj);
6926 size_t argsSrcOffset = ArgumentsData::offsetOfArgs();
6927
6928 // This is the end of the lifetime of argsObj.
6929 // After this call, the argsObj register holds the argument count instead.
6930 emitPushArrayAsArguments(tmpArgc, argsObj, scratch, argsSrcOffset);
6931
6932 // Push |this|.
6933 masm.pushValue(ToValue(apply->thisValue()));
6934 }
6935
6936 void CodeGenerator::emitPushArrayAsArguments(Register tmpArgc,
6937 Register srcBaseAndArgc,
6938 Register scratch,
6939 size_t argvSrcOffset) {
6940 // Preconditions:
6941 // 1. |tmpArgc| * sizeof(Value) bytes have been allocated at the top of
6942 // the stack to hold arguments.
6943 // 2. |srcBaseAndArgc| + |srcOffset| points to an array of |tmpArgc| values.
6944 //
6945 // Postconditions:
6946 // 1. The arguments at |srcBaseAndArgc| + |srcOffset| have been copied into
6947 // the allocated space.
6948 // 2. |srcBaseAndArgc| now contains the original value of |tmpArgc|.
6949 //
6950 // |scratch| is used as a temp register within this function and clobbered.
6951
6952 Label noCopy, epilogue;
6953
6954 // Skip the copy of arguments if there are none.
6955 masm.branchTestPtr(Assembler::Zero, tmpArgc, tmpArgc, &noCopy);
6956 {
6957 // Copy the values. This code is skipped entirely if there are no values.
6958 size_t argvDstOffset = 0;
6959
6960 Register argvSrcBase = srcBaseAndArgc;
6961
6962 // Stash away |tmpArgc| and adjust argvDstOffset accordingly.
6963 masm.push(tmpArgc);
6964 Register argvIndex = tmpArgc;
6965 argvDstOffset += sizeof(void*);
6966
6967 // Copy
6968 emitCopyValuesForApply(argvSrcBase, argvIndex, scratch, argvSrcOffset,
6969 argvDstOffset);
6970
6971 // Restore.
6972 masm.pop(srcBaseAndArgc); // srcBaseAndArgc now contains argc.
6973 masm.jump(&epilogue);
6974 }
6975 masm.bind(&noCopy);
6976 {
6977 // Clear argc if we skipped the copy step.
6978 masm.movePtr(ImmWord(0), srcBaseAndArgc);
6979 }
6980
6981 // Join with all arguments copied.
6982 // Note, "srcBase" has become "argc".
6983 masm.bind(&epilogue);
6984 }
6985
6986 void CodeGenerator::emitPushArguments(LApplyArrayGeneric* apply) {
6987 Register elements = ToRegister(apply->getElements());
6988 Register tmpArgc = ToRegister(apply->getTempObject());
6989 Register scratch = ToRegister(apply->getTempForArgCopy());
6990
6991 // argc and elements are mapped to the same calltemp register.
6992 MOZ_ASSERT(elements == ToRegister(apply->getArgc()));
6993
6994 // Invariants guarded in the caller:
6995 // - the array is not too long
6996 // - the array length equals its initialized length
6997
6998 // The array length is our argc for the purposes of allocating space.
6999 masm.load32(Address(elements, ObjectElements::offsetOfLength()), tmpArgc);
7000
7001 // Allocate space for the values.
7002 emitAllocateSpaceForApply(tmpArgc, scratch);
7003
7004 // After this call "elements" has become "argc".
7005 size_t elementsOffset = 0;
7006 emitPushArrayAsArguments(tmpArgc, elements, scratch, elementsOffset);
7007
7008 // Push |this|.
7009 masm.pushValue(ToValue(apply->thisValue()));
7010 }
7011
7012 void CodeGenerator::emitPushArguments(LConstructArgsGeneric* construct) {
7013 // Holds the function nargs.
7014 Register argcreg = ToRegister(construct->getArgc());
7015 Register copyreg = ToRegister(construct->getTempObject());
7016 Register scratch = ToRegister(construct->getTempForArgCopy());
7017 uint32_t extraFormals = construct->numExtraFormals();
7018
7019 // newTarget and scratch are mapped to the same calltemp register.
7020 MOZ_ASSERT(scratch == ToRegister(construct->getNewTarget()));
7021
7022 // Allocate space for the values.
7023 // After this call "newTarget" has become "scratch".
7024 emitAllocateSpaceForConstructAndPushNewTarget(argcreg, scratch);
7025
7026 emitPushArguments(argcreg, scratch, copyreg, extraFormals);
7027
7028 // Push |this|.
7029 masm.pushValue(ToValue(construct->thisValue()));
7030 }
7031
7032 void CodeGenerator::emitPushArguments(LConstructArrayGeneric* construct) {
7033 Register elements = ToRegister(construct->getElements());
7034 Register tmpArgc = ToRegister(construct->getTempObject());
7035 Register scratch = ToRegister(construct->getTempForArgCopy());
7036
7037 // argc and elements are mapped to the same calltemp register.
7038 MOZ_ASSERT(elements == ToRegister(construct->getArgc()));
7039
7040 // newTarget and scratch are mapped to the same calltemp register.
7041 MOZ_ASSERT(scratch == ToRegister(construct->getNewTarget()));
7042
7043 // Invariants guarded in the caller:
7044 // - the array is not too long
7045 // - the array length equals its initialized length
7046
7047 // The array length is our argc for the purposes of allocating space.
7048 masm.load32(Address(elements, ObjectElements::offsetOfLength()), tmpArgc);
7049
7050 // Allocate space for the values.
7051 // After this call "newTarget" has become "scratch".
7052 emitAllocateSpaceForConstructAndPushNewTarget(tmpArgc, scratch);
7053
7054 // After this call "elements" has become "argc".
7055 size_t elementsOffset = 0;
7056 emitPushArrayAsArguments(tmpArgc, elements, scratch, elementsOffset);
7057
7058 // Push |this|.
7059 masm.pushValue(ToValue(construct->thisValue()));
7060 }
7061
7062 template <typename T>
7063 void CodeGenerator::emitApplyGeneric(T* apply) {
7064 // Holds the function object.
7065 Register calleereg = ToRegister(apply->getFunction());
7066
7067 // Temporary register for modifying the function object.
7068 Register objreg = ToRegister(apply->getTempObject());
7069 Register scratch = ToRegister(apply->getTempForArgCopy());
7070
7071 // Holds the function nargs, computed in the invoker or (for ApplyArray,
7072 // ConstructArray, or ApplyArgsObj) in the argument pusher.
7073 Register argcreg = ToRegister(apply->getArgc());
7074
7075 // Copy the arguments of the current function.
7076 //
7077 // In the case of ApplyArray, ConstructArray, or ApplyArgsObj, also compute
7078 // argc. The argc register and the elements/argsObj register are the same;
7079 // argc must not be referenced before the call to emitPushArguments() and
7080 // elements/argsObj must not be referenced after it returns.
7081 //
7082 // In the case of ConstructArray or ConstructArgs, also overwrite newTarget;
7083 // newTarget must not be referenced after this point.
7084 //
7085 // objreg is dead across this call.
7086 emitPushArguments(apply);
7087
7088 masm.checkStackAlignment();
7089
7090 bool constructing = apply->mir()->isConstructing();
7091
7092 // If the function is native, the call is compiled through emitApplyNative.
7093 MOZ_ASSERT_IF(apply->hasSingleTarget(),
7094 !apply->getSingleTarget()->isNativeWithoutJitEntry());
7095
7096 Label end, invoke;
7097
7098 // Unless already known, guard that calleereg is actually a function object.
7099 if (!apply->hasSingleTarget()) {
7100 masm.branchTestObjIsFunction(Assembler::NotEqual, calleereg, objreg,
7101 calleereg, &invoke);
7102 }
7103
7104 // Guard that calleereg is an interpreted function with a JSScript.
7105 masm.branchIfFunctionHasNoJitEntry(calleereg, &invoke);
7106
7107 // Guard that callee allows the [[Call]] or [[Construct]] operation required.
7108 if (constructing) {
7109 masm.branchTestFunctionFlags(calleereg, FunctionFlags::CONSTRUCTOR,
7110 Assembler::Zero, &invoke);
7111 } else {
7112 masm.branchFunctionKind(Assembler::Equal, FunctionFlags::ClassConstructor,
7113 calleereg, objreg, &invoke);
7114 }
7115
7116 // Use the slow path if CreateThis was unable to create the |this| object.
7117 if (constructing) {
7118 Address thisAddr(masm.getStackPointer(), 0);
7119 masm.branchTestNull(Assembler::Equal, thisAddr, &invoke);
7120 }
7121
7122 // Call with an Ion frame or a rectifier frame.
7123 {
7124 if (apply->mir()->maybeCrossRealm()) {
7125 masm.switchToObjectRealm(calleereg, objreg);
7126 }
7127
7128 // Knowing that calleereg is a non-native function, load jitcode.
7129 masm.loadJitCodeRaw(calleereg, objreg);
7130
7131 masm.PushCalleeToken(calleereg, constructing);
7132 masm.PushFrameDescriptorForJitCall(FrameType::IonJS, argcreg, scratch);
7133
7134 Label underflow, rejoin;
7135
7136 // Check whether the provided arguments satisfy target argc.
7137 if (!apply->hasSingleTarget()) {
7138 Register nformals = scratch;
7139 masm.loadFunctionArgCount(calleereg, nformals);
7140 masm.branch32(Assembler::Below, argcreg, nformals, &underflow);
7141 } else {
7142 masm.branch32(Assembler::Below, argcreg,
7143 Imm32(apply->getSingleTarget()->nargs()), &underflow);
7144 }
7145
7146 // Skip the construction of the rectifier frame because we have no
7147 // underflow.
7148 masm.jump(&rejoin);
7149
7150 // Argument fixup needed. Get ready to call the argumentsRectifier.
7151 {
7152 masm.bind(&underflow);
7153
7154 // Hardcode the address of the argumentsRectifier code.
7155 TrampolinePtr argumentsRectifier =
7156 gen->jitRuntime()->getArgumentsRectifier();
7157 masm.movePtr(argumentsRectifier, objreg);
7158 }
7159
7160 masm.bind(&rejoin);
7161
7162 // Finally call the function in objreg, as assigned by one of the paths
7163 // above.
7164 ensureOsiSpace();
7165 uint32_t callOffset = masm.callJit(objreg);
7166 markSafepointAt(callOffset, apply);
7167
7168 if (apply->mir()->maybeCrossRealm()) {
7169 static_assert(!JSReturnOperand.aliases(ReturnReg),
7170 "ReturnReg available as scratch after scripted calls");
7171 masm.switchToRealm(gen->realm->realmPtr(), ReturnReg);
7172 }
7173
7174 // Discard JitFrameLayout fields still left on the stack.
7175 masm.freeStack(sizeof(JitFrameLayout) -
7176 JitFrameLayout::bytesPoppedAfterCall());
7177 masm.jump(&end);
7178 }
7179
7180 // Handle uncompiled or native functions.
7181 {
7182 masm.bind(&invoke);
7183 emitCallInvokeFunction(apply);
7184 }
7185
7186 masm.bind(&end);
7187
7188 // If the return value of the constructing function is Primitive, replace the
7189 // return value with the Object from CreateThis.
7190 if (constructing) {
7191 Label notPrimitive;
7192 masm.branchTestPrimitive(Assembler::NotEqual, JSReturnOperand,
7193 &notPrimitive);
7194 masm.loadValue(Address(masm.getStackPointer(), 0), JSReturnOperand);
7195
7196 #ifdef DEBUG
7197 masm.branchTestPrimitive(Assembler::NotEqual, JSReturnOperand,
7198 &notPrimitive);
7199 masm.assumeUnreachable("CreateThis creates an object");
7200 #endif
7201
7202 masm.bind(&notPrimitive);
7203 }
7204
7205 // Pop arguments and continue.
7206 emitRestoreStackPointerFromFP();
7207 }
7208
7209 template <typename T>
7210 void CodeGenerator::emitAlignStackForApplyNative(T* apply, Register argc) {
7211 static_assert(JitStackAlignment % ABIStackAlignment == 0,
7212 "aligning on JIT stack subsumes ABI alignment");
7213
7214 // Align the arguments on the JitStackAlignment.
7215 if (JitStackValueAlignment > 1) {
7216 MOZ_ASSERT(JitStackValueAlignment == 2,
7217 "Stack padding adds exactly one Value");
7218 MOZ_ASSERT(frameSize() % JitStackValueAlignment == 0,
7219 "Stack padding assumes that the frameSize is correct");
7220
7221 Assembler::Condition cond;
7222 if constexpr (T::isConstructing()) {
7223 // If the number of arguments is even, then we do not need any padding.
7224 //
7225 // Also see emitAllocateSpaceForApply().
7226 cond = Assembler::Zero;
7227 } else {
7228 // If the number of arguments is odd, then we do not need any padding.
7229 //
7230 // Also see emitAllocateSpaceForConstructAndPushNewTarget().
7231 cond = Assembler::NonZero;
7232 }
7233
7234 Label noPaddingNeeded;
7235 masm.branchTestPtr(cond, argc, Imm32(1), &noPaddingNeeded);
7236 masm.pushValue(MagicValue(JS_ARG_POISON));
7237 masm.bind(&noPaddingNeeded);
7238 }
7239 }
7240
7241 template <typename T>
7242 void CodeGenerator::emitPushNativeArguments(T* apply) {
7243 Register argc = ToRegister(apply->getArgc());
7244 Register tmpArgc = ToRegister(apply->getTempObject());
7245 Register scratch = ToRegister(apply->getTempForArgCopy());
7246 uint32_t extraFormals = apply->numExtraFormals();
7247
7248 // Align stack.
7249 emitAlignStackForApplyNative(apply, argc);
7250
7251 // Push newTarget.
7252 if constexpr (T::isConstructing()) {
7253 masm.pushValue(JSVAL_TYPE_OBJECT, ToRegister(apply->getNewTarget()));
7254 }
7255
7256 // Push arguments.
7257 Label noCopy;
7258 masm.branchTestPtr(Assembler::Zero, argc, argc, &noCopy);
7259 {
7260 // Use scratch register to calculate stack space.
7261 masm.movePtr(argc, scratch);
7262
7263 // Reserve space for copying the arguments.
7264 NativeObject::elementsSizeMustNotOverflow();
7265 masm.lshiftPtr(Imm32(ValueShift), scratch);
7266 masm.subFromStackPtr(scratch);
7267
7268 // Compute the source and destination offsets into the stack.
7269 Register argvSrcBase = FramePointer;
7270 size_t argvSrcOffset =
7271 JitFrameLayout::offsetOfActualArgs() + extraFormals * sizeof(JS::Value);
7272 size_t argvDstOffset = 0;
7273
7274 Register argvIndex = tmpArgc;
7275 masm.move32(argc, argvIndex);
7276
7277 // Copy arguments.
7278 emitCopyValuesForApply(argvSrcBase, argvIndex, scratch, argvSrcOffset,
7279 argvDstOffset);
7280 }
7281 masm.bind(&noCopy);
7282
7283 // Push |this|.
7284 if constexpr (T::isConstructing()) {
7285 masm.pushValue(MagicValue(JS_IS_CONSTRUCTING));
7286 } else {
7287 masm.pushValue(ToValue(apply->thisValue()));
7288 }
7289 }
7290
7291 template <typename T>
7292 void CodeGenerator::emitPushArrayAsNativeArguments(T* apply) {
7293 Register argc = ToRegister(apply->getArgc());
7294 Register elements = ToRegister(apply->getElements());
7295 Register tmpArgc = ToRegister(apply->getTempObject());
7296 Register scratch = ToRegister(apply->getTempForArgCopy());
7297
7298 // NB: argc and elements are mapped to the same register.
7299 MOZ_ASSERT(argc == elements);
7300
7301 // Invariants guarded in the caller:
7302 // - the array is not too long
7303 // - the array length equals its initialized length
7304
7305 // The array length is our argc.
7306 masm.load32(Address(elements, ObjectElements::offsetOfLength()), tmpArgc);
7307
7308 // Align stack.
7309 emitAlignStackForApplyNative(apply, tmpArgc);
7310
7311 // Push newTarget.
7312 if constexpr (T::isConstructing()) {
7313 masm.pushValue(JSVAL_TYPE_OBJECT, ToRegister(apply->getNewTarget()));
7314 }
7315
7316 // Skip the copy of arguments if there are none.
7317 Label noCopy;
7318 masm.branchTestPtr(Assembler::Zero, tmpArgc, tmpArgc, &noCopy);
7319 {
7320 // |tmpArgc| is off-by-one, so adjust the offset accordingly.
7321 BaseObjectElementIndex srcPtr(elements, tmpArgc,
7322 -int32_t(sizeof(JS::Value)));
7323
7324 Label loop;
7325 masm.bind(&loop);
7326 masm.pushValue(srcPtr, scratch);
7327 masm.decBranchPtr(Assembler::NonZero, tmpArgc, Imm32(1), &loop);
7328 }
7329 masm.bind(&noCopy);
7330
7331 // Set argc in preparation for calling the native function.
7332 masm.load32(Address(elements, ObjectElements::offsetOfLength()), argc);
7333
7334 // Push |this|.
7335 if constexpr (T::isConstructing()) {
7336 masm.pushValue(MagicValue(JS_IS_CONSTRUCTING));
7337 } else {
7338 masm.pushValue(ToValue(apply->thisValue()));
7339 }
7340 }
7341
7342 void CodeGenerator::emitPushArguments(LApplyArgsNative* apply) {
7343 emitPushNativeArguments(apply);
7344 }
7345
7346 void CodeGenerator::emitPushArguments(LApplyArrayNative* apply) {
7347 emitPushArrayAsNativeArguments(apply);
7348 }
7349
7350 void CodeGenerator::emitPushArguments(LConstructArgsNative* construct) {
7351 emitPushNativeArguments(construct);
7352 }
7353
7354 void CodeGenerator::emitPushArguments(LConstructArrayNative* construct) {
7355 emitPushArrayAsNativeArguments(construct);
7356 }
7357
7358 void CodeGenerator::emitPushArguments(LApplyArgsObjNative* apply) {
7359 Register argc = ToRegister(apply->getArgc());
7360 Register argsObj = ToRegister(apply->getArgsObj());
7361 Register tmpArgc = ToRegister(apply->getTempObject());
7362 Register scratch = ToRegister(apply->getTempForArgCopy());
7363 Register scratch2 = ToRegister(apply->getTempExtra());
7364
7365 // NB: argc and argsObj are mapped to the same register.
7366 MOZ_ASSERT(argc == argsObj);
7367
7368 // Load argc into tmpArgc.
7369 masm.loadArgumentsObjectLength(argsObj, tmpArgc);
7370
7371 // Align stack.
7372 emitAlignStackForApplyNative(apply, tmpArgc);
7373
7374 // Push arguments.
7375 Label noCopy, epilogue;
7376 masm.branchTestPtr(Assembler::Zero, tmpArgc, tmpArgc, &noCopy);
7377 {
7378 // Use scratch register to calculate stack space.
7379 masm.movePtr(tmpArgc, scratch);
7380
7381 // Reserve space for copying the arguments.
7382 NativeObject::elementsSizeMustNotOverflow();
7383 masm.lshiftPtr(Imm32(ValueShift), scratch);
7384 masm.subFromStackPtr(scratch);
7385
7386 // Load arguments data.
7387 Register argvSrcBase = argsObj;
7388 masm.loadPrivate(Address(argsObj, ArgumentsObject::getDataSlotOffset()),
7389 argvSrcBase);
7390 size_t argvSrcOffset = ArgumentsData::offsetOfArgs();
7391 size_t argvDstOffset = 0;
7392
7393 Register argvIndex = scratch2;
7394 masm.move32(tmpArgc, argvIndex);
7395
7396 // Copy the values.
7397 emitCopyValuesForApply(argvSrcBase, argvIndex, scratch, argvSrcOffset,
7398 argvDstOffset);
7399 }
7400 masm.bind(&noCopy);
7401
7402 // Set argc in preparation for calling the native function.
7403 masm.movePtr(tmpArgc, argc);
7404
7405 // Push |this|.
7406 masm.pushValue(ToValue(apply->thisValue()));
7407 }
7408
7409 template <typename T>
7410 void CodeGenerator::emitApplyNative(T* apply) {
7411 MOZ_ASSERT(T::isConstructing() == apply->mir()->isConstructing(),
7412 "isConstructing condition must be consistent");
7413
7414 WrappedFunction* target = apply->mir()->getSingleTarget();
7415 MOZ_ASSERT(target->isNativeWithoutJitEntry());
7416
7417 JSNative native = target->native();
7418 if (apply->mir()->ignoresReturnValue() && target->hasJitInfo()) {
7419 const JSJitInfo* jitInfo = target->jitInfo();
7420 if (jitInfo->type() == JSJitInfo::IgnoresReturnValueNative) {
7421 native = jitInfo->ignoresReturnValueMethod;
7422 }
7423 }
7424
7425 // Push arguments, including newTarget and |this|.
7426 emitPushArguments(apply);
7427
7428 // Registers used for callWithABI() argument-passing.
7429 Register argContextReg = ToRegister(apply->getTempObject());
7430 Register argUintNReg = ToRegister(apply->getArgc());
7431 Register argVpReg = ToRegister(apply->getTempForArgCopy());
7432 Register tempReg = ToRegister(apply->getTempExtra());
7433
7434 // No unused stack for variadic calls.
7435 uint32_t unusedStack = 0;
7436
7437 // Pushed arguments don't change the pushed frames amount.
7438 MOZ_ASSERT(masm.framePushed() == frameSize());
7439
7440 // Create the exit frame and call the native.
7441 emitCallNative(apply, native, argContextReg, argUintNReg, argVpReg, tempReg,
7442 unusedStack);
7443
7444 // The exit frame is still on the stack.
7445 MOZ_ASSERT(masm.framePushed() == frameSize() + NativeExitFrameLayout::Size());
7446
7447 // The next instruction is removing the exit frame, so there is no need for
7448 // leaveFakeExitFrame.
7449
7450 // Pop arguments and continue.
7451 masm.setFramePushed(frameSize());
7452 emitRestoreStackPointerFromFP();
7453 }
7454
7455 template <typename T>
7456 void CodeGenerator::emitApplyArgsGuard(T* apply) {
7457 LSnapshot* snapshot = apply->snapshot();
7458 Register argcreg = ToRegister(apply->getArgc());
7459
7460 // Ensure that we have a reasonable number of arguments.
7461 bailoutCmp32(Assembler::Above, argcreg, Imm32(JIT_ARGS_LENGTH_MAX), snapshot);
7462 }
7463
7464 template <typename T>
7465 void CodeGenerator::emitApplyArgsObjGuard(T* apply) {
7466 Register argsObj = ToRegister(apply->getArgsObj());
7467 Register temp = ToRegister(apply->getTempObject());
7468
7469 Label bail;
7470 masm.loadArgumentsObjectLength(argsObj, temp, &bail);
7471 masm.branch32(Assembler::Above, temp, Imm32(JIT_ARGS_LENGTH_MAX), &bail);
7472 bailoutFrom(&bail, apply->snapshot());
7473 }
7474
7475 template <typename T>
7476 void CodeGenerator::emitApplyArrayGuard(T* apply) {
7477 LSnapshot* snapshot = apply->snapshot();
7478 Register elements = ToRegister(apply->getElements());
7479 Register tmp = ToRegister(apply->getTempObject());
7480
7481 Address length(elements, ObjectElements::offsetOfLength());
7482 masm.load32(length, tmp);
7483
7484 // Ensure that we have a reasonable number of arguments.
7485 bailoutCmp32(Assembler::Above, tmp, Imm32(JIT_ARGS_LENGTH_MAX), snapshot);
7486
7487 // Ensure that the array does not contain an uninitialized tail.
7488
7489 Address initializedLength(elements,
7490 ObjectElements::offsetOfInitializedLength());
7491 masm.sub32(initializedLength, tmp);
7492 bailoutCmp32(Assembler::NotEqual, tmp, Imm32(0), snapshot);
7493 }
7494
7495 void CodeGenerator::visitApplyArgsGeneric(LApplyArgsGeneric* apply) {
7496 emitApplyArgsGuard(apply);
7497 emitApplyGeneric(apply);
7498 }
7499
7500 void CodeGenerator::visitApplyArgsObj(LApplyArgsObj* apply) {
7501 emitApplyArgsObjGuard(apply);
7502 emitApplyGeneric(apply);
7503 }
7504
7505 void CodeGenerator::visitApplyArrayGeneric(LApplyArrayGeneric* apply) {
7506 emitApplyArrayGuard(apply);
7507 emitApplyGeneric(apply);
7508 }
7509
7510 void CodeGenerator::visitConstructArgsGeneric(LConstructArgsGeneric* lir) {
7511 emitApplyArgsGuard(lir);
7512 emitApplyGeneric(lir);
7513 }
7514
7515 void CodeGenerator::visitConstructArrayGeneric(LConstructArrayGeneric* lir) {
7516 emitApplyArrayGuard(lir);
7517 emitApplyGeneric(lir);
7518 }
7519
7520 void CodeGenerator::visitApplyArgsNative(LApplyArgsNative* lir) {
7521 emitApplyArgsGuard(lir);
7522 emitApplyNative(lir);
7523 }
7524
7525 void CodeGenerator::visitApplyArgsObjNative(LApplyArgsObjNative* lir) {
7526 emitApplyArgsObjGuard(lir);
7527 emitApplyNative(lir);
7528 }
7529
7530 void CodeGenerator::visitApplyArrayNative(LApplyArrayNative* lir) {
7531 emitApplyArrayGuard(lir);
7532 emitApplyNative(lir);
7533 }
7534
7535 void CodeGenerator::visitConstructArgsNative(LConstructArgsNative* lir) {
7536 emitApplyArgsGuard(lir);
7537 emitApplyNative(lir);
7538 }
7539
7540 void CodeGenerator::visitConstructArrayNative(LConstructArrayNative* lir) {
7541 emitApplyArrayGuard(lir);
7542 emitApplyNative(lir);
7543 }
7544
7545 void CodeGenerator::visitBail(LBail* lir) { bailout(lir->snapshot()); }
7546
7547 void CodeGenerator::visitUnreachable(LUnreachable* lir) {
7548 masm.assumeUnreachable("end-of-block assumed unreachable");
7549 }
7550
7551 void CodeGenerator::visitEncodeSnapshot(LEncodeSnapshot* lir) {
7552 encode(lir->snapshot());
7553 }
7554
7555 void CodeGenerator::visitUnreachableResultV(LUnreachableResultV* lir) {
7556 masm.assumeUnreachable("must be unreachable");
7557 }
7558
7559 void CodeGenerator::visitUnreachableResultT(LUnreachableResultT* lir) {
7560 masm.assumeUnreachable("must be unreachable");
7561 }
7562
7563 void CodeGenerator::visitCheckOverRecursed(LCheckOverRecursed* lir) {
7564 // If we don't push anything on the stack, skip the check.
7565 if (omitOverRecursedCheck()) {
7566 return;
7567 }
7568
7569 // Ensure that this frame will not cross the stack limit.
7570 // This is a weak check, justified by Ion using the C stack: we must always
7571 // be some distance away from the actual limit, since if the limit is
7572 // crossed, an error must be thrown, which requires more frames.
7573 //
7574 // It must always be possible to trespass past the stack limit.
7575 // Ion may legally place frames very close to the limit. Calling additional
7576 // C functions may then violate the limit without any checking.
7577 //
7578 // Since Ion frames exist on the C stack, the stack limit may be
7579 // dynamically set by JS_SetThreadStackLimit() and JS_SetNativeStackQuota().
7580
7581 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
7582 // The OOL path is hit if the recursion depth has been exceeded.
7583 // Throw an InternalError for over-recursion.
7584
7585 // LFunctionEnvironment can appear before LCheckOverRecursed, so we have
7586 // to save all live registers to avoid crashes if CheckOverRecursed triggers
7587 // a GC.
7588 saveLive(lir);
7589
7590 using Fn = bool (*)(JSContext*);
7591 callVM<Fn, CheckOverRecursed>(lir);
7592
7593 restoreLive(lir);
7594 masm.jump(ool.rejoin());
7595 });
7596 addOutOfLineCode(ool, lir->mir());
7597
7598 // Conditional forward (unlikely) branch to failure.
7599 const void* limitAddr = gen->runtime->addressOfJitStackLimit();
7600 masm.branchStackPtrRhs(Assembler::AboveOrEqual, AbsoluteAddress(limitAddr),
7601 ool->entry());
7602 masm.bind(ool->rejoin());
7603 }
7604
7605 IonScriptCounts* CodeGenerator::maybeCreateScriptCounts() {
7606 // If scripts are being profiled, create a new IonScriptCounts for the
7607 // profiling data, which will be attached to the associated JSScript or
7608 // wasm module after code generation finishes.
7609 if (!gen->hasProfilingScripts()) {
7610 return nullptr;
7611 }
7612
7613 // This test inhibits IonScriptCount creation for wasm code which is
7614 // currently incompatible with wasm codegen for two reasons: (1) wasm code
7615 // must be serializable and script count codegen bakes in absolute
7616 // addresses, (2) wasm code does not have a JSScript with which to associate
7617 // code coverage data.
7618 JSScript* script = gen->outerInfo().script();
7619 if (!script) {
7620 return nullptr;
7621 }
7622
7623 auto counts = MakeUnique<IonScriptCounts>();
7624 if (!counts || !counts->init(graph.numBlocks())) {
7625 return nullptr;
7626 }
7627
7628 for (size_t i = 0; i < graph.numBlocks(); i++) {
7629 MBasicBlock* block = graph.getBlock(i)->mir();
7630
7631 uint32_t offset = 0;
7632 char* description = nullptr;
7633 if (MResumePoint* resume = block->entryResumePoint()) {
7634 // Find a PC offset in the outermost script to use. If this
7635 // block is from an inlined script, find a location in the
7636 // outer script to associate information about the inlining
7637 // with.
7638 while (resume->caller()) {
7639 resume = resume->caller();
7640 }
7641 offset = script->pcToOffset(resume->pc());
7642
7643 if (block->entryResumePoint()->caller()) {
7644 // Get the filename and line number of the inner script.
7645 JSScript* innerScript = block->info().script();
7646 description = js_pod_calloc<char>(200);
7647 if (description) {
7648 snprintf(description, 200, "%s:%u", innerScript->filename(),
7649 innerScript->lineno());
7650 }
7651 }
7652 }
7653
7654 if (!counts->block(i).init(block->id(), offset, description,
7655 block->numSuccessors())) {
7656 return nullptr;
7657 }
7658
7659 for (size_t j = 0; j < block->numSuccessors(); j++) {
7660 counts->block(i).setSuccessor(
7661 j, skipTrivialBlocks(block->getSuccessor(j))->id());
7662 }
7663 }
7664
7665 scriptCounts_ = counts.release();
7666 return scriptCounts_;
7667 }
7668
7669 // Structure for managing the state tracked for a block by script counters.
7670 struct ScriptCountBlockState {
7671 IonBlockCounts& block;
7672 MacroAssembler& masm;
7673
7674 Sprinter printer;
7675
7676 public:
7677 ScriptCountBlockState(IonBlockCounts* block, MacroAssembler* masm)
7678 : block(*block), masm(*masm), printer(GetJitContext()->cx, false) {}
7679
7680 bool init() {
7681 if (!printer.init()) {
7682 return false;
7683 }
7684
7685 // Bump the hit count for the block at the start. This code is not
7686 // included in either the text for the block or the instruction byte
7687 // counts.
7688 masm.inc64(AbsoluteAddress(block.addressOfHitCount()));
7689
7690 // Collect human readable assembly for the code generated in the block.
7691 masm.setPrinter(&printer);
7692
7693 return true;
7694 }
7695
7696 void visitInstruction(LInstruction* ins) {
7697 #ifdef JS_JITSPEW
7698 // Prefix stream of assembly instructions with their LIR instruction
7699 // name and any associated high level info.
7700 if (const char* extra = ins->getExtraName()) {
7701 printer.printf("[%s:%s]\n", ins->opName(), extra);
7702 } else {
7703 printer.printf("[%s]\n", ins->opName());
7704 }
7705 #endif
7706 }
7707
7708 ~ScriptCountBlockState() {
7709 masm.setPrinter(nullptr);
7710
7711 if (JS::UniqueChars str = printer.release()) {
7712 block.setCode(str.get());
7713 }
7714 }
7715 };
7716
7717 void CodeGenerator::branchIfInvalidated(Register temp, Label* invalidated) {
7718 CodeOffset label = masm.movWithPatch(ImmWord(uintptr_t(-1)), temp);
7719 masm.propagateOOM(ionScriptLabels_.append(label));
7720
7721 // If IonScript::invalidationCount_ != 0, the script has been invalidated.
7722 masm.branch32(Assembler::NotEqual,
7723 Address(temp, IonScript::offsetOfInvalidationCount()), Imm32(0),
7724 invalidated);
7725 }
7726
7727 #ifdef DEBUG
7728 void CodeGenerator::emitAssertGCThingResult(Register input,
7729 const MDefinition* mir) {
7730 MIRType type = mir->type();
7731 MOZ_ASSERT(type == MIRType::Object || type == MIRType::String ||
7732 type == MIRType::Symbol || type == MIRType::BigInt);
7733
7734 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
7735 regs.take(input);
7736
7737 Register temp = regs.takeAny();
7738 masm.push(temp);
7739
7740 // Don't check if the script has been invalidated. In that case invalid
7741 // types are expected (until we reach the OsiPoint and bailout).
7742 Label done;
7743 branchIfInvalidated(temp, &done);
7744
7745 # ifndef JS_SIMULATOR
7746 // Check that we have a valid GC pointer.
7747 // Disable for wasm because we don't have a context on wasm compilation
7748 // threads and this needs a context.
7749 // Also disable for simulator builds because the C++ call is a lot slower
7750 // there than on actual hardware.
7751 if (JitOptions.fullDebugChecks && !IsCompilingWasm()) {
7752 saveVolatile();
7753 masm.setupUnalignedABICall(temp);
7754 masm.loadJSContext(temp);
7755 masm.passABIArg(temp);
7756 masm.passABIArg(input);
7757
7758 switch (type) {
7759 case MIRType::Object: {
7760 using Fn = void (*)(JSContext* cx, JSObject* obj);
7761 masm.callWithABI<Fn, AssertValidObjectPtr>();
7762 break;
7763 }
7764 case MIRType::String: {
7765 using Fn = void (*)(JSContext* cx, JSString* str);
7766 masm.callWithABI<Fn, AssertValidStringPtr>();
7767 break;
7768 }
7769 case MIRType::Symbol: {
7770 using Fn = void (*)(JSContext* cx, JS::Symbol* sym);
7771 masm.callWithABI<Fn, AssertValidSymbolPtr>();
7772 break;
7773 }
7774 case MIRType::BigInt: {
7775 using Fn = void (*)(JSContext* cx, JS::BigInt* bi);
7776 masm.callWithABI<Fn, AssertValidBigIntPtr>();
7777 break;
7778 }
7779 default:
7780 MOZ_CRASH();
7781 }
7782
7783 restoreVolatile();
7784 }
7785 # endif
7786
7787 masm.bind(&done);
7788 masm.pop(temp);
7789 }
7790
7791 void CodeGenerator::emitAssertResultV(const ValueOperand input,
7792 const MDefinition* mir) {
7793 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
7794 regs.take(input);
7795
7796 Register temp1 = regs.takeAny();
7797 Register temp2 = regs.takeAny();
7798 masm.push(temp1);
7799 masm.push(temp2);
7800
7801 // Don't check if the script has been invalidated. In that case invalid
7802 // types are expected (until we reach the OsiPoint and bailout).
7803 Label done;
7804 branchIfInvalidated(temp1, &done);
7805
7806 // Check that we have a valid GC pointer.
7807 if (JitOptions.fullDebugChecks) {
7808 saveVolatile();
7809
7810 masm.pushValue(input);
7811 masm.moveStackPtrTo(temp1);
7812
7813 using Fn = void (*)(JSContext* cx, Value* v);
7814 masm.setupUnalignedABICall(temp2);
7815 masm.loadJSContext(temp2);
7816 masm.passABIArg(temp2);
7817 masm.passABIArg(temp1);
7818 masm.callWithABI<Fn, AssertValidValue>();
7819 masm.popValue(input);
7820 restoreVolatile();
7821 }
7822
7823 masm.bind(&done);
7824 masm.pop(temp2);
7825 masm.pop(temp1);
7826 }
7827
7828 void CodeGenerator::emitGCThingResultChecks(LInstruction* lir,
7829 MDefinition* mir) {
7830 if (lir->numDefs() == 0) {
7831 return;
7832 }
7833
7834 MOZ_ASSERT(lir->numDefs() == 1);
7835 if (lir->getDef(0)->isBogusTemp()) {
7836 return;
7837 }
7838
7839 Register output = ToRegister(lir->getDef(0));
7840 emitAssertGCThingResult(output, mir);
7841 }
7842
7843 void CodeGenerator::emitValueResultChecks(LInstruction* lir, MDefinition* mir) {
7844 if (lir->numDefs() == 0) {
7845 return;
7846 }
7847
7848 MOZ_ASSERT(lir->numDefs() == BOX_PIECES);
7849 if (!lir->getDef(0)->output()->isGeneralReg()) {
7850 return;
7851 }
7852
7853 ValueOperand output = ToOutValue(lir);
7854
7855 emitAssertResultV(output, mir);
7856 }
7857
7858 void CodeGenerator::emitWasmAnyrefResultChecks(LInstruction* lir,
7859 MDefinition* mir) {
7860 MOZ_ASSERT(mir->type() == MIRType::WasmAnyRef);
7861
7862 wasm::MaybeRefType destType = mir->wasmRefType();
7863 if (!destType) {
7864 return;
7865 }
7866
7867 if (!JitOptions.fullDebugChecks) {
7868 return;
7869 }
7870
7871 if (lir->numDefs() == 0) {
7872 return;
7873 }
7874
7875 MOZ_ASSERT(lir->numDefs() == 1);
7876 if (lir->getDef(0)->isBogusTemp()) {
7877 return;
7878 }
7879
7880 if (lir->getDef(0)->output()->isMemory()) {
7881 return;
7882 }
7883 Register output = ToRegister(lir->getDef(0));
7884
7885 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
7886 regs.take(output);
7887
7888 BranchWasmRefIsSubtypeRegisters needs =
7889 MacroAssembler::regsForBranchWasmRefIsSubtype(destType.value());
7890
7891 Register temp1;
7892 Register temp2;
7893 Register temp3;
7894 if (needs.needSuperSTV) {
7895 temp1 = regs.takeAny();
7896 masm.push(temp1);
7897 }
7898 if (needs.needScratch1) {
7899 temp2 = regs.takeAny();
7900 masm.push(temp2);
7901 }
7902 if (needs.needScratch2) {
7903 temp3 = regs.takeAny();
7904 masm.push(temp3);
7905 }
7906
7907 if (needs.needSuperSTV) {
7908 uint32_t typeIndex =
7909 wasmCodeMeta()->types->indexOf(*destType.value().typeDef());
7910
7911 // When full debug checks are enabled, we always write the callee instance
7912 // pointer into its usual slot in the frame in our function prologue, so
7913 // that we can get it even if the InstanceReg is currently being used for
7914 // something else.
7915 masm.loadPtr(
7916 Address(FramePointer, wasm::FrameWithInstances::calleeInstanceOffset()),
7917 temp1);
7918 masm.loadPtr(
7919 Address(temp1, wasm::Instance::offsetInData(
7920 wasmCodeMeta()->offsetOfSuperTypeVector(typeIndex))),
7921 temp1);
7922 }
7923
7924 Label ok;
7925 masm.branchWasmRefIsSubtype(output, wasm::MaybeRefType(), destType.value(),
7926 &ok, true, temp1, temp2, temp3);
7927 masm.breakpoint();
7928 masm.bind(&ok);
7929
7930 if (needs.needScratch2) {
7931 masm.pop(temp3);
7932 }
7933 if (needs.needScratch1) {
7934 masm.pop(temp2);
7935 }
7936 if (needs.needSuperSTV) {
7937 masm.pop(temp1);
7938 }
7939
7940 # ifdef JS_CODEGEN_ARM64
7941 masm.syncStackPtr();
7942 # endif
7943 }
7944
7945 void CodeGenerator::emitDebugResultChecks(LInstruction* ins) {
7946 // In debug builds, check that LIR instructions return valid values.
7947
7948 MDefinition* mir = ins->mirRaw();
7949 if (!mir) {
7950 return;
7951 }
7952
7953 switch (mir->type()) {
7954 case MIRType::Object:
7955 case MIRType::String:
7956 case MIRType::Symbol:
7957 case MIRType::BigInt:
7958 emitGCThingResultChecks(ins, mir);
7959 break;
7960 case MIRType::Value:
7961 emitValueResultChecks(ins, mir);
7962 break;
7963 case MIRType::WasmAnyRef:
7964 emitWasmAnyrefResultChecks(ins, mir);
7965 break;
7966 default:
7967 break;
7968 }
7969 }
7970
7971 void CodeGenerator::emitDebugForceBailing(LInstruction* lir) {
7972 if (MOZ_LIKELY(!gen->options.ionBailAfterEnabled())) {
7973 return;
7974 }
7975 if (!lir->snapshot()) {
7976 return;
7977 }
7978 if (lir->isOsiPoint()) {
7979 return;
7980 }
7981
7982 masm.comment("emitDebugForceBailing");
7983 const void* bailAfterCounterAddr =
7984 gen->runtime->addressOfIonBailAfterCounter();
7985
7986 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::All());
7987
7988 Label done, notBail;
7989 masm.branch32(Assembler::Equal, AbsoluteAddress(bailAfterCounterAddr),
7990 Imm32(0), &done);
7991 {
7992 Register temp = regs.takeAny();
7993
7994 masm.push(temp);
7995 masm.load32(AbsoluteAddress(bailAfterCounterAddr), temp);
7996 masm.sub32(Imm32(1), temp);
7997 masm.store32(temp, AbsoluteAddress(bailAfterCounterAddr));
7998
7999 masm.branch32(Assembler::NotEqual, temp, Imm32(0), &notBail);
8000 {
8001 masm.pop(temp);
8002 bailout(lir->snapshot());
8003 }
8004 masm.bind(&notBail);
8005 masm.pop(temp);
8006 }
8007 masm.bind(&done);
8008 }
8009 #endif // DEBUG
8010
8011 bool CodeGenerator::generateBody() {
8012 JitSpewCont(JitSpew_Codegen, "\n");
8013 AutoCreatedBy acb(masm, "CodeGenerator::generateBody");
8014
8015 JitSpew(JitSpew_Codegen, "==== BEGIN CodeGenerator::generateBody ====");
8016 IonScriptCounts* counts = maybeCreateScriptCounts();
8017
8018 const bool compilingWasm = gen->compilingWasm();
8019
8020 for (size_t i = 0; i < graph.numBlocks(); i++) {
8021 current = graph.getBlock(i);
8022
8023 // Don't emit any code for trivial blocks, containing just a goto. Such
8024 // blocks are created to split critical edges, and if we didn't end up
8025 // putting any instructions in them, we can skip them.
8026 if (current->isTrivial()) {
8027 continue;
8028 }
8029
8030 if (gen->shouldCancel("Generate Code (block loop)")) {
8031 return false;
8032 }
8033
8034 #ifdef JS_JITSPEW
8035 const char* filename = nullptr;
8036 size_t lineNumber = 0;
8037 JS::LimitedColumnNumberOneOrigin columnNumber;
8038 if (current->mir()->info().script()) {
8039 filename = current->mir()->info().script()->filename();
8040 if (current->mir()->pc()) {
8041 lineNumber = PCToLineNumber(current->mir()->info().script(),
8042 current->mir()->pc(), &columnNumber);
8043 }
8044 }
8045 JitSpew(JitSpew_Codegen, "--------------------------------");
8046 JitSpew(JitSpew_Codegen, "# block%zu %s:%zu:%u%s:", i,
8047 filename ? filename : "?", lineNumber,
8048 columnNumber.oneOriginValue(),
8049 current->mir()->isLoopHeader() ? " (loop header)" : "");
8050 #endif
8051
8052 if (current->mir()->isLoopHeader() && compilingWasm) {
8053 masm.nopAlign(CodeAlignment);
8054 }
8055
8056 masm.bind(current->label());
8057
8058 mozilla::Maybe<ScriptCountBlockState> blockCounts;
8059 if (counts) {
8060 blockCounts.emplace(&counts->block(i), &masm);
8061 if (!blockCounts->init()) {
8062 return false;
8063 }
8064 }
8065
8066 for (LInstructionIterator iter = current->begin(); iter != current->end();
8067 iter++) {
8068 if (gen->shouldCancel("Generate Code (instruction loop)")) {
8069 return false;
8070 }
8071 if (!alloc().ensureBallast()) {
8072 return false;
8073 }
8074
8075 perfSpewer_.recordInstruction(masm, *iter);
8076 #ifdef JS_JITSPEW
8077 JitSpewStart(JitSpew_Codegen, " # LIR=%s",
8078 iter->opName());
8079 if (const char* extra = iter->getExtraName()) {
8080 JitSpewCont(JitSpew_Codegen, ":%s", extra);
8081 }
8082 JitSpewFin(JitSpew_Codegen);
8083 #endif
8084
8085 if (counts) {
8086 blockCounts->visitInstruction(*iter);
8087 }
8088
8089 #ifdef CHECK_OSIPOINT_REGISTERS
8090 if (iter->safepoint() && !compilingWasm) {
8091 resetOsiPointRegs(iter->safepoint());
8092 }
8093 #endif
8094
8095 if (!compilingWasm) {
8096 if (MDefinition* mir = iter->mirRaw()) {
8097 if (!addNativeToBytecodeEntry(mir->trackedSite())) {
8098 return false;
8099 }
8100 }
8101 }
8102
8103 setElement(*iter); // needed to encode correct snapshot location.
8104
8105 #ifdef DEBUG
8106 emitDebugForceBailing(*iter);
8107 #endif
8108
8109 switch (iter->op()) {
8110 #ifndef JS_CODEGEN_NONE
8111 # define LIROP(op) \
8112 case LNode::Opcode::op: \
8113 visit##op(iter->to##op()); \
8114 break;
8115 LIR_OPCODE_LIST(LIROP)
8116 # undef LIROP
8117 #endif
8118 case LNode::Opcode::Invalid:
8119 default:
8120 MOZ_CRASH("Invalid LIR op");
8121 }
8122
8123 #ifdef DEBUG
8124 if (!counts) {
8125 emitDebugResultChecks(*iter);
8126 }
8127 #endif
8128 }
8129 if (masm.oom()) {
8130 return false;
8131 }
8132 }
8133
8134 JitSpew(JitSpew_Codegen, "==== END CodeGenerator::generateBody ====\n");
8135 return true;
8136 }
8137
8138 void CodeGenerator::visitNewArrayCallVM(LNewArray* lir) {
8139 Register objReg = ToRegister(lir->output());
8140
8141 MOZ_ASSERT(!lir->isCall());
8142 saveLive(lir);
8143
8144 JSObject* templateObject = lir->mir()->templateObject();
8145
8146 if (templateObject) {
8147 pushArg(ImmGCPtr(templateObject->shape()));
8148 pushArg(Imm32(lir->mir()->length()));
8149
8150 using Fn = ArrayObject* (*)(JSContext*, uint32_t, Handle<Shape*>);
8151 callVM<Fn, NewArrayWithShape>(lir);
8152 } else {
8153 pushArg(Imm32(GenericObject));
8154 pushArg(Imm32(lir->mir()->length()));
8155
8156 using Fn = ArrayObject* (*)(JSContext*, uint32_t, NewObjectKind);
8157 callVM<Fn, NewArrayOperation>(lir);
8158 }
8159
8160 masm.storeCallPointerResult(objReg);
8161
8162 MOZ_ASSERT(!lir->safepoint()->liveRegs().has(objReg));
8163 restoreLive(lir);
8164 }
8165
8166 void CodeGenerator::visitAtan2D(LAtan2D* lir) {
8167 FloatRegister y = ToFloatRegister(lir->y());
8168 FloatRegister x = ToFloatRegister(lir->x());
8169
8170 using Fn = double (*)(double x, double y);
8171 masm.setupAlignedABICall();
8172 masm.passABIArg(y, ABIType::Float64);
8173 masm.passABIArg(x, ABIType::Float64);
8174 masm.callWithABI<Fn, ecmaAtan2>(ABIType::Float64);
8175
8176 MOZ_ASSERT(ToFloatRegister(lir->output()) == ReturnDoubleReg);
8177 }
8178
8179 void CodeGenerator::visitHypot(LHypot* lir) {
8180 uint32_t numArgs = lir->numArgs();
8181 masm.setupAlignedABICall();
8182
8183 for (uint32_t i = 0; i < numArgs; ++i) {
8184 masm.passABIArg(ToFloatRegister(lir->getOperand(i)), ABIType::Float64);
8185 }
8186
8187 switch (numArgs) {
8188 case 2: {
8189 using Fn = double (*)(double x, double y);
8190 masm.callWithABI<Fn, ecmaHypot>(ABIType::Float64);
8191 break;
8192 }
8193 case 3: {
8194 using Fn = double (*)(double x, double y, double z);
8195 masm.callWithABI<Fn, hypot3>(ABIType::Float64);
8196 break;
8197 }
8198 case 4: {
8199 using Fn = double (*)(double x, double y, double z, double w);
8200 masm.callWithABI<Fn, hypot4>(ABIType::Float64);
8201 break;
8202 }
8203 default:
8204 MOZ_CRASH("Unexpected number of arguments to hypot function.");
8205 }
8206 MOZ_ASSERT(ToFloatRegister(lir->output()) == ReturnDoubleReg);
8207 }
8208
8209 void CodeGenerator::visitNewArray(LNewArray* lir) {
8210 Register objReg = ToRegister(lir->output());
8211 Register tempReg = ToRegister(lir->temp0());
8212 DebugOnly<uint32_t> length = lir->mir()->length();
8213
8214 MOZ_ASSERT(length <= NativeObject::MAX_DENSE_ELEMENTS_COUNT);
8215
8216 if (lir->mir()->isVMCall()) {
8217 visitNewArrayCallVM(lir);
8218 return;
8219 }
8220
8221 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
8222 visitNewArrayCallVM(lir);
8223 masm.jump(ool.rejoin());
8224 });
8225 addOutOfLineCode(ool, lir->mir());
8226 TemplateObject templateObject(lir->mir()->templateObject());
8227 #ifdef DEBUG
8228 size_t numInlineElements = gc::GetGCKindSlots(templateObject.getAllocKind()) -
8229 ObjectElements::VALUES_PER_HEADER;
8230 MOZ_ASSERT(length <= numInlineElements,
8231 "Inline allocation only supports inline elements");
8232 #endif
8233 masm.createGCObject(objReg, tempReg, templateObject,
8234 lir->mir()->initialHeap(), ool->entry());
8235
8236 masm.bind(ool->rejoin());
8237 }
8238
8239 void CodeGenerator::visitNewArrayDynamicLength(LNewArrayDynamicLength* lir) {
8240 Register lengthReg = ToRegister(lir->length());
8241 Register objReg = ToRegister(lir->output());
8242 Register tempReg = ToRegister(lir->temp0());
8243
8244 JSObject* templateObject = lir->mir()->templateObject();
8245 gc::Heap initialHeap = lir->mir()->initialHeap();
8246
8247 using Fn = ArrayObject* (*)(JSContext*, Handle<ArrayObject*>, int32_t length,
8248 gc::AllocSite*);
8249 OutOfLineCode* ool = oolCallVM<Fn, ArrayConstructorOneArg>(
8250 lir, ArgList(ImmGCPtr(templateObject), lengthReg, ImmPtr(nullptr)),
8251 StoreRegisterTo(objReg));
8252
8253 bool canInline = true;
8254 size_t inlineLength = 0;
8255 if (templateObject->as<ArrayObject>().hasFixedElements()) {
8256 size_t numSlots =
8257 gc::GetGCKindSlots(templateObject->asTenured().getAllocKind());
8258 inlineLength = numSlots - ObjectElements::VALUES_PER_HEADER;
8259 } else {
8260 canInline = false;
8261 }
8262
8263 if (canInline) {
8264 // Try to do the allocation inline if the template object is big enough
8265 // for the length in lengthReg. If the length is bigger we could still
8266 // use the template object and not allocate the elements, but it's more
8267 // efficient to do a single big allocation than (repeatedly) reallocating
8268 // the array later on when filling it.
8269 masm.branch32(Assembler::Above, lengthReg, Imm32(inlineLength),
8270 ool->entry());
8271
8272 TemplateObject templateObj(templateObject);
8273 masm.createGCObject(objReg, tempReg, templateObj, initialHeap,
8274 ool->entry());
8275
8276 size_t lengthOffset = NativeObject::offsetOfFixedElements() +
8277 ObjectElements::offsetOfLength();
8278 masm.store32(lengthReg, Address(objReg, lengthOffset));
8279 } else {
8280 masm.jump(ool->entry());
8281 }
8282
8283 masm.bind(ool->rejoin());
8284 }
8285
8286 void CodeGenerator::visitNewIterator(LNewIterator* lir) {
8287 Register objReg = ToRegister(lir->output());
8288 Register tempReg = ToRegister(lir->temp0());
8289
8290 OutOfLineCode* ool;
8291 switch (lir->mir()->type()) {
8292 case MNewIterator::ArrayIterator: {
8293 using Fn = ArrayIteratorObject* (*)(JSContext*);
8294 ool = oolCallVM<Fn, NewArrayIterator>(lir, ArgList(),
8295 StoreRegisterTo(objReg));
8296 break;
8297 }
8298 case MNewIterator::StringIterator: {
8299 using Fn = StringIteratorObject* (*)(JSContext*);
8300 ool = oolCallVM<Fn, NewStringIterator>(lir, ArgList(),
8301 StoreRegisterTo(objReg));
8302 break;
8303 }
8304 case MNewIterator::RegExpStringIterator: {
8305 using Fn = RegExpStringIteratorObject* (*)(JSContext*);
8306 ool = oolCallVM<Fn, NewRegExpStringIterator>(lir, ArgList(),
8307 StoreRegisterTo(objReg));
8308 break;
8309 }
8310 default:
8311 MOZ_CRASH("unexpected iterator type");
8312 }
8313
8314 TemplateObject templateObject(lir->mir()->templateObject());
8315 masm.createGCObject(objReg, tempReg, templateObject, gc::Heap::Default,
8316 ool->entry());
8317
8318 masm.bind(ool->rejoin());
8319 }
8320
8321 void CodeGenerator::visitNewTypedArray(LNewTypedArray* lir) {
8322 Register objReg = ToRegister(lir->output());
8323 Register tempReg = ToRegister(lir->temp0());
8324 Register lengthReg = ToRegister(lir->temp1());
8325 LiveRegisterSet liveRegs = liveVolatileRegs(lir);
8326
8327 JSObject* templateObject = lir->mir()->templateObject();
8328 gc::Heap initialHeap = lir->mir()->initialHeap();
8329
8330 auto* ttemplate = &templateObject->as<FixedLengthTypedArrayObject>();
8331
8332 size_t n = ttemplate->length();
8333 MOZ_ASSERT(n <= INT32_MAX,
8334 "Template objects are only created for int32 lengths");
8335
8336 using Fn = TypedArrayObject* (*)(JSContext*, HandleObject, int32_t length);
8337 OutOfLineCode* ool = oolCallVM<Fn, NewTypedArrayWithTemplateAndLength>(
8338 lir, ArgList(ImmGCPtr(templateObject), Imm32(n)),
8339 StoreRegisterTo(objReg));
8340
8341 TemplateObject templateObj(templateObject);
8342 masm.createGCObject(objReg, tempReg, templateObj, initialHeap, ool->entry());
8343
8344 masm.initTypedArraySlots(objReg, tempReg, lengthReg, liveRegs, ool->entry(),
8345 ttemplate, MacroAssembler::TypedArrayLength::Fixed);
8346
8347 masm.bind(ool->rejoin());
8348 }
8349
8350 void CodeGenerator::visitNewTypedArrayDynamicLength(
8351 LNewTypedArrayDynamicLength* lir) {
8352 Register lengthReg = ToRegister(lir->length());
8353 Register objReg = ToRegister(lir->output());
8354 Register tempReg = ToRegister(lir->temp0());
8355 LiveRegisterSet liveRegs = liveVolatileRegs(lir);
8356
8357 JSObject* templateObject = lir->mir()->templateObject();
8358 gc::Heap initialHeap = lir->mir()->initialHeap();
8359
8360 auto* ttemplate = &templateObject->as<FixedLengthTypedArrayObject>();
8361
8362 using Fn = TypedArrayObject* (*)(JSContext*, HandleObject, int32_t length);
8363 OutOfLineCode* ool = oolCallVM<Fn, NewTypedArrayWithTemplateAndLength>(
8364 lir, ArgList(ImmGCPtr(templateObject), lengthReg),
8365 StoreRegisterTo(objReg));
8366
8367 // Volatile |lengthReg| is saved across the ABI call in |initTypedArraySlots|.
8368 MOZ_ASSERT_IF(lengthReg.volatile_(), liveRegs.has(lengthReg));
8369
8370 TemplateObject templateObj(templateObject);
8371 masm.createGCObject(objReg, tempReg, templateObj, initialHeap, ool->entry());
8372
8373 masm.initTypedArraySlots(objReg, tempReg, lengthReg, liveRegs, ool->entry(),
8374 ttemplate,
8375 MacroAssembler::TypedArrayLength::Dynamic);
8376
8377 masm.bind(ool->rejoin());
8378 }
8379
8380 void CodeGenerator::visitNewTypedArrayFromArray(LNewTypedArrayFromArray* lir) {
8381 pushArg(ToRegister(lir->array()));
8382 pushArg(ImmGCPtr(lir->mir()->templateObject()));
8383
8384 using Fn = TypedArrayObject* (*)(JSContext*, HandleObject, HandleObject);
8385 callVM<Fn, js::NewTypedArrayWithTemplateAndArray>(lir);
8386 }
8387
8388 void CodeGenerator::visitNewTypedArrayFromArrayBuffer(
8389 LNewTypedArrayFromArrayBuffer* lir) {
8390 pushArg(ToValue(lir->length()));
8391 pushArg(ToValue(lir->byteOffset()));
8392 pushArg(ToRegister(lir->arrayBuffer()));
8393 pushArg(ImmGCPtr(lir->mir()->templateObject()));
8394
8395 using Fn = TypedArrayObject* (*)(JSContext*, HandleObject, HandleObject,
8396 HandleValue, HandleValue);
8397 callVM<Fn, js::NewTypedArrayWithTemplateAndBuffer>(lir);
8398 }
8399
8400 void CodeGenerator::visitBindFunction(LBindFunction* lir) {
8401 Register target = ToRegister(lir->target());
8402 Register temp1 = ToRegister(lir->temp0());
8403 Register temp2 = ToRegister(lir->temp1());
8404
8405 // Try to allocate a new BoundFunctionObject we can pass to the VM function.
8406 // If this fails, we set temp1 to nullptr so we do the allocation in C++.
8407 TemplateObject templateObject(lir->mir()->templateObject());
8408 Label allocOk, allocFailed;
8409 masm.createGCObject(temp1, temp2, templateObject, gc::Heap::Default,
8410 &allocFailed);
8411 masm.jump(&allocOk);
8412
8413 masm.bind(&allocFailed);
8414 masm.movePtr(ImmWord(0), temp1);
8415
8416 masm.bind(&allocOk);
8417
8418 // Set temp2 to the address of the first argument on the stack.
8419 // Note that the Value slots used for arguments are currently aligned for a
8420 // JIT call, even though that's not strictly necessary for calling into C++.
8421 uint32_t argc = lir->mir()->numStackArgs();
8422 if (JitStackValueAlignment > 1) {
8423 argc = AlignBytes(argc, JitStackValueAlignment);
8424 }
8425 uint32_t unusedStack = UnusedStackBytesForCall(argc);
8426 masm.computeEffectiveAddress(Address(masm.getStackPointer(), unusedStack),
8427 temp2);
8428
8429 pushArg(temp1);
8430 pushArg(Imm32(lir->mir()->numStackArgs()));
8431 pushArg(temp2);
8432 pushArg(target);
8433
8434 using Fn = BoundFunctionObject* (*)(JSContext*, Handle<JSObject*>, Value*,
8435 uint32_t, Handle<BoundFunctionObject*>);
8436 callVM<Fn, js::BoundFunctionObject::functionBindImpl>(lir);
8437 }
8438
8439 void CodeGenerator::visitNewBoundFunction(LNewBoundFunction* lir) {
8440 Register output = ToRegister(lir->output());
8441 Register temp = ToRegister(lir->temp0());
8442
8443 JSObject* templateObj = lir->mir()->templateObj();
8444
8445 using Fn = BoundFunctionObject* (*)(JSContext*, Handle<BoundFunctionObject*>);
8446 OutOfLineCode* ool = oolCallVM<Fn, BoundFunctionObject::createWithTemplate>(
8447 lir, ArgList(ImmGCPtr(templateObj)), StoreRegisterTo(output));
8448
8449 TemplateObject templateObject(templateObj);
8450 masm.createGCObject(output, temp, templateObject, gc::Heap::Default,
8451 ool->entry());
8452
8453 masm.bind(ool->rejoin());
8454 }
8455
8456 void CodeGenerator::visitNewObjectVMCall(LNewObject* lir) {
8457 Register objReg = ToRegister(lir->output());
8458
8459 MOZ_ASSERT(!lir->isCall());
8460 saveLive(lir);
8461
8462 JSObject* templateObject = lir->mir()->templateObject();
8463
8464 // If we're making a new object with a class prototype (that is, an object
8465 // that derives its class from its prototype instead of being
8466 // PlainObject::class_'d) from self-hosted code, we need a different init
8467 // function.
8468 switch (lir->mir()->mode()) {
8469 case MNewObject::ObjectLiteral: {
8470 MOZ_ASSERT(!templateObject);
8471 pushArg(ImmPtr(lir->mir()->resumePoint()->pc()));
8472 pushArg(ImmGCPtr(lir->mir()->block()->info().script()));
8473
8474 using Fn = JSObject* (*)(JSContext*, HandleScript, const jsbytecode* pc);
8475 callVM<Fn, NewObjectOperation>(lir);
8476 break;
8477 }
8478 case MNewObject::ObjectCreate: {
8479 pushArg(ImmGCPtr(templateObject));
8480
8481 using Fn = PlainObject* (*)(JSContext*, Handle<PlainObject*>);
8482 callVM<Fn, ObjectCreateWithTemplate>(lir);
8483 break;
8484 }
8485 }
8486
8487 masm.storeCallPointerResult(objReg);
8488
8489 MOZ_ASSERT(!lir->safepoint()->liveRegs().has(objReg));
8490 restoreLive(lir);
8491 }
8492
8493 static bool ShouldInitFixedSlots(MIRGenerator* gen, LNewPlainObject* lir,
8494 const Shape* shape, uint32_t nfixed) {
8495 // Look for StoreFixedSlot instructions following an object allocation
8496 // that write to this object before a GC is triggered or this object is
8497 // passed to a VM call. If all fixed slots will be initialized, the
8498 // allocation code doesn't need to set the slots to |undefined|.
8499
8500 if (nfixed == 0) {
8501 return false;
8502 }
8503
8504 #ifdef DEBUG
8505 // The bailAfter testing function can trigger a bailout between allocating the
8506 // object and initializing the slots.
8507 if (gen->options.ionBailAfterEnabled()) {
8508 return true;
8509 }
8510 #endif
8511
8512 // Keep track of the fixed slots that are initialized. initializedSlots is
8513 // a bit mask with a bit for each slot.
8514 MOZ_ASSERT(nfixed <= NativeObject::MAX_FIXED_SLOTS);
8515 static_assert(NativeObject::MAX_FIXED_SLOTS <= 32,
8516 "Slot bits must fit in 32 bits");
8517 uint32_t initializedSlots = 0;
8518 uint32_t numInitialized = 0;
8519
8520 MInstruction* allocMir = lir->mir();
8521 MBasicBlock* block = allocMir->block();
8522
8523 // Skip the allocation instruction.
8524 MInstructionIterator iter = block->begin(allocMir);
8525 MOZ_ASSERT(*iter == allocMir);
8526 iter++;
8527
8528 // Handle the leading shape guard, if present.
8529 for (; iter != block->end(); iter++) {
8530 if (iter->isConstant()) {
8531 // This instruction won't trigger a GC or read object slots.
8532 continue;
8533 }
8534 if (iter->isGuardShape()) {
8535 auto* guard = iter->toGuardShape();
8536 if (guard->object() != allocMir || guard->shape() != shape) {
8537 return true;
8538 }
8539 allocMir = guard;
8540 iter++;
8541 }
8542 break;
8543 }
8544
8545 for (; iter != block->end(); iter++) {
8546 if (iter->isConstant() || iter->isPostWriteBarrier()) {
8547 // These instructions won't trigger a GC or read object slots.
8548 continue;
8549 }
8550
8551 if (iter->isStoreFixedSlot()) {
8552 MStoreFixedSlot* store = iter->toStoreFixedSlot();
8553 if (store->object() != allocMir) {
8554 return true;
8555 }
8556
8557 // We may not initialize this object slot on allocation, so the
8558 // pre-barrier could read uninitialized memory. Simply disable
8559 // the barrier for this store: the object was just initialized
8560 // so the barrier is not necessary.
8561 store->setNeedsBarrier(false);
8562
8563 uint32_t slot = store->slot();
8564 MOZ_ASSERT(slot < nfixed);
8565 if ((initializedSlots & (1 << slot)) == 0) {
8566 numInitialized++;
8567 initializedSlots |= (1 << slot);
8568
8569 if (numInitialized == nfixed) {
8570 // All fixed slots will be initialized.
8571 MOZ_ASSERT(mozilla::CountPopulation32(initializedSlots) == nfixed);
8572 return false;
8573 }
8574 }
8575 continue;
8576 }
8577
8578 // Unhandled instruction, assume it bails or reads object slots.
8579 return true;
8580 }
8581
8582 MOZ_CRASH("Shouldn't get here");
8583 }
8584
8585 void CodeGenerator::visitNewObject(LNewObject* lir) {
8586 Register objReg = ToRegister(lir->output());
8587 Register tempReg = ToRegister(lir->temp0());
8588
8589 if (lir->mir()->isVMCall()) {
8590 visitNewObjectVMCall(lir);
8591 return;
8592 }
8593
8594 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
8595 visitNewObjectVMCall(lir);
8596 masm.jump(ool.rejoin());
8597 });
8598 addOutOfLineCode(ool, lir->mir());
8599
8600 TemplateObject templateObject(lir->mir()->templateObject());
8601
8602 masm.createGCObject(objReg, tempReg, templateObject,
8603 lir->mir()->initialHeap(), ool->entry());
8604
8605 masm.bind(ool->rejoin());
8606 }
8607
8608 void CodeGenerator::visitNewPlainObject(LNewPlainObject* lir) {
8609 Register objReg = ToRegister(lir->output());
8610 Register temp0Reg = ToRegister(lir->temp0());
8611 Register temp1Reg = ToRegister(lir->temp1());
8612 Register shapeReg = ToRegister(lir->temp2());
8613
8614 auto* mir = lir->mir();
8615 const Shape* shape = mir->shape();
8616 gc::Heap initialHeap = mir->initialHeap();
8617 gc::AllocKind allocKind = mir->allocKind();
8618
8619 using Fn =
8620 JSObject* (*)(JSContext*, Handle<SharedShape*>, gc::AllocKind, gc::Heap);
8621 OutOfLineCode* ool = oolCallVM<Fn, NewPlainObjectOptimizedFallback>(
8622 lir,
8623 ArgList(ImmGCPtr(shape), Imm32(int32_t(allocKind)),
8624 Imm32(int32_t(initialHeap))),
8625 StoreRegisterTo(objReg));
8626
8627 bool initContents =
8628 ShouldInitFixedSlots(gen, lir, shape, mir->numFixedSlots());
8629
8630 masm.movePtr(ImmGCPtr(shape), shapeReg);
8631 masm.createPlainGCObject(
8632 objReg, shapeReg, temp0Reg, temp1Reg, mir->numFixedSlots(),
8633 mir->numDynamicSlots(), allocKind, initialHeap, ool->entry(),
8634 AllocSiteInput(gc::CatchAllAllocSite::Optimized), initContents);
8635
8636 #ifdef DEBUG
8637 // ShouldInitFixedSlots expects that the leading GuardShape will never fail,
8638 // so ensure the newly created object has the correct shape. Should the guard
8639 // ever fail, we may end up with uninitialized fixed slots, which can confuse
8640 // the GC.
8641 Label ok;
8642 masm.branchTestObjShape(Assembler::Equal, objReg, shape, temp0Reg, objReg,
8643 &ok);
8644 masm.assumeUnreachable("Newly created object has the correct shape");
8645 masm.bind(&ok);
8646 #endif
8647
8648 masm.bind(ool->rejoin());
8649 }
8650
8651 void CodeGenerator::visitNewArrayObject(LNewArrayObject* lir) {
8652 Register objReg = ToRegister(lir->output());
8653 Register temp0Reg = ToRegister(lir->temp0());
8654 Register shapeReg = ToRegister(lir->temp1());
8655
8656 auto* mir = lir->mir();
8657 uint32_t arrayLength = mir->length();
8658
8659 gc::AllocKind allocKind = GuessArrayGCKind(arrayLength);
8660 MOZ_ASSERT(gc::GetObjectFinalizeKind(&ArrayObject::class_) ==
8661 gc::FinalizeKind::None);
8662 MOZ_ASSERT(!IsFinalizedKind(allocKind));
8663
8664 uint32_t slotCount = GetGCKindSlots(allocKind);
8665 MOZ_ASSERT(slotCount >= ObjectElements::VALUES_PER_HEADER);
8666 uint32_t arrayCapacity = slotCount - ObjectElements::VALUES_PER_HEADER;
8667
8668 const Shape* shape = mir->shape();
8669
8670 NewObjectKind objectKind =
8671 mir->initialHeap() == gc::Heap::Tenured ? TenuredObject : GenericObject;
8672
8673 using Fn =
8674 ArrayObject* (*)(JSContext*, uint32_t, gc::AllocKind, NewObjectKind);
8675 OutOfLineCode* ool = oolCallVM<Fn, NewArrayObjectOptimizedFallback>(
8676 lir,
8677 ArgList(Imm32(arrayLength), Imm32(int32_t(allocKind)), Imm32(objectKind)),
8678 StoreRegisterTo(objReg));
8679
8680 masm.movePtr(ImmPtr(shape), shapeReg);
8681 masm.createArrayWithFixedElements(
8682 objReg, shapeReg, temp0Reg, InvalidReg, arrayLength, arrayCapacity, 0, 0,
8683 allocKind, mir->initialHeap(), ool->entry(),
8684 AllocSiteInput(gc::CatchAllAllocSite::Optimized));
8685 masm.bind(ool->rejoin());
8686 }
8687
8688 void CodeGenerator::visitNewNamedLambdaObject(LNewNamedLambdaObject* lir) {
8689 Register objReg = ToRegister(lir->output());
8690 Register tempReg = ToRegister(lir->temp0());
8691 const CompileInfo& info = lir->mir()->block()->info();
8692 gc::Heap heap = lir->mir()->initialHeap();
8693
8694 using Fn = js::NamedLambdaObject* (*)(JSContext*, HandleFunction, gc::Heap);
8695 OutOfLineCode* ool = oolCallVM<Fn, NamedLambdaObject::createWithoutEnclosing>(
8696 lir, ArgList(info.funMaybeLazy(), Imm32(uint32_t(heap))),
8697 StoreRegisterTo(objReg));
8698
8699 TemplateObject templateObject(lir->mir()->templateObj());
8700
8701 masm.createGCObject(objReg, tempReg, templateObject, heap, ool->entry(),
8702 /* initContents = */ true,
8703 AllocSiteInput(gc::CatchAllAllocSite::Optimized));
8704
8705 masm.bind(ool->rejoin());
8706 }
8707
8708 void CodeGenerator::visitNewCallObject(LNewCallObject* lir) {
8709 Register objReg = ToRegister(lir->output());
8710 Register tempReg = ToRegister(lir->temp0());
8711
8712 CallObject* templateObj = lir->mir()->templateObject();
8713 gc::Heap heap = lir->mir()->initialHeap();
8714
8715 // todo: should get a specialized fallback that passes site
8716 using Fn = CallObject* (*)(JSContext*, Handle<SharedShape*>, gc::Heap);
8717 OutOfLineCode* ool = oolCallVM<Fn, CallObject::createWithShape>(
8718 lir, ArgList(ImmGCPtr(templateObj->sharedShape()), Imm32(uint32_t(heap))),
8719 StoreRegisterTo(objReg));
8720
8721 // Inline call object creation, using the OOL path only for tricky cases.
8722 TemplateObject templateObject(templateObj);
8723
8724 masm.createGCObject(objReg, tempReg, templateObject, heap, ool->entry(),
8725 /* initContents = */ true,
8726 AllocSiteInput(gc::CatchAllAllocSite::Optimized));
8727
8728 masm.bind(ool->rejoin());
8729 }
8730
8731 void CodeGenerator::visitNewMapObject(LNewMapObject* lir) {
8732 Register output = ToRegister(lir->output());
8733 Register temp = ToRegister(lir->temp0());
8734
8735 // Note: pass nullptr for |proto| to use |Map.prototype|.
8736 using Fn = MapObject* (*)(JSContext*, HandleObject);
8737 auto* ool = oolCallVM<Fn, MapObject::create>(lir, ArgList(ImmPtr(nullptr)),
8738 StoreRegisterTo(output));
8739
8740 TemplateObject templateObject(lir->mir()->templateObject());
8741 masm.createGCObject(output, temp, templateObject, gc::Heap::Default,
8742 ool->entry());
8743 masm.bind(ool->rejoin());
8744 }
8745
8746 void CodeGenerator::visitNewSetObject(LNewSetObject* lir) {
8747 Register output = ToRegister(lir->output());
8748 Register temp = ToRegister(lir->temp0());
8749
8750 // Note: pass nullptr for |proto| to use |Set.prototype|.
8751 using Fn = SetObject* (*)(JSContext*, HandleObject);
8752 auto* ool = oolCallVM<Fn, SetObject::create>(lir, ArgList(ImmPtr(nullptr)),
8753 StoreRegisterTo(output));
8754
8755 TemplateObject templateObject(lir->mir()->templateObject());
8756 masm.createGCObject(output, temp, templateObject, gc::Heap::Default,
8757 ool->entry());
8758 masm.bind(ool->rejoin());
8759 }
8760
8761 void CodeGenerator::visitNewMapObjectFromIterable(
8762 LNewMapObjectFromIterable* lir) {
8763 ValueOperand iterable = ToValue(lir->iterable());
8764 Register output = ToRegister(lir->output());
8765 Register temp1 = ToRegister(lir->temp0());
8766 Register temp2 = ToRegister(lir->temp1());
8767
8768 // Allocate a new MapObject. If this fails we pass nullptr for
8769 // allocatedFromJit.
8770 Label failedAlloc, vmCall, done;
8771 TemplateObject templateObject(lir->mir()->templateObject());
8772 masm.createGCObject(temp1, temp2, templateObject, gc::Heap::Default,
8773 &failedAlloc);
8774
8775 // We're done if |iterable| is null or undefined.
8776 masm.branchIfNotNullOrUndefined(iterable, &vmCall);
8777 masm.movePtr(temp1, output);
8778 masm.jump(&done);
8779
8780 masm.bind(&failedAlloc);
8781 masm.movePtr(ImmPtr(nullptr), temp1);
8782
8783 masm.bind(&vmCall);
8784
8785 pushArg(temp1); // allocatedFromJit
8786 pushArg(iterable);
8787 pushArg(ImmPtr(nullptr)); // proto
8788
8789 using Fn = MapObject* (*)(JSContext*, Handle<JSObject*>, Handle<Value>,
8790 Handle<MapObject*>);
8791 callVM<Fn, MapObject::createFromIterable>(lir);
8792
8793 masm.bind(&done);
8794 }
8795
8796 void CodeGenerator::visitNewSetObjectFromIterable(
8797 LNewSetObjectFromIterable* lir) {
8798 ValueOperand iterable = ToValue(lir->iterable());
8799 Register output = ToRegister(lir->output());
8800 Register temp1 = ToRegister(lir->temp0());
8801 Register temp2 = ToRegister(lir->temp1());
8802
8803 // Allocate a new SetObject. If this fails we pass nullptr for
8804 // allocatedFromJit.
8805 Label failedAlloc, vmCall, done;
8806 TemplateObject templateObject(lir->mir()->templateObject());
8807 masm.createGCObject(temp1, temp2, templateObject, gc::Heap::Default,
8808 &failedAlloc);
8809
8810 // We're done if |iterable| is null or undefined.
8811 masm.branchIfNotNullOrUndefined(iterable, &vmCall);
8812 masm.movePtr(temp1, output);
8813 masm.jump(&done);
8814
8815 masm.bind(&failedAlloc);
8816 masm.movePtr(ImmPtr(nullptr), temp1);
8817
8818 masm.bind(&vmCall);
8819
8820 pushArg(temp1); // allocatedFromJit
8821 pushArg(iterable);
8822 pushArg(ImmPtr(nullptr)); // proto
8823
8824 using Fn = SetObject* (*)(JSContext*, Handle<JSObject*>, Handle<Value>,
8825 Handle<SetObject*>);
8826 callVM<Fn, SetObject::createFromIterable>(lir);
8827
8828 masm.bind(&done);
8829 }
8830
8831 void CodeGenerator::visitNewStringObject(LNewStringObject* lir) {
8832 Register input = ToRegister(lir->input());
8833 Register output = ToRegister(lir->output());
8834 Register temp = ToRegister(lir->temp0());
8835
8836 StringObject* templateObj = lir->mir()->templateObj();
8837
8838 using Fn = JSObject* (*)(JSContext*, HandleString);
8839 OutOfLineCode* ool = oolCallVM<Fn, NewStringObject>(lir, ArgList(input),
8840 StoreRegisterTo(output));
8841
8842 TemplateObject templateObject(templateObj);
8843 masm.createGCObject(output, temp, templateObject, gc::Heap::Default,
8844 ool->entry());
8845
8846 masm.loadStringLength(input, temp);
8847
8848 masm.storeValue(JSVAL_TYPE_STRING, input,
8849 Address(output, StringObject::offsetOfPrimitiveValue()));
8850 masm.storeValue(JSVAL_TYPE_INT32, temp,
8851 Address(output, StringObject::offsetOfLength()));
8852
8853 masm.bind(ool->rejoin());
8854 }
8855
8856 void CodeGenerator::visitInitElemGetterSetter(LInitElemGetterSetter* lir) {
8857 Register obj = ToRegister(lir->object());
8858 Register value = ToRegister(lir->value());
8859
8860 pushArg(value);
8861 pushArg(ToValue(lir->id()));
8862 pushArg(obj);
8863 pushArg(ImmPtr(lir->mir()->resumePoint()->pc()));
8864
8865 using Fn = bool (*)(JSContext*, jsbytecode*, HandleObject, HandleValue,
8866 HandleObject);
8867 callVM<Fn, InitElemGetterSetterOperation>(lir);
8868 }
8869
8870 void CodeGenerator::visitMutateProto(LMutateProto* lir) {
8871 Register objReg = ToRegister(lir->object());
8872
8873 pushArg(ToValue(lir->value()));
8874 pushArg(objReg);
8875
8876 using Fn =
8877 bool (*)(JSContext* cx, Handle<PlainObject*> obj, HandleValue value);
8878 callVM<Fn, MutatePrototype>(lir);
8879 }
8880
8881 void CodeGenerator::visitInitPropGetterSetter(LInitPropGetterSetter* lir) {
8882 Register obj = ToRegister(lir->object());
8883 Register value = ToRegister(lir->value());
8884
8885 pushArg(value);
8886 pushArg(ImmGCPtr(lir->mir()->name()));
8887 pushArg(obj);
8888 pushArg(ImmPtr(lir->mir()->resumePoint()->pc()));
8889
8890 using Fn = bool (*)(JSContext*, jsbytecode*, HandleObject,
8891 Handle<PropertyName*>, HandleObject);
8892 callVM<Fn, InitPropGetterSetterOperation>(lir);
8893 }
8894
8895 void CodeGenerator::visitCreateThis(LCreateThis* lir) {
8896 const LAllocation* callee = lir->callee();
8897 const LAllocation* newTarget = lir->newTarget();
8898
8899 if (newTarget->isConstant()) {
8900 pushArg(ImmGCPtr(&newTarget->toConstant()->toObject()));
8901 } else {
8902 pushArg(ToRegister(newTarget));
8903 }
8904
8905 if (callee->isConstant()) {
8906 pushArg(ImmGCPtr(&callee->toConstant()->toObject()));
8907 } else {
8908 pushArg(ToRegister(callee));
8909 }
8910
8911 using Fn = bool (*)(JSContext* cx, HandleObject callee,
8912 HandleObject newTarget, MutableHandleValue rval);
8913 callVM<Fn, jit::CreateThisFromIon>(lir);
8914 }
8915
8916 void CodeGenerator::visitCreateArgumentsObject(LCreateArgumentsObject* lir) {
8917 // This should be getting constructed in the first block only, and not any OSR
8918 // entry blocks.
8919 MOZ_ASSERT(lir->mir()->block()->id() == 0);
8920
8921 Register callObj = ToRegister(lir->callObject());
8922 Register temp0 = ToRegister(lir->temp0());
8923 Label done;
8924
8925 if (ArgumentsObject* templateObj = lir->mir()->templateObject()) {
8926 Register objTemp = ToRegister(lir->temp1());
8927 Register cxTemp = ToRegister(lir->temp2());
8928
8929 masm.Push(callObj);
8930
8931 // Try to allocate an arguments object. This will leave the reserved
8932 // slots uninitialized, so it's important we don't GC until we
8933 // initialize these slots in ArgumentsObject::finishForIonPure.
8934 Label failure;
8935 TemplateObject templateObject(templateObj);
8936 masm.createGCObject(objTemp, temp0, templateObject, gc::Heap::Default,
8937 &failure,
8938 /* initContents = */ false);
8939
8940 masm.moveStackPtrTo(temp0);
8941 masm.addPtr(Imm32(masm.framePushed()), temp0);
8942
8943 using Fn = ArgumentsObject* (*)(JSContext* cx, jit::JitFrameLayout* frame,
8944 JSObject* scopeChain, ArgumentsObject* obj);
8945 masm.setupAlignedABICall();
8946 masm.loadJSContext(cxTemp);
8947 masm.passABIArg(cxTemp);
8948 masm.passABIArg(temp0);
8949 masm.passABIArg(callObj);
8950 masm.passABIArg(objTemp);
8951
8952 masm.callWithABI<Fn, ArgumentsObject::finishForIonPure>();
8953 masm.branchTestPtr(Assembler::Zero, ReturnReg, ReturnReg, &failure);
8954
8955 // Discard saved callObj on the stack.
8956 masm.addToStackPtr(Imm32(sizeof(uintptr_t)));
8957 masm.jump(&done);
8958
8959 masm.bind(&failure);
8960 masm.Pop(callObj);
8961 }
8962
8963 masm.moveStackPtrTo(temp0);
8964 masm.addPtr(Imm32(frameSize()), temp0);
8965
8966 pushArg(callObj);
8967 pushArg(temp0);
8968
8969 using Fn = ArgumentsObject* (*)(JSContext*, JitFrameLayout*, HandleObject);
8970 callVM<Fn, ArgumentsObject::createForIon>(lir);
8971
8972 masm.bind(&done);
8973 }
8974
8975 void CodeGenerator::visitCreateInlinedArgumentsObject(
8976 LCreateInlinedArgumentsObject* lir) {
8977 Register callObj = ToRegister(lir->getCallObject());
8978 Register callee = ToRegister(lir->getCallee());
8979 Register argsAddress = ToRegister(lir->temp1());
8980 Register argsObj = ToRegister(lir->temp2());
8981
8982 // TODO: Do we have to worry about alignment here?
8983
8984 // Create a contiguous array of values for ArgumentsObject::create
8985 // by pushing the arguments onto the stack in reverse order.
8986 uint32_t argc = lir->mir()->numActuals();
8987 for (uint32_t i = 0; i < argc; i++) {
8988 uint32_t argNum = argc - i - 1;
8989 uint32_t index = LCreateInlinedArgumentsObject::ArgIndex(argNum);
8990 ConstantOrRegister arg =
8991 toConstantOrRegister(lir, index, lir->mir()->getArg(argNum)->type());
8992 masm.Push(arg);
8993 }
8994 masm.moveStackPtrTo(argsAddress);
8995
8996 Label done;
8997 if (ArgumentsObject* templateObj = lir->mir()->templateObject()) {
8998 LiveRegisterSet liveRegs;
8999 liveRegs.add(callObj);
9000 liveRegs.add(callee);
9001
9002 masm.PushRegsInMask(liveRegs);
9003
9004 // We are free to clobber all registers, as LCreateInlinedArgumentsObject is
9005 // a call instruction.
9006 AllocatableGeneralRegisterSet allRegs(GeneralRegisterSet::All());
9007 allRegs.take(callObj);
9008 allRegs.take(callee);
9009 allRegs.take(argsObj);
9010 allRegs.take(argsAddress);
9011
9012 Register temp3 = allRegs.takeAny();
9013 Register temp4 = allRegs.takeAny();
9014
9015 // Try to allocate an arguments object. This will leave the reserved slots
9016 // uninitialized, so it's important we don't GC until we initialize these
9017 // slots in ArgumentsObject::finishForIonPure.
9018 Label failure;
9019 TemplateObject templateObject(templateObj);
9020 masm.createGCObject(argsObj, temp3, templateObject, gc::Heap::Default,
9021 &failure,
9022 /* initContents = */ false);
9023
9024 Register numActuals = temp3;
9025 masm.move32(Imm32(argc), numActuals);
9026
9027 using Fn = ArgumentsObject* (*)(JSContext*, JSObject*, JSFunction*, Value*,
9028 uint32_t, ArgumentsObject*);
9029 masm.setupAlignedABICall();
9030 masm.loadJSContext(temp4);
9031 masm.passABIArg(temp4);
9032 masm.passABIArg(callObj);
9033 masm.passABIArg(callee);
9034 masm.passABIArg(argsAddress);
9035 masm.passABIArg(numActuals);
9036 masm.passABIArg(argsObj);
9037
9038 masm.callWithABI<Fn, ArgumentsObject::finishInlineForIonPure>();
9039 masm.branchTestPtr(Assembler::Zero, ReturnReg, ReturnReg, &failure);
9040
9041 // Discard saved callObj, callee, and values array on the stack.
9042 masm.addToStackPtr(
9043 Imm32(MacroAssembler::PushRegsInMaskSizeInBytes(liveRegs) +
9044 argc * sizeof(Value)));
9045 masm.jump(&done);
9046
9047 masm.bind(&failure);
9048 masm.PopRegsInMask(liveRegs);
9049
9050 // Reload argsAddress because it may have been overridden.
9051 masm.moveStackPtrTo(argsAddress);
9052 }
9053
9054 pushArg(Imm32(argc));
9055 pushArg(callObj);
9056 pushArg(callee);
9057 pushArg(argsAddress);
9058
9059 using Fn = ArgumentsObject* (*)(JSContext*, Value*, HandleFunction,
9060 HandleObject, uint32_t);
9061 callVM<Fn, ArgumentsObject::createForInlinedIon>(lir);
9062
9063 // Discard the array of values.
9064 masm.freeStack(argc * sizeof(Value));
9065
9066 masm.bind(&done);
9067 }
9068
9069 template <class GetInlinedArgument>
9070 void CodeGenerator::emitGetInlinedArgument(GetInlinedArgument* lir,
9071 Register index,
9072 ValueOperand output) {
9073 uint32_t numActuals = lir->mir()->numActuals();
9074 MOZ_ASSERT(numActuals <= ArgumentsObject::MaxInlinedArgs);
9075
9076 // The index has already been bounds-checked, so the code we
9077 // generate here should be unreachable. We can end up in this
9078 // situation in self-hosted code using GetArgument(), or in a
9079 // monomorphically inlined function if we've inlined some CacheIR
9080 // that was created for a different caller.
9081 if (numActuals == 0) {
9082 masm.assumeUnreachable("LGetInlinedArgument: invalid index");
9083 return;
9084 }
9085
9086 // Check the first n-1 possible indices.
9087 Label done;
9088 for (uint32_t i = 0; i < numActuals - 1; i++) {
9089 Label skip;
9090 ConstantOrRegister arg = toConstantOrRegister(
9091 lir, GetInlinedArgument::ArgIndex(i), lir->mir()->getArg(i)->type());
9092 masm.branch32(Assembler::NotEqual, index, Imm32(i), &skip);
9093 masm.moveValue(arg, output);
9094
9095 masm.jump(&done);
9096 masm.bind(&skip);
9097 }
9098
9099 #ifdef DEBUG
9100 Label skip;
9101 masm.branch32(Assembler::Equal, index, Imm32(numActuals - 1), &skip);
9102 masm.assumeUnreachable("LGetInlinedArgument: invalid index");
9103 masm.bind(&skip);
9104 #endif
9105
9106 // The index has already been bounds-checked, so load the last argument.
9107 uint32_t lastIdx = numActuals - 1;
9108 ConstantOrRegister arg =
9109 toConstantOrRegister(lir, GetInlinedArgument::ArgIndex(lastIdx),
9110 lir->mir()->getArg(lastIdx)->type());
9111 masm.moveValue(arg, output);
9112 masm.bind(&done);
9113 }
9114
9115 void CodeGenerator::visitGetInlinedArgument(LGetInlinedArgument* lir) {
9116 Register index = ToRegister(lir->getIndex());
9117 ValueOperand output = ToOutValue(lir);
9118
9119 emitGetInlinedArgument(lir, index, output);
9120 }
9121
9122 void CodeGenerator::visitGetInlinedArgumentHole(LGetInlinedArgumentHole* lir) {
9123 Register index = ToRegister(lir->getIndex());
9124 ValueOperand output = ToOutValue(lir);
9125
9126 uint32_t numActuals = lir->mir()->numActuals();
9127
9128 if (numActuals == 0) {
9129 bailoutCmp32(Assembler::LessThan, index, Imm32(0), lir->snapshot());
9130 masm.moveValue(UndefinedValue(), output);
9131 return;
9132 }
9133
9134 Label outOfBounds, done;
9135 masm.branch32(Assembler::AboveOrEqual, index, Imm32(numActuals),
9136 &outOfBounds);
9137
9138 emitGetInlinedArgument(lir, index, output);
9139 masm.jump(&done);
9140
9141 masm.bind(&outOfBounds);
9142 bailoutCmp32(Assembler::LessThan, index, Imm32(0), lir->snapshot());
9143 masm.moveValue(UndefinedValue(), output);
9144
9145 masm.bind(&done);
9146 }
9147
9148 void CodeGenerator::visitGetArgumentsObjectArg(LGetArgumentsObjectArg* lir) {
9149 Register temp = ToRegister(lir->temp0());
9150 Register argsObj = ToRegister(lir->argsObject());
9151 ValueOperand out = ToOutValue(lir);
9152
9153 masm.loadPrivate(Address(argsObj, ArgumentsObject::getDataSlotOffset()),
9154 temp);
9155 Address argAddr(temp, ArgumentsData::offsetOfArgs() +
9156 lir->mir()->argno() * sizeof(Value));
9157 masm.loadValue(argAddr, out);
9158 #ifdef DEBUG
9159 Label success;
9160 masm.branchTestMagic(Assembler::NotEqual, out, &success);
9161 masm.assumeUnreachable(
9162 "Result from ArgumentObject shouldn't be JSVAL_TYPE_MAGIC.");
9163 masm.bind(&success);
9164 #endif
9165 }
9166
9167 void CodeGenerator::visitSetArgumentsObjectArg(LSetArgumentsObjectArg* lir) {
9168 Register temp = ToRegister(lir->temp0());
9169 Register argsObj = ToRegister(lir->argsObject());
9170 ValueOperand value = ToValue(lir->value());
9171
9172 masm.loadPrivate(Address(argsObj, ArgumentsObject::getDataSlotOffset()),
9173 temp);
9174 Address argAddr(temp, ArgumentsData::offsetOfArgs() +
9175 lir->mir()->argno() * sizeof(Value));
9176 emitPreBarrier(argAddr);
9177 #ifdef DEBUG
9178 Label success;
9179 masm.branchTestMagic(Assembler::NotEqual, argAddr, &success);
9180 masm.assumeUnreachable(
9181 "Result in ArgumentObject shouldn't be JSVAL_TYPE_MAGIC.");
9182 masm.bind(&success);
9183 #endif
9184 masm.storeValue(value, argAddr);
9185 }
9186
9187 void CodeGenerator::visitLoadArgumentsObjectArg(LLoadArgumentsObjectArg* lir) {
9188 Register temp = ToRegister(lir->temp0());
9189 Register argsObj = ToRegister(lir->argsObject());
9190 Register index = ToRegister(lir->index());
9191 ValueOperand out = ToOutValue(lir);
9192
9193 Label bail;
9194 masm.loadArgumentsObjectElement(argsObj, index, out, temp, &bail);
9195 bailoutFrom(&bail, lir->snapshot());
9196 }
9197
9198 void CodeGenerator::visitLoadArgumentsObjectArgHole(
9199 LLoadArgumentsObjectArgHole* lir) {
9200 Register temp = ToRegister(lir->temp0());
9201 Register argsObj = ToRegister(lir->argsObject());
9202 Register index = ToRegister(lir->index());
9203 ValueOperand out = ToOutValue(lir);
9204
9205 Label bail;
9206 masm.loadArgumentsObjectElementHole(argsObj, index, out, temp, &bail);
9207 bailoutFrom(&bail, lir->snapshot());
9208 }
9209
9210 void CodeGenerator::visitInArgumentsObjectArg(LInArgumentsObjectArg* lir) {
9211 Register temp = ToRegister(lir->temp0());
9212 Register argsObj = ToRegister(lir->argsObject());
9213 Register index = ToRegister(lir->index());
9214 Register out = ToRegister(lir->output());
9215
9216 Label bail;
9217 masm.loadArgumentsObjectElementExists(argsObj, index, out, temp, &bail);
9218 bailoutFrom(&bail, lir->snapshot());
9219 }
9220
9221 void CodeGenerator::visitArgumentsObjectLength(LArgumentsObjectLength* lir) {
9222 Register argsObj = ToRegister(lir->argsObject());
9223 Register out = ToRegister(lir->output());
9224
9225 Label bail;
9226 masm.loadArgumentsObjectLength(argsObj, out, &bail);
9227 bailoutFrom(&bail, lir->snapshot());
9228 }
9229
9230 void CodeGenerator::visitArrayFromArgumentsObject(
9231 LArrayFromArgumentsObject* lir) {
9232 pushArg(ToRegister(lir->argsObject()));
9233
9234 using Fn = ArrayObject* (*)(JSContext*, Handle<ArgumentsObject*>);
9235 callVM<Fn, js::ArrayFromArgumentsObject>(lir);
9236 }
9237
9238 void CodeGenerator::visitGuardArgumentsObjectFlags(
9239 LGuardArgumentsObjectFlags* lir) {
9240 Register argsObj = ToRegister(lir->argsObject());
9241 Register temp = ToRegister(lir->temp0());
9242
9243 Label bail;
9244 masm.branchTestArgumentsObjectFlags(argsObj, temp, lir->mir()->flags(),
9245 Assembler::NonZero, &bail);
9246 bailoutFrom(&bail, lir->snapshot());
9247 }
9248
9249 void CodeGenerator::visitGuardObjectHasSameRealm(
9250 LGuardObjectHasSameRealm* lir) {
9251 Register obj = ToRegister(lir->object());
9252 Register temp = ToRegister(lir->temp0());
9253
9254 Label bail;
9255 masm.guardObjectHasSameRealm(obj, temp, &bail);
9256 bailoutFrom(&bail, lir->snapshot());
9257 }
9258
9259 void CodeGenerator::visitBoundFunctionNumArgs(LBoundFunctionNumArgs* lir) {
9260 Register obj = ToRegister(lir->object());
9261 Register output = ToRegister(lir->output());
9262
9263 masm.unboxInt32(Address(obj, BoundFunctionObject::offsetOfFlagsSlot()),
9264 output);
9265 masm.rshift32(Imm32(BoundFunctionObject::NumBoundArgsShift), output);
9266 }
9267
9268 void CodeGenerator::visitGuardBoundFunctionIsConstructor(
9269 LGuardBoundFunctionIsConstructor* lir) {
9270 Register obj = ToRegister(lir->object());
9271
9272 Label bail;
9273 Address flagsSlot(obj, BoundFunctionObject::offsetOfFlagsSlot());
9274 masm.branchTest32(Assembler::Zero, flagsSlot,
9275 Imm32(BoundFunctionObject::IsConstructorFlag), &bail);
9276 bailoutFrom(&bail, lir->snapshot());
9277 }
9278
9279 void CodeGenerator::visitReturnFromCtor(LReturnFromCtor* lir) {
9280 ValueOperand value = ToValue(lir->value());
9281 Register obj = ToRegister(lir->object());
9282 Register output = ToRegister(lir->output());
9283
9284 Label valueIsObject, end;
9285
9286 masm.branchTestObject(Assembler::Equal, value, &valueIsObject);
9287
9288 // Value is not an object. Return that other object.
9289 masm.movePtr(obj, output);
9290 masm.jump(&end);
9291
9292 // Value is an object. Return unbox(Value).
9293 masm.bind(&valueIsObject);
9294 Register payload = masm.extractObject(value, output);
9295 if (payload != output) {
9296 masm.movePtr(payload, output);
9297 }
9298
9299 masm.bind(&end);
9300 }
9301
9302 void CodeGenerator::visitBoxNonStrictThis(LBoxNonStrictThis* lir) {
9303 ValueOperand value = ToValue(lir->value());
9304 Register output = ToRegister(lir->output());
9305
9306 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
9307 Label notNullOrUndefined;
9308 {
9309 Label isNullOrUndefined;
9310 ScratchTagScope tag(masm, value);
9311 masm.splitTagForTest(value, tag);
9312 masm.branchTestUndefined(Assembler::Equal, tag, &isNullOrUndefined);
9313 masm.branchTestNull(Assembler::NotEqual, tag, &notNullOrUndefined);
9314 masm.bind(&isNullOrUndefined);
9315 masm.movePtr(ImmGCPtr(lir->mir()->globalThis()), output);
9316 masm.jump(ool.rejoin());
9317 }
9318
9319 masm.bind(&notNullOrUndefined);
9320
9321 saveLive(lir);
9322
9323 pushArg(value);
9324 using Fn = JSObject* (*)(JSContext*, HandleValue);
9325 callVM<Fn, BoxNonStrictThis>(lir);
9326
9327 StoreRegisterTo(output).generate(this);
9328 restoreLiveIgnore(lir, StoreRegisterTo(output).clobbered());
9329
9330 masm.jump(ool.rejoin());
9331 });
9332 addOutOfLineCode(ool, lir->mir());
9333
9334 masm.fallibleUnboxObject(value, output, ool->entry());
9335 masm.bind(ool->rejoin());
9336 }
9337
9338 void CodeGenerator::visitImplicitThis(LImplicitThis* lir) {
9339 Register env = ToRegister(lir->env());
9340 ValueOperand output = ToOutValue(lir);
9341
9342 using Fn = void (*)(JSContext*, HandleObject, MutableHandleValue);
9343 auto* ool = oolCallVM<Fn, ImplicitThisOperation>(lir, ArgList(env),
9344 StoreValueTo(output));
9345
9346 masm.computeImplicitThis(env, output, ool->entry());
9347 masm.bind(ool->rejoin());
9348 }
9349
9350 void CodeGenerator::visitArrayLength(LArrayLength* lir) {
9351 Register elements = ToRegister(lir->elements());
9352 Register output = ToRegister(lir->output());
9353
9354 Address length(elements, ObjectElements::offsetOfLength());
9355 masm.load32(length, output);
9356
9357 bool intact = hasSeenArrayExceedsInt32LengthFuseIntactAndDependencyNoted();
9358
9359 if (intact) {
9360 #ifdef DEBUG
9361 Label done;
9362 masm.branchTest32(Assembler::NotSigned, output, output, &done);
9363 masm.assumeUnreachable("Unexpected array with length > INT32_MAX");
9364 masm.bind(&done);
9365 #endif
9366 } else {
9367 // Bail out if the length doesn't fit in int32.
9368 bailoutTest32(Assembler::Signed, output, output, lir->snapshot());
9369 }
9370 }
9371
9372 static void SetLengthFromIndex(MacroAssembler& masm, const LAllocation* index,
9373 const Address& length) {
9374 if (index->isConstant()) {
9375 masm.store32(Imm32(ToInt32(index) + 1), length);
9376 } else {
9377 Register newLength = ToRegister(index);
9378 masm.add32(Imm32(1), newLength);
9379 masm.store32(newLength, length);
9380 masm.sub32(Imm32(1), newLength);
9381 }
9382 }
9383
9384 void CodeGenerator::visitSetArrayLength(LSetArrayLength* lir) {
9385 Address length(ToRegister(lir->elements()), ObjectElements::offsetOfLength());
9386 SetLengthFromIndex(masm, lir->index(), length);
9387 }
9388
9389 void CodeGenerator::visitFunctionLength(LFunctionLength* lir) {
9390 Register function = ToRegister(lir->function());
9391 Register output = ToRegister(lir->output());
9392
9393 Label bail;
9394
9395 // Get the JSFunction flags.
9396 masm.load32(Address(function, JSFunction::offsetOfFlagsAndArgCount()),
9397 output);
9398
9399 // Functions with a SelfHostedLazyScript must be compiled with the slow-path
9400 // before the function length is known. If the length was previously resolved,
9401 // the length property may be shadowed.
9402 masm.branchTest32(
9403 Assembler::NonZero, output,
9404 Imm32(FunctionFlags::SELFHOSTLAZY | FunctionFlags::RESOLVED_LENGTH),
9405 &bail);
9406
9407 masm.loadFunctionLength(function, output, output, &bail);
9408
9409 bailoutFrom(&bail, lir->snapshot());
9410 }
9411
9412 void CodeGenerator::visitFunctionName(LFunctionName* lir) {
9413 Register function = ToRegister(lir->function());
9414 Register output = ToRegister(lir->output());
9415
9416 Label bail;
9417
9418 const JSAtomState& names = gen->runtime->names();
9419 masm.loadFunctionName(function, output, ImmGCPtr(names.empty_), &bail);
9420
9421 bailoutFrom(&bail, lir->snapshot());
9422 }
9423
9424 template <class TableObject>
9425 static void TableIteratorLoadEntry(MacroAssembler&, Register, Register,
9426 Register);
9427
9428 template <>
9429 void TableIteratorLoadEntry<MapObject>(MacroAssembler& masm, Register iter,
9430 Register i, Register front) {
9431 masm.unboxObject(Address(iter, MapIteratorObject::offsetOfTarget()), front);
9432 masm.loadPrivate(Address(front, MapObject::offsetOfData()), front);
9433
9434 static_assert(MapObject::Table::offsetOfImplDataElement() == 0,
9435 "offsetof(Data, element) is 0");
9436 static_assert(MapObject::Table::sizeofImplData() == 24, "sizeof(Data) is 24");
9437 masm.mulBy3(i, i);
9438 masm.lshiftPtr(Imm32(3), i);
9439 masm.addPtr(i, front);
9440 }
9441
9442 template <>
9443 void TableIteratorLoadEntry<SetObject>(MacroAssembler& masm, Register iter,
9444 Register i, Register front) {
9445 masm.unboxObject(Address(iter, SetIteratorObject::offsetOfTarget()), front);
9446 masm.loadPrivate(Address(front, SetObject::offsetOfData()), front);
9447
9448 static_assert(SetObject::Table::offsetOfImplDataElement() == 0,
9449 "offsetof(Data, element) is 0");
9450 static_assert(SetObject::Table::sizeofImplData() == 16, "sizeof(Data) is 16");
9451 masm.lshiftPtr(Imm32(4), i);
9452 masm.addPtr(i, front);
9453 }
9454
9455 template <class TableObject>
9456 static void TableIteratorAdvance(MacroAssembler& masm, Register iter,
9457 Register front, Register dataLength,
9458 Register temp) {
9459 Register i = temp;
9460
9461 // Note: |count| and |index| are stored as PrivateUint32Value. We use add32
9462 // and store32 to change the payload.
9463 masm.add32(Imm32(1), Address(iter, TableIteratorObject::offsetOfCount()));
9464
9465 masm.unboxInt32(Address(iter, TableIteratorObject::offsetOfIndex()), i);
9466
9467 Label done, seek;
9468 masm.bind(&seek);
9469 masm.add32(Imm32(1), i);
9470 masm.branch32(Assembler::AboveOrEqual, i, dataLength, &done);
9471
9472 // We can add sizeof(Data) to |front| to select the next element, because
9473 // |front| and |mapOrSetObject.data[i]| point to the same location.
9474 static_assert(TableObject::Table::offsetOfImplDataElement() == 0,
9475 "offsetof(Data, element) is 0");
9476 masm.addPtr(Imm32(TableObject::Table::sizeofImplData()), front);
9477
9478 masm.branchTestMagic(Assembler::Equal,
9479 Address(front, TableObject::Table::offsetOfEntryKey()),
9480 JS_HASH_KEY_EMPTY, &seek);
9481
9482 masm.bind(&done);
9483 masm.store32(i, Address(iter, TableIteratorObject::offsetOfIndex()));
9484 }
9485
9486 // Corresponds to TableIteratorObject::finish.
9487 static void TableIteratorFinish(MacroAssembler& masm, Register iter,
9488 Register temp0, Register temp1) {
9489 Register next = temp0;
9490 Register prevp = temp1;
9491 masm.loadPrivate(Address(iter, TableIteratorObject::offsetOfNext()), next);
9492 masm.loadPrivate(Address(iter, TableIteratorObject::offsetOfPrevPtr()),
9493 prevp);
9494 masm.storePtr(next, Address(prevp, 0));
9495
9496 Label hasNoNext;
9497 masm.branchTestPtr(Assembler::Zero, next, next, &hasNoNext);
9498 masm.storePrivateValue(prevp,
9499 Address(next, TableIteratorObject::offsetOfPrevPtr()));
9500 masm.bind(&hasNoNext);
9501
9502 // Mark iterator inactive.
9503 Address targetAddr(iter, TableIteratorObject::offsetOfTarget());
9504 masm.guardedCallPreBarrier(targetAddr, MIRType::Value);
9505 masm.storeValue(UndefinedValue(), targetAddr);
9506 }
9507
9508 template <>
9509 void CodeGenerator::emitLoadIteratorValues<MapObject>(Register result,
9510 Register temp,
9511 Register front) {
9512 size_t elementsOffset = NativeObject::offsetOfFixedElements();
9513
9514 Address keyAddress(front, MapObject::Table::Entry::offsetOfKey());
9515 Address valueAddress(front, MapObject::Table::Entry::offsetOfValue());
9516 Address keyElemAddress(result, elementsOffset);
9517 Address valueElemAddress(result, elementsOffset + sizeof(Value));
9518 masm.guardedCallPreBarrier(keyElemAddress, MIRType::Value);
9519 masm.guardedCallPreBarrier(valueElemAddress, MIRType::Value);
9520 masm.storeValue(keyAddress, keyElemAddress, temp);
9521 masm.storeValue(valueAddress, valueElemAddress, temp);
9522
9523 Label emitBarrier, skipBarrier;
9524 masm.branchValueIsNurseryCell(Assembler::Equal, keyAddress, temp,
9525 &emitBarrier);
9526 masm.branchValueIsNurseryCell(Assembler::NotEqual, valueAddress, temp,
9527 &skipBarrier);
9528 {
9529 masm.bind(&emitBarrier);
9530 saveVolatile(temp);
9531 emitPostWriteBarrier(result);
9532 restoreVolatile(temp);
9533 }
9534 masm.bind(&skipBarrier);
9535 }
9536
9537 template <>
9538 void CodeGenerator::emitLoadIteratorValues<SetObject>(Register result,
9539 Register temp,
9540 Register front) {
9541 size_t elementsOffset = NativeObject::offsetOfFixedElements();
9542
9543 Address keyAddress(front, SetObject::Table::offsetOfEntryKey());
9544 Address keyElemAddress(result, elementsOffset);
9545 masm.guardedCallPreBarrier(keyElemAddress, MIRType::Value);
9546 masm.storeValue(keyAddress, keyElemAddress, temp);
9547
9548 Label skipBarrier;
9549 masm.branchValueIsNurseryCell(Assembler::NotEqual, keyAddress, temp,
9550 &skipBarrier);
9551 {
9552 saveVolatile(temp);
9553 emitPostWriteBarrier(result);
9554 restoreVolatile(temp);
9555 }
9556 masm.bind(&skipBarrier);
9557 }
9558
9559 template <class IteratorObject, class TableObject>
9560 void CodeGenerator::emitGetNextEntryForIterator(LGetNextEntryForIterator* lir) {
9561 Register iter = ToRegister(lir->iter());
9562 Register result = ToRegister(lir->result());
9563 Register temp = ToRegister(lir->temp0());
9564 Register dataLength = ToRegister(lir->temp1());
9565 Register front = ToRegister(lir->temp2());
9566 Register output = ToRegister(lir->output());
9567
9568 #ifdef DEBUG
9569 // Self-hosted code is responsible for ensuring GetNextEntryForIterator is
9570 // only called with the correct iterator class. Assert here all self-
9571 // hosted callers of GetNextEntryForIterator perform this class check.
9572 // No Spectre mitigations are needed because this is DEBUG-only code.
9573 Label success;
9574 masm.branchTestObjClassNoSpectreMitigations(
9575 Assembler::Equal, iter, &IteratorObject::class_, temp, &success);
9576 masm.assumeUnreachable("Iterator object should have the correct class.");
9577 masm.bind(&success);
9578 #endif
9579
9580 // If the iterator has no target, it's already done.
9581 // See TableIteratorObject::isActive.
9582 Label iterAlreadyDone, iterDone, done;
9583 masm.branchTestUndefined(Assembler::Equal,
9584 Address(iter, IteratorObject::offsetOfTarget()),
9585 &iterAlreadyDone);
9586
9587 // Load |iter->index| in |temp| and |iter->target->dataLength| in
9588 // |dataLength|. Both values are stored as PrivateUint32Value.
9589 masm.unboxInt32(Address(iter, IteratorObject::offsetOfIndex()), temp);
9590 masm.unboxObject(Address(iter, IteratorObject::offsetOfTarget()), dataLength);
9591 masm.unboxInt32(Address(dataLength, TableObject::offsetOfDataLength()),
9592 dataLength);
9593 masm.branch32(Assembler::AboveOrEqual, temp, dataLength, &iterDone);
9594 {
9595 TableIteratorLoadEntry<TableObject>(masm, iter, temp, front);
9596
9597 emitLoadIteratorValues<TableObject>(result, temp, front);
9598
9599 TableIteratorAdvance<TableObject>(masm, iter, front, dataLength, temp);
9600
9601 masm.move32(Imm32(0), output);
9602 masm.jump(&done);
9603 }
9604 {
9605 masm.bind(&iterDone);
9606 TableIteratorFinish(masm, iter, temp, dataLength);
9607
9608 masm.bind(&iterAlreadyDone);
9609 masm.move32(Imm32(1), output);
9610 }
9611 masm.bind(&done);
9612 }
9613
9614 void CodeGenerator::visitGetNextEntryForIterator(
9615 LGetNextEntryForIterator* lir) {
9616 if (lir->mir()->mode() == MGetNextEntryForIterator::Map) {
9617 emitGetNextEntryForIterator<MapIteratorObject, MapObject>(lir);
9618 } else {
9619 MOZ_ASSERT(lir->mir()->mode() == MGetNextEntryForIterator::Set);
9620 emitGetNextEntryForIterator<SetIteratorObject, SetObject>(lir);
9621 }
9622 }
9623
9624 // The point of these is to inform Ion of where these values already are; they
9625 // don't normally generate (much) code.
9626 void CodeGenerator::visitWasmRegisterPairResult(LWasmRegisterPairResult* lir) {}
9627 void CodeGenerator::visitWasmStackResult(LWasmStackResult* lir) {}
9628 void CodeGenerator::visitWasmStackResult64(LWasmStackResult64* lir) {}
9629
9630 void CodeGenerator::visitWasmStackResultArea(LWasmStackResultArea* lir) {
9631 LAllocation* output = lir->getDef(0)->output();
9632 MOZ_ASSERT(output->isStackArea());
9633 bool tempInit = false;
9634 for (auto iter = output->toStackArea()->results(); iter; iter.next()) {
9635 // Zero out ref stack results.
9636 if (iter.isWasmAnyRef()) {
9637 Register temp = ToRegister(lir->temp0());
9638 if (!tempInit) {
9639 masm.xorPtr(temp, temp);
9640 tempInit = true;
9641 }
9642 masm.storePtr(temp, ToAddress(iter.alloc()));
9643 }
9644 }
9645 }
9646
9647 void CodeGenerator::visitWasmRegisterResult(LWasmRegisterResult* lir) {
9648 #ifdef JS_64BIT
9649 if (MWasmRegisterResult* mir = lir->mir()) {
9650 if (mir->type() == MIRType::Int32) {
9651 masm.widenInt32(ToRegister(lir->output()));
9652 }
9653 }
9654 #endif
9655 }
9656
9657 void CodeGenerator::visitWasmCall(LWasmCall* lir) {
9658 const MWasmCallBase* callBase = lir->callBase();
9659 bool isReturnCall = lir->isReturnCall();
9660
9661 // If this call is in Wasm try code block, initialise a wasm::TryNote for this
9662 // call.
9663 bool inTry = callBase->inTry();
9664 if (inTry) {
9665 size_t tryNoteIndex = callBase->tryNoteIndex();
9666 wasm::TryNoteVector& tryNotes = masm.tryNotes();
9667 wasm::TryNote& tryNote = tryNotes[tryNoteIndex];
9668 tryNote.setTryBodyBegin(masm.currentOffset());
9669 }
9670
9671 MOZ_ASSERT((sizeof(wasm::Frame) + masm.framePushed()) % WasmStackAlignment ==
9672 0);
9673 static_assert(
9674 WasmStackAlignment >= ABIStackAlignment &&
9675 WasmStackAlignment % ABIStackAlignment == 0,
9676 "The wasm stack alignment should subsume the ABI-required alignment");
9677
9678 #ifdef DEBUG
9679 Label ok;
9680 masm.branchTestStackPtr(Assembler::Zero, Imm32(WasmStackAlignment - 1), &ok);
9681 masm.breakpoint();
9682 masm.bind(&ok);
9683 #endif
9684
9685 // LWasmCallBase::isCallPreserved() assumes that all MWasmCalls preserve the
9686 // instance and pinned regs. The only case where where we don't have to
9687 // reload the instance and pinned regs is when the callee preserves them.
9688 bool reloadRegs = true;
9689 bool switchRealm = true;
9690
9691 const wasm::CallSiteDesc& desc = callBase->desc();
9692 const wasm::CalleeDesc& callee = callBase->callee();
9693 CodeOffset retOffset;
9694 CodeOffset secondRetOffset;
9695 switch (callee.which()) {
9696 case wasm::CalleeDesc::Func:
9697 if (isReturnCall) {
9698 ReturnCallAdjustmentInfo retCallInfo(
9699 callBase->stackArgAreaSizeUnaligned(), inboundStackArgBytes_);
9700 masm.wasmReturnCall(desc, callee.funcIndex(), retCallInfo);
9701 // The rest of the method is unnecessary for a return call.
9702 return;
9703 }
9704 MOZ_ASSERT(!isReturnCall);
9705 retOffset = masm.call(desc, callee.funcIndex());
9706 reloadRegs = false;
9707 switchRealm = false;
9708 break;
9709 case wasm::CalleeDesc::Import:
9710 if (isReturnCall) {
9711 ReturnCallAdjustmentInfo retCallInfo(
9712 callBase->stackArgAreaSizeUnaligned(), inboundStackArgBytes_);
9713 masm.wasmReturnCallImport(desc, callee, retCallInfo);
9714 // The rest of the method is unnecessary for a return call.
9715 return;
9716 }
9717 MOZ_ASSERT(!isReturnCall);
9718 retOffset = masm.wasmCallImport(desc, callee);
9719 break;
9720 case wasm::CalleeDesc::AsmJSTable:
9721 retOffset = masm.asmCallIndirect(desc, callee);
9722 break;
9723 case wasm::CalleeDesc::WasmTable: {
9724 Label* boundsCheckFailed = nullptr;
9725 if (lir->needsBoundsCheck()) {
9726 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
9727 masm.wasmTrap(wasm::Trap::OutOfBounds, desc.toTrapSiteDesc());
9728 });
9729 if (lir->isCatchable()) {
9730 addOutOfLineCode(ool, lir->mirCatchable());
9731 } else if (isReturnCall) {
9732 addOutOfLineCode(ool, lir->mirReturnCall());
9733 } else {
9734 addOutOfLineCode(ool, lir->mirUncatchable());
9735 }
9736 boundsCheckFailed = ool->entry();
9737 }
9738 Label* nullCheckFailed = nullptr;
9739 #ifndef WASM_HAS_HEAPREG
9740 {
9741 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
9742 masm.wasmTrap(wasm::Trap::IndirectCallToNull, desc.toTrapSiteDesc());
9743 });
9744 if (lir->isCatchable()) {
9745 addOutOfLineCode(ool, lir->mirCatchable());
9746 } else if (isReturnCall) {
9747 addOutOfLineCode(ool, lir->mirReturnCall());
9748 } else {
9749 addOutOfLineCode(ool, lir->mirUncatchable());
9750 }
9751 nullCheckFailed = ool->entry();
9752 }
9753 #endif
9754 if (isReturnCall) {
9755 ReturnCallAdjustmentInfo retCallInfo(
9756 callBase->stackArgAreaSizeUnaligned(), inboundStackArgBytes_);
9757 masm.wasmReturnCallIndirect(desc, callee, boundsCheckFailed,
9758 nullCheckFailed, mozilla::Nothing(),
9759 retCallInfo);
9760 // The rest of the method is unnecessary for a return call.
9761 return;
9762 }
9763 MOZ_ASSERT(!isReturnCall);
9764 masm.wasmCallIndirect(desc, callee, boundsCheckFailed, nullCheckFailed,
9765 lir->tableSize(), &retOffset, &secondRetOffset);
9766 // Register reloading and realm switching are handled dynamically inside
9767 // wasmCallIndirect. There are two return offsets, one for each call
9768 // instruction (fast path and slow path).
9769 reloadRegs = false;
9770 switchRealm = false;
9771 break;
9772 }
9773 case wasm::CalleeDesc::Builtin:
9774 retOffset = masm.call(desc, callee.builtin());
9775 reloadRegs = false;
9776 switchRealm = false;
9777 break;
9778 case wasm::CalleeDesc::BuiltinInstanceMethod:
9779 retOffset = masm.wasmCallBuiltinInstanceMethod(
9780 desc, callBase->instanceArg(), callee.builtin(),
9781 callBase->builtinMethodFailureMode());
9782 switchRealm = false;
9783 break;
9784 case wasm::CalleeDesc::FuncRef:
9785 if (isReturnCall) {
9786 ReturnCallAdjustmentInfo retCallInfo(
9787 callBase->stackArgAreaSizeUnaligned(), inboundStackArgBytes_);
9788 masm.wasmReturnCallRef(desc, callee, retCallInfo);
9789 // The rest of the method is unnecessary for a return call.
9790 return;
9791 }
9792 MOZ_ASSERT(!isReturnCall);
9793 // Register reloading and realm switching are handled dynamically inside
9794 // wasmCallRef. There are two return offsets, one for each call
9795 // instruction (fast path and slow path).
9796 masm.wasmCallRef(desc, callee, &retOffset, &secondRetOffset);
9797 reloadRegs = false;
9798 switchRealm = false;
9799 break;
9800 }
9801
9802 // Note the assembler offset for the associated LSafePoint.
9803 MOZ_ASSERT(!isReturnCall);
9804 markSafepointAt(retOffset.offset(), lir);
9805
9806 // Now that all the outbound in-memory args are on the stack, note the
9807 // required lower boundary point of the associated StackMap.
9808 uint32_t framePushedAtStackMapBase =
9809 masm.framePushed() -
9810 wasm::AlignStackArgAreaSize(callBase->stackArgAreaSizeUnaligned());
9811 lir->safepoint()->setFramePushedAtStackMapBase(framePushedAtStackMapBase);
9812 MOZ_ASSERT(lir->safepoint()->wasmSafepointKind() ==
9813 WasmSafepointKind::LirCall);
9814
9815 // Note the assembler offset and framePushed for use by the adjunct
9816 // LSafePoint, see visitor for LWasmCallIndirectAdjunctSafepoint below.
9817 if (callee.which() == wasm::CalleeDesc::WasmTable ||
9818 callee.which() == wasm::CalleeDesc::FuncRef) {
9819 lir->adjunctSafepoint()->recordSafepointInfo(secondRetOffset,
9820 framePushedAtStackMapBase);
9821 }
9822
9823 if (reloadRegs) {
9824 masm.loadPtr(
9825 Address(masm.getStackPointer(), WasmCallerInstanceOffsetBeforeCall),
9826 InstanceReg);
9827 masm.loadWasmPinnedRegsFromInstance(mozilla::Nothing());
9828 if (switchRealm) {
9829 masm.switchToWasmInstanceRealm(ABINonArgReturnReg0, ABINonArgReturnReg1);
9830 }
9831 } else {
9832 MOZ_ASSERT(!switchRealm);
9833 }
9834
9835 switch (callee.which()) {
9836 case wasm::CalleeDesc::Func:
9837 case wasm::CalleeDesc::Import:
9838 case wasm::CalleeDesc::WasmTable:
9839 case wasm::CalleeDesc::FuncRef:
9840 // Stack allocation could change during Wasm (return) calls,
9841 // recover pre-call state.
9842 masm.freeStackTo(masm.framePushed());
9843 break;
9844 default:
9845 break;
9846 }
9847
9848 if (inTry) {
9849 // Set the end of the try note range
9850 size_t tryNoteIndex = callBase->tryNoteIndex();
9851 wasm::TryNoteVector& tryNotes = masm.tryNotes();
9852 wasm::TryNote& tryNote = tryNotes[tryNoteIndex];
9853
9854 // Don't set the end of the try note if we've OOM'ed, as the above
9855 // instructions may not have been emitted, which will trigger an assert
9856 // about zero-length try-notes. This is okay as this compilation will be
9857 // thrown away.
9858 if (!masm.oom()) {
9859 tryNote.setTryBodyEnd(masm.currentOffset());
9860 }
9861
9862 // This instruction or the adjunct safepoint must be the last instruction
9863 // in the block. No other instructions may be inserted.
9864 LBlock* block = lir->block();
9865 MOZ_RELEASE_ASSERT(*block->rbegin() == lir ||
9866 (block->rbegin()->isWasmCallIndirectAdjunctSafepoint() &&
9867 *(++block->rbegin()) == lir));
9868
9869 // Jump to the fallthrough block
9870 jumpToBlock(lir->mirCatchable()->getSuccessor(
9871 MWasmCallCatchable::FallthroughBranchIndex));
9872 }
9873 }
9874
9875 #ifdef ENABLE_WASM_JSPI
9876 void CodeGenerator::callWasmUpdateSuspenderState(
9877 wasm::UpdateSuspenderStateAction kind, Register suspender, Register temp) {
9878 masm.Push(InstanceReg);
9879 int32_t framePushedAfterInstance = masm.framePushed();
9880
9881 masm.move32(Imm32(uint32_t(kind)), temp);
9882
9883 masm.setupWasmABICall();
9884 masm.passABIArg(InstanceReg);
9885 masm.passABIArg(suspender);
9886 masm.passABIArg(temp);
9887 int32_t instanceOffset = masm.framePushed() - framePushedAfterInstance;
9888 masm.callWithABI(wasm::BytecodeOffset(0),
9889 wasm::SymbolicAddress::UpdateSuspenderState,
9890 mozilla::Some(instanceOffset));
9891
9892 masm.Pop(InstanceReg);
9893 }
9894
9895 void CodeGenerator::prepareWasmStackSwitchTrampolineCall(Register suspender,
9896 Register data) {
9897 // Reserve stack space for the wasm call.
9898 unsigned argDecrement;
9899 {
9900 WasmABIArgGenerator abi;
9901 ABIArg arg;
9902 arg = abi.next(MIRType::Pointer);
9903 arg = abi.next(MIRType::Pointer);
9904 argDecrement = StackDecrementForCall(WasmStackAlignment, 0,
9905 abi.stackBytesConsumedSoFar());
9906 }
9907 masm.reserveStack(argDecrement);
9908
9909 // Pass the suspender and data params through the wasm function ABI registers.
9910 WasmABIArgGenerator abi;
9911 ABIArg arg;
9912 arg = abi.next(MIRType::Pointer);
9913 if (arg.kind() == ABIArg::GPR) {
9914 masm.movePtr(suspender, arg.gpr());
9915 } else {
9916 MOZ_ASSERT(arg.kind() == ABIArg::Stack);
9917 masm.storePtr(suspender,
9918 Address(masm.getStackPointer(), arg.offsetFromArgBase()));
9919 }
9920 arg = abi.next(MIRType::Pointer);
9921 if (arg.kind() == ABIArg::GPR) {
9922 masm.movePtr(data, arg.gpr());
9923 } else {
9924 MOZ_ASSERT(arg.kind() == ABIArg::Stack);
9925 masm.storePtr(data,
9926 Address(masm.getStackPointer(), arg.offsetFromArgBase()));
9927 }
9928
9929 masm.storePtr(InstanceReg, Address(masm.getStackPointer(),
9930 WasmCallerInstanceOffsetBeforeCall));
9931 }
9932 #endif // ENABLE_WASM_JSPI
9933
9934 void CodeGenerator::visitWasmStackSwitchToSuspendable(
9935 LWasmStackSwitchToSuspendable* lir) {
9936 #ifdef ENABLE_WASM_JSPI
9937 const Register SuspenderReg = lir->suspender()->toGeneralReg()->reg();
9938 const Register FnReg = lir->fn()->toGeneralReg()->reg();
9939 const Register DataReg = lir->data()->toGeneralReg()->reg();
9940 const Register SuspenderDataReg = ABINonArgReg3;
9941
9942 # ifdef JS_CODEGEN_ARM64
9943 vixl::UseScratchRegisterScope temps(&masm);
9944 const Register ScratchReg1 = temps.AcquireX().asUnsized();
9945 # elif defined(JS_CODEGEN_X86)
9946 const Register ScratchReg1 = ABINonArgReg3;
9947 # elif defined(JS_CODEGEN_X64)
9948 const Register ScratchReg1 = ScratchReg;
9949 # elif defined(JS_CODEGEN_ARM)
9950 const Register ScratchReg1 = ABINonArgReturnVolatileReg;
9951 # elif defined(JS_CODEGEN_LOONG64)
9952 SecondScratchRegisterScope scratch2(masm);
9953 const Register ScratchReg1 = scratch2;
9954 # else
9955 # error "NYI: scratch register"
9956 # endif
9957
9958 masm.Push(SuspenderReg);
9959 masm.Push(FnReg);
9960 masm.Push(DataReg);
9961
9962 callWasmUpdateSuspenderState(wasm::UpdateSuspenderStateAction::Enter,
9963 SuspenderReg, ScratchReg1);
9964 masm.Pop(DataReg);
9965 masm.Pop(FnReg);
9966 masm.Pop(SuspenderReg);
9967
9968 masm.Push(SuspenderReg);
9969 int32_t framePushedAtSuspender = masm.framePushed();
9970 masm.Push(InstanceReg);
9971
9972 wasm::CallSiteDesc desc(wasm::CallSiteKind::StackSwitch);
9973 CodeLabel returnCallsite;
9974
9975 // Aligning stack before trampoline call.
9976 uint32_t reserve = ComputeByteAlignment(
9977 masm.framePushed() - sizeof(wasm::Frame), WasmStackAlignment);
9978 masm.reserveStack(reserve);
9979
9980 masm.loadPrivate(Address(SuspenderReg, NativeObject::getFixedSlotOffset(
9981 wasm::SuspenderObjectDataSlot)),
9982 SuspenderDataReg);
9983
9984 // Switch stacks to suspendable, keep original FP to maintain
9985 // frames chain between main and suspendable stack segments.
9986 masm.storeStackPtr(
9987 Address(SuspenderDataReg, wasm::SuspenderObjectData::offsetOfMainSP()));
9988 masm.storePtr(
9989 FramePointer,
9990 Address(SuspenderDataReg, wasm::SuspenderObjectData::offsetOfMainFP()));
9991
9992 masm.loadStackPtr(Address(
9993 SuspenderDataReg, wasm::SuspenderObjectData::offsetOfSuspendableSP()));
9994
9995 masm.assertStackAlignment(WasmStackAlignment);
9996
9997 // The FramePointer is not changed for SwitchToSuspendable.
9998 uint32_t framePushed = masm.framePushed();
9999
10000 // On different stack, reset framePushed. FramePointer is not valid here.
10001 masm.setFramePushed(0);
10002
10003 prepareWasmStackSwitchTrampolineCall(SuspenderReg, DataReg);
10004
10005 // Get wasm instance pointer for callee.
10006 size_t instanceSlotOffset = FunctionExtended::offsetOfExtendedSlot(
10007 FunctionExtended::WASM_INSTANCE_SLOT);
10008 masm.loadPtr(Address(FnReg, instanceSlotOffset), InstanceReg);
10009
10010 masm.storePtr(InstanceReg, Address(masm.getStackPointer(),
10011 WasmCalleeInstanceOffsetBeforeCall));
10012 masm.loadWasmPinnedRegsFromInstance(mozilla::Nothing());
10013
10014 masm.assertStackAlignment(WasmStackAlignment);
10015
10016 const Register ReturnAddressReg = ScratchReg1;
10017
10018 // DataReg is not needed anymore, using it as a scratch register.
10019 const Register ScratchReg2 = DataReg;
10020
10021 // Save future of suspendable stack exit frame pointer.
10022 masm.computeEffectiveAddress(
10023 Address(masm.getStackPointer(), -int32_t(sizeof(wasm::Frame))),
10024 ScratchReg2);
10025 masm.storePtr(
10026 ScratchReg2,
10027 Address(SuspenderDataReg,
10028 wasm::SuspenderObjectData::offsetOfSuspendableExitFP()));
10029
10030 masm.mov(&returnCallsite, ReturnAddressReg);
10031
10032 // Call wasm function fast.
10033 # ifdef JS_USE_LINK_REGISTER
10034 # if defined(JS_CODEGEN_LOONG64)
10035 masm.mov(ReturnAddressReg, ra);
10036 # else
10037 masm.mov(ReturnAddressReg, lr);
10038 # endif
10039 # else
10040 masm.Push(ReturnAddressReg);
10041 # endif
10042 // Get funcUncheckedCallEntry() from the function's
10043 // WASM_FUNC_UNCHECKED_ENTRY_SLOT extended slot.
10044 size_t uncheckedEntrySlotOffset = FunctionExtended::offsetOfExtendedSlot(
10045 FunctionExtended::WASM_FUNC_UNCHECKED_ENTRY_SLOT);
10046 masm.loadPtr(Address(FnReg, uncheckedEntrySlotOffset), ScratchReg2);
10047 masm.jump(ScratchReg2);
10048
10049 // About to use valid FramePointer -- restore framePushed.
10050 masm.setFramePushed(framePushed);
10051
10052 // For IsPlausibleStackMapKey check for the following callsite.
10053 masm.wasmTrapInstruction();
10054
10055 // Callsite for return from main stack.
10056 masm.bind(&returnCallsite);
10057 masm.append(desc, *returnCallsite.target());
10058 masm.addCodeLabel(returnCallsite);
10059
10060 masm.assertStackAlignment(WasmStackAlignment);
10061
10062 markSafepointAt(returnCallsite.target()->offset(), lir);
10063 lir->safepoint()->setFramePushedAtStackMapBase(framePushed);
10064 lir->safepoint()->setWasmSafepointKind(WasmSafepointKind::StackSwitch);
10065 // Rooting SuspenderReg.
10066 masm.propagateOOM(
10067 lir->safepoint()->addWasmAnyRefSlot(true, framePushedAtSuspender));
10068
10069 masm.freeStackTo(framePushed);
10070
10071 masm.freeStack(reserve);
10072 masm.Pop(InstanceReg);
10073 masm.Pop(SuspenderReg);
10074
10075 masm.switchToWasmInstanceRealm(ScratchReg1, ScratchReg2);
10076
10077 callWasmUpdateSuspenderState(wasm::UpdateSuspenderStateAction::Leave,
10078 SuspenderReg, ScratchReg1);
10079 #else
10080 MOZ_CRASH("NYI");
10081 #endif // ENABLE_WASM_JSPI
10082 }
10083
10084 void CodeGenerator::visitWasmStackSwitchToMain(LWasmStackSwitchToMain* lir) {
10085 #ifdef ENABLE_WASM_JSPI
10086 const Register SuspenderReg = lir->suspender()->toGeneralReg()->reg();
10087 const Register FnReg = lir->fn()->toGeneralReg()->reg();
10088 const Register DataReg = lir->data()->toGeneralReg()->reg();
10089 const Register SuspenderDataReg = ABINonArgReg3;
10090
10091 # ifdef JS_CODEGEN_ARM64
10092 vixl::UseScratchRegisterScope temps(&masm);
10093 const Register ScratchReg1 = temps.AcquireX().asUnsized();
10094 # elif defined(JS_CODEGEN_X86)
10095 const Register ScratchReg1 = ABINonArgReg3;
10096 # elif defined(JS_CODEGEN_X64)
10097 const Register ScratchReg1 = ScratchReg;
10098 # elif defined(JS_CODEGEN_ARM)
10099 const Register ScratchReg1 = ABINonArgReturnVolatileReg;
10100 # elif defined(JS_CODEGEN_LOONG64)
10101 SecondScratchRegisterScope scratch2(masm);
10102 const Register ScratchReg1 = scratch2;
10103 # else
10104 # error "NYI: scratch register"
10105 # endif
10106
10107 masm.Push(SuspenderReg);
10108 masm.Push(FnReg);
10109 masm.Push(DataReg);
10110
10111 callWasmUpdateSuspenderState(wasm::UpdateSuspenderStateAction::Suspend,
10112 SuspenderReg, ScratchReg1);
10113
10114 masm.Pop(DataReg);
10115 masm.Pop(FnReg);
10116 masm.Pop(SuspenderReg);
10117
10118 masm.Push(SuspenderReg);
10119 int32_t framePushedAtSuspender = masm.framePushed();
10120 masm.Push(InstanceReg);
10121
10122 wasm::CallSiteDesc desc(wasm::CallSiteKind::StackSwitch);
10123 CodeLabel returnCallsite;
10124
10125 // Aligning stack before trampoline call.
10126 uint32_t reserve = ComputeByteAlignment(
10127 masm.framePushed() - sizeof(wasm::Frame), WasmStackAlignment);
10128 masm.reserveStack(reserve);
10129
10130 masm.loadPrivate(Address(SuspenderReg, NativeObject::getFixedSlotOffset(
10131 wasm::SuspenderObjectDataSlot)),
10132 SuspenderDataReg);
10133
10134 // Switch stacks to main.
10135 masm.storeStackPtr(Address(
10136 SuspenderDataReg, wasm::SuspenderObjectData::offsetOfSuspendableSP()));
10137 masm.storePtr(FramePointer,
10138 Address(SuspenderDataReg,
10139 wasm::SuspenderObjectData::offsetOfSuspendableFP()));
10140
10141 masm.loadStackPtr(
10142 Address(SuspenderDataReg, wasm::SuspenderObjectData::offsetOfMainSP()));
10143 masm.loadPtr(
10144 Address(SuspenderDataReg, wasm::SuspenderObjectData::offsetOfMainFP()),
10145 FramePointer);
10146
10147 // Set main_ra field to returnCallsite.
10148 # ifdef JS_CODEGEN_X86
10149 // SuspenderDataReg is also ScratchReg1, use DataReg as a scratch register.
10150 MOZ_ASSERT(ScratchReg1 == SuspenderDataReg);
10151 masm.push(DataReg);
10152 masm.mov(&returnCallsite, DataReg);
10153 masm.storePtr(
10154 DataReg,
10155 Address(SuspenderDataReg,
10156 wasm::SuspenderObjectData::offsetOfSuspendedReturnAddress()));
10157 masm.pop(DataReg);
10158 # else
10159 MOZ_ASSERT(ScratchReg1 != SuspenderDataReg);
10160 masm.mov(&returnCallsite, ScratchReg1);
10161 masm.storePtr(
10162 ScratchReg1,
10163 Address(SuspenderDataReg,
10164 wasm::SuspenderObjectData::offsetOfSuspendedReturnAddress()));
10165 # endif
10166
10167 masm.assertStackAlignment(WasmStackAlignment);
10168
10169 // The FramePointer is pointing to the same
10170 // place as before switch happened.
10171 uint32_t framePushed = masm.framePushed();
10172
10173 // On different stack, reset framePushed. FramePointer is not valid here.
10174 masm.setFramePushed(0);
10175
10176 prepareWasmStackSwitchTrampolineCall(SuspenderReg, DataReg);
10177
10178 // Get wasm instance pointer for callee.
10179 size_t instanceSlotOffset = FunctionExtended::offsetOfExtendedSlot(
10180 FunctionExtended::WASM_INSTANCE_SLOT);
10181 masm.loadPtr(Address(FnReg, instanceSlotOffset), InstanceReg);
10182
10183 masm.storePtr(InstanceReg, Address(masm.getStackPointer(),
10184 WasmCalleeInstanceOffsetBeforeCall));
10185 masm.loadWasmPinnedRegsFromInstance(mozilla::Nothing());
10186
10187 masm.assertStackAlignment(WasmStackAlignment);
10188
10189 const Register ReturnAddressReg = ScratchReg1;
10190 // DataReg is not needed anymore, using it as a scratch register.
10191 const Register ScratchReg2 = DataReg;
10192
10193 // Save future of main stack exit frame pointer.
10194 masm.computeEffectiveAddress(
10195 Address(masm.getStackPointer(), -int32_t(sizeof(wasm::Frame))),
10196 ScratchReg2);
10197 masm.storePtr(ScratchReg2,
10198 Address(SuspenderDataReg,
10199 wasm::SuspenderObjectData::offsetOfMainExitFP()));
10200
10201 // Load InstanceReg from suspendable stack exit frame.
10202 masm.loadPtr(Address(SuspenderDataReg,
10203 wasm::SuspenderObjectData::offsetOfSuspendableExitFP()),
10204 ScratchReg2);
10205 masm.loadPtr(
10206 Address(ScratchReg2, wasm::FrameWithInstances::callerInstanceOffset()),
10207 ScratchReg2);
10208 masm.storePtr(ScratchReg2, Address(masm.getStackPointer(),
10209 WasmCallerInstanceOffsetBeforeCall));
10210
10211 // Load RA from suspendable stack exit frame.
10212 masm.loadPtr(Address(SuspenderDataReg,
10213 wasm::SuspenderObjectData::offsetOfSuspendableExitFP()),
10214 ScratchReg1);
10215 masm.loadPtr(Address(ScratchReg1, wasm::Frame::returnAddressOffset()),
10216 ReturnAddressReg);
10217
10218 // Call wasm function fast.
10219 # ifdef JS_USE_LINK_REGISTER
10220 # if defined(JS_CODEGEN_LOONG64)
10221 masm.mov(ReturnAddressReg, ra);
10222 # else
10223 masm.mov(ReturnAddressReg, lr);
10224 # endif
10225 # else
10226 masm.Push(ReturnAddressReg);
10227 # endif
10228 // Get funcUncheckedCallEntry() from the function's
10229 // WASM_FUNC_UNCHECKED_ENTRY_SLOT extended slot.
10230 size_t uncheckedEntrySlotOffset = FunctionExtended::offsetOfExtendedSlot(
10231 FunctionExtended::WASM_FUNC_UNCHECKED_ENTRY_SLOT);
10232 masm.loadPtr(Address(FnReg, uncheckedEntrySlotOffset), ScratchReg2);
10233 masm.jump(ScratchReg2);
10234
10235 // About to use valid FramePointer -- restore framePushed.
10236 masm.setFramePushed(framePushed);
10237
10238 // For IsPlausibleStackMapKey check for the following callsite.
10239 masm.wasmTrapInstruction();
10240
10241 // Callsite for return from suspendable stack.
10242 masm.bind(&returnCallsite);
10243 masm.append(desc, *returnCallsite.target());
10244 masm.addCodeLabel(returnCallsite);
10245
10246 masm.assertStackAlignment(WasmStackAlignment);
10247
10248 markSafepointAt(returnCallsite.target()->offset(), lir);
10249 lir->safepoint()->setFramePushedAtStackMapBase(framePushed);
10250 lir->safepoint()->setWasmSafepointKind(WasmSafepointKind::StackSwitch);
10251 // Rooting SuspenderReg.
10252 masm.propagateOOM(
10253 lir->safepoint()->addWasmAnyRefSlot(true, framePushedAtSuspender));
10254
10255 masm.freeStackTo(framePushed);
10256
10257 // Push ReturnReg that is passed from ContinueOnSuspended on the stack after,
10258 // the SuspenderReg has been restored (see ScratchReg1 push below).
10259 // (On some platforms SuspenderReg == ReturnReg)
10260 masm.mov(ReturnReg, ScratchReg1);
10261
10262 masm.freeStack(reserve);
10263 masm.Pop(InstanceReg);
10264 masm.Pop(SuspenderReg);
10265
10266 masm.Push(ScratchReg1);
10267
10268 masm.switchToWasmInstanceRealm(ScratchReg1, ScratchReg2);
10269
10270 callWasmUpdateSuspenderState(wasm::UpdateSuspenderStateAction::Resume,
10271 SuspenderReg, ScratchReg1);
10272
10273 masm.Pop(ToRegister(lir->output()));
10274
10275 #else
10276 MOZ_CRASH("NYI");
10277 #endif // ENABLE_WASM_JSPI
10278 }
10279
10280 void CodeGenerator::visitWasmStackContinueOnSuspendable(
10281 LWasmStackContinueOnSuspendable* lir) {
10282 #ifdef ENABLE_WASM_JSPI
10283 const Register SuspenderReg = lir->suspender()->toGeneralReg()->reg();
10284 const Register ResultReg = lir->result()->toGeneralReg()->reg();
10285 const Register SuspenderDataReg = ABINonArgReg3;
10286
10287 # ifdef JS_CODEGEN_ARM64
10288 vixl::UseScratchRegisterScope temps(&masm);
10289 const Register ScratchReg1 = temps.AcquireX().asUnsized();
10290 # elif defined(JS_CODEGEN_X86)
10291 const Register ScratchReg1 = ABINonArgReturnReg1;
10292 # elif defined(JS_CODEGEN_X64)
10293 const Register ScratchReg1 = ScratchReg;
10294 # elif defined(JS_CODEGEN_ARM)
10295 const Register ScratchReg1 = ABINonArgReturnVolatileReg;
10296 # elif defined(JS_CODEGEN_LOONG64)
10297 SecondScratchRegisterScope scratch2(masm);
10298 const Register ScratchReg1 = scratch2;
10299 # else
10300 # error "NYI: scratch register"
10301 # endif
10302 const Register ScratchReg2 = ABINonArgReg1;
10303
10304 masm.Push(SuspenderReg);
10305 int32_t framePushedAtSuspender = masm.framePushed();
10306 masm.Push(InstanceReg);
10307
10308 wasm::CallSiteDesc desc(wasm::CallSiteKind::StackSwitch);
10309 CodeLabel returnCallsite;
10310
10311 // Aligning stack before trampoline call.
10312 uint32_t reserve = ComputeByteAlignment(
10313 masm.framePushed() - sizeof(wasm::Frame), WasmStackAlignment);
10314 masm.reserveStack(reserve);
10315
10316 masm.loadPrivate(Address(SuspenderReg, NativeObject::getFixedSlotOffset(
10317 wasm::SuspenderObjectDataSlot)),
10318 SuspenderDataReg);
10319 masm.storeStackPtr(
10320 Address(SuspenderDataReg, wasm::SuspenderObjectData::offsetOfMainSP()));
10321 masm.storePtr(
10322 FramePointer,
10323 Address(SuspenderDataReg, wasm::SuspenderObjectData::offsetOfMainFP()));
10324
10325 // Adjust exit frame FP.
10326 masm.loadPtr(Address(SuspenderDataReg,
10327 wasm::SuspenderObjectData::offsetOfSuspendableExitFP()),
10328 ScratchReg1);
10329 masm.storePtr(FramePointer,
10330 Address(ScratchReg1, wasm::Frame::callerFPOffset()));
10331
10332 // Adjust exit frame RA.
10333 masm.mov(&returnCallsite, ScratchReg2);
10334
10335 masm.storePtr(ScratchReg2,
10336 Address(ScratchReg1, wasm::Frame::returnAddressOffset()));
10337 // Adjust exit frame caller instance slot.
10338 masm.storePtr(
10339 InstanceReg,
10340 Address(ScratchReg1, wasm::FrameWithInstances::callerInstanceOffset()));
10341
10342 // Switch stacks to suspendable.
10343 masm.loadStackPtr(Address(
10344 SuspenderDataReg, wasm::SuspenderObjectData::offsetOfSuspendableSP()));
10345 masm.loadPtr(Address(SuspenderDataReg,
10346 wasm::SuspenderObjectData::offsetOfSuspendableFP()),
10347 FramePointer);
10348
10349 masm.assertStackAlignment(WasmStackAlignment);
10350
10351 // The FramePointer is pointing to the same
10352 // place as before switch happened.
10353 uint32_t framePushed = masm.framePushed();
10354
10355 // On different stack, reset framePushed. FramePointer is not valid here.
10356 masm.setFramePushed(0);
10357
10358 // Restore shadow stack area and instance slots.
10359 WasmABIArgGenerator abi;
10360 unsigned reserveBeforeCall = abi.stackBytesConsumedSoFar();
10361 MOZ_ASSERT(masm.framePushed() == 0);
10362 unsigned argDecrement =
10363 StackDecrementForCall(WasmStackAlignment, 0, reserveBeforeCall);
10364 masm.reserveStack(argDecrement);
10365
10366 masm.storePtr(InstanceReg, Address(masm.getStackPointer(),
10367 WasmCallerInstanceOffsetBeforeCall));
10368 masm.storePtr(InstanceReg, Address(masm.getStackPointer(),
10369 WasmCalleeInstanceOffsetBeforeCall));
10370
10371 masm.assertStackAlignment(WasmStackAlignment);
10372
10373 // Transfer results to ReturnReg so it will appear at SwitchToMain return.
10374 masm.mov(ResultReg, ReturnReg);
10375
10376 const Register ReturnAddressReg = ScratchReg1;
10377
10378 // Pretend we just returned from the function.
10379 masm.loadPtr(
10380 Address(SuspenderDataReg,
10381 wasm::SuspenderObjectData::offsetOfSuspendedReturnAddress()),
10382 ReturnAddressReg);
10383 masm.jump(ReturnAddressReg);
10384
10385 // About to use valid FramePointer -- restore framePushed.
10386 masm.setFramePushed(framePushed);
10387
10388 // For IsPlausibleStackMapKey check for the following callsite.
10389 masm.wasmTrapInstruction();
10390
10391 // Callsite for return from suspendable stack.
10392 masm.bind(&returnCallsite);
10393 masm.append(desc, *returnCallsite.target());
10394 masm.addCodeLabel(returnCallsite);
10395
10396 masm.assertStackAlignment(WasmStackAlignment);
10397
10398 markSafepointAt(returnCallsite.target()->offset(), lir);
10399 lir->safepoint()->setFramePushedAtStackMapBase(framePushed);
10400 lir->safepoint()->setWasmSafepointKind(WasmSafepointKind::StackSwitch);
10401 // Rooting SuspenderReg.
10402 masm.propagateOOM(
10403 lir->safepoint()->addWasmAnyRefSlot(true, framePushedAtSuspender));
10404
10405 masm.freeStackTo(framePushed);
10406
10407 masm.freeStack(reserve);
10408 masm.Pop(InstanceReg);
10409 masm.Pop(SuspenderReg);
10410
10411 // Using SuspenderDataReg and ABINonArgReg2 as temps.
10412 masm.switchToWasmInstanceRealm(SuspenderDataReg, ABINonArgReg2);
10413
10414 callWasmUpdateSuspenderState(wasm::UpdateSuspenderStateAction::Leave,
10415 SuspenderReg, ScratchReg1);
10416 #else
10417 MOZ_CRASH("NYI");
10418 #endif // ENABLE_WASM_JSPI
10419 }
10420
10421 void CodeGenerator::visitWasmCallLandingPrePad(LWasmCallLandingPrePad* lir) {
10422 LBlock* block = lir->block();
10423 MWasmCallLandingPrePad* mir = lir->mir();
10424 MBasicBlock* mirBlock = mir->block();
10425 MBasicBlock* callMirBlock = mir->callBlock();
10426
10427 // This block must be the pre-pad successor of the call block. No blocks may
10428 // be inserted between us, such as for critical edge splitting.
10429 MOZ_RELEASE_ASSERT(mirBlock == callMirBlock->getSuccessor(
10430 MWasmCallCatchable::PrePadBranchIndex));
10431
10432 // This instruction or a move group must be the first instruction in the
10433 // block. No other instructions may be inserted.
10434 MOZ_RELEASE_ASSERT(*block->begin() == lir || (block->begin()->isMoveGroup() &&
10435 *(++block->begin()) == lir));
10436
10437 wasm::TryNoteVector& tryNotes = masm.tryNotes();
10438 wasm::TryNote& tryNote = tryNotes[mir->tryNoteIndex()];
10439 // Set the entry point for the call try note to be the beginning of this
10440 // block. The above assertions (and assertions in visitWasmCall) guarantee
10441 // that we are not skipping over instructions that should be executed.
10442 tryNote.setLandingPad(block->label()->offset(), masm.framePushed());
10443 }
10444
10445 void CodeGenerator::visitWasmCallIndirectAdjunctSafepoint(
10446 LWasmCallIndirectAdjunctSafepoint* lir) {
10447 markSafepointAt(lir->safepointLocation().offset(), lir);
10448 lir->safepoint()->setFramePushedAtStackMapBase(
10449 lir->framePushedAtStackMapBase());
10450 }
10451
10452 template <typename InstructionWithMaybeTrapSite>
10453 void EmitSignalNullCheckTrapSite(MacroAssembler& masm,
10454 InstructionWithMaybeTrapSite* ins,
10455 FaultingCodeOffset fco,
10456 wasm::TrapMachineInsn tmi) {
10457 if (!ins->maybeTrap()) {
10458 return;
10459 }
10460 masm.append(wasm::Trap::NullPointerDereference, tmi, fco.get(),
10461 *ins->maybeTrap());
10462 }
10463
10464 template <typename InstructionWithMaybeTrapSite, class AddressOrBaseIndex>
10465 void CodeGenerator::emitWasmValueLoad(InstructionWithMaybeTrapSite* ins,
10466 MIRType type, MWideningOp wideningOp,
10467 AddressOrBaseIndex addr,
10468 AnyRegister dst) {
10469 FaultingCodeOffset fco;
10470 switch (type) {
10471 case MIRType::Int32:
10472 switch (wideningOp) {
10473 case MWideningOp::None:
10474 fco = masm.load32(addr, dst.gpr());
10475 EmitSignalNullCheckTrapSite(masm, ins, fco,
10476 wasm::TrapMachineInsn::Load32);
10477 break;
10478 case MWideningOp::FromU16:
10479 fco = masm.load16ZeroExtend(addr, dst.gpr());
10480 EmitSignalNullCheckTrapSite(masm, ins, fco,
10481 wasm::TrapMachineInsn::Load16);
10482 break;
10483 case MWideningOp::FromS16:
10484 fco = masm.load16SignExtend(addr, dst.gpr());
10485 EmitSignalNullCheckTrapSite(masm, ins, fco,
10486 wasm::TrapMachineInsn::Load16);
10487 break;
10488 case MWideningOp::FromU8:
10489 fco = masm.load8ZeroExtend(addr, dst.gpr());
10490 EmitSignalNullCheckTrapSite(masm, ins, fco,
10491 wasm::TrapMachineInsn::Load8);
10492 break;
10493 case MWideningOp::FromS8:
10494 fco = masm.load8SignExtend(addr, dst.gpr());
10495 EmitSignalNullCheckTrapSite(masm, ins, fco,
10496 wasm::TrapMachineInsn::Load8);
10497 break;
10498 default:
10499 MOZ_CRASH("unexpected widening op in ::visitWasmLoadElement");
10500 }
10501 break;
10502 case MIRType::Float32:
10503 MOZ_ASSERT(wideningOp == MWideningOp::None);
10504 fco = masm.loadFloat32(addr, dst.fpu());
10505 EmitSignalNullCheckTrapSite(masm, ins, fco,
10506 wasm::TrapMachineInsn::Load32);
10507 break;
10508 case MIRType::Double:
10509 MOZ_ASSERT(wideningOp == MWideningOp::None);
10510 fco = masm.loadDouble(addr, dst.fpu());
10511 EmitSignalNullCheckTrapSite(masm, ins, fco,
10512 wasm::TrapMachineInsn::Load64);
10513 break;
10514 case MIRType::Pointer:
10515 case MIRType::WasmAnyRef:
10516 case MIRType::WasmArrayData:
10517 MOZ_ASSERT(wideningOp == MWideningOp::None);
10518 fco = masm.loadPtr(addr, dst.gpr());
10519 EmitSignalNullCheckTrapSite(masm, ins, fco,
10520 wasm::TrapMachineInsnForLoadWord());
10521 break;
10522 default:
10523 MOZ_CRASH("unexpected type in ::emitWasmValueLoad");
10524 }
10525 }
10526
10527 template <typename InstructionWithMaybeTrapSite, class AddressOrBaseIndex>
10528 void CodeGenerator::emitWasmValueStore(InstructionWithMaybeTrapSite* ins,
10529 MIRType type, MNarrowingOp narrowingOp,
10530 AnyRegister src,
10531 AddressOrBaseIndex addr) {
10532 FaultingCodeOffset fco;
10533 switch (type) {
10534 case MIRType::Int32:
10535 switch (narrowingOp) {
10536 case MNarrowingOp::None:
10537 fco = masm.store32(src.gpr(), addr);
10538 EmitSignalNullCheckTrapSite(masm, ins, fco,
10539 wasm::TrapMachineInsn::Store32);
10540 break;
10541 case MNarrowingOp::To16:
10542 fco = masm.store16(src.gpr(), addr);
10543 EmitSignalNullCheckTrapSite(masm, ins, fco,
10544 wasm::TrapMachineInsn::Store16);
10545 break;
10546 case MNarrowingOp::To8:
10547 fco = masm.store8(src.gpr(), addr);
10548 EmitSignalNullCheckTrapSite(masm, ins, fco,
10549 wasm::TrapMachineInsn::Store8);
10550 break;
10551 default:
10552 MOZ_CRASH();
10553 }
10554 break;
10555 case MIRType::Float32:
10556 fco = masm.storeFloat32(src.fpu(), addr);
10557 EmitSignalNullCheckTrapSite(masm, ins, fco,
10558 wasm::TrapMachineInsn::Store32);
10559 break;
10560 case MIRType::Double:
10561 fco = masm.storeDouble(src.fpu(), addr);
10562 EmitSignalNullCheckTrapSite(masm, ins, fco,
10563 wasm::TrapMachineInsn::Store64);
10564 break;
10565 case MIRType::Pointer:
10566 // This could be correct, but it would be a new usage, so check carefully.
10567 MOZ_CRASH("Unexpected type in ::emitWasmValueStore.");
10568 case MIRType::WasmAnyRef:
10569 MOZ_CRASH("Bad type in ::emitWasmValueStore. Use LWasmStoreElementRef.");
10570 default:
10571 MOZ_CRASH("unexpected type in ::emitWasmValueStore");
10572 }
10573 }
10574
10575 void CodeGenerator::visitWasmLoadSlot(LWasmLoadSlot* ins) {
10576 MIRType type = ins->type();
10577 MWideningOp wideningOp = ins->wideningOp();
10578 Register container = ToRegister(ins->containerRef());
10579 Address addr(container, ins->offset());
10580 AnyRegister dst = ToAnyRegister(ins->output());
10581
10582 #ifdef ENABLE_WASM_SIMD
10583 if (type == MIRType::Simd128) {
10584 MOZ_ASSERT(wideningOp == MWideningOp::None);
10585 FaultingCodeOffset fco = masm.loadUnalignedSimd128(addr, dst.fpu());
10586 EmitSignalNullCheckTrapSite(masm, ins, fco, wasm::TrapMachineInsn::Load128);
10587 return;
10588 }
10589 #endif
10590 emitWasmValueLoad(ins, type, wideningOp, addr, dst);
10591 }
10592
10593 void CodeGenerator::visitWasmLoadElement(LWasmLoadElement* ins) {
10594 MIRType type = ins->type();
10595 MWideningOp wideningOp = ins->wideningOp();
10596 Scale scale = ins->scale();
10597 Register base = ToRegister(ins->base());
10598 Register index = ToRegister(ins->index());
10599 AnyRegister dst = ToAnyRegister(ins->output());
10600
10601 #ifdef ENABLE_WASM_SIMD
10602 if (type == MIRType::Simd128) {
10603 MOZ_ASSERT(wideningOp == MWideningOp::None);
10604 FaultingCodeOffset fco;
10605 Register temp = ToRegister(ins->temp0());
10606 masm.lshiftPtr(Imm32(4), index, temp);
10607 fco = masm.loadUnalignedSimd128(BaseIndex(base, temp, Scale::TimesOne),
10608 dst.fpu());
10609 EmitSignalNullCheckTrapSite(masm, ins, fco, wasm::TrapMachineInsn::Load128);
10610 return;
10611 }
10612 #endif
10613 emitWasmValueLoad(ins, type, wideningOp, BaseIndex(base, index, scale), dst);
10614 }
10615
10616 void CodeGenerator::visitWasmStoreSlot(LWasmStoreSlot* ins) {
10617 MIRType type = ins->type();
10618 MNarrowingOp narrowingOp = ins->narrowingOp();
10619 Register container = ToRegister(ins->containerRef());
10620 Address addr(container, ins->offset());
10621 AnyRegister src = ToAnyRegister(ins->value());
10622 if (type != MIRType::Int32) {
10623 MOZ_RELEASE_ASSERT(narrowingOp == MNarrowingOp::None);
10624 }
10625
10626 #ifdef ENABLE_WASM_SIMD
10627 if (type == MIRType::Simd128) {
10628 FaultingCodeOffset fco = masm.storeUnalignedSimd128(src.fpu(), addr);
10629 EmitSignalNullCheckTrapSite(masm, ins, fco,
10630 wasm::TrapMachineInsn::Store128);
10631 return;
10632 }
10633 #endif
10634 emitWasmValueStore(ins, type, narrowingOp, src, addr);
10635 }
10636
10637 void CodeGenerator::visitWasmStoreStackResult(LWasmStoreStackResult* ins) {
10638 const LAllocation* value = ins->value();
10639 Address addr(ToRegister(ins->stackResultsArea()), ins->offset());
10640
10641 switch (ins->type()) {
10642 case MIRType::Int32:
10643 masm.storePtr(ToRegister(value), addr);
10644 break;
10645 case MIRType::Float32:
10646 masm.storeFloat32(ToFloatRegister(value), addr);
10647 break;
10648 case MIRType::Double:
10649 masm.storeDouble(ToFloatRegister(value), addr);
10650 break;
10651 #ifdef ENABLE_WASM_SIMD
10652 case MIRType::Simd128:
10653 masm.storeUnalignedSimd128(ToFloatRegister(value), addr);
10654 break;
10655 #endif
10656 case MIRType::WasmAnyRef:
10657 masm.storePtr(ToRegister(value), addr);
10658 break;
10659 default:
10660 MOZ_CRASH("unexpected type in ::visitWasmStoreStackResult");
10661 }
10662 }
10663
10664 void CodeGenerator::visitWasmStoreStackResultI64(LWasmStoreStackResultI64* ins) {
10665 masm.store64(ToRegister64(ins->value()), Address(ToRegister(ins->stackResultsArea()), ins->offset()));
10666 }
10667
10668 void CodeGenerator::visitWasmStoreElement(LWasmStoreElement* ins) {
10669 MIRType type = ins->type();
10670 MNarrowingOp narrowingOp = ins->narrowingOp();
10671 Scale scale = ins->scale();
10672 Register base = ToRegister(ins->base());
10673 Register index = ToRegister(ins->index());
10674 AnyRegister src = ToAnyRegister(ins->value());
10675 if (type != MIRType::Int32) {
10676 MOZ_RELEASE_ASSERT(narrowingOp == MNarrowingOp::None);
10677 }
10678
10679 #ifdef ENABLE_WASM_SIMD
10680 if (type == MIRType::Simd128) {
10681 Register temp = ToRegister(ins->temp0());
10682 masm.lshiftPtr(Imm32(4), index, temp);
10683 FaultingCodeOffset fco = masm.storeUnalignedSimd128(
10684 src.fpu(), BaseIndex(base, temp, Scale::TimesOne));
10685 EmitSignalNullCheckTrapSite(masm, ins, fco,
10686 wasm::TrapMachineInsn::Store128);
10687 return;
10688 }
10689 #endif
10690 emitWasmValueStore(ins, type, narrowingOp, src,
10691 BaseIndex(base, index, scale));
10692 }
10693
10694 void CodeGenerator::visitWasmLoadTableElement(LWasmLoadTableElement* ins) {
10695 Register elements = ToRegister(ins->elements());
10696 Register index = ToRegister(ins->index());
10697 Register output = ToRegister(ins->output());
10698 masm.loadPtr(BaseIndex(elements, index, ScalePointer), output);
10699 }
10700
10701 void CodeGenerator::visitWasmDerivedPointer(LWasmDerivedPointer* ins) {
10702 masm.movePtr(ToRegister(ins->base()), ToRegister(ins->output()));
10703 masm.addPtr(Imm32(int32_t(ins->mir()->offset())), ToRegister(ins->output()));
10704 }
10705
10706 void CodeGenerator::visitWasmDerivedIndexPointer(
10707 LWasmDerivedIndexPointer* ins) {
10708 Register base = ToRegister(ins->base());
10709 Register index = ToRegister(ins->index());
10710 Register output = ToRegister(ins->output());
10711 masm.computeEffectiveAddress(BaseIndex(base, index, ins->mir()->scale()),
10712 output);
10713 }
10714
10715 void CodeGenerator::visitWasmStoreRef(LWasmStoreRef* ins) {
10716 Register instance = ToRegister(ins->instance());
10717 Register valueBase = ToRegister(ins->valueBase());
10718 size_t offset = ins->offset();
10719 Register value = ToRegister(ins->value());
10720 Register temp = ToRegister(ins->temp0());
10721
10722 if (ins->preBarrierKind() == WasmPreBarrierKind::Normal) {
10723 Label skipPreBarrier;
10724 wasm::EmitWasmPreBarrierGuard(masm, instance, temp,
10725 Address(valueBase, offset), &skipPreBarrier,
10726 ins->maybeTrap());
10727 wasm::EmitWasmPreBarrierCallImmediate(masm, instance, temp, valueBase,
10728 offset);
10729 masm.bind(&skipPreBarrier);
10730 }
10731
10732 FaultingCodeOffset fco = masm.storePtr(value, Address(valueBase, offset));
10733 EmitSignalNullCheckTrapSite(masm, ins, fco,
10734 wasm::TrapMachineInsnForStoreWord());
10735 // The postbarrier is handled separately.
10736 }
10737
10738 void CodeGenerator::visitWasmStoreElementRef(LWasmStoreElementRef* ins) {
10739 Register instance = ToRegister(ins->instance());
10740 Register base = ToRegister(ins->base());
10741 Register index = ToRegister(ins->index());
10742 Register value = ToRegister(ins->value());
10743 Register temp0 = ToTempRegisterOrInvalid(ins->temp0());
10744 Register temp1 = ToTempRegisterOrInvalid(ins->temp1());
10745
10746 BaseIndex addr(base, index, ScalePointer);
10747
10748 if (ins->preBarrierKind() == WasmPreBarrierKind::Normal) {
10749 Label skipPreBarrier;
10750 wasm::EmitWasmPreBarrierGuard(masm, instance, temp0, addr, &skipPreBarrier,
10751 ins->maybeTrap());
10752 wasm::EmitWasmPreBarrierCallIndex(masm, instance, temp0, temp1, addr);
10753 masm.bind(&skipPreBarrier);
10754 }
10755
10756 FaultingCodeOffset fco = masm.storePtr(value, addr);
10757 EmitSignalNullCheckTrapSite(masm, ins, fco,
10758 wasm::TrapMachineInsnForStoreWord());
10759 // The postbarrier is handled separately.
10760 }
10761
10762 void CodeGenerator::visitWasmPostWriteBarrierWholeCell(
10763 LWasmPostWriteBarrierWholeCell* lir) {
10764 Register object = ToRegister(lir->object());
10765 Register value = ToRegister(lir->value());
10766 Register temp = ToRegister(lir->temp0());
10767 MOZ_ASSERT(ToRegister(lir->instance()) == InstanceReg);
10768 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
10769 // Skip the barrier if this object was previously added to the store buffer.
10770 // We perform this check out of line because in practice the prior guards
10771 // eliminate most calls to the barrier.
10772 wasm::CheckWholeCellLastElementCache(masm, InstanceReg, object, temp,
10773 ool.rejoin());
10774
10775 saveLiveVolatile(lir);
10776 masm.Push(InstanceReg);
10777 int32_t framePushedAfterInstance = masm.framePushed();
10778
10779 // Call Instance::postBarrierWholeCell
10780 masm.setupWasmABICall();
10781 masm.passABIArg(InstanceReg);
10782 masm.passABIArg(object);
10783 int32_t instanceOffset = masm.framePushed() - framePushedAfterInstance;
10784 masm.callWithABI(wasm::BytecodeOffset(0),
10785 wasm::SymbolicAddress::PostBarrierWholeCell,
10786 mozilla::Some(instanceOffset), ABIType::General);
10787
10788 masm.Pop(InstanceReg);
10789 restoreLiveVolatile(lir);
10790
10791 masm.jump(ool.rejoin());
10792 });
10793 addOutOfLineCode(ool, lir->mir());
10794
10795 wasm::EmitWasmPostBarrierGuard(masm, mozilla::Some(object), temp, value,
10796 ool->rejoin());
10797 masm.jump(ool->entry());
10798 masm.bind(ool->rejoin());
10799 }
10800
10801 void CodeGenerator::visitWasmPostWriteBarrierEdgeAtIndex(
10802 LWasmPostWriteBarrierEdgeAtIndex* lir) {
10803 Register object = ToRegister(lir->object());
10804 Register value = ToRegister(lir->value());
10805 Register valueBase = ToRegister(lir->valueBase());
10806 Register index = ToRegister(lir->index());
10807 Register temp = ToRegister(lir->temp0());
10808 MOZ_ASSERT(ToRegister(lir->instance()) == InstanceReg);
10809 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
10810 saveLiveVolatile(lir);
10811 masm.Push(InstanceReg);
10812 int32_t framePushedAfterInstance = masm.framePushed();
10813
10814 // Fold the value offset into the value base
10815 if (lir->elemSize() == 16) {
10816 masm.lshiftPtr(Imm32(4), index, temp);
10817 masm.addPtr(valueBase, temp);
10818 } else {
10819 masm.computeEffectiveAddress(
10820 BaseIndex(valueBase, index, ScaleFromElemWidth(lir->elemSize())),
10821 temp);
10822 }
10823
10824 // Call Instance::postBarrier
10825 masm.setupWasmABICall();
10826 masm.passABIArg(InstanceReg);
10827 masm.passABIArg(temp);
10828 int32_t instanceOffset = masm.framePushed() - framePushedAfterInstance;
10829 masm.callWithABI(wasm::BytecodeOffset(0),
10830 wasm::SymbolicAddress::PostBarrierEdge,
10831 mozilla::Some(instanceOffset), ABIType::General);
10832
10833 masm.Pop(InstanceReg);
10834 restoreLiveVolatile(lir);
10835
10836 masm.jump(ool.rejoin());
10837 });
10838 addOutOfLineCode(ool, lir->mir());
10839
10840 wasm::EmitWasmPostBarrierGuard(masm, mozilla::Some(object), temp, value,
10841 ool->rejoin());
10842 masm.jump(ool->entry());
10843 masm.bind(ool->rejoin());
10844 }
10845
10846 void CodeGenerator::visitWasmLoadSlotI64(LWasmLoadSlotI64* ins) {
10847 Register container = ToRegister(ins->containerRef());
10848 Address addr(container, ins->offset());
10849 Register64 output = ToOutRegister64(ins);
10850 // Either 1 or 2 words. On a 32-bit target, it is hard to argue that one
10851 // transaction will always trap before the other, so it seems safest to
10852 // register both of them as potentially trapping.
10853 #ifdef JS_64BIT
10854 FaultingCodeOffset fco = masm.load64(addr, output);
10855 EmitSignalNullCheckTrapSite(masm, ins, fco, wasm::TrapMachineInsn::Load64);
10856 #else
10857 FaultingCodeOffsetPair fcop = masm.load64(addr, output);
10858 EmitSignalNullCheckTrapSite(masm, ins, fcop.first,
10859 wasm::TrapMachineInsn::Load32);
10860 EmitSignalNullCheckTrapSite(masm, ins, fcop.second,
10861 wasm::TrapMachineInsn::Load32);
10862 #endif
10863 }
10864
10865 void CodeGenerator::visitWasmLoadElementI64(LWasmLoadElementI64* ins) {
10866 Register base = ToRegister(ins->base());
10867 Register index = ToRegister(ins->index());
10868 BaseIndex addr(base, index, Scale::TimesEight);
10869 Register64 output = ToOutRegister64(ins);
10870 // Either 1 or 2 words. On a 32-bit target, it is hard to argue that one
10871 // transaction will always trap before the other, so it seems safest to
10872 // register both of them as potentially trapping.
10873 #ifdef JS_64BIT
10874 FaultingCodeOffset fco = masm.load64(addr, output);
10875 EmitSignalNullCheckTrapSite(masm, ins, fco, wasm::TrapMachineInsn::Load64);
10876 #else
10877 FaultingCodeOffsetPair fcop = masm.load64(addr, output);
10878 EmitSignalNullCheckTrapSite(masm, ins, fcop.first,
10879 wasm::TrapMachineInsn::Load32);
10880 EmitSignalNullCheckTrapSite(masm, ins, fcop.second,
10881 wasm::TrapMachineInsn::Load32);
10882 #endif
10883 }
10884
10885 void CodeGenerator::visitWasmStoreSlotI64(LWasmStoreSlotI64* ins) {
10886 Register container = ToRegister(ins->containerRef());
10887 Address addr(container, ins->offset());
10888 Register64 value = ToRegister64(ins->value());
10889 // Either 1 or 2 words. As above we register both transactions in the
10890 // 2-word case.
10891 #ifdef JS_64BIT
10892 FaultingCodeOffset fco = masm.store64(value, addr);
10893 EmitSignalNullCheckTrapSite(masm, ins, fco, wasm::TrapMachineInsn::Store64);
10894 #else
10895 FaultingCodeOffsetPair fcop = masm.store64(value, addr);
10896 EmitSignalNullCheckTrapSite(masm, ins, fcop.first,
10897 wasm::TrapMachineInsn::Store32);
10898 EmitSignalNullCheckTrapSite(masm, ins, fcop.second,
10899 wasm::TrapMachineInsn::Store32);
10900 #endif
10901 }
10902
10903 void CodeGenerator::visitWasmStoreElementI64(LWasmStoreElementI64* ins) {
10904 Register base = ToRegister(ins->base());
10905 Register index = ToRegister(ins->index());
10906 BaseIndex addr(base, index, Scale::TimesEight);
10907 Register64 value = ToRegister64(ins->value());
10908 // Either 1 or 2 words. As above we register both transactions in the
10909 // 2-word case.
10910 #ifdef JS_64BIT
10911 FaultingCodeOffset fco = masm.store64(value, addr);
10912 EmitSignalNullCheckTrapSite(masm, ins, fco, wasm::TrapMachineInsn::Store64);
10913 #else
10914 FaultingCodeOffsetPair fcop = masm.store64(value, addr);
10915 EmitSignalNullCheckTrapSite(masm, ins, fcop.first,
10916 wasm::TrapMachineInsn::Store32);
10917 EmitSignalNullCheckTrapSite(masm, ins, fcop.second,
10918 wasm::TrapMachineInsn::Store32);
10919 #endif
10920 }
10921
10922 void CodeGenerator::visitWasmClampTable64Address(
10923 LWasmClampTable64Address* lir) {
10924 #ifdef ENABLE_WASM_MEMORY64
10925 Register64 address = ToRegister64(lir->address());
10926 Register out = ToRegister(lir->output());
10927 masm.wasmClampTable64Address(address, out);
10928 #else
10929 MOZ_CRASH("table64 addresses should not be valid without memory64");
10930 #endif
10931 }
10932
10933 void CodeGenerator::visitArrayBufferByteLength(LArrayBufferByteLength* lir) {
10934 Register obj = ToRegister(lir->object());
10935 Register out = ToRegister(lir->output());
10936 masm.loadArrayBufferByteLengthIntPtr(obj, out);
10937 }
10938
10939 void CodeGenerator::visitArrayBufferViewLength(LArrayBufferViewLength* lir) {
10940 Register obj = ToRegister(lir->object());
10941 Register out = ToRegister(lir->output());
10942 masm.loadArrayBufferViewLengthIntPtr(obj, out);
10943 }
10944
10945 void CodeGenerator::visitArrayBufferViewByteOffset(
10946 LArrayBufferViewByteOffset* lir) {
10947 Register obj = ToRegister(lir->object());
10948 Register out = ToRegister(lir->output());
10949 masm.loadArrayBufferViewByteOffsetIntPtr(obj, out);
10950 }
10951
10952 void CodeGenerator::visitArrayBufferViewElements(
10953 LArrayBufferViewElements* lir) {
10954 Register obj = ToRegister(lir->object());
10955 Register out = ToRegister(lir->output());
10956 masm.loadPtr(Address(obj, ArrayBufferViewObject::dataOffset()), out);
10957 }
10958
10959 void CodeGenerator::visitTypedArrayElementSize(LTypedArrayElementSize* lir) {
10960 Register obj = ToRegister(lir->object());
10961 Register out = ToRegister(lir->output());
10962
10963 masm.typedArrayElementSize(obj, out);
10964 }
10965
10966 void CodeGenerator::visitResizableTypedArrayByteOffsetMaybeOutOfBounds(
10967 LResizableTypedArrayByteOffsetMaybeOutOfBounds* lir) {
10968 Register obj = ToRegister(lir->object());
10969 Register out = ToRegister(lir->output());
10970 Register temp = ToRegister(lir->temp0());
10971
10972 masm.loadResizableTypedArrayByteOffsetMaybeOutOfBoundsIntPtr(obj, out, temp);
10973 }
10974
10975 void CodeGenerator::visitResizableTypedArrayLength(
10976 LResizableTypedArrayLength* lir) {
10977 Register obj = ToRegister(lir->object());
10978 Register out = ToRegister(lir->output());
10979 Register temp = ToRegister(lir->temp0());
10980
10981 masm.loadResizableTypedArrayLengthIntPtr(lir->synchronization(), obj, out,
10982 temp);
10983 }
10984
10985 void CodeGenerator::visitResizableDataViewByteLength(
10986 LResizableDataViewByteLength* lir) {
10987 Register obj = ToRegister(lir->object());
10988 Register out = ToRegister(lir->output());
10989 Register temp = ToRegister(lir->temp0());
10990
10991 masm.loadResizableDataViewByteLengthIntPtr(lir->synchronization(), obj, out,
10992 temp);
10993 }
10994
10995 void CodeGenerator::visitGrowableSharedArrayBufferByteLength(
10996 LGrowableSharedArrayBufferByteLength* lir) {
10997 Register obj = ToRegister(lir->object());
10998 Register out = ToRegister(lir->output());
10999
11000 // Explicit |byteLength| accesses are seq-consistent atomic loads.
11001 auto sync = Synchronization::Load();
11002
11003 masm.loadGrowableSharedArrayBufferByteLengthIntPtr(sync, obj, out);
11004 }
11005
11006 void CodeGenerator::visitGuardResizableArrayBufferViewInBounds(
11007 LGuardResizableArrayBufferViewInBounds* lir) {
11008 Register obj = ToRegister(lir->object());
11009 Register temp = ToRegister(lir->temp0());
11010
11011 Label bail;
11012 masm.branchIfResizableArrayBufferViewOutOfBounds(obj, temp, &bail);
11013 bailoutFrom(&bail, lir->snapshot());
11014 }
11015
11016 void CodeGenerator::visitGuardResizableArrayBufferViewInBoundsOrDetached(
11017 LGuardResizableArrayBufferViewInBoundsOrDetached* lir) {
11018 Register obj = ToRegister(lir->object());
11019 Register temp = ToRegister(lir->temp0());
11020
11021 Label done, bail;
11022 masm.branchIfResizableArrayBufferViewInBounds(obj, temp, &done);
11023 masm.branchIfHasAttachedArrayBuffer(obj, temp, &bail);
11024 masm.bind(&done);
11025 bailoutFrom(&bail, lir->snapshot());
11026 }
11027
11028 void CodeGenerator::visitGuardHasAttachedArrayBuffer(
11029 LGuardHasAttachedArrayBuffer* lir) {
11030 Register obj = ToRegister(lir->object());
11031 Register temp = ToRegister(lir->temp0());
11032
11033 Label bail;
11034 masm.branchIfHasDetachedArrayBuffer(obj, temp, &bail);
11035 bailoutFrom(&bail, lir->snapshot());
11036 }
11037
11038 void CodeGenerator::visitGuardNumberToIntPtrIndex(
11039 LGuardNumberToIntPtrIndex* lir) {
11040 FloatRegister input = ToFloatRegister(lir->input());
11041 Register output = ToRegister(lir->output());
11042
11043 if (!lir->mir()->supportOOB()) {
11044 Label bail;
11045 masm.convertDoubleToPtr(input, output, &bail, false);
11046 bailoutFrom(&bail, lir->snapshot());
11047 return;
11048 }
11049
11050 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
11051 // Substitute the invalid index with an arbitrary out-of-bounds index.
11052 masm.movePtr(ImmWord(-1), output);
11053 masm.jump(ool.rejoin());
11054 });
11055 addOutOfLineCode(ool, lir->mir());
11056
11057 masm.convertDoubleToPtr(input, output, ool->entry(), false);
11058 masm.bind(ool->rejoin());
11059 }
11060
11061 void CodeGenerator::visitStringLength(LStringLength* lir) {
11062 Register input = ToRegister(lir->string());
11063 Register output = ToRegister(lir->output());
11064
11065 masm.loadStringLength(input, output);
11066 }
11067
11068 void CodeGenerator::visitMinMaxI(LMinMaxI* ins) {
11069 Register first = ToRegister(ins->first());
11070 Register output = ToRegister(ins->output());
11071
11072 MOZ_ASSERT(first == output);
11073
11074 Assembler::Condition cond =
11075 ins->mir()->isMax() ? Assembler::GreaterThan : Assembler::LessThan;
11076
11077 if (ins->second()->isConstant()) {
11078 Label done;
11079 masm.branch32(cond, first, Imm32(ToInt32(ins->second())), &done);
11080 masm.move32(Imm32(ToInt32(ins->second())), output);
11081 masm.bind(&done);
11082 } else {
11083 Register second = ToRegister(ins->second());
11084 masm.cmp32Move32(cond, second, first, second, output);
11085 }
11086 }
11087
11088 void CodeGenerator::visitMinMaxArrayI(LMinMaxArrayI* ins) {
11089 Register array = ToRegister(ins->array());
11090 Register output = ToRegister(ins->output());
11091 Register temp1 = ToRegister(ins->temp0());
11092 Register temp2 = ToRegister(ins->temp1());
11093 Register temp3 = ToRegister(ins->temp2());
11094 bool isMax = ins->mir()->isMax();
11095
11096 Label bail;
11097 masm.minMaxArrayInt32(array, output, temp1, temp2, temp3, isMax, &bail);
11098 bailoutFrom(&bail, ins->snapshot());
11099 }
11100
11101 void CodeGenerator::visitMinMaxArrayD(LMinMaxArrayD* ins) {
11102 Register array = ToRegister(ins->array());
11103 FloatRegister output = ToFloatRegister(ins->output());
11104 FloatRegister floatTemp = ToFloatRegister(ins->temp0());
11105 Register temp1 = ToRegister(ins->temp1());
11106 Register temp2 = ToRegister(ins->temp2());
11107 bool isMax = ins->mir()->isMax();
11108
11109 Label bail;
11110 masm.minMaxArrayNumber(array, output, floatTemp, temp1, temp2, isMax, &bail);
11111 bailoutFrom(&bail, ins->snapshot());
11112 }
11113
11114 // For Abs*, lowering will have tied input to output on platforms where that is
11115 // sensible, and otherwise left them untied.
11116
11117 void CodeGenerator::visitAbsI(LAbsI* ins) {
11118 Register input = ToRegister(ins->input());
11119 Register output = ToRegister(ins->output());
11120
11121 if (ins->mir()->fallible()) {
11122 Label positive;
11123 if (input != output) {
11124 masm.move32(input, output);
11125 }
11126 masm.branchTest32(Assembler::NotSigned, output, output, &positive);
11127 Label bail;
11128 masm.branchNeg32(Assembler::Overflow, output, &bail);
11129 bailoutFrom(&bail, ins->snapshot());
11130 masm.bind(&positive);
11131 } else {
11132 masm.abs32(input, output);
11133 }
11134 }
11135
11136 void CodeGenerator::visitAbsD(LAbsD* ins) {
11137 masm.absDouble(ToFloatRegister(ins->input()), ToFloatRegister(ins->output()));
11138 }
11139
11140 void CodeGenerator::visitAbsF(LAbsF* ins) {
11141 masm.absFloat32(ToFloatRegister(ins->input()),
11142 ToFloatRegister(ins->output()));
11143 }
11144
11145 void CodeGenerator::visitPowII(LPowII* ins) {
11146 Register value = ToRegister(ins->value());
11147 Register power = ToRegister(ins->power());
11148 Register output = ToRegister(ins->output());
11149 Register temp0 = ToRegister(ins->temp0());
11150 Register temp1 = ToRegister(ins->temp1());
11151
11152 Label bailout;
11153 masm.pow32(value, power, output, temp0, temp1, &bailout);
11154 bailoutFrom(&bailout, ins->snapshot());
11155 }
11156
11157 void CodeGenerator::visitPowI(LPowI* ins) {
11158 FloatRegister value = ToFloatRegister(ins->value());
11159 Register power = ToRegister(ins->power());
11160
11161 using Fn = double (*)(double x, int32_t y);
11162 masm.setupAlignedABICall();
11163 masm.passABIArg(value, ABIType::Float64);
11164 masm.passABIArg(power);
11165
11166 masm.callWithABI<Fn, js::powi>(ABIType::Float64);
11167 MOZ_ASSERT(ToFloatRegister(ins->output()) == ReturnDoubleReg);
11168 }
11169
11170 void CodeGenerator::visitPowD(LPowD* ins) {
11171 FloatRegister value = ToFloatRegister(ins->value());
11172 FloatRegister power = ToFloatRegister(ins->power());
11173
11174 using Fn = double (*)(double x, double y);
11175 masm.setupAlignedABICall();
11176 masm.passABIArg(value, ABIType::Float64);
11177 masm.passABIArg(power, ABIType::Float64);
11178 masm.callWithABI<Fn, ecmaPow>(ABIType::Float64);
11179
11180 MOZ_ASSERT(ToFloatRegister(ins->output()) == ReturnDoubleReg);
11181 }
11182
11183 void CodeGenerator::visitPowOfTwoI(LPowOfTwoI* ins) {
11184 Register power = ToRegister(ins->power());
11185 Register output = ToRegister(ins->output());
11186
11187 uint32_t base = ins->base();
11188 MOZ_ASSERT(mozilla::IsPowerOfTwo(base));
11189
11190 uint32_t n = mozilla::FloorLog2(base);
11191 MOZ_ASSERT(n != 0);
11192
11193 // Hacker's Delight, 2nd edition, theorem D2.
11194 auto ceilingDiv = [](uint32_t x, uint32_t y) { return (x + y - 1) / y; };
11195
11196 // Take bailout if |power| is greater-or-equals |log_y(2^31)| or is negative.
11197 // |2^(n*y) < 2^31| must hold, hence |n*y < 31| resp. |y < 31/n|.
11198 //
11199 // Note: it's important for this condition to match the code in CacheIR.cpp
11200 // (CanAttachInt32Pow) to prevent failure loops.
11201 bailoutCmp32(Assembler::AboveOrEqual, power, Imm32(ceilingDiv(31, n)),
11202 ins->snapshot());
11203
11204 // Compute (2^n)^y as 2^(n*y) using repeated shifts. We could directly scale
11205 // |power| and perform a single shift, but due to the lack of necessary
11206 // MacroAssembler functionality, like multiplying a register with an
11207 // immediate, we restrict the number of generated shift instructions when
11208 // lowering this operation.
11209 masm.move32(Imm32(1), output);
11210 do {
11211 masm.lshift32(power, output);
11212 n--;
11213 } while (n > 0);
11214 }
11215
11216 void CodeGenerator::visitSqrtD(LSqrtD* ins) {
11217 FloatRegister input = ToFloatRegister(ins->input());
11218 FloatRegister output = ToFloatRegister(ins->output());
11219 masm.sqrtDouble(input, output);
11220 }
11221
11222 void CodeGenerator::visitSqrtF(LSqrtF* ins) {
11223 FloatRegister input = ToFloatRegister(ins->input());
11224 FloatRegister output = ToFloatRegister(ins->output());
11225 masm.sqrtFloat32(input, output);
11226 }
11227
11228 void CodeGenerator::visitSignI(LSignI* ins) {
11229 Register input = ToRegister(ins->input());
11230 Register output = ToRegister(ins->output());
11231 masm.signInt32(input, output);
11232 }
11233
11234 void CodeGenerator::visitSignD(LSignD* ins) {
11235 FloatRegister input = ToFloatRegister(ins->input());
11236 FloatRegister output = ToFloatRegister(ins->output());
11237 masm.signDouble(input, output);
11238 }
11239
11240 void CodeGenerator::visitSignDI(LSignDI* ins) {
11241 FloatRegister input = ToFloatRegister(ins->input());
11242 FloatRegister temp = ToFloatRegister(ins->temp0());
11243 Register output = ToRegister(ins->output());
11244
11245 Label bail;
11246 masm.signDoubleToInt32(input, output, temp, &bail);
11247 bailoutFrom(&bail, ins->snapshot());
11248 }
11249
11250 void CodeGenerator::visitSignID(LSignID* ins) {
11251 Register input = ToRegister(ins->input());
11252 Register temp = ToRegister(ins->temp0());
11253 FloatRegister output = ToFloatRegister(ins->output());
11254
11255 masm.signInt32(input, temp);
11256 masm.convertInt32ToDouble(temp, output);
11257 }
11258
11259 void CodeGenerator::visitMathFunctionD(LMathFunctionD* ins) {
11260 FloatRegister input = ToFloatRegister(ins->input());
11261 MOZ_ASSERT(ToFloatRegister(ins->output()) == ReturnDoubleReg);
11262
11263 UnaryMathFunction fun = ins->mir()->function();
11264 UnaryMathFunctionType funPtr = GetUnaryMathFunctionPtr(fun);
11265
11266 masm.setupAlignedABICall();
11267
11268 masm.passABIArg(input, ABIType::Float64);
11269 masm.callWithABI(DynamicFunction<UnaryMathFunctionType>(funPtr),
11270 ABIType::Float64);
11271 }
11272
11273 void CodeGenerator::visitMathFunctionF(LMathFunctionF* ins) {
11274 FloatRegister input = ToFloatRegister(ins->input());
11275 MOZ_ASSERT(ToFloatRegister(ins->output()) == ReturnFloat32Reg);
11276
11277 masm.setupAlignedABICall();
11278 masm.passABIArg(input, ABIType::Float32);
11279
11280 using Fn = float (*)(float x);
11281 Fn funptr = nullptr;
11282 CheckUnsafeCallWithABI check = CheckUnsafeCallWithABI::Check;
11283 switch (ins->mir()->function()) {
11284 case UnaryMathFunction::Floor:
11285 funptr = floorf;
11286 check = CheckUnsafeCallWithABI::DontCheckOther;
11287 break;
11288 case UnaryMathFunction::Round:
11289 funptr = math_roundf_impl;
11290 break;
11291 case UnaryMathFunction::Trunc:
11292 funptr = math_truncf_impl;
11293 break;
11294 case UnaryMathFunction::Ceil:
11295 funptr = ceilf;
11296 check = CheckUnsafeCallWithABI::DontCheckOther;
11297 break;
11298 default:
11299 MOZ_CRASH("Unknown or unsupported float32 math function");
11300 }
11301
11302 masm.callWithABI(DynamicFunction<Fn>(funptr), ABIType::Float32, check);
11303 }
11304
11305 void CodeGenerator::visitModD(LModD* ins) {
11306 MOZ_ASSERT(!gen->compilingWasm());
11307
11308 FloatRegister lhs = ToFloatRegister(ins->lhs());
11309 FloatRegister rhs = ToFloatRegister(ins->rhs());
11310
11311 MOZ_ASSERT(ToFloatRegister(ins->output()) == ReturnDoubleReg);
11312
11313 using Fn = double (*)(double a, double b);
11314 masm.setupAlignedABICall();
11315 masm.passABIArg(lhs, ABIType::Float64);
11316 masm.passABIArg(rhs, ABIType::Float64);
11317 masm.callWithABI<Fn, NumberMod>(ABIType::Float64);
11318 }
11319
11320 void CodeGenerator::visitModPowTwoD(LModPowTwoD* ins) {
11321 FloatRegister lhs = ToFloatRegister(ins->lhs());
11322 uint32_t divisor = ins->divisor();
11323 MOZ_ASSERT(mozilla::IsPowerOfTwo(divisor));
11324
11325 FloatRegister output = ToFloatRegister(ins->output());
11326
11327 // Compute |n % d| using |copysign(n - (d * trunc(n / d)), n)|.
11328 //
11329 // This doesn't work if |d| isn't a power of two, because we may lose too much
11330 // precision. For example |Number.MAX_VALUE % 3 == 2|, but
11331 // |3 * trunc(Number.MAX_VALUE / 3) == Infinity|.
11332
11333 Label done;
11334 {
11335 ScratchDoubleScope scratch(masm);
11336
11337 // Subnormals can lead to performance degradation, which can make calling
11338 // |fmod| faster than this inline implementation. Work around this issue by
11339 // directly returning the input for any value in the interval ]-1, +1[.
11340 Label notSubnormal;
11341 masm.loadConstantDouble(1.0, scratch);
11342 masm.loadConstantDouble(-1.0, output);
11343 masm.branchDouble(Assembler::DoubleGreaterThanOrEqual, lhs, scratch,
11344 &notSubnormal);
11345 masm.branchDouble(Assembler::DoubleLessThanOrEqual, lhs, output,
11346 &notSubnormal);
11347
11348 masm.moveDouble(lhs, output);
11349 masm.jump(&done);
11350
11351 masm.bind(&notSubnormal);
11352
11353 if (divisor == 1) {
11354 // The pattern |n % 1 == 0| is used to detect integer numbers. We can skip
11355 // the multiplication by one in this case.
11356 masm.moveDouble(lhs, output);
11357 masm.nearbyIntDouble(RoundingMode::TowardsZero, output, scratch);
11358 masm.subDouble(scratch, output);
11359 } else {
11360 masm.loadConstantDouble(1.0 / double(divisor), scratch);
11361 masm.loadConstantDouble(double(divisor), output);
11362
11363 masm.mulDouble(lhs, scratch);
11364 masm.nearbyIntDouble(RoundingMode::TowardsZero, scratch, scratch);
11365 masm.mulDouble(output, scratch);
11366
11367 masm.moveDouble(lhs, output);
11368 masm.subDouble(scratch, output);
11369 }
11370 }
11371
11372 masm.copySignDouble(output, lhs, output);
11373 masm.bind(&done);
11374 }
11375
11376 void CodeGenerator::visitWasmBuiltinModD(LWasmBuiltinModD* ins) {
11377 masm.Push(InstanceReg);
11378 int32_t framePushedAfterInstance = masm.framePushed();
11379
11380 FloatRegister lhs = ToFloatRegister(ins->lhs());
11381 FloatRegister rhs = ToFloatRegister(ins->rhs());
11382
11383 MOZ_ASSERT(ToFloatRegister(ins->output()) == ReturnDoubleReg);
11384
11385 masm.setupWasmABICall();
11386 masm.passABIArg(lhs, ABIType::Float64);
11387 masm.passABIArg(rhs, ABIType::Float64);
11388
11389 int32_t instanceOffset = masm.framePushed() - framePushedAfterInstance;
11390 masm.callWithABI(ins->mir()->bytecodeOffset(), wasm::SymbolicAddress::ModD,
11391 mozilla::Some(instanceOffset), ABIType::Float64);
11392
11393 masm.Pop(InstanceReg);
11394 }
11395
11396 void CodeGenerator::visitClzI(LClzI* ins) {
11397 Register input = ToRegister(ins->input());
11398 Register output = ToRegister(ins->output());
11399 bool knownNotZero = ins->mir()->operandIsNeverZero();
11400
11401 masm.clz32(input, output, knownNotZero);
11402 }
11403
11404 void CodeGenerator::visitCtzI(LCtzI* ins) {
11405 Register input = ToRegister(ins->input());
11406 Register output = ToRegister(ins->output());
11407 bool knownNotZero = ins->mir()->operandIsNeverZero();
11408
11409 masm.ctz32(input, output, knownNotZero);
11410 }
11411
11412 void CodeGenerator::visitPopcntI(LPopcntI* ins) {
11413 Register input = ToRegister(ins->input());
11414 Register output = ToRegister(ins->output());
11415 Register temp = ToRegister(ins->temp0());
11416
11417 masm.popcnt32(input, output, temp);
11418 }
11419
11420 void CodeGenerator::visitClzI64(LClzI64* ins) {
11421 Register64 input = ToRegister64(ins->input());
11422 Register64 output = ToOutRegister64(ins);
11423
11424 masm.clz64(input, output);
11425 }
11426
11427 void CodeGenerator::visitCtzI64(LCtzI64* ins) {
11428 Register64 input = ToRegister64(ins->input());
11429 Register64 output = ToOutRegister64(ins);
11430
11431 masm.ctz64(input, output);
11432 }
11433
11434 void CodeGenerator::visitPopcntI64(LPopcntI64* ins) {
11435 Register64 input = ToRegister64(ins->input());
11436 Register64 output = ToOutRegister64(ins);
11437 Register temp = ToRegister(ins->temp0());
11438
11439 masm.popcnt64(input, output, temp);
11440 }
11441
11442 void CodeGenerator::visitBigIntAdd(LBigIntAdd* ins) {
11443 pushArg(ToRegister(ins->rhs()));
11444 pushArg(ToRegister(ins->lhs()));
11445
11446 using Fn = BigInt* (*)(JSContext*, HandleBigInt, HandleBigInt);
11447 callVM<Fn, BigInt::add>(ins);
11448 }
11449
11450 void CodeGenerator::visitBigIntSub(LBigIntSub* ins) {
11451 pushArg(ToRegister(ins->rhs()));
11452 pushArg(ToRegister(ins->lhs()));
11453
11454 using Fn = BigInt* (*)(JSContext*, HandleBigInt, HandleBigInt);
11455 callVM<Fn, BigInt::sub>(ins);
11456 }
11457
11458 void CodeGenerator::visitBigIntMul(LBigIntMul* ins) {
11459 pushArg(ToRegister(ins->rhs()));
11460 pushArg(ToRegister(ins->lhs()));
11461
11462 using Fn = BigInt* (*)(JSContext*, HandleBigInt, HandleBigInt);
11463 callVM<Fn, BigInt::mul>(ins);
11464 }
11465
11466 void CodeGenerator::visitBigIntDiv(LBigIntDiv* ins) {
11467 pushArg(ToRegister(ins->rhs()));
11468 pushArg(ToRegister(ins->lhs()));
11469
11470 using Fn = BigInt* (*)(JSContext*, HandleBigInt, HandleBigInt);
11471 callVM<Fn, BigInt::div>(ins);
11472 }
11473
11474 void CodeGenerator::visitBigIntMod(LBigIntMod* ins) {
11475 pushArg(ToRegister(ins->rhs()));
11476 pushArg(ToRegister(ins->lhs()));
11477
11478 using Fn = BigInt* (*)(JSContext*, HandleBigInt, HandleBigInt);
11479 callVM<Fn, BigInt::mod>(ins);
11480 }
11481
11482 void CodeGenerator::visitBigIntPow(LBigIntPow* ins) {
11483 pushArg(ToRegister(ins->rhs()));
11484 pushArg(ToRegister(ins->lhs()));
11485
11486 using Fn = BigInt* (*)(JSContext*, HandleBigInt, HandleBigInt);
11487 callVM<Fn, BigInt::pow>(ins);
11488 }
11489
11490 void CodeGenerator::visitBigIntBitAnd(LBigIntBitAnd* ins) {
11491 pushArg(ToRegister(ins->rhs()));
11492 pushArg(ToRegister(ins->lhs()));
11493
11494 using Fn = BigInt* (*)(JSContext*, HandleBigInt, HandleBigInt);
11495 callVM<Fn, BigInt::bitAnd>(ins);
11496 }
11497
11498 void CodeGenerator::visitBigIntBitOr(LBigIntBitOr* ins) {
11499 pushArg(ToRegister(ins->rhs()));
11500 pushArg(ToRegister(ins->lhs()));
11501
11502 using Fn = BigInt* (*)(JSContext*, HandleBigInt, HandleBigInt);
11503 callVM<Fn, BigInt::bitOr>(ins);
11504 }
11505
11506 void CodeGenerator::visitBigIntBitXor(LBigIntBitXor* ins) {
11507 pushArg(ToRegister(ins->rhs()));
11508 pushArg(ToRegister(ins->lhs()));
11509
11510 using Fn = BigInt* (*)(JSContext*, HandleBigInt, HandleBigInt);
11511 callVM<Fn, BigInt::bitXor>(ins);
11512 }
11513
11514 void CodeGenerator::visitBigIntLsh(LBigIntLsh* ins) {
11515 pushArg(ToRegister(ins->rhs()));
11516 pushArg(ToRegister(ins->lhs()));
11517
11518 using Fn = BigInt* (*)(JSContext*, HandleBigInt, HandleBigInt);
11519 callVM<Fn, BigInt::lsh>(ins);
11520 }
11521
11522 void CodeGenerator::visitBigIntRsh(LBigIntRsh* ins) {
11523 pushArg(ToRegister(ins->rhs()));
11524 pushArg(ToRegister(ins->lhs()));
11525
11526 using Fn = BigInt* (*)(JSContext*, HandleBigInt, HandleBigInt);
11527 callVM<Fn, BigInt::rsh>(ins);
11528 }
11529
11530 void CodeGenerator::visitBigIntIncrement(LBigIntIncrement* ins) {
11531 pushArg(ToRegister(ins->input()));
11532
11533 using Fn = BigInt* (*)(JSContext*, HandleBigInt);
11534 callVM<Fn, BigInt::inc>(ins);
11535 }
11536
11537 void CodeGenerator::visitBigIntDecrement(LBigIntDecrement* ins) {
11538 pushArg(ToRegister(ins->input()));
11539
11540 using Fn = BigInt* (*)(JSContext*, HandleBigInt);
11541 callVM<Fn, BigInt::dec>(ins);
11542 }
11543
11544 void CodeGenerator::visitBigIntNegate(LBigIntNegate* ins) {
11545 Register input = ToRegister(ins->input());
11546 Register temp = ToRegister(ins->temp0());
11547 Register output = ToRegister(ins->output());
11548
11549 using Fn = BigInt* (*)(JSContext*, HandleBigInt);
11550 auto* ool =
11551 oolCallVM<Fn, BigInt::neg>(ins, ArgList(input), StoreRegisterTo(output));
11552
11553 // -0n == 0n
11554 Label lhsNonZero;
11555 masm.branchIfBigIntIsNonZero(input, &lhsNonZero);
11556 masm.movePtr(input, output);
11557 masm.jump(ool->rejoin());
11558 masm.bind(&lhsNonZero);
11559
11560 // Call into the VM when the input uses heap digits.
11561 masm.copyBigIntWithInlineDigits(input, output, temp, initialBigIntHeap(),
11562 ool->entry());
11563
11564 // Flip the sign bit.
11565 masm.xor32(Imm32(BigInt::signBitMask()),
11566 Address(output, BigInt::offsetOfFlags()));
11567
11568 masm.bind(ool->rejoin());
11569 }
11570
11571 void CodeGenerator::visitBigIntBitNot(LBigIntBitNot* ins) {
11572 pushArg(ToRegister(ins->input()));
11573
11574 using Fn = BigInt* (*)(JSContext*, HandleBigInt);
11575 callVM<Fn, BigInt::bitNot>(ins);
11576 }
11577
11578 void CodeGenerator::visitBigIntToIntPtr(LBigIntToIntPtr* ins) {
11579 Register input = ToRegister(ins->input());
11580 Register output = ToRegister(ins->output());
11581
11582 Label bail;
11583 masm.loadBigIntPtr(input, output, &bail);
11584 bailoutFrom(&bail, ins->snapshot());
11585 }
11586
11587 void CodeGenerator::visitIntPtrToBigInt(LIntPtrToBigInt* ins) {
11588 Register input = ToRegister(ins->input());
11589 Register temp = ToRegister(ins->temp0());
11590 Register output = ToRegister(ins->output());
11591
11592 using Fn = BigInt* (*)(JSContext*, intptr_t);
11593 auto* ool = oolCallVM<Fn, JS::BigInt::createFromIntPtr>(
11594 ins, ArgList(input), StoreRegisterTo(output));
11595
11596 masm.newGCBigInt(output, temp, initialBigIntHeap(), ool->entry());
11597 masm.movePtr(input, temp);
11598 masm.initializeBigIntPtr(output, temp);
11599
11600 masm.bind(ool->rejoin());
11601 }
11602
11603 void CodeGenerator::visitBigIntPtrAdd(LBigIntPtrAdd* ins) {
11604 Register lhs = ToRegister(ins->lhs());
11605 const LAllocation* rhs = ins->rhs();
11606 Register output = ToRegister(ins->output());
11607
11608 if (rhs->isConstant()) {
11609 masm.movePtr(ImmWord(ToIntPtr(rhs)), output);
11610 } else {
11611 masm.movePtr(ToRegister(rhs), output);
11612 }
11613
11614 Label bail;
11615 masm.branchAddPtr(Assembler::Overflow, lhs, output, &bail);
11616 bailoutFrom(&bail, ins->snapshot());
11617 }
11618
11619 void CodeGenerator::visitBigIntPtrSub(LBigIntPtrSub* ins) {
11620 Register lhs = ToRegister(ins->lhs());
11621 Register rhs = ToRegister(ins->rhs());
11622 Register output = ToRegister(ins->output());
11623
11624 Label bail;
11625 masm.movePtr(lhs, output);
11626 masm.branchSubPtr(Assembler::Overflow, rhs, output, &bail);
11627 bailoutFrom(&bail, ins->snapshot());
11628 }
11629
11630 void CodeGenerator::visitBigIntPtrMul(LBigIntPtrMul* ins) {
11631 Register lhs = ToRegister(ins->lhs());
11632 const LAllocation* rhs = ins->rhs();
11633 Register output = ToRegister(ins->output());
11634
11635 if (rhs->isConstant()) {
11636 masm.movePtr(ImmWord(ToIntPtr(rhs)), output);
11637 } else {
11638 masm.movePtr(ToRegister(rhs), output);
11639 }
11640
11641 Label bail;
11642 masm.branchMulPtr(Assembler::Overflow, lhs, output, &bail);
11643 bailoutFrom(&bail, ins->snapshot());
11644 }
11645
11646 void CodeGenerator::visitBigIntPtrDiv(LBigIntPtrDiv* ins) {
11647 Register lhs = ToRegister(ins->lhs());
11648 Register rhs = ToRegister(ins->rhs());
11649 Register output = ToRegister(ins->output());
11650
11651 // x / 0 throws an error.
11652 Label bail;
11653 if (ins->mir()->canBeDivideByZero()) {
11654 masm.branchPtr(Assembler::Equal, rhs, Imm32(0), &bail);
11655 }
11656
11657 static constexpr auto DigitMin = std::numeric_limits<
11658 mozilla::SignedStdintTypeForSize<sizeof(BigInt::Digit)>::Type>::min();
11659
11660 // Handle an integer overflow from INT{32,64}_MIN / -1.
11661 Label notOverflow;
11662 masm.branchPtr(Assembler::NotEqual, lhs, ImmWord(DigitMin), &notOverflow);
11663 masm.branchPtr(Assembler::Equal, rhs, Imm32(-1), &bail);
11664 masm.bind(&notOverflow);
11665
11666 emitBigIntPtrDiv(ins, lhs, rhs, output);
11667
11668 bailoutFrom(&bail, ins->snapshot());
11669 }
11670
11671 void CodeGenerator::visitBigIntPtrDivPowTwo(LBigIntPtrDivPowTwo* ins) {
11672 Register lhs = ToRegister(ins->lhs());
11673 Register output = ToRegister(ins->output());
11674 int32_t shift = ins->shift();
11675 bool negativeDivisor = ins->negativeDivisor();
11676
11677 masm.movePtr(lhs, output);
11678
11679 if (shift) {
11680 // Adjust the value so that shifting produces a correctly rounded result
11681 // when the numerator is negative.
11682 // See 10-1 "Signed Division by a Known Power of 2" in Henry S. Warren,
11683 // Jr.'s Hacker's Delight.
11684
11685 constexpr size_t bits = BigInt::DigitBits;
11686
11687 if (shift > 1) {
11688 // Copy the sign bit of the numerator. (= (2^bits - 1) or 0)
11689 masm.rshiftPtrArithmetic(Imm32(bits - 1), output);
11690 }
11691
11692 // Divide by 2^(bits - shift)
11693 // i.e. (= (2^bits - 1) / 2^(bits - shift) or 0)
11694 // i.e. (= (2^shift - 1) or 0)
11695 masm.rshiftPtr(Imm32(bits - shift), output);
11696
11697 // If signed, make any 1 bit below the shifted bits to bubble up, such that
11698 // once shifted the value would be rounded towards 0.
11699 masm.addPtr(lhs, output);
11700
11701 masm.rshiftPtrArithmetic(Imm32(shift), output);
11702
11703 if (negativeDivisor) {
11704 masm.negPtr(output);
11705 }
11706 } else if (negativeDivisor) {
11707 Label bail;
11708 masm.branchNegPtr(Assembler::Overflow, output, &bail);
11709 bailoutFrom(&bail, ins->snapshot());
11710 }
11711 }
11712
11713 void CodeGenerator::visitBigIntPtrMod(LBigIntPtrMod* ins) {
11714 Register lhs = ToRegister(ins->lhs());
11715 Register rhs = ToRegister(ins->rhs());
11716 Register output = ToRegister(ins->output());
11717 Register temp = ToRegister(ins->temp0());
11718
11719 // x % 0 throws an error.
11720 if (ins->mir()->canBeDivideByZero()) {
11721 bailoutCmpPtr(Assembler::Equal, rhs, Imm32(0), ins->snapshot());
11722 }
11723
11724 static constexpr auto DigitMin = std::numeric_limits<
11725 mozilla::SignedStdintTypeForSize<sizeof(BigInt::Digit)>::Type>::min();
11726
11727 masm.movePtr(lhs, temp);
11728
11729 // Handle an integer overflow from INT{32,64}_MIN / -1.
11730 Label notOverflow;
11731 masm.branchPtr(Assembler::NotEqual, lhs, ImmWord(DigitMin), &notOverflow);
11732 masm.branchPtr(Assembler::NotEqual, rhs, Imm32(-1), &notOverflow);
11733 masm.movePtr(ImmWord(0), temp);
11734 masm.bind(&notOverflow);
11735
11736 emitBigIntPtrMod(ins, temp, rhs, output);
11737 }
11738
11739 void CodeGenerator::visitBigIntPtrModPowTwo(LBigIntPtrModPowTwo* ins) {
11740 Register lhs = ToRegister(ins->lhs());
11741 Register output = ToRegister(ins->output());
11742 Register temp = ToRegister(ins->temp0());
11743 int32_t shift = ins->shift();
11744
11745 masm.movePtr(lhs, output);
11746 masm.movePtr(ImmWord((uintptr_t(1) << shift) - uintptr_t(1)), temp);
11747
11748 // Switch based on sign of the lhs.
11749
11750 // Positive numbers are just a bitmask.
11751 Label negative;
11752 masm.branchTestPtr(Assembler::Signed, lhs, lhs, &negative);
11753
11754 masm.andPtr(temp, output);
11755
11756 Label done;
11757 masm.jump(&done);
11758
11759 // Negative numbers need a negate, bitmask, negate
11760 masm.bind(&negative);
11761
11762 masm.negPtr(output);
11763 masm.andPtr(temp, output);
11764 masm.negPtr(output);
11765
11766 masm.bind(&done);
11767 }
11768
11769 void CodeGenerator::visitBigIntPtrPow(LBigIntPtrPow* ins) {
11770 Register lhs = ToRegister(ins->lhs());
11771 Register rhs = ToRegister(ins->rhs());
11772 Register output = ToRegister(ins->output());
11773 Register temp0 = ToRegister(ins->temp0());
11774 Register temp1 = ToRegister(ins->temp1());
11775
11776 Label bail;
11777 masm.powPtr(lhs, rhs, output, temp0, temp1, &bail);
11778 bailoutFrom(&bail, ins->snapshot());
11779 }
11780
11781 void CodeGenerator::visitBigIntPtrBitAnd(LBigIntPtrBitAnd* ins) {
11782 Register lhs = ToRegister(ins->lhs());
11783 const LAllocation* rhs = ins->rhs();
11784 Register output = ToRegister(ins->output());
11785
11786 if (rhs->isConstant()) {
11787 masm.movePtr(ImmWord(ToIntPtr(rhs)), output);
11788 } else {
11789 masm.movePtr(ToRegister(rhs), output);
11790 }
11791 masm.andPtr(lhs, output);
11792 }
11793
11794 void CodeGenerator::visitBigIntPtrBitOr(LBigIntPtrBitOr* ins) {
11795 Register lhs = ToRegister(ins->lhs());
11796 const LAllocation* rhs = ins->rhs();
11797 Register output = ToRegister(ins->output());
11798
11799 if (rhs->isConstant()) {
11800 masm.movePtr(ImmWord(ToIntPtr(rhs)), output);
11801 } else {
11802 masm.movePtr(ToRegister(rhs), output);
11803 }
11804 masm.orPtr(lhs, output);
11805 }
11806
11807 void CodeGenerator::visitBigIntPtrBitXor(LBigIntPtrBitXor* ins) {
11808 Register lhs = ToRegister(ins->lhs());
11809 const LAllocation* rhs = ins->rhs();
11810 Register output = ToRegister(ins->output());
11811
11812 if (rhs->isConstant()) {
11813 masm.movePtr(ImmWord(ToIntPtr(rhs)), output);
11814 } else {
11815 masm.movePtr(ToRegister(rhs), output);
11816 }
11817 masm.xorPtr(lhs, output);
11818 }
11819
11820 void CodeGenerator::visitBigIntPtrLsh(LBigIntPtrLsh* ins) {
11821 Register lhs = ToRegister(ins->lhs());
11822 Register output = ToRegister(ins->output());
11823 Register temp = ToTempRegisterOrInvalid(ins->temp0());
11824 Register tempShift = ToTempRegisterOrInvalid(ins->temp1());
11825
11826 if (ins->rhs()->isConstant()) {
11827 intptr_t rhs = ToIntPtr(ins->rhs());
11828
11829 if (rhs >= intptr_t(BigInt::DigitBits)) {
11830 MOZ_ASSERT(ins->mir()->fallible());
11831
11832 // x << DigitBits with x != 0n always exceeds pointer-sized storage.
11833 masm.movePtr(ImmWord(0), output);
11834 bailoutCmpPtr(Assembler::NotEqual, lhs, Imm32(0), ins->snapshot());
11835 } else if (rhs <= -intptr_t(BigInt::DigitBits)) {
11836 MOZ_ASSERT(!ins->mir()->fallible());
11837
11838 // x << -DigitBits == x >> DigitBits, which is either 0n or -1n.
11839 masm.rshiftPtrArithmetic(Imm32(BigInt::DigitBits - 1), lhs, output);
11840 } else if (rhs <= 0) {
11841 MOZ_ASSERT(!ins->mir()->fallible());
11842
11843 // |x << -y| is computed as |x >> y|.
11844 masm.rshiftPtrArithmetic(Imm32(-rhs), lhs, output);
11845 } else {
11846 MOZ_ASSERT(ins->mir()->fallible());
11847
11848 masm.lshiftPtr(Imm32(rhs), lhs, output);
11849
11850 // Check for overflow: ((lhs << rhs) >> rhs) == lhs.
11851 masm.rshiftPtrArithmetic(Imm32(rhs), output, temp);
11852 bailoutCmpPtr(Assembler::NotEqual, temp, lhs, ins->snapshot());
11853 }
11854 } else {
11855 Register rhs = ToRegister(ins->rhs());
11856
11857 Label done, bail;
11858 MOZ_ASSERT(ins->mir()->fallible());
11859
11860 masm.movePtr(lhs, output);
11861
11862 // 0n << x == 0n
11863 masm.branchPtr(Assembler::Equal, lhs, Imm32(0), &done);
11864
11865 // x << DigitBits with x != 0n always exceeds pointer-sized storage.
11866 masm.branchPtr(Assembler::GreaterThanOrEqual, rhs, Imm32(BigInt::DigitBits),
11867 &bail);
11868
11869 // x << -DigitBits == x >> DigitBits, which is either 0n or -1n.
11870 Label shift;
11871 masm.branchPtr(Assembler::GreaterThan, rhs,
11872 Imm32(-int32_t(BigInt::DigitBits)), &shift);
11873 {
11874 masm.rshiftPtrArithmetic(Imm32(BigInt::DigitBits - 1), output);
11875 masm.jump(&done);
11876 }
11877 masm.bind(&shift);
11878
11879 // Move |rhs| into the designated shift register.
11880 masm.movePtr(rhs, tempShift);
11881
11882 // |x << -y| is computed as |x >> y|.
11883 Label leftShift;
11884 masm.branchPtr(Assembler::GreaterThanOrEqual, rhs, Imm32(0), &leftShift);
11885 {
11886 masm.negPtr(tempShift);
11887 masm.rshiftPtrArithmetic(tempShift, output);
11888 masm.jump(&done);
11889 }
11890 masm.bind(&leftShift);
11891
11892 masm.lshiftPtr(tempShift, output);
11893
11894 // Check for overflow: ((lhs << rhs) >> rhs) == lhs.
11895 masm.movePtr(output, temp);
11896 masm.rshiftPtrArithmetic(tempShift, temp);
11897 masm.branchPtr(Assembler::NotEqual, temp, lhs, &bail);
11898
11899 masm.bind(&done);
11900 bailoutFrom(&bail, ins->snapshot());
11901 }
11902 }
11903
11904 void CodeGenerator::visitBigIntPtrRsh(LBigIntPtrRsh* ins) {
11905 Register lhs = ToRegister(ins->lhs());
11906 Register output = ToRegister(ins->output());
11907 Register temp = ToTempRegisterOrInvalid(ins->temp0());
11908 Register tempShift = ToTempRegisterOrInvalid(ins->temp1());
11909
11910 if (ins->rhs()->isConstant()) {
11911 intptr_t rhs = ToIntPtr(ins->rhs());
11912
11913 if (rhs <= -intptr_t(BigInt::DigitBits)) {
11914 MOZ_ASSERT(ins->mir()->fallible());
11915
11916 // x >> -DigitBits == x << DigitBits, which exceeds pointer-sized storage.
11917 masm.movePtr(ImmWord(0), output);
11918 bailoutCmpPtr(Assembler::NotEqual, lhs, Imm32(0), ins->snapshot());
11919 } else if (rhs >= intptr_t(BigInt::DigitBits)) {
11920 MOZ_ASSERT(!ins->mir()->fallible());
11921
11922 // x >> DigitBits is either 0n or -1n.
11923 masm.rshiftPtrArithmetic(Imm32(BigInt::DigitBits - 1), lhs, output);
11924 } else if (rhs < 0) {
11925 MOZ_ASSERT(ins->mir()->fallible());
11926
11927 // |x >> -y| is computed as |x << y|.
11928 masm.lshiftPtr(Imm32(-rhs), lhs, output);
11929
11930 // Check for overflow: ((lhs << rhs) >> rhs) == lhs.
11931 masm.rshiftPtrArithmetic(Imm32(-rhs), output, temp);
11932 bailoutCmpPtr(Assembler::NotEqual, temp, lhs, ins->snapshot());
11933 } else {
11934 MOZ_ASSERT(!ins->mir()->fallible());
11935
11936 masm.rshiftPtrArithmetic(Imm32(rhs), lhs, output);
11937 }
11938 } else {
11939 Register rhs = ToRegister(ins->rhs());
11940
11941 Label done, bail;
11942 MOZ_ASSERT(ins->mir()->fallible());
11943
11944 masm.movePtr(lhs, output);
11945
11946 // 0n >> x == 0n
11947 masm.branchPtr(Assembler::Equal, lhs, Imm32(0), &done);
11948
11949 // x >> -DigitBits == x << DigitBits, which exceeds pointer-sized storage.
11950 masm.branchPtr(Assembler::LessThanOrEqual, rhs,
11951 Imm32(-int32_t(BigInt::DigitBits)), &bail);
11952
11953 // x >> DigitBits is either 0n or -1n.
11954 Label shift;
11955 masm.branchPtr(Assembler::LessThan, rhs, Imm32(BigInt::DigitBits), &shift);
11956 {
11957 masm.rshiftPtrArithmetic(Imm32(BigInt::DigitBits - 1), output);
11958 masm.jump(&done);
11959 }
11960 masm.bind(&shift);
11961
11962 // Move |rhs| into the designated shift register.
11963 masm.movePtr(rhs, tempShift);
11964
11965 // |x >> -y| is computed as |x << y|.
11966 Label rightShift;
11967 masm.branchPtr(Assembler::GreaterThanOrEqual, rhs, Imm32(0), &rightShift);
11968 {
11969 masm.negPtr(tempShift);
11970 masm.lshiftPtr(tempShift, output);
11971
11972 // Check for overflow: ((lhs << rhs) >> rhs) == lhs.
11973 masm.movePtr(output, temp);
11974 masm.rshiftPtrArithmetic(tempShift, temp);
11975 masm.branchPtr(Assembler::NotEqual, temp, lhs, &bail);
11976
11977 masm.jump(&done);
11978 }
11979 masm.bind(&rightShift);
11980
11981 masm.rshiftPtrArithmetic(tempShift, output);
11982
11983 masm.bind(&done);
11984 bailoutFrom(&bail, ins->snapshot());
11985 }
11986 }
11987
11988 void CodeGenerator::visitBigIntPtrBitNot(LBigIntPtrBitNot* ins) {
11989 Register input = ToRegister(ins->input());
11990 Register output = ToRegister(ins->output());
11991
11992 masm.movePtr(input, output);
11993 masm.notPtr(output);
11994 }
11995
11996 void CodeGenerator::visitInt32ToStringWithBase(LInt32ToStringWithBase* lir) {
11997 Register input = ToRegister(lir->input());
11998 RegisterOrInt32 base = ToRegisterOrInt32(lir->base());
11999 Register output = ToRegister(lir->output());
12000 Register temp0 = ToRegister(lir->temp0());
12001 Register temp1 = ToRegister(lir->temp1());
12002
12003 bool lowerCase = lir->mir()->lowerCase();
12004
12005 using Fn = JSLinearString* (*)(JSContext*, int32_t, int32_t, bool);
12006 if (base.is<Register>()) {
12007 auto* ool = oolCallVM<Fn, js::Int32ToStringWithBase<CanGC>>(
12008 lir, ArgList(input, base.as<Register>(), Imm32(lowerCase)),
12009 StoreRegisterTo(output));
12010
12011 LiveRegisterSet liveRegs = liveVolatileRegs(lir);
12012 masm.loadInt32ToStringWithBase(input, base.as<Register>(), output, temp0,
12013 temp1, gen->runtime->staticStrings(),
12014 liveRegs, lowerCase, ool->entry());
12015 masm.bind(ool->rejoin());
12016 } else {
12017 auto* ool = oolCallVM<Fn, js::Int32ToStringWithBase<CanGC>>(
12018 lir, ArgList(input, Imm32(base.as<int32_t>()), Imm32(lowerCase)),
12019 StoreRegisterTo(output));
12020
12021 masm.loadInt32ToStringWithBase(input, base.as<int32_t>(), output, temp0,
12022 temp1, gen->runtime->staticStrings(),
12023 lowerCase, ool->entry());
12024 masm.bind(ool->rejoin());
12025 }
12026 }
12027
12028 void CodeGenerator::visitNumberParseInt(LNumberParseInt* lir) {
12029 Register string = ToRegister(lir->string());
12030 Register radix = ToRegister(lir->radix());
12031 ValueOperand output = ToOutValue(lir);
12032 Register temp = ToRegister(lir->temp0());
12033
12034 #ifdef DEBUG
12035 Label ok;
12036 masm.branch32(Assembler::Equal, radix, Imm32(0), &ok);
12037 masm.branch32(Assembler::Equal, radix, Imm32(10), &ok);
12038 masm.assumeUnreachable("radix must be 0 or 10 for indexed value fast path");
12039 masm.bind(&ok);
12040 #endif
12041
12042 // Use indexed value as fast path if possible.
12043 Label vmCall, done;
12044 masm.loadStringIndexValue(string, temp, &vmCall);
12045 masm.tagValue(JSVAL_TYPE_INT32, temp, output);
12046 masm.jump(&done);
12047 {
12048 masm.bind(&vmCall);
12049
12050 pushArg(radix);
12051 pushArg(string);
12052
12053 using Fn = bool (*)(JSContext*, HandleString, int32_t, MutableHandleValue);
12054 callVM<Fn, js::NumberParseInt>(lir);
12055 }
12056 masm.bind(&done);
12057 }
12058
12059 void CodeGenerator::visitDoubleParseInt(LDoubleParseInt* lir) {
12060 FloatRegister number = ToFloatRegister(lir->number());
12061 Register output = ToRegister(lir->output());
12062 FloatRegister temp = ToFloatRegister(lir->temp0());
12063
12064 Label bail;
12065 masm.branchDouble(Assembler::DoubleUnordered, number, number, &bail);
12066 masm.branchTruncateDoubleToInt32(number, output, &bail);
12067
12068 Label ok;
12069 masm.branch32(Assembler::NotEqual, output, Imm32(0), &ok);
12070 {
12071 // Accept both +0 and -0 and return 0.
12072 masm.loadConstantDouble(0.0, temp);
12073 masm.branchDouble(Assembler::DoubleEqual, number, temp, &ok);
12074
12075 // Fail if a non-zero input is in the exclusive range (-1, 1.0e-6).
12076 masm.loadConstantDouble(DOUBLE_DECIMAL_IN_SHORTEST_LOW, temp);
12077 masm.branchDouble(Assembler::DoubleLessThan, number, temp, &bail);
12078 }
12079 masm.bind(&ok);
12080
12081 bailoutFrom(&bail, lir->snapshot());
12082 }
12083
12084 void CodeGenerator::visitFloor(LFloor* lir) {
12085 FloatRegister input = ToFloatRegister(lir->input());
12086 Register output = ToRegister(lir->output());
12087
12088 Label bail;
12089 masm.floorDoubleToInt32(input, output, &bail);
12090 bailoutFrom(&bail, lir->snapshot());
12091 }
12092
12093 void CodeGenerator::visitFloorF(LFloorF* lir) {
12094 FloatRegister input = ToFloatRegister(lir->input());
12095 Register output = ToRegister(lir->output());
12096
12097 Label bail;
12098 masm.floorFloat32ToInt32(input, output, &bail);
12099 bailoutFrom(&bail, lir->snapshot());
12100 }
12101
12102 void CodeGenerator::visitCeil(LCeil* lir) {
12103 FloatRegister input = ToFloatRegister(lir->input());
12104 Register output = ToRegister(lir->output());
12105
12106 Label bail;
12107 masm.ceilDoubleToInt32(input, output, &bail);
12108 bailoutFrom(&bail, lir->snapshot());
12109 }
12110
12111 void CodeGenerator::visitCeilF(LCeilF* lir) {
12112 FloatRegister input = ToFloatRegister(lir->input());
12113 Register output = ToRegister(lir->output());
12114
12115 Label bail;
12116 masm.ceilFloat32ToInt32(input, output, &bail);
12117 bailoutFrom(&bail, lir->snapshot());
12118 }
12119
12120 void CodeGenerator::visitRound(LRound* lir) {
12121 FloatRegister input = ToFloatRegister(lir->input());
12122 FloatRegister temp = ToFloatRegister(lir->temp0());
12123 Register output = ToRegister(lir->output());
12124
12125 Label bail;
12126 masm.roundDoubleToInt32(input, output, temp, &bail);
12127 bailoutFrom(&bail, lir->snapshot());
12128 }
12129
12130 void CodeGenerator::visitRoundF(LRoundF* lir) {
12131 FloatRegister input = ToFloatRegister(lir->input());
12132 FloatRegister temp = ToFloatRegister(lir->temp0());
12133 Register output = ToRegister(lir->output());
12134
12135 Label bail;
12136 masm.roundFloat32ToInt32(input, output, temp, &bail);
12137 bailoutFrom(&bail, lir->snapshot());
12138 }
12139
12140 void CodeGenerator::visitTrunc(LTrunc* lir) {
12141 FloatRegister input = ToFloatRegister(lir->input());
12142 Register output = ToRegister(lir->output());
12143
12144 Label bail;
12145 masm.truncDoubleToInt32(input, output, &bail);
12146 bailoutFrom(&bail, lir->snapshot());
12147 }
12148
12149 void CodeGenerator::visitTruncF(LTruncF* lir) {
12150 FloatRegister input = ToFloatRegister(lir->input());
12151 Register output = ToRegister(lir->output());
12152
12153 Label bail;
12154 masm.truncFloat32ToInt32(input, output, &bail);
12155 bailoutFrom(&bail, lir->snapshot());
12156 }
12157
12158 void CodeGenerator::visitCompareS(LCompareS* lir) {
12159 JSOp op = lir->mir()->jsop();
12160 Register left = ToRegister(lir->left());
12161 Register right = ToRegister(lir->right());
12162 Register output = ToRegister(lir->output());
12163
12164 OutOfLineCode* ool = nullptr;
12165
12166 using Fn = bool (*)(JSContext*, HandleString, HandleString, bool*);
12167 if (op == JSOp::Eq || op == JSOp::StrictEq) {
12168 ool = oolCallVM<Fn, jit::StringsEqual<EqualityKind::Equal>>(
12169 lir, ArgList(left, right), StoreRegisterTo(output));
12170 } else if (op == JSOp::Ne || op == JSOp::StrictNe) {
12171 ool = oolCallVM<Fn, jit::StringsEqual<EqualityKind::NotEqual>>(
12172 lir, ArgList(left, right), StoreRegisterTo(output));
12173 } else if (op == JSOp::Lt) {
12174 ool = oolCallVM<Fn, jit::StringsCompare<ComparisonKind::LessThan>>(
12175 lir, ArgList(left, right), StoreRegisterTo(output));
12176 } else if (op == JSOp::Le) {
12177 // Push the operands in reverse order for JSOp::Le:
12178 // - |left <= right| is implemented as |right >= left|.
12179 ool =
12180 oolCallVM<Fn, jit::StringsCompare<ComparisonKind::GreaterThanOrEqual>>(
12181 lir, ArgList(right, left), StoreRegisterTo(output));
12182 } else if (op == JSOp::Gt) {
12183 // Push the operands in reverse order for JSOp::Gt:
12184 // - |left > right| is implemented as |right < left|.
12185 ool = oolCallVM<Fn, jit::StringsCompare<ComparisonKind::LessThan>>(
12186 lir, ArgList(right, left), StoreRegisterTo(output));
12187 } else {
12188 MOZ_ASSERT(op == JSOp::Ge);
12189 ool =
12190 oolCallVM<Fn, jit::StringsCompare<ComparisonKind::GreaterThanOrEqual>>(
12191 lir, ArgList(left, right), StoreRegisterTo(output));
12192 }
12193
12194 masm.compareStrings(op, left, right, output, ool->entry());
12195
12196 masm.bind(ool->rejoin());
12197 }
12198
12199 void CodeGenerator::visitCompareSInline(LCompareSInline* lir) {
12200 JSOp op = lir->mir()->jsop();
12201 MOZ_ASSERT(IsEqualityOp(op));
12202
12203 Register input = ToRegister(lir->input());
12204 Register output = ToRegister(lir->output());
12205
12206 const JSLinearString* str = lir->constant();
12207 MOZ_ASSERT(str->length() > 0);
12208
12209 OutOfLineCode* ool = nullptr;
12210
12211 using Fn = bool (*)(JSContext*, HandleString, HandleString, bool*);
12212 if (op == JSOp::Eq || op == JSOp::StrictEq) {
12213 ool = oolCallVM<Fn, jit::StringsEqual<EqualityKind::Equal>>(
12214 lir, ArgList(ImmGCPtr(str), input), StoreRegisterTo(output));
12215 } else {
12216 MOZ_ASSERT(op == JSOp::Ne || op == JSOp::StrictNe);
12217 ool = oolCallVM<Fn, jit::StringsEqual<EqualityKind::NotEqual>>(
12218 lir, ArgList(ImmGCPtr(str), input), StoreRegisterTo(output));
12219 }
12220
12221 Label compareChars;
12222 {
12223 Label notPointerEqual;
12224
12225 // If operands point to the same instance, the strings are trivially equal.
12226 masm.branchPtr(Assembler::NotEqual, input, ImmGCPtr(str), &notPointerEqual);
12227 masm.move32(Imm32(op == JSOp::Eq || op == JSOp::StrictEq), output);
12228 masm.jump(ool->rejoin());
12229
12230 masm.bind(&notPointerEqual);
12231
12232 Label setNotEqualResult;
12233
12234 if (str->isAtom()) {
12235 // Atoms cannot be equal to each other if they point to different strings.
12236 Imm32 atomBit(JSString::ATOM_BIT);
12237 masm.branchTest32(Assembler::NonZero,
12238 Address(input, JSString::offsetOfFlags()), atomBit,
12239 &setNotEqualResult);
12240 }
12241
12242 if (str->hasTwoByteChars()) {
12243 // Pure two-byte strings can't be equal to Latin-1 strings.
12244 JS::AutoCheckCannotGC nogc;
12245 if (!mozilla::IsUtf16Latin1(str->twoByteRange(nogc))) {
12246 masm.branchLatin1String(input, &setNotEqualResult);
12247 }
12248 }
12249
12250 // Strings of different length can never be equal.
12251 masm.branch32(Assembler::NotEqual,
12252 Address(input, JSString::offsetOfLength()),
12253 Imm32(str->length()), &setNotEqualResult);
12254
12255 if (str->isAtom()) {
12256 Label forwardedPtrEqual;
12257 masm.tryFastAtomize(input, output, output, &compareChars);
12258
12259 // We now have two atoms. Just check pointer equality.
12260 masm.branchPtr(Assembler::Equal, output, ImmGCPtr(str),
12261 &forwardedPtrEqual);
12262
12263 masm.move32(Imm32(op == JSOp::Ne || op == JSOp::StrictNe), output);
12264 masm.jump(ool->rejoin());
12265
12266 masm.bind(&forwardedPtrEqual);
12267 masm.move32(Imm32(op == JSOp::Eq || op == JSOp::StrictEq), output);
12268 masm.jump(ool->rejoin());
12269 } else {
12270 masm.jump(&compareChars);
12271 }
12272
12273 masm.bind(&setNotEqualResult);
12274 masm.move32(Imm32(op == JSOp::Ne || op == JSOp::StrictNe), output);
12275 masm.jump(ool->rejoin());
12276 }
12277
12278 masm.bind(&compareChars);
12279
12280 // Load the input string's characters.
12281 Register stringChars = output;
12282 masm.loadStringCharsForCompare(input, str, stringChars, ool->entry());
12283
12284 // Start comparing character by character.
12285 masm.compareStringChars(op, stringChars, str, output);
12286
12287 masm.bind(ool->rejoin());
12288 }
12289
12290 void CodeGenerator::visitCompareSSingle(LCompareSSingle* lir) {
12291 JSOp op = lir->jsop();
12292 MOZ_ASSERT(IsRelationalOp(op));
12293
12294 Register input = ToRegister(lir->input());
12295 Register output = ToRegister(lir->output());
12296 Register temp = ToRegister(lir->temp0());
12297
12298 const JSLinearString* str = lir->constant();
12299 MOZ_ASSERT(str->length() == 1);
12300
12301 char16_t ch = str->latin1OrTwoByteChar(0);
12302
12303 masm.movePtr(input, temp);
12304
12305 // Check if the string is empty.
12306 Label compareLength;
12307 masm.branch32(Assembler::Equal, Address(temp, JSString::offsetOfLength()),
12308 Imm32(0), &compareLength);
12309
12310 // The first character is in the left-most rope child.
12311 Label notRope;
12312 masm.branchIfNotRope(temp, &notRope);
12313 {
12314 // Unwind ropes at the start if possible.
12315 Label unwindRope;
12316 masm.bind(&unwindRope);
12317 masm.loadRopeLeftChild(temp, output);
12318 masm.movePtr(output, temp);
12319
12320 #ifdef DEBUG
12321 Label notEmpty;
12322 masm.branch32(Assembler::NotEqual,
12323 Address(temp, JSString::offsetOfLength()), Imm32(0),
12324 &notEmpty);
12325 masm.assumeUnreachable("rope children are non-empty");
12326 masm.bind(&notEmpty);
12327 #endif
12328
12329 // Otherwise keep unwinding ropes.
12330 masm.branchIfRope(temp, &unwindRope);
12331 }
12332 masm.bind(&notRope);
12333
12334 // Load the first character into |output|.
12335 auto loadFirstChar = [&](auto encoding) {
12336 masm.loadStringChars(temp, output, encoding);
12337 masm.loadChar(Address(output, 0), output, encoding);
12338 };
12339
12340 Label done;
12341 if (ch <= JSString::MAX_LATIN1_CHAR) {
12342 // Handle both encodings when the search character is Latin-1.
12343 Label twoByte, compare;
12344 masm.branchTwoByteString(temp, &twoByte);
12345
12346 loadFirstChar(CharEncoding::Latin1);
12347 masm.jump(&compare);
12348
12349 masm.bind(&twoByte);
12350 loadFirstChar(CharEncoding::TwoByte);
12351
12352 masm.bind(&compare);
12353 } else {
12354 // The search character is a two-byte character, so it can't be equal to any
12355 // character of a Latin-1 string.
12356 masm.move32(Imm32(int32_t(op == JSOp::Lt || op == JSOp::Le)), output);
12357 masm.branchLatin1String(temp, &done);
12358
12359 loadFirstChar(CharEncoding::TwoByte);
12360 }
12361
12362 // Compare the string length when the search character is equal to the
12363 // input's first character.
12364 masm.branch32(Assembler::Equal, output, Imm32(ch), &compareLength);
12365
12366 // Otherwise compute the result and jump to the end.
12367 masm.cmp32Set(JSOpToCondition(op, /* isSigned = */ false), output, Imm32(ch),
12368 output);
12369 masm.jump(&done);
12370
12371 // Compare the string length to compute the overall result.
12372 masm.bind(&compareLength);
12373 masm.cmp32Set(JSOpToCondition(op, /* isSigned = */ false),
12374 Address(input, JSString::offsetOfLength()), Imm32(1), output);
12375
12376 masm.bind(&done);
12377 }
12378
12379 void CodeGenerator::visitCompareBigInt(LCompareBigInt* lir) {
12380 JSOp op = lir->mir()->jsop();
12381 Register left = ToRegister(lir->left());
12382 Register right = ToRegister(lir->right());
12383 Register temp0 = ToRegister(lir->temp0());
12384 Register temp1 = ToRegister(lir->temp1());
12385 Register temp2 = ToRegister(lir->temp2());
12386 Register output = ToRegister(lir->output());
12387
12388 Label notSame;
12389 Label compareSign;
12390 Label compareLength;
12391 Label compareDigit;
12392
12393 Label* notSameSign;
12394 Label* notSameLength;
12395 Label* notSameDigit;
12396 if (IsEqualityOp(op)) {
12397 notSameSign = &notSame;
12398 notSameLength = &notSame;
12399 notSameDigit = &notSame;
12400 } else {
12401 notSameSign = &compareSign;
12402 notSameLength = &compareLength;
12403 notSameDigit = &compareDigit;
12404 }
12405
12406 masm.equalBigInts(left, right, temp0, temp1, temp2, output, notSameSign,
12407 notSameLength, notSameDigit);
12408
12409 Label done;
12410 masm.move32(Imm32(op == JSOp::Eq || op == JSOp::StrictEq || op == JSOp::Le ||
12411 op == JSOp::Ge),
12412 output);
12413 masm.jump(&done);
12414
12415 if (IsEqualityOp(op)) {
12416 masm.bind(&notSame);
12417 masm.move32(Imm32(op == JSOp::Ne || op == JSOp::StrictNe), output);
12418 } else {
12419 Label invertWhenNegative;
12420
12421 // There are two cases when sign(left) != sign(right):
12422 // 1. sign(left) = positive and sign(right) = negative,
12423 // 2. or the dual case with reversed signs.
12424 //
12425 // For case 1, |left| <cmp> |right| is true for cmp=Gt or cmp=Ge and false
12426 // for cmp=Lt or cmp=Le. Initialize the result for case 1 and handle case 2
12427 // with |invertWhenNegative|.
12428 masm.bind(&compareSign);
12429 masm.move32(Imm32(op == JSOp::Gt || op == JSOp::Ge), output);
12430 masm.jump(&invertWhenNegative);
12431
12432 // For sign(left) = sign(right) and len(digits(left)) != len(digits(right)),
12433 // we have to consider the two cases:
12434 // 1. len(digits(left)) < len(digits(right))
12435 // 2. len(digits(left)) > len(digits(right))
12436 //
12437 // For |left| <cmp> |right| with cmp=Lt:
12438 // Assume both BigInts are positive, then |left < right| is true for case 1
12439 // and false for case 2. When both are negative, the result is reversed.
12440 //
12441 // The other comparison operators can be handled similarly.
12442 //
12443 // |temp0| holds the digits length of the right-hand side operand.
12444 masm.bind(&compareLength);
12445 masm.cmp32Set(JSOpToCondition(op, /* isSigned = */ false),
12446 Address(left, BigInt::offsetOfLength()), temp0, output);
12447 masm.jump(&invertWhenNegative);
12448
12449 // Similar to the case above, compare the current digit to determine the
12450 // overall comparison result.
12451 //
12452 // |temp1| points to the current digit of the left-hand side operand.
12453 // |output| holds the current digit of the right-hand side operand.
12454 masm.bind(&compareDigit);
12455 masm.cmpPtrSet(JSOpToCondition(op, /* isSigned = */ false),
12456 Address(temp1, 0), output, output);
12457
12458 Label nonNegative;
12459 masm.bind(&invertWhenNegative);
12460 masm.branchIfBigIntIsNonNegative(left, &nonNegative);
12461 masm.xor32(Imm32(1), output);
12462 masm.bind(&nonNegative);
12463 }
12464
12465 masm.bind(&done);
12466 }
12467
12468 void CodeGenerator::visitCompareBigIntInt32(LCompareBigIntInt32* lir) {
12469 JSOp op = lir->mir()->jsop();
12470 Register left = ToRegister(lir->left());
12471 Register temp0 = ToRegister(lir->temp0());
12472 Register temp1 = ToTempRegisterOrInvalid(lir->temp1());
12473 Register output = ToRegister(lir->output());
12474
12475 Label ifTrue, ifFalse;
12476 if (lir->right()->isConstant()) {
12477 MOZ_ASSERT(temp1 == InvalidReg);
12478
12479 Imm32 right = Imm32(ToInt32(lir->right()));
12480 masm.compareBigIntAndInt32(op, left, right, temp0, &ifTrue, &ifFalse);
12481 } else {
12482 MOZ_ASSERT(temp1 != InvalidReg);
12483
12484 Register right = ToRegister(lir->right());
12485 masm.compareBigIntAndInt32(op, left, right, temp0, temp1, &ifTrue,
12486 &ifFalse);
12487 }
12488
12489 Label done;
12490 masm.bind(&ifFalse);
12491 masm.move32(Imm32(0), output);
12492 masm.jump(&done);
12493 masm.bind(&ifTrue);
12494 masm.move32(Imm32(1), output);
12495 masm.bind(&done);
12496 }
12497
12498 void CodeGenerator::visitCompareBigIntInt32AndBranch(
12499 LCompareBigIntInt32AndBranch* lir) {
12500 JSOp op = lir->cmpMir()->jsop();
12501 Register left = ToRegister(lir->left());
12502 Register temp1 = ToRegister(lir->temp0());
12503 Register temp2 = ToTempRegisterOrInvalid(lir->temp1());
12504
12505 Label* ifTrue = getJumpLabelForBranch(lir->ifTrue());
12506 Label* ifFalse = getJumpLabelForBranch(lir->ifFalse());
12507
12508 // compareBigIntAndInt32 falls through to the false case. If the next block
12509 // is the true case, negate the comparison so we can fall through.
12510 if (isNextBlock(lir->ifTrue()->lir())) {
12511 op = NegateCompareOp(op);
12512 std::swap(ifTrue, ifFalse);
12513 }
12514
12515 if (lir->right()->isConstant()) {
12516 MOZ_ASSERT(temp2 == InvalidReg);
12517
12518 Imm32 right = Imm32(ToInt32(lir->right()));
12519 masm.compareBigIntAndInt32(op, left, right, temp1, ifTrue, ifFalse);
12520 } else {
12521 MOZ_ASSERT(temp2 != InvalidReg);
12522
12523 Register right = ToRegister(lir->right());
12524 masm.compareBigIntAndInt32(op, left, right, temp1, temp2, ifTrue, ifFalse);
12525 }
12526
12527 if (!isNextBlock(lir->ifTrue()->lir())) {
12528 jumpToBlock(lir->ifFalse());
12529 }
12530 }
12531
12532 void CodeGenerator::visitCompareBigIntDouble(LCompareBigIntDouble* lir) {
12533 JSOp op = lir->mir()->jsop();
12534 Register left = ToRegister(lir->left());
12535 FloatRegister right = ToFloatRegister(lir->right());
12536 Register output = ToRegister(lir->output());
12537
12538 masm.setupAlignedABICall();
12539
12540 // Push the operands in reverse order for JSOp::Le and JSOp::Gt:
12541 // - |left <= right| is implemented as |right >= left|.
12542 // - |left > right| is implemented as |right < left|.
12543 if (op == JSOp::Le || op == JSOp::Gt) {
12544 masm.passABIArg(right, ABIType::Float64);
12545 masm.passABIArg(left);
12546 } else {
12547 masm.passABIArg(left);
12548 masm.passABIArg(right, ABIType::Float64);
12549 }
12550
12551 using FnBigIntNumber = bool (*)(BigInt*, double);
12552 using FnNumberBigInt = bool (*)(double, BigInt*);
12553 switch (op) {
12554 case JSOp::Eq: {
12555 masm.callWithABI<FnBigIntNumber,
12556 jit::BigIntNumberEqual<EqualityKind::Equal>>();
12557 break;
12558 }
12559 case JSOp::Ne: {
12560 masm.callWithABI<FnBigIntNumber,
12561 jit::BigIntNumberEqual<EqualityKind::NotEqual>>();
12562 break;
12563 }
12564 case JSOp::Lt: {
12565 masm.callWithABI<FnBigIntNumber,
12566 jit::BigIntNumberCompare<ComparisonKind::LessThan>>();
12567 break;
12568 }
12569 case JSOp::Gt: {
12570 masm.callWithABI<FnNumberBigInt,
12571 jit::NumberBigIntCompare<ComparisonKind::LessThan>>();
12572 break;
12573 }
12574 case JSOp::Le: {
12575 masm.callWithABI<
12576 FnNumberBigInt,
12577 jit::NumberBigIntCompare<ComparisonKind::GreaterThanOrEqual>>();
12578 break;
12579 }
12580 case JSOp::Ge: {
12581 masm.callWithABI<
12582 FnBigIntNumber,
12583 jit::BigIntNumberCompare<ComparisonKind::GreaterThanOrEqual>>();
12584 break;
12585 }
12586 default:
12587 MOZ_CRASH("unhandled op");
12588 }
12589
12590 masm.storeCallBoolResult(output);
12591 }
12592
12593 void CodeGenerator::visitCompareBigIntString(LCompareBigIntString* lir) {
12594 JSOp op = lir->mir()->jsop();
12595 Register left = ToRegister(lir->left());
12596 Register right = ToRegister(lir->right());
12597
12598 // Push the operands in reverse order for JSOp::Le and JSOp::Gt:
12599 // - |left <= right| is implemented as |right >= left|.
12600 // - |left > right| is implemented as |right < left|.
12601 if (op == JSOp::Le || op == JSOp::Gt) {
12602 pushArg(left);
12603 pushArg(right);
12604 } else {
12605 pushArg(right);
12606 pushArg(left);
12607 }
12608
12609 using FnBigIntString =
12610 bool (*)(JSContext*, HandleBigInt, HandleString, bool*);
12611 using FnStringBigInt =
12612 bool (*)(JSContext*, HandleString, HandleBigInt, bool*);
12613
12614 switch (op) {
12615 case JSOp::Eq: {
12616 constexpr auto Equal = EqualityKind::Equal;
12617 callVM<FnBigIntString, BigIntStringEqual<Equal>>(lir);
12618 break;
12619 }
12620 case JSOp::Ne: {
12621 constexpr auto NotEqual = EqualityKind::NotEqual;
12622 callVM<FnBigIntString, BigIntStringEqual<NotEqual>>(lir);
12623 break;
12624 }
12625 case JSOp::Lt: {
12626 constexpr auto LessThan = ComparisonKind::LessThan;
12627 callVM<FnBigIntString, BigIntStringCompare<LessThan>>(lir);
12628 break;
12629 }
12630 case JSOp::Gt: {
12631 constexpr auto LessThan = ComparisonKind::LessThan;
12632 callVM<FnStringBigInt, StringBigIntCompare<LessThan>>(lir);
12633 break;
12634 }
12635 case JSOp::Le: {
12636 constexpr auto GreaterThanOrEqual = ComparisonKind::GreaterThanOrEqual;
12637 callVM<FnStringBigInt, StringBigIntCompare<GreaterThanOrEqual>>(lir);
12638 break;
12639 }
12640 case JSOp::Ge: {
12641 constexpr auto GreaterThanOrEqual = ComparisonKind::GreaterThanOrEqual;
12642 callVM<FnBigIntString, BigIntStringCompare<GreaterThanOrEqual>>(lir);
12643 break;
12644 }
12645 default:
12646 MOZ_CRASH("Unexpected compare op");
12647 }
12648 }
12649
12650 void CodeGenerator::visitIsNullOrLikeUndefinedV(LIsNullOrLikeUndefinedV* lir) {
12651 MOZ_ASSERT(lir->mir()->compareType() == MCompare::Compare_Undefined ||
12652 lir->mir()->compareType() == MCompare::Compare_Null);
12653
12654 JSOp op = lir->mir()->jsop();
12655 MOZ_ASSERT(IsLooseEqualityOp(op));
12656
12657 ValueOperand value = ToValue(lir->value());
12658 Register output = ToRegister(lir->output());
12659
12660 bool intact = hasSeenObjectEmulateUndefinedFuseIntactAndDependencyNoted();
12661 if (!intact) {
12662 auto* ool = new (alloc()) OutOfLineTestObjectWithLabels();
12663 addOutOfLineCode(ool, lir->mir());
12664
12665 Label* nullOrLikeUndefined = ool->label1();
12666 Label* notNullOrLikeUndefined = ool->label2();
12667
12668 {
12669 ScratchTagScope tag(masm, value);
12670 masm.splitTagForTest(value, tag);
12671
12672 masm.branchTestNull(Assembler::Equal, tag, nullOrLikeUndefined);
12673 masm.branchTestUndefined(Assembler::Equal, tag, nullOrLikeUndefined);
12674
12675 // Check whether it's a truthy object or a falsy object that emulates
12676 // undefined.
12677 masm.branchTestObject(Assembler::NotEqual, tag, notNullOrLikeUndefined);
12678 }
12679
12680 Register objreg =
12681 masm.extractObject(value, ToTempUnboxRegister(lir->temp0()));
12682 branchTestObjectEmulatesUndefined(objreg, nullOrLikeUndefined,
12683 notNullOrLikeUndefined, output, ool);
12684 // fall through
12685
12686 Label done;
12687
12688 // It's not null or undefined, and if it's an object it doesn't
12689 // emulate undefined, so it's not like undefined.
12690 masm.move32(Imm32(op == JSOp::Ne), output);
12691 masm.jump(&done);
12692
12693 masm.bind(nullOrLikeUndefined);
12694 masm.move32(Imm32(op == JSOp::Eq), output);
12695
12696 // Both branches meet here.
12697 masm.bind(&done);
12698 } else {
12699 Label nullOrUndefined, notNullOrLikeUndefined;
12700 #if defined(DEBUG) || defined(FUZZING)
12701 Register objreg = Register::Invalid();
12702 #endif
12703 {
12704 ScratchTagScope tag(masm, value);
12705 masm.splitTagForTest(value, tag);
12706
12707 masm.branchTestNull(Assembler::Equal, tag, &nullOrUndefined);
12708 masm.branchTestUndefined(Assembler::Equal, tag, &nullOrUndefined);
12709
12710 #if defined(DEBUG) || defined(FUZZING)
12711 // Check whether it's a truthy object or a falsy object that emulates
12712 // undefined.
12713 masm.branchTestObject(Assembler::NotEqual, tag, &notNullOrLikeUndefined);
12714 objreg = masm.extractObject(value, ToTempUnboxRegister(lir->temp0()));
12715 #endif
12716 }
12717
12718 #if defined(DEBUG) || defined(FUZZING)
12719 assertObjectDoesNotEmulateUndefined(objreg, output, lir->mir());
12720 masm.bind(&notNullOrLikeUndefined);
12721 #endif
12722
12723 Label done;
12724
12725 // It's not null or undefined, and if it's an object it doesn't
12726 // emulate undefined.
12727 masm.move32(Imm32(op == JSOp::Ne), output);
12728 masm.jump(&done);
12729
12730 masm.bind(&nullOrUndefined);
12731 masm.move32(Imm32(op == JSOp::Eq), output);
12732
12733 // Both branches meet here.
12734 masm.bind(&done);
12735 }
12736 }
12737
12738 void CodeGenerator::visitIsNullOrLikeUndefinedAndBranchV(
12739 LIsNullOrLikeUndefinedAndBranchV* lir) {
12740 MOZ_ASSERT(lir->cmpMir()->compareType() == MCompare::Compare_Undefined ||
12741 lir->cmpMir()->compareType() == MCompare::Compare_Null);
12742
12743 JSOp op = lir->cmpMir()->jsop();
12744 MOZ_ASSERT(IsLooseEqualityOp(op));
12745
12746 ValueOperand value = ToValue(lir->value());
12747
12748 MBasicBlock* ifTrue = lir->ifTrue();
12749 MBasicBlock* ifFalse = lir->ifFalse();
12750
12751 if (op == JSOp::Ne) {
12752 // Swap branches.
12753 std::swap(ifTrue, ifFalse);
12754 }
12755
12756 bool intact = hasSeenObjectEmulateUndefinedFuseIntactAndDependencyNoted();
12757
12758 Label* ifTrueLabel = getJumpLabelForBranch(ifTrue);
12759 Label* ifFalseLabel = getJumpLabelForBranch(ifFalse);
12760
12761 {
12762 ScratchTagScope tag(masm, value);
12763 masm.splitTagForTest(value, tag);
12764
12765 masm.branchTestNull(Assembler::Equal, tag, ifTrueLabel);
12766 masm.branchTestUndefined(Assembler::Equal, tag, ifTrueLabel);
12767
12768 masm.branchTestObject(Assembler::NotEqual, tag, ifFalseLabel);
12769 }
12770
12771 bool extractObject = !intact;
12772 #if defined(DEBUG) || defined(FUZZING)
12773 // always extract objreg if we're in debug and
12774 // assertObjectDoesNotEmulateUndefined;
12775 extractObject = true;
12776 #endif
12777
12778 Register objreg = Register::Invalid();
12779 Register scratch = ToRegister(lir->temp0());
12780 if (extractObject) {
12781 objreg = masm.extractObject(value, ToTempUnboxRegister(lir->temp1()));
12782 }
12783 if (!intact) {
12784 // Objects that emulate undefined are loosely equal to null/undefined.
12785 OutOfLineTestObject* ool = new (alloc()) OutOfLineTestObject();
12786 addOutOfLineCode(ool, lir->cmpMir());
12787 testObjectEmulatesUndefined(objreg, ifTrueLabel, ifFalseLabel, scratch,
12788 ool);
12789 } else {
12790 assertObjectDoesNotEmulateUndefined(objreg, scratch, lir->cmpMir());
12791 // Bug 1874905. This would be nice to optimize out at the MIR level.
12792 masm.jump(ifFalseLabel);
12793 }
12794 }
12795
12796 void CodeGenerator::visitIsNullOrLikeUndefinedT(LIsNullOrLikeUndefinedT* lir) {
12797 MOZ_ASSERT(lir->mir()->compareType() == MCompare::Compare_Undefined ||
12798 lir->mir()->compareType() == MCompare::Compare_Null);
12799 MOZ_ASSERT(lir->mir()->lhs()->type() == MIRType::Object);
12800
12801 bool intact = hasSeenObjectEmulateUndefinedFuseIntactAndDependencyNoted();
12802 JSOp op = lir->mir()->jsop();
12803 Register output = ToRegister(lir->output());
12804 Register objreg = ToRegister(lir->input());
12805 if (!intact) {
12806 MOZ_ASSERT(IsLooseEqualityOp(op),
12807 "Strict equality should have been folded");
12808
12809 auto* ool = new (alloc()) OutOfLineTestObjectWithLabels();
12810 addOutOfLineCode(ool, lir->mir());
12811
12812 Label* emulatesUndefined = ool->label1();
12813 Label* doesntEmulateUndefined = ool->label2();
12814
12815 branchTestObjectEmulatesUndefined(objreg, emulatesUndefined,
12816 doesntEmulateUndefined, output, ool);
12817
12818 Label done;
12819
12820 masm.move32(Imm32(op == JSOp::Ne), output);
12821 masm.jump(&done);
12822
12823 masm.bind(emulatesUndefined);
12824 masm.move32(Imm32(op == JSOp::Eq), output);
12825 masm.bind(&done);
12826 } else {
12827 assertObjectDoesNotEmulateUndefined(objreg, output, lir->mir());
12828 masm.move32(Imm32(op == JSOp::Ne), output);
12829 }
12830 }
12831
12832 void CodeGenerator::visitIsNullOrLikeUndefinedAndBranchT(
12833 LIsNullOrLikeUndefinedAndBranchT* lir) {
12834 MOZ_ASSERT(lir->cmpMir()->compareType() == MCompare::Compare_Undefined ||
12835 lir->cmpMir()->compareType() == MCompare::Compare_Null);
12836 MOZ_ASSERT(lir->cmpMir()->lhs()->type() == MIRType::Object);
12837
12838 bool intact = hasSeenObjectEmulateUndefinedFuseIntactAndDependencyNoted();
12839
12840 JSOp op = lir->cmpMir()->jsop();
12841 MOZ_ASSERT(IsLooseEqualityOp(op), "Strict equality should have been folded");
12842
12843 MBasicBlock* ifTrue = lir->ifTrue();
12844 MBasicBlock* ifFalse = lir->ifFalse();
12845
12846 if (op == JSOp::Ne) {
12847 // Swap branches.
12848 std::swap(ifTrue, ifFalse);
12849 }
12850
12851 Register input = ToRegister(lir->value());
12852 Register scratch = ToRegister(lir->temp0());
12853 Label* ifTrueLabel = getJumpLabelForBranch(ifTrue);
12854 Label* ifFalseLabel = getJumpLabelForBranch(ifFalse);
12855
12856 if (intact) {
12857 // Bug 1874905. Ideally branches like this would be optimized out.
12858 assertObjectDoesNotEmulateUndefined(input, scratch, lir->mir());
12859 masm.jump(ifFalseLabel);
12860 } else {
12861 auto* ool = new (alloc()) OutOfLineTestObject();
12862 addOutOfLineCode(ool, lir->cmpMir());
12863
12864 // Objects that emulate undefined are loosely equal to null/undefined.
12865 testObjectEmulatesUndefined(input, ifTrueLabel, ifFalseLabel, scratch, ool);
12866 }
12867 }
12868
12869 void CodeGenerator::visitIsNull(LIsNull* lir) {
12870 MCompare::CompareType compareType = lir->mir()->compareType();
12871 MOZ_ASSERT(compareType == MCompare::Compare_Null);
12872
12873 JSOp op = lir->mir()->jsop();
12874 MOZ_ASSERT(IsStrictEqualityOp(op));
12875
12876 ValueOperand value = ToValue(lir->value());
12877 Register output = ToRegister(lir->output());
12878
12879 Assembler::Condition cond = JSOpToCondition(compareType, op);
12880 masm.testNullSet(cond, value, output);
12881 }
12882
12883 void CodeGenerator::visitIsUndefined(LIsUndefined* lir) {
12884 MCompare::CompareType compareType = lir->mir()->compareType();
12885 MOZ_ASSERT(compareType == MCompare::Compare_Undefined);
12886
12887 JSOp op = lir->mir()->jsop();
12888 MOZ_ASSERT(IsStrictEqualityOp(op));
12889
12890 ValueOperand value = ToValue(lir->value());
12891 Register output = ToRegister(lir->output());
12892
12893 Assembler::Condition cond = JSOpToCondition(compareType, op);
12894 masm.testUndefinedSet(cond, value, output);
12895 }
12896
12897 void CodeGenerator::visitIsNullAndBranch(LIsNullAndBranch* lir) {
12898 MCompare::CompareType compareType = lir->cmpMir()->compareType();
12899 MOZ_ASSERT(compareType == MCompare::Compare_Null);
12900
12901 JSOp op = lir->cmpMir()->jsop();
12902 MOZ_ASSERT(IsStrictEqualityOp(op));
12903
12904 ValueOperand value = ToValue(lir->value());
12905
12906 Assembler::Condition cond = JSOpToCondition(compareType, op);
12907
12908 MBasicBlock* ifTrue = lir->ifTrue();
12909 MBasicBlock* ifFalse = lir->ifFalse();
12910
12911 if (isNextBlock(ifFalse->lir())) {
12912 masm.branchTestNull(cond, value, getJumpLabelForBranch(ifTrue));
12913 } else {
12914 masm.branchTestNull(Assembler::InvertCondition(cond), value,
12915 getJumpLabelForBranch(ifFalse));
12916 jumpToBlock(ifTrue);
12917 }
12918 }
12919
12920 void CodeGenerator::visitIsUndefinedAndBranch(LIsUndefinedAndBranch* lir) {
12921 MCompare::CompareType compareType = lir->cmpMir()->compareType();
12922 MOZ_ASSERT(compareType == MCompare::Compare_Undefined);
12923
12924 JSOp op = lir->cmpMir()->jsop();
12925 MOZ_ASSERT(IsStrictEqualityOp(op));
12926
12927 ValueOperand value = ToValue(lir->value());
12928
12929 Assembler::Condition cond = JSOpToCondition(compareType, op);
12930
12931 MBasicBlock* ifTrue = lir->ifTrue();
12932 MBasicBlock* ifFalse = lir->ifFalse();
12933
12934 if (isNextBlock(ifFalse->lir())) {
12935 masm.branchTestUndefined(cond, value, getJumpLabelForBranch(ifTrue));
12936 } else {
12937 masm.branchTestUndefined(Assembler::InvertCondition(cond), value,
12938 getJumpLabelForBranch(ifFalse));
12939 jumpToBlock(ifTrue);
12940 }
12941 }
12942
12943 void CodeGenerator::visitSameValueDouble(LSameValueDouble* lir) {
12944 FloatRegister left = ToFloatRegister(lir->left());
12945 FloatRegister right = ToFloatRegister(lir->right());
12946 FloatRegister temp = ToFloatRegister(lir->temp0());
12947 Register output = ToRegister(lir->output());
12948
12949 masm.sameValueDouble(left, right, temp, output);
12950 }
12951
12952 void CodeGenerator::visitSameValue(LSameValue* lir) {
12953 ValueOperand lhs = ToValue(lir->left());
12954 ValueOperand rhs = ToValue(lir->right());
12955 Register output = ToRegister(lir->output());
12956
12957 using Fn = bool (*)(JSContext*, HandleValue, HandleValue, bool*);
12958 OutOfLineCode* ool =
12959 oolCallVM<Fn, SameValue>(lir, ArgList(lhs, rhs), StoreRegisterTo(output));
12960
12961 // First check to see if the values have identical bits.
12962 // This is correct for SameValue because SameValue(NaN,NaN) is true,
12963 // and SameValue(0,-0) is false.
12964 masm.branch64(Assembler::NotEqual, lhs.toRegister64(), rhs.toRegister64(),
12965 ool->entry());
12966 masm.move32(Imm32(1), output);
12967
12968 // If this fails, call SameValue.
12969 masm.bind(ool->rejoin());
12970 }
12971
12972 void CodeGenerator::emitConcat(LInstruction* lir, Register lhs, Register rhs,
12973 Register output) {
12974 using Fn =
12975 JSString* (*)(JSContext*, HandleString, HandleString, js::gc::Heap);
12976 OutOfLineCode* ool = oolCallVM<Fn, ConcatStrings<CanGC>>(
12977 lir, ArgList(lhs, rhs, static_cast<Imm32>(int32_t(gc::Heap::Default))),
12978 StoreRegisterTo(output));
12979
12980 JitCode* stringConcatStub =
12981 snapshot_->getZoneStub(JitZone::StubKind::StringConcat);
12982 masm.call(stringConcatStub);
12983 masm.branchTestPtr(Assembler::Zero, output, output, ool->entry());
12984
12985 masm.bind(ool->rejoin());
12986 }
12987
12988 void CodeGenerator::visitConcat(LConcat* lir) {
12989 Register lhs = ToRegister(lir->lhs());
12990 Register rhs = ToRegister(lir->rhs());
12991
12992 Register output = ToRegister(lir->output());
12993
12994 MOZ_ASSERT(lhs == CallTempReg0);
12995 MOZ_ASSERT(rhs == CallTempReg1);
12996 MOZ_ASSERT(ToRegister(lir->temp0()) == CallTempReg0);
12997 MOZ_ASSERT(ToRegister(lir->temp1()) == CallTempReg1);
12998 MOZ_ASSERT(ToRegister(lir->temp2()) == CallTempReg2);
12999 MOZ_ASSERT(ToRegister(lir->temp3()) == CallTempReg3);
13000 MOZ_ASSERT(ToRegister(lir->temp4()) == CallTempReg4);
13001 MOZ_ASSERT(output == CallTempReg5);
13002
13003 emitConcat(lir, lhs, rhs, output);
13004 }
13005
13006 static void CopyStringChars(MacroAssembler& masm, Register to, Register from,
13007 Register len, Register byteOpScratch,
13008 CharEncoding fromEncoding, CharEncoding toEncoding,
13009 size_t maximumLength = SIZE_MAX) {
13010 // Copy |len| char16_t code units from |from| to |to|. Assumes len > 0
13011 // (checked below in debug builds), and when done |to| must point to the
13012 // next available char.
13013
13014 #ifdef DEBUG
13015 Label ok;
13016 masm.branch32(Assembler::GreaterThan, len, Imm32(0), &ok);
13017 masm.assumeUnreachable("Length should be greater than 0.");
13018 masm.bind(&ok);
13019
13020 if (maximumLength != SIZE_MAX) {
13021 MOZ_ASSERT(maximumLength <= INT32_MAX, "maximum length fits into int32");
13022
13023 Label ok;
13024 masm.branchPtr(Assembler::BelowOrEqual, len, Imm32(maximumLength), &ok);
13025 masm.assumeUnreachable("Length should not exceed maximum length.");
13026 masm.bind(&ok);
13027 }
13028 #endif
13029
13030 MOZ_ASSERT_IF(toEncoding == CharEncoding::Latin1,
13031 fromEncoding == CharEncoding::Latin1);
13032
13033 size_t fromWidth =
13034 fromEncoding == CharEncoding::Latin1 ? sizeof(char) : sizeof(char16_t);
13035 size_t toWidth =
13036 toEncoding == CharEncoding::Latin1 ? sizeof(char) : sizeof(char16_t);
13037
13038 // Try to copy multiple characters at once when both encoding are equal.
13039 if (fromEncoding == toEncoding) {
13040 constexpr size_t ptrWidth = sizeof(uintptr_t);
13041
13042 // Copy |width| bytes and then adjust |from| and |to|.
13043 auto copyCharacters = [&](size_t width) {
13044 static_assert(ptrWidth <= 8, "switch handles only up to eight bytes");
13045
13046 switch (width) {
13047 case 1:
13048 masm.load8ZeroExtend(Address(from, 0), byteOpScratch);
13049 masm.store8(byteOpScratch, Address(to, 0));
13050 break;
13051 case 2:
13052 masm.load16ZeroExtend(Address(from, 0), byteOpScratch);
13053 masm.store16(byteOpScratch, Address(to, 0));
13054 break;
13055 case 4:
13056 masm.load32(Address(from, 0), byteOpScratch);
13057 masm.store32(byteOpScratch, Address(to, 0));
13058 break;
13059 case 8:
13060 MOZ_ASSERT(width == ptrWidth);
13061 masm.loadPtr(Address(from, 0), byteOpScratch);
13062 masm.storePtr(byteOpScratch, Address(to, 0));
13063 break;
13064 }
13065
13066 masm.addPtr(Imm32(width), from);
13067 masm.addPtr(Imm32(width), to);
13068 };
13069
13070 // First align |len| to pointer width.
13071 Label done;
13072 for (size_t width = fromWidth; width < ptrWidth; width *= 2) {
13073 // Number of characters which fit into |width| bytes.
13074 size_t charsPerWidth = width / fromWidth;
13075
13076 if (charsPerWidth < maximumLength) {
13077 Label next;
13078 masm.branchTest32(Assembler::Zero, len, Imm32(charsPerWidth), &next);
13079
13080 copyCharacters(width);
13081
13082 masm.branchSub32(Assembler::Zero, Imm32(charsPerWidth), len, &done);
13083 masm.bind(&next);
13084 } else if (charsPerWidth == maximumLength) {
13085 copyCharacters(width);
13086 masm.sub32(Imm32(charsPerWidth), len);
13087 }
13088 }
13089
13090 size_t maxInlineLength;
13091 if (fromEncoding == CharEncoding::Latin1) {
13092 maxInlineLength = JSFatInlineString::MAX_LENGTH_LATIN1;
13093 } else {
13094 maxInlineLength = JSFatInlineString::MAX_LENGTH_TWO_BYTE;
13095 }
13096
13097 // Number of characters which fit into a single register.
13098 size_t charsPerPtr = ptrWidth / fromWidth;
13099
13100 // Unroll small loops.
13101 constexpr size_t unrollLoopLimit = 3;
13102 size_t loopCount = std::min(maxInlineLength, maximumLength) / charsPerPtr;
13103
13104 #ifdef JS_64BIT
13105 static constexpr size_t latin1MaxInlineByteLength =
13106 JSFatInlineString::MAX_LENGTH_LATIN1 * sizeof(char);
13107 static constexpr size_t twoByteMaxInlineByteLength =
13108 JSFatInlineString::MAX_LENGTH_TWO_BYTE * sizeof(char16_t);
13109
13110 // |unrollLoopLimit| should be large enough to allow loop unrolling on
13111 // 64-bit targets.
13112 static_assert(latin1MaxInlineByteLength / ptrWidth == unrollLoopLimit,
13113 "Latin-1 loops are unrolled on 64-bit");
13114 static_assert(twoByteMaxInlineByteLength / ptrWidth == unrollLoopLimit,
13115 "Two-byte loops are unrolled on 64-bit");
13116 #endif
13117
13118 if (loopCount <= unrollLoopLimit) {
13119 Label labels[unrollLoopLimit];
13120
13121 // Check up front how many characters can be copied.
13122 for (size_t i = 1; i < loopCount; i++) {
13123 masm.branch32(Assembler::Below, len, Imm32((i + 1) * charsPerPtr),
13124 &labels[i]);
13125 }
13126
13127 // Generate the unrolled loop body.
13128 for (size_t i = loopCount; i > 0; i--) {
13129 copyCharacters(ptrWidth);
13130 masm.sub32(Imm32(charsPerPtr), len);
13131
13132 // Jump target for the previous length check.
13133 if (i != 1) {
13134 masm.bind(&labels[i - 1]);
13135 }
13136 }
13137 } else {
13138 Label start;
13139 masm.bind(&start);
13140 copyCharacters(ptrWidth);
13141 masm.branchSub32(Assembler::NonZero, Imm32(charsPerPtr), len, &start);
13142 }
13143
13144 masm.bind(&done);
13145 } else {
13146 Label start;
13147 masm.bind(&start);
13148 masm.loadChar(Address(from, 0), byteOpScratch, fromEncoding);
13149 masm.storeChar(byteOpScratch, Address(to, 0), toEncoding);
13150 masm.addPtr(Imm32(fromWidth), from);
13151 masm.addPtr(Imm32(toWidth), to);
13152 masm.branchSub32(Assembler::NonZero, Imm32(1), len, &start);
13153 }
13154 }
13155
13156 static void CopyStringChars(MacroAssembler& masm, Register to, Register from,
13157 Register len, Register byteOpScratch,
13158 CharEncoding encoding, size_t maximumLength) {
13159 CopyStringChars(masm, to, from, len, byteOpScratch, encoding, encoding,
13160 maximumLength);
13161 }
13162
13163 static void CopyStringCharsMaybeInflate(MacroAssembler& masm, Register input,
13164 Register destChars, Register temp1,
13165 Register temp2) {
13166 // destChars is TwoByte and input is a Latin1 or TwoByte string, so we may
13167 // have to inflate.
13168
13169 Label isLatin1, done;
13170 masm.loadStringLength(input, temp1);
13171 masm.branchLatin1String(input, &isLatin1);
13172 {
13173 masm.loadStringChars(input, temp2, CharEncoding::TwoByte);
13174 masm.movePtr(temp2, input);
13175 CopyStringChars(masm, destChars, input, temp1, temp2,
13176 CharEncoding::TwoByte);
13177 masm.jump(&done);
13178 }
13179 masm.bind(&isLatin1);
13180 {
13181 masm.loadStringChars(input, temp2, CharEncoding::Latin1);
13182 masm.movePtr(temp2, input);
13183 CopyStringChars(masm, destChars, input, temp1, temp2, CharEncoding::Latin1,
13184 CharEncoding::TwoByte);
13185 }
13186 masm.bind(&done);
13187 }
13188
13189 static void AllocateThinOrFatInlineString(MacroAssembler& masm, Register output,
13190 Register length, Register temp,
13191 gc::Heap initialStringHeap,
13192 Label* failure,
13193 CharEncoding encoding) {
13194 #ifdef DEBUG
13195 size_t maxInlineLength;
13196 if (encoding == CharEncoding::Latin1) {
13197 maxInlineLength = JSFatInlineString::MAX_LENGTH_LATIN1;
13198 } else {
13199 maxInlineLength = JSFatInlineString::MAX_LENGTH_TWO_BYTE;
13200 }
13201
13202 Label ok;
13203 masm.branch32(Assembler::BelowOrEqual, length, Imm32(maxInlineLength), &ok);
13204 masm.assumeUnreachable("string length too large to be allocated as inline");
13205 masm.bind(&ok);
13206 #endif
13207
13208 size_t maxThinInlineLength;
13209 if (encoding == CharEncoding::Latin1) {
13210 maxThinInlineLength = JSThinInlineString::MAX_LENGTH_LATIN1;
13211 } else {
13212 maxThinInlineLength = JSThinInlineString::MAX_LENGTH_TWO_BYTE;
13213 }
13214
13215 Label isFat, allocDone;
13216 masm.branch32(Assembler::Above, length, Imm32(maxThinInlineLength), &isFat);
13217 {
13218 uint32_t flags = JSString::INIT_THIN_INLINE_FLAGS;
13219 if (encoding == CharEncoding::Latin1) {
13220 flags |= JSString::LATIN1_CHARS_BIT;
13221 }
13222 masm.newGCString(output, temp, initialStringHeap, failure);
13223 masm.store32(Imm32(flags), Address(output, JSString::offsetOfFlags()));
13224 masm.jump(&allocDone);
13225 }
13226 masm.bind(&isFat);
13227 {
13228 uint32_t flags = JSString::INIT_FAT_INLINE_FLAGS;
13229 if (encoding == CharEncoding::Latin1) {
13230 flags |= JSString::LATIN1_CHARS_BIT;
13231 }
13232 masm.newGCFatInlineString(output, temp, initialStringHeap, failure);
13233 masm.store32(Imm32(flags), Address(output, JSString::offsetOfFlags()));
13234 }
13235 masm.bind(&allocDone);
13236
13237 // Store length.
13238 masm.store32(length, Address(output, JSString::offsetOfLength()));
13239 }
13240
13241 static void ConcatInlineString(MacroAssembler& masm, Register lhs, Register rhs,
13242 Register output, Register temp1, Register temp2,
13243 Register temp3, gc::Heap initialStringHeap,
13244 Label* failure, CharEncoding encoding) {
13245 JitSpew(JitSpew_Codegen, "# Emitting ConcatInlineString (encoding=%s)",
13246 (encoding == CharEncoding::Latin1 ? "Latin-1" : "Two-Byte"));
13247
13248 // State: result length in temp2.
13249
13250 // Ensure both strings are linear.
13251 masm.branchIfRope(lhs, failure);
13252 masm.branchIfRope(rhs, failure);
13253
13254 // Allocate a JSThinInlineString or JSFatInlineString.
13255 AllocateThinOrFatInlineString(masm, output, temp2, temp1, initialStringHeap,
13256 failure, encoding);
13257
13258 // Load chars pointer in temp2.
13259 masm.loadInlineStringCharsForStore(output, temp2);
13260
13261 auto copyChars = [&](Register src) {
13262 if (encoding == CharEncoding::TwoByte) {
13263 CopyStringCharsMaybeInflate(masm, src, temp2, temp1, temp3);
13264 } else {
13265 masm.loadStringLength(src, temp3);
13266 masm.loadStringChars(src, temp1, CharEncoding::Latin1);
13267 masm.movePtr(temp1, src);
13268 CopyStringChars(masm, temp2, src, temp3, temp1, CharEncoding::Latin1);
13269 }
13270 };
13271
13272 // Copy lhs chars. Note that this advances temp2 to point to the next
13273 // char. This also clobbers the lhs register.
13274 copyChars(lhs);
13275
13276 // Copy rhs chars. Clobbers the rhs register.
13277 copyChars(rhs);
13278 }
13279
13280 void CodeGenerator::visitSubstr(LSubstr* lir) {
13281 Register string = ToRegister(lir->string());
13282 Register begin = ToRegister(lir->begin());
13283 Register length = ToRegister(lir->length());
13284 Register output = ToRegister(lir->output());
13285 Register temp0 = ToRegister(lir->temp0());
13286 Register temp2 = ToRegister(lir->temp2());
13287
13288 // On x86 there are not enough registers. In that case reuse the string
13289 // register as temporary.
13290 Register temp1 =
13291 lir->temp1()->isBogusTemp() ? string : ToRegister(lir->temp1());
13292
13293 size_t maximumLength = SIZE_MAX;
13294
13295 Range* range = lir->mir()->length()->range();
13296 if (range && range->hasInt32UpperBound()) {
13297 MOZ_ASSERT(range->upper() >= 0);
13298 maximumLength = size_t(range->upper());
13299 }
13300
13301 static_assert(JSThinInlineString::MAX_LENGTH_TWO_BYTE <=
13302 JSThinInlineString::MAX_LENGTH_LATIN1);
13303
13304 static_assert(JSFatInlineString::MAX_LENGTH_TWO_BYTE <=
13305 JSFatInlineString::MAX_LENGTH_LATIN1);
13306
13307 bool tryFatInlineOrDependent =
13308 maximumLength > JSThinInlineString::MAX_LENGTH_TWO_BYTE;
13309 bool tryDependent = maximumLength > JSFatInlineString::MAX_LENGTH_TWO_BYTE;
13310
13311 #ifdef DEBUG
13312 if (maximumLength != SIZE_MAX) {
13313 Label ok;
13314 masm.branch32(Assembler::BelowOrEqual, length, Imm32(maximumLength), &ok);
13315 masm.assumeUnreachable("length should not exceed maximum length");
13316 masm.bind(&ok);
13317 }
13318 #endif
13319
13320 Label nonZero, nonInput;
13321
13322 // For every edge case use the C++ variant.
13323 // Note: we also use this upon allocation failure in newGCString and
13324 // newGCFatInlineString. To squeeze out even more performance those failures
13325 // can be handled by allocate in ool code and returning to jit code to fill
13326 // in all data.
13327 using Fn = JSString* (*)(JSContext* cx, HandleString str, int32_t begin,
13328 int32_t len);
13329 OutOfLineCode* ool = oolCallVM<Fn, SubstringKernel>(
13330 lir, ArgList(string, begin, length), StoreRegisterTo(output));
13331 Label* slowPath = ool->entry();
13332 Label* done = ool->rejoin();
13333
13334 // Zero length, return emptystring.
13335 masm.branchTest32(Assembler::NonZero, length, length, &nonZero);
13336 const JSAtomState& names = gen->runtime->names();
13337 masm.movePtr(ImmGCPtr(names.empty_), output);
13338 masm.jump(done);
13339
13340 // Substring from 0..|str.length|, return str.
13341 masm.bind(&nonZero);
13342 masm.branch32(Assembler::NotEqual,
13343 Address(string, JSString::offsetOfLength()), length, &nonInput);
13344 #ifdef DEBUG
13345 {
13346 Label ok;
13347 masm.branchTest32(Assembler::Zero, begin, begin, &ok);
13348 masm.assumeUnreachable("length == str.length implies begin == 0");
13349 masm.bind(&ok);
13350 }
13351 #endif
13352 masm.movePtr(string, output);
13353 masm.jump(done);
13354
13355 // Use slow path for ropes.
13356 masm.bind(&nonInput);
13357 masm.branchIfRope(string, slowPath);
13358
13359 // Optimize one and two character strings.
13360 Label nonStatic;
13361 masm.branch32(Assembler::Above, length, Imm32(2), &nonStatic);
13362 {
13363 Label loadLengthOne, loadLengthTwo;
13364
13365 auto loadChars = [&](CharEncoding encoding, bool fallthru) {
13366 size_t size = encoding == CharEncoding::Latin1 ? sizeof(JS::Latin1Char)
13367 : sizeof(char16_t);
13368
13369 masm.loadStringChars(string, temp0, encoding);
13370 masm.loadChar(temp0, begin, temp2, encoding);
13371 masm.branch32(Assembler::Equal, length, Imm32(1), &loadLengthOne);
13372 masm.loadChar(temp0, begin, temp0, encoding, int32_t(size));
13373 if (!fallthru) {
13374 masm.jump(&loadLengthTwo);
13375 }
13376 };
13377
13378 Label isLatin1;
13379 masm.branchLatin1String(string, &isLatin1);
13380 loadChars(CharEncoding::TwoByte, /* fallthru = */ false);
13381
13382 masm.bind(&isLatin1);
13383 loadChars(CharEncoding::Latin1, /* fallthru = */ true);
13384
13385 // Try to load a length-two static string.
13386 masm.bind(&loadLengthTwo);
13387 masm.lookupStaticString(temp2, temp0, output, gen->runtime->staticStrings(),
13388 &nonStatic);
13389 masm.jump(done);
13390
13391 // Try to load a length-one static string.
13392 masm.bind(&loadLengthOne);
13393 masm.lookupStaticString(temp2, output, gen->runtime->staticStrings(),
13394 &nonStatic);
13395 masm.jump(done);
13396 }
13397 masm.bind(&nonStatic);
13398
13399 // Allocate either a JSThinInlineString or JSFatInlineString, or jump to
13400 // notInline if we need a dependent string.
13401 Label notInline;
13402 {
13403 static_assert(JSThinInlineString::MAX_LENGTH_LATIN1 <
13404 JSFatInlineString::MAX_LENGTH_LATIN1);
13405 static_assert(JSThinInlineString::MAX_LENGTH_TWO_BYTE <
13406 JSFatInlineString::MAX_LENGTH_TWO_BYTE);
13407
13408 // Use temp2 to store the JS(Thin|Fat)InlineString flags. This avoids having
13409 // duplicate newGCString/newGCFatInlineString codegen for Latin1 vs TwoByte
13410 // strings.
13411
13412 Label allocFat, allocDone;
13413 if (tryFatInlineOrDependent) {
13414 Label isLatin1, allocThin;
13415 masm.branchLatin1String(string, &isLatin1);
13416 {
13417 if (tryDependent) {
13418 masm.branch32(Assembler::Above, length,
13419 Imm32(JSFatInlineString::MAX_LENGTH_TWO_BYTE),
13420 &notInline);
13421 }
13422 masm.move32(Imm32(0), temp2);
13423 masm.branch32(Assembler::Above, length,
13424 Imm32(JSThinInlineString::MAX_LENGTH_TWO_BYTE),
13425 &allocFat);
13426 masm.jump(&allocThin);
13427 }
13428
13429 masm.bind(&isLatin1);
13430 {
13431 if (tryDependent) {
13432 masm.branch32(Assembler::Above, length,
13433 Imm32(JSFatInlineString::MAX_LENGTH_LATIN1),
13434 &notInline);
13435 }
13436 masm.move32(Imm32(JSString::LATIN1_CHARS_BIT), temp2);
13437 masm.branch32(Assembler::Above, length,
13438 Imm32(JSThinInlineString::MAX_LENGTH_LATIN1), &allocFat);
13439 }
13440
13441 masm.bind(&allocThin);
13442 } else {
13443 masm.load32(Address(string, JSString::offsetOfFlags()), temp2);
13444 masm.and32(Imm32(JSString::LATIN1_CHARS_BIT), temp2);
13445 }
13446
13447 {
13448 masm.newGCString(output, temp0, initialStringHeap(), slowPath);
13449 masm.or32(Imm32(JSString::INIT_THIN_INLINE_FLAGS), temp2);
13450 }
13451
13452 if (tryFatInlineOrDependent) {
13453 masm.jump(&allocDone);
13454
13455 masm.bind(&allocFat);
13456 {
13457 masm.newGCFatInlineString(output, temp0, initialStringHeap(), slowPath);
13458 masm.or32(Imm32(JSString::INIT_FAT_INLINE_FLAGS), temp2);
13459 }
13460
13461 masm.bind(&allocDone);
13462 }
13463
13464 masm.store32(temp2, Address(output, JSString::offsetOfFlags()));
13465 masm.store32(length, Address(output, JSString::offsetOfLength()));
13466
13467 auto initializeInlineString = [&](CharEncoding encoding) {
13468 masm.loadStringChars(string, temp0, encoding);
13469 masm.addToCharPtr(temp0, begin, encoding);
13470 if (temp1 == string) {
13471 masm.push(string);
13472 }
13473 masm.loadInlineStringCharsForStore(output, temp1);
13474 CopyStringChars(masm, temp1, temp0, length, temp2, encoding,
13475 maximumLength);
13476 masm.loadStringLength(output, length);
13477 if (temp1 == string) {
13478 masm.pop(string);
13479 }
13480 };
13481
13482 Label isInlineLatin1;
13483 masm.branchTest32(Assembler::NonZero, temp2,
13484 Imm32(JSString::LATIN1_CHARS_BIT), &isInlineLatin1);
13485 initializeInlineString(CharEncoding::TwoByte);
13486 masm.jump(done);
13487
13488 masm.bind(&isInlineLatin1);
13489 initializeInlineString(CharEncoding::Latin1);
13490 }
13491
13492 // Handle other cases with a DependentString.
13493 if (tryDependent) {
13494 masm.jump(done);
13495
13496 masm.bind(&notInline);
13497 masm.newGCString(output, temp0, gen->initialStringHeap(), slowPath);
13498 masm.store32(length, Address(output, JSString::offsetOfLength()));
13499
13500 // Note: no post barrier is needed because the dependent string is either
13501 // allocated in the nursery or both strings are tenured (if nursery strings
13502 // are disabled for this zone).
13503 EmitInitDependentStringBase(masm, output, string, temp0, temp2,
13504 /* needsPostBarrier = */ false);
13505
13506 auto initializeDependentString = [&](CharEncoding encoding) {
13507 uint32_t flags = JSString::INIT_DEPENDENT_FLAGS;
13508 if (encoding == CharEncoding::Latin1) {
13509 flags |= JSString::LATIN1_CHARS_BIT;
13510 }
13511 masm.store32(Imm32(flags), Address(output, JSString::offsetOfFlags()));
13512 masm.loadNonInlineStringChars(string, temp0, encoding);
13513 masm.addToCharPtr(temp0, begin, encoding);
13514 masm.storeNonInlineStringChars(temp0, output);
13515 };
13516
13517 Label isLatin1;
13518 masm.branchLatin1String(string, &isLatin1);
13519 initializeDependentString(CharEncoding::TwoByte);
13520 masm.jump(done);
13521
13522 masm.bind(&isLatin1);
13523 initializeDependentString(CharEncoding::Latin1);
13524 }
13525
13526 masm.bind(done);
13527 }
13528
13529 JitCode* JitZone::generateStringConcatStub(JSContext* cx) {
13530 JitSpew(JitSpew_Codegen, "# Emitting StringConcat stub");
13531
13532 TempAllocator temp(&cx->tempLifoAlloc());
13533 JitContext jcx(cx);
13534 StackMacroAssembler masm(cx, temp);
13535 AutoCreatedBy acb(masm, "JitZone::generateStringConcatStub");
13536
13537 Register lhs = CallTempReg0;
13538 Register rhs = CallTempReg1;
13539 Register temp1 = CallTempReg2;
13540 Register temp2 = CallTempReg3;
13541 Register temp3 = CallTempReg4;
13542 Register output = CallTempReg5;
13543
13544 Label failure;
13545 #ifdef JS_USE_LINK_REGISTER
13546 masm.pushReturnAddress();
13547 #endif
13548 masm.Push(FramePointer);
13549 masm.moveStackPtrTo(FramePointer);
13550
13551 // If lhs is empty, return rhs.
13552 Label leftEmpty;
13553 masm.loadStringLength(lhs, temp1);
13554 masm.branchTest32(Assembler::Zero, temp1, temp1, &leftEmpty);
13555
13556 // If rhs is empty, return lhs.
13557 Label rightEmpty;
13558 masm.loadStringLength(rhs, temp2);
13559 masm.branchTest32(Assembler::Zero, temp2, temp2, &rightEmpty);
13560
13561 masm.add32(temp1, temp2);
13562
13563 // Check if we can use a JSInlineString. The result is a Latin1 string if
13564 // lhs and rhs are both Latin1, so we AND the flags.
13565 Label isInlineTwoByte, isInlineLatin1;
13566 masm.load32(Address(lhs, JSString::offsetOfFlags()), temp1);
13567 masm.and32(Address(rhs, JSString::offsetOfFlags()), temp1);
13568
13569 Label isLatin1, notInline;
13570 masm.branchTest32(Assembler::NonZero, temp1,
13571 Imm32(JSString::LATIN1_CHARS_BIT), &isLatin1);
13572 {
13573 masm.branch32(Assembler::BelowOrEqual, temp2,
13574 Imm32(JSFatInlineString::MAX_LENGTH_TWO_BYTE),
13575 &isInlineTwoByte);
13576 masm.jump(&notInline);
13577 }
13578 masm.bind(&isLatin1);
13579 {
13580 masm.branch32(Assembler::BelowOrEqual, temp2,
13581 Imm32(JSFatInlineString::MAX_LENGTH_LATIN1), &isInlineLatin1);
13582 }
13583 masm.bind(&notInline);
13584
13585 // Keep AND'ed flags in temp1.
13586
13587 // Ensure result length <= JSString::MAX_LENGTH.
13588 masm.branch32(Assembler::Above, temp2, Imm32(JSString::MAX_LENGTH), &failure);
13589
13590 // Allocate a new rope, guaranteed to be in the nursery if initialStringHeap
13591 // == gc::Heap::Default. (As a result, no post barriers are needed below.)
13592 masm.newGCString(output, temp3, initialStringHeap, &failure);
13593
13594 // Store rope length and flags. temp1 still holds the result of AND'ing the
13595 // lhs and rhs flags, so we just have to clear the other flags to get our rope
13596 // flags (Latin1 if both lhs and rhs are Latin1).
13597 static_assert(JSString::INIT_ROPE_FLAGS == 0,
13598 "Rope type flags must have no bits set");
13599 masm.and32(Imm32(JSString::LATIN1_CHARS_BIT), temp1);
13600 masm.store32(temp1, Address(output, JSString::offsetOfFlags()));
13601 masm.store32(temp2, Address(output, JSString::offsetOfLength()));
13602
13603 // Store left and right nodes.
13604 masm.storeRopeChildren(lhs, rhs, output);
13605 masm.pop(FramePointer);
13606 masm.ret();
13607
13608 masm.bind(&leftEmpty);
13609 masm.mov(rhs, output);
13610 masm.pop(FramePointer);
13611 masm.ret();
13612
13613 masm.bind(&rightEmpty);
13614 masm.mov(lhs, output);
13615 masm.pop(FramePointer);
13616 masm.ret();
13617
13618 masm.bind(&isInlineTwoByte);
13619 ConcatInlineString(masm, lhs, rhs, output, temp1, temp2, temp3,
13620 initialStringHeap, &failure, CharEncoding::TwoByte);
13621 masm.pop(FramePointer);
13622 masm.ret();
13623
13624 masm.bind(&isInlineLatin1);
13625 ConcatInlineString(masm, lhs, rhs, output, temp1, temp2, temp3,
13626 initialStringHeap, &failure, CharEncoding::Latin1);
13627 masm.pop(FramePointer);
13628 masm.ret();
13629
13630 masm.bind(&failure);
13631 masm.movePtr(ImmPtr(nullptr), output);
13632 masm.pop(FramePointer);
13633 masm.ret();
13634
13635 Linker linker(masm);
13636 JitCode* code = linker.newCode(cx, CodeKind::Other);
13637
13638 CollectPerfSpewerJitCodeProfile(code, "StringConcatStub");
13639 #ifdef MOZ_VTUNE
13640 vtune::MarkStub(code, "StringConcatStub");
13641 #endif
13642
13643 return code;
13644 }
13645
13646 void JitRuntime::generateLazyLinkStub(MacroAssembler& masm) {
13647 AutoCreatedBy acb(masm, "JitRuntime::generateLazyLinkStub");
13648
13649 lazyLinkStubOffset_ = startTrampolineCode(masm);
13650
13651 #ifdef JS_USE_LINK_REGISTER
13652 masm.pushReturnAddress();
13653 #endif
13654 masm.Push(FramePointer);
13655 masm.moveStackPtrTo(FramePointer);
13656
13657 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::Volatile());
13658 Register temp0 = regs.takeAny();
13659 Register temp1 = regs.takeAny();
13660 Register temp2 = regs.takeAny();
13661
13662 masm.loadJSContext(temp0);
13663 masm.enterFakeExitFrame(temp0, temp2, ExitFrameType::LazyLink);
13664 masm.moveStackPtrTo(temp1);
13665
13666 using Fn = uint8_t* (*)(JSContext* cx, LazyLinkExitFrameLayout* frame);
13667 masm.setupUnalignedABICall(temp2);
13668 masm.passABIArg(temp0);
13669 masm.passABIArg(temp1);
13670 masm.callWithABI<Fn, LazyLinkTopActivation>(
13671 ABIType::General, CheckUnsafeCallWithABI::DontCheckHasExitFrame);
13672
13673 // Discard exit frame and restore frame pointer.
13674 masm.leaveExitFrame(0);
13675 masm.pop(FramePointer);
13676
13677 #ifdef JS_USE_LINK_REGISTER
13678 // Restore the return address such that the emitPrologue function of the
13679 // CodeGenerator can push it back on the stack with pushReturnAddress.
13680 masm.popReturnAddress();
13681 #endif
13682 masm.jump(ReturnReg);
13683 }
13684
13685 void JitRuntime::generateInterpreterStub(MacroAssembler& masm) {
13686 AutoCreatedBy acb(masm, "JitRuntime::generateInterpreterStub");
13687
13688 interpreterStubOffset_ = startTrampolineCode(masm);
13689
13690 #ifdef JS_USE_LINK_REGISTER
13691 masm.pushReturnAddress();
13692 #endif
13693 masm.Push(FramePointer);
13694 masm.moveStackPtrTo(FramePointer);
13695
13696 AllocatableGeneralRegisterSet regs(GeneralRegisterSet::Volatile());
13697 Register temp0 = regs.takeAny();
13698 Register temp1 = regs.takeAny();
13699 Register temp2 = regs.takeAny();
13700
13701 masm.loadJSContext(temp0);
13702 masm.enterFakeExitFrame(temp0, temp2, ExitFrameType::InterpreterStub);
13703 masm.moveStackPtrTo(temp1);
13704
13705 using Fn = bool (*)(JSContext* cx, InterpreterStubExitFrameLayout* frame);
13706 masm.setupUnalignedABICall(temp2);
13707 masm.passABIArg(temp0);
13708 masm.passABIArg(temp1);
13709 masm.callWithABI<Fn, InvokeFromInterpreterStub>(
13710 ABIType::General, CheckUnsafeCallWithABI::DontCheckHasExitFrame);
13711
13712 masm.branchIfFalseBool(ReturnReg, masm.failureLabel());
13713
13714 // Discard exit frame and restore frame pointer.
13715 masm.leaveExitFrame(0);
13716 masm.pop(FramePointer);
13717
13718 // InvokeFromInterpreterStub stores the return value in argv[0], where the
13719 // caller stored |this|. Subtract |sizeof(void*)| for the frame pointer we
13720 // just popped.
13721 masm.loadValue(Address(masm.getStackPointer(),
13722 JitFrameLayout::offsetOfThis() - sizeof(void*)),
13723 JSReturnOperand);
13724 masm.ret();
13725 }
13726
13727 void JitRuntime::generateDoubleToInt32ValueStub(MacroAssembler& masm) {
13728 AutoCreatedBy acb(masm, "JitRuntime::generateDoubleToInt32ValueStub");
13729 doubleToInt32ValueStubOffset_ = startTrampolineCode(masm);
13730
13731 Label done;
13732 masm.branchTestDouble(Assembler::NotEqual, R0, &done);
13733
13734 masm.unboxDouble(R0, FloatReg0);
13735 masm.convertDoubleToInt32(FloatReg0, R1.scratchReg(), &done,
13736 /* negativeZeroCheck = */ false);
13737 masm.tagValue(JSVAL_TYPE_INT32, R1.scratchReg(), R0);
13738
13739 masm.bind(&done);
13740 masm.abiret();
13741 }
13742
13743 void CodeGenerator::visitLinearizeString(LLinearizeString* lir) {
13744 Register str = ToRegister(lir->string());
13745 Register output = ToRegister(lir->output());
13746
13747 using Fn = JSLinearString* (*)(JSContext*, JSString*);
13748 auto* ool = oolCallVM<Fn, jit::LinearizeForCharAccess>(
13749 lir, ArgList(str), StoreRegisterTo(output));
13750
13751 masm.branchIfRope(str, ool->entry());
13752
13753 masm.movePtr(str, output);
13754 masm.bind(ool->rejoin());
13755 }
13756
13757 void CodeGenerator::visitLinearizeForCharAccess(LLinearizeForCharAccess* lir) {
13758 Register str = ToRegister(lir->string());
13759 Register index = ToRegister(lir->index());
13760 Register output = ToRegister(lir->output());
13761
13762 using Fn = JSLinearString* (*)(JSContext*, JSString*);
13763 auto* ool = oolCallVM<Fn, jit::LinearizeForCharAccess>(
13764 lir, ArgList(str), StoreRegisterTo(output));
13765
13766 masm.branchIfNotCanLoadStringChar(str, index, output, ool->entry());
13767
13768 masm.movePtr(str, output);
13769 masm.bind(ool->rejoin());
13770 }
13771
13772 void CodeGenerator::visitLinearizeForCodePointAccess(
13773 LLinearizeForCodePointAccess* lir) {
13774 Register str = ToRegister(lir->string());
13775 Register index = ToRegister(lir->index());
13776 Register output = ToRegister(lir->output());
13777 Register temp = ToRegister(lir->temp0());
13778
13779 using Fn = JSLinearString* (*)(JSContext*, JSString*);
13780 auto* ool = oolCallVM<Fn, jit::LinearizeForCharAccess>(
13781 lir, ArgList(str), StoreRegisterTo(output));
13782
13783 masm.branchIfNotCanLoadStringCodePoint(str, index, output, temp,
13784 ool->entry());
13785
13786 masm.movePtr(str, output);
13787 masm.bind(ool->rejoin());
13788 }
13789
13790 void CodeGenerator::visitToRelativeStringIndex(LToRelativeStringIndex* lir) {
13791 Register index = ToRegister(lir->index());
13792 Register length = ToRegister(lir->length());
13793 Register output = ToRegister(lir->output());
13794
13795 masm.move32(Imm32(0), output);
13796 masm.cmp32Move32(Assembler::LessThan, index, Imm32(0), length, output);
13797 masm.add32(index, output);
13798 }
13799
13800 void CodeGenerator::visitCharCodeAt(LCharCodeAt* lir) {
13801 Register str = ToRegister(lir->string());
13802 Register output = ToRegister(lir->output());
13803 Register temp0 = ToRegister(lir->temp0());
13804 Register temp1 = ToRegister(lir->temp1());
13805
13806 using Fn = bool (*)(JSContext*, HandleString, int32_t, uint32_t*);
13807
13808 if (lir->index()->isBogus()) {
13809 auto* ool = oolCallVM<Fn, jit::CharCodeAt>(lir, ArgList(str, Imm32(0)),
13810 StoreRegisterTo(output));
13811 masm.loadStringChar(str, 0, output, temp0, temp1, ool->entry());
13812 masm.bind(ool->rejoin());
13813 } else {
13814 Register index = ToRegister(lir->index());
13815
13816 auto* ool = oolCallVM<Fn, jit::CharCodeAt>(lir, ArgList(str, index),
13817 StoreRegisterTo(output));
13818 masm.loadStringChar(str, index, output, temp0, temp1, ool->entry());
13819 masm.bind(ool->rejoin());
13820 }
13821 }
13822
13823 void CodeGenerator::visitCharCodeAtOrNegative(LCharCodeAtOrNegative* lir) {
13824 Register str = ToRegister(lir->string());
13825 Register output = ToRegister(lir->output());
13826 Register temp0 = ToRegister(lir->temp0());
13827 Register temp1 = ToRegister(lir->temp1());
13828
13829 using Fn = bool (*)(JSContext*, HandleString, int32_t, uint32_t*);
13830
13831 // Return -1 for out-of-bounds access.
13832 masm.move32(Imm32(-1), output);
13833
13834 if (lir->index()->isBogus()) {
13835 auto* ool = oolCallVM<Fn, jit::CharCodeAt>(lir, ArgList(str, Imm32(0)),
13836 StoreRegisterTo(output));
13837
13838 masm.branch32(Assembler::Equal, Address(str, JSString::offsetOfLength()),
13839 Imm32(0), ool->rejoin());
13840 masm.loadStringChar(str, 0, output, temp0, temp1, ool->entry());
13841 masm.bind(ool->rejoin());
13842 } else {
13843 Register index = ToRegister(lir->index());
13844
13845 auto* ool = oolCallVM<Fn, jit::CharCodeAt>(lir, ArgList(str, index),
13846 StoreRegisterTo(output));
13847
13848 masm.spectreBoundsCheck32(index, Address(str, JSString::offsetOfLength()),
13849 temp0, ool->rejoin());
13850 masm.loadStringChar(str, index, output, temp0, temp1, ool->entry());
13851 masm.bind(ool->rejoin());
13852 }
13853 }
13854
13855 void CodeGenerator::visitCodePointAt(LCodePointAt* lir) {
13856 Register str = ToRegister(lir->string());
13857 Register index = ToRegister(lir->index());
13858 Register output = ToRegister(lir->output());
13859 Register temp0 = ToRegister(lir->temp0());
13860 Register temp1 = ToRegister(lir->temp1());
13861
13862 using Fn = bool (*)(JSContext*, HandleString, int32_t, uint32_t*);
13863 auto* ool = oolCallVM<Fn, jit::CodePointAt>(lir, ArgList(str, index),
13864 StoreRegisterTo(output));
13865
13866 masm.loadStringCodePoint(str, index, output, temp0, temp1, ool->entry());
13867 masm.bind(ool->rejoin());
13868 }
13869
13870 void CodeGenerator::visitCodePointAtOrNegative(LCodePointAtOrNegative* lir) {
13871 Register str = ToRegister(lir->string());
13872 Register index = ToRegister(lir->index());
13873 Register output = ToRegister(lir->output());
13874 Register temp0 = ToRegister(lir->temp0());
13875 Register temp1 = ToRegister(lir->temp1());
13876
13877 using Fn = bool (*)(JSContext*, HandleString, int32_t, uint32_t*);
13878 auto* ool = oolCallVM<Fn, jit::CodePointAt>(lir, ArgList(str, index),
13879 StoreRegisterTo(output));
13880
13881 // Return -1 for out-of-bounds access.
13882 masm.move32(Imm32(-1), output);
13883
13884 masm.spectreBoundsCheck32(index, Address(str, JSString::offsetOfLength()),
13885 temp0, ool->rejoin());
13886 masm.loadStringCodePoint(str, index, output, temp0, temp1, ool->entry());
13887 masm.bind(ool->rejoin());
13888 }
13889
13890 void CodeGenerator::visitNegativeToNaN(LNegativeToNaN* lir) {
13891 Register input = ToRegister(lir->input());
13892 ValueOperand output = ToOutValue(lir);
13893
13894 masm.tagValue(JSVAL_TYPE_INT32, input, output);
13895
13896 Label done;
13897 masm.branchTest32(Assembler::NotSigned, input, input, &done);
13898 masm.moveValue(JS::NaNValue(), output);
13899 masm.bind(&done);
13900 }
13901
13902 void CodeGenerator::visitNegativeToUndefined(LNegativeToUndefined* lir) {
13903 Register input = ToRegister(lir->input());
13904 ValueOperand output = ToOutValue(lir);
13905
13906 masm.tagValue(JSVAL_TYPE_INT32, input, output);
13907
13908 Label done;
13909 masm.branchTest32(Assembler::NotSigned, input, input, &done);
13910 masm.moveValue(JS::UndefinedValue(), output);
13911 masm.bind(&done);
13912 }
13913
13914 void CodeGenerator::visitFromCharCode(LFromCharCode* lir) {
13915 Register code = ToRegister(lir->code());
13916 Register output = ToRegister(lir->output());
13917
13918 using Fn = JSLinearString* (*)(JSContext*, int32_t);
13919 auto* ool = oolCallVM<Fn, js::StringFromCharCode>(lir, ArgList(code),
13920 StoreRegisterTo(output));
13921
13922 // OOL path if code >= UNIT_STATIC_LIMIT.
13923 masm.lookupStaticString(code, output, gen->runtime->staticStrings(),
13924 ool->entry());
13925
13926 masm.bind(ool->rejoin());
13927 }
13928
13929 void CodeGenerator::visitFromCharCodeEmptyIfNegative(
13930 LFromCharCodeEmptyIfNegative* lir) {
13931 Register code = ToRegister(lir->code());
13932 Register output = ToRegister(lir->output());
13933
13934 using Fn = JSLinearString* (*)(JSContext*, int32_t);
13935 auto* ool = oolCallVM<Fn, js::StringFromCharCode>(lir, ArgList(code),
13936 StoreRegisterTo(output));
13937
13938 // Return the empty string for negative inputs.
13939 const JSAtomState& names = gen->runtime->names();
13940 masm.movePtr(ImmGCPtr(names.empty_), output);
13941 masm.branchTest32(Assembler::Signed, code, code, ool->rejoin());
13942
13943 // OOL path if code >= UNIT_STATIC_LIMIT.
13944 masm.lookupStaticString(code, output, gen->runtime->staticStrings(),
13945 ool->entry());
13946
13947 masm.bind(ool->rejoin());
13948 }
13949
13950 void CodeGenerator::visitFromCharCodeUndefinedIfNegative(
13951 LFromCharCodeUndefinedIfNegative* lir) {
13952 Register code = ToRegister(lir->code());
13953 ValueOperand output = ToOutValue(lir);
13954 Register temp = output.scratchReg();
13955
13956 using Fn = JSLinearString* (*)(JSContext*, int32_t);
13957 auto* ool = oolCallVM<Fn, js::StringFromCharCode>(lir, ArgList(code),
13958 StoreRegisterTo(temp));
13959
13960 // Return |undefined| for negative inputs.
13961 Label done;
13962 masm.moveValue(UndefinedValue(), output);
13963 masm.branchTest32(Assembler::Signed, code, code, &done);
13964
13965 // OOL path if code >= UNIT_STATIC_LIMIT.
13966 masm.lookupStaticString(code, temp, gen->runtime->staticStrings(),
13967 ool->entry());
13968
13969 masm.bind(ool->rejoin());
13970 masm.tagValue(JSVAL_TYPE_STRING, temp, output);
13971
13972 masm.bind(&done);
13973 }
13974
13975 void CodeGenerator::visitFromCodePoint(LFromCodePoint* lir) {
13976 Register codePoint = ToRegister(lir->codePoint());
13977 Register output = ToRegister(lir->output());
13978 Register temp0 = ToRegister(lir->temp0());
13979 Register temp1 = ToRegister(lir->temp1());
13980 LSnapshot* snapshot = lir->snapshot();
13981
13982 // The OOL path is only taken when we can't allocate the inline string.
13983 using Fn = JSLinearString* (*)(JSContext*, char32_t);
13984 auto* ool = oolCallVM<Fn, js::StringFromCodePoint>(lir, ArgList(codePoint),
13985 StoreRegisterTo(output));
13986
13987 Label isTwoByte;
13988 Label* done = ool->rejoin();
13989
13990 static_assert(
13991 StaticStrings::UNIT_STATIC_LIMIT - 1 == JSString::MAX_LATIN1_CHAR,
13992 "Latin-1 strings can be loaded from static strings");
13993
13994 {
13995 masm.lookupStaticString(codePoint, output, gen->runtime->staticStrings(),
13996 &isTwoByte);
13997 masm.jump(done);
13998 }
13999 masm.bind(&isTwoByte);
14000 {
14001 // Use a bailout if the input is not a valid code point, because
14002 // MFromCodePoint is movable and it'd be observable when a moved
14003 // fromCodePoint throws an exception before its actual call site.
14004 bailoutCmp32(Assembler::Above, codePoint, Imm32(unicode::NonBMPMax),
14005 snapshot);
14006
14007 // Allocate a JSThinInlineString.
14008 {
14009 static_assert(JSThinInlineString::MAX_LENGTH_TWO_BYTE >= 2,
14010 "JSThinInlineString can hold a supplementary code point");
14011
14012 uint32_t flags = JSString::INIT_THIN_INLINE_FLAGS;
14013 masm.newGCString(output, temp0, gen->initialStringHeap(), ool->entry());
14014 masm.store32(Imm32(flags), Address(output, JSString::offsetOfFlags()));
14015 }
14016
14017 Label isSupplementary;
14018 masm.branch32(Assembler::AboveOrEqual, codePoint, Imm32(unicode::NonBMPMin),
14019 &isSupplementary);
14020 {
14021 // Store length.
14022 masm.store32(Imm32(1), Address(output, JSString::offsetOfLength()));
14023
14024 // Load chars pointer in temp0.
14025 masm.loadInlineStringCharsForStore(output, temp0);
14026
14027 masm.store16(codePoint, Address(temp0, 0));
14028
14029 masm.jump(done);
14030 }
14031 masm.bind(&isSupplementary);
14032 {
14033 // Store length.
14034 masm.store32(Imm32(2), Address(output, JSString::offsetOfLength()));
14035
14036 // Load chars pointer in temp0.
14037 masm.loadInlineStringCharsForStore(output, temp0);
14038
14039 // Inlined unicode::LeadSurrogate(uint32_t).
14040 masm.rshift32(Imm32(10), codePoint, temp1);
14041 masm.add32(Imm32(unicode::LeadSurrogateMin - (unicode::NonBMPMin >> 10)),
14042 temp1);
14043
14044 masm.store16(temp1, Address(temp0, 0));
14045
14046 // Inlined unicode::TrailSurrogate(uint32_t).
14047 masm.and32(Imm32(0x3FF), codePoint, temp1);
14048 masm.or32(Imm32(unicode::TrailSurrogateMin), temp1);
14049
14050 masm.store16(temp1, Address(temp0, sizeof(char16_t)));
14051 }
14052 }
14053
14054 masm.bind(done);
14055 }
14056
14057 void CodeGenerator::visitStringIncludes(LStringIncludes* lir) {
14058 pushArg(ToRegister(lir->searchString()));
14059 pushArg(ToRegister(lir->string()));
14060
14061 using Fn = bool (*)(JSContext*, HandleString, HandleString, bool*);
14062 callVM<Fn, js::StringIncludes>(lir);
14063 }
14064
14065 template <typename LIns>
14066 static void CallStringMatch(MacroAssembler& masm, LIns* lir, OutOfLineCode* ool,
14067 LiveRegisterSet volatileRegs) {
14068 Register string = ToRegister(lir->string());
14069 Register output = ToRegister(lir->output());
14070 Register tempLength = ToRegister(lir->temp0());
14071 Register tempChars = ToRegister(lir->temp1());
14072 Register maybeTempPat = ToTempRegisterOrInvalid(lir->temp2());
14073
14074 const JSLinearString* searchString = lir->searchString();
14075 size_t length = searchString->length();
14076 MOZ_ASSERT(length == 1 || length == 2);
14077
14078 // The additional temp register is only needed when searching for two
14079 // pattern characters.
14080 MOZ_ASSERT_IF(length == 2, maybeTempPat != InvalidReg);
14081
14082 if constexpr (std::is_same_v<LIns, LStringIncludesSIMD>) {
14083 masm.move32(Imm32(0), output);
14084 } else {
14085 masm.move32(Imm32(-1), output);
14086 }
14087
14088 masm.loadStringLength(string, tempLength);
14089
14090 // Can't be a substring when the string is smaller than the search string.
14091 Label done;
14092 masm.branch32(Assembler::Below, tempLength, Imm32(length), ool->rejoin());
14093
14094 bool searchStringIsPureTwoByte = false;
14095 if (searchString->hasTwoByteChars()) {
14096 JS::AutoCheckCannotGC nogc;
14097 searchStringIsPureTwoByte =
14098 !mozilla::IsUtf16Latin1(searchString->twoByteRange(nogc));
14099 }
14100
14101 // Pure two-byte strings can't occur in a Latin-1 string.
14102 if (searchStringIsPureTwoByte) {
14103 masm.branchLatin1String(string, ool->rejoin());
14104 }
14105
14106 // Slow path when we need to linearize the string.
14107 masm.branchIfRope(string, ool->entry());
14108
14109 Label restoreVolatile;
14110
14111 auto callMatcher = [&](CharEncoding encoding) {
14112 masm.loadStringChars(string, tempChars, encoding);
14113
14114 LiveGeneralRegisterSet liveRegs;
14115 if constexpr (std::is_same_v<LIns, LStringIndexOfSIMD>) {
14116 // Save |tempChars| to compute the result index.
14117 liveRegs.add(tempChars);
14118
14119 #ifdef DEBUG
14120 // Save |tempLength| in debug-mode for assertions.
14121 liveRegs.add(tempLength);
14122 #endif
14123
14124 // Exclude non-volatile registers.
14125 liveRegs.set() = GeneralRegisterSet::Intersect(
14126 liveRegs.set(), GeneralRegisterSet::Volatile());
14127
14128 masm.PushRegsInMask(liveRegs);
14129 }
14130
14131 if (length == 1) {
14132 char16_t pat = searchString->latin1OrTwoByteChar(0);
14133 MOZ_ASSERT_IF(encoding == CharEncoding::Latin1,
14134 pat <= JSString::MAX_LATIN1_CHAR);
14135
14136 masm.move32(Imm32(pat), output);
14137
14138 masm.setupAlignedABICall();
14139 masm.passABIArg(tempChars);
14140 masm.passABIArg(output);
14141 masm.passABIArg(tempLength);
14142 if (encoding == CharEncoding::Latin1) {
14143 using Fn = const char* (*)(const char*, char, size_t);
14144 masm.callWithABI<Fn, mozilla::SIMD::memchr8>(
14145 ABIType::General, CheckUnsafeCallWithABI::DontCheckOther);
14146 } else {
14147 using Fn = const char16_t* (*)(const char16_t*, char16_t, size_t);
14148 masm.callWithABI<Fn, mozilla::SIMD::memchr16>(
14149 ABIType::General, CheckUnsafeCallWithABI::DontCheckOther);
14150 }
14151 } else {
14152 char16_t pat0 = searchString->latin1OrTwoByteChar(0);
14153 MOZ_ASSERT_IF(encoding == CharEncoding::Latin1,
14154 pat0 <= JSString::MAX_LATIN1_CHAR);
14155
14156 char16_t pat1 = searchString->latin1OrTwoByteChar(1);
14157 MOZ_ASSERT_IF(encoding == CharEncoding::Latin1,
14158 pat1 <= JSString::MAX_LATIN1_CHAR);
14159
14160 masm.move32(Imm32(pat0), output);
14161 masm.move32(Imm32(pat1), maybeTempPat);
14162
14163 masm.setupAlignedABICall();
14164 masm.passABIArg(tempChars);
14165 masm.passABIArg(output);
14166 masm.passABIArg(maybeTempPat);
14167 masm.passABIArg(tempLength);
14168 if (encoding == CharEncoding::Latin1) {
14169 using Fn = const char* (*)(const char*, char, char, size_t);
14170 masm.callWithABI<Fn, mozilla::SIMD::memchr2x8>(
14171 ABIType::General, CheckUnsafeCallWithABI::DontCheckOther);
14172 } else {
14173 using Fn =
14174 const char16_t* (*)(const char16_t*, char16_t, char16_t, size_t);
14175 masm.callWithABI<Fn, mozilla::SIMD::memchr2x16>(
14176 ABIType::General, CheckUnsafeCallWithABI::DontCheckOther);
14177 }
14178 }
14179
14180 masm.storeCallPointerResult(output);
14181
14182 // Convert to string index for `indexOf`.
14183 if constexpr (std::is_same_v<LIns, LStringIndexOfSIMD>) {
14184 // Restore |tempChars|. (And in debug mode |tempLength|.)
14185 masm.PopRegsInMask(liveRegs);
14186
14187 Label found;
14188 masm.branchPtr(Assembler::NotEqual, output, ImmPtr(nullptr), &found);
14189 {
14190 masm.move32(Imm32(-1), output);
14191 masm.jump(&restoreVolatile);
14192 }
14193 masm.bind(&found);
14194
14195 #ifdef DEBUG
14196 // Check lower bound.
14197 Label lower;
14198 masm.branchPtr(Assembler::AboveOrEqual, output, tempChars, &lower);
14199 masm.assumeUnreachable("result pointer below string chars");
14200 masm.bind(&lower);
14201
14202 // Compute the end position of the characters.
14203 auto scale = encoding == CharEncoding::Latin1 ? TimesOne : TimesTwo;
14204 masm.computeEffectiveAddress(BaseIndex(tempChars, tempLength, scale),
14205 tempLength);
14206
14207 // Check upper bound.
14208 Label upper;
14209 masm.branchPtr(Assembler::Below, output, tempLength, &upper);
14210 masm.assumeUnreachable("result pointer above string chars");
14211 masm.bind(&upper);
14212 #endif
14213
14214 masm.subPtr(tempChars, output);
14215
14216 if (encoding == CharEncoding::TwoByte) {
14217 masm.rshiftPtr(Imm32(1), output);
14218 }
14219 }
14220 };
14221
14222 volatileRegs.takeUnchecked(output);
14223 volatileRegs.takeUnchecked(tempLength);
14224 volatileRegs.takeUnchecked(tempChars);
14225 if (maybeTempPat != InvalidReg) {
14226 volatileRegs.takeUnchecked(maybeTempPat);
14227 }
14228 masm.PushRegsInMask(volatileRegs);
14229
14230 // Handle the case when the input is a Latin-1 string.
14231 if (!searchStringIsPureTwoByte) {
14232 Label twoByte;
14233 masm.branchTwoByteString(string, &twoByte);
14234 {
14235 callMatcher(CharEncoding::Latin1);
14236 masm.jump(&restoreVolatile);
14237 }
14238 masm.bind(&twoByte);
14239 }
14240
14241 // Handle the case when the input is a two-byte string.
14242 callMatcher(CharEncoding::TwoByte);
14243
14244 masm.bind(&restoreVolatile);
14245 masm.PopRegsInMask(volatileRegs);
14246
14247 // Convert to bool for `includes`.
14248 if constexpr (std::is_same_v<LIns, LStringIncludesSIMD>) {
14249 masm.cmpPtrSet(Assembler::NotEqual, output, ImmPtr(nullptr), output);
14250 }
14251
14252 masm.bind(ool->rejoin());
14253 }
14254
14255 void CodeGenerator::visitStringIncludesSIMD(LStringIncludesSIMD* lir) {
14256 Register string = ToRegister(lir->string());
14257 Register output = ToRegister(lir->output());
14258 const JSLinearString* searchString = lir->searchString();
14259
14260 using Fn = bool (*)(JSContext*, HandleString, HandleString, bool*);
14261 auto* ool = oolCallVM<Fn, js::StringIncludes>(
14262 lir, ArgList(string, ImmGCPtr(searchString)), StoreRegisterTo(output));
14263
14264 CallStringMatch(masm, lir, ool, liveVolatileRegs(lir));
14265 }
14266
14267 void CodeGenerator::visitStringIndexOf(LStringIndexOf* lir) {
14268 pushArg(ToRegister(lir->searchString()));
14269 pushArg(ToRegister(lir->string()));
14270
14271 using Fn = bool (*)(JSContext*, HandleString, HandleString, int32_t*);
14272 callVM<Fn, js::StringIndexOf>(lir);
14273 }
14274
14275 void CodeGenerator::visitStringIndexOfSIMD(LStringIndexOfSIMD* lir) {
14276 Register string = ToRegister(lir->string());
14277 Register output = ToRegister(lir->output());
14278 const JSLinearString* searchString = lir->searchString();
14279
14280 using Fn = bool (*)(JSContext*, HandleString, HandleString, int32_t*);
14281 auto* ool = oolCallVM<Fn, js::StringIndexOf>(
14282 lir, ArgList(string, ImmGCPtr(searchString)), StoreRegisterTo(output));
14283
14284 CallStringMatch(masm, lir, ool, liveVolatileRegs(lir));
14285 }
14286
14287 void CodeGenerator::visitStringLastIndexOf(LStringLastIndexOf* lir) {
14288 pushArg(ToRegister(lir->searchString()));
14289 pushArg(ToRegister(lir->string()));
14290
14291 using Fn = bool (*)(JSContext*, HandleString, HandleString, int32_t*);
14292 callVM<Fn, js::StringLastIndexOf>(lir);
14293 }
14294
14295 void CodeGenerator::visitStringStartsWith(LStringStartsWith* lir) {
14296 pushArg(ToRegister(lir->searchString()));
14297 pushArg(ToRegister(lir->string()));
14298
14299 using Fn = bool (*)(JSContext*, HandleString, HandleString, bool*);
14300 callVM<Fn, js::StringStartsWith>(lir);
14301 }
14302
14303 void CodeGenerator::visitStringStartsWithInline(LStringStartsWithInline* lir) {
14304 Register string = ToRegister(lir->string());
14305 Register output = ToRegister(lir->output());
14306 Register temp = ToRegister(lir->temp0());
14307
14308 const JSLinearString* searchString = lir->searchString();
14309
14310 size_t length = searchString->length();
14311 MOZ_ASSERT(length > 0);
14312
14313 using Fn = bool (*)(JSContext*, HandleString, HandleString, bool*);
14314 auto* ool = oolCallVM<Fn, js::StringStartsWith>(
14315 lir, ArgList(string, ImmGCPtr(searchString)), StoreRegisterTo(output));
14316
14317 masm.move32(Imm32(0), output);
14318
14319 // Can't be a prefix when the string is smaller than the search string.
14320 masm.branch32(Assembler::Below, Address(string, JSString::offsetOfLength()),
14321 Imm32(length), ool->rejoin());
14322
14323 // Unwind ropes at the start if possible.
14324 Label compare;
14325 masm.movePtr(string, temp);
14326 masm.branchIfNotRope(temp, &compare);
14327
14328 Label unwindRope;
14329 masm.bind(&unwindRope);
14330 masm.loadRopeLeftChild(temp, output);
14331 masm.movePtr(output, temp);
14332
14333 // If the left child is smaller than the search string, jump into the VM to
14334 // linearize the string.
14335 masm.branch32(Assembler::Below, Address(temp, JSString::offsetOfLength()),
14336 Imm32(length), ool->entry());
14337
14338 // Otherwise keep unwinding ropes.
14339 masm.branchIfRope(temp, &unwindRope);
14340
14341 masm.bind(&compare);
14342
14343 // If operands point to the same instance, it's trivially a prefix.
14344 Label notPointerEqual;
14345 masm.branchPtr(Assembler::NotEqual, temp, ImmGCPtr(searchString),
14346 &notPointerEqual);
14347 masm.move32(Imm32(1), output);
14348 masm.jump(ool->rejoin());
14349 masm.bind(&notPointerEqual);
14350
14351 if (searchString->hasTwoByteChars()) {
14352 // Pure two-byte strings can't be a prefix of Latin-1 strings.
14353 JS::AutoCheckCannotGC nogc;
14354 if (!mozilla::IsUtf16Latin1(searchString->twoByteRange(nogc))) {
14355 Label compareChars;
14356 masm.branchTwoByteString(temp, &compareChars);
14357 masm.move32(Imm32(0), output);
14358 masm.jump(ool->rejoin());
14359 masm.bind(&compareChars);
14360 }
14361 }
14362
14363 // Load the input string's characters.
14364 Register stringChars = output;
14365 masm.loadStringCharsForCompare(temp, searchString, stringChars, ool->entry());
14366
14367 // Start comparing character by character.
14368 masm.compareStringChars(JSOp::Eq, stringChars, searchString, output);
14369
14370 masm.bind(ool->rejoin());
14371 }
14372
14373 void CodeGenerator::visitStringEndsWith(LStringEndsWith* lir) {
14374 pushArg(ToRegister(lir->searchString()));
14375 pushArg(ToRegister(lir->string()));
14376
14377 using Fn = bool (*)(JSContext*, HandleString, HandleString, bool*);
14378 callVM<Fn, js::StringEndsWith>(lir);
14379 }
14380
14381 void CodeGenerator::visitStringEndsWithInline(LStringEndsWithInline* lir) {
14382 Register string = ToRegister(lir->string());
14383 Register output = ToRegister(lir->output());
14384 Register temp = ToRegister(lir->temp0());
14385
14386 const JSLinearString* searchString = lir->searchString();
14387
14388 size_t length = searchString->length();
14389 MOZ_ASSERT(length > 0);
14390
14391 using Fn = bool (*)(JSContext*, HandleString, HandleString, bool*);
14392 auto* ool = oolCallVM<Fn, js::StringEndsWith>(
14393 lir, ArgList(string, ImmGCPtr(searchString)), StoreRegisterTo(output));
14394
14395 masm.move32(Imm32(0), output);
14396
14397 // Can't be a suffix when the string is smaller than the search string.
14398 masm.branch32(Assembler::Below, Address(string, JSString::offsetOfLength()),
14399 Imm32(length), ool->rejoin());
14400
14401 // Unwind ropes at the end if possible.
14402 Label compare;
14403 masm.movePtr(string, temp);
14404 masm.branchIfNotRope(temp, &compare);
14405
14406 Label unwindRope;
14407 masm.bind(&unwindRope);
14408 masm.loadRopeRightChild(temp, output);
14409 masm.movePtr(output, temp);
14410
14411 // If the right child is smaller than the search string, jump into the VM to
14412 // linearize the string.
14413 masm.branch32(Assembler::Below, Address(temp, JSString::offsetOfLength()),
14414 Imm32(length), ool->entry());
14415
14416 // Otherwise keep unwinding ropes.
14417 masm.branchIfRope(temp, &unwindRope);
14418
14419 masm.bind(&compare);
14420
14421 // If operands point to the same instance, it's trivially a suffix.
14422 Label notPointerEqual;
14423 masm.branchPtr(Assembler::NotEqual, temp, ImmGCPtr(searchString),
14424 &notPointerEqual);
14425 masm.move32(Imm32(1), output);
14426 masm.jump(ool->rejoin());
14427 masm.bind(&notPointerEqual);
14428
14429 CharEncoding encoding = searchString->hasLatin1Chars()
14430 ? CharEncoding::Latin1
14431 : CharEncoding::TwoByte;
14432 if (encoding == CharEncoding::TwoByte) {
14433 // Pure two-byte strings can't be a suffix of Latin-1 strings.
14434 JS::AutoCheckCannotGC nogc;
14435 if (!mozilla::IsUtf16Latin1(searchString->twoByteRange(nogc))) {
14436 Label compareChars;
14437 masm.branchTwoByteString(temp, &compareChars);
14438 masm.move32(Imm32(0), output);
14439 masm.jump(ool->rejoin());
14440 masm.bind(&compareChars);
14441 }
14442 }
14443
14444 // Load the input string's characters.
14445 Register stringChars = output;
14446 masm.loadStringCharsForCompare(temp, searchString, stringChars, ool->entry());
14447
14448 // Move string-char pointer to the suffix string.
14449 masm.loadStringLength(temp, temp);
14450 masm.sub32(Imm32(length), temp);
14451 masm.addToCharPtr(stringChars, temp, encoding);
14452
14453 // Start comparing character by character.
14454 masm.compareStringChars(JSOp::Eq, stringChars, searchString, output);
14455
14456 masm.bind(ool->rejoin());
14457 }
14458
14459 void CodeGenerator::visitStringToLowerCase(LStringToLowerCase* lir) {
14460 Register string = ToRegister(lir->string());
14461 Register output = ToRegister(lir->output());
14462 Register temp0 = ToRegister(lir->temp0());
14463 Register temp1 = ToRegister(lir->temp1());
14464 Register temp2 = ToRegister(lir->temp2());
14465
14466 // On x86 there are not enough registers. In that case reuse the string
14467 // register as a temporary.
14468 Register temp3 =
14469 lir->temp3()->isBogusTemp() ? string : ToRegister(lir->temp3());
14470 Register temp4 = ToRegister(lir->temp4());
14471
14472 using Fn = JSLinearString* (*)(JSContext*, JSString*);
14473 OutOfLineCode* ool = oolCallVM<Fn, js::StringToLowerCase>(
14474 lir, ArgList(string), StoreRegisterTo(output));
14475
14476 // Take the slow path if the string isn't a linear Latin-1 string.
14477 Imm32 linearLatin1Bits(JSString::LINEAR_BIT | JSString::LATIN1_CHARS_BIT);
14478 Register flags = temp0;
14479 masm.load32(Address(string, JSString::offsetOfFlags()), flags);
14480 masm.and32(linearLatin1Bits, flags);
14481 masm.branch32(Assembler::NotEqual, flags, linearLatin1Bits, ool->entry());
14482
14483 Register length = temp0;
14484 masm.loadStringLength(string, length);
14485
14486 // Return the input if it's the empty string.
14487 Label notEmptyString;
14488 masm.branch32(Assembler::NotEqual, length, Imm32(0), &notEmptyString);
14489 {
14490 masm.movePtr(string, output);
14491 masm.jump(ool->rejoin());
14492 }
14493 masm.bind(&notEmptyString);
14494
14495 Register inputChars = temp1;
14496 masm.loadStringChars(string, inputChars, CharEncoding::Latin1);
14497
14498 Register toLowerCaseTable = temp2;
14499 masm.movePtr(ImmPtr(unicode::latin1ToLowerCaseTable), toLowerCaseTable);
14500
14501 // Single element strings can be directly retrieved from static strings cache.
14502 Label notSingleElementString;
14503 masm.branch32(Assembler::NotEqual, length, Imm32(1), &notSingleElementString);
14504 {
14505 Register current = temp4;
14506
14507 masm.loadChar(Address(inputChars, 0), current, CharEncoding::Latin1);
14508 masm.load8ZeroExtend(BaseIndex(toLowerCaseTable, current, TimesOne),
14509 current);
14510 masm.lookupStaticString(current, output, gen->runtime->staticStrings());
14511
14512 masm.jump(ool->rejoin());
14513 }
14514 masm.bind(&notSingleElementString);
14515
14516 // Use the OOL-path when the string is too long. This prevents scanning long
14517 // strings which have upper case characters only near the end a second time in
14518 // the VM.
14519 constexpr int32_t MaxInlineLength = 64;
14520 masm.branch32(Assembler::Above, length, Imm32(MaxInlineLength), ool->entry());
14521
14522 {
14523 // Check if there are any characters which need to be converted.
14524 //
14525 // This extra loop gives a small performance improvement for strings which
14526 // are already lower cased and lets us avoid calling into the runtime for
14527 // non-inline, all lower case strings. But more importantly it avoids
14528 // repeated inline allocation failures:
14529 // |AllocateThinOrFatInlineString| below takes the OOL-path and calls the
14530 // |js::StringToLowerCase| runtime function when the result string can't be
14531 // allocated inline. And |js::StringToLowerCase| directly returns the input
14532 // string when no characters need to be converted. That means it won't
14533 // trigger GC to clear up the free nursery space, so the next toLowerCase()
14534 // call will again fail to inline allocate the result string.
14535 Label hasUpper;
14536 {
14537 Register checkInputChars = output;
14538 masm.movePtr(inputChars, checkInputChars);
14539
14540 Register current = temp4;
14541
14542 Label start;
14543 masm.bind(&start);
14544 masm.loadChar(Address(checkInputChars, 0), current, CharEncoding::Latin1);
14545 masm.branch8(Assembler::NotEqual,
14546 BaseIndex(toLowerCaseTable, current, TimesOne), current,
14547 &hasUpper);
14548 masm.addPtr(Imm32(sizeof(Latin1Char)), checkInputChars);
14549 masm.branchSub32(Assembler::NonZero, Imm32(1), length, &start);
14550
14551 // Input is already in lower case.
14552 masm.movePtr(string, output);
14553 masm.jump(ool->rejoin());
14554 }
14555 masm.bind(&hasUpper);
14556
14557 // |length| was clobbered above, reload.
14558 masm.loadStringLength(string, length);
14559
14560 // Call into the runtime when we can't create an inline string.
14561 masm.branch32(Assembler::Above, length,
14562 Imm32(JSFatInlineString::MAX_LENGTH_LATIN1), ool->entry());
14563
14564 AllocateThinOrFatInlineString(masm, output, length, temp4,
14565 initialStringHeap(), ool->entry(),
14566 CharEncoding::Latin1);
14567
14568 if (temp3 == string) {
14569 masm.push(string);
14570 }
14571
14572 Register outputChars = temp3;
14573 masm.loadInlineStringCharsForStore(output, outputChars);
14574
14575 {
14576 Register current = temp4;
14577
14578 Label start;
14579 masm.bind(&start);
14580 masm.loadChar(Address(inputChars, 0), current, CharEncoding::Latin1);
14581 masm.load8ZeroExtend(BaseIndex(toLowerCaseTable, current, TimesOne),
14582 current);
14583 masm.storeChar(current, Address(outputChars, 0), CharEncoding::Latin1);
14584 masm.addPtr(Imm32(sizeof(Latin1Char)), inputChars);
14585 masm.addPtr(Imm32(sizeof(Latin1Char)), outputChars);
14586 masm.branchSub32(Assembler::NonZero, Imm32(1), length, &start);
14587 }
14588
14589 if (temp3 == string) {
14590 masm.pop(string);
14591 }
14592 }
14593
14594 masm.bind(ool->rejoin());
14595 }
14596
14597 void CodeGenerator::visitStringToUpperCase(LStringToUpperCase* lir) {
14598 pushArg(ToRegister(lir->string()));
14599
14600 using Fn = JSLinearString* (*)(JSContext*, JSString*);
14601 callVM<Fn, js::StringToUpperCase>(lir);
14602 }
14603
14604 void CodeGenerator::visitCharCodeToLowerCase(LCharCodeToLowerCase* lir) {
14605 Register code = ToRegister(lir->code());
14606 Register output = ToRegister(lir->output());
14607 Register temp = ToRegister(lir->temp0());
14608
14609 using Fn = JSString* (*)(JSContext*, int32_t);
14610 auto* ool = oolCallVM<Fn, jit::CharCodeToLowerCase>(lir, ArgList(code),
14611 StoreRegisterTo(output));
14612
14613 constexpr char16_t NonLatin1Min = char16_t(JSString::MAX_LATIN1_CHAR) + 1;
14614
14615 // OOL path if code >= NonLatin1Min.
14616 masm.boundsCheck32PowerOfTwo(code, NonLatin1Min, ool->entry());
14617
14618 // Convert to lower case.
14619 masm.movePtr(ImmPtr(unicode::latin1ToLowerCaseTable), temp);
14620 masm.load8ZeroExtend(BaseIndex(temp, code, TimesOne), temp);
14621
14622 // Load static string for lower case character.
14623 masm.lookupStaticString(temp, output, gen->runtime->staticStrings());
14624
14625 masm.bind(ool->rejoin());
14626 }
14627
14628 void CodeGenerator::visitCharCodeToUpperCase(LCharCodeToUpperCase* lir) {
14629 Register code = ToRegister(lir->code());
14630 Register output = ToRegister(lir->output());
14631 Register temp = ToRegister(lir->temp0());
14632
14633 using Fn = JSString* (*)(JSContext*, int32_t);
14634 auto* ool = oolCallVM<Fn, jit::CharCodeToUpperCase>(lir, ArgList(code),
14635 StoreRegisterTo(output));
14636
14637 constexpr char16_t NonLatin1Min = char16_t(JSString::MAX_LATIN1_CHAR) + 1;
14638
14639 // OOL path if code >= NonLatin1Min.
14640 masm.boundsCheck32PowerOfTwo(code, NonLatin1Min, ool->entry());
14641
14642 // Most one element Latin-1 strings can be directly retrieved from the
14643 // static strings cache, except the following three characters:
14644 //
14645 // 1. ToUpper(U+00B5) = 0+039C
14646 // 2. ToUpper(U+00FF) = 0+0178
14647 // 3. ToUpper(U+00DF) = 0+0053 0+0053
14648 masm.branch32(Assembler::Equal, code, Imm32(unicode::MICRO_SIGN),
14649 ool->entry());
14650 masm.branch32(Assembler::Equal, code,
14651 Imm32(unicode::LATIN_SMALL_LETTER_Y_WITH_DIAERESIS),
14652 ool->entry());
14653 masm.branch32(Assembler::Equal, code,
14654 Imm32(unicode::LATIN_SMALL_LETTER_SHARP_S), ool->entry());
14655
14656 // Inline unicode::ToUpperCase (without the special case for ASCII characters)
14657
14658 constexpr size_t shift = unicode::CharInfoShift;
14659
14660 // code >> shift
14661 masm.rshift32(Imm32(shift), code, temp);
14662
14663 // index = index1[code >> shift];
14664 masm.movePtr(ImmPtr(unicode::index1), output);
14665 masm.load8ZeroExtend(BaseIndex(output, temp, TimesOne), temp);
14666
14667 // (code & ((1 << shift) - 1)
14668 masm.and32(Imm32((1 << shift) - 1), code, output);
14669
14670 // (index << shift) + (code & ((1 << shift) - 1))
14671 masm.lshift32(Imm32(shift), temp);
14672 masm.add32(output, temp);
14673
14674 // index = index2[(index << shift) + (code & ((1 << shift) - 1))]
14675 masm.movePtr(ImmPtr(unicode::index2), output);
14676 masm.load8ZeroExtend(BaseIndex(output, temp, TimesOne), temp);
14677
14678 // Compute |index * 6| through |(index * 3) * TimesTwo|.
14679 static_assert(sizeof(unicode::CharacterInfo) == 6);
14680 masm.mulBy3(temp, temp);
14681
14682 // upperCase = js_charinfo[index].upperCase
14683 masm.movePtr(ImmPtr(unicode::js_charinfo), output);
14684 masm.load16ZeroExtend(BaseIndex(output, temp, TimesTwo,
14685 offsetof(unicode::CharacterInfo, upperCase)),
14686 temp);
14687
14688 // uint16_t(ch) + upperCase
14689 masm.add32(code, temp);
14690
14691 // Clear any high bits added when performing the unsigned 16-bit addition
14692 // through a signed 32-bit addition.
14693 masm.move8ZeroExtend(temp, temp);
14694
14695 // Load static string for upper case character.
14696 masm.lookupStaticString(temp, output, gen->runtime->staticStrings());
14697
14698 masm.bind(ool->rejoin());
14699 }
14700
14701 void CodeGenerator::visitStringTrimStartIndex(LStringTrimStartIndex* lir) {
14702 Register string = ToRegister(lir->string());
14703 Register output = ToRegister(lir->output());
14704
14705 auto volatileRegs = liveVolatileRegs(lir);
14706 volatileRegs.takeUnchecked(output);
14707
14708 masm.PushRegsInMask(volatileRegs);
14709
14710 using Fn = int32_t (*)(const JSString*);
14711 masm.setupAlignedABICall();
14712 masm.passABIArg(string);
14713 masm.callWithABI<Fn, jit::StringTrimStartIndex>();
14714 masm.storeCallInt32Result(output);
14715
14716 masm.PopRegsInMask(volatileRegs);
14717 }
14718
14719 void CodeGenerator::visitStringTrimEndIndex(LStringTrimEndIndex* lir) {
14720 Register string = ToRegister(lir->string());
14721 Register start = ToRegister(lir->start());
14722 Register output = ToRegister(lir->output());
14723
14724 auto volatileRegs = liveVolatileRegs(lir);
14725 volatileRegs.takeUnchecked(output);
14726
14727 masm.PushRegsInMask(volatileRegs);
14728
14729 using Fn = int32_t (*)(const JSString*, int32_t);
14730 masm.setupAlignedABICall();
14731 masm.passABIArg(string);
14732 masm.passABIArg(start);
14733 masm.callWithABI<Fn, jit::StringTrimEndIndex>();
14734 masm.storeCallInt32Result(output);
14735
14736 masm.PopRegsInMask(volatileRegs);
14737 }
14738
14739 void CodeGenerator::visitStringSplit(LStringSplit* lir) {
14740 pushArg(Imm32(INT32_MAX));
14741 pushArg(ToRegister(lir->separator()));
14742 pushArg(ToRegister(lir->string()));
14743
14744 using Fn = ArrayObject* (*)(JSContext*, HandleString, HandleString, uint32_t);
14745 callVM<Fn, js::StringSplitString>(lir);
14746 }
14747
14748 void CodeGenerator::visitInitializedLength(LInitializedLength* lir) {
14749 Address initLength(ToRegister(lir->elements()),
14750 ObjectElements::offsetOfInitializedLength());
14751 masm.load32(initLength, ToRegister(lir->output()));
14752 }
14753
14754 void CodeGenerator::visitSetInitializedLength(LSetInitializedLength* lir) {
14755 Address initLength(ToRegister(lir->elements()),
14756 ObjectElements::offsetOfInitializedLength());
14757 SetLengthFromIndex(masm, lir->index(), initLength);
14758 }
14759
14760 void CodeGenerator::visitNotI(LNotI* lir) {
14761 Register input = ToRegister(lir->input());
14762 Register output = ToRegister(lir->output());
14763
14764 masm.cmp32Set(Assembler::Equal, input, Imm32(0), output);
14765 }
14766
14767 void CodeGenerator::visitNotIPtr(LNotIPtr* lir) {
14768 Register input = ToRegister(lir->input());
14769 Register output = ToRegister(lir->output());
14770
14771 masm.cmpPtrSet(Assembler::Equal, input, ImmWord(0), output);
14772 }
14773
14774 void CodeGenerator::visitNotI64(LNotI64* lir) {
14775 Register64 input = ToRegister64(lir->inputI64());
14776 Register output = ToRegister(lir->output());
14777
14778 masm.cmp64Set(Assembler::Equal, input, Imm64(0), output);
14779 }
14780
14781 void CodeGenerator::visitNotBI(LNotBI* lir) {
14782 Register input = ToRegister(lir->input());
14783 Register output = ToRegister(lir->output());
14784
14785 masm.cmp32Set(Assembler::Equal, Address(input, BigInt::offsetOfLength()),
14786 Imm32(0), output);
14787 }
14788
14789 void CodeGenerator::visitNotO(LNotO* lir) {
14790 Register objreg = ToRegister(lir->input());
14791 Register output = ToRegister(lir->output());
14792
14793 bool intact = hasSeenObjectEmulateUndefinedFuseIntactAndDependencyNoted();
14794 if (intact) {
14795 // Bug 1874905: It would be fantastic if this could be optimized out.
14796 assertObjectDoesNotEmulateUndefined(objreg, output, lir->mir());
14797 masm.move32(Imm32(0), output);
14798 } else {
14799 auto* ool = new (alloc()) OutOfLineTestObjectWithLabels();
14800 addOutOfLineCode(ool, lir->mir());
14801
14802 Label* ifEmulatesUndefined = ool->label1();
14803 Label* ifDoesntEmulateUndefined = ool->label2();
14804
14805 branchTestObjectEmulatesUndefined(objreg, ifEmulatesUndefined,
14806 ifDoesntEmulateUndefined, output, ool);
14807 // fall through
14808
14809 Label join;
14810
14811 masm.move32(Imm32(0), output);
14812 masm.jump(&join);
14813
14814 masm.bind(ifEmulatesUndefined);
14815 masm.move32(Imm32(1), output);
14816
14817 masm.bind(&join);
14818 }
14819 }
14820
14821 void CodeGenerator::visitNotV(LNotV* lir) {
14822 auto* ool = new (alloc()) OutOfLineTestObjectWithLabels();
14823 addOutOfLineCode(ool, lir->mir());
14824
14825 Label* ifTruthy = ool->label1();
14826 Label* ifFalsy = ool->label2();
14827
14828 ValueOperand input = ToValue(lir->input());
14829 Register tempToUnbox = ToTempUnboxRegister(lir->temp1());
14830 FloatRegister floatTemp = ToFloatRegister(lir->temp0());
14831 Register output = ToRegister(lir->output());
14832 const TypeDataList& observedTypes = lir->mir()->observedTypes();
14833
14834 testValueTruthy(input, tempToUnbox, output, floatTemp, observedTypes,
14835 ifTruthy, ifFalsy, ool);
14836
14837 Label join;
14838
14839 // Note that the testValueTruthy call above may choose to fall through
14840 // to ifTruthy instead of branching there.
14841 masm.bind(ifTruthy);
14842 masm.move32(Imm32(0), output);
14843 masm.jump(&join);
14844
14845 masm.bind(ifFalsy);
14846 masm.move32(Imm32(1), output);
14847
14848 // both branches meet here.
14849 masm.bind(&join);
14850 }
14851
14852 void CodeGenerator::visitBoundsCheck(LBoundsCheck* lir) {
14853 const LAllocation* index = lir->index();
14854 const LAllocation* length = lir->length();
14855 LSnapshot* snapshot = lir->snapshot();
14856
14857 MIRType type = lir->mir()->type();
14858
14859 auto bailoutCmp = [&](Assembler::Condition cond, auto lhs, auto rhs) {
14860 if (type == MIRType::Int32) {
14861 bailoutCmp32(cond, lhs, rhs, snapshot);
14862 } else {
14863 MOZ_ASSERT(type == MIRType::IntPtr);
14864 bailoutCmpPtr(cond, lhs, rhs, snapshot);
14865 }
14866 };
14867
14868 auto bailoutCmpConstant = [&](Assembler::Condition cond, auto lhs,
14869 int32_t rhs) {
14870 if (type == MIRType::Int32) {
14871 bailoutCmp32(cond, lhs, Imm32(rhs), snapshot);
14872 } else {
14873 MOZ_ASSERT(type == MIRType::IntPtr);
14874 bailoutCmpPtr(cond, lhs, ImmWord(rhs), snapshot);
14875 }
14876 };
14877
14878 if (index->isConstant()) {
14879 // Use uint32 so that the comparison is unsigned.
14880 uint32_t idx = ToInt32(index);
14881 if (length->isConstant()) {
14882 uint32_t len = ToInt32(lir->length());
14883 if (idx < len) {
14884 return;
14885 }
14886 bailout(snapshot);
14887 return;
14888 }
14889
14890 if (length->isGeneralReg()) {
14891 bailoutCmpConstant(Assembler::BelowOrEqual, ToRegister(length), idx);
14892 } else {
14893 bailoutCmpConstant(Assembler::BelowOrEqual, ToAddress(length), idx);
14894 }
14895 return;
14896 }
14897
14898 Register indexReg = ToRegister(index);
14899 if (length->isConstant()) {
14900 bailoutCmpConstant(Assembler::AboveOrEqual, indexReg, ToInt32(length));
14901 } else if (length->isGeneralReg()) {
14902 bailoutCmp(Assembler::BelowOrEqual, ToRegister(length), indexReg);
14903 } else {
14904 bailoutCmp(Assembler::BelowOrEqual, ToAddress(length), indexReg);
14905 }
14906 }
14907
14908 void CodeGenerator::visitBoundsCheckRange(LBoundsCheckRange* lir) {
14909 int32_t min = lir->mir()->minimum();
14910 int32_t max = lir->mir()->maximum();
14911 MOZ_ASSERT(max >= min);
14912
14913 LSnapshot* snapshot = lir->snapshot();
14914 MIRType type = lir->mir()->type();
14915
14916 const LAllocation* length = lir->length();
14917 Register temp = ToRegister(lir->temp0());
14918
14919 auto bailoutCmp = [&](Assembler::Condition cond, auto lhs, auto rhs) {
14920 if (type == MIRType::Int32) {
14921 bailoutCmp32(cond, lhs, rhs, snapshot);
14922 } else {
14923 MOZ_ASSERT(type == MIRType::IntPtr);
14924 bailoutCmpPtr(cond, lhs, rhs, snapshot);
14925 }
14926 };
14927
14928 auto bailoutCmpConstant = [&](Assembler::Condition cond, auto lhs,
14929 int32_t rhs) {
14930 if (type == MIRType::Int32) {
14931 bailoutCmp32(cond, lhs, Imm32(rhs), snapshot);
14932 } else {
14933 MOZ_ASSERT(type == MIRType::IntPtr);
14934 bailoutCmpPtr(cond, lhs, ImmWord(rhs), snapshot);
14935 }
14936 };
14937
14938 if (lir->index()->isConstant()) {
14939 int32_t nmin, nmax;
14940 int32_t index = ToInt32(lir->index());
14941 if (SafeAdd(index, min, &nmin) && SafeAdd(index, max, &nmax) && nmin >= 0) {
14942 if (length->isGeneralReg()) {
14943 bailoutCmpConstant(Assembler::BelowOrEqual, ToRegister(length), nmax);
14944 } else {
14945 bailoutCmpConstant(Assembler::BelowOrEqual, ToAddress(length), nmax);
14946 }
14947 return;
14948 }
14949 masm.mov(ImmWord(index), temp);
14950 } else {
14951 masm.mov(ToRegister(lir->index()), temp);
14952 }
14953
14954 // If the minimum and maximum differ then do an underflow check first.
14955 // If the two are the same then doing an unsigned comparison on the
14956 // length will also catch a negative index.
14957 if (min != max) {
14958 if (min != 0) {
14959 Label bail;
14960 if (type == MIRType::Int32) {
14961 masm.branchAdd32(Assembler::Overflow, Imm32(min), temp, &bail);
14962 } else {
14963 masm.branchAddPtr(Assembler::Overflow, Imm32(min), temp, &bail);
14964 }
14965 bailoutFrom(&bail, snapshot);
14966 }
14967
14968 bailoutCmpConstant(Assembler::LessThan, temp, 0);
14969
14970 if (min != 0) {
14971 int32_t diff;
14972 if (SafeSub(max, min, &diff)) {
14973 max = diff;
14974 } else {
14975 if (type == MIRType::Int32) {
14976 masm.sub32(Imm32(min), temp);
14977 } else {
14978 masm.subPtr(Imm32(min), temp);
14979 }
14980 }
14981 }
14982 }
14983
14984 // Compute the maximum possible index. No overflow check is needed when
14985 // max > 0. We can only wraparound to a negative number, which will test as
14986 // larger than all nonnegative numbers in the unsigned comparison, and the
14987 // length is required to be nonnegative (else testing a negative length
14988 // would succeed on any nonnegative index).
14989 if (max != 0) {
14990 if (max < 0) {
14991 Label bail;
14992 if (type == MIRType::Int32) {
14993 masm.branchAdd32(Assembler::Overflow, Imm32(max), temp, &bail);
14994 } else {
14995 masm.branchAddPtr(Assembler::Overflow, Imm32(max), temp, &bail);
14996 }
14997 bailoutFrom(&bail, snapshot);
14998 } else {
14999 if (type == MIRType::Int32) {
15000 masm.add32(Imm32(max), temp);
15001 } else {
15002 masm.addPtr(Imm32(max), temp);
15003 }
15004 }
15005 }
15006
15007 if (length->isGeneralReg()) {
15008 bailoutCmp(Assembler::BelowOrEqual, ToRegister(length), temp);
15009 } else {
15010 bailoutCmp(Assembler::BelowOrEqual, ToAddress(length), temp);
15011 }
15012 }
15013
15014 void CodeGenerator::visitBoundsCheckLower(LBoundsCheckLower* lir) {
15015 int32_t min = lir->mir()->minimum();
15016 bailoutCmp32(Assembler::LessThan, ToRegister(lir->index()), Imm32(min),
15017 lir->snapshot());
15018 }
15019
15020 void CodeGenerator::visitSpectreMaskIndex(LSpectreMaskIndex* lir) {
15021 MOZ_ASSERT(JitOptions.spectreIndexMasking);
15022
15023 const LAllocation* length = lir->length();
15024 Register index = ToRegister(lir->index());
15025 Register output = ToRegister(lir->output());
15026
15027 if (lir->mir()->type() == MIRType::Int32) {
15028 if (length->isGeneralReg()) {
15029 masm.spectreMaskIndex32(index, ToRegister(length), output);
15030 } else {
15031 masm.spectreMaskIndex32(index, ToAddress(length), output);
15032 }
15033 } else {
15034 MOZ_ASSERT(lir->mir()->type() == MIRType::IntPtr);
15035 if (length->isGeneralReg()) {
15036 masm.spectreMaskIndexPtr(index, ToRegister(length), output);
15037 } else {
15038 masm.spectreMaskIndexPtr(index, ToAddress(length), output);
15039 }
15040 }
15041 }
15042
15043 void CodeGenerator::emitStoreHoleCheck(Register elements,
15044 const LAllocation* index,
15045 LSnapshot* snapshot) {
15046 Label bail;
15047 if (index->isConstant()) {
15048 Address dest(elements, ToInt32(index) * sizeof(js::Value));
15049 masm.branchTestMagic(Assembler::Equal, dest, &bail);
15050 } else {
15051 BaseObjectElementIndex dest(elements, ToRegister(index));
15052 masm.branchTestMagic(Assembler::Equal, dest, &bail);
15053 }
15054 bailoutFrom(&bail, snapshot);
15055 }
15056
15057 void CodeGenerator::emitStoreElementTyped(const LAllocation* value,
15058 MIRType valueType, Register elements,
15059 const LAllocation* index) {
15060 MOZ_ASSERT(valueType != MIRType::MagicHole);
15061 ConstantOrRegister v = ToConstantOrRegister(value, valueType);
15062 if (index->isConstant()) {
15063 Address dest(elements, ToInt32(index) * sizeof(js::Value));
15064 masm.storeUnboxedValue(v, valueType, dest);
15065 } else {
15066 BaseObjectElementIndex dest(elements, ToRegister(index));
15067 masm.storeUnboxedValue(v, valueType, dest);
15068 }
15069 }
15070
15071 void CodeGenerator::visitStoreElementT(LStoreElementT* store) {
15072 Register elements = ToRegister(store->elements());
15073 const LAllocation* index = store->index();
15074
15075 if (store->mir()->needsBarrier()) {
15076 emitPreBarrier(elements, index);
15077 }
15078
15079 if (store->mir()->needsHoleCheck()) {
15080 emitStoreHoleCheck(elements, index, store->snapshot());
15081 }
15082
15083 emitStoreElementTyped(store->value(), store->mir()->value()->type(), elements,
15084 index);
15085 }
15086
15087 void CodeGenerator::visitStoreElementV(LStoreElementV* lir) {
15088 ValueOperand value = ToValue(lir->value());
15089 Register elements = ToRegister(lir->elements());
15090 const LAllocation* index = lir->index();
15091
15092 if (lir->mir()->needsBarrier()) {
15093 emitPreBarrier(elements, index);
15094 }
15095
15096 if (lir->mir()->needsHoleCheck()) {
15097 emitStoreHoleCheck(elements, index, lir->snapshot());
15098 }
15099
15100 if (lir->index()->isConstant()) {
15101 Address dest(elements, ToInt32(lir->index()) * sizeof(js::Value));
15102 masm.storeValue(value, dest);
15103 } else {
15104 BaseObjectElementIndex dest(elements, ToRegister(lir->index()));
15105 masm.storeValue(value, dest);
15106 }
15107 }
15108
15109 void CodeGenerator::visitStoreHoleValueElement(LStoreHoleValueElement* lir) {
15110 Register elements = ToRegister(lir->elements());
15111 Register index = ToRegister(lir->index());
15112
15113 Address elementsFlags(elements, ObjectElements::offsetOfFlags());
15114 masm.or32(Imm32(ObjectElements::NON_PACKED), elementsFlags);
15115
15116 BaseObjectElementIndex element(elements, index);
15117 masm.storeValue(MagicValue(JS_ELEMENTS_HOLE), element);
15118 }
15119
15120 void CodeGenerator::visitStoreElementHoleT(LStoreElementHoleT* lir) {
15121 Register obj = ToRegister(lir->object());
15122 Register elements = ToRegister(lir->elements());
15123 Register index = ToRegister(lir->index());
15124 Register temp = ToRegister(lir->temp0());
15125
15126 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
15127 Label bail;
15128 masm.prepareOOBStoreElement(obj, index, elements, temp, &bail,
15129 liveVolatileRegs(lir));
15130 bailoutFrom(&bail, lir->snapshot());
15131
15132 // Jump to the inline path where we will store the value.
15133 // We rejoin after the prebarrier, because the memory is uninitialized.
15134 masm.jump(ool.rejoin());
15135 });
15136 addOutOfLineCode(ool, lir->mir());
15137
15138 Address initLength(elements, ObjectElements::offsetOfInitializedLength());
15139 masm.spectreBoundsCheck32(index, initLength, temp, ool->entry());
15140
15141 emitPreBarrier(elements, lir->index());
15142
15143 masm.bind(ool->rejoin());
15144 emitStoreElementTyped(lir->value(), lir->mir()->value()->type(), elements,
15145 lir->index());
15146
15147 if (ValueNeedsPostBarrier(lir->mir()->value())) {
15148 LiveRegisterSet regs = liveVolatileRegs(lir);
15149 ConstantOrRegister val =
15150 ToConstantOrRegister(lir->value(), lir->mir()->value()->type());
15151 emitElementPostWriteBarrier(lir->mir(), regs, obj, lir->index(), temp, val);
15152 }
15153 }
15154
15155 void CodeGenerator::visitStoreElementHoleV(LStoreElementHoleV* lir) {
15156 Register obj = ToRegister(lir->object());
15157 Register elements = ToRegister(lir->elements());
15158 Register index = ToRegister(lir->index());
15159 ValueOperand value = ToValue(lir->value());
15160 Register temp = ToRegister(lir->temp0());
15161
15162 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
15163 Label bail;
15164 masm.prepareOOBStoreElement(obj, index, elements, temp, &bail,
15165 liveVolatileRegs(lir));
15166 bailoutFrom(&bail, lir->snapshot());
15167
15168 // Jump to the inline path where we will store the value.
15169 // We rejoin after the prebarrier, because the memory is uninitialized.
15170 masm.jump(ool.rejoin());
15171 });
15172 addOutOfLineCode(ool, lir->mir());
15173
15174 Address initLength(elements, ObjectElements::offsetOfInitializedLength());
15175 masm.spectreBoundsCheck32(index, initLength, temp, ool->entry());
15176
15177 emitPreBarrier(elements, lir->index());
15178
15179 masm.bind(ool->rejoin());
15180 masm.storeValue(value, BaseObjectElementIndex(elements, index));
15181
15182 if (ValueNeedsPostBarrier(lir->mir()->value())) {
15183 LiveRegisterSet regs = liveVolatileRegs(lir);
15184 emitElementPostWriteBarrier(lir->mir(), regs, obj, lir->index(), temp,
15185 ConstantOrRegister(value));
15186 }
15187 }
15188
15189 void CodeGenerator::visitArrayPopShift(LArrayPopShift* lir) {
15190 Register obj = ToRegister(lir->object());
15191 Register temp1 = ToRegister(lir->temp0());
15192 Register temp2 = ToRegister(lir->temp1());
15193 ValueOperand out = ToOutValue(lir);
15194
15195 Label bail;
15196 if (lir->mir()->mode() == MArrayPopShift::Pop) {
15197 masm.packedArrayPop(obj, out, temp1, temp2, &bail);
15198 } else {
15199 MOZ_ASSERT(lir->mir()->mode() == MArrayPopShift::Shift);
15200 LiveRegisterSet volatileRegs = liveVolatileRegs(lir);
15201 masm.packedArrayShift(obj, out, temp1, temp2, volatileRegs, &bail);
15202 }
15203 bailoutFrom(&bail, lir->snapshot());
15204 }
15205
15206 void CodeGenerator::visitArrayPush(LArrayPush* lir) {
15207 Register obj = ToRegister(lir->object());
15208 Register elementsTemp = ToRegister(lir->temp0());
15209 Register length = ToRegister(lir->output());
15210 ValueOperand value = ToValue(lir->value());
15211 Register spectreTemp = ToTempRegisterOrInvalid(lir->temp1());
15212
15213 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
15214 Register temp = ToRegister(lir->temp0());
15215
15216 LiveRegisterSet liveRegs = liveVolatileRegs(lir);
15217 liveRegs.takeUnchecked(temp);
15218 liveRegs.addUnchecked(ToRegister(lir->output()));
15219 liveRegs.addUnchecked(ToValue(lir->value()));
15220
15221 masm.PushRegsInMask(liveRegs);
15222
15223 masm.setupAlignedABICall();
15224 masm.loadJSContext(temp);
15225 masm.passABIArg(temp);
15226 masm.passABIArg(obj);
15227
15228 using Fn = bool (*)(JSContext*, NativeObject* obj);
15229 masm.callWithABI<Fn, NativeObject::addDenseElementPure>();
15230 masm.storeCallPointerResult(temp);
15231
15232 masm.PopRegsInMask(liveRegs);
15233 bailoutIfFalseBool(temp, lir->snapshot());
15234
15235 // Load the reallocated elements pointer.
15236 masm.loadPtr(Address(obj, NativeObject::offsetOfElements()), temp);
15237
15238 masm.jump(ool.rejoin());
15239 });
15240 addOutOfLineCode(ool, lir->mir());
15241
15242 // Load obj->elements in elementsTemp.
15243 masm.loadPtr(Address(obj, NativeObject::offsetOfElements()), elementsTemp);
15244
15245 Address initLengthAddr(elementsTemp,
15246 ObjectElements::offsetOfInitializedLength());
15247 Address lengthAddr(elementsTemp, ObjectElements::offsetOfLength());
15248 Address capacityAddr(elementsTemp, ObjectElements::offsetOfCapacity());
15249
15250 // Bail out if length != initLength.
15251 masm.load32(lengthAddr, length);
15252 bailoutCmp32(Assembler::NotEqual, initLengthAddr, length, lir->snapshot());
15253
15254 // If length < capacity, we can add a dense element inline. If not, we
15255 // need to allocate more elements.
15256 masm.spectreBoundsCheck32(length, capacityAddr, spectreTemp, ool->entry());
15257 masm.bind(ool->rejoin());
15258
15259 // Store the value.
15260 masm.storeValue(value, BaseObjectElementIndex(elementsTemp, length));
15261
15262 // Update length and initialized length.
15263 masm.add32(Imm32(1), length);
15264 masm.store32(length, Address(elementsTemp, ObjectElements::offsetOfLength()));
15265 masm.store32(length, Address(elementsTemp,
15266 ObjectElements::offsetOfInitializedLength()));
15267
15268 if (ValueNeedsPostBarrier(lir->mir()->value())) {
15269 LiveRegisterSet regs = liveVolatileRegs(lir);
15270 regs.addUnchecked(length);
15271 emitElementPostWriteBarrier(lir->mir(), regs, obj, lir->output()->output(),
15272 elementsTemp, ConstantOrRegister(value),
15273 /* indexDiff = */ -1);
15274 }
15275 }
15276
15277 void CodeGenerator::visitArraySlice(LArraySlice* lir) {
15278 Register object = ToRegister(lir->object());
15279 Register begin = ToRegister(lir->begin());
15280 Register end = ToRegister(lir->end());
15281 Register temp0 = ToRegister(lir->temp0());
15282 Register temp1 = ToRegister(lir->temp1());
15283
15284 Label call, fail;
15285
15286 Label bail;
15287 masm.branchArrayIsNotPacked(object, temp0, temp1, &bail);
15288 bailoutFrom(&bail, lir->snapshot());
15289
15290 // Try to allocate an object.
15291 TemplateObject templateObject(lir->mir()->templateObj());
15292 masm.createGCObject(temp0, temp1, templateObject, lir->mir()->initialHeap(),
15293 &fail);
15294
15295 masm.jump(&call);
15296 {
15297 masm.bind(&fail);
15298 masm.movePtr(ImmPtr(nullptr), temp0);
15299 }
15300 masm.bind(&call);
15301
15302 pushArg(temp0);
15303 pushArg(end);
15304 pushArg(begin);
15305 pushArg(object);
15306
15307 using Fn =
15308 JSObject* (*)(JSContext*, HandleObject, int32_t, int32_t, HandleObject);
15309 callVM<Fn, ArraySliceDense>(lir);
15310 }
15311
15312 void CodeGenerator::visitArgumentsSlice(LArgumentsSlice* lir) {
15313 Register object = ToRegister(lir->object());
15314 Register begin = ToRegister(lir->begin());
15315 Register end = ToRegister(lir->end());
15316 Register temp0 = ToRegister(lir->temp0());
15317 Register temp1 = ToRegister(lir->temp1());
15318
15319 Label call, fail;
15320
15321 // Try to allocate an object.
15322 TemplateObject templateObject(lir->mir()->templateObj());
15323 masm.createGCObject(temp0, temp1, templateObject, lir->mir()->initialHeap(),
15324 &fail);
15325
15326 masm.jump(&call);
15327 {
15328 masm.bind(&fail);
15329 masm.movePtr(ImmPtr(nullptr), temp0);
15330 }
15331 masm.bind(&call);
15332
15333 pushArg(temp0);
15334 pushArg(end);
15335 pushArg(begin);
15336 pushArg(object);
15337
15338 using Fn =
15339 JSObject* (*)(JSContext*, HandleObject, int32_t, int32_t, HandleObject);
15340 callVM<Fn, ArgumentsSliceDense>(lir);
15341 }
15342
15343 #ifdef DEBUG
15344 void CodeGenerator::emitAssertArgumentsSliceBounds(const RegisterOrInt32& begin,
15345 const RegisterOrInt32& count,
15346 Register numActualArgs) {
15347 // |begin| must be positive or zero.
15348 if (begin.is<Register>()) {
15349 Label beginOk;
15350 masm.branch32(Assembler::GreaterThanOrEqual, begin.as<Register>(), Imm32(0),
15351 &beginOk);
15352 masm.assumeUnreachable("begin < 0");
15353 masm.bind(&beginOk);
15354 } else {
15355 MOZ_ASSERT(begin.as<int32_t>() >= 0);
15356 }
15357
15358 // |count| must be positive or zero.
15359 if (count.is<Register>()) {
15360 Label countOk;
15361 masm.branch32(Assembler::GreaterThanOrEqual, count.as<Register>(), Imm32(0),
15362 &countOk);
15363 masm.assumeUnreachable("count < 0");
15364 masm.bind(&countOk);
15365 } else {
15366 MOZ_ASSERT(count.as<int32_t>() >= 0);
15367 }
15368
15369 // |begin| must be less-or-equal to |numActualArgs|.
15370 Label argsBeginOk;
15371 if (begin.is<Register>()) {
15372 masm.branchPtr(Assembler::AboveOrEqual, numActualArgs, begin.as<Register>(),
15373 &argsBeginOk);
15374 } else {
15375 masm.branchPtr(Assembler::AboveOrEqual, numActualArgs,
15376 Imm32(begin.as<int32_t>()), &argsBeginOk);
15377 }
15378 masm.assumeUnreachable("begin <= numActualArgs");
15379 masm.bind(&argsBeginOk);
15380
15381 // |count| must be less-or-equal to |numActualArgs|.
15382 Label argsCountOk;
15383 if (count.is<Register>()) {
15384 masm.branchPtr(Assembler::AboveOrEqual, numActualArgs, count.as<Register>(),
15385 &argsCountOk);
15386 } else {
15387 masm.branchPtr(Assembler::AboveOrEqual, numActualArgs,
15388 Imm32(count.as<int32_t>()), &argsCountOk);
15389 }
15390 masm.assumeUnreachable("count <= numActualArgs");
15391 masm.bind(&argsCountOk);
15392
15393 // |begin| and |count| must be preserved, but |numActualArgs| can be changed.
15394 //
15395 // Pre-condition: |count| <= |numActualArgs|
15396 // Condition to test: |begin + count| <= |numActualArgs|
15397 // Transform to: |begin| <= |numActualArgs - count|
15398 if (count.is<Register>()) {
15399 masm.subPtr(count.as<Register>(), numActualArgs);
15400 } else {
15401 masm.subPtr(Imm32(count.as<int32_t>()), numActualArgs);
15402 }
15403
15404 // |begin + count| must be less-or-equal to |numActualArgs|.
15405 Label argsBeginCountOk;
15406 if (begin.is<Register>()) {
15407 masm.branchPtr(Assembler::AboveOrEqual, numActualArgs, begin.as<Register>(),
15408 &argsBeginCountOk);
15409 } else {
15410 masm.branchPtr(Assembler::AboveOrEqual, numActualArgs,
15411 Imm32(begin.as<int32_t>()), &argsBeginCountOk);
15412 }
15413 masm.assumeUnreachable("begin + count <= numActualArgs");
15414 masm.bind(&argsBeginCountOk);
15415 }
15416 #endif
15417
15418 template <class ArgumentsSlice>
15419 void CodeGenerator::emitNewArray(ArgumentsSlice* lir,
15420 const RegisterOrInt32& count, Register output,
15421 Register temp) {
15422 using Fn = ArrayObject* (*)(JSContext*, int32_t);
15423 auto* ool = count.match(
15424 [&](Register count) {
15425 return oolCallVM<Fn, NewArrayObjectEnsureDenseInitLength>(
15426 lir, ArgList(count), StoreRegisterTo(output));
15427 },
15428 [&](int32_t count) {
15429 return oolCallVM<Fn, NewArrayObjectEnsureDenseInitLength>(
15430 lir, ArgList(Imm32(count)), StoreRegisterTo(output));
15431 });
15432
15433 TemplateObject templateObject(lir->mir()->templateObj());
15434 MOZ_ASSERT(templateObject.isArrayObject());
15435
15436 auto templateNativeObj = templateObject.asTemplateNativeObject();
15437 MOZ_ASSERT(templateNativeObj.getArrayLength() == 0);
15438 MOZ_ASSERT(templateNativeObj.getDenseInitializedLength() == 0);
15439 MOZ_ASSERT(!templateNativeObj.hasDynamicElements());
15440
15441 // Check array capacity. Call into the VM if the template object's capacity
15442 // is too small.
15443 bool tryAllocate = count.match(
15444 [&](Register count) {
15445 masm.branch32(Assembler::Above, count,
15446 Imm32(templateNativeObj.getDenseCapacity()),
15447 ool->entry());
15448 return true;
15449 },
15450 [&](int32_t count) {
15451 MOZ_ASSERT(count >= 0);
15452 if (uint32_t(count) > templateNativeObj.getDenseCapacity()) {
15453 masm.jump(ool->entry());
15454 return false;
15455 }
15456 return true;
15457 });
15458
15459 if (tryAllocate) {
15460 // Try to allocate an object.
15461 masm.createGCObject(output, temp, templateObject, lir->mir()->initialHeap(),
15462 ool->entry());
15463
15464 auto setInitializedLengthAndLength = [&](auto count) {
15465 const int elementsOffset = NativeObject::offsetOfFixedElements();
15466
15467 // Update initialized length.
15468 Address initLength(
15469 output, elementsOffset + ObjectElements::offsetOfInitializedLength());
15470 masm.store32(count, initLength);
15471
15472 // Update length.
15473 Address length(output, elementsOffset + ObjectElements::offsetOfLength());
15474 masm.store32(count, length);
15475 };
15476
15477 // The array object was successfully created. Set the length and initialized
15478 // length and then proceed to fill the elements.
15479 count.match([&](Register count) { setInitializedLengthAndLength(count); },
15480 [&](int32_t count) {
15481 if (count > 0) {
15482 setInitializedLengthAndLength(Imm32(count));
15483 }
15484 });
15485 }
15486
15487 masm.bind(ool->rejoin());
15488 }
15489
15490 void CodeGenerator::visitFrameArgumentsSlice(LFrameArgumentsSlice* lir) {
15491 Register begin = ToRegister(lir->begin());
15492 Register count = ToRegister(lir->count());
15493 Register temp = ToRegister(lir->temp0());
15494 Register output = ToRegister(lir->output());
15495
15496 #ifdef DEBUG
15497 masm.loadNumActualArgs(FramePointer, temp);
15498 emitAssertArgumentsSliceBounds(RegisterOrInt32(begin), RegisterOrInt32(count),
15499 temp);
15500 #endif
15501
15502 emitNewArray(lir, RegisterOrInt32(count), output, temp);
15503
15504 Label done;
15505 masm.branch32(Assembler::Equal, count, Imm32(0), &done);
15506 {
15507 AllocatableGeneralRegisterSet allRegs(GeneralRegisterSet::All());
15508 allRegs.take(begin);
15509 allRegs.take(count);
15510 allRegs.take(temp);
15511 allRegs.take(output);
15512
15513 ValueOperand value = allRegs.takeAnyValue();
15514
15515 LiveRegisterSet liveRegs;
15516 liveRegs.add(output);
15517 liveRegs.add(begin);
15518 liveRegs.add(value);
15519
15520 masm.PushRegsInMask(liveRegs);
15521
15522 // Initialize all elements.
15523
15524 Register elements = output;
15525 masm.loadPtr(Address(output, NativeObject::offsetOfElements()), elements);
15526
15527 Register argIndex = begin;
15528
15529 Register index = temp;
15530 masm.move32(Imm32(0), index);
15531
15532 size_t argvOffset = JitFrameLayout::offsetOfActualArgs();
15533 BaseValueIndex argPtr(FramePointer, argIndex, argvOffset);
15534
15535 Label loop;
15536 masm.bind(&loop);
15537
15538 masm.loadValue(argPtr, value);
15539
15540 // We don't need a pre-barrier, because the element at |index| is guaranteed
15541 // to be a non-GC thing (either uninitialized memory or the magic hole
15542 // value).
15543 masm.storeValue(value, BaseObjectElementIndex(elements, index));
15544
15545 masm.add32(Imm32(1), index);
15546 masm.add32(Imm32(1), argIndex);
15547
15548 masm.branch32(Assembler::LessThan, index, count, &loop);
15549
15550 masm.PopRegsInMask(liveRegs);
15551
15552 // Emit a post-write barrier if |output| is tenured.
15553 //
15554 // We expect that |output| is nursery allocated, so it isn't worth the
15555 // trouble to check if no frame argument is a nursery thing, which would
15556 // allow to omit the post-write barrier.
15557 masm.branchPtrInNurseryChunk(Assembler::Equal, output, temp, &done);
15558
15559 LiveRegisterSet volatileRegs = liveVolatileRegs(lir);
15560 volatileRegs.takeUnchecked(temp);
15561 if (output.volatile_()) {
15562 volatileRegs.addUnchecked(output);
15563 }
15564
15565 masm.PushRegsInMask(volatileRegs);
15566 emitPostWriteBarrier(output);
15567 masm.PopRegsInMask(volatileRegs);
15568 }
15569 masm.bind(&done);
15570 }
15571
15572 CodeGenerator::RegisterOrInt32 CodeGenerator::ToRegisterOrInt32(
15573 const LAllocation* allocation) {
15574 if (allocation->isConstant()) {
15575 return RegisterOrInt32(allocation->toConstant()->toInt32());
15576 }
15577 return RegisterOrInt32(ToRegister(allocation));
15578 }
15579
15580 void CodeGenerator::visitInlineArgumentsSlice(LInlineArgumentsSlice* lir) {
15581 RegisterOrInt32 begin = ToRegisterOrInt32(lir->begin());
15582 RegisterOrInt32 count = ToRegisterOrInt32(lir->count());
15583 Register temp = ToRegister(lir->temp());
15584 Register output = ToRegister(lir->output());
15585
15586 uint32_t numActuals = lir->mir()->numActuals();
15587
15588 #ifdef DEBUG
15589 masm.move32(Imm32(numActuals), temp);
15590
15591 emitAssertArgumentsSliceBounds(begin, count, temp);
15592 #endif
15593
15594 emitNewArray(lir, count, output, temp);
15595
15596 // We're done if there are no actual arguments.
15597 if (numActuals == 0) {
15598 return;
15599 }
15600
15601 // Check if any arguments have to be copied.
15602 Label done;
15603 if (count.is<Register>()) {
15604 masm.branch32(Assembler::Equal, count.as<Register>(), Imm32(0), &done);
15605 } else if (count.as<int32_t>() == 0) {
15606 return;
15607 }
15608
15609 auto getArg = [&](uint32_t i) {
15610 return toConstantOrRegister(lir, LInlineArgumentsSlice::ArgIndex(i),
15611 lir->mir()->getArg(i)->type());
15612 };
15613
15614 auto storeArg = [&](uint32_t i, auto dest) {
15615 // We don't need a pre-barrier because the element at |index| is guaranteed
15616 // to be a non-GC thing (either uninitialized memory or the magic hole
15617 // value).
15618 masm.storeConstantOrRegister(getArg(i), dest);
15619 };
15620
15621 // Initialize all elements.
15622 if (numActuals == 1) {
15623 // There's exactly one argument. We've checked that |count| is non-zero,
15624 // which implies that |begin| must be zero.
15625 MOZ_ASSERT_IF(begin.is<int32_t>(), begin.as<int32_t>() == 0);
15626
15627 Register elements = temp;
15628 masm.loadPtr(Address(output, NativeObject::offsetOfElements()), elements);
15629
15630 storeArg(0, Address(elements, 0));
15631 } else if (begin.is<Register>()) {
15632 // There is more than one argument and |begin| isn't a compile-time
15633 // constant. Iterate through 0..numActuals to search for |begin| and then
15634 // start copying |count| arguments from that index.
15635
15636 LiveGeneralRegisterSet liveRegs;
15637 liveRegs.add(output);
15638 liveRegs.add(begin.as<Register>());
15639
15640 masm.PushRegsInMask(liveRegs);
15641
15642 Register elements = output;
15643 masm.loadPtr(Address(output, NativeObject::offsetOfElements()), elements);
15644
15645 Register argIndex = begin.as<Register>();
15646
15647 Register index = temp;
15648 masm.move32(Imm32(0), index);
15649
15650 Label doneLoop;
15651 for (uint32_t i = 0; i < numActuals; ++i) {
15652 Label next;
15653 masm.branch32(Assembler::NotEqual, argIndex, Imm32(i), &next);
15654
15655 storeArg(i, BaseObjectElementIndex(elements, index));
15656
15657 masm.add32(Imm32(1), index);
15658 masm.add32(Imm32(1), argIndex);
15659
15660 if (count.is<Register>()) {
15661 masm.branch32(Assembler::GreaterThanOrEqual, index,
15662 count.as<Register>(), &doneLoop);
15663 } else {
15664 masm.branch32(Assembler::GreaterThanOrEqual, index,
15665 Imm32(count.as<int32_t>()), &doneLoop);
15666 }
15667
15668 masm.bind(&next);
15669 }
15670 masm.bind(&doneLoop);
15671
15672 masm.PopRegsInMask(liveRegs);
15673 } else {
15674 // There is more than one argument and |begin| is a compile-time constant.
15675
15676 Register elements = temp;
15677 masm.loadPtr(Address(output, NativeObject::offsetOfElements()), elements);
15678
15679 int32_t argIndex = begin.as<int32_t>();
15680
15681 int32_t index = 0;
15682
15683 Label doneLoop;
15684 for (uint32_t i = argIndex; i < numActuals; ++i) {
15685 storeArg(i, Address(elements, index * sizeof(Value)));
15686
15687 index += 1;
15688
15689 if (count.is<Register>()) {
15690 masm.branch32(Assembler::LessThanOrEqual, count.as<Register>(),
15691 Imm32(index), &doneLoop);
15692 } else {
15693 if (index >= count.as<int32_t>()) {
15694 break;
15695 }
15696 }
15697 }
15698 masm.bind(&doneLoop);
15699 }
15700
15701 // Determine if we have to emit post-write barrier.
15702 //
15703 // If either |begin| or |count| is a constant, use their value directly.
15704 // Otherwise assume we copy all inline arguments from 0..numActuals.
15705 bool postWriteBarrier = false;
15706 uint32_t actualBegin = begin.match([](Register) { return 0; },
15707 [](int32_t value) { return value; });
15708 uint32_t actualCount =
15709 count.match([=](Register) { return numActuals; },
15710 [](int32_t value) -> uint32_t { return value; });
15711 for (uint32_t i = 0; i < actualCount; ++i) {
15712 ConstantOrRegister arg = getArg(actualBegin + i);
15713 if (arg.constant()) {
15714 Value v = arg.value();
15715 if (v.isGCThing() && IsInsideNursery(v.toGCThing())) {
15716 postWriteBarrier = true;
15717 }
15718 } else {
15719 MIRType type = arg.reg().type();
15720 if (type == MIRType::Value || NeedsPostBarrier(type)) {
15721 postWriteBarrier = true;
15722 }
15723 }
15724 }
15725
15726 // Emit a post-write barrier if |output| is tenured and we couldn't
15727 // determine at compile-time that no barrier is needed.
15728 if (postWriteBarrier) {
15729 masm.branchPtrInNurseryChunk(Assembler::Equal, output, temp, &done);
15730
15731 LiveRegisterSet volatileRegs = liveVolatileRegs(lir);
15732 volatileRegs.takeUnchecked(temp);
15733 if (output.volatile_()) {
15734 volatileRegs.addUnchecked(output);
15735 }
15736
15737 masm.PushRegsInMask(volatileRegs);
15738 emitPostWriteBarrier(output);
15739 masm.PopRegsInMask(volatileRegs);
15740 }
15741
15742 masm.bind(&done);
15743 }
15744
15745 void CodeGenerator::visitNormalizeSliceTerm(LNormalizeSliceTerm* lir) {
15746 Register value = ToRegister(lir->value());
15747 Register length = ToRegister(lir->length());
15748 Register output = ToRegister(lir->output());
15749
15750 masm.move32(value, output);
15751
15752 Label positive;
15753 masm.branch32(Assembler::GreaterThanOrEqual, value, Imm32(0), &positive);
15754
15755 Label done;
15756 masm.add32(length, output);
15757 masm.branch32(Assembler::GreaterThanOrEqual, output, Imm32(0), &done);
15758 masm.move32(Imm32(0), output);
15759 masm.jump(&done);
15760
15761 masm.bind(&positive);
15762 masm.cmp32Move32(Assembler::LessThan, length, value, length, output);
15763
15764 masm.bind(&done);
15765 }
15766
15767 void CodeGenerator::visitArrayJoin(LArrayJoin* lir) {
15768 Label skipCall;
15769
15770 Register output = ToRegister(lir->output());
15771 Register sep = ToRegister(lir->separator());
15772 Register array = ToRegister(lir->array());
15773 Register temp = ToRegister(lir->temp0());
15774
15775 // Fast path for simple length <= 1 cases.
15776 {
15777 masm.loadPtr(Address(array, NativeObject::offsetOfElements()), temp);
15778 Address length(temp, ObjectElements::offsetOfLength());
15779 Address initLength(temp, ObjectElements::offsetOfInitializedLength());
15780
15781 // Check for length == 0
15782 Label notEmpty;
15783 masm.branch32(Assembler::NotEqual, length, Imm32(0), &notEmpty);
15784 const JSAtomState& names = gen->runtime->names();
15785 masm.movePtr(ImmGCPtr(names.empty_), output);
15786 masm.jump(&skipCall);
15787
15788 masm.bind(&notEmpty);
15789 Label notSingleString;
15790 // Check for length == 1, initializedLength >= 1, arr[0].isString()
15791 masm.branch32(Assembler::NotEqual, length, Imm32(1), &notSingleString);
15792 masm.branch32(Assembler::LessThan, initLength, Imm32(1), &notSingleString);
15793
15794 Address elem0(temp, 0);
15795 masm.branchTestString(Assembler::NotEqual, elem0, &notSingleString);
15796
15797 // At this point, 'output' can be used as a scratch register, since we're
15798 // guaranteed to succeed.
15799 masm.unboxString(elem0, output);
15800 masm.jump(&skipCall);
15801 masm.bind(&notSingleString);
15802 }
15803
15804 pushArg(sep);
15805 pushArg(array);
15806
15807 using Fn = JSString* (*)(JSContext*, HandleObject, HandleString);
15808 callVM<Fn, jit::ArrayJoin>(lir);
15809 masm.bind(&skipCall);
15810 }
15811
15812 void CodeGenerator::visitObjectKeys(LObjectKeys* lir) {
15813 Register object = ToRegister(lir->object());
15814
15815 pushArg(object);
15816
15817 using Fn = JSObject* (*)(JSContext*, HandleObject);
15818 callVM<Fn, jit::ObjectKeys>(lir);
15819 }
15820
15821 void CodeGenerator::visitObjectKeysLength(LObjectKeysLength* lir) {
15822 Register object = ToRegister(lir->object());
15823
15824 pushArg(object);
15825
15826 using Fn = bool (*)(JSContext*, HandleObject, int32_t*);
15827 callVM<Fn, jit::ObjectKeysLength>(lir);
15828 }
15829
15830 void CodeGenerator::visitGetIteratorCache(LGetIteratorCache* lir) {
15831 LiveRegisterSet liveRegs = lir->safepoint()->liveRegs();
15832 TypedOrValueRegister val =
15833 toConstantOrRegister(lir, LGetIteratorCache::ValueIndex,
15834 lir->mir()->value()->type())
15835 .reg();
15836 Register output = ToRegister(lir->output());
15837 Register temp0 = ToRegister(lir->temp0());
15838 Register temp1 = ToRegister(lir->temp1());
15839
15840 IonGetIteratorIC ic(liveRegs, val, output, temp0, temp1);
15841 addIC(lir, allocateIC(ic));
15842 }
15843
15844 void CodeGenerator::visitOptimizeSpreadCallCache(
15845 LOptimizeSpreadCallCache* lir) {
15846 LiveRegisterSet liveRegs = lir->safepoint()->liveRegs();
15847 ValueOperand val = ToValue(lir->value());
15848 ValueOperand output = ToOutValue(lir);
15849 Register temp = ToRegister(lir->temp0());
15850
15851 IonOptimizeSpreadCallIC ic(liveRegs, val, output, temp);
15852 addIC(lir, allocateIC(ic));
15853 }
15854
15855 void CodeGenerator::visitCloseIterCache(LCloseIterCache* lir) {
15856 LiveRegisterSet liveRegs = lir->safepoint()->liveRegs();
15857 Register iter = ToRegister(lir->iter());
15858 Register temp = ToRegister(lir->temp0());
15859 CompletionKind kind = CompletionKind(lir->mir()->completionKind());
15860
15861 IonCloseIterIC ic(liveRegs, iter, temp, kind);
15862 addIC(lir, allocateIC(ic));
15863 }
15864
15865 void CodeGenerator::visitOptimizeGetIteratorCache(
15866 LOptimizeGetIteratorCache* lir) {
15867 LiveRegisterSet liveRegs = lir->safepoint()->liveRegs();
15868 ValueOperand val = ToValue(lir->value());
15869 Register output = ToRegister(lir->output());
15870 Register temp = ToRegister(lir->temp0());
15871
15872 IonOptimizeGetIteratorIC ic(liveRegs, val, output, temp);
15873 addIC(lir, allocateIC(ic));
15874 }
15875
15876 void CodeGenerator::visitIteratorMore(LIteratorMore* lir) {
15877 const Register obj = ToRegister(lir->iterator());
15878 const ValueOperand output = ToOutValue(lir);
15879 const Register temp = ToRegister(lir->temp0());
15880
15881 masm.iteratorMore(obj, output, temp);
15882 }
15883
15884 void CodeGenerator::visitIsNoIterAndBranch(LIsNoIterAndBranch* lir) {
15885 ValueOperand input = ToValue(lir->input());
15886 Label* ifTrue = getJumpLabelForBranch(lir->ifTrue());
15887 Label* ifFalse = getJumpLabelForBranch(lir->ifFalse());
15888
15889 masm.branchTestMagic(Assembler::Equal, input, ifTrue);
15890
15891 if (!isNextBlock(lir->ifFalse()->lir())) {
15892 masm.jump(ifFalse);
15893 }
15894 }
15895
15896 void CodeGenerator::visitIteratorEnd(LIteratorEnd* lir) {
15897 const Register obj = ToRegister(lir->iterator());
15898 const Register temp0 = ToRegister(lir->temp0());
15899 const Register temp1 = ToRegister(lir->temp1());
15900 const Register temp2 = ToRegister(lir->temp2());
15901
15902 masm.iteratorClose(obj, temp0, temp1, temp2);
15903 }
15904
15905 void CodeGenerator::visitArgumentsLength(LArgumentsLength* lir) {
15906 // read number of actual arguments from the JS frame.
15907 Register argc = ToRegister(lir->output());
15908 masm.loadNumActualArgs(FramePointer, argc);
15909 }
15910
15911 void CodeGenerator::visitGetFrameArgument(LGetFrameArgument* lir) {
15912 ValueOperand result = ToOutValue(lir);
15913 const LAllocation* index = lir->index();
15914 size_t argvOffset = JitFrameLayout::offsetOfActualArgs();
15915
15916 // This instruction is used to access actual arguments and formal arguments.
15917 // The number of Values on the stack is |max(numFormals, numActuals)|, so we
15918 // assert |index < numFormals || index < numActuals| in debug builds.
15919 DebugOnly<size_t> numFormals = gen->outerInfo().script()->function()->nargs();
15920
15921 if (index->isConstant()) {
15922 int32_t i = index->toConstant()->toInt32();
15923 #ifdef DEBUG
15924 if (uint32_t(i) >= numFormals) {
15925 Label ok;
15926 Register argc = result.scratchReg();
15927 masm.loadNumActualArgs(FramePointer, argc);
15928 masm.branch32(Assembler::Above, argc, Imm32(i), &ok);
15929 masm.assumeUnreachable("Invalid argument index");
15930 masm.bind(&ok);
15931 }
15932 #endif
15933 Address argPtr(FramePointer, sizeof(Value) * i + argvOffset);
15934 masm.loadValue(argPtr, result);
15935 } else {
15936 Register i = ToRegister(index);
15937 #ifdef DEBUG
15938 Label ok;
15939 Register argc = result.scratchReg();
15940 masm.branch32(Assembler::Below, i, Imm32(numFormals), &ok);
15941 masm.loadNumActualArgs(FramePointer, argc);
15942 masm.branch32(Assembler::Above, argc, i, &ok);
15943 masm.assumeUnreachable("Invalid argument index");
15944 masm.bind(&ok);
15945 #endif
15946 BaseValueIndex argPtr(FramePointer, i, argvOffset);
15947 masm.loadValue(argPtr, result);
15948 }
15949 }
15950
15951 void CodeGenerator::visitGetFrameArgumentHole(LGetFrameArgumentHole* lir) {
15952 ValueOperand result = ToOutValue(lir);
15953 Register index = ToRegister(lir->index());
15954 Register length = ToRegister(lir->length());
15955 Register spectreTemp = ToTempRegisterOrInvalid(lir->temp0());
15956 size_t argvOffset = JitFrameLayout::offsetOfActualArgs();
15957
15958 Label outOfBounds, done;
15959 masm.spectreBoundsCheck32(index, length, spectreTemp, &outOfBounds);
15960
15961 BaseValueIndex argPtr(FramePointer, index, argvOffset);
15962 masm.loadValue(argPtr, result);
15963 masm.jump(&done);
15964
15965 masm.bind(&outOfBounds);
15966 bailoutCmp32(Assembler::LessThan, index, Imm32(0), lir->snapshot());
15967 masm.moveValue(UndefinedValue(), result);
15968
15969 masm.bind(&done);
15970 }
15971
15972 void CodeGenerator::visitRest(LRest* lir) {
15973 Register numActuals = ToRegister(lir->numActuals());
15974 Register temp0 = ToRegister(lir->temp0());
15975 Register temp1 = ToRegister(lir->temp1());
15976 Register temp2 = ToRegister(lir->temp2());
15977 Register temp3 = ToRegister(lir->temp3());
15978 unsigned numFormals = lir->mir()->numFormals();
15979
15980 // In baseline, DoRestFallback calls into NewArray to allocate the rest array.
15981 // If the length is 0, NewArray guesses a good capacity for it. We don't want
15982 // a smaller capacity in Ion, because that can lead to bailout loops.
15983 constexpr uint32_t arrayCapacity = 6;
15984 static_assert(GuessArrayGCKind(0) == GuessArrayGCKind(arrayCapacity));
15985
15986 if (Shape* shape = lir->mir()->shape()) {
15987 uint32_t arrayLength = 0;
15988 gc::AllocKind allocKind = GuessArrayGCKind(arrayCapacity);
15989 MOZ_ASSERT(gc::GetObjectFinalizeKind(&ArrayObject::class_) ==
15990 gc::FinalizeKind::None);
15991 MOZ_ASSERT(!IsFinalizedKind(allocKind));
15992 MOZ_ASSERT(GetGCKindSlots(allocKind) ==
15993 arrayCapacity + ObjectElements::VALUES_PER_HEADER);
15994
15995 Label joinAlloc, failAlloc;
15996 masm.movePtr(ImmGCPtr(shape), temp0);
15997 masm.createArrayWithFixedElements(temp2, temp0, temp1, InvalidReg,
15998 arrayLength, arrayCapacity, 0, 0,
15999 allocKind, gc::Heap::Default, &failAlloc);
16000 masm.jump(&joinAlloc);
16001 {
16002 masm.bind(&failAlloc);
16003 masm.movePtr(ImmPtr(nullptr), temp2);
16004 }
16005 masm.bind(&joinAlloc);
16006 } else {
16007 masm.movePtr(ImmPtr(nullptr), temp2);
16008 }
16009
16010 // Set temp1 to the address of the first actual argument.
16011 size_t actualsOffset = JitFrameLayout::offsetOfActualArgs();
16012 masm.computeEffectiveAddress(Address(FramePointer, actualsOffset), temp1);
16013
16014 // Compute array length: max(numActuals - numFormals, 0).
16015 Register lengthReg;
16016 if (numFormals) {
16017 lengthReg = temp0;
16018 Label emptyLength, joinLength;
16019 masm.branch32(Assembler::LessThanOrEqual, numActuals, Imm32(numFormals),
16020 &emptyLength);
16021 {
16022 masm.move32(numActuals, lengthReg);
16023 masm.sub32(Imm32(numFormals), lengthReg);
16024
16025 // Skip formal arguments.
16026 masm.addPtr(Imm32(sizeof(Value) * numFormals), temp1);
16027
16028 masm.jump(&joinLength);
16029 }
16030 masm.bind(&emptyLength);
16031 {
16032 masm.move32(Imm32(0), lengthReg);
16033
16034 // Leave temp1 pointed to the start of actuals() when the rest-array
16035 // length is zero. We don't use |actuals() + numFormals| because
16036 // |numFormals| can be any non-negative int32 value when this MRest was
16037 // created from scalar replacement optimizations. And it seems
16038 // questionable to compute a Value* pointer which points to who knows
16039 // where.
16040 }
16041 masm.bind(&joinLength);
16042 } else {
16043 // Use numActuals directly when there are no formals.
16044 lengthReg = numActuals;
16045 }
16046
16047 // Try to initialize the array elements.
16048 Label vmCall, done;
16049 if (lir->mir()->shape()) {
16050 // Call into C++ if we failed to allocate an array or there are more than
16051 // |arrayCapacity| elements.
16052 masm.branchTestPtr(Assembler::Zero, temp2, temp2, &vmCall);
16053 masm.branch32(Assembler::Above, lengthReg, Imm32(arrayCapacity), &vmCall);
16054
16055 // The array must be nursery allocated so no post barrier is needed.
16056 #ifdef DEBUG
16057 Label ok;
16058 masm.branchPtrInNurseryChunk(Assembler::Equal, temp2, temp3, &ok);
16059 masm.assumeUnreachable("Unexpected tenured object for LRest");
16060 masm.bind(&ok);
16061 #endif
16062
16063 Label nonZeroLength;
16064 masm.branch32(Assembler::NotEqual, lengthReg, Imm32(0), &nonZeroLength);
16065 masm.movePtr(temp2, ReturnReg);
16066 masm.jump(&done);
16067 masm.bind(&nonZeroLength);
16068
16069 // Store length and initializedLength.
16070 Register elements = temp3;
16071 masm.loadPtr(Address(temp2, NativeObject::offsetOfElements()), elements);
16072 Address lengthAddr(elements, ObjectElements::offsetOfLength());
16073 Address initLengthAddr(elements,
16074 ObjectElements::offsetOfInitializedLength());
16075 masm.store32(lengthReg, lengthAddr);
16076 masm.store32(lengthReg, initLengthAddr);
16077
16078 masm.push(temp2); // Spill result to free up register.
16079
16080 Register end = temp0;
16081 Register args = temp1;
16082 Register scratch = temp2;
16083 masm.computeEffectiveAddress(BaseValueIndex(elements, lengthReg), end);
16084
16085 Label loop;
16086 masm.bind(&loop);
16087 masm.storeValue(Address(args, 0), Address(elements, 0), scratch);
16088 masm.addPtr(Imm32(sizeof(Value)), args);
16089 masm.addPtr(Imm32(sizeof(Value)), elements);
16090 masm.branchPtr(Assembler::Below, elements, end, &loop);
16091
16092 // Pop result
16093 masm.pop(ReturnReg);
16094 masm.jump(&done);
16095 }
16096
16097 masm.bind(&vmCall);
16098
16099 pushArg(temp2);
16100 pushArg(temp1);
16101 pushArg(lengthReg);
16102
16103 using Fn =
16104 ArrayObject* (*)(JSContext*, uint32_t, Value*, Handle<ArrayObject*>);
16105 callVM<Fn, InitRestParameter>(lir);
16106
16107 masm.bind(&done);
16108 }
16109
16110 // Create a stackmap from the given safepoint, with the structure:
16111 //
16112 // <reg dump, if any>
16113 // | ++ <body (general spill)>
16114 // | | ++ <space for Frame>
16115 // | | ++ <inbound args>
16116 // | | |
16117 // Lowest Addr Highest Addr
16118 // |
16119 // framePushedAtStackMapBase
16120 //
16121 // The caller owns the resulting stackmap. This assumes a grow-down stack.
16122 //
16123 // For non-debug builds, if the stackmap would contain no pointers, no
16124 // stackmap is created, and nullptr is returned. For a debug build, a
16125 // stackmap is always created and returned.
16126 //
16127 // Depending on the type of safepoint, the stackmap may need to account for
16128 // spilled registers. WasmSafepointKind::LirCall corresponds to LIR nodes where
16129 // isCall() == true, for which the register allocator will spill/restore all
16130 // live registers at the LIR level - in this case, the LSafepoint sees only live
16131 // values on the stack, never in registers. WasmSafepointKind::CodegenCall, on
16132 // the other hand, is for LIR nodes which may manually spill/restore live
16133 // registers in codegen, in which case the stackmap must account for this. Traps
16134 // also require tracking of live registers, but spilling is handled by the trap
16135 // mechanism.
16136 static bool CreateStackMapFromLSafepoint(LSafepoint& safepoint,
16137 const RegisterOffsets& trapExitLayout,
16138 size_t trapExitLayoutNumWords,
16139 size_t nInboundStackArgBytes,
16140 wasm::StackMap** result) {
16141 // Ensure this is defined on all return paths.
16142 *result = nullptr;
16143
16144 // The size of the wasm::Frame itself.
16145 const size_t nFrameBytes = sizeof(wasm::Frame);
16146
16147 // This is the number of bytes spilled for live registers, outside of a trap.
16148 // For traps, trapExitLayout and trapExitLayoutNumWords will be used.
16149 const size_t nRegisterDumpBytes =
16150 MacroAssembler::PushRegsInMaskSizeInBytes(safepoint.liveRegs());
16151
16152 // As mentioned above, for WasmSafepointKind::LirCall, register spills and
16153 // restores are handled at the LIR level and there should therefore be no live
16154 // registers to handle here.
16155 MOZ_ASSERT_IF(safepoint.wasmSafepointKind() == WasmSafepointKind::LirCall,
16156 nRegisterDumpBytes == 0);
16157 MOZ_ASSERT(nRegisterDumpBytes % sizeof(void*) == 0);
16158
16159 // This is the number of bytes in the general spill area, below the Frame.
16160 const size_t nBodyBytes = safepoint.framePushedAtStackMapBase();
16161
16162 // The stack map owns any alignment padding around inbound stack args.
16163 const size_t nInboundStackArgBytesAligned =
16164 wasm::AlignStackArgAreaSize(nInboundStackArgBytes);
16165
16166 // This is the number of bytes in the general spill area, the Frame, and the
16167 // incoming args, but not including any register dump area.
16168 const size_t nNonRegisterBytes =
16169 nBodyBytes + nFrameBytes + nInboundStackArgBytesAligned;
16170 MOZ_ASSERT(nNonRegisterBytes % sizeof(void*) == 0);
16171
16172 // This is the number of bytes in the register dump area, if any, below the
16173 // general spill area.
16174 const size_t nRegisterBytes =
16175 (safepoint.wasmSafepointKind() == WasmSafepointKind::Trap)
16176 ? (trapExitLayoutNumWords * sizeof(void*))
16177 : nRegisterDumpBytes;
16178
16179 // This is the total number of bytes covered by the map.
16180 const size_t nTotalBytes = nNonRegisterBytes + nRegisterBytes;
16181
16182 #ifndef DEBUG
16183 bool needStackMap = !(safepoint.wasmAnyRefRegs().empty() &&
16184 safepoint.wasmAnyRefSlots().empty() &&
16185 safepoint.slotsOrElementsSlots().empty());
16186
16187 // There are no references, and this is a non-debug build, so don't bother
16188 // building the stackmap.
16189 if (!needStackMap) {
16190 return true;
16191 }
16192 #endif
16193
16194 wasm::StackMap* stackMap =
16195 wasm::StackMap::create(nTotalBytes / sizeof(void*));
16196 if (!stackMap) {
16197 return false;
16198 }
16199 if (safepoint.wasmSafepointKind() == WasmSafepointKind::Trap) {
16200 stackMap->setExitStubWords(trapExitLayoutNumWords);
16201 }
16202
16203 // REG DUMP AREA, if any.
16204 size_t regDumpWords = 0;
16205 const LiveGeneralRegisterSet wasmAnyRefRegs = safepoint.wasmAnyRefRegs();
16206 const LiveGeneralRegisterSet slotsOrElementsRegs =
16207 safepoint.slotsOrElementsRegs();
16208 const LiveGeneralRegisterSet refRegs(GeneralRegisterSet::Union(
16209 wasmAnyRefRegs.set(), slotsOrElementsRegs.set()));
16210 GeneralRegisterForwardIterator refRegsIter(refRegs);
16211 switch (safepoint.wasmSafepointKind()) {
16212 case WasmSafepointKind::LirCall:
16213 case WasmSafepointKind::StackSwitch:
16214 case WasmSafepointKind::CodegenCall: {
16215 size_t spilledNumWords = nRegisterDumpBytes / sizeof(void*);
16216 regDumpWords += spilledNumWords;
16217
16218 for (; refRegsIter.more(); ++refRegsIter) {
16219 Register reg = *refRegsIter;
16220 size_t offsetFromSpillBase =
16221 safepoint.liveRegs().gprs().offsetOfPushedRegister(reg) /
16222 sizeof(void*);
16223 MOZ_ASSERT(0 < offsetFromSpillBase &&
16224 offsetFromSpillBase <= spilledNumWords);
16225 size_t index = spilledNumWords - offsetFromSpillBase;
16226
16227 if (wasmAnyRefRegs.has(reg)) {
16228 stackMap->set(index, wasm::StackMap::AnyRef);
16229 } else {
16230 MOZ_ASSERT(slotsOrElementsRegs.has(reg));
16231 stackMap->set(index, wasm::StackMap::ArrayDataPointer);
16232 }
16233 }
16234 // Float and vector registers do not have to be handled; they cannot
16235 // contain wasm anyrefs, and they are spilled after general-purpose
16236 // registers. Gprs are therefore closest to the spill base and thus their
16237 // offset calculation does not need to account for other spills.
16238 } break;
16239 case WasmSafepointKind::Trap: {
16240 regDumpWords += trapExitLayoutNumWords;
16241
16242 for (; refRegsIter.more(); ++refRegsIter) {
16243 Register reg = *refRegsIter;
16244 size_t offsetFromTop = trapExitLayout.getOffset(reg);
16245
16246 // If this doesn't hold, the associated register wasn't saved by
16247 // the trap exit stub. Better to crash now than much later, in
16248 // some obscure place, and possibly with security consequences.
16249 MOZ_RELEASE_ASSERT(offsetFromTop < trapExitLayoutNumWords);
16250
16251 // offsetFromTop is an offset in words down from the highest
16252 // address in the exit stub save area. Switch it around to be an
16253 // offset up from the bottom of the (integer register) save area.
16254 size_t offsetFromBottom = trapExitLayoutNumWords - 1 - offsetFromTop;
16255
16256 if (wasmAnyRefRegs.has(reg)) {
16257 stackMap->set(offsetFromBottom, wasm::StackMap::AnyRef);
16258 } else {
16259 MOZ_ASSERT(slotsOrElementsRegs.has(reg));
16260 stackMap->set(offsetFromBottom, wasm::StackMap::ArrayDataPointer);
16261 }
16262 }
16263 } break;
16264 default:
16265 MOZ_CRASH("unreachable");
16266 }
16267
16268 // Ensure other reg/slot collections on LSafepoint are empty.
16269 MOZ_ASSERT(safepoint.gcRegs().empty() && safepoint.gcSlots().empty());
16270 #ifdef JS_NUNBOX32
16271 MOZ_ASSERT(safepoint.nunboxParts().empty());
16272 #elif JS_PUNBOX64
16273 MOZ_ASSERT(safepoint.valueRegs().empty() && safepoint.valueSlots().empty());
16274 #endif
16275
16276 // BODY (GENERAL SPILL) AREA and FRAME and INCOMING ARGS
16277 // Deal with roots on the stack.
16278 const LSafepoint::SlotList& wasmAnyRefSlots = safepoint.wasmAnyRefSlots();
16279 for (SafepointSlotEntry wasmAnyRefSlot : wasmAnyRefSlots) {
16280 // The following needs to correspond with JitFrameLayout::slotRef
16281 // wasmAnyRefSlot.stack == 0 means the slot is in the args area
16282 if (wasmAnyRefSlot.stack) {
16283 // It's a slot in the body allocation, so .slot is interpreted
16284 // as an index downwards from the Frame*
16285 MOZ_ASSERT(wasmAnyRefSlot.slot <= nBodyBytes);
16286 uint32_t offsetInBytes = nBodyBytes - wasmAnyRefSlot.slot;
16287 MOZ_ASSERT(offsetInBytes % sizeof(void*) == 0);
16288 stackMap->set(regDumpWords + offsetInBytes / sizeof(void*),
16289 wasm::StackMap::AnyRef);
16290 } else {
16291 // It's an argument slot
16292 MOZ_ASSERT(wasmAnyRefSlot.slot < nInboundStackArgBytes);
16293 uint32_t offsetInBytes = nBodyBytes + nFrameBytes + wasmAnyRefSlot.slot;
16294 MOZ_ASSERT(offsetInBytes % sizeof(void*) == 0);
16295 stackMap->set(regDumpWords + offsetInBytes / sizeof(void*),
16296 wasm::StackMap::AnyRef);
16297 }
16298 }
16299
16300 // Track array data pointers on the stack
16301 const LSafepoint::SlotList& slots = safepoint.slotsOrElementsSlots();
16302 for (SafepointSlotEntry slot : slots) {
16303 MOZ_ASSERT(slot.stack);
16304
16305 // It's a slot in the body allocation, so .slot is interpreted
16306 // as an index downwards from the Frame*
16307 MOZ_ASSERT(slot.slot <= nBodyBytes);
16308 uint32_t offsetInBytes = nBodyBytes - slot.slot;
16309 MOZ_ASSERT(offsetInBytes % sizeof(void*) == 0);
16310 stackMap->set(regDumpWords + offsetInBytes / sizeof(void*),
16311 wasm::StackMap::Kind::ArrayDataPointer);
16312 }
16313
16314 // Record in the map, how far down from the highest address the Frame* is.
16315 // Take the opportunity to check that we haven't marked any part of the
16316 // Frame itself as a pointer.
16317 stackMap->setFrameOffsetFromTop((nInboundStackArgBytesAligned + nFrameBytes) /
16318 sizeof(void*));
16319 #ifdef DEBUG
16320 for (uint32_t i = 0; i < nFrameBytes / sizeof(void*); i++) {
16321 MOZ_ASSERT(stackMap->get(stackMap->header.numMappedWords -
16322 stackMap->header.frameOffsetFromTop + i) ==
16323 wasm::StackMap::Kind::POD);
16324 }
16325 #endif
16326
16327 *result = stackMap;
16328 return true;
16329 }
16330
16331 bool CodeGenerator::generateWasm(wasm::CallIndirectId callIndirectId,
16332 const wasm::TrapSiteDesc& entryTrapSiteDesc,
16333 const wasm::ArgTypeVector& argTypes,
16334 const RegisterOffsets& trapExitLayout,
16335 size_t trapExitLayoutNumWords,
16336 wasm::FuncOffsets* offsets,
16337 wasm::StackMaps* stackMaps,
16338 wasm::Decoder* decoder,
16339 jit::IonPerfSpewer* spewer) {
16340 AutoCreatedBy acb(masm, "CodeGenerator::generateWasm");
16341
16342 JitSpew(JitSpew_Codegen, "# Emitting wasm code");
16343
16344 size_t nInboundStackArgBytes = StackArgAreaSizeUnaligned(argTypes);
16345 inboundStackArgBytes_ = nInboundStackArgBytes;
16346
16347 perfSpewer_.markStartOffset(masm.currentOffset());
16348 perfSpewer_.recordOffset(masm, "Prologue");
16349 wasm::GenerateFunctionPrologue(masm, callIndirectId, mozilla::Nothing(),
16350 offsets);
16351
16352 #ifdef DEBUG
16353 // If we are doing full debug checks, always load the instance pointer into
16354 // the usual spot in the frame so that it can be loaded later regardless of
16355 // what is in InstanceReg. See CodeGenerator::emitDebugResultChecks.
16356 if (JitOptions.fullDebugChecks) {
16357 masm.storePtr(InstanceReg,
16358 Address(FramePointer,
16359 wasm::FrameWithInstances::calleeInstanceOffset()));
16360 }
16361 #endif
16362
16363 MOZ_ASSERT(masm.framePushed() == 0);
16364
16365 // Very large frames are implausible, probably an attack.
16366 if (frameSize() > wasm::MaxFrameSize) {
16367 return decoder->fail(decoder->beginOffset(), "stack frame is too large");
16368 }
16369
16370 if (omitOverRecursedCheck()) {
16371 masm.reserveStack(frameSize());
16372 } else {
16373 std::pair<CodeOffset, uint32_t> pair =
16374 masm.wasmReserveStackChecked(frameSize(), entryTrapSiteDesc);
16375 CodeOffset trapInsnOffset = pair.first;
16376 size_t nBytesReservedBeforeTrap = pair.second;
16377
16378 wasm::StackMap* functionEntryStackMap = nullptr;
16379 if (!CreateStackMapForFunctionEntryTrap(
16380 argTypes, trapExitLayout, trapExitLayoutNumWords,
16381 nBytesReservedBeforeTrap, nInboundStackArgBytes,
16382 &functionEntryStackMap)) {
16383 return false;
16384 }
16385
16386 // In debug builds, we'll always have a stack map, even if there are no
16387 // refs to track.
16388 MOZ_ASSERT(functionEntryStackMap);
16389
16390 if (functionEntryStackMap &&
16391 !stackMaps->add(trapInsnOffset.offset(), functionEntryStackMap)) {
16392 functionEntryStackMap->destroy();
16393 return false;
16394 }
16395 }
16396
16397 MOZ_ASSERT(masm.framePushed() == frameSize());
16398
16399 if (!generateBody()) {
16400 return false;
16401 }
16402
16403 perfSpewer_.recordOffset(masm, "Epilogue");
16404 masm.bind(&returnLabel_);
16405 wasm::GenerateFunctionEpilogue(masm, frameSize(), offsets);
16406
16407 perfSpewer_.recordOffset(masm, "OOLCode");
16408 if (!generateOutOfLineCode()) {
16409 return false;
16410 }
16411
16412 masm.flush();
16413 if (masm.oom()) {
16414 return false;
16415 }
16416
16417 offsets->end = masm.currentOffset();
16418
16419 MOZ_ASSERT(!masm.failureLabel()->used());
16420 MOZ_ASSERT(snapshots_.listSize() == 0);
16421 MOZ_ASSERT(snapshots_.RVATableSize() == 0);
16422 MOZ_ASSERT(recovers_.size() == 0);
16423 MOZ_ASSERT(graph.numConstants() == 0);
16424 MOZ_ASSERT(osiIndices_.empty());
16425 MOZ_ASSERT(icList_.empty());
16426 MOZ_ASSERT(safepoints_.size() == 0);
16427 MOZ_ASSERT(!scriptCounts_);
16428
16429 // Convert the safepoints to stackmaps and add them to our running
16430 // collection thereof.
16431 for (CodegenSafepointIndex& index : safepointIndices_) {
16432 wasm::StackMap* stackMap = nullptr;
16433 if (!CreateStackMapFromLSafepoint(*index.safepoint(), trapExitLayout,
16434 trapExitLayoutNumWords,
16435 nInboundStackArgBytes, &stackMap)) {
16436 return false;
16437 }
16438
16439 // In debug builds, we'll always have a stack map.
16440 MOZ_ASSERT(stackMap);
16441 if (!stackMap) {
16442 continue;
16443 }
16444
16445 if (!stackMaps->add(index.displacement(), stackMap)) {
16446 stackMap->destroy();
16447 return false;
16448 }
16449 }
16450
16451 *spewer = std::move(perfSpewer_);
16452 return true;
16453 }
16454
16455 bool CodeGenerator::generate(const WarpSnapshot* snapshot) {
16456 AutoCreatedBy acb(masm, "CodeGenerator::generate");
16457
16458 MOZ_ASSERT(snapshot);
16459 snapshot_ = snapshot;
16460
16461 JitSpew(JitSpew_Codegen, "# Emitting code for script %s:%u:%u",
16462 gen->outerInfo().script()->filename(),
16463 gen->outerInfo().script()->lineno(),
16464 gen->outerInfo().script()->column().oneOriginValue());
16465
16466 // Initialize native code table with an entry to the start of
16467 // top-level script.
16468 InlineScriptTree* tree = gen->outerInfo().inlineScriptTree();
16469 jsbytecode* startPC = tree->script()->code();
16470 BytecodeSite* startSite = new (gen->alloc()) BytecodeSite(tree, startPC);
16471 if (!addNativeToBytecodeEntry(startSite)) {
16472 return false;
16473 }
16474
16475 if (!safepoints_.init(gen->alloc())) {
16476 return false;
16477 }
16478
16479 size_t maxSafepointIndices =
16480 graph.numSafepoints() + graph.extraSafepointUses();
16481 if (!safepointIndices_.reserve(maxSafepointIndices)) {
16482 return false;
16483 }
16484 if (!osiIndices_.reserve(graph.numSafepoints())) {
16485 return false;
16486 }
16487
16488 perfSpewer_.recordOffset(masm, "Prologue");
16489 if (!generatePrologue()) {
16490 return false;
16491 }
16492
16493 // Reset native => bytecode map table with top-level script and startPc.
16494 if (!addNativeToBytecodeEntry(startSite)) {
16495 return false;
16496 }
16497
16498 if (!generateBody()) {
16499 return false;
16500 }
16501
16502 // Reset native => bytecode map table with top-level script and startPc.
16503 if (!addNativeToBytecodeEntry(startSite)) {
16504 return false;
16505 }
16506
16507 perfSpewer_.recordOffset(masm, "Epilogue");
16508 if (!generateEpilogue()) {
16509 return false;
16510 }
16511
16512 // Reset native => bytecode map table with top-level script and startPc.
16513 if (!addNativeToBytecodeEntry(startSite)) {
16514 return false;
16515 }
16516
16517 perfSpewer_.recordOffset(masm, "InvalidateEpilogue");
16518 generateInvalidateEpilogue();
16519
16520 // native => bytecode entries for OOL code will be added
16521 // by CodeGeneratorShared::generateOutOfLineCode
16522 perfSpewer_.recordOffset(masm, "OOLCode");
16523 if (!generateOutOfLineCode()) {
16524 return false;
16525 }
16526
16527 // Add terminal entry.
16528 if (!addNativeToBytecodeEntry(startSite)) {
16529 return false;
16530 }
16531
16532 // Dump Native to bytecode entries to spew.
16533 dumpNativeToBytecodeEntries();
16534
16535 // We encode safepoints after the OSI-point offsets have been determined.
16536 if (!encodeSafepoints()) {
16537 return false;
16538 }
16539
16540 // If this assertion trips, then you have multiple things to do:
16541 //
16542 // This assertion will report if a safepoint is used multiple times for the
16543 // same instruction. To fix this assertion make sure to call
16544 // `lirGraph_.addExtraSafepointUses(..);` in the Lowering phase.
16545 //
16546 // However, this non-worrying issue might hide a more dramatic security issue,
16547 // which is that having multiple encoding of a safepoint in a single LIR
16548 // instruction is not safe, unless:
16549 //
16550 // - The multiple uses of the safepoints are in different code path. i-e
16551 // there should be not single execution trace making use of multiple
16552 // calls within a single instruction.
16553 //
16554 // - There is enough space to encode data in-place of the call instruction.
16555 // Such that a patched-call site does not corrupt the code path on another
16556 // execution trace.
16557 //
16558 // This issue is caused by the way invalidation works, to keep the code alive
16559 // when invalidated code is only referenced by the stack. This works by
16560 // storing data in-place of the calling code, which thus becomes unsafe to
16561 // execute.
16562 MOZ_ASSERT(safepointIndices_.length() <= maxSafepointIndices);
16563
16564 // For each instruction with a safepoint, we have an OSI point inserted after
16565 // which handles bailouts in case of invalidation of the code.
16566 MOZ_ASSERT(osiIndices_.length() == graph.numSafepoints());
16567
16568 return !masm.oom();
16569 }
16570
16571 static bool AddInlinedCompilations(JSContext* cx, HandleScript script,
16572 IonCompilationId compilationId,
16573 const WarpSnapshot* snapshot,
16574 bool* isValid) {
16575 MOZ_ASSERT(!*isValid);
16576 RecompileInfo recompileInfo(script, compilationId);
16577
16578 JitZone* jitZone = cx->zone()->jitZone();
16579
16580 for (const auto* scriptSnapshot : snapshot->scripts()) {
16581 JSScript* inlinedScript = scriptSnapshot->script();
16582 if (inlinedScript == script) {
16583 continue;
16584 }
16585
16586 // TODO(post-Warp): This matches FinishCompilation and is necessary to
16587 // ensure in-progress compilations are canceled when an inlined functon
16588 // becomes a debuggee. See the breakpoint-14.js jit-test.
16589 // When TI is gone, try to clean this up by moving AddInlinedCompilations to
16590 // WarpOracle so that we can handle this as part of addPendingRecompile
16591 // instead of requiring this separate check.
16592 if (inlinedScript->isDebuggee()) {
16593 *isValid = false;
16594 return true;
16595 }
16596
16597 if (!jitZone->addInlinedCompilation(recompileInfo, inlinedScript)) {
16598 return false;
16599 }
16600 }
16601
16602 *isValid = true;
16603 return true;
16604 }
16605
16606 struct EmulatesUndefinedDependency final : public CompilationDependency {
16607 explicit EmulatesUndefinedDependency()
16608 : CompilationDependency(CompilationDependency::Type::EmulatesUndefined) {
16609 };
16610
16611 virtual bool operator==(const CompilationDependency& dep) const override {
16612 // Since the emulates undefined fuse is runtime wide, they are all equal
16613 return dep.type == type;
16614 }
16615
16616 virtual bool checkDependency(JSContext* cx) override {
16617 return cx->runtime()->hasSeenObjectEmulateUndefinedFuse.ref().intact();
16618 }
16619
16620 virtual bool registerDependency(JSContext* cx, HandleScript script) override {
16621 MOZ_ASSERT(checkDependency(cx));
16622 return cx->runtime()
16623 ->hasSeenObjectEmulateUndefinedFuse.ref()
16624 .addFuseDependency(cx, script);
16625 }
16626
16627 virtual UniquePtr<CompilationDependency> clone() const override {
16628 return MakeUnique<EmulatesUndefinedDependency>();
16629 }
16630 };
16631
16632 struct ArrayExceedsInt32LengthDependency final : public CompilationDependency {
16633 explicit ArrayExceedsInt32LengthDependency()
16634 : CompilationDependency(
16635 CompilationDependency::Type::ArrayExceedsInt32Length) {};
16636
16637 virtual bool operator==(const CompilationDependency& dep) const override {
16638 return dep.type == type;
16639 }
16640
16641 virtual bool checkDependency(JSContext* cx) override {
16642 return cx->runtime()->hasSeenArrayExceedsInt32LengthFuse.ref().intact();
16643 }
16644
16645 virtual bool registerDependency(JSContext* cx, HandleScript script) override {
16646 MOZ_ASSERT(checkDependency(cx));
16647 return cx->runtime()
16648 ->hasSeenArrayExceedsInt32LengthFuse.ref()
16649 .addFuseDependency(cx, script);
16650 }
16651
16652 virtual UniquePtr<CompilationDependency> clone() const override {
16653 return MakeUnique<ArrayExceedsInt32LengthDependency>();
16654 }
16655 };
16656
16657 bool CodeGenerator::addHasSeenObjectEmulateUndefinedFuseDependency() {
16658 EmulatesUndefinedDependency dep;
16659 return mirGen().tracker.addDependency(dep);
16660 }
16661
16662 bool CodeGenerator::addHasSeenArrayExceedsInt32LengthFuseDependency() {
16663 ArrayExceedsInt32LengthDependency dep;
16664 return mirGen().tracker.addDependency(dep);
16665 }
16666
16667 bool CodeGenerator::link(JSContext* cx) {
16668 AutoCreatedBy acb(masm, "CodeGenerator::link");
16669
16670 // We cancel off-thread Ion compilations in a few places during GC, but if
16671 // this compilation was performed off-thread it will already have been
16672 // removed from the relevant lists by this point. Don't allow GC here.
16673 JS::AutoAssertNoGC nogc(cx);
16674
16675 RootedScript script(cx, gen->outerInfo().script());
16676 MOZ_ASSERT(!script->hasIonScript());
16677
16678 if (scriptCounts_ && !script->hasScriptCounts() &&
16679 !script->initScriptCounts(cx)) {
16680 return false;
16681 }
16682
16683 JitZone* jitZone = cx->zone()->jitZone();
16684
16685 IonCompilationId compilationId =
16686 cx->runtime()->jitRuntime()->nextCompilationId();
16687 jitZone->currentCompilationIdRef().emplace(compilationId);
16688 auto resetCurrentId = mozilla::MakeScopeExit(
16689 [jitZone] { jitZone->currentCompilationIdRef().reset(); });
16690
16691 // Record constraints. If an error occured, returns false and potentially
16692 // prevent future compilations. Otherwise, if an invalidation occured, then
16693 // skip the current compilation.
16694 bool isValid = false;
16695
16696 // If an inlined script is invalidated (for example, by attaching
16697 // a debugger), we must also invalidate the parent IonScript.
16698 if (!AddInlinedCompilations(cx, script, compilationId, snapshot_, &isValid)) {
16699 return false;
16700 }
16701
16702 // This compilation is no longer valid; don't proceed, but return true as this
16703 // isn't an error case either.
16704 if (!isValid) {
16705 return true;
16706 }
16707
16708 CompilationDependencyTracker& tracker = mirGen().tracker;
16709 // Make sure we're using the same realm as this context.
16710 MOZ_ASSERT(mirGen().realm->realmPtr() == cx->realm());
16711 if (!tracker.checkDependencies(cx)) {
16712 return true;
16713 }
16714
16715 for (auto& dep : tracker.dependencies) {
16716 if (!dep->registerDependency(cx, script)) {
16717 return false; // Should we make sure we only return false on OOM and then
16718 // eat the OOM here?
16719 }
16720 }
16721
16722 uint32_t argumentSlots = (gen->outerInfo().nargs() + 1) * sizeof(Value);
16723
16724 size_t numNurseryObjects = snapshot_->nurseryObjects().length();
16725
16726 IonScript* ionScript = IonScript::New(
16727 cx, compilationId, graph.localSlotsSize(), argumentSlots, frameDepth_,
16728 snapshots_.listSize(), snapshots_.RVATableSize(), recovers_.size(),
16729 graph.numConstants(), numNurseryObjects, safepointIndices_.length(),
16730 osiIndices_.length(), icList_.length(), runtimeData_.length(),
16731 safepoints_.size());
16732 if (!ionScript) {
16733 return false;
16734 }
16735 #ifdef DEBUG
16736 ionScript->setICHash(snapshot_->icHash());
16737 #endif
16738
16739 auto freeIonScript = mozilla::MakeScopeExit([&ionScript] {
16740 // Use js_free instead of IonScript::Destroy: the cache list is still
16741 // uninitialized.
16742 js_free(ionScript);
16743 });
16744
16745 Linker linker(masm);
16746 JitCode* code = linker.newCode(cx, CodeKind::Ion);
16747 if (!code) {
16748 return false;
16749 }
16750
16751 // Encode native to bytecode map if profiling is enabled.
16752 if (isProfilerInstrumentationEnabled()) {
16753 // Generate native-to-bytecode main table.
16754 IonEntry::ScriptList scriptList;
16755 if (!generateCompactNativeToBytecodeMap(cx, code, scriptList)) {
16756 return false;
16757 }
16758
16759 uint8_t* ionTableAddr =
16760 ((uint8_t*)nativeToBytecodeMap_.get()) + nativeToBytecodeTableOffset_;
16761 JitcodeIonTable* ionTable = (JitcodeIonTable*)ionTableAddr;
16762
16763 // Construct the IonEntry that will go into the global table.
16764 auto entry = MakeJitcodeGlobalEntry<IonEntry>(
16765 cx, code, code->raw(), code->rawEnd(), std::move(scriptList), ionTable);
16766 if (!entry) {
16767 return false;
16768 }
16769 (void)nativeToBytecodeMap_.release(); // Table is now owned by |entry|.
16770
16771 // Add entry to the global table.
16772 JitcodeGlobalTable* globalTable =
16773 cx->runtime()->jitRuntime()->getJitcodeGlobalTable();
16774 if (!globalTable->addEntry(std::move(entry))) {
16775 return false;
16776 }
16777
16778 // Mark the jitcode as having a bytecode map.
16779 code->setHasBytecodeMap();
16780 } else {
16781 // Add a dumy jitcodeGlobalTable entry.
16782 auto entry = MakeJitcodeGlobalEntry<DummyEntry>(cx, code, code->raw(),
16783 code->rawEnd());
16784 if (!entry) {
16785 return false;
16786 }
16787
16788 // Add entry to the global table.
16789 JitcodeGlobalTable* globalTable =
16790 cx->runtime()->jitRuntime()->getJitcodeGlobalTable();
16791 if (!globalTable->addEntry(std::move(entry))) {
16792 return false;
16793 }
16794
16795 // Mark the jitcode as having a bytecode map.
16796 code->setHasBytecodeMap();
16797 }
16798
16799 ionScript->setMethod(code);
16800
16801 // If the Gecko Profiler is enabled, mark IonScript as having been
16802 // instrumented accordingly.
16803 if (isProfilerInstrumentationEnabled()) {
16804 ionScript->setHasProfilingInstrumentation();
16805 }
16806
16807 Assembler::PatchDataWithValueCheck(
16808 CodeLocationLabel(code, invalidateEpilogueData_), ImmPtr(ionScript),
16809 ImmPtr((void*)-1));
16810
16811 for (CodeOffset offset : ionScriptLabels_) {
16812 Assembler::PatchDataWithValueCheck(CodeLocationLabel(code, offset),
16813 ImmPtr(ionScript), ImmPtr((void*)-1));
16814 }
16815
16816 for (NurseryObjectLabel label : ionNurseryObjectLabels_) {
16817 void* entry = ionScript->addressOfNurseryObject(label.nurseryIndex);
16818 Assembler::PatchDataWithValueCheck(CodeLocationLabel(code, label.offset),
16819 ImmPtr(entry), ImmPtr((void*)-1));
16820 }
16821
16822 // for generating inline caches during the execution.
16823 if (runtimeData_.length()) {
16824 ionScript->copyRuntimeData(&runtimeData_[0]);
16825 }
16826 if (icList_.length()) {
16827 ionScript->copyICEntries(&icList_[0]);
16828 }
16829
16830 for (size_t i = 0; i < icInfo_.length(); i++) {
16831 IonIC& ic = ionScript->getICFromIndex(i);
16832 Assembler::PatchDataWithValueCheck(
16833 CodeLocationLabel(code, icInfo_[i].icOffsetForJump),
16834 ImmPtr(ic.codeRawPtr()), ImmPtr((void*)-1));
16835 Assembler::PatchDataWithValueCheck(
16836 CodeLocationLabel(code, icInfo_[i].icOffsetForPush), ImmPtr(&ic),
16837 ImmPtr((void*)-1));
16838 }
16839
16840 JitSpew(JitSpew_Codegen, "Created IonScript %p (raw %p)", (void*)ionScript,
16841 (void*)code->raw());
16842
16843 ionScript->setInvalidationEpilogueDataOffset(
16844 invalidateEpilogueData_.offset());
16845 if (jsbytecode* osrPc = gen->outerInfo().osrPc()) {
16846 ionScript->setOsrPc(osrPc);
16847 ionScript->setOsrEntryOffset(getOsrEntryOffset());
16848 }
16849 ionScript->setInvalidationEpilogueOffset(invalidate_.offset());
16850
16851 perfSpewer_.saveJSProfile(cx, script, code);
16852
16853 #ifdef MOZ_VTUNE
16854 vtune::MarkScript(code, script, "ion");
16855 #endif
16856
16857 // Set a Ion counter hint for this script.
16858 if (cx->runtime()->jitRuntime()->hasJitHintsMap()) {
16859 JitHintsMap* jitHints = cx->runtime()->jitRuntime()->getJitHintsMap();
16860 jitHints->recordIonCompilation(script);
16861 }
16862
16863 // for marking during GC.
16864 if (safepointIndices_.length()) {
16865 ionScript->copySafepointIndices(&safepointIndices_[0]);
16866 }
16867 if (safepoints_.size()) {
16868 ionScript->copySafepoints(&safepoints_);
16869 }
16870
16871 // for recovering from an Ion Frame.
16872 if (osiIndices_.length()) {
16873 ionScript->copyOsiIndices(&osiIndices_[0]);
16874 }
16875 if (snapshots_.listSize()) {
16876 ionScript->copySnapshots(&snapshots_);
16877 }
16878 MOZ_ASSERT_IF(snapshots_.listSize(), recovers_.size());
16879 if (recovers_.size()) {
16880 ionScript->copyRecovers(&recovers_);
16881 }
16882 if (graph.numConstants()) {
16883 const Value* vp = graph.constantPool();
16884 ionScript->copyConstants(vp);
16885 for (size_t i = 0; i < graph.numConstants(); i++) {
16886 const Value& v = vp[i];
16887 if (v.isGCThing()) {
16888 if (gc::StoreBuffer* sb = v.toGCThing()->storeBuffer()) {
16889 sb->putWholeCell(script);
16890 break;
16891 }
16892 }
16893 }
16894 }
16895
16896 // Attach any generated script counts to the script.
16897 if (IonScriptCounts* counts = extractScriptCounts()) {
16898 script->addIonCounts(counts);
16899 }
16900 // WARNING: Code after this point must be infallible!
16901
16902 // Copy the list of nursery objects. Note that the store buffer can add
16903 // HeapPtr edges that must be cleared in IonScript::Destroy. See the
16904 // infallibility warning above.
16905 const auto& nurseryObjects = snapshot_->nurseryObjects();
16906 for (size_t i = 0; i < nurseryObjects.length(); i++) {
16907 ionScript->nurseryObjects()[i].init(nurseryObjects[i]);
16908 }
16909
16910 // Transfer ownership of the IonScript to the JitScript. At this point enough
16911 // of the IonScript must be initialized for IonScript::Destroy to work.
16912 freeIonScript.release();
16913 script->jitScript()->setIonScript(script, ionScript);
16914
16915 return true;
16916 }
16917
16918 void CodeGenerator::visitUnboxFloatingPoint(LUnboxFloatingPoint* lir) {
16919 ValueOperand box = ToValue(lir->input());
16920 const LDefinition* result = lir->output();
16921
16922 // Out-of-line path to convert int32 to double or bailout
16923 // if this instruction is fallible.
16924 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
16925 ValueOperand value = ToValue(lir->input());
16926
16927 if (lir->mir()->fallible()) {
16928 Label bail;
16929 masm.branchTestInt32(Assembler::NotEqual, value, &bail);
16930 bailoutFrom(&bail, lir->snapshot());
16931 }
16932 masm.convertInt32ToDouble(value.payloadOrValueReg(),
16933 ToFloatRegister(lir->output()));
16934 masm.jump(ool.rejoin());
16935 });
16936 addOutOfLineCode(ool, lir->mir());
16937
16938 FloatRegister resultReg = ToFloatRegister(result);
16939 masm.branchTestDouble(Assembler::NotEqual, box, ool->entry());
16940 masm.unboxDouble(box, resultReg);
16941 masm.bind(ool->rejoin());
16942 }
16943
16944 void CodeGenerator::visitCallBindVar(LCallBindVar* lir) {
16945 pushArg(ToRegister(lir->environmentChain()));
16946
16947 using Fn = JSObject* (*)(JSContext*, JSObject*);
16948 callVM<Fn, BindVarOperation>(lir);
16949 }
16950
16951 void CodeGenerator::visitMegamorphicSetElement(LMegamorphicSetElement* lir) {
16952 Register obj = ToRegister(lir->object());
16953 ValueOperand idVal = ToValue(lir->index());
16954 ValueOperand value = ToValue(lir->value());
16955
16956 Register temp0 = ToRegister(lir->temp0());
16957 // See comment in LIROps.yaml (x86 is short on registers)
16958 #ifndef JS_CODEGEN_X86
16959 Register temp1 = ToRegister(lir->temp1());
16960 Register temp2 = ToRegister(lir->temp2());
16961 #endif
16962
16963 // The instruction is marked as call-instruction so only these registers are
16964 // live.
16965 LiveRegisterSet liveRegs;
16966 liveRegs.addUnchecked(obj);
16967 liveRegs.addUnchecked(idVal);
16968 liveRegs.addUnchecked(value);
16969 liveRegs.addUnchecked(temp0);
16970 #ifndef JS_CODEGEN_X86
16971 liveRegs.addUnchecked(temp1);
16972 liveRegs.addUnchecked(temp2);
16973 #endif
16974
16975 Label cacheHit, done;
16976 #ifdef JS_CODEGEN_X86
16977 masm.emitMegamorphicCachedSetSlot(
16978 idVal, obj, temp0, value, liveRegs, &cacheHit,
16979 [](MacroAssembler& masm, const Address& addr, MIRType mirType) {
16980 EmitPreBarrier(masm, addr, mirType);
16981 });
16982 #else
16983 masm.emitMegamorphicCachedSetSlot(
16984 idVal, obj, temp0, temp1, temp2, value, liveRegs, &cacheHit,
16985 [](MacroAssembler& masm, const Address& addr, MIRType mirType) {
16986 EmitPreBarrier(masm, addr, mirType);
16987 });
16988 #endif
16989
16990 pushArg(Imm32(lir->mir()->strict()));
16991 pushArg(ToValue(lir->value()));
16992 pushArg(ToValue(lir->index()));
16993 pushArg(obj);
16994
16995 using Fn = bool (*)(JSContext*, HandleObject, HandleValue, HandleValue, bool);
16996 callVM<Fn, js::jit::SetElementMegamorphic<true>>(lir);
16997
16998 masm.jump(&done);
16999 masm.bind(&cacheHit);
17000
17001 masm.branchPtrInNurseryChunk(Assembler::Equal, obj, temp0, &done);
17002 masm.branchValueIsNurseryCell(Assembler::NotEqual, value, temp0, &done);
17003
17004 // Note: because this is a call-instruction, no registers need to be saved.
17005 MOZ_ASSERT(lir->isCall());
17006 emitPostWriteBarrier(obj);
17007
17008 masm.bind(&done);
17009 }
17010
17011 void CodeGenerator::visitLoadScriptedProxyHandler(
17012 LLoadScriptedProxyHandler* ins) {
17013 Register obj = ToRegister(ins->object());
17014 Register output = ToRegister(ins->output());
17015
17016 masm.loadPtr(Address(obj, ProxyObject::offsetOfReservedSlots()), output);
17017
17018 Label bail;
17019 Address handlerAddr(output, js::detail::ProxyReservedSlots::offsetOfSlot(
17020 ScriptedProxyHandler::HANDLER_EXTRA));
17021 masm.fallibleUnboxObject(handlerAddr, output, &bail);
17022 bailoutFrom(&bail, ins->snapshot());
17023 }
17024
17025 #ifdef JS_PUNBOX64
17026 void CodeGenerator::visitCheckScriptedProxyGetResult(
17027 LCheckScriptedProxyGetResult* ins) {
17028 ValueOperand target = ToValue(ins->target());
17029 ValueOperand value = ToValue(ins->value());
17030 ValueOperand id = ToValue(ins->id());
17031 Register scratch = ToRegister(ins->temp0());
17032 Register scratch2 = ToRegister(ins->temp1());
17033
17034 using Fn = bool (*)(JSContext*, HandleObject, HandleValue, HandleValue,
17035 MutableHandleValue);
17036 OutOfLineCode* ool = oolCallVM<Fn, CheckProxyGetByValueResult>(
17037 ins, ArgList(scratch, id, value), StoreValueTo(value));
17038
17039 masm.unboxObject(target, scratch);
17040 masm.branchTestObjectNeedsProxyResultValidation(Assembler::NonZero, scratch,
17041 scratch2, ool->entry());
17042 masm.bind(ool->rejoin());
17043 }
17044 #endif
17045
17046 void CodeGenerator::visitIdToStringOrSymbol(LIdToStringOrSymbol* ins) {
17047 ValueOperand id = ToValue(ins->idVal());
17048 ValueOperand output = ToOutValue(ins);
17049 Register scratch = ToRegister(ins->temp0());
17050
17051 masm.moveValue(id, output);
17052
17053 Label done, callVM;
17054 Label bail;
17055 {
17056 ScratchTagScope tag(masm, output);
17057 masm.splitTagForTest(output, tag);
17058 masm.branchTestString(Assembler::Equal, tag, &done);
17059 masm.branchTestSymbol(Assembler::Equal, tag, &done);
17060 masm.branchTestInt32(Assembler::NotEqual, tag, &bail);
17061 }
17062
17063 masm.unboxInt32(output, scratch);
17064
17065 using Fn = JSLinearString* (*)(JSContext*, int);
17066 OutOfLineCode* ool = oolCallVM<Fn, Int32ToString<CanGC>>(
17067 ins, ArgList(scratch), StoreRegisterTo(output.scratchReg()));
17068
17069 masm.lookupStaticIntString(scratch, output.scratchReg(),
17070 gen->runtime->staticStrings(), ool->entry());
17071
17072 masm.bind(ool->rejoin());
17073 masm.tagValue(JSVAL_TYPE_STRING, output.scratchReg(), output);
17074 masm.bind(&done);
17075
17076 bailoutFrom(&bail, ins->snapshot());
17077 }
17078
17079 void CodeGenerator::visitLoadFixedSlotV(LLoadFixedSlotV* ins) {
17080 const Register obj = ToRegister(ins->object());
17081 size_t slot = ins->mir()->slot();
17082 ValueOperand result = ToOutValue(ins);
17083
17084 masm.loadValue(Address(obj, NativeObject::getFixedSlotOffset(slot)), result);
17085 }
17086
17087 void CodeGenerator::visitLoadFixedSlotT(LLoadFixedSlotT* ins) {
17088 const Register obj = ToRegister(ins->object());
17089 size_t slot = ins->mir()->slot();
17090 AnyRegister result = ToAnyRegister(ins->output());
17091 MIRType type = ins->mir()->type();
17092
17093 masm.loadUnboxedValue(Address(obj, NativeObject::getFixedSlotOffset(slot)),
17094 type, result);
17095 }
17096
17097 template <typename T>
17098 static void EmitLoadAndUnbox(MacroAssembler& masm, const T& src, MIRType type,
17099 bool fallible, AnyRegister dest, Label* fail) {
17100 if (type == MIRType::Double) {
17101 MOZ_ASSERT(dest.isFloat());
17102 masm.ensureDouble(src, dest.fpu(), fail);
17103 return;
17104 }
17105 if (fallible) {
17106 switch (type) {
17107 case MIRType::Int32:
17108 masm.fallibleUnboxInt32(src, dest.gpr(), fail);
17109 break;
17110 case MIRType::Boolean:
17111 masm.fallibleUnboxBoolean(src, dest.gpr(), fail);
17112 break;
17113 case MIRType::Object:
17114 masm.fallibleUnboxObject(src, dest.gpr(), fail);
17115 break;
17116 case MIRType::String:
17117 masm.fallibleUnboxString(src, dest.gpr(), fail);
17118 break;
17119 case MIRType::Symbol:
17120 masm.fallibleUnboxSymbol(src, dest.gpr(), fail);
17121 break;
17122 case MIRType::BigInt:
17123 masm.fallibleUnboxBigInt(src, dest.gpr(), fail);
17124 break;
17125 default:
17126 MOZ_CRASH("Unexpected MIRType");
17127 }
17128 return;
17129 }
17130 masm.loadUnboxedValue(src, type, dest);
17131 }
17132
17133 void CodeGenerator::visitLoadFixedSlotAndUnbox(LLoadFixedSlotAndUnbox* ins) {
17134 const MLoadFixedSlotAndUnbox* mir = ins->mir();
17135 MIRType type = mir->type();
17136 Register input = ToRegister(ins->object());
17137 AnyRegister result = ToAnyRegister(ins->output());
17138 size_t slot = mir->slot();
17139
17140 Address address(input, NativeObject::getFixedSlotOffset(slot));
17141
17142 Label bail;
17143 EmitLoadAndUnbox(masm, address, type, mir->fallible(), result, &bail);
17144 if (mir->fallible()) {
17145 bailoutFrom(&bail, ins->snapshot());
17146 }
17147 }
17148
17149 void CodeGenerator::visitLoadDynamicSlotAndUnbox(
17150 LLoadDynamicSlotAndUnbox* ins) {
17151 const MLoadDynamicSlotAndUnbox* mir = ins->mir();
17152 MIRType type = mir->type();
17153 Register input = ToRegister(ins->slots());
17154 AnyRegister result = ToAnyRegister(ins->output());
17155 size_t slot = mir->slot();
17156
17157 Address address(input, slot * sizeof(JS::Value));
17158
17159 Label bail;
17160 EmitLoadAndUnbox(masm, address, type, mir->fallible(), result, &bail);
17161 if (mir->fallible()) {
17162 bailoutFrom(&bail, ins->snapshot());
17163 }
17164 }
17165
17166 void CodeGenerator::visitLoadElementAndUnbox(LLoadElementAndUnbox* ins) {
17167 const MLoadElementAndUnbox* mir = ins->mir();
17168 MIRType type = mir->type();
17169 Register elements = ToRegister(ins->elements());
17170 AnyRegister result = ToAnyRegister(ins->output());
17171
17172 Label bail;
17173 if (ins->index()->isConstant()) {
17174 NativeObject::elementsSizeMustNotOverflow();
17175 int32_t offset = ToInt32(ins->index()) * sizeof(Value);
17176 Address address(elements, offset);
17177 EmitLoadAndUnbox(masm, address, type, mir->fallible(), result, &bail);
17178 } else {
17179 BaseObjectElementIndex address(elements, ToRegister(ins->index()));
17180 EmitLoadAndUnbox(masm, address, type, mir->fallible(), result, &bail);
17181 }
17182
17183 if (mir->fallible()) {
17184 bailoutFrom(&bail, ins->snapshot());
17185 }
17186 }
17187
17188 void CodeGenerator::emitMaybeAtomizeSlot(LInstruction* ins, Register stringReg,
17189 Address slotAddr,
17190 TypedOrValueRegister dest) {
17191 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
17192 // This code is called with a non-atomic string in |stringReg|.
17193 // When it returns, |stringReg| contains an unboxed pointer to an
17194 // atomized version of that string, and |slotAddr| contains a
17195 // StringValue pointing to that atom. If |dest| is a ValueOperand,
17196 // it contains the same StringValue; otherwise we assert that |dest|
17197 // is |stringReg|.
17198
17199 saveLive(ins);
17200 pushArg(stringReg);
17201
17202 using Fn = JSAtom* (*)(JSContext*, JSString*);
17203 callVM<Fn, js::AtomizeString>(ins);
17204 StoreRegisterTo(stringReg).generate(this);
17205 restoreLiveIgnore(ins, StoreRegisterTo(stringReg).clobbered());
17206
17207 if (dest.hasValue()) {
17208 masm.moveValue(
17209 TypedOrValueRegister(MIRType::String, AnyRegister(stringReg)),
17210 dest.valueReg());
17211 } else {
17212 MOZ_ASSERT(dest.typedReg().gpr() == stringReg);
17213 }
17214
17215 emitPreBarrier(slotAddr);
17216 masm.storeTypedOrValue(dest, slotAddr);
17217
17218 // We don't need a post-barrier because atoms aren't nursery-allocated.
17219 #ifdef DEBUG
17220 // We need a temp register for the nursery check. Spill something.
17221 AllocatableGeneralRegisterSet allRegs(GeneralRegisterSet::All());
17222 allRegs.take(stringReg);
17223 Register temp = allRegs.takeAny();
17224 masm.push(temp);
17225
17226 Label tenured;
17227 masm.branchPtrInNurseryChunk(Assembler::NotEqual, stringReg, temp,
17228 &tenured);
17229 masm.assumeUnreachable("AtomizeString returned a nursery pointer");
17230 masm.bind(&tenured);
17231
17232 masm.pop(temp);
17233 #endif
17234
17235 masm.jump(ool.rejoin());
17236 });
17237 addOutOfLineCode(ool, ins->mirRaw()->toInstruction());
17238 masm.branchTest32(Assembler::NonZero,
17239 Address(stringReg, JSString::offsetOfFlags()),
17240 Imm32(JSString::ATOM_BIT), ool->rejoin());
17241
17242 masm.branchTest32(Assembler::Zero,
17243 Address(stringReg, JSString::offsetOfFlags()),
17244 Imm32(JSString::ATOM_REF_BIT), ool->entry());
17245 masm.loadPtr(Address(stringReg, JSAtomRefString::offsetOfAtom()), stringReg);
17246
17247 if (dest.hasValue()) {
17248 masm.moveValue(
17249 TypedOrValueRegister(MIRType::String, AnyRegister(stringReg)),
17250 dest.valueReg());
17251 } else {
17252 MOZ_ASSERT(dest.typedReg().gpr() == stringReg);
17253 }
17254
17255 emitPreBarrier(slotAddr);
17256 masm.storeTypedOrValue(dest, slotAddr);
17257
17258 masm.bind(ool->rejoin());
17259 }
17260
17261 void CodeGenerator::visitLoadFixedSlotAndAtomize(
17262 LLoadFixedSlotAndAtomize* ins) {
17263 Register obj = ToRegister(ins->object());
17264 Register temp = ToRegister(ins->temp0());
17265 size_t slot = ins->mir()->slot();
17266 ValueOperand result = ToOutValue(ins);
17267
17268 Address slotAddr(obj, NativeObject::getFixedSlotOffset(slot));
17269 masm.loadValue(slotAddr, result);
17270
17271 Label notString;
17272 masm.branchTestString(Assembler::NotEqual, result, &notString);
17273 masm.unboxString(result, temp);
17274 emitMaybeAtomizeSlot(ins, temp, slotAddr, result);
17275 masm.bind(&notString);
17276 }
17277
17278 void CodeGenerator::visitLoadDynamicSlotAndAtomize(
17279 LLoadDynamicSlotAndAtomize* ins) {
17280 ValueOperand result = ToOutValue(ins);
17281 Register temp = ToRegister(ins->temp0());
17282 Register base = ToRegister(ins->input());
17283 int32_t offset = ins->mir()->slot() * sizeof(js::Value);
17284
17285 Address slotAddr(base, offset);
17286 masm.loadValue(slotAddr, result);
17287
17288 Label notString;
17289 masm.branchTestString(Assembler::NotEqual, result, &notString);
17290 masm.unboxString(result, temp);
17291 emitMaybeAtomizeSlot(ins, temp, slotAddr, result);
17292 masm.bind(&notString);
17293 }
17294
17295 void CodeGenerator::visitLoadFixedSlotUnboxAndAtomize(
17296 LLoadFixedSlotUnboxAndAtomize* ins) {
17297 const MLoadFixedSlotAndUnbox* mir = ins->mir();
17298 MOZ_ASSERT(mir->type() == MIRType::String);
17299 Register input = ToRegister(ins->object());
17300 AnyRegister result = ToAnyRegister(ins->output());
17301 size_t slot = mir->slot();
17302
17303 Address slotAddr(input, NativeObject::getFixedSlotOffset(slot));
17304
17305 Label bail;
17306 EmitLoadAndUnbox(masm, slotAddr, MIRType::String, mir->fallible(), result,
17307 &bail);
17308 emitMaybeAtomizeSlot(ins, result.gpr(), slotAddr,
17309 TypedOrValueRegister(MIRType::String, result));
17310
17311 if (mir->fallible()) {
17312 bailoutFrom(&bail, ins->snapshot());
17313 }
17314 }
17315
17316 void CodeGenerator::visitLoadDynamicSlotUnboxAndAtomize(
17317 LLoadDynamicSlotUnboxAndAtomize* ins) {
17318 const MLoadDynamicSlotAndUnbox* mir = ins->mir();
17319 MOZ_ASSERT(mir->type() == MIRType::String);
17320 Register input = ToRegister(ins->slots());
17321 AnyRegister result = ToAnyRegister(ins->output());
17322 size_t slot = mir->slot();
17323
17324 Address slotAddr(input, slot * sizeof(JS::Value));
17325
17326 Label bail;
17327 EmitLoadAndUnbox(masm, slotAddr, MIRType::String, mir->fallible(), result,
17328 &bail);
17329 emitMaybeAtomizeSlot(ins, result.gpr(), slotAddr,
17330 TypedOrValueRegister(MIRType::String, result));
17331
17332 if (mir->fallible()) {
17333 bailoutFrom(&bail, ins->snapshot());
17334 }
17335 }
17336
17337 void CodeGenerator::visitAddAndStoreSlot(LAddAndStoreSlot* ins) {
17338 Register obj = ToRegister(ins->object());
17339 ValueOperand value = ToValue(ins->value());
17340 Register maybeTemp = ToTempRegisterOrInvalid(ins->temp0());
17341
17342 Shape* shape = ins->mir()->shape();
17343 masm.storeObjShape(shape, obj, [](MacroAssembler& masm, const Address& addr) {
17344 EmitPreBarrier(masm, addr, MIRType::Shape);
17345 });
17346
17347 // Perform the store. No pre-barrier required since this is a new
17348 // initialization.
17349
17350 uint32_t offset = ins->mir()->slotOffset();
17351 if (ins->mir()->kind() == MAddAndStoreSlot::Kind::FixedSlot) {
17352 Address slot(obj, offset);
17353 masm.storeValue(value, slot);
17354 } else {
17355 masm.loadPtr(Address(obj, NativeObject::offsetOfSlots()), maybeTemp);
17356 Address slot(maybeTemp, offset);
17357 masm.storeValue(value, slot);
17358 }
17359 }
17360
17361 void CodeGenerator::visitAllocateAndStoreSlot(LAllocateAndStoreSlot* ins) {
17362 Register obj = ToRegister(ins->object());
17363 ValueOperand value = ToValue(ins->value());
17364 Register temp0 = ToRegister(ins->temp0());
17365 Register temp1 = ToRegister(ins->temp1());
17366
17367 masm.Push(obj);
17368 masm.Push(value);
17369
17370 using Fn = bool (*)(JSContext* cx, NativeObject* obj, uint32_t newCount);
17371 masm.setupAlignedABICall();
17372 masm.loadJSContext(temp0);
17373 masm.passABIArg(temp0);
17374 masm.passABIArg(obj);
17375 masm.move32(Imm32(ins->mir()->numNewSlots()), temp1);
17376 masm.passABIArg(temp1);
17377 masm.callWithABI<Fn, NativeObject::growSlotsPure>();
17378 masm.storeCallPointerResult(temp0);
17379
17380 masm.Pop(value);
17381 masm.Pop(obj);
17382
17383 bailoutIfFalseBool(temp0, ins->snapshot());
17384
17385 masm.storeObjShape(ins->mir()->shape(), obj,
17386 [](MacroAssembler& masm, const Address& addr) {
17387 EmitPreBarrier(masm, addr, MIRType::Shape);
17388 });
17389
17390 // Perform the store. No pre-barrier required since this is a new
17391 // initialization.
17392 masm.loadPtr(Address(obj, NativeObject::offsetOfSlots()), temp0);
17393 Address slot(temp0, ins->mir()->slotOffset());
17394 masm.storeValue(value, slot);
17395 }
17396
17397 void CodeGenerator::visitAddSlotAndCallAddPropHook(
17398 LAddSlotAndCallAddPropHook* ins) {
17399 Register obj = ToRegister(ins->object());
17400 ValueOperand value = ToValue(ins->value());
17401
17402 pushArg(ImmGCPtr(ins->mir()->shape()));
17403 pushArg(value);
17404 pushArg(obj);
17405
17406 using Fn =
17407 bool (*)(JSContext*, Handle<NativeObject*>, HandleValue, Handle<Shape*>);
17408 callVM<Fn, AddSlotAndCallAddPropHook>(ins);
17409 }
17410
17411 void CodeGenerator::visitStoreFixedSlotV(LStoreFixedSlotV* ins) {
17412 Register obj = ToRegister(ins->obj());
17413 size_t slot = ins->mir()->slot();
17414
17415 ValueOperand value = ToValue(ins->value());
17416
17417 Address address(obj, NativeObject::getFixedSlotOffset(slot));
17418 if (ins->mir()->needsBarrier()) {
17419 emitPreBarrier(address);
17420 }
17421
17422 masm.storeValue(value, address);
17423 }
17424
17425 void CodeGenerator::visitStoreFixedSlotT(LStoreFixedSlotT* ins) {
17426 const Register obj = ToRegister(ins->obj());
17427 size_t slot = ins->mir()->slot();
17428
17429 const LAllocation* value = ins->value();
17430 MIRType valueType = ins->mir()->value()->type();
17431
17432 Address address(obj, NativeObject::getFixedSlotOffset(slot));
17433 if (ins->mir()->needsBarrier()) {
17434 emitPreBarrier(address);
17435 }
17436
17437 ConstantOrRegister nvalue =
17438 value->isConstant()
17439 ? ConstantOrRegister(value->toConstant()->toJSValue())
17440 : TypedOrValueRegister(valueType, ToAnyRegister(value));
17441 masm.storeConstantOrRegister(nvalue, address);
17442 }
17443
17444 void CodeGenerator::visitGetNameCache(LGetNameCache* ins) {
17445 LiveRegisterSet liveRegs = ins->safepoint()->liveRegs();
17446 Register envChain = ToRegister(ins->envObj());
17447 ValueOperand output = ToOutValue(ins);
17448 Register temp = ToRegister(ins->temp0());
17449
17450 IonGetNameIC ic(liveRegs, envChain, output, temp);
17451 addIC(ins, allocateIC(ic));
17452 }
17453
17454 void CodeGenerator::addGetPropertyCache(LInstruction* ins,
17455 LiveRegisterSet liveRegs,
17456 TypedOrValueRegister value,
17457 const ConstantOrRegister& id,
17458 ValueOperand output) {
17459 CacheKind kind = CacheKind::GetElem;
17460 if (id.constant() && id.value().isString()) {
17461 JSString* idString = id.value().toString();
17462 if (idString->isAtom() && !idString->asAtom().isIndex()) {
17463 kind = CacheKind::GetProp;
17464 }
17465 }
17466 IonGetPropertyIC cache(kind, liveRegs, value, id, output);
17467 addIC(ins, allocateIC(cache));
17468 }
17469
17470 void CodeGenerator::addSetPropertyCache(LInstruction* ins,
17471 LiveRegisterSet liveRegs,
17472 Register objReg, Register temp,
17473 const ConstantOrRegister& id,
17474 const ConstantOrRegister& value,
17475 bool strict) {
17476 CacheKind kind = CacheKind::SetElem;
17477 if (id.constant() && id.value().isString()) {
17478 JSString* idString = id.value().toString();
17479 if (idString->isAtom() && !idString->asAtom().isIndex()) {
17480 kind = CacheKind::SetProp;
17481 }
17482 }
17483 IonSetPropertyIC cache(kind, liveRegs, objReg, temp, id, value, strict);
17484 addIC(ins, allocateIC(cache));
17485 }
17486
17487 ConstantOrRegister CodeGenerator::toConstantOrRegister(LInstruction* lir,
17488 size_t n, MIRType type) {
17489 if (type == MIRType::Value) {
17490 return TypedOrValueRegister(ToValue(lir->getBoxOperand(n)));
17491 }
17492
17493 const LAllocation* value = lir->getOperand(n);
17494 if (value->isConstant()) {
17495 return ConstantOrRegister(value->toConstant()->toJSValue());
17496 }
17497
17498 return TypedOrValueRegister(type, ToAnyRegister(value));
17499 }
17500
17501 void CodeGenerator::visitGetPropertyCache(LGetPropertyCache* ins) {
17502 LiveRegisterSet liveRegs = ins->safepoint()->liveRegs();
17503 TypedOrValueRegister value =
17504 toConstantOrRegister(ins, LGetPropertyCache::ValueIndex,
17505 ins->mir()->value()->type())
17506 .reg();
17507 ConstantOrRegister id = toConstantOrRegister(ins, LGetPropertyCache::IdIndex,
17508 ins->mir()->idval()->type());
17509 ValueOperand output = ToOutValue(ins);
17510 addGetPropertyCache(ins, liveRegs, value, id, output);
17511 }
17512
17513 void CodeGenerator::visitGetPropSuperCache(LGetPropSuperCache* ins) {
17514 LiveRegisterSet liveRegs = ins->safepoint()->liveRegs();
17515 Register obj = ToRegister(ins->obj());
17516 TypedOrValueRegister receiver =
17517 toConstantOrRegister(ins, LGetPropSuperCache::ReceiverIndex,
17518 ins->mir()->receiver()->type())
17519 .reg();
17520 ConstantOrRegister id = toConstantOrRegister(ins, LGetPropSuperCache::IdIndex,
17521 ins->mir()->idval()->type());
17522 ValueOperand output = ToOutValue(ins);
17523
17524 CacheKind kind = CacheKind::GetElemSuper;
17525 if (id.constant() && id.value().isString()) {
17526 JSString* idString = id.value().toString();
17527 if (idString->isAtom() && !idString->asAtom().isIndex()) {
17528 kind = CacheKind::GetPropSuper;
17529 }
17530 }
17531
17532 IonGetPropSuperIC cache(kind, liveRegs, obj, receiver, id, output);
17533 addIC(ins, allocateIC(cache));
17534 }
17535
17536 void CodeGenerator::visitBindNameCache(LBindNameCache* ins) {
17537 LiveRegisterSet liveRegs = ins->safepoint()->liveRegs();
17538 Register envChain = ToRegister(ins->environmentChain());
17539 Register output = ToRegister(ins->output());
17540 Register temp = ToRegister(ins->temp0());
17541
17542 IonBindNameIC ic(liveRegs, envChain, output, temp);
17543 addIC(ins, allocateIC(ic));
17544 }
17545
17546 void CodeGenerator::visitHasOwnCache(LHasOwnCache* ins) {
17547 LiveRegisterSet liveRegs = ins->safepoint()->liveRegs();
17548 TypedOrValueRegister value =
17549 toConstantOrRegister(ins, LHasOwnCache::ValueIndex,
17550 ins->mir()->value()->type())
17551 .reg();
17552 TypedOrValueRegister id = toConstantOrRegister(ins, LHasOwnCache::IdIndex,
17553 ins->mir()->idval()->type())
17554 .reg();
17555 Register output = ToRegister(ins->output());
17556
17557 IonHasOwnIC cache(liveRegs, value, id, output);
17558 addIC(ins, allocateIC(cache));
17559 }
17560
17561 void CodeGenerator::visitCheckPrivateFieldCache(LCheckPrivateFieldCache* ins) {
17562 LiveRegisterSet liveRegs = ins->safepoint()->liveRegs();
17563 TypedOrValueRegister value =
17564 toConstantOrRegister(ins, LCheckPrivateFieldCache::ValueIndex,
17565 ins->mir()->value()->type())
17566 .reg();
17567 TypedOrValueRegister id =
17568 toConstantOrRegister(ins, LCheckPrivateFieldCache::IdIndex,
17569 ins->mir()->idval()->type())
17570 .reg();
17571 Register output = ToRegister(ins->output());
17572
17573 IonCheckPrivateFieldIC cache(liveRegs, value, id, output);
17574 addIC(ins, allocateIC(cache));
17575 }
17576
17577 void CodeGenerator::visitNewPrivateName(LNewPrivateName* ins) {
17578 pushArg(ImmGCPtr(ins->mir()->name()));
17579
17580 using Fn = JS::Symbol* (*)(JSContext*, Handle<JSAtom*>);
17581 callVM<Fn, NewPrivateName>(ins);
17582 }
17583
17584 void CodeGenerator::visitCallDeleteProperty(LCallDeleteProperty* lir) {
17585 pushArg(ImmGCPtr(lir->mir()->name()));
17586 pushArg(ToValue(lir->value()));
17587
17588 using Fn = bool (*)(JSContext*, HandleValue, Handle<PropertyName*>, bool*);
17589 if (lir->mir()->strict()) {
17590 callVM<Fn, DelPropOperation<true>>(lir);
17591 } else {
17592 callVM<Fn, DelPropOperation<false>>(lir);
17593 }
17594 }
17595
17596 void CodeGenerator::visitCallDeleteElement(LCallDeleteElement* lir) {
17597 pushArg(ToValue(lir->index()));
17598 pushArg(ToValue(lir->value()));
17599
17600 using Fn = bool (*)(JSContext*, HandleValue, HandleValue, bool*);
17601 if (lir->mir()->strict()) {
17602 callVM<Fn, DelElemOperation<true>>(lir);
17603 } else {
17604 callVM<Fn, DelElemOperation<false>>(lir);
17605 }
17606 }
17607
17608 void CodeGenerator::visitObjectToIterator(LObjectToIterator* lir) {
17609 Register obj = ToRegister(lir->object());
17610 Register iterObj = ToRegister(lir->output());
17611 Register temp = ToRegister(lir->temp0());
17612 Register temp2 = ToRegister(lir->temp1());
17613 Register temp3 = ToRegister(lir->temp2());
17614
17615 using Fn = PropertyIteratorObject* (*)(JSContext*, HandleObject);
17616 OutOfLineCode* ool = (lir->mir()->wantsIndices())
17617 ? oolCallVM<Fn, GetIteratorWithIndices>(
17618 lir, ArgList(obj), StoreRegisterTo(iterObj))
17619 : oolCallVM<Fn, GetIterator>(
17620 lir, ArgList(obj), StoreRegisterTo(iterObj));
17621
17622 masm.maybeLoadIteratorFromShape(obj, iterObj, temp, temp2, temp3,
17623 ool->entry());
17624
17625 Register nativeIter = temp;
17626 masm.loadPrivate(
17627 Address(iterObj, PropertyIteratorObject::offsetOfIteratorSlot()),
17628 nativeIter);
17629
17630 if (lir->mir()->wantsIndices()) {
17631 // At least one consumer of the output of this iterator has been optimized
17632 // to use iterator indices. If the cached iterator doesn't include indices,
17633 // but it was marked to indicate that we can create them if needed, then we
17634 // do a VM call to replace the cached iterator with a fresh iterator
17635 // including indices.
17636 masm.branchNativeIteratorIndices(Assembler::Equal, nativeIter, temp2,
17637 NativeIteratorIndices::AvailableOnRequest,
17638 ool->entry());
17639 }
17640
17641 Address iterFlagsAddr(nativeIter, NativeIterator::offsetOfFlagsAndCount());
17642 masm.storePtr(
17643 obj, Address(nativeIter, NativeIterator::offsetOfObjectBeingIterated()));
17644 masm.or32(Imm32(NativeIterator::Flags::Active), iterFlagsAddr);
17645
17646 Register enumeratorsAddr = temp2;
17647 masm.movePtr(ImmPtr(lir->mir()->enumeratorsAddr()), enumeratorsAddr);
17648 masm.registerIterator(enumeratorsAddr, nativeIter, temp3);
17649
17650 // Generate post-write barrier for storing to |iterObj->objectBeingIterated_|.
17651 // We already know that |iterObj| is tenured, so we only have to check |obj|.
17652 Label skipBarrier;
17653 masm.branchPtrInNurseryChunk(Assembler::NotEqual, obj, temp2, &skipBarrier);
17654 {
17655 LiveRegisterSet save = liveVolatileRegs(lir);
17656 save.takeUnchecked(temp);
17657 save.takeUnchecked(temp2);
17658 save.takeUnchecked(temp3);
17659 if (iterObj.volatile_()) {
17660 save.addUnchecked(iterObj);
17661 }
17662
17663 masm.PushRegsInMask(save);
17664 emitPostWriteBarrier(iterObj);
17665 masm.PopRegsInMask(save);
17666 }
17667 masm.bind(&skipBarrier);
17668
17669 masm.bind(ool->rejoin());
17670 }
17671
17672 void CodeGenerator::visitValueToIterator(LValueToIterator* lir) {
17673 pushArg(ToValue(lir->value()));
17674
17675 using Fn = PropertyIteratorObject* (*)(JSContext*, HandleValue);
17676 callVM<Fn, ValueToIterator>(lir);
17677 }
17678
17679 void CodeGenerator::visitIteratorHasIndicesAndBranch(
17680 LIteratorHasIndicesAndBranch* lir) {
17681 Register iterator = ToRegister(lir->iterator());
17682 Register object = ToRegister(lir->object());
17683 Register temp = ToRegister(lir->temp0());
17684 Register temp2 = ToRegister(lir->temp1());
17685 Label* ifTrue = getJumpLabelForBranch(lir->ifTrue());
17686 Label* ifFalse = getJumpLabelForBranch(lir->ifFalse());
17687
17688 // Check that the iterator has indices available.
17689 Address nativeIterAddr(iterator,
17690 PropertyIteratorObject::offsetOfIteratorSlot());
17691 masm.loadPrivate(nativeIterAddr, temp);
17692 masm.branchNativeIteratorIndices(Assembler::NotEqual, temp, temp2,
17693 NativeIteratorIndices::Valid, ifFalse);
17694
17695 // Guard that the first shape stored in the iterator matches the current
17696 // shape of the iterated object.
17697 Address firstShapeAddr(temp, NativeIterator::offsetOfFirstShape());
17698 masm.loadPtr(firstShapeAddr, temp);
17699 masm.branchTestObjShape(Assembler::NotEqual, object, temp, temp2, object,
17700 ifFalse);
17701
17702 if (!isNextBlock(lir->ifTrue()->lir())) {
17703 masm.jump(ifTrue);
17704 }
17705 }
17706
17707 void CodeGenerator::visitLoadSlotByIteratorIndex(
17708 LLoadSlotByIteratorIndex* lir) {
17709 Register object = ToRegister(lir->object());
17710 Register iterator = ToRegister(lir->iterator());
17711 Register temp = ToRegister(lir->temp0());
17712 Register temp2 = ToRegister(lir->temp1());
17713 ValueOperand result = ToOutValue(lir);
17714
17715 masm.extractCurrentIndexAndKindFromIterator(iterator, temp, temp2);
17716
17717 Label notDynamicSlot, notFixedSlot, done;
17718 masm.branch32(Assembler::NotEqual, temp2,
17719 Imm32(uint32_t(PropertyIndex::Kind::DynamicSlot)),
17720 &notDynamicSlot);
17721 masm.loadPtr(Address(object, NativeObject::offsetOfSlots()), temp2);
17722 masm.loadValue(BaseValueIndex(temp2, temp), result);
17723 masm.jump(&done);
17724
17725 masm.bind(&notDynamicSlot);
17726 masm.branch32(Assembler::NotEqual, temp2,
17727 Imm32(uint32_t(PropertyIndex::Kind::FixedSlot)), &notFixedSlot);
17728 // Fixed slot
17729 masm.loadValue(BaseValueIndex(object, temp, sizeof(NativeObject)), result);
17730 masm.jump(&done);
17731 masm.bind(&notFixedSlot);
17732
17733 #ifdef DEBUG
17734 Label kindOkay;
17735 masm.branch32(Assembler::Equal, temp2,
17736 Imm32(uint32_t(PropertyIndex::Kind::Element)), &kindOkay);
17737 masm.assumeUnreachable("Invalid PropertyIndex::Kind");
17738 masm.bind(&kindOkay);
17739 #endif
17740
17741 // Dense element
17742 masm.loadPtr(Address(object, NativeObject::offsetOfElements()), temp2);
17743 Label indexOkay;
17744 Address initLength(temp2, ObjectElements::offsetOfInitializedLength());
17745 masm.branch32(Assembler::Above, initLength, temp, &indexOkay);
17746 masm.assumeUnreachable("Dense element out of bounds");
17747 masm.bind(&indexOkay);
17748
17749 masm.loadValue(BaseObjectElementIndex(temp2, temp), result);
17750 masm.branchTestMagicValue(Assembler::NotEqual, result, JS_ELEMENTS_HOLE,
17751 &done);
17752 masm.assumeUnreachable("Dense element is a hole");
17753 masm.bind(&done);
17754 }
17755
17756 void CodeGenerator::visitStoreSlotByIteratorIndex(
17757 LStoreSlotByIteratorIndex* lir) {
17758 Register object = ToRegister(lir->object());
17759 Register iterator = ToRegister(lir->iterator());
17760 ValueOperand value = ToValue(lir->value());
17761 Register temp = ToRegister(lir->temp0());
17762 Register temp2 = ToRegister(lir->temp1());
17763
17764 masm.extractCurrentIndexAndKindFromIterator(iterator, temp, temp2);
17765
17766 Label notDynamicSlot, notFixedSlot, done, doStore;
17767 masm.branch32(Assembler::NotEqual, temp2,
17768 Imm32(uint32_t(PropertyIndex::Kind::DynamicSlot)),
17769 &notDynamicSlot);
17770 masm.loadPtr(Address(object, NativeObject::offsetOfSlots()), temp2);
17771 masm.computeEffectiveAddress(BaseValueIndex(temp2, temp), temp);
17772 masm.jump(&doStore);
17773
17774 masm.bind(&notDynamicSlot);
17775 masm.branch32(Assembler::NotEqual, temp2,
17776 Imm32(uint32_t(PropertyIndex::Kind::FixedSlot)), &notFixedSlot);
17777 // Fixed slot
17778 masm.computeEffectiveAddress(
17779 BaseValueIndex(object, temp, sizeof(NativeObject)), temp);
17780 masm.jump(&doStore);
17781 masm.bind(&notFixedSlot);
17782
17783 #ifdef DEBUG
17784 Label kindOkay;
17785 masm.branch32(Assembler::Equal, temp2,
17786 Imm32(uint32_t(PropertyIndex::Kind::Element)), &kindOkay);
17787 masm.assumeUnreachable("Invalid PropertyIndex::Kind");
17788 masm.bind(&kindOkay);
17789 #endif
17790
17791 // Dense element
17792 masm.loadPtr(Address(object, NativeObject::offsetOfElements()), temp2);
17793 Label indexOkay;
17794 Address initLength(temp2, ObjectElements::offsetOfInitializedLength());
17795 masm.branch32(Assembler::Above, initLength, temp, &indexOkay);
17796 masm.assumeUnreachable("Dense element out of bounds");
17797 masm.bind(&indexOkay);
17798
17799 BaseObjectElementIndex elementAddress(temp2, temp);
17800 masm.computeEffectiveAddress(elementAddress, temp);
17801
17802 masm.bind(&doStore);
17803 Address storeAddress(temp, 0);
17804 emitPreBarrier(storeAddress);
17805 masm.storeValue(value, storeAddress);
17806
17807 masm.branchPtrInNurseryChunk(Assembler::Equal, object, temp2, &done);
17808 masm.branchValueIsNurseryCell(Assembler::NotEqual, value, temp2, &done);
17809
17810 saveVolatile(temp2);
17811 emitPostWriteBarrier(object);
17812 restoreVolatile(temp2);
17813
17814 masm.bind(&done);
17815 }
17816
17817 void CodeGenerator::visitSetPropertyCache(LSetPropertyCache* ins) {
17818 LiveRegisterSet liveRegs = ins->safepoint()->liveRegs();
17819 Register objReg = ToRegister(ins->object());
17820 Register temp = ToRegister(ins->temp0());
17821
17822 ConstantOrRegister id = toConstantOrRegister(ins, LSetPropertyCache::IdIndex,
17823 ins->mir()->idval()->type());
17824 ConstantOrRegister value = toConstantOrRegister(
17825 ins, LSetPropertyCache::ValueIndex, ins->mir()->value()->type());
17826
17827 addSetPropertyCache(ins, liveRegs, objReg, temp, id, value,
17828 ins->mir()->strict());
17829 }
17830
17831 void CodeGenerator::visitThrow(LThrow* lir) {
17832 pushArg(ToValue(lir->value()));
17833
17834 using Fn = bool (*)(JSContext*, HandleValue);
17835 callVM<Fn, js::ThrowOperation>(lir);
17836 }
17837
17838 void CodeGenerator::visitThrowWithStack(LThrowWithStack* lir) {
17839 pushArg(ToValue(lir->stack()));
17840 pushArg(ToValue(lir->value()));
17841
17842 using Fn = bool (*)(JSContext*, HandleValue, HandleValue);
17843 callVM<Fn, js::ThrowWithStackOperation>(lir);
17844 }
17845
17846 void CodeGenerator::emitTypeOfJSType(JSValueType type, Register output) {
17847 switch (type) {
17848 case JSVAL_TYPE_OBJECT:
17849 masm.move32(Imm32(JSTYPE_OBJECT), output);
17850 break;
17851 case JSVAL_TYPE_DOUBLE:
17852 case JSVAL_TYPE_INT32:
17853 masm.move32(Imm32(JSTYPE_NUMBER), output);
17854 break;
17855 case JSVAL_TYPE_BOOLEAN:
17856 masm.move32(Imm32(JSTYPE_BOOLEAN), output);
17857 break;
17858 case JSVAL_TYPE_UNDEFINED:
17859 masm.move32(Imm32(JSTYPE_UNDEFINED), output);
17860 break;
17861 case JSVAL_TYPE_NULL:
17862 masm.move32(Imm32(JSTYPE_OBJECT), output);
17863 break;
17864 case JSVAL_TYPE_STRING:
17865 masm.move32(Imm32(JSTYPE_STRING), output);
17866 break;
17867 case JSVAL_TYPE_SYMBOL:
17868 masm.move32(Imm32(JSTYPE_SYMBOL), output);
17869 break;
17870 case JSVAL_TYPE_BIGINT:
17871 masm.move32(Imm32(JSTYPE_BIGINT), output);
17872 break;
17873 default:
17874 MOZ_CRASH("Unsupported JSValueType");
17875 }
17876 }
17877
17878 void CodeGenerator::emitTypeOfCheck(JSValueType type, Register tag,
17879 Register output, Label* done,
17880 Label* oolObject) {
17881 Label notMatch;
17882 switch (type) {
17883 case JSVAL_TYPE_OBJECT:
17884 // The input may be a callable object (result is "function") or
17885 // may emulate undefined (result is "undefined"). Use an OOL path.
17886 masm.branchTestObject(Assembler::Equal, tag, oolObject);
17887 return;
17888 case JSVAL_TYPE_DOUBLE:
17889 case JSVAL_TYPE_INT32:
17890 masm.branchTestNumber(Assembler::NotEqual, tag, &notMatch);
17891 break;
17892 default:
17893 masm.branchTestType(Assembler::NotEqual, tag, type, &notMatch);
17894 break;
17895 }
17896
17897 emitTypeOfJSType(type, output);
17898 masm.jump(done);
17899 masm.bind(&notMatch);
17900 }
17901
17902 void CodeGenerator::visitTypeOfV(LTypeOfV* lir) {
17903 ValueOperand value = ToValue(lir->input());
17904 Register output = ToRegister(lir->output());
17905 Register tag = masm.extractTag(value, output);
17906
17907 Label done;
17908
17909 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
17910 ValueOperand input = ToValue(lir->input());
17911 Register temp = ToTempUnboxRegister(lir->temp0());
17912 Register output = ToRegister(lir->output());
17913
17914 Register obj = masm.extractObject(input, temp);
17915 emitTypeOfObject(obj, output, ool.rejoin());
17916 masm.jump(ool.rejoin());
17917 });
17918 addOutOfLineCode(ool, lir->mir());
17919
17920 const std::initializer_list<JSValueType> defaultOrder = {
17921 JSVAL_TYPE_OBJECT, JSVAL_TYPE_DOUBLE, JSVAL_TYPE_UNDEFINED,
17922 JSVAL_TYPE_NULL, JSVAL_TYPE_BOOLEAN, JSVAL_TYPE_STRING,
17923 JSVAL_TYPE_SYMBOL, JSVAL_TYPE_BIGINT};
17924
17925 mozilla::EnumSet<JSValueType, uint32_t> remaining(defaultOrder);
17926
17927 // Generate checks for previously observed types first.
17928 // The TypeDataList is sorted by descending frequency.
17929 for (auto& observed : lir->mir()->observedTypes()) {
17930 JSValueType type = observed.type();
17931
17932 // Unify number types.
17933 if (type == JSVAL_TYPE_INT32) {
17934 type = JSVAL_TYPE_DOUBLE;
17935 }
17936
17937 remaining -= type;
17938
17939 emitTypeOfCheck(type, tag, output, &done, ool->entry());
17940 }
17941
17942 // Generate checks for remaining types.
17943 for (auto type : defaultOrder) {
17944 if (!remaining.contains(type)) {
17945 continue;
17946 }
17947 remaining -= type;
17948
17949 if (remaining.isEmpty() && type != JSVAL_TYPE_OBJECT) {
17950 // We can skip the check for the last remaining type, unless the type is
17951 // JSVAL_TYPE_OBJECT, which may have to go through the OOL path.
17952 #ifdef DEBUG
17953 emitTypeOfCheck(type, tag, output, &done, ool->entry());
17954 masm.assumeUnreachable("Unexpected Value type in visitTypeOfV");
17955 #else
17956 emitTypeOfJSType(type, output);
17957 #endif
17958 } else {
17959 emitTypeOfCheck(type, tag, output, &done, ool->entry());
17960 }
17961 }
17962 MOZ_ASSERT(remaining.isEmpty());
17963
17964 masm.bind(&done);
17965 masm.bind(ool->rejoin());
17966 }
17967
17968 void CodeGenerator::emitTypeOfObject(Register obj, Register output,
17969 Label* done) {
17970 Label slowCheck, isObject, isCallable, isUndefined;
17971 masm.typeOfObject(obj, output, &slowCheck, &isObject, &isCallable,
17972 &isUndefined);
17973
17974 masm.bind(&isCallable);
17975 masm.move32(Imm32(JSTYPE_FUNCTION), output);
17976 masm.jump(done);
17977
17978 masm.bind(&isUndefined);
17979 masm.move32(Imm32(JSTYPE_UNDEFINED), output);
17980 masm.jump(done);
17981
17982 masm.bind(&isObject);
17983 masm.move32(Imm32(JSTYPE_OBJECT), output);
17984 masm.jump(done);
17985
17986 masm.bind(&slowCheck);
17987
17988 saveVolatile(output);
17989 using Fn = JSType (*)(JSObject*);
17990 masm.setupAlignedABICall();
17991 masm.passABIArg(obj);
17992 masm.callWithABI<Fn, js::TypeOfObject>();
17993 masm.storeCallInt32Result(output);
17994 restoreVolatile(output);
17995 }
17996
17997 void CodeGenerator::visitTypeOfO(LTypeOfO* lir) {
17998 Register obj = ToRegister(lir->object());
17999 Register output = ToRegister(lir->output());
18000
18001 Label done;
18002 emitTypeOfObject(obj, output, &done);
18003 masm.bind(&done);
18004 }
18005
18006 void CodeGenerator::visitTypeOfName(LTypeOfName* lir) {
18007 Register input = ToRegister(lir->input());
18008 Register output = ToRegister(lir->output());
18009
18010 #ifdef DEBUG
18011 Label ok;
18012 masm.branch32(Assembler::Below, input, Imm32(JSTYPE_LIMIT), &ok);
18013 masm.assumeUnreachable("bad JSType");
18014 masm.bind(&ok);
18015 #endif
18016
18017 static_assert(JSTYPE_UNDEFINED == 0);
18018
18019 masm.movePtr(ImmPtr(&gen->runtime->names().undefined), output);
18020 masm.loadPtr(BaseIndex(output, input, ScalePointer), output);
18021 }
18022
18023 void CodeGenerator::emitTypeOfIsObjectOOL(MTypeOfIs* mir, Register obj,
18024 Register output) {
18025 saveVolatile(output);
18026 using Fn = JSType (*)(JSObject*);
18027 masm.setupAlignedABICall();
18028 masm.passABIArg(obj);
18029 masm.callWithABI<Fn, js::TypeOfObject>();
18030 masm.storeCallInt32Result(output);
18031 restoreVolatile(output);
18032
18033 auto cond = JSOpToCondition(mir->jsop(), /* isSigned = */ false);
18034 masm.cmp32Set(cond, output, Imm32(mir->jstype()), output);
18035 }
18036
18037 void CodeGenerator::emitTypeOfIsObject(MTypeOfIs* mir, Register obj,
18038 Register output, Label* success,
18039 Label* fail, Label* slowCheck) {
18040 Label* isObject = fail;
18041 Label* isFunction = fail;
18042 Label* isUndefined = fail;
18043
18044 switch (mir->jstype()) {
18045 case JSTYPE_UNDEFINED:
18046 isUndefined = success;
18047 break;
18048
18049 case JSTYPE_OBJECT:
18050 isObject = success;
18051 break;
18052
18053 case JSTYPE_FUNCTION:
18054 isFunction = success;
18055 break;
18056
18057 case JSTYPE_STRING:
18058 case JSTYPE_NUMBER:
18059 case JSTYPE_BOOLEAN:
18060 case JSTYPE_SYMBOL:
18061 case JSTYPE_BIGINT:
18062 case JSTYPE_LIMIT:
18063 MOZ_CRASH("Primitive type");
18064 }
18065
18066 masm.typeOfObject(obj, output, slowCheck, isObject, isFunction, isUndefined);
18067
18068 auto op = mir->jsop();
18069
18070 Label done;
18071 masm.bind(fail);
18072 masm.move32(Imm32(op == JSOp::Ne || op == JSOp::StrictNe), output);
18073 masm.jump(&done);
18074 masm.bind(success);
18075 masm.move32(Imm32(op == JSOp::Eq || op == JSOp::StrictEq), output);
18076 masm.bind(&done);
18077 }
18078
18079 void CodeGenerator::visitTypeOfIsNonPrimitiveV(LTypeOfIsNonPrimitiveV* lir) {
18080 ValueOperand input = ToValue(lir->input());
18081 Register output = ToRegister(lir->output());
18082 Register temp = ToTempUnboxRegister(lir->temp0());
18083
18084 auto* mir = lir->mir();
18085
18086 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
18087 ValueOperand input = ToValue(lir->input());
18088 Register output = ToRegister(lir->output());
18089 Register temp = ToTempUnboxRegister(lir->temp0());
18090
18091 Register obj = masm.extractObject(input, temp);
18092
18093 emitTypeOfIsObjectOOL(lir->mir(), obj, output);
18094
18095 masm.jump(ool.rejoin());
18096 });
18097 addOutOfLineCode(ool, mir);
18098
18099 Label success, fail;
18100
18101 switch (mir->jstype()) {
18102 case JSTYPE_UNDEFINED: {
18103 ScratchTagScope tag(masm, input);
18104 masm.splitTagForTest(input, tag);
18105
18106 masm.branchTestUndefined(Assembler::Equal, tag, &success);
18107 masm.branchTestObject(Assembler::NotEqual, tag, &fail);
18108 break;
18109 }
18110
18111 case JSTYPE_OBJECT: {
18112 ScratchTagScope tag(masm, input);
18113 masm.splitTagForTest(input, tag);
18114
18115 masm.branchTestNull(Assembler::Equal, tag, &success);
18116 masm.branchTestObject(Assembler::NotEqual, tag, &fail);
18117 break;
18118 }
18119
18120 case JSTYPE_FUNCTION: {
18121 masm.branchTestObject(Assembler::NotEqual, input, &fail);
18122 break;
18123 }
18124
18125 case JSTYPE_STRING:
18126 case JSTYPE_NUMBER:
18127 case JSTYPE_BOOLEAN:
18128 case JSTYPE_SYMBOL:
18129 case JSTYPE_BIGINT:
18130 case JSTYPE_LIMIT:
18131 MOZ_CRASH("Primitive type");
18132 }
18133
18134 Register obj = masm.extractObject(input, temp);
18135
18136 emitTypeOfIsObject(mir, obj, output, &success, &fail, ool->entry());
18137
18138 masm.bind(ool->rejoin());
18139 }
18140
18141 void CodeGenerator::visitTypeOfIsNonPrimitiveO(LTypeOfIsNonPrimitiveO* lir) {
18142 Register input = ToRegister(lir->input());
18143 Register output = ToRegister(lir->output());
18144
18145 auto* mir = lir->mir();
18146
18147 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
18148 Register input = ToRegister(lir->input());
18149 Register output = ToRegister(lir->output());
18150
18151 emitTypeOfIsObjectOOL(lir->mir(), input, output);
18152
18153 masm.jump(ool.rejoin());
18154 });
18155 addOutOfLineCode(ool, mir);
18156
18157 Label success, fail;
18158 emitTypeOfIsObject(mir, input, output, &success, &fail, ool->entry());
18159
18160 masm.bind(ool->rejoin());
18161 }
18162
18163 void CodeGenerator::visitTypeOfIsPrimitive(LTypeOfIsPrimitive* lir) {
18164 ValueOperand input = ToValue(lir->input());
18165 Register output = ToRegister(lir->output());
18166
18167 auto* mir = lir->mir();
18168 auto cond = JSOpToCondition(mir->jsop(), /* isSigned = */ false);
18169
18170 switch (mir->jstype()) {
18171 case JSTYPE_STRING:
18172 masm.testStringSet(cond, input, output);
18173 break;
18174 case JSTYPE_NUMBER:
18175 masm.testNumberSet(cond, input, output);
18176 break;
18177 case JSTYPE_BOOLEAN:
18178 masm.testBooleanSet(cond, input, output);
18179 break;
18180 case JSTYPE_SYMBOL:
18181 masm.testSymbolSet(cond, input, output);
18182 break;
18183 case JSTYPE_BIGINT:
18184 masm.testBigIntSet(cond, input, output);
18185 break;
18186
18187 case JSTYPE_UNDEFINED:
18188 case JSTYPE_OBJECT:
18189 case JSTYPE_FUNCTION:
18190 case JSTYPE_LIMIT:
18191 MOZ_CRASH("Non-primitive type");
18192 }
18193 }
18194
18195 void CodeGenerator::visitToAsyncIter(LToAsyncIter* lir) {
18196 pushArg(ToValue(lir->nextMethod()));
18197 pushArg(ToRegister(lir->iterator()));
18198
18199 using Fn = JSObject* (*)(JSContext*, HandleObject, HandleValue);
18200 callVM<Fn, js::CreateAsyncFromSyncIterator>(lir);
18201 }
18202
18203 void CodeGenerator::visitToPropertyKeyCache(LToPropertyKeyCache* lir) {
18204 LiveRegisterSet liveRegs = lir->safepoint()->liveRegs();
18205 ValueOperand input = ToValue(lir->input());
18206 ValueOperand output = ToOutValue(lir);
18207
18208 IonToPropertyKeyIC ic(liveRegs, input, output);
18209 addIC(lir, allocateIC(ic));
18210 }
18211
18212 void CodeGenerator::visitLoadElementV(LLoadElementV* load) {
18213 Register elements = ToRegister(load->elements());
18214 const ValueOperand out = ToOutValue(load);
18215
18216 if (load->index()->isConstant()) {
18217 NativeObject::elementsSizeMustNotOverflow();
18218 int32_t offset = ToInt32(load->index()) * sizeof(Value);
18219 masm.loadValue(Address(elements, offset), out);
18220 } else {
18221 masm.loadValue(BaseObjectElementIndex(elements, ToRegister(load->index())),
18222 out);
18223 }
18224
18225 Label testMagic;
18226 masm.branchTestMagic(Assembler::Equal, out, &testMagic);
18227 bailoutFrom(&testMagic, load->snapshot());
18228 }
18229
18230 void CodeGenerator::visitLoadElementHole(LLoadElementHole* lir) {
18231 Register elements = ToRegister(lir->elements());
18232 Register index = ToRegister(lir->index());
18233 Register initLength = ToRegister(lir->initLength());
18234 const ValueOperand out = ToOutValue(lir);
18235
18236 const MLoadElementHole* mir = lir->mir();
18237
18238 // If the index is out of bounds, load |undefined|. Otherwise, load the
18239 // value.
18240 Label outOfBounds, done;
18241 masm.spectreBoundsCheck32(index, initLength, out.scratchReg(), &outOfBounds);
18242
18243 masm.loadValue(BaseObjectElementIndex(elements, index), out);
18244
18245 // If the value wasn't a hole, we're done. Otherwise, we'll load undefined.
18246 masm.branchTestMagic(Assembler::NotEqual, out, &done);
18247
18248 if (mir->needsNegativeIntCheck()) {
18249 Label loadUndefined;
18250 masm.jump(&loadUndefined);
18251
18252 masm.bind(&outOfBounds);
18253
18254 bailoutCmp32(Assembler::LessThan, index, Imm32(0), lir->snapshot());
18255
18256 masm.bind(&loadUndefined);
18257 } else {
18258 masm.bind(&outOfBounds);
18259 }
18260 masm.moveValue(UndefinedValue(), out);
18261
18262 masm.bind(&done);
18263 }
18264
18265 void CodeGenerator::visitLoadUnboxedScalar(LLoadUnboxedScalar* lir) {
18266 Register elements = ToRegister(lir->elements());
18267 Register temp0 = ToTempRegisterOrInvalid(lir->temp0());
18268 Register temp1 = ToTempRegisterOrInvalid(lir->temp1());
18269 AnyRegister out = ToAnyRegister(lir->output());
18270
18271 const MLoadUnboxedScalar* mir = lir->mir();
18272
18273 Scalar::Type storageType = mir->storageType();
18274
18275 LiveRegisterSet volatileRegs;
18276 if (MacroAssembler::LoadRequiresCall(storageType)) {
18277 volatileRegs = liveVolatileRegs(lir);
18278 }
18279
18280 Label fail;
18281 if (lir->index()->isConstant()) {
18282 Address source =
18283 ToAddress(elements, lir->index(), storageType, mir->offsetAdjustment());
18284 masm.loadFromTypedArray(storageType, source, out, temp0, temp1, &fail,
18285 volatileRegs);
18286 } else {
18287 BaseIndex source(elements, ToRegister(lir->index()),
18288 ScaleFromScalarType(storageType), mir->offsetAdjustment());
18289 masm.loadFromTypedArray(storageType, source, out, temp0, temp1, &fail,
18290 volatileRegs);
18291 }
18292
18293 if (fail.used()) {
18294 bailoutFrom(&fail, lir->snapshot());
18295 }
18296 }
18297
18298 void CodeGenerator::visitLoadUnboxedInt64(LLoadUnboxedInt64* lir) {
18299 Register elements = ToRegister(lir->elements());
18300 Register64 out = ToOutRegister64(lir);
18301
18302 const MLoadUnboxedScalar* mir = lir->mir();
18303
18304 Scalar::Type storageType = mir->storageType();
18305
18306 if (lir->index()->isConstant()) {
18307 Address source =
18308 ToAddress(elements, lir->index(), storageType, mir->offsetAdjustment());
18309 masm.load64(source, out);
18310 } else {
18311 BaseIndex source(elements, ToRegister(lir->index()),
18312 ScaleFromScalarType(storageType), mir->offsetAdjustment());
18313 masm.load64(source, out);
18314 }
18315 }
18316
18317 void CodeGenerator::visitLoadDataViewElement(LLoadDataViewElement* lir) {
18318 Register elements = ToRegister(lir->elements());
18319 const LAllocation* littleEndian = lir->littleEndian();
18320 Register temp1 = ToTempRegisterOrInvalid(lir->temp0());
18321 Register temp2 = ToTempRegisterOrInvalid(lir->temp1());
18322 Register64 temp64 = ToTempRegister64OrInvalid(lir->temp2());
18323 AnyRegister out = ToAnyRegister(lir->output());
18324
18325 const MLoadDataViewElement* mir = lir->mir();
18326 Scalar::Type storageType = mir->storageType();
18327
18328 LiveRegisterSet volatileRegs;
18329 if (MacroAssembler::LoadRequiresCall(storageType)) {
18330 volatileRegs = liveVolatileRegs(lir);
18331 }
18332
18333 BaseIndex source(elements, ToRegister(lir->index()), TimesOne);
18334
18335 bool noSwap = littleEndian->isConstant() &&
18336 ToBoolean(littleEndian) == MOZ_LITTLE_ENDIAN();
18337
18338 // Directly load if no byte swap is needed and the platform supports unaligned
18339 // accesses for the access. (Such support is assumed for integer types.)
18340 if (noSwap && (!Scalar::isFloatingType(storageType) ||
18341 MacroAssembler::SupportsFastUnalignedFPAccesses())) {
18342 Label fail;
18343 masm.loadFromTypedArray(storageType, source, out, temp1, temp2, &fail,
18344 volatileRegs);
18345
18346 if (fail.used()) {
18347 bailoutFrom(&fail, lir->snapshot());
18348 }
18349 return;
18350 }
18351
18352 // Load the value into a gpr register.
18353 switch (storageType) {
18354 case Scalar::Int16:
18355 masm.load16UnalignedSignExtend(source, out.gpr());
18356 break;
18357 case Scalar::Uint16:
18358 masm.load16UnalignedZeroExtend(source, out.gpr());
18359 break;
18360 case Scalar::Int32:
18361 masm.load32Unaligned(source, out.gpr());
18362 break;
18363 case Scalar::Uint32:
18364 masm.load32Unaligned(source, out.isFloat() ? temp1 : out.gpr());
18365 break;
18366 case Scalar::Float16:
18367 masm.load16UnalignedZeroExtend(source, temp1);
18368 break;
18369 case Scalar::Float32:
18370 masm.load32Unaligned(source, temp1);
18371 break;
18372 case Scalar::Float64:
18373 masm.load64Unaligned(source, temp64);
18374 break;
18375 case Scalar::Int8:
18376 case Scalar::Uint8:
18377 case Scalar::Uint8Clamped:
18378 case Scalar::BigInt64:
18379 case Scalar::BigUint64:
18380 default:
18381 MOZ_CRASH("Invalid typed array type");
18382 }
18383
18384 if (!noSwap) {
18385 // Swap the bytes in the loaded value.
18386 Label skip;
18387 if (!littleEndian->isConstant()) {
18388 masm.branch32(
18389 MOZ_LITTLE_ENDIAN() ? Assembler::NotEqual : Assembler::Equal,
18390 ToRegister(littleEndian), Imm32(0), &skip);
18391 }
18392
18393 switch (storageType) {
18394 case Scalar::Int16:
18395 masm.byteSwap16SignExtend(out.gpr());
18396 break;
18397 case Scalar::Uint16:
18398 masm.byteSwap16ZeroExtend(out.gpr());
18399 break;
18400 case Scalar::Int32:
18401 masm.byteSwap32(out.gpr());
18402 break;
18403 case Scalar::Uint32:
18404 masm.byteSwap32(out.isFloat() ? temp1 : out.gpr());
18405 break;
18406 case Scalar::Float16:
18407 masm.byteSwap16ZeroExtend(temp1);
18408 break;
18409 case Scalar::Float32:
18410 masm.byteSwap32(temp1);
18411 break;
18412 case Scalar::Float64:
18413 masm.byteSwap64(temp64);
18414 break;
18415 case Scalar::Int8:
18416 case Scalar::Uint8:
18417 case Scalar::Uint8Clamped:
18418 case Scalar::BigInt64:
18419 case Scalar::BigUint64:
18420 default:
18421 MOZ_CRASH("Invalid typed array type");
18422 }
18423
18424 if (skip.used()) {
18425 masm.bind(&skip);
18426 }
18427 }
18428
18429 // Move the value into the output register.
18430 switch (storageType) {
18431 case Scalar::Int16:
18432 case Scalar::Uint16:
18433 case Scalar::Int32:
18434 break;
18435 case Scalar::Uint32:
18436 if (out.isFloat()) {
18437 masm.convertUInt32ToDouble(temp1, out.fpu());
18438 } else {
18439 // Bail out if the value doesn't fit into a signed int32 value. This
18440 // is what allows MLoadDataViewElement to have a type() of
18441 // MIRType::Int32 for UInt32 array loads.
18442 bailoutTest32(Assembler::Signed, out.gpr(), out.gpr(), lir->snapshot());
18443 }
18444 break;
18445 case Scalar::Float16:
18446 masm.moveGPRToFloat16(temp1, out.fpu(), temp2, volatileRegs);
18447 masm.canonicalizeFloat(out.fpu());
18448 break;
18449 case Scalar::Float32:
18450 masm.moveGPRToFloat32(temp1, out.fpu());
18451 masm.canonicalizeFloat(out.fpu());
18452 break;
18453 case Scalar::Float64:
18454 masm.moveGPR64ToDouble(temp64, out.fpu());
18455 masm.canonicalizeDouble(out.fpu());
18456 break;
18457 case Scalar::Int8:
18458 case Scalar::Uint8:
18459 case Scalar::Uint8Clamped:
18460 case Scalar::BigInt64:
18461 case Scalar::BigUint64:
18462 default:
18463 MOZ_CRASH("Invalid typed array type");
18464 }
18465 }
18466
18467 void CodeGenerator::visitLoadDataViewElement64(LLoadDataViewElement64* lir) {
18468 Register elements = ToRegister(lir->elements());
18469 const LAllocation* littleEndian = lir->littleEndian();
18470 Register64 out = ToOutRegister64(lir);
18471
18472 MOZ_ASSERT(Scalar::isBigIntType(lir->mir()->storageType()));
18473
18474 BaseIndex source(elements, ToRegister(lir->index()), TimesOne);
18475
18476 bool noSwap = littleEndian->isConstant() &&
18477 ToBoolean(littleEndian) == MOZ_LITTLE_ENDIAN();
18478
18479 // Load the value into a register.
18480 masm.load64Unaligned(source, out);
18481
18482 if (!noSwap) {
18483 // Swap the bytes in the loaded value.
18484 Label skip;
18485 if (!littleEndian->isConstant()) {
18486 masm.branch32(
18487 MOZ_LITTLE_ENDIAN() ? Assembler::NotEqual : Assembler::Equal,
18488 ToRegister(littleEndian), Imm32(0), &skip);
18489 }
18490
18491 masm.byteSwap64(out);
18492
18493 if (skip.used()) {
18494 masm.bind(&skip);
18495 }
18496 }
18497 }
18498
18499 void CodeGenerator::visitLoadTypedArrayElementHole(
18500 LLoadTypedArrayElementHole* lir) {
18501 Register elements = ToRegister(lir->elements());
18502 Register index = ToRegister(lir->index());
18503 Register length = ToRegister(lir->length());
18504 Register temp = ToTempRegisterOrInvalid(lir->temp0());
18505 const ValueOperand out = ToOutValue(lir);
18506
18507 Register scratch = out.scratchReg();
18508
18509 // Load undefined if index >= length.
18510 Label outOfBounds, done;
18511 masm.spectreBoundsCheckPtr(index, length, scratch, &outOfBounds);
18512
18513 Scalar::Type arrayType = lir->mir()->arrayType();
18514
18515 LiveRegisterSet volatileRegs;
18516 if (MacroAssembler::LoadRequiresCall(arrayType)) {
18517 volatileRegs = liveVolatileRegs(lir);
18518 }
18519
18520 Label fail;
18521 BaseIndex source(elements, index, ScaleFromScalarType(arrayType));
18522 MacroAssembler::Uint32Mode uint32Mode =
18523 lir->mir()->forceDouble() ? MacroAssembler::Uint32Mode::ForceDouble
18524 : MacroAssembler::Uint32Mode::FailOnDouble;
18525 masm.loadFromTypedArray(arrayType, source, out, uint32Mode, temp, &fail,
18526 volatileRegs);
18527 masm.jump(&done);
18528
18529 masm.bind(&outOfBounds);
18530 masm.moveValue(UndefinedValue(), out);
18531
18532 if (fail.used()) {
18533 bailoutFrom(&fail, lir->snapshot());
18534 }
18535
18536 masm.bind(&done);
18537 }
18538
18539 void CodeGenerator::visitLoadTypedArrayElementHoleBigInt(
18540 LLoadTypedArrayElementHoleBigInt* lir) {
18541 Register elements = ToRegister(lir->elements());
18542 Register index = ToRegister(lir->index());
18543 Register length = ToRegister(lir->length());
18544 const ValueOperand out = ToOutValue(lir);
18545
18546 Register temp = ToRegister(lir->temp0());
18547
18548 // On x86 there are not enough registers. In that case reuse the output
18549 // registers as temporaries.
18550 #ifdef JS_CODEGEN_X86
18551 MOZ_ASSERT(lir->temp1().isBogusTemp());
18552 Register64 temp64 = out.toRegister64();
18553 #else
18554 Register64 temp64 = ToRegister64(lir->temp1());
18555 #endif
18556
18557 // Load undefined if index >= length.
18558 Label outOfBounds, done;
18559 masm.spectreBoundsCheckPtr(index, length, temp, &outOfBounds);
18560
18561 Scalar::Type arrayType = lir->mir()->arrayType();
18562 BaseIndex source(elements, index, ScaleFromScalarType(arrayType));
18563 masm.load64(source, temp64);
18564
18565 #ifdef JS_CODEGEN_X86
18566 Register bigInt = temp;
18567 Register maybeTemp = InvalidReg;
18568 #else
18569 Register bigInt = out.scratchReg();
18570 Register maybeTemp = temp;
18571 #endif
18572 emitCreateBigInt(lir, arrayType, temp64, bigInt, maybeTemp);
18573
18574 masm.tagValue(JSVAL_TYPE_BIGINT, bigInt, out);
18575 masm.jump(&done);
18576
18577 masm.bind(&outOfBounds);
18578 masm.moveValue(UndefinedValue(), out);
18579
18580 masm.bind(&done);
18581 }
18582
18583 template <typename T>
18584 static inline void StoreToTypedArray(MacroAssembler& masm,
18585 Scalar::Type writeType,
18586 const LAllocation* value, const T& dest,
18587 Register temp,
18588 LiveRegisterSet volatileRegs) {
18589 if (Scalar::isFloatingType(writeType)) {
18590 masm.storeToTypedFloatArray(writeType, ToFloatRegister(value), dest, temp,
18591 volatileRegs);
18592 } else {
18593 if (value->isConstant()) {
18594 masm.storeToTypedIntArray(writeType, Imm32(ToInt32(value)), dest);
18595 } else {
18596 masm.storeToTypedIntArray(writeType, ToRegister(value), dest);
18597 }
18598 }
18599 }
18600
18601 void CodeGenerator::visitStoreUnboxedScalar(LStoreUnboxedScalar* lir) {
18602 Register elements = ToRegister(lir->elements());
18603 Register temp = ToTempRegisterOrInvalid(lir->temp0());
18604 const LAllocation* value = lir->value();
18605
18606 const MStoreUnboxedScalar* mir = lir->mir();
18607
18608 Scalar::Type writeType = mir->writeType();
18609
18610 LiveRegisterSet volatileRegs;
18611 if (MacroAssembler::StoreRequiresCall(writeType)) {
18612 volatileRegs = liveVolatileRegs(lir);
18613 }
18614
18615 if (lir->index()->isConstant()) {
18616 Address dest = ToAddress(elements, lir->index(), writeType);
18617 StoreToTypedArray(masm, writeType, value, dest, temp, volatileRegs);
18618 } else {
18619 BaseIndex dest(elements, ToRegister(lir->index()),
18620 ScaleFromScalarType(writeType));
18621 StoreToTypedArray(masm, writeType, value, dest, temp, volatileRegs);
18622 }
18623 }
18624
18625 template <typename T>
18626 static inline void StoreToTypedBigIntArray(MacroAssembler& masm,
18627 const LInt64Allocation& value,
18628 const T& dest) {
18629 if (IsConstant(value)) {
18630 masm.storeToTypedBigIntArray(Imm64(ToInt64(value)), dest);
18631 } else {
18632 masm.storeToTypedBigIntArray(ToRegister64(value), dest);
18633 }
18634 }
18635
18636 void CodeGenerator::visitStoreUnboxedInt64(LStoreUnboxedInt64* lir) {
18637 Register elements = ToRegister(lir->elements());
18638 LInt64Allocation value = lir->value();
18639
18640 Scalar::Type writeType = lir->mir()->writeType();
18641 MOZ_ASSERT(Scalar::isBigIntType(writeType));
18642
18643 if (lir->index()->isConstant()) {
18644 Address dest = ToAddress(elements, lir->index(), writeType);
18645 StoreToTypedBigIntArray(masm, value, dest);
18646 } else {
18647 BaseIndex dest(elements, ToRegister(lir->index()),
18648 ScaleFromScalarType(writeType));
18649 StoreToTypedBigIntArray(masm, value, dest);
18650 }
18651 }
18652
18653 void CodeGenerator::visitStoreDataViewElement(LStoreDataViewElement* lir) {
18654 Register elements = ToRegister(lir->elements());
18655 const LAllocation* value = lir->value();
18656 const LAllocation* littleEndian = lir->littleEndian();
18657 Register temp = ToTempRegisterOrInvalid(lir->temp0());
18658 Register64 temp64 = ToTempRegister64OrInvalid(lir->temp1());
18659
18660 Scalar::Type writeType = lir->mir()->writeType();
18661
18662 LiveRegisterSet volatileRegs;
18663 if (MacroAssembler::StoreRequiresCall(writeType)) {
18664 volatileRegs = liveVolatileRegs(lir);
18665 }
18666
18667 BaseIndex dest(elements, ToRegister(lir->index()), TimesOne);
18668
18669 bool noSwap = littleEndian->isConstant() &&
18670 ToBoolean(littleEndian) == MOZ_LITTLE_ENDIAN();
18671
18672 // Directly store if no byte swap is needed and the platform supports
18673 // unaligned accesses for the access. (Such support is assumed for integer
18674 // types.)
18675 if (noSwap && (!Scalar::isFloatingType(writeType) ||
18676 MacroAssembler::SupportsFastUnalignedFPAccesses())) {
18677 StoreToTypedArray(masm, writeType, value, dest, temp, volatileRegs);
18678 return;
18679 }
18680
18681 // Load the value into a gpr register.
18682 switch (writeType) {
18683 case Scalar::Int16:
18684 case Scalar::Uint16:
18685 case Scalar::Int32:
18686 case Scalar::Uint32:
18687 if (value->isConstant()) {
18688 masm.move32(Imm32(ToInt32(value)), temp);
18689 } else {
18690 masm.move32(ToRegister(value), temp);
18691 }
18692 break;
18693 case Scalar::Float16: {
18694 FloatRegister fvalue = ToFloatRegister(value);
18695 masm.moveFloat16ToGPR(fvalue, temp, volatileRegs);
18696 break;
18697 }
18698 case Scalar::Float32: {
18699 FloatRegister fvalue = ToFloatRegister(value);
18700 masm.moveFloat32ToGPR(fvalue, temp);
18701 break;
18702 }
18703 case Scalar::Float64: {
18704 FloatRegister fvalue = ToFloatRegister(value);
18705 masm.moveDoubleToGPR64(fvalue, temp64);
18706 break;
18707 }
18708 case Scalar::Int8:
18709 case Scalar::Uint8:
18710 case Scalar::Uint8Clamped:
18711 case Scalar::BigInt64:
18712 case Scalar::BigUint64:
18713 default:
18714 MOZ_CRASH("Invalid typed array type");
18715 }
18716
18717 if (!noSwap) {
18718 // Swap the bytes in the loaded value.
18719 Label skip;
18720 if (!littleEndian->isConstant()) {
18721 masm.branch32(
18722 MOZ_LITTLE_ENDIAN() ? Assembler::NotEqual : Assembler::Equal,
18723 ToRegister(littleEndian), Imm32(0), &skip);
18724 }
18725
18726 switch (writeType) {
18727 case Scalar::Int16:
18728 masm.byteSwap16SignExtend(temp);
18729 break;
18730 case Scalar::Uint16:
18731 case Scalar::Float16:
18732 masm.byteSwap16ZeroExtend(temp);
18733 break;
18734 case Scalar::Int32:
18735 case Scalar::Uint32:
18736 case Scalar::Float32:
18737 masm.byteSwap32(temp);
18738 break;
18739 case Scalar::Float64:
18740 masm.byteSwap64(temp64);
18741 break;
18742 case Scalar::Int8:
18743 case Scalar::Uint8:
18744 case Scalar::Uint8Clamped:
18745 case Scalar::BigInt64:
18746 case Scalar::BigUint64:
18747 default:
18748 MOZ_CRASH("Invalid typed array type");
18749 }
18750
18751 if (skip.used()) {
18752 masm.bind(&skip);
18753 }
18754 }
18755
18756 // Store the value into the destination.
18757 switch (writeType) {
18758 case Scalar::Int16:
18759 case Scalar::Uint16:
18760 case Scalar::Float16:
18761 masm.store16Unaligned(temp, dest);
18762 break;
18763 case Scalar::Int32:
18764 case Scalar::Uint32:
18765 case Scalar::Float32:
18766 masm.store32Unaligned(temp, dest);
18767 break;
18768 case Scalar::Float64:
18769 masm.store64Unaligned(temp64, dest);
18770 break;
18771 case Scalar::Int8:
18772 case Scalar::Uint8:
18773 case Scalar::Uint8Clamped:
18774 case Scalar::BigInt64:
18775 case Scalar::BigUint64:
18776 default:
18777 MOZ_CRASH("Invalid typed array type");
18778 }
18779 }
18780
18781 void CodeGenerator::visitStoreDataViewElement64(LStoreDataViewElement64* lir) {
18782 Register elements = ToRegister(lir->elements());
18783 LInt64Allocation value = lir->value();
18784 const LAllocation* littleEndian = lir->littleEndian();
18785 Register64 temp = ToTempRegister64OrInvalid(lir->temp0());
18786
18787 MOZ_ASSERT(Scalar::isBigIntType(lir->mir()->writeType()));
18788
18789 BaseIndex dest(elements, ToRegister(lir->index()), TimesOne);
18790
18791 bool noSwap = littleEndian->isConstant() &&
18792 ToBoolean(littleEndian) == MOZ_LITTLE_ENDIAN();
18793
18794 // Directly store if no byte swap is needed and the platform supports
18795 // unaligned accesses for the access. (Such support is assumed for integer
18796 // types.)
18797 if (noSwap) {
18798 StoreToTypedBigIntArray(masm, value, dest);
18799 return;
18800 }
18801
18802 Register64 valueReg = Register64::Invalid();
18803 if (IsConstant(value)) {
18804 MOZ_ASSERT(temp != Register64::Invalid());
18805 masm.move64(Imm64(ToInt64(value)), temp);
18806 } else {
18807 valueReg = ToRegister64(value);
18808
18809 // Preserve the input value.
18810 if (temp != Register64::Invalid()) {
18811 masm.move64(valueReg, temp);
18812 } else {
18813 masm.Push(valueReg);
18814 temp = valueReg;
18815 }
18816 }
18817
18818 // Swap the bytes in the loaded value.
18819 Label skip;
18820 if (!littleEndian->isConstant()) {
18821 masm.branch32(MOZ_LITTLE_ENDIAN() ? Assembler::NotEqual : Assembler::Equal,
18822 ToRegister(littleEndian), Imm32(0), &skip);
18823 }
18824
18825 masm.byteSwap64(temp);
18826
18827 if (skip.used()) {
18828 masm.bind(&skip);
18829 }
18830
18831 // Store the value into the destination.
18832 masm.store64Unaligned(temp, dest);
18833
18834 // Restore |value| if it was modified.
18835 if (valueReg == temp) {
18836 masm.Pop(valueReg);
18837 }
18838 }
18839
18840 void CodeGenerator::visitStoreTypedArrayElementHole(
18841 LStoreTypedArrayElementHole* lir) {
18842 Register elements = ToRegister(lir->elements());
18843 const LAllocation* value = lir->value();
18844
18845 Scalar::Type arrayType = lir->mir()->arrayType();
18846
18847 Register index = ToRegister(lir->index());
18848 const LAllocation* length = lir->length();
18849 Register temp = ToTempRegisterOrInvalid(lir->temp0());
18850
18851 LiveRegisterSet volatileRegs;
18852 if (MacroAssembler::StoreRequiresCall(arrayType)) {
18853 volatileRegs = liveVolatileRegs(lir);
18854 }
18855
18856 Label skip;
18857 if (length->isGeneralReg()) {
18858 masm.spectreBoundsCheckPtr(index, ToRegister(length), temp, &skip);
18859 } else {
18860 masm.spectreBoundsCheckPtr(index, ToAddress(length), temp, &skip);
18861 }
18862
18863 BaseIndex dest(elements, index, ScaleFromScalarType(arrayType));
18864 StoreToTypedArray(masm, arrayType, value, dest, temp, volatileRegs);
18865
18866 masm.bind(&skip);
18867 }
18868
18869 void CodeGenerator::visitStoreTypedArrayElementHoleInt64(
18870 LStoreTypedArrayElementHoleInt64* lir) {
18871 Register elements = ToRegister(lir->elements());
18872 LInt64Allocation value = lir->value();
18873
18874 Scalar::Type arrayType = lir->mir()->arrayType();
18875 MOZ_ASSERT(Scalar::isBigIntType(arrayType));
18876
18877 Register index = ToRegister(lir->index());
18878 const LAllocation* length = lir->length();
18879 Register spectreTemp = ToTempRegisterOrInvalid(lir->temp0());
18880
18881 Label skip;
18882 if (length->isGeneralReg()) {
18883 masm.spectreBoundsCheckPtr(index, ToRegister(length), spectreTemp, &skip);
18884 } else {
18885 masm.spectreBoundsCheckPtr(index, ToAddress(length), spectreTemp, &skip);
18886 }
18887
18888 BaseIndex dest(elements, index, ScaleFromScalarType(arrayType));
18889 StoreToTypedBigIntArray(masm, value, dest);
18890
18891 masm.bind(&skip);
18892 }
18893
18894 void CodeGenerator::visitMemoryBarrier(LMemoryBarrier* ins) {
18895 masm.memoryBarrier(ins->barrier());
18896 }
18897
18898 void CodeGenerator::visitAtomicIsLockFree(LAtomicIsLockFree* lir) {
18899 Register value = ToRegister(lir->value());
18900 Register output = ToRegister(lir->output());
18901
18902 masm.atomicIsLockFreeJS(value, output);
18903 }
18904
18905 void CodeGenerator::visitAtomicPause(LAtomicPause* lir) { masm.atomicPause(); }
18906
18907 void CodeGenerator::visitClampIToUint8(LClampIToUint8* lir) {
18908 Register output = ToRegister(lir->output());
18909 MOZ_ASSERT(output == ToRegister(lir->input()));
18910 masm.clampIntToUint8(output);
18911 }
18912
18913 void CodeGenerator::visitClampDToUint8(LClampDToUint8* lir) {
18914 FloatRegister input = ToFloatRegister(lir->input());
18915 Register output = ToRegister(lir->output());
18916 masm.clampDoubleToUint8(input, output);
18917 }
18918
18919 void CodeGenerator::visitClampVToUint8(LClampVToUint8* lir) {
18920 ValueOperand operand = ToValue(lir->input());
18921 FloatRegister tempFloat = ToFloatRegister(lir->temp0());
18922 Register output = ToRegister(lir->output());
18923
18924 using Fn = bool (*)(JSContext*, JSString*, double*);
18925 OutOfLineCode* oolString = oolCallVM<Fn, StringToNumber>(
18926 lir, ArgList(output), StoreFloatRegisterTo(tempFloat));
18927 Label* stringEntry = oolString->entry();
18928 Label* stringRejoin = oolString->rejoin();
18929
18930 Label fails;
18931 masm.clampValueToUint8(operand, stringEntry, stringRejoin, output, tempFloat,
18932 output, &fails);
18933
18934 bailoutFrom(&fails, lir->snapshot());
18935 }
18936
18937 void CodeGenerator::visitInCache(LInCache* ins) {
18938 LiveRegisterSet liveRegs = ins->safepoint()->liveRegs();
18939
18940 ConstantOrRegister key =
18941 toConstantOrRegister(ins, LInCache::LhsIndex, ins->mir()->key()->type());
18942 Register object = ToRegister(ins->rhs());
18943 Register output = ToRegister(ins->output());
18944 Register temp = ToRegister(ins->temp0());
18945
18946 IonInIC cache(liveRegs, key, object, output, temp);
18947 addIC(ins, allocateIC(cache));
18948 }
18949
18950 void CodeGenerator::visitInArray(LInArray* lir) {
18951 const MInArray* mir = lir->mir();
18952 Register elements = ToRegister(lir->elements());
18953 Register initLength = ToRegister(lir->initLength());
18954 Register output = ToRegister(lir->output());
18955
18956 Label falseBranch, done, trueBranch;
18957
18958 if (lir->index()->isConstant()) {
18959 int32_t index = ToInt32(lir->index());
18960
18961 if (index < 0) {
18962 MOZ_ASSERT(mir->needsNegativeIntCheck());
18963 bailout(lir->snapshot());
18964 return;
18965 }
18966
18967 masm.branch32(Assembler::BelowOrEqual, initLength, Imm32(index),
18968 &falseBranch);
18969
18970 NativeObject::elementsSizeMustNotOverflow();
18971 Address address = Address(elements, index * sizeof(Value));
18972 masm.branchTestMagic(Assembler::Equal, address, &falseBranch);
18973 } else {
18974 Register index = ToRegister(lir->index());
18975
18976 Label negativeIntCheck;
18977 Label* failedInitLength = &falseBranch;
18978 if (mir->needsNegativeIntCheck()) {
18979 failedInitLength = &negativeIntCheck;
18980 }
18981
18982 masm.branch32(Assembler::BelowOrEqual, initLength, index, failedInitLength);
18983
18984 BaseObjectElementIndex address(elements, index);
18985 masm.branchTestMagic(Assembler::Equal, address, &falseBranch);
18986
18987 if (mir->needsNegativeIntCheck()) {
18988 masm.jump(&trueBranch);
18989 masm.bind(&negativeIntCheck);
18990
18991 bailoutCmp32(Assembler::LessThan, index, Imm32(0), lir->snapshot());
18992
18993 masm.jump(&falseBranch);
18994 }
18995 }
18996
18997 masm.bind(&trueBranch);
18998 masm.move32(Imm32(1), output);
18999 masm.jump(&done);
19000
19001 masm.bind(&falseBranch);
19002 masm.move32(Imm32(0), output);
19003 masm.bind(&done);
19004 }
19005
19006 void CodeGenerator::visitGuardElementNotHole(LGuardElementNotHole* lir) {
19007 Register elements = ToRegister(lir->elements());
19008 const LAllocation* index = lir->index();
19009
19010 Label testMagic;
19011 if (index->isConstant()) {
19012 Address address(elements, ToInt32(index) * sizeof(js::Value));
19013 masm.branchTestMagic(Assembler::Equal, address, &testMagic);
19014 } else {
19015 BaseObjectElementIndex address(elements, ToRegister(index));
19016 masm.branchTestMagic(Assembler::Equal, address, &testMagic);
19017 }
19018 bailoutFrom(&testMagic, lir->snapshot());
19019 }
19020
19021 void CodeGenerator::visitInstanceOfO(LInstanceOfO* ins) {
19022 Register protoReg = ToRegister(ins->rhs());
19023 emitInstanceOf(ins, protoReg);
19024 }
19025
19026 void CodeGenerator::visitInstanceOfV(LInstanceOfV* ins) {
19027 Register protoReg = ToRegister(ins->rhs());
19028 emitInstanceOf(ins, protoReg);
19029 }
19030
19031 void CodeGenerator::emitInstanceOf(LInstruction* ins, Register protoReg) {
19032 // This path implements fun_hasInstance when the function's prototype is
19033 // known to be the object in protoReg
19034
19035 Label done;
19036 Register output = ToRegister(ins->getDef(0));
19037
19038 // If the lhs is a primitive, the result is false.
19039 Register objReg;
19040 if (ins->isInstanceOfV()) {
19041 Label isObject;
19042 ValueOperand lhsValue = ToValue(ins->toInstanceOfV()->lhs());
19043 masm.branchTestObject(Assembler::Equal, lhsValue, &isObject);
19044 masm.mov(ImmWord(0), output);
19045 masm.jump(&done);
19046 masm.bind(&isObject);
19047 objReg = masm.extractObject(lhsValue, output);
19048 } else {
19049 objReg = ToRegister(ins->toInstanceOfO()->lhs());
19050 }
19051
19052 // Crawl the lhs's prototype chain in a loop to search for prototypeObject.
19053 // This follows the main loop of js::IsPrototypeOf, though additionally breaks
19054 // out of the loop on Proxy::LazyProto.
19055
19056 // Load the lhs's prototype.
19057 masm.loadObjProto(objReg, output);
19058
19059 Label testLazy;
19060 {
19061 Label loopPrototypeChain;
19062 masm.bind(&loopPrototypeChain);
19063
19064 // Test for the target prototype object.
19065 Label notPrototypeObject;
19066 masm.branchPtr(Assembler::NotEqual, output, protoReg, &notPrototypeObject);
19067 masm.mov(ImmWord(1), output);
19068 masm.jump(&done);
19069 masm.bind(&notPrototypeObject);
19070
19071 MOZ_ASSERT(uintptr_t(TaggedProto::LazyProto) == 1);
19072
19073 // Test for nullptr or Proxy::LazyProto
19074 masm.branchPtr(Assembler::BelowOrEqual, output, ImmWord(1), &testLazy);
19075
19076 // Load the current object's prototype.
19077 masm.loadObjProto(output, output);
19078
19079 masm.jump(&loopPrototypeChain);
19080 }
19081
19082 // Make a VM call if an object with a lazy proto was found on the prototype
19083 // chain. This currently occurs only for cross compartment wrappers, which
19084 // we do not expect to be compared with non-wrapper functions from this
19085 // compartment. Otherwise, we stopped on a nullptr prototype and the output
19086 // register is already correct.
19087
19088 using Fn = bool (*)(JSContext*, HandleObject, JSObject*, bool*);
19089 auto* ool = oolCallVM<Fn, IsPrototypeOf>(ins, ArgList(protoReg, objReg),
19090 StoreRegisterTo(output));
19091
19092 // Regenerate the original lhs object for the VM call.
19093 Label regenerate, *lazyEntry;
19094 if (objReg != output) {
19095 lazyEntry = ool->entry();
19096 } else {
19097 masm.bind(&regenerate);
19098 lazyEntry = &regenerate;
19099 if (ins->isInstanceOfV()) {
19100 ValueOperand lhsValue = ToValue(ins->toInstanceOfV()->lhs());
19101 objReg = masm.extractObject(lhsValue, output);
19102 } else {
19103 objReg = ToRegister(ins->toInstanceOfO()->lhs());
19104 }
19105 MOZ_ASSERT(objReg == output);
19106 masm.jump(ool->entry());
19107 }
19108
19109 masm.bind(&testLazy);
19110 masm.branchPtr(Assembler::Equal, output, ImmWord(1), lazyEntry);
19111
19112 masm.bind(&done);
19113 masm.bind(ool->rejoin());
19114 }
19115
19116 void CodeGenerator::visitInstanceOfCache(LInstanceOfCache* ins) {
19117 // The Lowering ensures that RHS is an object, and that LHS is a value.
19118 LiveRegisterSet liveRegs = ins->safepoint()->liveRegs();
19119 TypedOrValueRegister lhs = TypedOrValueRegister(ToValue(ins->obj()));
19120 Register rhs = ToRegister(ins->proto());
19121 Register output = ToRegister(ins->output());
19122
19123 IonInstanceOfIC ic(liveRegs, lhs, rhs, output);
19124 addIC(ins, allocateIC(ic));
19125 }
19126
19127 void CodeGenerator::visitGetDOMProperty(LGetDOMProperty* ins) {
19128 const Register JSContextReg = ToRegister(ins->temp0());
19129 const Register ObjectReg = ToRegister(ins->object());
19130 const Register PrivateReg = ToRegister(ins->temp1());
19131 const Register ValueReg = ToRegister(ins->temp2());
19132
19133 Label haveValue;
19134 if (ins->mir()->valueMayBeInSlot()) {
19135 size_t slot = ins->mir()->domMemberSlotIndex();
19136 // It's a bit annoying to redo these slot calculations, which duplcate
19137 // LSlots and a few other things like that, but I'm not sure there's a
19138 // way to reuse those here.
19139 //
19140 // If this ever gets fixed to work with proxies (by not assuming that
19141 // reserved slot indices, which is what domMemberSlotIndex() returns,
19142 // match fixed slot indices), we can reenable MGetDOMProperty for
19143 // proxies in IonBuilder.
19144 if (slot < NativeObject::MAX_FIXED_SLOTS) {
19145 masm.loadValue(Address(ObjectReg, NativeObject::getFixedSlotOffset(slot)),
19146 JSReturnOperand);
19147 } else {
19148 // It's a dynamic slot.
19149 slot -= NativeObject::MAX_FIXED_SLOTS;
19150 // Use PrivateReg as a scratch register for the slots pointer.
19151 masm.loadPtr(Address(ObjectReg, NativeObject::offsetOfSlots()),
19152 PrivateReg);
19153 masm.loadValue(Address(PrivateReg, slot * sizeof(js::Value)),
19154 JSReturnOperand);
19155 }
19156 masm.branchTestUndefined(Assembler::NotEqual, JSReturnOperand, &haveValue);
19157 }
19158
19159 DebugOnly<uint32_t> initialStack = masm.framePushed();
19160
19161 masm.checkStackAlignment();
19162
19163 // Make space for the outparam. Pre-initialize it to UndefinedValue so we
19164 // can trace it at GC time.
19165 masm.Push(UndefinedValue());
19166 // We pass the pointer to our out param as an instance of
19167 // JSJitGetterCallArgs, since on the binary level it's the same thing.
19168 static_assert(sizeof(JSJitGetterCallArgs) == sizeof(Value*));
19169 masm.moveStackPtrTo(ValueReg);
19170
19171 masm.Push(ObjectReg);
19172
19173 LoadDOMPrivate(masm, ObjectReg, PrivateReg, ins->mir()->objectKind());
19174
19175 // Rooting will happen at GC time.
19176 masm.moveStackPtrTo(ObjectReg);
19177
19178 Realm* getterRealm = ins->mir()->getterRealm();
19179 if (gen->realm->realmPtr() != getterRealm) {
19180 // We use JSContextReg as scratch register here.
19181 masm.switchToRealm(getterRealm, JSContextReg);
19182 }
19183
19184 uint32_t safepointOffset = masm.buildFakeExitFrame(JSContextReg);
19185 masm.loadJSContext(JSContextReg);
19186 masm.enterFakeExitFrame(JSContextReg, JSContextReg,
19187 ExitFrameType::IonDOMGetter);
19188
19189 markSafepointAt(safepointOffset, ins);
19190
19191 masm.setupAlignedABICall();
19192 masm.loadJSContext(JSContextReg);
19193 masm.passABIArg(JSContextReg);
19194 masm.passABIArg(ObjectReg);
19195 masm.passABIArg(PrivateReg);
19196 masm.passABIArg(ValueReg);
19197 ensureOsiSpace();
19198 masm.callWithABI(DynamicFunction<JSJitGetterOp>(ins->mir()->fun()),
19199 ABIType::General,
19200 CheckUnsafeCallWithABI::DontCheckHasExitFrame);
19201
19202 if (ins->mir()->isInfallible()) {
19203 masm.loadValue(Address(masm.getStackPointer(),
19204 IonDOMExitFrameLayout::offsetOfResult()),
19205 JSReturnOperand);
19206 } else {
19207 masm.branchIfFalseBool(ReturnReg, masm.exceptionLabel());
19208
19209 masm.loadValue(Address(masm.getStackPointer(),
19210 IonDOMExitFrameLayout::offsetOfResult()),
19211 JSReturnOperand);
19212 }
19213
19214 // Switch back to the current realm if needed. Note: if the getter threw an
19215 // exception, the exception handler will do this.
19216 if (gen->realm->realmPtr() != getterRealm) {
19217 static_assert(!JSReturnOperand.aliases(ReturnReg),
19218 "Clobbering ReturnReg should not affect the return value");
19219 masm.switchToRealm(gen->realm->realmPtr(), ReturnReg);
19220 }
19221
19222 // Until C++ code is instrumented against Spectre, prevent speculative
19223 // execution from returning any private data.
19224 if (JitOptions.spectreJitToCxxCalls && ins->mir()->hasLiveDefUses()) {
19225 masm.speculationBarrier();
19226 }
19227
19228 masm.adjustStack(IonDOMExitFrameLayout::Size());
19229
19230 masm.bind(&haveValue);
19231
19232 MOZ_ASSERT(masm.framePushed() == initialStack);
19233 }
19234
19235 void CodeGenerator::visitGetDOMMemberV(LGetDOMMemberV* ins) {
19236 // It's simpler to duplicate visitLoadFixedSlotV here than it is to try to
19237 // use an LLoadFixedSlotV or some subclass of it for this case: that would
19238 // require us to have MGetDOMMember inherit from MLoadFixedSlot, and then
19239 // we'd have to duplicate a bunch of stuff we now get for free from
19240 // MGetDOMProperty.
19241 //
19242 // If this ever gets fixed to work with proxies (by not assuming that
19243 // reserved slot indices, which is what domMemberSlotIndex() returns,
19244 // match fixed slot indices), we can reenable MGetDOMMember for
19245 // proxies in IonBuilder.
19246 Register object = ToRegister(ins->object());
19247 size_t slot = ins->mir()->domMemberSlotIndex();
19248 ValueOperand result = ToOutValue(ins);
19249
19250 masm.loadValue(Address(object, NativeObject::getFixedSlotOffset(slot)),
19251 result);
19252 }
19253
19254 void CodeGenerator::visitGetDOMMemberT(LGetDOMMemberT* ins) {
19255 // It's simpler to duplicate visitLoadFixedSlotT here than it is to try to
19256 // use an LLoadFixedSlotT or some subclass of it for this case: that would
19257 // require us to have MGetDOMMember inherit from MLoadFixedSlot, and then
19258 // we'd have to duplicate a bunch of stuff we now get for free from
19259 // MGetDOMProperty.
19260 //
19261 // If this ever gets fixed to work with proxies (by not assuming that
19262 // reserved slot indices, which is what domMemberSlotIndex() returns,
19263 // match fixed slot indices), we can reenable MGetDOMMember for
19264 // proxies in IonBuilder.
19265 Register object = ToRegister(ins->object());
19266 size_t slot = ins->mir()->domMemberSlotIndex();
19267 AnyRegister result = ToAnyRegister(ins->output());
19268 MIRType type = ins->mir()->type();
19269
19270 masm.loadUnboxedValue(Address(object, NativeObject::getFixedSlotOffset(slot)),
19271 type, result);
19272 }
19273
19274 void CodeGenerator::visitSetDOMProperty(LSetDOMProperty* ins) {
19275 const Register JSContextReg = ToRegister(ins->temp0());
19276 const Register ObjectReg = ToRegister(ins->object());
19277 const Register PrivateReg = ToRegister(ins->temp1());
19278 const Register ValueReg = ToRegister(ins->temp2());
19279
19280 DebugOnly<uint32_t> initialStack = masm.framePushed();
19281
19282 masm.checkStackAlignment();
19283
19284 // Push the argument. Rooting will happen at GC time.
19285 ValueOperand argVal = ToValue(ins->value());
19286 masm.Push(argVal);
19287 // We pass the pointer to our out param as an instance of
19288 // JSJitGetterCallArgs, since on the binary level it's the same thing.
19289 static_assert(sizeof(JSJitSetterCallArgs) == sizeof(Value*));
19290 masm.moveStackPtrTo(ValueReg);
19291
19292 masm.Push(ObjectReg);
19293
19294 LoadDOMPrivate(masm, ObjectReg, PrivateReg, ins->mir()->objectKind());
19295
19296 // Rooting will happen at GC time.
19297 masm.moveStackPtrTo(ObjectReg);
19298
19299 Realm* setterRealm = ins->mir()->setterRealm();
19300 if (gen->realm->realmPtr() != setterRealm) {
19301 // We use JSContextReg as scratch register here.
19302 masm.switchToRealm(setterRealm, JSContextReg);
19303 }
19304
19305 uint32_t safepointOffset = masm.buildFakeExitFrame(JSContextReg);
19306 masm.loadJSContext(JSContextReg);
19307 masm.enterFakeExitFrame(JSContextReg, JSContextReg,
19308 ExitFrameType::IonDOMSetter);
19309
19310 markSafepointAt(safepointOffset, ins);
19311
19312 masm.setupAlignedABICall();
19313 masm.loadJSContext(JSContextReg);
19314 masm.passABIArg(JSContextReg);
19315 masm.passABIArg(ObjectReg);
19316 masm.passABIArg(PrivateReg);
19317 masm.passABIArg(ValueReg);
19318 ensureOsiSpace();
19319 masm.callWithABI(DynamicFunction<JSJitSetterOp>(ins->mir()->fun()),
19320 ABIType::General,
19321 CheckUnsafeCallWithABI::DontCheckHasExitFrame);
19322
19323 masm.branchIfFalseBool(ReturnReg, masm.exceptionLabel());
19324
19325 // Switch back to the current realm if needed. Note: if the setter threw an
19326 // exception, the exception handler will do this.
19327 if (gen->realm->realmPtr() != setterRealm) {
19328 masm.switchToRealm(gen->realm->realmPtr(), ReturnReg);
19329 }
19330
19331 masm.adjustStack(IonDOMExitFrameLayout::Size());
19332
19333 MOZ_ASSERT(masm.framePushed() == initialStack);
19334 }
19335
19336 void CodeGenerator::visitLoadDOMExpandoValue(LLoadDOMExpandoValue* ins) {
19337 Register proxy = ToRegister(ins->proxy());
19338 ValueOperand out = ToOutValue(ins);
19339
19340 masm.loadPtr(Address(proxy, ProxyObject::offsetOfReservedSlots()),
19341 out.scratchReg());
19342 masm.loadValue(Address(out.scratchReg(),
19343 js::detail::ProxyReservedSlots::offsetOfPrivateSlot()),
19344 out);
19345 }
19346
19347 void CodeGenerator::visitLoadDOMExpandoValueGuardGeneration(
19348 LLoadDOMExpandoValueGuardGeneration* ins) {
19349 Register proxy = ToRegister(ins->proxy());
19350 ValueOperand out = ToOutValue(ins);
19351
19352 Label bail;
19353 masm.loadDOMExpandoValueGuardGeneration(proxy, out,
19354 ins->mir()->expandoAndGeneration(),
19355 ins->mir()->generation(), &bail);
19356 bailoutFrom(&bail, ins->snapshot());
19357 }
19358
19359 void CodeGenerator::visitLoadDOMExpandoValueIgnoreGeneration(
19360 LLoadDOMExpandoValueIgnoreGeneration* ins) {
19361 Register proxy = ToRegister(ins->proxy());
19362 ValueOperand out = ToOutValue(ins);
19363
19364 masm.loadPtr(Address(proxy, ProxyObject::offsetOfReservedSlots()),
19365 out.scratchReg());
19366
19367 // Load the ExpandoAndGeneration* from the PrivateValue.
19368 masm.loadPrivate(
19369 Address(out.scratchReg(),
19370 js::detail::ProxyReservedSlots::offsetOfPrivateSlot()),
19371 out.scratchReg());
19372
19373 // Load expandoAndGeneration->expando into the output Value register.
19374 masm.loadValue(
19375 Address(out.scratchReg(), ExpandoAndGeneration::offsetOfExpando()), out);
19376 }
19377
19378 void CodeGenerator::visitGuardDOMExpandoMissingOrGuardShape(
19379 LGuardDOMExpandoMissingOrGuardShape* ins) {
19380 Register temp = ToRegister(ins->temp0());
19381 ValueOperand input = ToValue(ins->input());
19382
19383 Label done;
19384 masm.branchTestUndefined(Assembler::Equal, input, &done);
19385
19386 masm.debugAssertIsObject(input);
19387 masm.unboxObject(input, temp);
19388 // The expando object is not used in this case, so we don't need Spectre
19389 // mitigations.
19390 Label bail;
19391 masm.branchTestObjShapeNoSpectreMitigations(Assembler::NotEqual, temp,
19392 ins->mir()->shape(), &bail);
19393 bailoutFrom(&bail, ins->snapshot());
19394
19395 masm.bind(&done);
19396 }
19397
19398 void CodeGenerator::emitIsCallableOOL(Register object, Register output) {
19399 saveVolatile(output);
19400 using Fn = bool (*)(JSObject* obj);
19401 masm.setupAlignedABICall();
19402 masm.passABIArg(object);
19403 masm.callWithABI<Fn, ObjectIsCallable>();
19404 masm.storeCallBoolResult(output);
19405 restoreVolatile(output);
19406 }
19407
19408 void CodeGenerator::visitIsCallableO(LIsCallableO* ins) {
19409 Register object = ToRegister(ins->object());
19410 Register output = ToRegister(ins->output());
19411
19412 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
19413 emitIsCallableOOL(object, output);
19414 masm.jump(ool.rejoin());
19415 });
19416 addOutOfLineCode(ool, ins->mir());
19417
19418 masm.isCallable(object, output, ool->entry());
19419
19420 masm.bind(ool->rejoin());
19421 }
19422
19423 void CodeGenerator::visitIsCallableV(LIsCallableV* ins) {
19424 ValueOperand val = ToValue(ins->object());
19425 Register output = ToRegister(ins->output());
19426 Register temp = ToRegister(ins->temp0());
19427
19428 Label notObject;
19429 masm.fallibleUnboxObject(val, temp, &notObject);
19430
19431 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
19432 emitIsCallableOOL(temp, output);
19433 masm.jump(ool.rejoin());
19434 });
19435 addOutOfLineCode(ool, ins->mir());
19436
19437 masm.isCallable(temp, output, ool->entry());
19438 masm.jump(ool->rejoin());
19439
19440 masm.bind(&notObject);
19441 masm.move32(Imm32(0), output);
19442
19443 masm.bind(ool->rejoin());
19444 }
19445
19446 void CodeGenerator::visitIsConstructor(LIsConstructor* ins) {
19447 Register object = ToRegister(ins->object());
19448 Register output = ToRegister(ins->output());
19449
19450 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
19451 saveVolatile(output);
19452 using Fn = bool (*)(JSObject* obj);
19453 masm.setupAlignedABICall();
19454 masm.passABIArg(object);
19455 masm.callWithABI<Fn, ObjectIsConstructor>();
19456 masm.storeCallBoolResult(output);
19457 restoreVolatile(output);
19458 masm.jump(ool.rejoin());
19459 });
19460 addOutOfLineCode(ool, ins->mir());
19461
19462 masm.isConstructor(object, output, ool->entry());
19463
19464 masm.bind(ool->rejoin());
19465 }
19466
19467 void CodeGenerator::visitIsCrossRealmArrayConstructor(
19468 LIsCrossRealmArrayConstructor* ins) {
19469 Register object = ToRegister(ins->object());
19470 Register output = ToRegister(ins->output());
19471
19472 masm.setIsCrossRealmArrayConstructor(object, output);
19473 }
19474
19475 static void EmitObjectIsArray(MacroAssembler& masm, OutOfLineCode* ool,
19476 Register obj, Register output,
19477 Label* notArray = nullptr) {
19478 masm.loadObjClassUnsafe(obj, output);
19479
19480 Label isArray;
19481 masm.branchPtr(Assembler::Equal, output, ImmPtr(&ArrayObject::class_),
19482 &isArray);
19483
19484 // Branch to OOL path if it's a proxy.
19485 masm.branchTestClassIsProxy(true, output, ool->entry());
19486
19487 if (notArray) {
19488 masm.bind(notArray);
19489 }
19490 masm.move32(Imm32(0), output);
19491 masm.jump(ool->rejoin());
19492
19493 masm.bind(&isArray);
19494 masm.move32(Imm32(1), output);
19495
19496 masm.bind(ool->rejoin());
19497 }
19498
19499 void CodeGenerator::visitIsArrayO(LIsArrayO* lir) {
19500 Register object = ToRegister(lir->object());
19501 Register output = ToRegister(lir->output());
19502
19503 using Fn = bool (*)(JSContext*, HandleObject, bool*);
19504 OutOfLineCode* ool = oolCallVM<Fn, js::IsArrayFromJit>(
19505 lir, ArgList(object), StoreRegisterTo(output));
19506 EmitObjectIsArray(masm, ool, object, output);
19507 }
19508
19509 void CodeGenerator::visitIsArrayV(LIsArrayV* lir) {
19510 ValueOperand val = ToValue(lir->value());
19511 Register output = ToRegister(lir->output());
19512 Register temp = ToRegister(lir->temp0());
19513
19514 Label notArray;
19515 masm.fallibleUnboxObject(val, temp, &notArray);
19516
19517 using Fn = bool (*)(JSContext*, HandleObject, bool*);
19518 OutOfLineCode* ool = oolCallVM<Fn, js::IsArrayFromJit>(
19519 lir, ArgList(temp), StoreRegisterTo(output));
19520 EmitObjectIsArray(masm, ool, temp, output, &notArray);
19521 }
19522
19523 void CodeGenerator::visitIsTypedArray(LIsTypedArray* lir) {
19524 Register object = ToRegister(lir->object());
19525 Register output = ToRegister(lir->output());
19526
19527 OutOfLineCode* ool = nullptr;
19528 if (lir->mir()->isPossiblyWrapped()) {
19529 using Fn = bool (*)(JSContext*, JSObject*, bool*);
19530 ool = oolCallVM<Fn, jit::IsPossiblyWrappedTypedArray>(
19531 lir, ArgList(object), StoreRegisterTo(output));
19532 }
19533
19534 Label notTypedArray;
19535 Label done;
19536
19537 masm.loadObjClassUnsafe(object, output);
19538 masm.branchIfClassIsNotTypedArray(output, &notTypedArray);
19539
19540 masm.move32(Imm32(1), output);
19541 masm.jump(&done);
19542 masm.bind(&notTypedArray);
19543 if (ool) {
19544 Label notProxy;
19545 masm.branchTestClassIsProxy(false, output, &notProxy);
19546 masm.branchTestProxyHandlerFamily(Assembler::Equal, object, output,
19547 &Wrapper::family, ool->entry());
19548 masm.bind(&notProxy);
19549 }
19550 masm.move32(Imm32(0), output);
19551 masm.bind(&done);
19552 if (ool) {
19553 masm.bind(ool->rejoin());
19554 }
19555 }
19556
19557 void CodeGenerator::visitIsObject(LIsObject* ins) {
19558 Register output = ToRegister(ins->output());
19559 ValueOperand value = ToValue(ins->object());
19560 masm.testObjectSet(Assembler::Equal, value, output);
19561 }
19562
19563 void CodeGenerator::visitIsObjectAndBranch(LIsObjectAndBranch* ins) {
19564 ValueOperand value = ToValue(ins->input());
19565
19566 MBasicBlock* ifTrue = ins->ifTrue();
19567 MBasicBlock* ifFalse = ins->ifFalse();
19568
19569 if (isNextBlock(ifFalse->lir())) {
19570 masm.branchTestObject(Assembler::Equal, value,
19571 getJumpLabelForBranch(ifTrue));
19572 } else {
19573 masm.branchTestObject(Assembler::NotEqual, value,
19574 getJumpLabelForBranch(ifFalse));
19575 jumpToBlock(ifTrue);
19576 }
19577 }
19578
19579 void CodeGenerator::visitIsNullOrUndefined(LIsNullOrUndefined* ins) {
19580 Register output = ToRegister(ins->output());
19581 ValueOperand value = ToValue(ins->value());
19582
19583 Label isNotNull, done;
19584 masm.branchTestNull(Assembler::NotEqual, value, &isNotNull);
19585
19586 masm.move32(Imm32(1), output);
19587 masm.jump(&done);
19588
19589 masm.bind(&isNotNull);
19590 masm.testUndefinedSet(Assembler::Equal, value, output);
19591
19592 masm.bind(&done);
19593 }
19594
19595 void CodeGenerator::visitIsNullOrUndefinedAndBranch(
19596 LIsNullOrUndefinedAndBranch* ins) {
19597 Label* ifTrue = getJumpLabelForBranch(ins->ifTrue());
19598 Label* ifFalse = getJumpLabelForBranch(ins->ifFalse());
19599 ValueOperand value = ToValue(ins->input());
19600
19601 ScratchTagScope tag(masm, value);
19602 masm.splitTagForTest(value, tag);
19603
19604 masm.branchTestNull(Assembler::Equal, tag, ifTrue);
19605 masm.branchTestUndefined(Assembler::Equal, tag, ifTrue);
19606
19607 if (!isNextBlock(ins->ifFalse()->lir())) {
19608 masm.jump(ifFalse);
19609 }
19610 }
19611
19612 void CodeGenerator::visitHasClass(LHasClass* ins) {
19613 Register lhs = ToRegister(ins->lhs());
19614 Register output = ToRegister(ins->output());
19615
19616 masm.loadObjClassUnsafe(lhs, output);
19617 masm.cmpPtrSet(Assembler::Equal, output, ImmPtr(ins->mir()->getClass()),
19618 output);
19619 }
19620
19621 void CodeGenerator::visitHasShape(LHasShape* ins) {
19622 Register obj = ToRegister(ins->object());
19623 Register output = ToRegister(ins->output());
19624
19625 // Note: no Spectre mitigations are needed here because this shape check only
19626 // affects correctness.
19627 masm.loadObjShapeUnsafe(obj, output);
19628 masm.cmpPtrSet(Assembler::Equal, output, ImmGCPtr(ins->mir()->shape()),
19629 output);
19630 }
19631
19632 void CodeGenerator::visitGuardToClass(LGuardToClass* ins) {
19633 Register lhs = ToRegister(ins->lhs());
19634 Register temp = ToRegister(ins->temp0());
19635
19636 // branchTestObjClass may zero the object register on speculative paths
19637 // (we should have a defineReuseInput allocation in this case).
19638 Register spectreRegToZero = lhs;
19639
19640 Label notEqual;
19641
19642 masm.branchTestObjClass(Assembler::NotEqual, lhs, ins->mir()->getClass(),
19643 temp, spectreRegToZero, &notEqual);
19644
19645 // Can't return null-return here, so bail.
19646 bailoutFrom(&notEqual, ins->snapshot());
19647 }
19648
19649 void CodeGenerator::visitGuardToEitherClass(LGuardToEitherClass* ins) {
19650 Register lhs = ToRegister(ins->lhs());
19651 Register temp = ToRegister(ins->temp0());
19652
19653 // branchTestObjClass may zero the object register on speculative paths
19654 // (we should have a defineReuseInput allocation in this case).
19655 Register spectreRegToZero = lhs;
19656
19657 Label notEqual;
19658
19659 masm.branchTestObjClass(Assembler::NotEqual, lhs,
19660 {ins->mir()->getClass1(), ins->mir()->getClass2()},
19661 temp, spectreRegToZero, &notEqual);
19662
19663 // Can't return null-return here, so bail.
19664 bailoutFrom(&notEqual, ins->snapshot());
19665 }
19666
19667 void CodeGenerator::visitGuardToFunction(LGuardToFunction* ins) {
19668 Register lhs = ToRegister(ins->lhs());
19669 Register temp = ToRegister(ins->temp0());
19670
19671 // branchTestObjClass may zero the object register on speculative paths
19672 // (we should have a defineReuseInput allocation in this case).
19673 Register spectreRegToZero = lhs;
19674
19675 Label notEqual;
19676
19677 masm.branchTestObjIsFunction(Assembler::NotEqual, lhs, temp, spectreRegToZero,
19678 &notEqual);
19679
19680 // Can't return null-return here, so bail.
19681 bailoutFrom(&notEqual, ins->snapshot());
19682 }
19683
19684 void CodeGenerator::visitObjectClassToString(LObjectClassToString* lir) {
19685 Register obj = ToRegister(lir->object());
19686 Register temp = ToRegister(lir->temp0());
19687
19688 using Fn = JSString* (*)(JSContext*, JSObject*);
19689 masm.setupAlignedABICall();
19690 masm.loadJSContext(temp);
19691 masm.passABIArg(temp);
19692 masm.passABIArg(obj);
19693 masm.callWithABI<Fn, js::ObjectClassToString>();
19694
19695 bailoutCmpPtr(Assembler::Equal, ReturnReg, ImmWord(0), lir->snapshot());
19696 }
19697
19698 void CodeGenerator::visitWasmParameter(LWasmParameter* lir) {}
19699
19700 void CodeGenerator::visitWasmParameterI64(LWasmParameterI64* lir) {}
19701
19702 void CodeGenerator::visitWasmReturn(LWasmReturn* lir) {
19703 // Don't emit a jump to the return label if this is the last block.
19704 if (current->mir() != *gen->graph().poBegin()) {
19705 masm.jump(&returnLabel_);
19706 }
19707 }
19708
19709 void CodeGenerator::visitWasmReturnI64(LWasmReturnI64* lir) {
19710 // Don't emit a jump to the return label if this is the last block.
19711 if (current->mir() != *gen->graph().poBegin()) {
19712 masm.jump(&returnLabel_);
19713 }
19714 }
19715
19716 void CodeGenerator::visitWasmReturnVoid(LWasmReturnVoid* lir) {
19717 // Don't emit a jump to the return label if this is the last block.
19718 if (current->mir() != *gen->graph().poBegin()) {
19719 masm.jump(&returnLabel_);
19720 }
19721 }
19722
19723 void CodeGenerator::emitAssertRangeI(MIRType type, const Range* r,
19724 Register input) {
19725 // Check the lower bound.
19726 if (r->hasInt32LowerBound() && r->lower() > INT32_MIN) {
19727 Label success;
19728 if (type == MIRType::Int32 || type == MIRType::Boolean) {
19729 masm.branch32(Assembler::GreaterThanOrEqual, input, Imm32(r->lower()),
19730 &success);
19731 } else {
19732 MOZ_ASSERT(type == MIRType::IntPtr);
19733 masm.branchPtr(Assembler::GreaterThanOrEqual, input, Imm32(r->lower()),
19734 &success);
19735 }
19736 masm.assumeUnreachable(
19737 "Integer input should be equal or higher than Lowerbound.");
19738 masm.bind(&success);
19739 }
19740
19741 // Check the upper bound.
19742 if (r->hasInt32UpperBound() && r->upper() < INT32_MAX) {
19743 Label success;
19744 if (type == MIRType::Int32 || type == MIRType::Boolean) {
19745 masm.branch32(Assembler::LessThanOrEqual, input, Imm32(r->upper()),
19746 &success);
19747 } else {
19748 MOZ_ASSERT(type == MIRType::IntPtr);
19749 masm.branchPtr(Assembler::LessThanOrEqual, input, Imm32(r->upper()),
19750 &success);
19751 }
19752 masm.assumeUnreachable(
19753 "Integer input should be lower or equal than Upperbound.");
19754 masm.bind(&success);
19755 }
19756
19757 // For r->canHaveFractionalPart(), r->canBeNegativeZero(), and
19758 // r->exponent(), there's nothing to check, because if we ended up in the
19759 // integer range checking code, the value is already in an integer register
19760 // in the integer range.
19761 }
19762
19763 void CodeGenerator::emitAssertRangeD(const Range* r, FloatRegister input,
19764 FloatRegister temp) {
19765 // Check the lower bound.
19766 if (r->hasInt32LowerBound()) {
19767 Label success;
19768 masm.loadConstantDouble(r->lower(), temp);
19769 if (r->canBeNaN()) {
19770 masm.branchDouble(Assembler::DoubleUnordered, input, input, &success);
19771 }
19772 masm.branchDouble(Assembler::DoubleGreaterThanOrEqual, input, temp,
19773 &success);
19774 masm.assumeUnreachable(
19775 "Double input should be equal or higher than Lowerbound.");
19776 masm.bind(&success);
19777 }
19778 // Check the upper bound.
19779 if (r->hasInt32UpperBound()) {
19780 Label success;
19781 masm.loadConstantDouble(r->upper(), temp);
19782 if (r->canBeNaN()) {
19783 masm.branchDouble(Assembler::DoubleUnordered, input, input, &success);
19784 }
19785 masm.branchDouble(Assembler::DoubleLessThanOrEqual, input, temp, &success);
19786 masm.assumeUnreachable(
19787 "Double input should be lower or equal than Upperbound.");
19788 masm.bind(&success);
19789 }
19790
19791 // This code does not yet check r->canHaveFractionalPart(). This would require
19792 // new assembler interfaces to make rounding instructions available.
19793
19794 if (!r->canBeNegativeZero()) {
19795 Label success;
19796
19797 // First, test for being equal to 0.0, which also includes -0.0.
19798 masm.loadConstantDouble(0.0, temp);
19799 masm.branchDouble(Assembler::DoubleNotEqualOrUnordered, input, temp,
19800 &success);
19801
19802 // The easiest way to distinguish -0.0 from 0.0 is that 1.0/-0.0 is
19803 // -Infinity instead of Infinity.
19804 masm.loadConstantDouble(1.0, temp);
19805 masm.divDouble(input, temp);
19806 masm.branchDouble(Assembler::DoubleGreaterThan, temp, input, &success);
19807
19808 masm.assumeUnreachable("Input shouldn't be negative zero.");
19809
19810 masm.bind(&success);
19811 }
19812
19813 if (!r->hasInt32Bounds() && !r->canBeInfiniteOrNaN() &&
19814 r->exponent() < FloatingPoint<double>::kExponentBias) {
19815 // Check the bounds implied by the maximum exponent.
19816 Label exponentLoOk;
19817 masm.loadConstantDouble(pow(2.0, r->exponent() + 1), temp);
19818 masm.branchDouble(Assembler::DoubleUnordered, input, input, &exponentLoOk);
19819 masm.branchDouble(Assembler::DoubleLessThanOrEqual, input, temp,
19820 &exponentLoOk);
19821 masm.assumeUnreachable("Check for exponent failed.");
19822 masm.bind(&exponentLoOk);
19823
19824 Label exponentHiOk;
19825 masm.loadConstantDouble(-pow(2.0, r->exponent() + 1), temp);
19826 masm.branchDouble(Assembler::DoubleUnordered, input, input, &exponentHiOk);
19827 masm.branchDouble(Assembler::DoubleGreaterThanOrEqual, input, temp,
19828 &exponentHiOk);
19829 masm.assumeUnreachable("Check for exponent failed.");
19830 masm.bind(&exponentHiOk);
19831 } else if (!r->hasInt32Bounds() && !r->canBeNaN()) {
19832 // If we think the value can't be NaN, check that it isn't.
19833 Label notnan;
19834 masm.branchDouble(Assembler::DoubleOrdered, input, input, &notnan);
19835 masm.assumeUnreachable("Input shouldn't be NaN.");
19836 masm.bind(&notnan);
19837
19838 // If we think the value also can't be an infinity, check that it isn't.
19839 if (!r->canBeInfiniteOrNaN()) {
19840 Label notposinf;
19841 masm.loadConstantDouble(PositiveInfinity<double>(), temp);
19842 masm.branchDouble(Assembler::DoubleLessThan, input, temp, &notposinf);
19843 masm.assumeUnreachable("Input shouldn't be +Inf.");
19844 masm.bind(&notposinf);
19845
19846 Label notneginf;
19847 masm.loadConstantDouble(NegativeInfinity<double>(), temp);
19848 masm.branchDouble(Assembler::DoubleGreaterThan, input, temp, &notneginf);
19849 masm.assumeUnreachable("Input shouldn't be -Inf.");
19850 masm.bind(&notneginf);
19851 }
19852 }
19853 }
19854
19855 void CodeGenerator::visitAssertClass(LAssertClass* ins) {
19856 Register obj = ToRegister(ins->input());
19857 Register temp = ToRegister(ins->temp0());
19858
19859 Label success;
19860 if (ins->mir()->getClass() == &FunctionClass) {
19861 // Allow both possible function classes here.
19862 masm.branchTestObjIsFunctionNoSpectreMitigations(Assembler::Equal, obj,
19863 temp, &success);
19864 } else {
19865 masm.branchTestObjClassNoSpectreMitigations(
19866 Assembler::Equal, obj, ins->mir()->getClass(), temp, &success);
19867 }
19868 masm.assumeUnreachable("Wrong KnownClass during run-time");
19869 masm.bind(&success);
19870 }
19871
19872 void CodeGenerator::visitAssertShape(LAssertShape* ins) {
19873 Register obj = ToRegister(ins->input());
19874
19875 Label success;
19876 masm.branchTestObjShapeNoSpectreMitigations(Assembler::Equal, obj,
19877 ins->mir()->shape(), &success);
19878 masm.assumeUnreachable("Wrong Shape during run-time");
19879 masm.bind(&success);
19880 }
19881
19882 void CodeGenerator::visitAssertRangeI(LAssertRangeI* ins) {
19883 Register input = ToRegister(ins->input());
19884 const Range* r = ins->mir()->assertedRange();
19885
19886 emitAssertRangeI(ins->mir()->input()->type(), r, input);
19887 }
19888
19889 void CodeGenerator::visitAssertRangeD(LAssertRangeD* ins) {
19890 FloatRegister input = ToFloatRegister(ins->input());
19891 FloatRegister temp = ToFloatRegister(ins->temp0());
19892 const Range* r = ins->mir()->assertedRange();
19893
19894 emitAssertRangeD(r, input, temp);
19895 }
19896
19897 void CodeGenerator::visitAssertRangeF(LAssertRangeF* ins) {
19898 FloatRegister input = ToFloatRegister(ins->input());
19899 FloatRegister temp = ToFloatRegister(ins->temp0());
19900 FloatRegister temp2 = ToFloatRegister(ins->temp1());
19901
19902 const Range* r = ins->mir()->assertedRange();
19903
19904 masm.convertFloat32ToDouble(input, temp);
19905 emitAssertRangeD(r, temp, temp2);
19906 }
19907
19908 void CodeGenerator::visitAssertRangeV(LAssertRangeV* ins) {
19909 const Range* r = ins->mir()->assertedRange();
19910 ValueOperand value = ToValue(ins->input());
19911 Label done;
19912
19913 {
19914 ScratchTagScope tag(masm, value);
19915 masm.splitTagForTest(value, tag);
19916
19917 {
19918 Label isNotInt32;
19919 masm.branchTestInt32(Assembler::NotEqual, tag, &isNotInt32);
19920 {
19921 ScratchTagScopeRelease _(&tag);
19922 Register unboxInt32 = ToTempUnboxRegister(ins->temp0());
19923 Register input = masm.extractInt32(value, unboxInt32);
19924 emitAssertRangeI(MIRType::Int32, r, input);
19925 masm.jump(&done);
19926 }
19927 masm.bind(&isNotInt32);
19928 }
19929
19930 {
19931 Label isNotDouble;
19932 masm.branchTestDouble(Assembler::NotEqual, tag, &isNotDouble);
19933 {
19934 ScratchTagScopeRelease _(&tag);
19935 FloatRegister input = ToFloatRegister(ins->temp1());
19936 FloatRegister temp = ToFloatRegister(ins->temp2());
19937 masm.unboxDouble(value, input);
19938 emitAssertRangeD(r, input, temp);
19939 masm.jump(&done);
19940 }
19941 masm.bind(&isNotDouble);
19942 }
19943 }
19944
19945 masm.assumeUnreachable("Incorrect range for Value.");
19946 masm.bind(&done);
19947 }
19948
19949 void CodeGenerator::visitInterruptCheck(LInterruptCheck* lir) {
19950 using Fn = bool (*)(JSContext*);
19951 OutOfLineCode* ool =
19952 oolCallVM<Fn, InterruptCheck>(lir, ArgList(), StoreNothing());
19953
19954 const void* interruptAddr = gen->runtime->addressOfInterruptBits();
19955 masm.branch32(Assembler::NotEqual, AbsoluteAddress(interruptAddr), Imm32(0),
19956 ool->entry());
19957 masm.bind(ool->rejoin());
19958 }
19959
19960 void CodeGenerator::visitWasmInterruptCheck(LWasmInterruptCheck* lir) {
19961 MOZ_ASSERT(gen->compilingWasm());
19962
19963 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
19964 emitResumableWasmTrapOOL(lir, masm.framePushed(),
19965 lir->mir()->trapSiteDesc(),
19966 wasm::Trap::CheckInterrupt);
19967 masm.jump(ool.rejoin());
19968 });
19969 addOutOfLineCode(ool, lir->mir());
19970 masm.branch32(
19971 Assembler::NotEqual,
19972 Address(ToRegister(lir->instance()), wasm::Instance::offsetOfInterrupt()),
19973 Imm32(0), ool->entry());
19974 masm.bind(ool->rejoin());
19975 }
19976
19977 void CodeGenerator::visitWasmTrap(LWasmTrap* lir) {
19978 MOZ_ASSERT(gen->compilingWasm());
19979 const MWasmTrap* mir = lir->mir();
19980
19981 masm.wasmTrap(mir->trap(), mir->trapSiteDesc());
19982 }
19983
19984 void CodeGenerator::visitWasmRefAsNonNull(LWasmRefAsNonNull* lir) {
19985 MOZ_ASSERT(gen->compilingWasm());
19986 const MWasmRefAsNonNull* mir = lir->mir();
19987 Label nonNull;
19988 Register ref = ToRegister(lir->ref());
19989
19990 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
19991 masm.wasmTrap(wasm::Trap::NullPointerDereference, mir->trapSiteDesc());
19992 });
19993 addOutOfLineCode(ool, mir);
19994 masm.branchWasmAnyRefIsNull(true, ref, ool->entry());
19995 }
19996
19997 void CodeGenerator::visitWasmRefTestAbstract(LWasmRefTestAbstract* ins) {
19998 MOZ_ASSERT(gen->compilingWasm());
19999
20000 const MWasmRefTestAbstract* mir = ins->mir();
20001 MOZ_ASSERT(!mir->destType().isTypeRef());
20002
20003 Register ref = ToRegister(ins->ref());
20004 Register superSTV = Register::Invalid();
20005 Register scratch1 = ToTempRegisterOrInvalid(ins->temp0());
20006 Register scratch2 = Register::Invalid();
20007 Register result = ToRegister(ins->output());
20008 Label onSuccess;
20009 Label onFail;
20010 Label join;
20011 masm.branchWasmRefIsSubtype(ref, mir->ref()->wasmRefType(), mir->destType(),
20012 &onSuccess, /*onSuccess=*/true, superSTV,
20013 scratch1, scratch2);
20014 masm.bind(&onFail);
20015 masm.xor32(result, result);
20016 masm.jump(&join);
20017 masm.bind(&onSuccess);
20018 masm.move32(Imm32(1), result);
20019 masm.bind(&join);
20020 }
20021
20022 void CodeGenerator::visitWasmRefTestConcrete(LWasmRefTestConcrete* ins) {
20023 MOZ_ASSERT(gen->compilingWasm());
20024
20025 const MWasmRefTestConcrete* mir = ins->mir();
20026 MOZ_ASSERT(mir->destType().isTypeRef());
20027
20028 Register ref = ToRegister(ins->ref());
20029 Register superSTV = ToRegister(ins->superSTV());
20030 Register scratch1 = ToRegister(ins->temp0());
20031 Register scratch2 = ToTempRegisterOrInvalid(ins->temp1());
20032 Register result = ToRegister(ins->output());
20033 Label onSuccess;
20034 Label join;
20035 masm.branchWasmRefIsSubtype(ref, mir->ref()->wasmRefType(), mir->destType(),
20036 &onSuccess, /*onSuccess=*/true, superSTV,
20037 scratch1, scratch2);
20038 masm.move32(Imm32(0), result);
20039 masm.jump(&join);
20040 masm.bind(&onSuccess);
20041 masm.move32(Imm32(1), result);
20042 masm.bind(&join);
20043 }
20044
20045 void CodeGenerator::visitWasmRefTestAbstractAndBranch(
20046 LWasmRefTestAbstractAndBranch* ins) {
20047 MOZ_ASSERT(gen->compilingWasm());
20048 Register ref = ToRegister(ins->ref());
20049 Register scratch1 = ToTempRegisterOrInvalid(ins->temp0());
20050 Label* onSuccess = getJumpLabelForBranch(ins->ifTrue());
20051 Label* onFail = getJumpLabelForBranch(ins->ifFalse());
20052 masm.branchWasmRefIsSubtype(
20053 ref, ins->sourceType(), ins->destType(), onSuccess, /*onSuccess=*/true,
20054 Register::Invalid(), scratch1, Register::Invalid());
20055 masm.jump(onFail);
20056 }
20057
20058 void CodeGenerator::visitWasmRefTestConcreteAndBranch(
20059 LWasmRefTestConcreteAndBranch* ins) {
20060 MOZ_ASSERT(gen->compilingWasm());
20061 Register ref = ToRegister(ins->ref());
20062 Register superSTV = ToRegister(ins->superSTV());
20063 Register scratch1 = ToRegister(ins->temp0());
20064 Register scratch2 = ToTempRegisterOrInvalid(ins->temp1());
20065 Label* onSuccess = getJumpLabelForBranch(ins->ifTrue());
20066 Label* onFail = getJumpLabelForBranch(ins->ifFalse());
20067 masm.branchWasmRefIsSubtype(ref, ins->sourceType(), ins->destType(),
20068 onSuccess, /*onSuccess=*/true, superSTV, scratch1,
20069 scratch2);
20070 masm.jump(onFail);
20071 }
20072
20073 void CodeGenerator::visitWasmRefCastAbstract(LWasmRefCastAbstract* ins) {
20074 MOZ_ASSERT(gen->compilingWasm());
20075
20076 const MWasmRefCastAbstract* mir = ins->mir();
20077 MOZ_ASSERT(!mir->destType().isTypeRef());
20078
20079 Register ref = ToRegister(ins->ref());
20080 Register superSTV = Register::Invalid();
20081 Register scratch1 = ToTempRegisterOrInvalid(ins->temp0());
20082 Register scratch2 = Register::Invalid();
20083 MOZ_ASSERT(ref == ToRegister(ins->output()));
20084 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
20085 masm.wasmTrap(wasm::Trap::BadCast, mir->trapSiteDesc());
20086 });
20087 addOutOfLineCode(ool, ins->mir());
20088 masm.branchWasmRefIsSubtype(ref, mir->ref()->wasmRefType(), mir->destType(),
20089 ool->entry(), /*onSuccess=*/false, superSTV,
20090 scratch1, scratch2);
20091 }
20092
20093 void CodeGenerator::visitWasmRefCastConcrete(LWasmRefCastConcrete* ins) {
20094 MOZ_ASSERT(gen->compilingWasm());
20095
20096 const MWasmRefCastConcrete* mir = ins->mir();
20097 MOZ_ASSERT(mir->destType().isTypeRef());
20098
20099 Register ref = ToRegister(ins->ref());
20100 Register superSTV = ToRegister(ins->superSTV());
20101 Register scratch1 = ToRegister(ins->temp0());
20102 Register scratch2 = ToTempRegisterOrInvalid(ins->temp1());
20103 MOZ_ASSERT(ref == ToRegister(ins->output()));
20104 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
20105 masm.wasmTrap(wasm::Trap::BadCast, mir->trapSiteDesc());
20106 });
20107 addOutOfLineCode(ool, ins->mir());
20108 masm.branchWasmRefIsSubtype(ref, mir->ref()->wasmRefType(), mir->destType(),
20109 ool->entry(), /*onSuccess=*/false, superSTV,
20110 scratch1, scratch2);
20111 }
20112
20113 void CodeGenerator::callWasmStructAllocFun(
20114 LInstruction* lir, wasm::SymbolicAddress fun, Register typeDefIndex,
20115 Register allocSite, Register output,
20116 const wasm::TrapSiteDesc& trapSiteDesc) {
20117 MOZ_ASSERT(fun == wasm::SymbolicAddress::StructNewIL_true ||
20118 fun == wasm::SymbolicAddress::StructNewIL_false ||
20119 fun == wasm::SymbolicAddress::StructNewOOL_true ||
20120 fun == wasm::SymbolicAddress::StructNewOOL_false);
20121 MOZ_ASSERT(wasm::SASigStructNewIL_true.failureMode ==
20122 wasm::FailureMode::FailOnNullPtr);
20123 MOZ_ASSERT(wasm::SASigStructNewIL_false.failureMode ==
20124 wasm::FailureMode::FailOnNullPtr);
20125 MOZ_ASSERT(wasm::SASigStructNewOOL_true.failureMode ==
20126 wasm::FailureMode::FailOnNullPtr);
20127 MOZ_ASSERT(wasm::SASigStructNewOOL_false.failureMode ==
20128 wasm::FailureMode::FailOnNullPtr);
20129
20130 masm.Push(InstanceReg);
20131 int32_t framePushedAfterInstance = masm.framePushed();
20132 saveLive(lir);
20133
20134 masm.setupWasmABICall();
20135 masm.passABIArg(InstanceReg);
20136 masm.passABIArg(typeDefIndex);
20137 masm.passABIArg(allocSite);
20138 int32_t instanceOffset = masm.framePushed() - framePushedAfterInstance;
20139 CodeOffset offset =
20140 masm.callWithABI(trapSiteDesc.bytecodeOffset, fun,
20141 mozilla::Some(instanceOffset), ABIType::General);
20142 masm.storeCallPointerResult(output);
20143
20144 markSafepointAt(offset.offset(), lir);
20145 lir->safepoint()->setFramePushedAtStackMapBase(framePushedAfterInstance);
20146 lir->safepoint()->setWasmSafepointKind(WasmSafepointKind::CodegenCall);
20147
20148 restoreLive(lir);
20149 masm.Pop(InstanceReg);
20150 #if JS_CODEGEN_ARM64
20151 masm.syncStackPtr();
20152 #endif
20153
20154 masm.wasmTrapOnFailedInstanceCall(output, wasm::FailureMode::FailOnNullPtr,
20155 trapSiteDesc);
20156 }
20157
20158 void CodeGenerator::visitWasmNewStructObject(LWasmNewStructObject* lir) {
20159 MOZ_ASSERT(gen->compilingWasm());
20160
20161 MWasmNewStructObject* mir = lir->mir();
20162 uint32_t typeDefIndex = wasmCodeMeta()->types->indexOf(mir->typeDef());
20163
20164 Register allocSite = ToRegister(lir->allocSite());
20165 Register output = ToRegister(lir->output());
20166 Register temp = ToRegister(lir->temp0());
20167
20168 if (mir->isOutline()) {
20169 wasm::SymbolicAddress fun = mir->zeroFields()
20170 ? wasm::SymbolicAddress::StructNewOOL_true
20171 : wasm::SymbolicAddress::StructNewOOL_false;
20172
20173 masm.move32(Imm32(typeDefIndex), temp);
20174 callWasmStructAllocFun(lir, fun, temp, allocSite, output,
20175 mir->trapSiteDesc());
20176 } else {
20177 wasm::SymbolicAddress fun = mir->zeroFields()
20178 ? wasm::SymbolicAddress::StructNewIL_true
20179 : wasm::SymbolicAddress::StructNewIL_false;
20180
20181 Register instance = ToRegister(lir->instance());
20182 MOZ_ASSERT(instance == InstanceReg);
20183
20184 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
20185 masm.move32(Imm32(typeDefIndex), temp);
20186 callWasmStructAllocFun(lir, fun, temp, allocSite, output,
20187 mir->trapSiteDesc());
20188 masm.jump(ool.rejoin());
20189 });
20190 addOutOfLineCode(ool, lir->mir());
20191
20192 size_t offsetOfTypeDefData = wasm::Instance::offsetInData(
20193 wasmCodeMeta()->offsetOfTypeDefInstanceData(typeDefIndex));
20194 masm.wasmNewStructObject(instance, output, allocSite, temp,
20195 offsetOfTypeDefData, ool->entry(),
20196 mir->allocKind(), mir->zeroFields());
20197
20198 masm.bind(ool->rejoin());
20199 }
20200 }
20201
20202 void CodeGenerator::callWasmArrayAllocFun(
20203 LInstruction* lir, wasm::SymbolicAddress fun, Register numElements,
20204 Register typeDefIndex, Register allocSite, Register output,
20205 const wasm::TrapSiteDesc& trapSiteDesc) {
20206 MOZ_ASSERT(fun == wasm::SymbolicAddress::ArrayNew_true ||
20207 fun == wasm::SymbolicAddress::ArrayNew_false);
20208 MOZ_ASSERT(wasm::SASigArrayNew_true.failureMode ==
20209 wasm::FailureMode::FailOnNullPtr);
20210 MOZ_ASSERT(wasm::SASigArrayNew_false.failureMode ==
20211 wasm::FailureMode::FailOnNullPtr);
20212
20213 masm.Push(InstanceReg);
20214 int32_t framePushedAfterInstance = masm.framePushed();
20215 saveLive(lir);
20216
20217 masm.setupWasmABICall();
20218 masm.passABIArg(InstanceReg);
20219 masm.passABIArg(numElements);
20220 masm.passABIArg(typeDefIndex);
20221 masm.passABIArg(allocSite);
20222 int32_t instanceOffset = masm.framePushed() - framePushedAfterInstance;
20223 CodeOffset offset =
20224 masm.callWithABI(trapSiteDesc.bytecodeOffset, fun,
20225 mozilla::Some(instanceOffset), ABIType::General);
20226 masm.storeCallPointerResult(output);
20227
20228 markSafepointAt(offset.offset(), lir);
20229 lir->safepoint()->setFramePushedAtStackMapBase(framePushedAfterInstance);
20230 lir->safepoint()->setWasmSafepointKind(WasmSafepointKind::CodegenCall);
20231
20232 restoreLive(lir);
20233 masm.Pop(InstanceReg);
20234 #if JS_CODEGEN_ARM64
20235 masm.syncStackPtr();
20236 #endif
20237
20238 masm.wasmTrapOnFailedInstanceCall(output, wasm::FailureMode::FailOnNullPtr,
20239 trapSiteDesc);
20240 }
20241
20242 void CodeGenerator::visitWasmNewArrayObject(LWasmNewArrayObject* lir) {
20243 MOZ_ASSERT(gen->compilingWasm());
20244
20245 MWasmNewArrayObject* mir = lir->mir();
20246 uint32_t typeDefIndex = wasmCodeMeta()->types->indexOf(mir->typeDef());
20247
20248 Register allocSite = ToRegister(lir->allocSite());
20249 Register output = ToRegister(lir->output());
20250 Register temp0 = ToRegister(lir->temp0());
20251 Register temp1 = ToRegister(lir->temp1());
20252
20253 wasm::SymbolicAddress fun = mir->zeroFields()
20254 ? wasm::SymbolicAddress::ArrayNew_true
20255 : wasm::SymbolicAddress::ArrayNew_false;
20256
20257 if (lir->numElements()->isConstant()) {
20258 // numElements is constant, so we can do optimized code generation.
20259 uint32_t numElements = lir->numElements()->toConstant()->toInt32();
20260 CheckedUint32 storageBytes =
20261 WasmArrayObject::calcStorageBytesChecked(mir->elemSize(), numElements);
20262 if (!storageBytes.isValid() ||
20263 storageBytes.value() > WasmArrayObject_MaxInlineBytes) {
20264 // Too much array data to store inline. Immediately perform an instance
20265 // call to handle the out-of-line storage (or the trap).
20266 masm.move32(Imm32(typeDefIndex), temp0);
20267 masm.move32(Imm32(numElements), temp1);
20268 callWasmArrayAllocFun(lir, fun, temp1, temp0, allocSite, output,
20269 mir->trapSiteDesc());
20270 } else {
20271 // storageBytes is small enough to be stored inline in WasmArrayObject.
20272 // Attempt a nursery allocation and fall back to an instance call if it
20273 // fails.
20274 Register instance = ToRegister(lir->instance());
20275 MOZ_ASSERT(instance == InstanceReg);
20276
20277 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
20278 masm.move32(Imm32(typeDefIndex), temp0);
20279 masm.move32(Imm32(numElements), temp1);
20280 callWasmArrayAllocFun(lir, fun, temp1, temp0, allocSite, output,
20281 mir->trapSiteDesc());
20282 masm.jump(ool.rejoin());
20283 });
20284 addOutOfLineCode(ool, lir->mir());
20285
20286 size_t offsetOfTypeDefData = wasm::Instance::offsetInData(
20287 wasmCodeMeta()->offsetOfTypeDefInstanceData(typeDefIndex));
20288 masm.wasmNewArrayObjectFixed(
20289 instance, output, allocSite, temp0, temp1, offsetOfTypeDefData,
20290 ool->entry(), numElements, storageBytes.value(), mir->zeroFields());
20291
20292 masm.bind(ool->rejoin());
20293 }
20294 } else {
20295 // numElements is dynamic. Attempt a dynamic inline-storage nursery
20296 // allocation and fall back to an instance call if it fails.
20297 Register instance = ToRegister(lir->instance());
20298 MOZ_ASSERT(instance == InstanceReg);
20299 Register numElements = ToRegister(lir->numElements());
20300
20301 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
20302 masm.move32(Imm32(typeDefIndex), temp0);
20303 callWasmArrayAllocFun(lir, fun, numElements, temp0, allocSite, output,
20304 mir->trapSiteDesc());
20305 masm.jump(ool.rejoin());
20306 });
20307 addOutOfLineCode(ool, lir->mir());
20308
20309 size_t offsetOfTypeDefData = wasm::Instance::offsetInData(
20310 wasmCodeMeta()->offsetOfTypeDefInstanceData(typeDefIndex));
20311 masm.wasmNewArrayObject(instance, output, numElements, allocSite, temp1,
20312 offsetOfTypeDefData, ool->entry(), mir->elemSize(),
20313 mir->zeroFields());
20314
20315 masm.bind(ool->rejoin());
20316 }
20317 }
20318
20319 void CodeGenerator::visitWasmHeapReg(LWasmHeapReg* ins) {
20320 #ifdef WASM_HAS_HEAPREG
20321 masm.movePtr(HeapReg, ToRegister(ins->output()));
20322 #else
20323 MOZ_CRASH();
20324 #endif
20325 }
20326
20327 void CodeGenerator::emitResumableWasmTrapOOL(
20328 LInstruction* lir, size_t framePushed,
20329 const wasm::TrapSiteDesc& trapSiteDesc, wasm::Trap trap) {
20330 masm.wasmTrap(trap, trapSiteDesc);
20331
20332 markSafepointAt(masm.currentOffset(), lir);
20333
20334 // Note that masm.framePushed() doesn't include the register dump area.
20335 // That will be taken into account when the StackMap is created from the
20336 // LSafepoint.
20337 lir->safepoint()->setFramePushedAtStackMapBase(framePushed);
20338 lir->safepoint()->setWasmSafepointKind(WasmSafepointKind::Trap);
20339 }
20340
20341 void CodeGenerator::visitWasmBoundsCheck(LWasmBoundsCheck* ins) {
20342 const MWasmBoundsCheck* mir = ins->mir();
20343 Register ptr = ToRegister(ins->ptr());
20344 Register boundsCheckLimit = ToRegister(ins->boundsCheckLimit());
20345 // When there are no spectre mitigations in place, branching out-of-line to
20346 // the trap is a big performance win, but with mitigations it's trickier. See
20347 // bug 1680243.
20348 if (JitOptions.spectreIndexMasking) {
20349 Label ok;
20350 masm.wasmBoundsCheck32(Assembler::Below, ptr, boundsCheckLimit, &ok);
20351 masm.wasmTrap(wasm::Trap::OutOfBounds, mir->trapSiteDesc());
20352 masm.bind(&ok);
20353 } else {
20354 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
20355 masm.wasmTrap(wasm::Trap::OutOfBounds, mir->trapSiteDesc());
20356 });
20357 addOutOfLineCode(ool, mir);
20358 masm.wasmBoundsCheck32(Assembler::AboveOrEqual, ptr, boundsCheckLimit,
20359 ool->entry());
20360 }
20361 }
20362
20363 void CodeGenerator::visitWasmBoundsCheck64(LWasmBoundsCheck64* ins) {
20364 const MWasmBoundsCheck* mir = ins->mir();
20365 Register64 ptr = ToRegister64(ins->ptr());
20366 Register64 boundsCheckLimit = ToRegister64(ins->boundsCheckLimit());
20367 // See above.
20368 if (JitOptions.spectreIndexMasking) {
20369 Label ok;
20370 masm.wasmBoundsCheck64(Assembler::Below, ptr, boundsCheckLimit, &ok);
20371 masm.wasmTrap(wasm::Trap::OutOfBounds, mir->trapSiteDesc());
20372 masm.bind(&ok);
20373 } else {
20374 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
20375 masm.wasmTrap(wasm::Trap::OutOfBounds, mir->trapSiteDesc());
20376 });
20377 addOutOfLineCode(ool, mir);
20378 masm.wasmBoundsCheck64(Assembler::AboveOrEqual, ptr, boundsCheckLimit,
20379 ool->entry());
20380 }
20381 }
20382
20383 void CodeGenerator::visitWasmBoundsCheckRange32(LWasmBoundsCheckRange32* ins) {
20384 const MWasmBoundsCheckRange32* mir = ins->mir();
20385 Register index = ToRegister(ins->index());
20386 Register length = ToRegister(ins->length());
20387 Register limit = ToRegister(ins->limit());
20388 Register tmp = ToRegister(ins->temp0());
20389
20390 masm.wasmBoundsCheckRange32(index, length, limit, tmp, mir->trapSiteDesc());
20391 }
20392
20393 void CodeGenerator::visitWasmAlignmentCheck(LWasmAlignmentCheck* ins) {
20394 const MWasmAlignmentCheck* mir = ins->mir();
20395 Register ptr = ToRegister(ins->ptr());
20396 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
20397 masm.wasmTrap(wasm::Trap::UnalignedAccess, mir->trapSiteDesc());
20398 });
20399 addOutOfLineCode(ool, mir);
20400 masm.branchTest32(Assembler::NonZero, ptr, Imm32(mir->byteSize() - 1),
20401 ool->entry());
20402 }
20403
20404 void CodeGenerator::visitWasmAlignmentCheck64(LWasmAlignmentCheck64* ins) {
20405 const MWasmAlignmentCheck* mir = ins->mir();
20406 Register64 ptr = ToRegister64(ins->ptr());
20407 #ifdef JS_64BIT
20408 Register r = ptr.reg;
20409 #else
20410 Register r = ptr.low;
20411 #endif
20412 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
20413 masm.wasmTrap(wasm::Trap::UnalignedAccess, mir->trapSiteDesc());
20414 });
20415 addOutOfLineCode(ool, mir);
20416 masm.branchTestPtr(Assembler::NonZero, r, Imm32(mir->byteSize() - 1),
20417 ool->entry());
20418 }
20419
20420 void CodeGenerator::visitWasmLoadInstance(LWasmLoadInstance* ins) {
20421 switch (ins->mir()->type()) {
20422 case MIRType::WasmAnyRef:
20423 case MIRType::Pointer:
20424 masm.loadPtr(Address(ToRegister(ins->instance()), ins->mir()->offset()),
20425 ToRegister(ins->output()));
20426 break;
20427 case MIRType::Int32:
20428 masm.load32(Address(ToRegister(ins->instance()), ins->mir()->offset()),
20429 ToRegister(ins->output()));
20430 break;
20431 default:
20432 MOZ_CRASH("MIRType not supported in WasmLoadInstance");
20433 }
20434 }
20435
20436 void CodeGenerator::visitWasmLoadInstance64(LWasmLoadInstance64* ins) {
20437 MOZ_ASSERT(ins->mir()->type() == MIRType::Int64);
20438 masm.load64(Address(ToRegister(ins->instance()), ins->mir()->offset()),
20439 ToOutRegister64(ins));
20440 }
20441
20442 void CodeGenerator::incrementWarmUpCounter(AbsoluteAddress warmUpCount,
20443 JSScript* script, Register tmp) {
20444 // The code depends on the JitScript* not being discarded without also
20445 // invalidating Ion code. Assert this.
20446 #ifdef DEBUG
20447 Label ok;
20448 masm.movePtr(ImmGCPtr(script), tmp);
20449 masm.loadJitScript(tmp, tmp);
20450 masm.branchPtr(Assembler::Equal, tmp, ImmPtr(script->jitScript()), &ok);
20451 masm.assumeUnreachable("Didn't find JitScript?");
20452 masm.bind(&ok);
20453 #endif
20454
20455 masm.load32(warmUpCount, tmp);
20456 masm.add32(Imm32(1), tmp);
20457 masm.store32(tmp, warmUpCount);
20458 }
20459
20460 void CodeGenerator::visitIncrementWarmUpCounter(LIncrementWarmUpCounter* ins) {
20461 Register tmp = ToRegister(ins->temp0());
20462
20463 AbsoluteAddress warmUpCount =
20464 AbsoluteAddress(ins->mir()->script()->jitScript())
20465 .offset(JitScript::offsetOfWarmUpCount());
20466 incrementWarmUpCounter(warmUpCount, ins->mir()->script(), tmp);
20467 }
20468
20469 void CodeGenerator::visitLexicalCheck(LLexicalCheck* ins) {
20470 ValueOperand inputValue = ToValue(ins->input());
20471 Label bail;
20472 masm.branchTestMagicValue(Assembler::Equal, inputValue,
20473 JS_UNINITIALIZED_LEXICAL, &bail);
20474 bailoutFrom(&bail, ins->snapshot());
20475 }
20476
20477 void CodeGenerator::visitThrowRuntimeLexicalError(
20478 LThrowRuntimeLexicalError* ins) {
20479 pushArg(Imm32(ins->mir()->errorNumber()));
20480
20481 using Fn = bool (*)(JSContext*, unsigned);
20482 callVM<Fn, jit::ThrowRuntimeLexicalError>(ins);
20483 }
20484
20485 void CodeGenerator::visitThrowMsg(LThrowMsg* ins) {
20486 pushArg(Imm32(static_cast<int32_t>(ins->mir()->throwMsgKind())));
20487
20488 using Fn = bool (*)(JSContext*, unsigned);
20489 callVM<Fn, js::ThrowMsgOperation>(ins);
20490 }
20491
20492 void CodeGenerator::visitGlobalDeclInstantiation(
20493 LGlobalDeclInstantiation* ins) {
20494 pushArg(ImmPtr(ins->mir()->resumePoint()->pc()));
20495 pushArg(ImmGCPtr(ins->mir()->block()->info().script()));
20496
20497 using Fn = bool (*)(JSContext*, HandleScript, const jsbytecode*);
20498 callVM<Fn, GlobalDeclInstantiationFromIon>(ins);
20499 }
20500
20501 void CodeGenerator::visitDebugger(LDebugger* ins) {
20502 Register cx = ToRegister(ins->temp0());
20503
20504 masm.loadJSContext(cx);
20505 using Fn = bool (*)(JSContext* cx);
20506 masm.setupAlignedABICall();
20507 masm.passABIArg(cx);
20508 masm.callWithABI<Fn, GlobalHasLiveOnDebuggerStatement>();
20509
20510 Label bail;
20511 masm.branchIfTrueBool(ReturnReg, &bail);
20512 bailoutFrom(&bail, ins->snapshot());
20513 }
20514
20515 void CodeGenerator::visitNewTarget(LNewTarget* ins) {
20516 ValueOperand output = ToOutValue(ins);
20517
20518 // if (isConstructing) output = argv[Max(numActualArgs, numFormalArgs)]
20519 Label notConstructing, done;
20520 Address calleeToken(FramePointer, JitFrameLayout::offsetOfCalleeToken());
20521 masm.branchTestPtr(Assembler::Zero, calleeToken,
20522 Imm32(CalleeToken_FunctionConstructing), &notConstructing);
20523
20524 Register argvLen = output.scratchReg();
20525 masm.loadNumActualArgs(FramePointer, argvLen);
20526
20527 Label useNFormals;
20528
20529 size_t numFormalArgs = ins->mirRaw()->block()->info().nargs();
20530 masm.branchPtr(Assembler::Below, argvLen, Imm32(numFormalArgs), &useNFormals);
20531
20532 size_t argsOffset = JitFrameLayout::offsetOfActualArgs();
20533 {
20534 BaseValueIndex newTarget(FramePointer, argvLen, argsOffset);
20535 masm.loadValue(newTarget, output);
20536 masm.jump(&done);
20537 }
20538
20539 masm.bind(&useNFormals);
20540
20541 {
20542 Address newTarget(FramePointer,
20543 argsOffset + (numFormalArgs * sizeof(Value)));
20544 masm.loadValue(newTarget, output);
20545 masm.jump(&done);
20546 }
20547
20548 // else output = undefined
20549 masm.bind(&notConstructing);
20550 masm.moveValue(UndefinedValue(), output);
20551 masm.bind(&done);
20552 }
20553
20554 void CodeGenerator::visitCheckReturn(LCheckReturn* ins) {
20555 ValueOperand returnValue = ToValue(ins->returnValue());
20556 ValueOperand thisValue = ToValue(ins->thisValue());
20557 ValueOperand output = ToOutValue(ins);
20558
20559 using Fn = bool (*)(JSContext*, HandleValue);
20560 OutOfLineCode* ool = oolCallVM<Fn, ThrowBadDerivedReturnOrUninitializedThis>(
20561 ins, ArgList(returnValue), StoreNothing());
20562
20563 Label noChecks;
20564 masm.branchTestObject(Assembler::Equal, returnValue, &noChecks);
20565 masm.branchTestUndefined(Assembler::NotEqual, returnValue, ool->entry());
20566 masm.branchTestMagic(Assembler::Equal, thisValue, ool->entry());
20567 masm.moveValue(thisValue, output);
20568 masm.jump(ool->rejoin());
20569 masm.bind(&noChecks);
20570 masm.moveValue(returnValue, output);
20571 masm.bind(ool->rejoin());
20572 }
20573
20574 void CodeGenerator::visitCheckIsObj(LCheckIsObj* ins) {
20575 ValueOperand value = ToValue(ins->value());
20576 Register output = ToRegister(ins->output());
20577
20578 using Fn = bool (*)(JSContext*, CheckIsObjectKind);
20579 OutOfLineCode* ool = oolCallVM<Fn, ThrowCheckIsObject>(
20580 ins, ArgList(Imm32(ins->mir()->checkKind())), StoreNothing());
20581
20582 masm.fallibleUnboxObject(value, output, ool->entry());
20583 masm.bind(ool->rejoin());
20584 }
20585
20586 void CodeGenerator::visitCheckObjCoercible(LCheckObjCoercible* ins) {
20587 ValueOperand checkValue = ToValue(ins->value());
20588
20589 using Fn = bool (*)(JSContext*, HandleValue);
20590 OutOfLineCode* ool = oolCallVM<Fn, ThrowObjectCoercible>(
20591 ins, ArgList(checkValue), StoreNothing());
20592 masm.branchTestNull(Assembler::Equal, checkValue, ool->entry());
20593 masm.branchTestUndefined(Assembler::Equal, checkValue, ool->entry());
20594 masm.bind(ool->rejoin());
20595 }
20596
20597 void CodeGenerator::visitCheckClassHeritage(LCheckClassHeritage* ins) {
20598 ValueOperand heritage = ToValue(ins->heritage());
20599 Register temp0 = ToRegister(ins->temp0());
20600 Register temp1 = ToRegister(ins->temp1());
20601
20602 using Fn = bool (*)(JSContext*, HandleValue);
20603 OutOfLineCode* ool = oolCallVM<Fn, CheckClassHeritageOperation>(
20604 ins, ArgList(heritage), StoreNothing());
20605
20606 masm.branchTestNull(Assembler::Equal, heritage, ool->rejoin());
20607 masm.fallibleUnboxObject(heritage, temp0, ool->entry());
20608
20609 masm.isConstructor(temp0, temp1, ool->entry());
20610 masm.branchTest32(Assembler::Zero, temp1, temp1, ool->entry());
20611
20612 masm.bind(ool->rejoin());
20613 }
20614
20615 void CodeGenerator::visitCheckThis(LCheckThis* ins) {
20616 ValueOperand thisValue = ToValue(ins->value());
20617
20618 using Fn = bool (*)(JSContext*);
20619 OutOfLineCode* ool =
20620 oolCallVM<Fn, ThrowUninitializedThis>(ins, ArgList(), StoreNothing());
20621 masm.branchTestMagic(Assembler::Equal, thisValue, ool->entry());
20622 masm.bind(ool->rejoin());
20623 }
20624
20625 void CodeGenerator::visitCheckThisReinit(LCheckThisReinit* ins) {
20626 ValueOperand thisValue = ToValue(ins->thisValue());
20627
20628 using Fn = bool (*)(JSContext*);
20629 OutOfLineCode* ool =
20630 oolCallVM<Fn, ThrowInitializedThis>(ins, ArgList(), StoreNothing());
20631 masm.branchTestMagic(Assembler::NotEqual, thisValue, ool->entry());
20632 masm.bind(ool->rejoin());
20633 }
20634
20635 void CodeGenerator::visitGenerator(LGenerator* lir) {
20636 Register callee = ToRegister(lir->callee());
20637 Register environmentChain = ToRegister(lir->environmentChain());
20638 Register argsObject = ToRegister(lir->argsObject());
20639
20640 pushArg(argsObject);
20641 pushArg(environmentChain);
20642 pushArg(ImmGCPtr(current->mir()->info().script()));
20643 pushArg(callee);
20644
20645 using Fn = JSObject* (*)(JSContext* cx, HandleFunction, HandleScript,
20646 HandleObject, HandleObject);
20647 callVM<Fn, CreateGenerator>(lir);
20648 }
20649
20650 void CodeGenerator::visitAsyncResolve(LAsyncResolve* lir) {
20651 Register generator = ToRegister(lir->generator());
20652 ValueOperand value = ToValue(lir->value());
20653
20654 pushArg(value);
20655 pushArg(generator);
20656
20657 using Fn = JSObject* (*)(JSContext*, Handle<AsyncFunctionGeneratorObject*>,
20658 HandleValue);
20659 callVM<Fn, js::AsyncFunctionResolve>(lir);
20660 }
20661
20662 void CodeGenerator::visitAsyncReject(LAsyncReject* lir) {
20663 Register generator = ToRegister(lir->generator());
20664 ValueOperand reason = ToValue(lir->reason());
20665 ValueOperand stack = ToValue(lir->stack());
20666
20667 pushArg(stack);
20668 pushArg(reason);
20669 pushArg(generator);
20670
20671 using Fn = JSObject* (*)(JSContext*, Handle<AsyncFunctionGeneratorObject*>,
20672 HandleValue, HandleValue);
20673 callVM<Fn, js::AsyncFunctionReject>(lir);
20674 }
20675
20676 void CodeGenerator::visitAsyncAwait(LAsyncAwait* lir) {
20677 ValueOperand value = ToValue(lir->value());
20678 Register generator = ToRegister(lir->generator());
20679
20680 pushArg(value);
20681 pushArg(generator);
20682
20683 using Fn =
20684 JSObject* (*)(JSContext* cx, Handle<AsyncFunctionGeneratorObject*> genObj,
20685 HandleValue value);
20686 callVM<Fn, js::AsyncFunctionAwait>(lir);
20687 }
20688
20689 void CodeGenerator::visitCanSkipAwait(LCanSkipAwait* lir) {
20690 ValueOperand value = ToValue(lir->value());
20691
20692 pushArg(value);
20693
20694 using Fn = bool (*)(JSContext*, HandleValue, bool* canSkip);
20695 callVM<Fn, js::CanSkipAwait>(lir);
20696 }
20697
20698 void CodeGenerator::visitMaybeExtractAwaitValue(LMaybeExtractAwaitValue* lir) {
20699 ValueOperand value = ToValue(lir->value());
20700 ValueOperand output = ToOutValue(lir);
20701 Register canSkip = ToRegister(lir->canSkip());
20702
20703 Label cantExtract, finished;
20704 masm.branchIfFalseBool(canSkip, &cantExtract);
20705
20706 pushArg(value);
20707
20708 using Fn = bool (*)(JSContext*, HandleValue, MutableHandleValue);
20709 callVM<Fn, js::ExtractAwaitValue>(lir);
20710 masm.jump(&finished);
20711 masm.bind(&cantExtract);
20712
20713 masm.moveValue(value, output);
20714
20715 masm.bind(&finished);
20716 }
20717
20718 void CodeGenerator::visitDebugCheckSelfHosted(LDebugCheckSelfHosted* ins) {
20719 ValueOperand checkValue = ToValue(ins->value());
20720 pushArg(checkValue);
20721 using Fn = bool (*)(JSContext*, HandleValue);
20722 callVM<Fn, js::Debug_CheckSelfHosted>(ins);
20723 }
20724
20725 void CodeGenerator::visitRandom(LRandom* ins) {
20726 using mozilla::non_crypto::XorShift128PlusRNG;
20727
20728 FloatRegister output = ToFloatRegister(ins->output());
20729 Register rngReg = ToRegister(ins->temp0());
20730
20731 Register64 temp1 = ToRegister64(ins->temp1());
20732 Register64 temp2 = ToRegister64(ins->temp2());
20733
20734 const XorShift128PlusRNG* rng = gen->realm->addressOfRandomNumberGenerator();
20735 masm.movePtr(ImmPtr(rng), rngReg);
20736
20737 masm.randomDouble(rngReg, output, temp1, temp2);
20738 if (js::SupportDifferentialTesting()) {
20739 masm.loadConstantDouble(0.0, output);
20740 }
20741 }
20742
20743 void CodeGenerator::visitSignExtendInt32(LSignExtendInt32* ins) {
20744 Register input = ToRegister(ins->input());
20745 Register output = ToRegister(ins->output());
20746
20747 switch (ins->mir()->mode()) {
20748 case MSignExtendInt32::Byte:
20749 masm.move8SignExtend(input, output);
20750 break;
20751 case MSignExtendInt32::Half:
20752 masm.move16SignExtend(input, output);
20753 break;
20754 }
20755 }
20756
20757 void CodeGenerator::visitSignExtendIntPtr(LSignExtendIntPtr* ins) {
20758 Register input = ToRegister(ins->input());
20759 Register output = ToRegister(ins->output());
20760
20761 switch (ins->mir()->mode()) {
20762 case MSignExtendIntPtr::Byte:
20763 masm.move8SignExtendToPtr(input, output);
20764 break;
20765 case MSignExtendIntPtr::Half:
20766 masm.move16SignExtendToPtr(input, output);
20767 break;
20768 case MSignExtendIntPtr::Word:
20769 masm.move32SignExtendToPtr(input, output);
20770 break;
20771 }
20772 }
20773
20774 void CodeGenerator::visitRotate(LRotate* ins) {
20775 MRotate* mir = ins->mir();
20776 Register input = ToRegister(ins->input());
20777 Register dest = ToRegister(ins->output());
20778
20779 const LAllocation* count = ins->count();
20780 if (count->isConstant()) {
20781 int32_t c = ToInt32(count) & 0x1F;
20782 if (mir->isLeftRotate()) {
20783 masm.rotateLeft(Imm32(c), input, dest);
20784 } else {
20785 masm.rotateRight(Imm32(c), input, dest);
20786 }
20787 } else {
20788 Register creg = ToRegister(count);
20789 if (mir->isLeftRotate()) {
20790 masm.rotateLeft(creg, input, dest);
20791 } else {
20792 masm.rotateRight(creg, input, dest);
20793 }
20794 }
20795 }
20796
20797 void CodeGenerator::visitRotateI64(LRotateI64* lir) {
20798 MRotate* mir = lir->mir();
20799 const LAllocation* count = lir->count();
20800
20801 Register64 input = ToRegister64(lir->input());
20802 Register64 output = ToOutRegister64(lir);
20803 Register temp = ToTempRegisterOrInvalid(lir->temp0());
20804
20805 if (count->isConstant()) {
20806 int32_t c = int32_t(count->toConstant()->toInt64() & 0x3F);
20807 if (!c) {
20808 if (input != output) {
20809 masm.move64(input, output);
20810 }
20811 return;
20812 }
20813 if (mir->isLeftRotate()) {
20814 masm.rotateLeft64(Imm32(c), input, output, temp);
20815 } else {
20816 masm.rotateRight64(Imm32(c), input, output, temp);
20817 }
20818 } else {
20819 if (mir->isLeftRotate()) {
20820 masm.rotateLeft64(ToRegister(count), input, output, temp);
20821 } else {
20822 masm.rotateRight64(ToRegister(count), input, output, temp);
20823 }
20824 }
20825 }
20826
20827 void CodeGenerator::visitReinterpretCast(LReinterpretCast* lir) {
20828 MReinterpretCast* ins = lir->mir();
20829
20830 MIRType to = ins->type();
20831 mozilla::DebugOnly<MIRType> from = ins->input()->type();
20832
20833 switch (to) {
20834 case MIRType::Int32:
20835 MOZ_ASSERT(from == MIRType::Float32);
20836 masm.moveFloat32ToGPR(ToFloatRegister(lir->input()),
20837 ToRegister(lir->output()));
20838 break;
20839 case MIRType::Float32:
20840 MOZ_ASSERT(from == MIRType::Int32);
20841 masm.moveGPRToFloat32(ToRegister(lir->input()),
20842 ToFloatRegister(lir->output()));
20843 break;
20844 case MIRType::Double:
20845 case MIRType::Int64:
20846 MOZ_CRASH("not handled by this LIR opcode");
20847 default:
20848 MOZ_CRASH("unexpected ReinterpretCast");
20849 }
20850 }
20851
20852 void CodeGenerator::visitReinterpretCastFromI64(LReinterpretCastFromI64* lir) {
20853 MOZ_ASSERT(lir->mir()->type() == MIRType::Double);
20854 MOZ_ASSERT(lir->mir()->input()->type() == MIRType::Int64);
20855 masm.moveGPR64ToDouble(ToRegister64(lir->input()),
20856 ToFloatRegister(lir->output()));
20857 }
20858
20859 void CodeGenerator::visitReinterpretCastToI64(LReinterpretCastToI64* lir) {
20860 MOZ_ASSERT(lir->mir()->type() == MIRType::Int64);
20861 MOZ_ASSERT(lir->mir()->input()->type() == MIRType::Double);
20862 masm.moveDoubleToGPR64(ToFloatRegister(lir->input()), ToOutRegister64(lir));
20863 }
20864
20865 void CodeGenerator::visitNaNToZero(LNaNToZero* lir) {
20866 FloatRegister input = ToFloatRegister(lir->input());
20867
20868 auto* ool = new (alloc()) LambdaOutOfLineCode([=](OutOfLineCode& ool) {
20869 FloatRegister output = ToFloatRegister(lir->output());
20870 masm.loadConstantDouble(0.0, output);
20871 masm.jump(ool.rejoin());
20872 });
20873 addOutOfLineCode(ool, lir->mir());
20874
20875 if (lir->mir()->operandIsNeverNegativeZero()) {
20876 masm.branchDouble(Assembler::DoubleUnordered, input, input, ool->entry());
20877 } else {
20878 FloatRegister scratch = ToFloatRegister(lir->temp0());
20879 masm.loadConstantDouble(0.0, scratch);
20880 masm.branchDouble(Assembler::DoubleEqualOrUnordered, input, scratch,
20881 ool->entry());
20882 }
20883 masm.bind(ool->rejoin());
20884 }
20885
20886 void CodeGenerator::visitIsPackedArray(LIsPackedArray* lir) {
20887 Register obj = ToRegister(lir->object());
20888 Register output = ToRegister(lir->output());
20889 Register temp = ToRegister(lir->temp0());
20890
20891 masm.setIsPackedArray(obj, output, temp);
20892 }
20893
20894 void CodeGenerator::visitGuardArrayIsPacked(LGuardArrayIsPacked* lir) {
20895 Register array = ToRegister(lir->array());
20896 Register temp0 = ToRegister(lir->temp0());
20897 Register temp1 = ToRegister(lir->temp1());
20898
20899 Label bail;
20900 masm.branchArrayIsNotPacked(array, temp0, temp1, &bail);
20901 bailoutFrom(&bail, lir->snapshot());
20902 }
20903
20904 void CodeGenerator::visitGetPrototypeOf(LGetPrototypeOf* lir) {
20905 Register target = ToRegister(lir->target());
20906 ValueOperand out = ToOutValue(lir);
20907 Register scratch = out.scratchReg();
20908
20909 using Fn = bool (*)(JSContext*, HandleObject, MutableHandleValue);
20910 OutOfLineCode* ool = oolCallVM<Fn, jit::GetPrototypeOf>(lir, ArgList(target),
20911 StoreValueTo(out));
20912
20913 MOZ_ASSERT(uintptr_t(TaggedProto::LazyProto) == 1);
20914
20915 masm.loadObjProto(target, scratch);
20916
20917 Label hasProto;
20918 masm.branchPtr(Assembler::Above, scratch, ImmWord(1), &hasProto);
20919
20920 // Call into the VM for lazy prototypes.
20921 masm.branchPtr(Assembler::Equal, scratch, ImmWord(1), ool->entry());
20922
20923 masm.moveValue(NullValue(), out);
20924 masm.jump(ool->rejoin());
20925
20926 masm.bind(&hasProto);
20927 masm.tagValue(JSVAL_TYPE_OBJECT, scratch, out);
20928
20929 masm.bind(ool->rejoin());
20930 }
20931
20932 void CodeGenerator::visitObjectWithProto(LObjectWithProto* lir) {
20933 pushArg(ToValue(lir->prototype()));
20934
20935 using Fn = PlainObject* (*)(JSContext*, HandleValue);
20936 callVM<Fn, js::ObjectWithProtoOperation>(lir);
20937 }
20938
20939 void CodeGenerator::visitObjectStaticProto(LObjectStaticProto* lir) {
20940 Register obj = ToRegister(lir->object());
20941 Register output = ToRegister(lir->output());
20942
20943 masm.loadObjProto(obj, output);
20944
20945 #ifdef DEBUG
20946 // We shouldn't encounter a null or lazy proto.
20947 MOZ_ASSERT(uintptr_t(TaggedProto::LazyProto) == 1);
20948
20949 Label done;
20950 masm.branchPtr(Assembler::Above, output, ImmWord(1), &done);
20951 masm.assumeUnreachable("Unexpected null or lazy proto in MObjectStaticProto");
20952 masm.bind(&done);
20953 #endif
20954 }
20955
20956 void CodeGenerator::visitBuiltinObject(LBuiltinObject* lir) {
20957 pushArg(Imm32(static_cast<int32_t>(lir->mir()->builtinObjectKind())));
20958
20959 using Fn = JSObject* (*)(JSContext*, BuiltinObjectKind);
20960 callVM<Fn, js::BuiltinObjectOperation>(lir);
20961 }
20962
20963 void CodeGenerator::visitSuperFunction(LSuperFunction* lir) {
20964 Register callee = ToRegister(lir->callee());
20965 ValueOperand out = ToOutValue(lir);
20966 Register temp = ToRegister(lir->temp0());
20967
20968 #ifdef DEBUG
20969 Label classCheckDone;
20970 masm.branchTestObjIsFunction(Assembler::Equal, callee, temp, callee,
20971 &classCheckDone);
20972 masm.assumeUnreachable("Unexpected non-JSFunction callee in JSOp::SuperFun");
20973 masm.bind(&classCheckDone);
20974 #endif
20975
20976 // Load prototype of callee
20977 masm.loadObjProto(callee, temp);
20978
20979 #ifdef DEBUG
20980 // We won't encounter a lazy proto, because |callee| is guaranteed to be a
20981 // JSFunction and only proxy objects can have a lazy proto.
20982 MOZ_ASSERT(uintptr_t(TaggedProto::LazyProto) == 1);
20983
20984 Label proxyCheckDone;
20985 masm.branchPtr(Assembler::NotEqual, temp, ImmWord(1), &proxyCheckDone);
20986 masm.assumeUnreachable("Unexpected lazy proto in JSOp::SuperFun");
20987 masm.bind(&proxyCheckDone);
20988 #endif
20989
20990 Label nullProto, done;
20991 masm.branchPtr(Assembler::Equal, temp, ImmWord(0), &nullProto);
20992
20993 // Box prototype and return
20994 masm.tagValue(JSVAL_TYPE_OBJECT, temp, out);
20995 masm.jump(&done);
20996
20997 masm.bind(&nullProto);
20998 masm.moveValue(NullValue(), out);
20999
21000 masm.bind(&done);
21001 }
21002
21003 void CodeGenerator::visitInitHomeObject(LInitHomeObject* lir) {
21004 Register func = ToRegister(lir->function());
21005 ValueOperand homeObject = ToValue(lir->homeObject());
21006
21007 masm.assertFunctionIsExtended(func);
21008
21009 Address addr(func, FunctionExtended::offsetOfMethodHomeObjectSlot());
21010
21011 emitPreBarrier(addr);
21012 masm.storeValue(homeObject, addr);
21013 }
21014
21015 void CodeGenerator::visitIsTypedArrayConstructor(
21016 LIsTypedArrayConstructor* lir) {
21017 Register object = ToRegister(lir->object());
21018 Register output = ToRegister(lir->output());
21019
21020 masm.setIsDefinitelyTypedArrayConstructor(object, output);
21021 }
21022
21023 void CodeGenerator::visitLoadValueTag(LLoadValueTag* lir) {
21024 ValueOperand value = ToValue(lir->value());
21025 Register output = ToRegister(lir->output());
21026
21027 Register tag = masm.extractTag(value, output);
21028 if (tag != output) {
21029 masm.mov(tag, output);
21030 }
21031 }
21032
21033 void CodeGenerator::visitGuardTagNotEqual(LGuardTagNotEqual* lir) {
21034 Register lhs = ToRegister(lir->lhs());
21035 Register rhs = ToRegister(lir->rhs());
21036
21037 bailoutCmp32(Assembler::Equal, lhs, rhs, lir->snapshot());
21038
21039 // If both lhs and rhs are numbers, can't use tag comparison to do inequality
21040 // comparison
21041 Label done;
21042 masm.branchTestNumber(Assembler::NotEqual, lhs, &done);
21043 masm.branchTestNumber(Assembler::NotEqual, rhs, &done);
21044 bailout(lir->snapshot());
21045
21046 masm.bind(&done);
21047 }
21048
21049 void CodeGenerator::visitLoadWrapperTarget(LLoadWrapperTarget* lir) {
21050 Register object = ToRegister(lir->object());
21051 Register output = ToRegister(lir->output());
21052
21053 masm.loadPtr(Address(object, ProxyObject::offsetOfReservedSlots()), output);
21054
21055 // Bail for revoked proxies.
21056 Label bail;
21057 Address targetAddr(output,
21058 js::detail::ProxyReservedSlots::offsetOfPrivateSlot());
21059 if (lir->mir()->fallible()) {
21060 masm.fallibleUnboxObject(targetAddr, output, &bail);
21061 bailoutFrom(&bail, lir->snapshot());
21062 } else {
21063 masm.unboxObject(targetAddr, output);
21064 }
21065 }
21066
21067 void CodeGenerator::visitGuardHasGetterSetter(LGuardHasGetterSetter* lir) {
21068 Register object = ToRegister(lir->object());
21069 Register temp0 = ToRegister(lir->temp0());
21070 Register temp1 = ToRegister(lir->temp1());
21071 Register temp2 = ToRegister(lir->temp2());
21072
21073 masm.movePropertyKey(lir->mir()->propId(), temp1);
21074 masm.movePtr(ImmGCPtr(lir->mir()->getterSetter()), temp2);
21075
21076 using Fn = bool (*)(JSContext* cx, JSObject* obj, jsid id,
21077 GetterSetter* getterSetter);
21078 masm.setupAlignedABICall();
21079 masm.loadJSContext(temp0);
21080 masm.passABIArg(temp0);
21081 masm.passABIArg(object);
21082 masm.passABIArg(temp1);
21083 masm.passABIArg(temp2);
21084 masm.callWithABI<Fn, ObjectHasGetterSetterPure>();
21085
21086 bailoutIfFalseBool(ReturnReg, lir->snapshot());
21087 }
21088
21089 void CodeGenerator::visitGuardIsExtensible(LGuardIsExtensible* lir) {
21090 Register object = ToRegister(lir->object());
21091 Register temp = ToRegister(lir->temp0());
21092
21093 Label bail;
21094 masm.branchIfObjectNotExtensible(object, temp, &bail);
21095 bailoutFrom(&bail, lir->snapshot());
21096 }
21097
21098 void CodeGenerator::visitGuardInt32IsNonNegative(
21099 LGuardInt32IsNonNegative* lir) {
21100 Register index = ToRegister(lir->index());
21101
21102 bailoutCmp32(Assembler::LessThan, index, Imm32(0), lir->snapshot());
21103 }
21104
21105 void CodeGenerator::visitGuardInt32Range(LGuardInt32Range* lir) {
21106 Register input = ToRegister(lir->input());
21107
21108 bailoutCmp32(Assembler::LessThan, input, Imm32(lir->mir()->minimum()),
21109 lir->snapshot());
21110 bailoutCmp32(Assembler::GreaterThan, input, Imm32(lir->mir()->maximum()),
21111 lir->snapshot());
21112 }
21113
21114 void CodeGenerator::visitGuardIndexIsNotDenseElement(
21115 LGuardIndexIsNotDenseElement* lir) {
21116 Register object = ToRegister(lir->object());
21117 Register index = ToRegister(lir->index());
21118 Register temp = ToRegister(lir->temp0());
21119 Register spectreTemp = ToTempRegisterOrInvalid(lir->temp1());
21120
21121 // Load obj->elements.
21122 masm.loadPtr(Address(object, NativeObject::offsetOfElements()), temp);
21123
21124 // Ensure index >= initLength or the element is a hole.
21125 Label notDense;
21126 Address capacity(temp, ObjectElements::offsetOfInitializedLength());
21127 masm.spectreBoundsCheck32(index, capacity, spectreTemp, &notDense);
21128
21129 BaseValueIndex element(temp, index);
21130 masm.branchTestMagic(Assembler::Equal, element, &notDense);
21131
21132 bailout(lir->snapshot());
21133
21134 masm.bind(&notDense);
21135 }
21136
21137 void CodeGenerator::visitGuardIndexIsValidUpdateOrAdd(
21138 LGuardIndexIsValidUpdateOrAdd* lir) {
21139 Register object = ToRegister(lir->object());
21140 Register index = ToRegister(lir->index());
21141 Register temp = ToRegister(lir->temp0());
21142 Register spectreTemp = ToTempRegisterOrInvalid(lir->temp1());
21143
21144 // Load obj->elements.
21145 masm.loadPtr(Address(object, NativeObject::offsetOfElements()), temp);
21146
21147 Label success;
21148
21149 // If length is writable, branch to &success. All indices are writable.
21150 Address flags(temp, ObjectElements::offsetOfFlags());
21151 masm.branchTest32(Assembler::Zero, flags,
21152 Imm32(ObjectElements::Flags::NONWRITABLE_ARRAY_LENGTH),
21153 &success);
21154
21155 // Otherwise, ensure index is in bounds.
21156 Label bail;
21157 Address length(temp, ObjectElements::offsetOfLength());
21158 masm.spectreBoundsCheck32(index, length, spectreTemp, &bail);
21159 masm.bind(&success);
21160
21161 bailoutFrom(&bail, lir->snapshot());
21162 }
21163
21164 void CodeGenerator::visitCallAddOrUpdateSparseElement(
21165 LCallAddOrUpdateSparseElement* lir) {
21166 Register object = ToRegister(lir->object());
21167 Register index = ToRegister(lir->index());
21168 ValueOperand value = ToValue(lir->value());
21169
21170 pushArg(Imm32(lir->mir()->strict()));
21171 pushArg(value);
21172 pushArg(index);
21173 pushArg(object);
21174
21175 using Fn =
21176 bool (*)(JSContext*, Handle<NativeObject*>, int32_t, HandleValue, bool);
21177 callVM<Fn, js::AddOrUpdateSparseElementHelper>(lir);
21178 }
21179
21180 void CodeGenerator::visitCallGetSparseElement(LCallGetSparseElement* lir) {
21181 Register object = ToRegister(lir->object());
21182 Register index = ToRegister(lir->index());
21183
21184 pushArg(index);
21185 pushArg(object);
21186
21187 using Fn =
21188 bool (*)(JSContext*, Handle<NativeObject*>, int32_t, MutableHandleValue);
21189 callVM<Fn, js::GetSparseElementHelper>(lir);
21190 }
21191
21192 void CodeGenerator::visitCallNativeGetElement(LCallNativeGetElement* lir) {
21193 Register object = ToRegister(lir->object());
21194 Register index = ToRegister(lir->index());
21195
21196 pushArg(index);
21197 pushArg(TypedOrValueRegister(MIRType::Object, AnyRegister(object)));
21198 pushArg(object);
21199
21200 using Fn = bool (*)(JSContext*, Handle<NativeObject*>, HandleValue, int32_t,
21201 MutableHandleValue);
21202 callVM<Fn, js::NativeGetElement>(lir);
21203 }
21204
21205 void CodeGenerator::visitCallNativeGetElementSuper(
21206 LCallNativeGetElementSuper* lir) {
21207 Register object = ToRegister(lir->object());
21208 Register index = ToRegister(lir->index());
21209 ValueOperand receiver = ToValue(lir->receiver());
21210
21211 pushArg(index);
21212 pushArg(receiver);
21213 pushArg(object);
21214
21215 using Fn = bool (*)(JSContext*, Handle<NativeObject*>, HandleValue, int32_t,
21216 MutableHandleValue);
21217 callVM<Fn, js::NativeGetElement>(lir);
21218 }
21219
21220 void CodeGenerator::visitCallObjectHasSparseElement(
21221 LCallObjectHasSparseElement* lir) {
21222 Register object = ToRegister(lir->object());
21223 Register index = ToRegister(lir->index());
21224 Register temp0 = ToRegister(lir->temp0());
21225 Register temp1 = ToRegister(lir->temp1());
21226 Register output = ToRegister(lir->output());
21227
21228 masm.reserveStack(sizeof(Value));
21229 masm.moveStackPtrTo(temp1);
21230
21231 using Fn = bool (*)(JSContext*, NativeObject*, int32_t, Value*);
21232 masm.setupAlignedABICall();
21233 masm.loadJSContext(temp0);
21234 masm.passABIArg(temp0);
21235 masm.passABIArg(object);
21236 masm.passABIArg(index);
21237 masm.passABIArg(temp1);
21238 masm.callWithABI<Fn, HasNativeElementPure>();
21239 masm.storeCallPointerResult(temp0);
21240
21241 Label bail, ok;
21242 uint32_t framePushed = masm.framePushed();
21243 masm.branchIfTrueBool(temp0, &ok);
21244 masm.adjustStack(sizeof(Value));
21245 masm.jump(&bail);
21246
21247 masm.bind(&ok);
21248 masm.setFramePushed(framePushed);
21249 masm.unboxBoolean(Address(masm.getStackPointer(), 0), output);
21250 masm.adjustStack(sizeof(Value));
21251
21252 bailoutFrom(&bail, lir->snapshot());
21253 }
21254
21255 void CodeGenerator::visitBigIntAsIntN(LBigIntAsIntN* ins) {
21256 Register bits = ToRegister(ins->bits());
21257 Register input = ToRegister(ins->input());
21258
21259 pushArg(bits);
21260 pushArg(input);
21261
21262 using Fn = BigInt* (*)(JSContext*, HandleBigInt, int32_t);
21263 callVM<Fn, jit::BigIntAsIntN>(ins);
21264 }
21265
21266 void CodeGenerator::visitBigIntAsUintN(LBigIntAsUintN* ins) {
21267 Register bits = ToRegister(ins->bits());
21268 Register input = ToRegister(ins->input());
21269
21270 pushArg(bits);
21271 pushArg(input);
21272
21273 using Fn = BigInt* (*)(JSContext*, HandleBigInt, int32_t);
21274 callVM<Fn, jit::BigIntAsUintN>(ins);
21275 }
21276
21277 void CodeGenerator::visitGuardNonGCThing(LGuardNonGCThing* ins) {
21278 ValueOperand input = ToValue(ins->input());
21279
21280 Label bail;
21281 masm.branchTestGCThing(Assembler::Equal, input, &bail);
21282 bailoutFrom(&bail, ins->snapshot());
21283 }
21284
21285 void CodeGenerator::visitToHashableNonGCThing(LToHashableNonGCThing* ins) {
21286 ValueOperand input = ToValue(ins->input());
21287 FloatRegister tempFloat = ToFloatRegister(ins->temp0());
21288 ValueOperand output = ToOutValue(ins);
21289
21290 masm.toHashableNonGCThing(input, output, tempFloat);
21291 }
21292
21293 void CodeGenerator::visitToHashableString(LToHashableString* ins) {
21294 Register input = ToRegister(ins->input());
21295 Register output = ToRegister(ins->output());
21296
21297 using Fn = JSAtom* (*)(JSContext*, JSString*);
21298 auto* ool = oolCallVM<Fn, js::AtomizeString>(ins, ArgList(input),
21299 StoreRegisterTo(output));
21300
21301 Label isAtom;
21302 masm.branchTest32(Assembler::NonZero,
21303 Address(input, JSString::offsetOfFlags()),
21304 Imm32(JSString::ATOM_BIT), &isAtom);
21305
21306 masm.tryFastAtomize(input, output, output, ool->entry());
21307 masm.jump(ool->rejoin());
21308 masm.bind(&isAtom);
21309 masm.movePtr(input, output);
21310 masm.bind(ool->rejoin());
21311 }
21312
21313 void CodeGenerator::visitToHashableValue(LToHashableValue* ins) {
21314 ValueOperand input = ToValue(ins->input());
21315 FloatRegister tempFloat = ToFloatRegister(ins->temp0());
21316 ValueOperand output = ToOutValue(ins);
21317
21318 Register str = output.scratchReg();
21319
21320 using Fn = JSAtom* (*)(JSContext*, JSString*);
21321 auto* ool =
21322 oolCallVM<Fn, js::AtomizeString>(ins, ArgList(str), StoreRegisterTo(str));
21323
21324 masm.toHashableValue(input, output, tempFloat, ool->entry(), ool->rejoin());
21325 }
21326
21327 void CodeGenerator::visitHashNonGCThing(LHashNonGCThing* ins) {
21328 ValueOperand input = ToValue(ins->input());
21329 Register temp = ToRegister(ins->temp0());
21330 Register output = ToRegister(ins->output());
21331
21332 masm.prepareHashNonGCThing(input, output, temp);
21333 }
21334
21335 void CodeGenerator::visitHashString(LHashString* ins) {
21336 Register input = ToRegister(ins->input());
21337 Register temp = ToRegister(ins->temp0());
21338 Register output = ToRegister(ins->output());
21339
21340 masm.prepareHashString(input, output, temp);
21341 }
21342
21343 void CodeGenerator::visitHashSymbol(LHashSymbol* ins) {
21344 Register input = ToRegister(ins->input());
21345 Register output = ToRegister(ins->output());
21346
21347 masm.prepareHashSymbol(input, output);
21348 }
21349
21350 void CodeGenerator::visitHashBigInt(LHashBigInt* ins) {
21351 Register input = ToRegister(ins->input());
21352 Register temp0 = ToRegister(ins->temp0());
21353 Register temp1 = ToRegister(ins->temp1());
21354 Register temp2 = ToRegister(ins->temp2());
21355 Register output = ToRegister(ins->output());
21356
21357 masm.prepareHashBigInt(input, output, temp0, temp1, temp2);
21358 }
21359
21360 void CodeGenerator::visitHashObject(LHashObject* ins) {
21361 Register setObj = ToRegister(ins->setObject());
21362 ValueOperand input = ToValue(ins->input());
21363 Register temp0 = ToRegister(ins->temp0());
21364 Register temp1 = ToRegister(ins->temp1());
21365 Register temp2 = ToRegister(ins->temp2());
21366 Register temp3 = ToRegister(ins->temp3());
21367 Register output = ToRegister(ins->output());
21368
21369 masm.prepareHashObject(setObj, input, output, temp0, temp1, temp2, temp3);
21370 }
21371
21372 void CodeGenerator::visitHashValue(LHashValue* ins) {
21373 Register setObj = ToRegister(ins->setObject());
21374 ValueOperand input = ToValue(ins->input());
21375 Register temp0 = ToRegister(ins->temp0());
21376 Register temp1 = ToRegister(ins->temp1());
21377 Register temp2 = ToRegister(ins->temp2());
21378 Register temp3 = ToRegister(ins->temp3());
21379 Register output = ToRegister(ins->output());
21380
21381 masm.prepareHashValue(setObj, input, output, temp0, temp1, temp2, temp3);
21382 }
21383
21384 void CodeGenerator::visitSetObjectHasNonBigInt(LSetObjectHasNonBigInt* ins) {
21385 Register setObj = ToRegister(ins->setObject());
21386 ValueOperand input = ToValue(ins->value());
21387 Register hash = ToRegister(ins->hash());
21388 Register temp0 = ToRegister(ins->temp0());
21389 Register temp1 = ToRegister(ins->temp1());
21390 Register output = ToRegister(ins->output());
21391
21392 masm.setObjectHasNonBigInt(setObj, input, hash, output, temp0, temp1);
21393 }
21394
21395 void CodeGenerator::visitSetObjectHasBigInt(LSetObjectHasBigInt* ins) {
21396 Register setObj = ToRegister(ins->setObject());
21397 ValueOperand input = ToValue(ins->value());
21398 Register hash = ToRegister(ins->hash());
21399 Register temp0 = ToRegister(ins->temp0());
21400 Register temp1 = ToRegister(ins->temp1());
21401 Register temp2 = ToRegister(ins->temp2());
21402 Register temp3 = ToRegister(ins->temp3());
21403 Register output = ToRegister(ins->output());
21404
21405 masm.setObjectHasBigInt(setObj, input, hash, output, temp0, temp1, temp2,
21406 temp3);
21407 }
21408
21409 void CodeGenerator::visitSetObjectHasValue(LSetObjectHasValue* ins) {
21410 Register setObj = ToRegister(ins->setObject());
21411 ValueOperand input = ToValue(ins->value());
21412 Register hash = ToRegister(ins->hash());
21413 Register temp0 = ToRegister(ins->temp0());
21414 Register temp1 = ToRegister(ins->temp1());
21415 Register temp2 = ToRegister(ins->temp2());
21416 Register temp3 = ToRegister(ins->temp3());
21417 Register output = ToRegister(ins->output());
21418
21419 masm.setObjectHasValue(setObj, input, hash, output, temp0, temp1, temp2,
21420 temp3);
21421 }
21422
21423 void CodeGenerator::visitSetObjectHasValueVMCall(
21424 LSetObjectHasValueVMCall* ins) {
21425 pushArg(ToValue(ins->value()));
21426 pushArg(ToRegister(ins->setObject()));
21427
21428 using Fn = bool (*)(JSContext*, Handle<SetObject*>, HandleValue, bool*);
21429 callVM<Fn, jit::SetObjectHas>(ins);
21430 }
21431
21432 void CodeGenerator::visitSetObjectDelete(LSetObjectDelete* ins) {
21433 pushArg(ToValue(ins->key()));
21434 pushArg(ToRegister(ins->setObject()));
21435 using Fn = bool (*)(JSContext*, Handle<SetObject*>, HandleValue, bool*);
21436 callVM<Fn, jit::SetObjectDelete>(ins);
21437 }
21438
21439 void CodeGenerator::visitSetObjectAdd(LSetObjectAdd* ins) {
21440 pushArg(ToValue(ins->key()));
21441 pushArg(ToRegister(ins->setObject()));
21442 using Fn = bool (*)(JSContext*, Handle<SetObject*>, HandleValue);
21443 callVM<Fn, jit::SetObjectAdd>(ins);
21444 }
21445
21446 void CodeGenerator::visitSetObjectSize(LSetObjectSize* ins) {
21447 Register setObj = ToRegister(ins->setObject());
21448 Register output = ToRegister(ins->output());
21449
21450 masm.loadSetObjectSize(setObj, output);
21451 }
21452
21453 void CodeGenerator::visitMapObjectHasNonBigInt(LMapObjectHasNonBigInt* ins) {
21454 Register mapObj = ToRegister(ins->mapObject());
21455 ValueOperand input = ToValue(ins->value());
21456 Register hash = ToRegister(ins->hash());
21457 Register temp0 = ToRegister(ins->temp0());
21458 Register temp1 = ToRegister(ins->temp1());
21459 Register output = ToRegister(ins->output());
21460
21461 masm.mapObjectHasNonBigInt(mapObj, input, hash, output, temp0, temp1);
21462 }
21463
21464 void CodeGenerator::visitMapObjectHasBigInt(LMapObjectHasBigInt* ins) {
21465 Register mapObj = ToRegister(ins->mapObject());
21466 ValueOperand input = ToValue(ins->value());
21467 Register hash = ToRegister(ins->hash());
21468 Register temp0 = ToRegister(ins->temp0());
21469 Register temp1 = ToRegister(ins->temp1());
21470 Register temp2 = ToRegister(ins->temp2());
21471 Register temp3 = ToRegister(ins->temp3());
21472 Register output = ToRegister(ins->output());
21473
21474 masm.mapObjectHasBigInt(mapObj, input, hash, output, temp0, temp1, temp2,
21475 temp3);
21476 }
21477
21478 void CodeGenerator::visitMapObjectHasValue(LMapObjectHasValue* ins) {
21479 Register mapObj = ToRegister(ins->mapObject());
21480 ValueOperand input = ToValue(ins->value());
21481 Register hash = ToRegister(ins->hash());
21482 Register temp0 = ToRegister(ins->temp0());
21483 Register temp1 = ToRegister(ins->temp1());
21484 Register temp2 = ToRegister(ins->temp2());
21485 Register temp3 = ToRegister(ins->temp3());
21486 Register output = ToRegister(ins->output());
21487
21488 masm.mapObjectHasValue(mapObj, input, hash, output, temp0, temp1, temp2,
21489 temp3);
21490 }
21491
21492 void CodeGenerator::visitMapObjectHasValueVMCall(
21493 LMapObjectHasValueVMCall* ins) {
21494 pushArg(ToValue(ins->value()));
21495 pushArg(ToRegister(ins->mapObject()));
21496
21497 using Fn = bool (*)(JSContext*, Handle<MapObject*>, HandleValue, bool*);
21498 callVM<Fn, jit::MapObjectHas>(ins);
21499 }
21500
21501 void CodeGenerator::visitMapObjectGetNonBigInt(LMapObjectGetNonBigInt* ins) {
21502 Register mapObj = ToRegister(ins->mapObject());
21503 ValueOperand input = ToValue(ins->value());
21504 Register hash = ToRegister(ins->hash());
21505 Register temp0 = ToRegister(ins->temp0());
21506 Register temp1 = ToRegister(ins->temp1());
21507 ValueOperand output = ToOutValue(ins);
21508
21509 masm.mapObjectGetNonBigInt(mapObj, input, hash, output, temp0, temp1,
21510 output.scratchReg());
21511 }
21512
21513 void CodeGenerator::visitMapObjectGetBigInt(LMapObjectGetBigInt* ins) {
21514 Register mapObj = ToRegister(ins->mapObject());
21515 ValueOperand input = ToValue(ins->value());
21516 Register hash = ToRegister(ins->hash());
21517 Register temp0 = ToRegister(ins->temp0());
21518 Register temp1 = ToRegister(ins->temp1());
21519 Register temp2 = ToRegister(ins->temp2());
21520 Register temp3 = ToRegister(ins->temp3());
21521 ValueOperand output = ToOutValue(ins);
21522
21523 masm.mapObjectGetBigInt(mapObj, input, hash, output, temp0, temp1, temp2,
21524 temp3, output.scratchReg());
21525 }
21526
21527 void CodeGenerator::visitMapObjectGetValue(LMapObjectGetValue* ins) {
21528 Register mapObj = ToRegister(ins->mapObject());
21529 ValueOperand input = ToValue(ins->value());
21530 Register hash = ToRegister(ins->hash());
21531 Register temp0 = ToRegister(ins->temp0());
21532 Register temp1 = ToRegister(ins->temp1());
21533 Register temp2 = ToRegister(ins->temp2());
21534 Register temp3 = ToRegister(ins->temp3());
21535 ValueOperand output = ToOutValue(ins);
21536
21537 masm.mapObjectGetValue(mapObj, input, hash, output, temp0, temp1, temp2,
21538 temp3, output.scratchReg());
21539 }
21540
21541 void CodeGenerator::visitMapObjectGetValueVMCall(
21542 LMapObjectGetValueVMCall* ins) {
21543 pushArg(ToValue(ins->value()));
21544 pushArg(ToRegister(ins->mapObject()));
21545
21546 using Fn =
21547 bool (*)(JSContext*, Handle<MapObject*>, HandleValue, MutableHandleValue);
21548 callVM<Fn, jit::MapObjectGet>(ins);
21549 }
21550
21551 void CodeGenerator::visitMapObjectDelete(LMapObjectDelete* ins) {
21552 pushArg(ToValue(ins->key()));
21553 pushArg(ToRegister(ins->mapObject()));
21554 using Fn = bool (*)(JSContext*, Handle<MapObject*>, HandleValue, bool*);
21555 callVM<Fn, jit::MapObjectDelete>(ins);
21556 }
21557
21558 void CodeGenerator::visitMapObjectSet(LMapObjectSet* ins) {
21559 pushArg(ToValue(ins->value()));
21560 pushArg(ToValue(ins->key()));
21561 pushArg(ToRegister(ins->mapObject()));
21562 using Fn = bool (*)(JSContext*, Handle<MapObject*>, HandleValue, HandleValue);
21563 callVM<Fn, jit::MapObjectSet>(ins);
21564 }
21565
21566 void CodeGenerator::visitMapObjectSize(LMapObjectSize* ins) {
21567 Register mapObj = ToRegister(ins->mapObject());
21568 Register output = ToRegister(ins->output());
21569
21570 masm.loadMapObjectSize(mapObj, output);
21571 }
21572
21573 void CodeGenerator::visitDateFillLocalTimeSlots(LDateFillLocalTimeSlots* ins) {
21574 Register date = ToRegister(ins->date());
21575 Register temp = ToRegister(ins->temp0());
21576
21577 masm.dateFillLocalTimeSlots(date, temp, liveVolatileRegs(ins));
21578 }
21579
21580 void CodeGenerator::visitDateHoursFromSecondsIntoYear(
21581 LDateHoursFromSecondsIntoYear* ins) {
21582 auto secondsIntoYear = ToValue(ins->secondsIntoYear());
21583 auto output = ToOutValue(ins);
21584 Register temp0 = ToRegister(ins->temp0());
21585 Register temp1 = ToRegister(ins->temp1());
21586
21587 masm.dateHoursFromSecondsIntoYear(secondsIntoYear, output, temp0, temp1);
21588 }
21589
21590 void CodeGenerator::visitDateMinutesFromSecondsIntoYear(
21591 LDateMinutesFromSecondsIntoYear* ins) {
21592 auto secondsIntoYear = ToValue(ins->secondsIntoYear());
21593 auto output = ToOutValue(ins);
21594 Register temp0 = ToRegister(ins->temp0());
21595 Register temp1 = ToRegister(ins->temp1());
21596
21597 masm.dateMinutesFromSecondsIntoYear(secondsIntoYear, output, temp0, temp1);
21598 }
21599
21600 void CodeGenerator::visitDateSecondsFromSecondsIntoYear(
21601 LDateSecondsFromSecondsIntoYear* ins) {
21602 auto secondsIntoYear = ToValue(ins->secondsIntoYear());
21603 auto output = ToOutValue(ins);
21604 Register temp0 = ToRegister(ins->temp0());
21605 Register temp1 = ToRegister(ins->temp1());
21606
21607 masm.dateSecondsFromSecondsIntoYear(secondsIntoYear, output, temp0, temp1);
21608 }
21609
21610 void CodeGenerator::visitCanonicalizeNaND(LCanonicalizeNaND* ins) {
21611 auto output = ToFloatRegister(ins->output());
21612 MOZ_ASSERT(output == ToFloatRegister(ins->input()));
21613
21614 masm.canonicalizeDouble(output);
21615 }
21616
21617 void CodeGenerator::visitCanonicalizeNaNF(LCanonicalizeNaNF* ins) {
21618 auto output = ToFloatRegister(ins->output());
21619 MOZ_ASSERT(output == ToFloatRegister(ins->input()));
21620
21621 masm.canonicalizeFloat(output);
21622 }
21623
21624 template <size_t NumDefs>
21625 void CodeGenerator::emitIonToWasmCallBase(LIonToWasmCallBase<NumDefs>* lir) {
21626 wasm::JitCallStackArgVector stackArgs;
21627 masm.propagateOOM(stackArgs.reserve(lir->numOperands()));
21628 if (masm.oom()) {
21629 return;
21630 }
21631
21632 MIonToWasmCall* mir = lir->mir();
21633 const wasm::FuncExport& funcExport = mir->funcExport();
21634 const wasm::FuncType& sig =
21635 mir->instance()->code().codeMeta().getFuncType(funcExport.funcIndex());
21636
21637 WasmABIArgGenerator abi;
21638 for (size_t i = 0; i < lir->numOperands(); i++) {
21639 MIRType argMir;
21640 switch (sig.args()[i].kind()) {
21641 case wasm::ValType::I32:
21642 case wasm::ValType::I64:
21643 case wasm::ValType::F32:
21644 case wasm::ValType::F64:
21645 argMir = sig.args()[i].toMIRType();
21646 break;
21647 case wasm::ValType::V128:
21648 MOZ_CRASH("unexpected argument type when calling from ion to wasm");
21649 case wasm::ValType::Ref:
21650 // temporarilyUnsupportedReftypeForEntry() restricts args to externref
21651 MOZ_RELEASE_ASSERT(sig.args()[i].refType().isExtern());
21652 // Argument is boxed on the JS side to an anyref, so passed as a
21653 // pointer here.
21654 argMir = sig.args()[i].toMIRType();
21655 break;
21656 }
21657
21658 ABIArg arg = abi.next(argMir);
21659 switch (arg.kind()) {
21660 case ABIArg::GPR:
21661 case ABIArg::FPU: {
21662 MOZ_ASSERT(ToAnyRegister(lir->getOperand(i)) == arg.reg());
21663 stackArgs.infallibleEmplaceBack(wasm::JitCallStackArg());
21664 break;
21665 }
21666 case ABIArg::Stack: {
21667 const LAllocation* larg = lir->getOperand(i);
21668 if (larg->isConstant()) {
21669 stackArgs.infallibleEmplaceBack(ToInt32(larg));
21670 } else if (larg->isGeneralReg()) {
21671 stackArgs.infallibleEmplaceBack(ToRegister(larg));
21672 } else if (larg->isFloatReg()) {
21673 stackArgs.infallibleEmplaceBack(ToFloatRegister(larg));
21674 } else {
21675 // Always use the stack pointer here because GenerateDirectCallFromJit
21676 // depends on this.
21677 Address addr = ToAddress<BaseRegForAddress::SP>(larg);
21678 stackArgs.infallibleEmplaceBack(addr);
21679 }
21680 break;
21681 }
21682 #ifdef JS_CODEGEN_REGISTER_PAIR
21683 case ABIArg::GPR_PAIR: {
21684 MOZ_CRASH(
21685 "no way to pass i64, and wasm uses hardfp for function calls");
21686 }
21687 #endif
21688 case ABIArg::Uninitialized: {
21689 MOZ_CRASH("Uninitialized ABIArg kind");
21690 }
21691 }
21692 }
21693
21694 const wasm::ValTypeVector& results = sig.results();
21695 if (results.length() == 0) {
21696 MOZ_ASSERT(lir->mir()->type() == MIRType::Value);
21697 } else {
21698 MOZ_ASSERT(results.length() == 1, "multi-value return unimplemented");
21699 switch (results[0].kind()) {
21700 case wasm::ValType::I32:
21701 MOZ_ASSERT(lir->mir()->type() == MIRType::Int32);
21702 MOZ_ASSERT(ToRegister(lir->output()) == ReturnReg);
21703 break;
21704 case wasm::ValType::I64:
21705 MOZ_ASSERT(lir->mir()->type() == MIRType::Int64);
21706 MOZ_ASSERT(ToOutRegister64(lir) == ReturnReg64);
21707 break;
21708 case wasm::ValType::F32:
21709 MOZ_ASSERT(lir->mir()->type() == MIRType::Float32);
21710 MOZ_ASSERT(ToFloatRegister(lir->output()) == ReturnFloat32Reg);
21711 break;
21712 case wasm::ValType::F64:
21713 MOZ_ASSERT(lir->mir()->type() == MIRType::Double);
21714 MOZ_ASSERT(ToFloatRegister(lir->output()) == ReturnDoubleReg);
21715 break;
21716 case wasm::ValType::V128:
21717 MOZ_CRASH("unexpected return type when calling from ion to wasm");
21718 case wasm::ValType::Ref:
21719 // The wasm stubs layer unboxes anything that needs to be unboxed
21720 // and leaves it in a Value. A FuncRef/EqRef we could in principle
21721 // leave it as a raw object pointer but for now it complicates the
21722 // API to do so.
21723 MOZ_ASSERT(lir->mir()->type() == MIRType::Value);
21724 break;
21725 }
21726 }
21727
21728 WasmInstanceObject* instObj = lir->mir()->instanceObject();
21729
21730 Register scratch = ToRegister(lir->temp());
21731
21732 uint32_t callOffset;
21733 ensureOsiSpace();
21734 GenerateDirectCallFromJit(masm, funcExport, instObj->instance(), stackArgs,
21735 scratch, &callOffset);
21736
21737 // Add the instance object to the constant pool, so it is transferred to
21738 // the owning IonScript and so that it gets traced as long as the IonScript
21739 // lives.
21740
21741 uint32_t unused;
21742 masm.propagateOOM(graph.addConstantToPool(ObjectValue(*instObj), &unused));
21743
21744 markSafepointAt(callOffset, lir);
21745 }
21746
21747 void CodeGenerator::visitIonToWasmCall(LIonToWasmCall* lir) {
21748 emitIonToWasmCallBase(lir);
21749 }
21750 void CodeGenerator::visitIonToWasmCallV(LIonToWasmCallV* lir) {
21751 emitIonToWasmCallBase(lir);
21752 }
21753 void CodeGenerator::visitIonToWasmCallI64(LIonToWasmCallI64* lir) {
21754 emitIonToWasmCallBase(lir);
21755 }
21756
21757 void CodeGenerator::visitWasmNullConstant(LWasmNullConstant* lir) {
21758 masm.xorPtr(ToRegister(lir->output()), ToRegister(lir->output()));
21759 }
21760
21761 void CodeGenerator::visitWasmFence(LWasmFence* lir) {
21762 MOZ_ASSERT(gen->compilingWasm());
21763 masm.memoryBarrier(MemoryBarrier::Full());
21764 }
21765
21766 void CodeGenerator::visitWasmAnyRefFromJSValue(LWasmAnyRefFromJSValue* lir) {
21767 ValueOperand input = ToValue(lir->def());
21768 Register output = ToRegister(lir->output());
21769 FloatRegister tempFloat = ToFloatRegister(lir->temp0());
21770
21771 using Fn = JSObject* (*)(JSContext* cx, HandleValue value);
21772 OutOfLineCode* oolBoxValue = oolCallVM<Fn, wasm::AnyRef::boxValue>(
21773 lir, ArgList(input), StoreRegisterTo(output));
21774 masm.convertValueToWasmAnyRef(input, output, tempFloat, oolBoxValue->entry());
21775 masm.bind(oolBoxValue->rejoin());
21776 }
21777
21778 void CodeGenerator::visitWasmAnyRefFromJSObject(LWasmAnyRefFromJSObject* lir) {
21779 Register input = ToRegister(lir->def());
21780 Register output = ToRegister(lir->output());
21781 masm.convertObjectToWasmAnyRef(input, output);
21782 }
21783
21784 void CodeGenerator::visitWasmAnyRefFromJSString(LWasmAnyRefFromJSString* lir) {
21785 Register input = ToRegister(lir->def());
21786 Register output = ToRegister(lir->output());
21787 masm.convertStringToWasmAnyRef(input, output);
21788 }
21789
21790 void CodeGenerator::visitWasmAnyRefIsJSString(LWasmAnyRefIsJSString* lir) {
21791 Register input = ToRegister(lir->input());
21792 Register output = ToRegister(lir->output());
21793 Register temp = ToRegister(lir->temp0());
21794 Label fallthrough;
21795 Label isJSString;
21796 masm.branchWasmAnyRefIsJSString(true, input, temp, &isJSString);
21797 masm.move32(Imm32(0), output);
21798 masm.jump(&fallthrough);
21799 masm.bind(&isJSString);
21800 masm.move32(Imm32(1), output);
21801 masm.bind(&fallthrough);
21802 }
21803
21804 void CodeGenerator::visitWasmTrapIfAnyRefIsNotJSString(
21805 LWasmTrapIfAnyRefIsNotJSString* lir) {
21806 Register input = ToRegister(lir->input());
21807 Register temp = ToRegister(lir->temp0());
21808 Label isJSString;
21809 masm.branchWasmAnyRefIsJSString(true, input, temp, &isJSString);
21810 masm.wasmTrap(lir->mir()->trap(), lir->mir()->trapSiteDesc());
21811 masm.bind(&isJSString);
21812 }
21813
21814 void CodeGenerator::visitWasmAnyRefJSStringLength(
21815 LWasmAnyRefJSStringLength* lir) {
21816 Register input = ToRegister(lir->input());
21817 Register output = ToRegister(lir->output());
21818 Register temp = ToRegister(lir->temp0());
21819 Label isJSString;
21820 masm.branchWasmAnyRefIsJSString(true, input, temp, &isJSString);
21821 masm.wasmTrap(lir->mir()->trap(), lir->mir()->trapSiteDesc());
21822 masm.bind(&isJSString);
21823 masm.untagWasmAnyRef(input, temp, wasm::AnyRefTag::String);
21824 masm.loadStringLength(temp, output);
21825 }
21826
21827 void CodeGenerator::visitWasmNewI31Ref(LWasmNewI31Ref* lir) {
21828 if (lir->value()->isConstant()) {
21829 // i31ref are often created with constants. If that's the case we will
21830 // do the operation statically here. This is similar to what is done
21831 // in masm.truncate32ToWasmI31Ref.
21832 Register output = ToRegister(lir->output());
21833 uint32_t value =
21834 static_cast<uint32_t>(lir->value()->toConstant()->toInt32());
21835 uintptr_t ptr = wasm::AnyRef::fromUint32Truncate(value).rawValue();
21836 masm.movePtr(ImmWord(ptr), output);
21837 } else {
21838 Register value = ToRegister(lir->value());
21839 Register output = ToRegister(lir->output());
21840 masm.truncate32ToWasmI31Ref(value, output);
21841 }
21842 }
21843
21844 void CodeGenerator::visitWasmI31RefGet(LWasmI31RefGet* lir) {
21845 Register value = ToRegister(lir->input());
21846 Register output = ToRegister(lir->output());
21847 if (lir->mir()->wideningOp() == wasm::FieldWideningOp::Signed) {
21848 masm.convertWasmI31RefTo32Signed(value, output);
21849 } else {
21850 masm.convertWasmI31RefTo32Unsigned(value, output);
21851 }
21852 }
21853
21854 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
21855 void CodeGenerator::visitAddDisposableResource(LAddDisposableResource* lir) {
21856 Register environment = ToRegister(lir->environment());
21857 ValueOperand resource = ToValue(lir->resource());
21858 ValueOperand method = ToValue(lir->method());
21859 Register needsClosure = ToRegister(lir->needsClosure());
21860 uint8_t hint = lir->hint();
21861
21862 pushArg(Imm32(hint));
21863 pushArg(needsClosure);
21864 pushArg(method);
21865 pushArg(resource);
21866 pushArg(environment);
21867
21868 using Fn = bool (*)(JSContext*, JS::Handle<JSObject*>, JS::Handle<JS::Value>,
21869 JS::Handle<JS::Value>, bool, UsingHint);
21870 callVM<Fn, js::AddDisposableResourceToCapability>(lir);
21871 }
21872
21873 void CodeGenerator::visitTakeDisposeCapability(LTakeDisposeCapability* lir) {
21874 Register environment = ToRegister(lir->environment());
21875 ValueOperand output = ToOutValue(lir);
21876
21877 Address capabilityAddr(
21878 environment, DisposableEnvironmentObject::offsetOfDisposeCapability());
21879 emitPreBarrier(capabilityAddr);
21880 masm.loadValue(capabilityAddr, output);
21881 masm.storeValue(JS::UndefinedValue(), capabilityAddr);
21882 }
21883
21884 void CodeGenerator::visitCreateSuppressedError(LCreateSuppressedError* lir) {
21885 ValueOperand error = ToValue(lir->error());
21886 ValueOperand suppressed = ToValue(lir->suppressed());
21887
21888 pushArg(suppressed);
21889 pushArg(error);
21890
21891 using Fn = ErrorObject* (*)(JSContext*, JS::Handle<JS::Value>,
21892 JS::Handle<JS::Value>);
21893 callVM<Fn, js::CreateSuppressedError>(lir);
21894 }
21895 #endif
21896
21897 #ifdef FUZZING_JS_FUZZILLI
21898 void CodeGenerator::emitFuzzilliHashObject(LInstruction* lir, Register obj,
21899 Register output) {
21900 using Fn = void (*)(JSContext* cx, JSObject* obj, uint32_t* out);
21901 OutOfLineCode* ool = oolCallVM<Fn, FuzzilliHashObjectInl>(
21902 lir, ArgList(obj), StoreRegisterTo(output));
21903
21904 masm.jump(ool->entry());
21905 masm.bind(ool->rejoin());
21906 }
21907
21908 void CodeGenerator::emitFuzzilliHashBigInt(LInstruction* lir, Register bigInt,
21909 Register output) {
21910 LiveRegisterSet volatileRegs = liveVolatileRegs(lir);
21911 volatileRegs.takeUnchecked(output);
21912
21913 masm.PushRegsInMask(volatileRegs);
21914
21915 using Fn = uint32_t (*)(BigInt* bigInt);
21916 masm.setupUnalignedABICall(output);
21917 masm.passABIArg(bigInt);
21918 masm.callWithABI<Fn, js::FuzzilliHashBigInt>();
21919 masm.storeCallInt32Result(output);
21920
21921 masm.PopRegsInMask(volatileRegs);
21922 }
21923
21924 void CodeGenerator::visitFuzzilliHashV(LFuzzilliHashV* ins) {
21925 ValueOperand value = ToValue(ins->value());
21926
21927 FloatRegister scratchFloat = ToFloatRegister(ins->temp1());
21928 Register scratch = ToRegister(ins->temp0());
21929 Register output = ToRegister(ins->output());
21930 MOZ_ASSERT(scratch != output);
21931
21932 Label hashDouble, done;
21933
21934 Label isInt32, isDouble, isNull, isUndefined, isBoolean, isBigInt, isObject;
21935 {
21936 ScratchTagScope tag(masm, value);
21937 masm.splitTagForTest(value, tag);
21938
21939 masm.branchTestInt32(Assembler::Equal, tag, &isInt32);
21940 masm.branchTestDouble(Assembler::Equal, tag, &isDouble);
21941 masm.branchTestNull(Assembler::Equal, tag, &isNull);
21942 masm.branchTestUndefined(Assembler::Equal, tag, &isUndefined);
21943 masm.branchTestBoolean(Assembler::Equal, tag, &isBoolean);
21944 masm.branchTestBigInt(Assembler::Equal, tag, &isBigInt);
21945 masm.branchTestObject(Assembler::Equal, tag, &isObject);
21946
21947 // Symbol or String.
21948 masm.move32(Imm32(0), output);
21949 masm.jump(&done);
21950 }
21951
21952 masm.bind(&isInt32);
21953 {
21954 masm.unboxInt32(value, scratch);
21955 masm.convertInt32ToDouble(scratch, scratchFloat);
21956 masm.jump(&hashDouble);
21957 }
21958
21959 masm.bind(&isDouble);
21960 {
21961 masm.unboxDouble(value, scratchFloat);
21962 masm.jump(&hashDouble);
21963 }
21964
21965 masm.bind(&isNull);
21966 {
21967 masm.loadConstantDouble(1.0, scratchFloat);
21968 masm.jump(&hashDouble);
21969 }
21970
21971 masm.bind(&isUndefined);
21972 {
21973 masm.loadConstantDouble(2.0, scratchFloat);
21974 masm.jump(&hashDouble);
21975 }
21976
21977 masm.bind(&isBoolean);
21978 {
21979 masm.unboxBoolean(value, scratch);
21980 masm.add32(Imm32(3), scratch);
21981 masm.convertInt32ToDouble(scratch, scratchFloat);
21982 masm.jump(&hashDouble);
21983 }
21984
21985 masm.bind(&isBigInt);
21986 {
21987 masm.unboxBigInt(value, scratch);
21988 emitFuzzilliHashBigInt(ins, scratch, output);
21989 masm.jump(&done);
21990 }
21991
21992 masm.bind(&isObject);
21993 {
21994 masm.unboxObject(value, scratch);
21995 emitFuzzilliHashObject(ins, scratch, output);
21996 masm.jump(&done);
21997 }
21998
21999 masm.bind(&hashDouble);
22000 masm.fuzzilliHashDouble(scratchFloat, output, scratch);
22001
22002 masm.bind(&done);
22003 }
22004
22005 void CodeGenerator::visitFuzzilliHashT(LFuzzilliHashT* ins) {
22006 const LAllocation* value = ins->value();
22007 MIRType mirType = ins->mir()->getOperand(0)->type();
22008
22009 Register scratch = ToTempRegisterOrInvalid(ins->temp0());
22010 FloatRegister scratchFloat = ToTempFloatRegisterOrInvalid(ins->temp1());
22011
22012 Register output = ToRegister(ins->output());
22013 MOZ_ASSERT(scratch != output);
22014
22015 switch (mirType) {
22016 case MIRType::Undefined: {
22017 masm.loadConstantDouble(2.0, scratchFloat);
22018 masm.fuzzilliHashDouble(scratchFloat, output, scratch);
22019 break;
22020 }
22021
22022 case MIRType::Null: {
22023 masm.loadConstantDouble(1.0, scratchFloat);
22024 masm.fuzzilliHashDouble(scratchFloat, output, scratch);
22025 break;
22026 }
22027
22028 case MIRType::Int32: {
22029 masm.move32(ToRegister(value), scratch);
22030 masm.convertInt32ToDouble(scratch, scratchFloat);
22031 masm.fuzzilliHashDouble(scratchFloat, output, scratch);
22032 break;
22033 }
22034
22035 case MIRType::Double: {
22036 masm.moveDouble(ToFloatRegister(value), scratchFloat);
22037 masm.fuzzilliHashDouble(scratchFloat, output, scratch);
22038 break;
22039 }
22040
22041 case MIRType::Float32: {
22042 masm.convertFloat32ToDouble(ToFloatRegister(value), scratchFloat);
22043 masm.fuzzilliHashDouble(scratchFloat, output, scratch);
22044 break;
22045 }
22046
22047 case MIRType::Boolean: {
22048 masm.add32(Imm32(3), ToRegister(value), scratch);
22049 masm.convertInt32ToDouble(scratch, scratchFloat);
22050 masm.fuzzilliHashDouble(scratchFloat, output, scratch);
22051 break;
22052 }
22053
22054 case MIRType::BigInt: {
22055 emitFuzzilliHashBigInt(ins, ToRegister(value), output);
22056 break;
22057 }
22058
22059 case MIRType::Object: {
22060 emitFuzzilliHashObject(ins, ToRegister(value), output);
22061 break;
22062 }
22063
22064 default:
22065 MOZ_CRASH("unexpected type");
22066 }
22067 }
22068
22069 void CodeGenerator::visitFuzzilliHashStore(LFuzzilliHashStore* ins) {
22070 Register value = ToRegister(ins->value());
22071 Register temp0 = ToRegister(ins->temp0());
22072 Register temp1 = ToRegister(ins->temp1());
22073
22074 masm.fuzzilliStoreHash(value, temp0, temp1);
22075 }
22076 #endif
22077
22078 static_assert(!std::is_polymorphic_v<CodeGenerator>,
22079 "CodeGenerator should not have any virtual methods");
22080
22081 } // namespace jit
22082 } // namespace js