Debian Codegraph @

js/src/jit/BaselineCacheIRCompiler.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/BaselineCacheIRCompiler.h"
8
9 #include "mozilla/RandomNum.h"
10
11 #include "gc/GC.h"
12 #include "jit/CacheIR.h"
13 #include "jit/CacheIRAOT.h"
14 #include "jit/CacheIRCloner.h"
15 #include "jit/CacheIRSpewer.h"
16 #include "jit/CacheIRWriter.h"
17 #include "jit/JitFrames.h"
18 #include "jit/JitRuntime.h"
19 #include "jit/JitZone.h"
20 #include "jit/Linker.h"
21 #include "jit/MoveEmitter.h"
22 #include "jit/RegExpStubConstants.h"
23 #include "jit/SharedICHelpers.h"
24 #include "jit/VMFunctions.h"
25 #include "js/experimental/JitInfo.h" // JSJitInfo
26 #include "js/friend/DOMProxy.h" // JS::ExpandoAndGeneration
27 #include "proxy/DeadObjectProxy.h"
28 #include "proxy/Proxy.h"
29 #include "util/DifferentialTesting.h"
30 #include "util/Unicode.h"
31 #include "vm/PortableBaselineInterpret.h"
32 #include "vm/StaticStrings.h"
33
34 #include "jit/JitScript-inl.h"
35 #include "jit/MacroAssembler-inl.h"
36 #include "jit/SharedICHelpers-inl.h"
37 #include "jit/VMFunctionList-inl.h"
38 #include "vm/List-inl.h"
39
40 using namespace js;
41 using namespace js::jit;
42
43 using mozilla::Maybe;
44
45 using JS::ExpandoAndGeneration;
46
47 namespace js {
48 namespace jit {
49
50 static uint32_t GetICStackValueOffset() {
51 uint32_t offset = ICStackValueOffset;
52 if (JitOptions.enableICFramePointers) {
53 #ifdef JS_USE_LINK_REGISTER
54 // The frame pointer and return address are also on the stack.
55 offset += 2 * sizeof(uintptr_t);
56 #else
57 // The frame pointer is also on the stack.
58 offset += sizeof(uintptr_t);
59 #endif
60 }
61 return offset;
62 }
63
64 static void PushICFrameRegs(MacroAssembler& masm) {
65 MOZ_ASSERT(JitOptions.enableICFramePointers);
66 #ifdef JS_USE_LINK_REGISTER
67 masm.pushReturnAddress();
68 #endif
69 masm.push(FramePointer);
70 }
71
72 static void PopICFrameRegs(MacroAssembler& masm) {
73 MOZ_ASSERT(JitOptions.enableICFramePointers);
74 masm.pop(FramePointer);
75 #ifdef JS_USE_LINK_REGISTER
76 masm.popReturnAddress();
77 #endif
78 }
79
80 Address CacheRegisterAllocator::addressOf(MacroAssembler& masm,
81 BaselineFrameSlot slot) const {
82 uint32_t offset =
83 stackPushed_ + GetICStackValueOffset() + slot.slot() * sizeof(JS::Value);
84 return Address(masm.getStackPointer(), offset);
85 }
86 BaseValueIndex CacheRegisterAllocator::addressOf(MacroAssembler& masm,
87 Register argcReg,
88 BaselineFrameSlot slot) const {
89 uint32_t offset =
90 stackPushed_ + GetICStackValueOffset() + slot.slot() * sizeof(JS::Value);
91 return BaseValueIndex(masm.getStackPointer(), argcReg, offset);
92 }
93
94 // BaselineCacheIRCompiler compiles CacheIR to BaselineIC native code.
95 BaselineCacheIRCompiler::BaselineCacheIRCompiler(JSContext* cx,
96 TempAllocator& alloc,
97 const CacheIRWriter& writer,
98 uint32_t stubDataOffset)
99 : CacheIRCompiler(cx, alloc, writer, stubDataOffset, Mode::Baseline,
100 StubFieldPolicy::Address),
101 makesGCCalls_(false) {}
102
103 // AutoStubFrame methods
104 AutoStubFrame::AutoStubFrame(BaselineCacheIRCompiler& compiler)
105 : compiler(compiler)
106 #ifdef DEBUG
107 ,
108 framePushedAtEnterStubFrame_(0)
109 #endif
110 {
111 }
112 void AutoStubFrame::enter(MacroAssembler& masm, Register scratch) {
113 MOZ_ASSERT(compiler.allocator.stackPushed() == 0);
114
115 if (JitOptions.enableICFramePointers) {
116 // If we have already pushed the frame pointer, pop it
117 // before creating the stub frame.
118 PopICFrameRegs(masm);
119 }
120 EmitBaselineEnterStubFrame(masm, scratch);
121
122 #ifdef DEBUG
123 framePushedAtEnterStubFrame_ = masm.framePushed();
124 #endif
125
126 MOZ_ASSERT(!compiler.enteredStubFrame_);
127 compiler.enteredStubFrame_ = true;
128
129 // All current uses of this are to call VM functions that can GC.
130 compiler.makesGCCalls_ = true;
131 }
132 void AutoStubFrame::leave(MacroAssembler& masm) {
133 MOZ_ASSERT(compiler.enteredStubFrame_);
134 compiler.enteredStubFrame_ = false;
135
136 #ifdef DEBUG
137 masm.setFramePushed(framePushedAtEnterStubFrame_);
138 #endif
139
140 EmitBaselineLeaveStubFrame(masm);
141 if (JitOptions.enableICFramePointers) {
142 // We will pop the frame pointer when we return,
143 // so we have to push it again now.
144 PushICFrameRegs(masm);
145 }
146 }
147
148 void AutoStubFrame::storeTracedValue(MacroAssembler& masm, ValueOperand value) {
149 MOZ_ASSERT(compiler.localTracingSlots_ < 255);
150 MOZ_ASSERT(masm.framePushed() - framePushedAtEnterStubFrame_ ==
151 compiler.localTracingSlots_ * sizeof(Value));
152 masm.Push(value);
153 compiler.localTracingSlots_++;
154 }
155
156 void AutoStubFrame::loadTracedValue(MacroAssembler& masm, uint8_t slotIndex,
157 ValueOperand value) {
158 MOZ_ASSERT(slotIndex <= compiler.localTracingSlots_);
159 int32_t offset = BaselineStubFrameLayout::LocallyTracedValueOffset +
160 slotIndex * sizeof(Value);
161 masm.loadValue(Address(FramePointer, -offset), value);
162 }
163
164 #ifdef DEBUG
165 AutoStubFrame::~AutoStubFrame() { MOZ_ASSERT(!compiler.enteredStubFrame_); }
166 #endif
167
168 } // namespace jit
169 } // namespace js
170
171 bool BaselineCacheIRCompiler::makesGCCalls() const { return makesGCCalls_; }
172
173 Address BaselineCacheIRCompiler::stubAddress(uint32_t offset) const {
174 return Address(ICStubReg, stubDataOffset_ + offset);
175 }
176
177 template <typename Fn, Fn fn>
178 void BaselineCacheIRCompiler::callVM(MacroAssembler& masm) {
179 VMFunctionId id = VMFunctionToId<Fn, fn>::id;
180 callVMInternal(masm, id);
181 }
182
183 JitCode* BaselineCacheIRCompiler::compile() {
184 AutoCreatedBy acb(masm, "BaselineCacheIRCompiler::compile");
185
186 #ifndef JS_USE_LINK_REGISTER
187 masm.adjustFrame(sizeof(intptr_t));
188 #endif
189 #ifdef JS_CODEGEN_ARM
190 AutoNonDefaultSecondScratchRegister andssr(masm, BaselineSecondScratchReg);
191 #endif
192 if (JitOptions.enableICFramePointers) {
193 /* [SMDOC] Baseline IC Frame Pointers
194 *
195 * In general, ICs don't have frame pointers until just before
196 * doing a VM call, at which point we retroactively create a stub
197 * frame. However, for the sake of external profilers, we
198 * optionally support full-IC frame pointers in baseline ICs, with
199 * the following approach:
200 * 1. We push a frame pointer when we enter an IC.
201 * 2. We pop the frame pointer when we return from an IC, or
202 * when we jump to the next IC.
203 * 3. Entering a stub frame for a VM call already pushes a
204 * frame pointer, so we pop our existing frame pointer
205 * just before entering a stub frame and push it again
206 * just after leaving a stub frame.
207 * Some ops take advantage of the fact that the frame pointer is
208 * not updated until we enter a stub frame to read values from
209 * the caller's frame. To support this, we allocate a separate
210 * baselineFrame register when IC frame pointers are enabled.
211 */
212 PushICFrameRegs(masm);
213 masm.moveStackPtrTo(FramePointer);
214
215 MOZ_ASSERT(baselineFrameReg() != FramePointer);
216 masm.loadPtr(Address(FramePointer, 0), baselineFrameReg());
217 }
218
219 // Count stub entries: We count entries rather than successes as it much
220 // easier to ensure ICStubReg is valid at entry than at exit.
221 Address enteredCount(ICStubReg, ICCacheIRStub::offsetOfEnteredCount());
222 masm.add32(Imm32(1), enteredCount);
223
224 CacheIRReader reader(writer_);
225 do {
226 CacheOp op = reader.readOp();
227 perfSpewer_.recordInstruction(masm, op);
228 switch (op) {
229 #define DEFINE_OP(op, ...) \
230 case CacheOp::op: \
231 if (!emit##op(reader)) return nullptr; \
232 break;
233 CACHE_IR_OPS(DEFINE_OP)
234 #undef DEFINE_OP
235
236 default:
237 MOZ_CRASH("Invalid op");
238 }
239 allocator.nextOp();
240 } while (reader.more());
241
242 MOZ_ASSERT(!enteredStubFrame_);
243 masm.assumeUnreachable("Should have returned from IC");
244
245 // Done emitting the main IC code. Now emit the failure paths.
246 for (size_t i = 0; i < failurePaths.length(); i++) {
247 if (!emitFailurePath(i)) {
248 return nullptr;
249 }
250 if (JitOptions.enableICFramePointers) {
251 PopICFrameRegs(masm);
252 }
253 EmitStubGuardFailure(masm);
254 }
255
256 Linker linker(masm);
257 Rooted<JitCode*> newStubCode(cx_, linker.newCode(cx_, CodeKind::Baseline));
258 if (!newStubCode) {
259 cx_->recoverFromOutOfMemory();
260 return nullptr;
261 }
262
263 newStubCode->setLocalTracingSlots(localTracingSlots_);
264
265 return newStubCode;
266 }
267
268 bool BaselineCacheIRCompiler::emitGuardShape(ObjOperandId objId,
269 uint32_t shapeOffset) {
270 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
271 Register obj = allocator.useRegister(masm, objId);
272 AutoScratchRegister scratch1(allocator, masm);
273
274 bool needSpectreMitigations = objectGuardNeedsSpectreMitigations(objId);
275
276 Maybe<AutoScratchRegister> maybeScratch2;
277 if (needSpectreMitigations) {
278 maybeScratch2.emplace(allocator, masm);
279 }
280
281 FailurePath* failure;
282 if (!addFailurePath(&failure)) {
283 return false;
284 }
285
286 Address addr(stubAddress(shapeOffset));
287 masm.loadPtr(addr, scratch1);
288 if (needSpectreMitigations) {
289 masm.branchTestObjShape(Assembler::NotEqual, obj, scratch1, *maybeScratch2,
290 obj, failure->label());
291 } else {
292 masm.branchTestObjShapeNoSpectreMitigations(Assembler::NotEqual, obj,
293 scratch1, failure->label());
294 }
295
296 return true;
297 }
298
299 bool BaselineCacheIRCompiler::emitGuardProto(ObjOperandId objId,
300 uint32_t protoOffset) {
301 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
302 Register obj = allocator.useRegister(masm, objId);
303 AutoScratchRegister scratch(allocator, masm);
304
305 FailurePath* failure;
306 if (!addFailurePath(&failure)) {
307 return false;
308 }
309
310 Address addr(stubAddress(protoOffset));
311 masm.loadObjProto(obj, scratch);
312 masm.branchPtr(Assembler::NotEqual, addr, scratch, failure->label());
313 return true;
314 }
315
316 bool BaselineCacheIRCompiler::emitGuardCompartment(ObjOperandId objId,
317 uint32_t globalOffset,
318 uint32_t compartmentOffset) {
319 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
320 Register obj = allocator.useRegister(masm, objId);
321 AutoScratchRegister scratch(allocator, masm);
322
323 FailurePath* failure;
324 if (!addFailurePath(&failure)) {
325 return false;
326 }
327
328 // Verify that the global wrapper is still valid, as
329 // it is pre-requisite for doing the compartment check.
330 Address globalWrapper(stubAddress(globalOffset));
331 masm.loadPtr(globalWrapper, scratch);
332 Address handlerAddr(scratch, ProxyObject::offsetOfHandler());
333 masm.branchPtr(Assembler::Equal, handlerAddr,
334 ImmPtr(&DeadObjectProxy::singleton), failure->label());
335
336 Address addr(stubAddress(compartmentOffset));
337 masm.branchTestObjCompartment(Assembler::NotEqual, obj, addr, scratch,
338 failure->label());
339 return true;
340 }
341
342 bool BaselineCacheIRCompiler::emitGuardAnyClass(ObjOperandId objId,
343 uint32_t claspOffset) {
344 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
345 Register obj = allocator.useRegister(masm, objId);
346 AutoScratchRegister scratch(allocator, masm);
347
348 FailurePath* failure;
349 if (!addFailurePath(&failure)) {
350 return false;
351 }
352
353 Address testAddr(stubAddress(claspOffset));
354 if (objectGuardNeedsSpectreMitigations(objId)) {
355 masm.branchTestObjClass(Assembler::NotEqual, obj, testAddr, scratch, obj,
356 failure->label());
357 } else {
358 masm.branchTestObjClassNoSpectreMitigations(
359 Assembler::NotEqual, obj, testAddr, scratch, failure->label());
360 }
361
362 return true;
363 }
364
365 bool BaselineCacheIRCompiler::emitGuardHasProxyHandler(ObjOperandId objId,
366 uint32_t handlerOffset) {
367 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
368 Register obj = allocator.useRegister(masm, objId);
369 AutoScratchRegister scratch(allocator, masm);
370
371 FailurePath* failure;
372 if (!addFailurePath(&failure)) {
373 return false;
374 }
375
376 Address testAddr(stubAddress(handlerOffset));
377 masm.loadPtr(testAddr, scratch);
378
379 Address handlerAddr(obj, ProxyObject::offsetOfHandler());
380 masm.branchPtr(Assembler::NotEqual, handlerAddr, scratch, failure->label());
381 return true;
382 }
383
384 bool BaselineCacheIRCompiler::emitGuardSpecificObject(ObjOperandId objId,
385 uint32_t expectedOffset) {
386 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
387 Register obj = allocator.useRegister(masm, objId);
388
389 FailurePath* failure;
390 if (!addFailurePath(&failure)) {
391 return false;
392 }
393
394 Address addr(stubAddress(expectedOffset));
395 masm.branchPtr(Assembler::NotEqual, addr, obj, failure->label());
396 return true;
397 }
398
399 bool BaselineCacheIRCompiler::emitGuardSpecificFunction(
400 ObjOperandId objId, uint32_t expectedOffset, uint32_t nargsAndFlagsOffset) {
401 return emitGuardSpecificObject(objId, expectedOffset);
402 }
403
404 bool BaselineCacheIRCompiler::emitGuardFunctionScript(
405 ObjOperandId funId, uint32_t expectedOffset, uint32_t nargsAndFlagsOffset) {
406 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
407
408 Register fun = allocator.useRegister(masm, funId);
409 AutoScratchRegister scratch(allocator, masm);
410
411 FailurePath* failure;
412 if (!addFailurePath(&failure)) {
413 return false;
414 }
415
416 Address addr(stubAddress(expectedOffset));
417 masm.loadPrivate(Address(fun, JSFunction::offsetOfJitInfoOrScript()),
418 scratch);
419 masm.branchPtr(Assembler::NotEqual, addr, scratch, failure->label());
420 return true;
421 }
422
423 bool BaselineCacheIRCompiler::emitGuardSpecificAtom(StringOperandId strId,
424 uint32_t expectedOffset) {
425 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
426 Register str = allocator.useRegister(masm, strId);
427 AutoScratchRegister scratch(allocator, masm);
428
429 FailurePath* failure;
430 if (!addFailurePath(&failure)) {
431 return false;
432 }
433
434 Address atomAddr(stubAddress(expectedOffset));
435
436 Label done, notCachedAtom;
437 masm.branchPtr(Assembler::Equal, atomAddr, str, &done);
438
439 // The pointers are not equal, so if the input string is also an atom it
440 // must be a different string.
441 masm.branchTest32(Assembler::NonZero, Address(str, JSString::offsetOfFlags()),
442 Imm32(JSString::ATOM_BIT), failure->label());
443
444 masm.tryFastAtomize(str, scratch, scratch, &notCachedAtom);
445 masm.branchPtr(Assembler::Equal, atomAddr, scratch, &done);
446 masm.jump(failure->label());
447 masm.bind(&notCachedAtom);
448
449 // Check the length.
450 masm.loadPtr(atomAddr, scratch);
451 masm.loadStringLength(scratch, scratch);
452 masm.branch32(Assembler::NotEqual, Address(str, JSString::offsetOfLength()),
453 scratch, failure->label());
454
455 // We have a non-atomized string with the same length. Call a helper
456 // function to do the comparison.
457 LiveRegisterSet volatileRegs = liveVolatileRegs();
458 masm.PushRegsInMask(volatileRegs);
459
460 using Fn = bool (*)(JSString* str1, JSString* str2);
461 masm.setupUnalignedABICall(scratch);
462 masm.loadPtr(atomAddr, scratch);
463 masm.passABIArg(scratch);
464 masm.passABIArg(str);
465 masm.callWithABI<Fn, EqualStringsHelperPure>();
466 masm.storeCallPointerResult(scratch);
467
468 LiveRegisterSet ignore;
469 ignore.add(scratch);
470 masm.PopRegsInMaskIgnore(volatileRegs, ignore);
471 masm.branchIfFalseBool(scratch, failure->label());
472
473 masm.bind(&done);
474 return true;
475 }
476
477 bool BaselineCacheIRCompiler::emitGuardSpecificSymbol(SymbolOperandId symId,
478 uint32_t expectedOffset) {
479 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
480 Register sym = allocator.useRegister(masm, symId);
481
482 FailurePath* failure;
483 if (!addFailurePath(&failure)) {
484 return false;
485 }
486
487 Address addr(stubAddress(expectedOffset));
488 masm.branchPtr(Assembler::NotEqual, addr, sym, failure->label());
489 return true;
490 }
491
492 bool BaselineCacheIRCompiler::emitGuardSpecificValue(ValOperandId valId,
493 uint32_t expectedOffset) {
494 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
495 ValueOperand val = allocator.useValueRegister(masm, valId);
496
497 FailurePath* failure;
498 if (!addFailurePath(&failure)) {
499 return false;
500 }
501
502 Address addr(stubAddress(expectedOffset));
503 masm.branchTestValue(Assembler::NotEqual, addr, val, failure->label());
504 return true;
505 }
506
507 bool BaselineCacheIRCompiler::emitLoadValueResult(uint32_t valOffset) {
508 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
509 AutoOutputRegister output(*this);
510 masm.loadValue(stubAddress(valOffset), output.valueReg());
511 return true;
512 }
513
514 bool BaselineCacheIRCompiler::emitLoadFixedSlotResult(ObjOperandId objId,
515 uint32_t offsetOffset) {
516 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
517 AutoOutputRegister output(*this);
518 Register obj = allocator.useRegister(masm, objId);
519 AutoScratchRegisterMaybeOutput scratch(allocator, masm, output);
520
521 masm.load32(stubAddress(offsetOffset), scratch);
522 masm.loadValue(BaseIndex(obj, scratch, TimesOne), output.valueReg());
523 return true;
524 }
525
526 bool BaselineCacheIRCompiler::emitLoadFixedSlotTypedResult(
527 ObjOperandId objId, uint32_t offsetOffset, ValueType) {
528 // The type is only used by Warp.
529 return emitLoadFixedSlotResult(objId, offsetOffset);
530 }
531
532 bool BaselineCacheIRCompiler::emitLoadDynamicSlotResult(ObjOperandId objId,
533 uint32_t offsetOffset) {
534 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
535 AutoOutputRegister output(*this);
536 Register obj = allocator.useRegister(masm, objId);
537 AutoScratchRegisterMaybeOutput scratch(allocator, masm, output);
538 AutoScratchRegister scratch2(allocator, masm);
539
540 masm.load32(stubAddress(offsetOffset), scratch);
541 masm.loadPtr(Address(obj, NativeObject::offsetOfSlots()), scratch2);
542 masm.loadValue(BaseIndex(scratch2, scratch, TimesOne), output.valueReg());
543 return true;
544 }
545
546 bool BaselineCacheIRCompiler::emitCallScriptedGetterShared(
547 ValOperandId receiverId, uint32_t getterOffset, bool sameRealm,
548 uint32_t nargsAndFlagsOffset, Maybe<uint32_t> icScriptOffset) {
549 ValueOperand receiver = allocator.useValueRegister(masm, receiverId);
550 Address getterAddr(stubAddress(getterOffset));
551
552 AutoScratchRegister code(allocator, masm);
553 AutoScratchRegister callee(allocator, masm);
554 AutoScratchRegister scratch(allocator, masm);
555
556 bool isInlined = icScriptOffset.isSome();
557
558 // First, retrieve raw jitcode for getter.
559 masm.loadPtr(getterAddr, callee);
560 if (isInlined) {
561 FailurePath* failure;
562 if (!addFailurePath(&failure)) {
563 return false;
564 }
565 masm.loadBaselineJitCodeRaw(callee, code, failure->label());
566 } else {
567 masm.loadJitCodeRaw(callee, code);
568 }
569
570 allocator.discardStack(masm);
571
572 AutoStubFrame stubFrame(*this);
573 stubFrame.enter(masm, scratch);
574
575 if (!sameRealm) {
576 masm.switchToObjectRealm(callee, scratch);
577 }
578
579 // Align the stack such that the JitFrameLayout is aligned on
580 // JitStackAlignment.
581 masm.alignJitStackBasedOnNArgs(0, /*countIncludesThis = */ false);
582
583 // Getter is called with 0 arguments, just |receiver| as thisv.
584 // Note that we use Push, not push, so that callJit will align the stack
585 // properly on ARM.
586 masm.Push(receiver);
587
588 if (isInlined) {
589 // Store icScript in the context.
590 Address icScriptAddr(stubAddress(*icScriptOffset));
591 masm.loadPtr(icScriptAddr, scratch);
592 masm.storeICScriptInJSContext(scratch);
593 }
594
595 masm.Push(callee);
596 masm.PushFrameDescriptorForJitCall(FrameType::BaselineStub, /* argc = */ 0);
597
598 // Handle arguments underflow.
599 Label noUnderflow;
600 masm.loadFunctionArgCount(callee, callee);
601 masm.branch32(Assembler::Equal, callee, Imm32(0), &noUnderflow);
602
603 // Call the arguments rectifier.
604 ArgumentsRectifierKind kind = isInlined
605 ? ArgumentsRectifierKind::TrialInlining
606 : ArgumentsRectifierKind::Normal;
607 TrampolinePtr argumentsRectifier =
608 cx_->runtime()->jitRuntime()->getArgumentsRectifier(kind);
609 masm.movePtr(argumentsRectifier, code);
610
611 masm.bind(&noUnderflow);
612 masm.callJit(code);
613
614 stubFrame.leave(masm);
615
616 if (!sameRealm) {
617 masm.switchToBaselineFrameRealm(R1.scratchReg());
618 }
619
620 return true;
621 }
622
623 bool BaselineCacheIRCompiler::emitCallScriptedGetterResult(
624 ValOperandId receiverId, uint32_t getterOffset, bool sameRealm,
625 uint32_t nargsAndFlagsOffset) {
626 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
627 Maybe<uint32_t> icScriptOffset = mozilla::Nothing();
628 return emitCallScriptedGetterShared(receiverId, getterOffset, sameRealm,
629 nargsAndFlagsOffset, icScriptOffset);
630 }
631
632 bool BaselineCacheIRCompiler::emitCallInlinedGetterResult(
633 ValOperandId receiverId, uint32_t getterOffset, uint32_t icScriptOffset,
634 bool sameRealm, uint32_t nargsAndFlagsOffset) {
635 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
636 return emitCallScriptedGetterShared(receiverId, getterOffset, sameRealm,
637 nargsAndFlagsOffset,
638 mozilla::Some(icScriptOffset));
639 }
640
641 bool BaselineCacheIRCompiler::emitCallNativeGetterResult(
642 ValOperandId receiverId, uint32_t getterOffset, bool sameRealm,
643 uint32_t nargsAndFlagsOffset) {
644 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
645
646 ValueOperand receiver = allocator.useValueRegister(masm, receiverId);
647 Address getterAddr(stubAddress(getterOffset));
648
649 AutoScratchRegister scratch(allocator, masm);
650
651 allocator.discardStack(masm);
652
653 AutoStubFrame stubFrame(*this);
654 stubFrame.enter(masm, scratch);
655
656 // Load the callee in the scratch register.
657 masm.loadPtr(getterAddr, scratch);
658
659 masm.Push(receiver);
660 masm.Push(scratch);
661
662 using Fn =
663 bool (*)(JSContext*, HandleFunction, HandleValue, MutableHandleValue);
664 callVM<Fn, CallNativeGetter>(masm);
665
666 stubFrame.leave(masm);
667 return true;
668 }
669
670 bool BaselineCacheIRCompiler::emitCallDOMGetterResult(ObjOperandId objId,
671 uint32_t jitInfoOffset) {
672 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
673
674 Register obj = allocator.useRegister(masm, objId);
675 Address jitInfoAddr(stubAddress(jitInfoOffset));
676
677 AutoScratchRegister scratch(allocator, masm);
678
679 allocator.discardStack(masm);
680
681 AutoStubFrame stubFrame(*this);
682 stubFrame.enter(masm, scratch);
683
684 // Load the JSJitInfo in the scratch register.
685 masm.loadPtr(jitInfoAddr, scratch);
686
687 masm.Push(obj);
688 masm.Push(scratch);
689
690 using Fn =
691 bool (*)(JSContext*, const JSJitInfo*, HandleObject, MutableHandleValue);
692 callVM<Fn, CallDOMGetter>(masm);
693
694 stubFrame.leave(masm);
695 return true;
696 }
697
698 bool BaselineCacheIRCompiler::emitProxyGetResult(ObjOperandId objId,
699 uint32_t idOffset) {
700 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
701 Register obj = allocator.useRegister(masm, objId);
702 Address idAddr(stubAddress(idOffset));
703
704 AutoScratchRegister scratch(allocator, masm);
705
706 allocator.discardStack(masm);
707
708 AutoStubFrame stubFrame(*this);
709 stubFrame.enter(masm, scratch);
710
711 // Load the jsid in the scratch register.
712 masm.loadPtr(idAddr, scratch);
713
714 masm.Push(scratch);
715 masm.Push(obj);
716
717 using Fn = bool (*)(JSContext*, HandleObject, HandleId, MutableHandleValue);
718 callVM<Fn, ProxyGetProperty>(masm);
719
720 stubFrame.leave(masm);
721 return true;
722 }
723
724 bool BaselineCacheIRCompiler::emitFrameIsConstructingResult() {
725 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
726
727 AutoOutputRegister output(*this);
728 Register outputScratch = output.valueReg().scratchReg();
729
730 // Load the CalleeToken.
731 Address tokenAddr(baselineFrameReg(), JitFrameLayout::offsetOfCalleeToken());
732 masm.loadPtr(tokenAddr, outputScratch);
733
734 // The low bit indicates whether this call is constructing, just clear the
735 // other bits.
736 static_assert(CalleeToken_Function == 0x0);
737 static_assert(CalleeToken_FunctionConstructing == 0x1);
738 masm.andPtr(Imm32(0x1), outputScratch);
739
740 masm.tagValue(JSVAL_TYPE_BOOLEAN, outputScratch, output.valueReg());
741 return true;
742 }
743
744 bool BaselineCacheIRCompiler::emitLoadConstantStringResult(uint32_t strOffset) {
745 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
746 AutoOutputRegister output(*this);
747 AutoScratchRegisterMaybeOutput scratch(allocator, masm, output);
748
749 masm.loadPtr(stubAddress(strOffset), scratch);
750 masm.tagValue(JSVAL_TYPE_STRING, scratch, output.valueReg());
751 return true;
752 }
753
754 bool BaselineCacheIRCompiler::emitCompareStringResult(JSOp op,
755 StringOperandId lhsId,
756 StringOperandId rhsId) {
757 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
758 AutoOutputRegister output(*this);
759
760 Register left = allocator.useRegister(masm, lhsId);
761 Register right = allocator.useRegister(masm, rhsId);
762
763 AutoScratchRegisterMaybeOutput scratch(allocator, masm, output);
764
765 allocator.discardStack(masm);
766
767 Label slow, done;
768 masm.compareStrings(op, left, right, scratch, &slow);
769 masm.jump(&done);
770 masm.bind(&slow);
771 {
772 AutoStubFrame stubFrame(*this);
773 stubFrame.enter(masm, scratch);
774
775 // Push the operands in reverse order for JSOp::Le and JSOp::Gt:
776 // - |left <= right| is implemented as |right >= left|.
777 // - |left > right| is implemented as |right < left|.
778 if (op == JSOp::Le || op == JSOp::Gt) {
779 masm.Push(left);
780 masm.Push(right);
781 } else {
782 masm.Push(right);
783 masm.Push(left);
784 }
785
786 using Fn = bool (*)(JSContext*, HandleString, HandleString, bool*);
787 if (op == JSOp::Eq || op == JSOp::StrictEq) {
788 callVM<Fn, jit::StringsEqual<EqualityKind::Equal>>(masm);
789 } else if (op == JSOp::Ne || op == JSOp::StrictNe) {
790 callVM<Fn, jit::StringsEqual<EqualityKind::NotEqual>>(masm);
791 } else if (op == JSOp::Lt || op == JSOp::Gt) {
792 callVM<Fn, jit::StringsCompare<ComparisonKind::LessThan>>(masm);
793 } else {
794 MOZ_ASSERT(op == JSOp::Le || op == JSOp::Ge);
795 callVM<Fn, jit::StringsCompare<ComparisonKind::GreaterThanOrEqual>>(masm);
796 }
797
798 stubFrame.leave(masm);
799 masm.storeCallPointerResult(scratch);
800 }
801 masm.bind(&done);
802 masm.tagValue(JSVAL_TYPE_BOOLEAN, scratch, output.valueReg());
803 return true;
804 }
805
806 bool BaselineCacheIRCompiler::emitSameValueResult(ValOperandId lhsId,
807 ValOperandId rhsId) {
808 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
809
810 AutoOutputRegister output(*this);
811 AutoScratchRegister scratch(allocator, masm);
812 ValueOperand lhs = allocator.useValueRegister(masm, lhsId);
813 #ifdef JS_CODEGEN_X86
814 // Use the output to avoid running out of registers.
815 allocator.copyToScratchValueRegister(masm, rhsId, output.valueReg());
816 ValueOperand rhs = output.valueReg();
817 #else
818 ValueOperand rhs = allocator.useValueRegister(masm, rhsId);
819 #endif
820
821 allocator.discardStack(masm);
822
823 Label done;
824 Label call;
825
826 // Check to see if the values have identical bits.
827 // This is correct for SameValue because SameValue(NaN,NaN) is true,
828 // and SameValue(0,-0) is false.
829 masm.branch64(Assembler::NotEqual, lhs.toRegister64(), rhs.toRegister64(),
830 &call);
831 masm.moveValue(BooleanValue(true), output.valueReg());
832 masm.jump(&done);
833
834 {
835 masm.bind(&call);
836
837 AutoStubFrame stubFrame(*this);
838 stubFrame.enter(masm, scratch);
839
840 masm.pushValue(lhs);
841 masm.pushValue(rhs);
842
843 using Fn = bool (*)(JSContext*, HandleValue, HandleValue, bool*);
844 callVM<Fn, SameValue>(masm);
845
846 stubFrame.leave(masm);
847 masm.tagValue(JSVAL_TYPE_BOOLEAN, ReturnReg, output.valueReg());
848 }
849
850 masm.bind(&done);
851 return true;
852 }
853
854 bool BaselineCacheIRCompiler::emitStoreSlotShared(bool isFixed,
855 ObjOperandId objId,
856 uint32_t offsetOffset,
857 ValOperandId rhsId) {
858 Register obj = allocator.useRegister(masm, objId);
859 ValueOperand val = allocator.useValueRegister(masm, rhsId);
860
861 AutoScratchRegister scratch1(allocator, masm);
862 Maybe<AutoScratchRegister> scratch2;
863 if (!isFixed) {
864 scratch2.emplace(allocator, masm);
865 }
866
867 Address offsetAddr = stubAddress(offsetOffset);
868 masm.load32(offsetAddr, scratch1);
869
870 if (isFixed) {
871 BaseIndex slot(obj, scratch1, TimesOne);
872 EmitPreBarrier(masm, slot, MIRType::Value);
873 masm.storeValue(val, slot);
874 } else {
875 masm.loadPtr(Address(obj, NativeObject::offsetOfSlots()), scratch2.ref());
876 BaseIndex slot(scratch2.ref(), scratch1, TimesOne);
877 EmitPreBarrier(masm, slot, MIRType::Value);
878 masm.storeValue(val, slot);
879 }
880
881 emitPostBarrierSlot(obj, val, scratch1);
882 return true;
883 }
884
885 bool BaselineCacheIRCompiler::emitStoreFixedSlot(ObjOperandId objId,
886 uint32_t offsetOffset,
887 ValOperandId rhsId) {
888 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
889 return emitStoreSlotShared(true, objId, offsetOffset, rhsId);
890 }
891
892 bool BaselineCacheIRCompiler::emitStoreDynamicSlot(ObjOperandId objId,
893 uint32_t offsetOffset,
894 ValOperandId rhsId) {
895 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
896 return emitStoreSlotShared(false, objId, offsetOffset, rhsId);
897 }
898
899 bool BaselineCacheIRCompiler::emitAddAndStoreSlotShared(
900 CacheOp op, ObjOperandId objId, uint32_t offsetOffset, ValOperandId rhsId,
901 uint32_t newShapeOffset, Maybe<uint32_t> numNewSlotsOffset) {
902 Register obj = allocator.useRegister(masm, objId);
903 ValueOperand val = allocator.useValueRegister(masm, rhsId);
904
905 AutoScratchRegister scratch1(allocator, masm);
906 AutoScratchRegister scratch2(allocator, masm);
907
908 Address newShapeAddr = stubAddress(newShapeOffset);
909 Address offsetAddr = stubAddress(offsetOffset);
910
911 if (op == CacheOp::AllocateAndStoreDynamicSlot) {
912 // We have to (re)allocate dynamic slots. Do this first, as it's the
913 // only fallible operation here. Note that growSlotsPure is fallible but
914 // does not GC.
915 Address numNewSlotsAddr = stubAddress(*numNewSlotsOffset);
916
917 FailurePath* failure;
918 if (!addFailurePath(&failure)) {
919 return false;
920 }
921
922 LiveRegisterSet save = liveVolatileRegs();
923 masm.PushRegsInMask(save);
924
925 using Fn = bool (*)(JSContext* cx, NativeObject* obj, uint32_t newCount);
926 masm.setupUnalignedABICall(scratch1);
927 masm.loadJSContext(scratch1);
928 masm.passABIArg(scratch1);
929 masm.passABIArg(obj);
930 masm.load32(numNewSlotsAddr, scratch2);
931 masm.passABIArg(scratch2);
932 masm.callWithABI<Fn, NativeObject::growSlotsPure>();
933 masm.storeCallPointerResult(scratch1);
934
935 LiveRegisterSet ignore;
936 ignore.add(scratch1);
937 masm.PopRegsInMaskIgnore(save, ignore);
938
939 masm.branchIfFalseBool(scratch1, failure->label());
940 }
941
942 // Update the object's shape.
943 masm.loadPtr(newShapeAddr, scratch1);
944 masm.storeObjShape(scratch1, obj,
945 [](MacroAssembler& masm, const Address& addr) {
946 EmitPreBarrier(masm, addr, MIRType::Shape);
947 });
948
949 // Perform the store. No pre-barrier required since this is a new
950 // initialization.
951 masm.load32(offsetAddr, scratch1);
952 if (op == CacheOp::AddAndStoreFixedSlot) {
953 BaseIndex slot(obj, scratch1, TimesOne);
954 masm.storeValue(val, slot);
955 } else {
956 MOZ_ASSERT(op == CacheOp::AddAndStoreDynamicSlot ||
957 op == CacheOp::AllocateAndStoreDynamicSlot);
958 masm.loadPtr(Address(obj, NativeObject::offsetOfSlots()), scratch2);
959 BaseIndex slot(scratch2, scratch1, TimesOne);
960 masm.storeValue(val, slot);
961 }
962
963 emitPostBarrierSlot(obj, val, scratch1);
964 return true;
965 }
966
967 bool BaselineCacheIRCompiler::emitAddAndStoreFixedSlot(
968 ObjOperandId objId, uint32_t offsetOffset, ValOperandId rhsId,
969 uint32_t newShapeOffset) {
970 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
971 Maybe<uint32_t> numNewSlotsOffset = mozilla::Nothing();
972 return emitAddAndStoreSlotShared(CacheOp::AddAndStoreFixedSlot, objId,
973 offsetOffset, rhsId, newShapeOffset,
974 numNewSlotsOffset);
975 }
976
977 bool BaselineCacheIRCompiler::emitAddAndStoreDynamicSlot(
978 ObjOperandId objId, uint32_t offsetOffset, ValOperandId rhsId,
979 uint32_t newShapeOffset) {
980 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
981 Maybe<uint32_t> numNewSlotsOffset = mozilla::Nothing();
982 return emitAddAndStoreSlotShared(CacheOp::AddAndStoreDynamicSlot, objId,
983 offsetOffset, rhsId, newShapeOffset,
984 numNewSlotsOffset);
985 }
986
987 bool BaselineCacheIRCompiler::emitAllocateAndStoreDynamicSlot(
988 ObjOperandId objId, uint32_t offsetOffset, ValOperandId rhsId,
989 uint32_t newShapeOffset, uint32_t numNewSlotsOffset) {
990 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
991 return emitAddAndStoreSlotShared(CacheOp::AllocateAndStoreDynamicSlot, objId,
992 offsetOffset, rhsId, newShapeOffset,
993 mozilla::Some(numNewSlotsOffset));
994 }
995
996 bool BaselineCacheIRCompiler::emitArrayJoinResult(ObjOperandId objId,
997 StringOperandId sepId) {
998 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
999
1000 AutoOutputRegister output(*this);
1001 Register obj = allocator.useRegister(masm, objId);
1002 Register sep = allocator.useRegister(masm, sepId);
1003 AutoScratchRegisterMaybeOutput scratch(allocator, masm, output);
1004
1005 allocator.discardStack(masm);
1006
1007 // Load obj->elements in scratch.
1008 masm.loadPtr(Address(obj, NativeObject::offsetOfElements()), scratch);
1009 Address lengthAddr(scratch, ObjectElements::offsetOfLength());
1010
1011 // If array length is 0, return empty string.
1012 Label finished;
1013
1014 {
1015 Label arrayNotEmpty;
1016 masm.branch32(Assembler::NotEqual, lengthAddr, Imm32(0), &arrayNotEmpty);
1017 masm.movePtr(ImmGCPtr(cx_->names().empty_), scratch);
1018 masm.tagValue(JSVAL_TYPE_STRING, scratch, output.valueReg());
1019 masm.jump(&finished);
1020 masm.bind(&arrayNotEmpty);
1021 }
1022
1023 Label vmCall;
1024
1025 // Otherwise, handle array length 1 case.
1026 masm.branch32(Assembler::NotEqual, lengthAddr, Imm32(1), &vmCall);
1027
1028 // But only if initializedLength is also 1.
1029 Address initLength(scratch, ObjectElements::offsetOfInitializedLength());
1030 masm.branch32(Assembler::NotEqual, initLength, Imm32(1), &vmCall);
1031
1032 // And only if elem0 is a string.
1033 Address elementAddr(scratch, 0);
1034 masm.branchTestString(Assembler::NotEqual, elementAddr, &vmCall);
1035
1036 // Store the value.
1037 masm.loadValue(elementAddr, output.valueReg());
1038 masm.jump(&finished);
1039
1040 // Otherwise call into the VM.
1041 {
1042 masm.bind(&vmCall);
1043
1044 AutoStubFrame stubFrame(*this);
1045 stubFrame.enter(masm, scratch);
1046
1047 masm.Push(sep);
1048 masm.Push(obj);
1049
1050 using Fn = JSString* (*)(JSContext*, HandleObject, HandleString);
1051 callVM<Fn, jit::ArrayJoin>(masm);
1052
1053 stubFrame.leave(masm);
1054
1055 masm.tagValue(JSVAL_TYPE_STRING, ReturnReg, output.valueReg());
1056 }
1057
1058 masm.bind(&finished);
1059
1060 return true;
1061 }
1062
1063 bool BaselineCacheIRCompiler::emitPackedArraySliceResult(
1064 uint32_t templateObjectOffset, ObjOperandId arrayId, Int32OperandId beginId,
1065 Int32OperandId endId) {
1066 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1067
1068 AutoOutputRegister output(*this);
1069 AutoScratchRegisterMaybeOutput scratch1(allocator, masm, output);
1070 AutoScratchRegisterMaybeOutputType scratch2(allocator, masm, output);
1071
1072 Register array = allocator.useRegister(masm, arrayId);
1073 Register begin = allocator.useRegister(masm, beginId);
1074 Register end = allocator.useRegister(masm, endId);
1075
1076 FailurePath* failure;
1077 if (!addFailurePath(&failure)) {
1078 return false;
1079 }
1080
1081 masm.branchArrayIsNotPacked(array, scratch1, scratch2, failure->label());
1082
1083 allocator.discardStack(masm);
1084
1085 AutoStubFrame stubFrame(*this);
1086 stubFrame.enter(masm, scratch1);
1087
1088 // Don't attempt to pre-allocate the object, instead always use the slow
1089 // path.
1090 ImmPtr result(nullptr);
1091
1092 masm.Push(result);
1093 masm.Push(end);
1094 masm.Push(begin);
1095 masm.Push(array);
1096
1097 using Fn =
1098 JSObject* (*)(JSContext*, HandleObject, int32_t, int32_t, HandleObject);
1099 callVM<Fn, ArraySliceDense>(masm);
1100
1101 stubFrame.leave(masm);
1102
1103 masm.tagValue(JSVAL_TYPE_OBJECT, ReturnReg, output.valueReg());
1104 return true;
1105 }
1106
1107 bool BaselineCacheIRCompiler::emitArgumentsSliceResult(
1108 uint32_t templateObjectOffset, ObjOperandId argsId, Int32OperandId beginId,
1109 Int32OperandId endId) {
1110 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1111
1112 AutoOutputRegister output(*this);
1113 AutoScratchRegisterMaybeOutput scratch(allocator, masm, output);
1114
1115 Register args = allocator.useRegister(masm, argsId);
1116 Register begin = allocator.useRegister(masm, beginId);
1117 Register end = allocator.useRegister(masm, endId);
1118
1119 allocator.discardStack(masm);
1120
1121 AutoStubFrame stubFrame(*this);
1122 stubFrame.enter(masm, scratch);
1123
1124 // Don't attempt to pre-allocate the object, instead always use the slow path.
1125 ImmPtr result(nullptr);
1126
1127 masm.Push(result);
1128 masm.Push(end);
1129 masm.Push(begin);
1130 masm.Push(args);
1131
1132 using Fn =
1133 JSObject* (*)(JSContext*, HandleObject, int32_t, int32_t, HandleObject);
1134 callVM<Fn, ArgumentsSliceDense>(masm);
1135
1136 stubFrame.leave(masm);
1137
1138 masm.tagValue(JSVAL_TYPE_OBJECT, ReturnReg, output.valueReg());
1139 return true;
1140 }
1141
1142 bool BaselineCacheIRCompiler::emitIsArrayResult(ValOperandId inputId) {
1143 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1144
1145 AutoOutputRegister output(*this);
1146 AutoScratchRegister scratch1(allocator, masm);
1147 AutoScratchRegisterMaybeOutput scratch2(allocator, masm, output);
1148
1149 ValueOperand val = allocator.useValueRegister(masm, inputId);
1150
1151 allocator.discardStack(masm);
1152
1153 Label isNotArray;
1154 // Primitives are never Arrays.
1155 masm.fallibleUnboxObject(val, scratch1, &isNotArray);
1156
1157 Label isArray;
1158 masm.branchTestObjClass(Assembler::Equal, scratch1, &ArrayObject::class_,
1159 scratch2, scratch1, &isArray);
1160
1161 // isArray can also return true for Proxy wrapped Arrays.
1162 masm.branchTestObjectIsProxy(false, scratch1, scratch2, &isNotArray);
1163 Label done;
1164 {
1165 AutoStubFrame stubFrame(*this);
1166 stubFrame.enter(masm, scratch2);
1167
1168 masm.Push(scratch1);
1169
1170 using Fn = bool (*)(JSContext*, HandleObject, bool*);
1171 callVM<Fn, js::IsArrayFromJit>(masm);
1172
1173 stubFrame.leave(masm);
1174
1175 masm.tagValue(JSVAL_TYPE_BOOLEAN, ReturnReg, output.valueReg());
1176 masm.jump(&done);
1177 }
1178
1179 masm.bind(&isNotArray);
1180 masm.moveValue(BooleanValue(false), output.valueReg());
1181 masm.jump(&done);
1182
1183 masm.bind(&isArray);
1184 masm.moveValue(BooleanValue(true), output.valueReg());
1185
1186 masm.bind(&done);
1187 return true;
1188 }
1189
1190 bool BaselineCacheIRCompiler::emitIsTypedArrayResult(ObjOperandId objId,
1191 bool isPossiblyWrapped) {
1192 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1193
1194 AutoOutputRegister output(*this);
1195 AutoScratchRegisterMaybeOutput scratch(allocator, masm, output);
1196 Register obj = allocator.useRegister(masm, objId);
1197
1198 allocator.discardStack(masm);
1199
1200 Label notTypedArray, isWrapper, done;
1201 masm.loadObjClassUnsafe(obj, scratch);
1202 masm.branchIfClassIsNotTypedArray(scratch, &notTypedArray);
1203 masm.moveValue(BooleanValue(true), output.valueReg());
1204 masm.jump(&done);
1205
1206 masm.bind(&notTypedArray);
1207 if (isPossiblyWrapped) {
1208 Label notProxy;
1209 masm.branchTestClassIsProxy(false, scratch, &notProxy);
1210 masm.branchTestProxyHandlerFamily(Assembler::Equal, obj, scratch,
1211 &Wrapper::family, &isWrapper);
1212 masm.bind(&notProxy);
1213 }
1214 masm.moveValue(BooleanValue(false), output.valueReg());
1215
1216 if (isPossiblyWrapped) {
1217 masm.jump(&done);
1218
1219 masm.bind(&isWrapper);
1220
1221 AutoStubFrame stubFrame(*this);
1222 stubFrame.enter(masm, scratch);
1223
1224 masm.Push(obj);
1225
1226 using Fn = bool (*)(JSContext*, JSObject*, bool*);
1227 callVM<Fn, jit::IsPossiblyWrappedTypedArray>(masm);
1228
1229 stubFrame.leave(masm);
1230
1231 masm.tagValue(JSVAL_TYPE_BOOLEAN, ReturnReg, output.valueReg());
1232 }
1233
1234 masm.bind(&done);
1235 return true;
1236 }
1237
1238 bool BaselineCacheIRCompiler::emitLoadStringCharResult(
1239 StringOperandId strId, Int32OperandId indexId,
1240 StringCharOutOfBounds outOfBounds) {
1241 AutoOutputRegister output(*this);
1242 Register str = allocator.useRegister(masm, strId);
1243 Register index = allocator.useRegister(masm, indexId);
1244 AutoScratchRegisterMaybeOutput scratch1(allocator, masm, output);
1245 AutoScratchRegisterMaybeOutputType scratch2(allocator, masm, output);
1246 AutoScratchRegister scratch3(allocator, masm);
1247
1248 // Bounds check, load string char.
1249 Label done;
1250 Label tagResult;
1251 Label loadFailed;
1252 if (outOfBounds == StringCharOutOfBounds::Failure) {
1253 FailurePath* failure;
1254 if (!addFailurePath(&failure)) {
1255 return false;
1256 }
1257
1258 masm.spectreBoundsCheck32(index, Address(str, JSString::offsetOfLength()),
1259 scratch3, failure->label());
1260 masm.loadStringChar(str, index, scratch2, scratch1, scratch3,
1261 failure->label());
1262
1263 allocator.discardStack(masm);
1264 } else {
1265 // Discard the stack before jumping to |done|.
1266 allocator.discardStack(masm);
1267
1268 if (outOfBounds == StringCharOutOfBounds::EmptyString) {
1269 // Return the empty string for out-of-bounds access.
1270 masm.movePtr(ImmGCPtr(cx_->names().empty_), scratch1);
1271 } else {
1272 // Return |undefined| for out-of-bounds access.
1273 masm.moveValue(UndefinedValue(), output.valueReg());
1274 }
1275
1276 // This CacheIR op is always preceded by |LinearizeForCharAccess|, so we're
1277 // guaranteed to see no nested ropes.
1278 masm.spectreBoundsCheck32(index, Address(str, JSString::offsetOfLength()),
1279 scratch3, &done);
1280 masm.loadStringChar(str, index, scratch2, scratch1, scratch3, &loadFailed);
1281 }
1282
1283 // Load StaticString for this char. For larger code units perform a VM call.
1284 Label vmCall;
1285 masm.lookupStaticString(scratch2, scratch1, cx_->staticStrings(), &vmCall);
1286 masm.jump(&tagResult);
1287
1288 if (outOfBounds != StringCharOutOfBounds::Failure) {
1289 masm.bind(&loadFailed);
1290 masm.assumeUnreachable("loadStringChar can't fail for linear strings");
1291 }
1292
1293 {
1294 masm.bind(&vmCall);
1295
1296 AutoStubFrame stubFrame(*this);
1297 stubFrame.enter(masm, scratch3);
1298
1299 masm.Push(scratch2);
1300
1301 using Fn = JSLinearString* (*)(JSContext*, int32_t);
1302 callVM<Fn, js::StringFromCharCode>(masm);
1303
1304 stubFrame.leave(masm);
1305
1306 masm.storeCallPointerResult(scratch1);
1307 }
1308
1309 if (outOfBounds != StringCharOutOfBounds::UndefinedValue) {
1310 masm.bind(&tagResult);
1311 masm.bind(&done);
1312 masm.tagValue(JSVAL_TYPE_STRING, scratch1, output.valueReg());
1313 } else {
1314 masm.bind(&tagResult);
1315 masm.tagValue(JSVAL_TYPE_STRING, scratch1, output.valueReg());
1316 masm.bind(&done);
1317 }
1318 return true;
1319 }
1320
1321 bool BaselineCacheIRCompiler::emitLoadStringCharResult(StringOperandId strId,
1322 Int32OperandId indexId,
1323 bool handleOOB) {
1324 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1325 auto outOfBounds = handleOOB ? StringCharOutOfBounds::EmptyString
1326 : StringCharOutOfBounds::Failure;
1327 return emitLoadStringCharResult(strId, indexId, outOfBounds);
1328 }
1329
1330 bool BaselineCacheIRCompiler::emitLoadStringAtResult(StringOperandId strId,
1331 Int32OperandId indexId,
1332 bool handleOOB) {
1333 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1334 auto outOfBounds = handleOOB ? StringCharOutOfBounds::UndefinedValue
1335 : StringCharOutOfBounds::Failure;
1336 return emitLoadStringCharResult(strId, indexId, outOfBounds);
1337 }
1338
1339 bool BaselineCacheIRCompiler::emitStringFromCodeResult(Int32OperandId codeId,
1340 StringCode stringCode) {
1341 AutoOutputRegister output(*this);
1342 AutoScratchRegisterMaybeOutput scratch(allocator, masm, output);
1343
1344 Register code = allocator.useRegister(masm, codeId);
1345
1346 FailurePath* failure = nullptr;
1347 if (stringCode == StringCode::CodePoint) {
1348 if (!addFailurePath(&failure)) {
1349 return false;
1350 }
1351 }
1352
1353 if (stringCode == StringCode::CodePoint) {
1354 // Note: This condition must match tryAttachStringFromCodePoint to prevent
1355 // failure loops.
1356 masm.branch32(Assembler::Above, code, Imm32(unicode::NonBMPMax),
1357 failure->label());
1358 }
1359
1360 allocator.discardStack(masm);
1361
1362 // We pre-allocate atoms for the first UNIT_STATIC_LIMIT characters.
1363 // For code units larger than that, we must do a VM call.
1364 Label vmCall;
1365 masm.lookupStaticString(code, scratch, cx_->staticStrings(), &vmCall);
1366
1367 Label done;
1368 masm.jump(&done);
1369
1370 {
1371 masm.bind(&vmCall);
1372
1373 AutoStubFrame stubFrame(*this);
1374 stubFrame.enter(masm, scratch);
1375
1376 masm.Push(code);
1377
1378 if (stringCode == StringCode::CodeUnit) {
1379 using Fn = JSLinearString* (*)(JSContext*, int32_t);
1380 callVM<Fn, js::StringFromCharCode>(masm);
1381 } else {
1382 using Fn = JSLinearString* (*)(JSContext*, char32_t);
1383 callVM<Fn, js::StringFromCodePoint>(masm);
1384 }
1385
1386 stubFrame.leave(masm);
1387 masm.storeCallPointerResult(scratch);
1388 }
1389
1390 masm.bind(&done);
1391 masm.tagValue(JSVAL_TYPE_STRING, scratch, output.valueReg());
1392 return true;
1393 }
1394
1395 bool BaselineCacheIRCompiler::emitStringFromCharCodeResult(
1396 Int32OperandId codeId) {
1397 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1398
1399 return emitStringFromCodeResult(codeId, StringCode::CodeUnit);
1400 }
1401
1402 bool BaselineCacheIRCompiler::emitStringFromCodePointResult(
1403 Int32OperandId codeId) {
1404 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1405
1406 return emitStringFromCodeResult(codeId, StringCode::CodePoint);
1407 }
1408
1409 bool BaselineCacheIRCompiler::emitMathRandomResult(uint32_t rngOffset) {
1410 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1411
1412 AutoOutputRegister output(*this);
1413 AutoScratchRegister scratch1(allocator, masm);
1414 AutoScratchRegister64 scratch2(allocator, masm);
1415 AutoAvailableFloatRegister scratchFloat(*this, FloatReg0);
1416
1417 Address rngAddr(stubAddress(rngOffset));
1418 masm.loadPtr(rngAddr, scratch1);
1419
1420 masm.randomDouble(scratch1, scratchFloat, scratch2,
1421 output.valueReg().toRegister64());
1422
1423 if (js::SupportDifferentialTesting()) {
1424 masm.loadConstantDouble(0.0, scratchFloat);
1425 }
1426
1427 masm.boxDouble(scratchFloat, output.valueReg(), scratchFloat);
1428 return true;
1429 }
1430
1431 bool BaselineCacheIRCompiler::emitReflectGetPrototypeOfResult(
1432 ObjOperandId objId) {
1433 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1434
1435 AutoOutputRegister output(*this);
1436 AutoScratchRegisterMaybeOutput scratch(allocator, masm, output);
1437
1438 Register obj = allocator.useRegister(masm, objId);
1439
1440 allocator.discardStack(masm);
1441
1442 MOZ_ASSERT(uintptr_t(TaggedProto::LazyProto) == 1);
1443
1444 masm.loadObjProto(obj, scratch);
1445
1446 Label hasProto;
1447 masm.branchPtr(Assembler::Above, scratch, ImmWord(1), &hasProto);
1448
1449 // Call into the VM for lazy prototypes.
1450 Label slow, done;
1451 masm.branchPtr(Assembler::Equal, scratch, ImmWord(1), &slow);
1452
1453 masm.moveValue(NullValue(), output.valueReg());
1454 masm.jump(&done);
1455
1456 masm.bind(&hasProto);
1457 masm.tagValue(JSVAL_TYPE_OBJECT, scratch, output.valueReg());
1458 masm.jump(&done);
1459
1460 {
1461 masm.bind(&slow);
1462
1463 AutoStubFrame stubFrame(*this);
1464 stubFrame.enter(masm, scratch);
1465
1466 masm.Push(obj);
1467
1468 using Fn = bool (*)(JSContext*, HandleObject, MutableHandleValue);
1469 callVM<Fn, jit::GetPrototypeOf>(masm);
1470
1471 stubFrame.leave(masm);
1472 }
1473
1474 masm.bind(&done);
1475 return true;
1476 }
1477
1478 bool BaselineCacheIRCompiler::emitHasClassResult(ObjOperandId objId,
1479 uint32_t claspOffset) {
1480 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1481
1482 AutoOutputRegister output(*this);
1483 Register obj = allocator.useRegister(masm, objId);
1484 AutoScratchRegisterMaybeOutput scratch(allocator, masm, output);
1485
1486 Address claspAddr(stubAddress(claspOffset));
1487 masm.loadObjClassUnsafe(obj, scratch);
1488 masm.cmpPtrSet(Assembler::Equal, claspAddr, scratch.get(), scratch);
1489 masm.tagValue(JSVAL_TYPE_BOOLEAN, scratch, output.valueReg());
1490 return true;
1491 }
1492
1493 bool BaselineCacheIRCompiler::emitHasShapeResult(ObjOperandId objId,
1494 uint32_t shapeOffset) {
1495 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1496
1497 AutoOutputRegister output(*this);
1498 Register obj = allocator.useRegister(masm, objId);
1499 AutoScratchRegisterMaybeOutput scratch(allocator, masm, output);
1500
1501 // Note: no Spectre mitigations are needed here because this shape check only
1502 // affects correctness.
1503 Address shapeAddr(stubAddress(shapeOffset));
1504 masm.loadObjShapeUnsafe(obj, scratch);
1505 masm.cmpPtrSet(Assembler::Equal, shapeAddr, scratch.get(), scratch);
1506 masm.tagValue(JSVAL_TYPE_BOOLEAN, scratch, output.valueReg());
1507 return true;
1508 }
1509
1510 void BaselineCacheIRCompiler::emitAtomizeString(Register str, Register temp,
1511 Label* failure) {
1512 Label isAtom, notCachedAtom;
1513 masm.branchTest32(Assembler::NonZero, Address(str, JSString::offsetOfFlags()),
1514 Imm32(JSString::ATOM_BIT), &isAtom);
1515 masm.tryFastAtomize(str, temp, str, &notCachedAtom);
1516 masm.jump(&isAtom);
1517 masm.bind(&notCachedAtom);
1518
1519 {
1520 LiveRegisterSet save = liveVolatileRegs();
1521 masm.PushRegsInMask(save);
1522
1523 using Fn = JSAtom* (*)(JSContext* cx, JSString* str);
1524 masm.setupUnalignedABICall(temp);
1525 masm.loadJSContext(temp);
1526 masm.passABIArg(temp);
1527 masm.passABIArg(str);
1528 masm.callWithABI<Fn, jit::AtomizeStringNoGC>();
1529 masm.storeCallPointerResult(temp);
1530
1531 LiveRegisterSet ignore;
1532 ignore.add(temp);
1533 masm.PopRegsInMaskIgnore(save, ignore);
1534
1535 masm.branchPtr(Assembler::Equal, temp, ImmWord(0), failure);
1536 masm.mov(temp, str);
1537 }
1538 masm.bind(&isAtom);
1539 }
1540
1541 bool BaselineCacheIRCompiler::emitSetHasStringResult(ObjOperandId setId,
1542 StringOperandId strId) {
1543 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1544
1545 AutoOutputRegister output(*this);
1546 Register set = allocator.useRegister(masm, setId);
1547 Register str = allocator.useRegister(masm, strId);
1548
1549 AutoScratchRegister scratch1(allocator, masm);
1550 AutoScratchRegister scratch2(allocator, masm);
1551 AutoScratchRegister scratch3(allocator, masm);
1552 AutoScratchRegister scratch4(allocator, masm);
1553
1554 FailurePath* failure;
1555 if (!addFailurePath(&failure)) {
1556 return false;
1557 }
1558
1559 emitAtomizeString(str, scratch1, failure->label());
1560 masm.prepareHashString(str, scratch1, scratch2);
1561
1562 masm.tagValue(JSVAL_TYPE_STRING, str, output.valueReg());
1563 masm.setObjectHasNonBigInt(set, output.valueReg(), scratch1, scratch2,
1564 scratch3, scratch4);
1565 masm.tagValue(JSVAL_TYPE_BOOLEAN, scratch2, output.valueReg());
1566 return true;
1567 }
1568
1569 bool BaselineCacheIRCompiler::emitMapHasStringResult(ObjOperandId mapId,
1570 StringOperandId strId) {
1571 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1572
1573 AutoOutputRegister output(*this);
1574 Register map = allocator.useRegister(masm, mapId);
1575 Register str = allocator.useRegister(masm, strId);
1576
1577 AutoScratchRegister scratch1(allocator, masm);
1578 AutoScratchRegister scratch2(allocator, masm);
1579 AutoScratchRegister scratch3(allocator, masm);
1580 AutoScratchRegister scratch4(allocator, masm);
1581
1582 FailurePath* failure;
1583 if (!addFailurePath(&failure)) {
1584 return false;
1585 }
1586
1587 emitAtomizeString(str, scratch1, failure->label());
1588 masm.prepareHashString(str, scratch1, scratch2);
1589
1590 masm.tagValue(JSVAL_TYPE_STRING, str, output.valueReg());
1591 masm.mapObjectHasNonBigInt(map, output.valueReg(), scratch1, scratch2,
1592 scratch3, scratch4);
1593 masm.tagValue(JSVAL_TYPE_BOOLEAN, scratch2, output.valueReg());
1594 return true;
1595 }
1596
1597 bool BaselineCacheIRCompiler::emitMapGetStringResult(ObjOperandId mapId,
1598 StringOperandId strId) {
1599 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1600
1601 AutoOutputRegister output(*this);
1602 Register map = allocator.useRegister(masm, mapId);
1603 Register str = allocator.useRegister(masm, strId);
1604
1605 AutoScratchRegister scratch1(allocator, masm);
1606 AutoScratchRegister scratch2(allocator, masm);
1607 AutoScratchRegister scratch3(allocator, masm);
1608 AutoScratchRegister scratch4(allocator, masm);
1609
1610 FailurePath* failure;
1611 if (!addFailurePath(&failure)) {
1612 return false;
1613 }
1614
1615 emitAtomizeString(str, scratch1, failure->label());
1616 masm.prepareHashString(str, scratch1, scratch2);
1617
1618 masm.tagValue(JSVAL_TYPE_STRING, str, output.valueReg());
1619 masm.mapObjectGetNonBigInt(map, output.valueReg(), scratch1,
1620 output.valueReg(), scratch2, scratch3, scratch4);
1621 return true;
1622 }
1623
1624 bool BaselineCacheIRCompiler::emitCallNativeSetter(
1625 ObjOperandId receiverId, uint32_t setterOffset, ValOperandId rhsId,
1626 bool sameRealm, uint32_t nargsAndFlagsOffset) {
1627 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1628 Register receiver = allocator.useRegister(masm, receiverId);
1629 Address setterAddr(stubAddress(setterOffset));
1630 ValueOperand val = allocator.useValueRegister(masm, rhsId);
1631
1632 AutoScratchRegister scratch(allocator, masm);
1633
1634 allocator.discardStack(masm);
1635
1636 AutoStubFrame stubFrame(*this);
1637 stubFrame.enter(masm, scratch);
1638
1639 // Load the callee in the scratch register.
1640 masm.loadPtr(setterAddr, scratch);
1641
1642 masm.Push(val);
1643 masm.Push(receiver);
1644 masm.Push(scratch);
1645
1646 using Fn = bool (*)(JSContext*, HandleFunction, HandleObject, HandleValue);
1647 callVM<Fn, CallNativeSetter>(masm);
1648
1649 stubFrame.leave(masm);
1650 return true;
1651 }
1652
1653 bool BaselineCacheIRCompiler::emitCallScriptedSetterShared(
1654 ObjOperandId receiverId, uint32_t setterOffset, ValOperandId rhsId,
1655 bool sameRealm, uint32_t nargsAndFlagsOffset,
1656 Maybe<uint32_t> icScriptOffset) {
1657 AutoScratchRegister callee(allocator, masm);
1658 AutoScratchRegister scratch(allocator, masm);
1659 #if defined(JS_CODEGEN_X86)
1660 Register code = scratch;
1661 #else
1662 AutoScratchRegister code(allocator, masm);
1663 #endif
1664
1665 Register receiver = allocator.useRegister(masm, receiverId);
1666 Address setterAddr(stubAddress(setterOffset));
1667 ValueOperand val = allocator.useValueRegister(masm, rhsId);
1668
1669 bool isInlined = icScriptOffset.isSome();
1670
1671 // First, load the callee.
1672 masm.loadPtr(setterAddr, callee);
1673
1674 if (isInlined) {
1675 // If we are calling a trial-inlined setter, guard that the
1676 // target has a BaselineScript.
1677 FailurePath* failure;
1678 if (!addFailurePath(&failure)) {
1679 return false;
1680 }
1681 masm.loadBaselineJitCodeRaw(callee, code, failure->label());
1682 }
1683
1684 allocator.discardStack(masm);
1685
1686 AutoStubFrame stubFrame(*this);
1687 stubFrame.enter(masm, scratch);
1688
1689 if (!sameRealm) {
1690 masm.switchToObjectRealm(callee, scratch);
1691 }
1692
1693 // Align the stack such that the JitFrameLayout is aligned on
1694 // JitStackAlignment.
1695 masm.alignJitStackBasedOnNArgs(1, /*countIncludesThis = */ false);
1696
1697 // Setter is called with 1 argument, and |receiver| as thisv. Note that we use
1698 // Push, not push, so that callJit will align the stack properly on ARM.
1699 masm.Push(val);
1700 masm.Push(TypedOrValueRegister(MIRType::Object, AnyRegister(receiver)));
1701
1702 // Push callee.
1703 masm.Push(callee);
1704
1705 // Push frame descriptor.
1706 masm.PushFrameDescriptorForJitCall(FrameType::BaselineStub, /* argc = */ 1);
1707
1708 if (isInlined) {
1709 // Store icScript in the context.
1710 Address icScriptAddr(stubAddress(*icScriptOffset));
1711 masm.loadPtr(icScriptAddr, scratch);
1712 masm.storeICScriptInJSContext(scratch);
1713 }
1714
1715 // Load the jitcode pointer.
1716 if (isInlined) {
1717 // On non-x86 platforms, this pointer is still in a register
1718 // after guarding on it above. On x86, we don't have enough
1719 // registers and have to reload it here.
1720 #ifdef JS_CODEGEN_X86
1721 masm.loadBaselineJitCodeRaw(callee, code);
1722 #endif
1723 } else {
1724 masm.loadJitCodeRaw(callee, code);
1725 }
1726
1727 // Handle arguments underflow. The rhs value is no longer needed and
1728 // can be used as scratch.
1729 Label noUnderflow;
1730 Register scratch2 = val.scratchReg();
1731 masm.loadFunctionArgCount(callee, scratch2);
1732 masm.branch32(Assembler::BelowOrEqual, scratch2, Imm32(1), &noUnderflow);
1733
1734 // Call the arguments rectifier.
1735 ArgumentsRectifierKind kind = isInlined
1736 ? ArgumentsRectifierKind::TrialInlining
1737 : ArgumentsRectifierKind::Normal;
1738 TrampolinePtr argumentsRectifier =
1739 cx_->runtime()->jitRuntime()->getArgumentsRectifier(kind);
1740 masm.movePtr(argumentsRectifier, code);
1741
1742 masm.bind(&noUnderflow);
1743 masm.callJit(code);
1744
1745 stubFrame.leave(masm);
1746
1747 if (!sameRealm) {
1748 masm.switchToBaselineFrameRealm(R1.scratchReg());
1749 }
1750
1751 return true;
1752 }
1753
1754 bool BaselineCacheIRCompiler::emitCallScriptedSetter(
1755 ObjOperandId receiverId, uint32_t setterOffset, ValOperandId rhsId,
1756 bool sameRealm, uint32_t nargsAndFlagsOffset) {
1757 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1758 Maybe<uint32_t> icScriptOffset = mozilla::Nothing();
1759 return emitCallScriptedSetterShared(receiverId, setterOffset, rhsId,
1760 sameRealm, nargsAndFlagsOffset,
1761 icScriptOffset);
1762 }
1763
1764 bool BaselineCacheIRCompiler::emitCallInlinedSetter(
1765 ObjOperandId receiverId, uint32_t setterOffset, ValOperandId rhsId,
1766 uint32_t icScriptOffset, bool sameRealm, uint32_t nargsAndFlagsOffset) {
1767 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1768 return emitCallScriptedSetterShared(receiverId, setterOffset, rhsId,
1769 sameRealm, nargsAndFlagsOffset,
1770 mozilla::Some(icScriptOffset));
1771 }
1772
1773 bool BaselineCacheIRCompiler::emitCallDOMSetter(ObjOperandId objId,
1774 uint32_t jitInfoOffset,
1775 ValOperandId rhsId) {
1776 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1777 Register obj = allocator.useRegister(masm, objId);
1778 ValueOperand val = allocator.useValueRegister(masm, rhsId);
1779 Address jitInfoAddr(stubAddress(jitInfoOffset));
1780
1781 AutoScratchRegister scratch(allocator, masm);
1782
1783 allocator.discardStack(masm);
1784
1785 AutoStubFrame stubFrame(*this);
1786 stubFrame.enter(masm, scratch);
1787
1788 // Load the JSJitInfo in the scratch register.
1789 masm.loadPtr(jitInfoAddr, scratch);
1790
1791 masm.Push(val);
1792 masm.Push(obj);
1793 masm.Push(scratch);
1794
1795 using Fn = bool (*)(JSContext*, const JSJitInfo*, HandleObject, HandleValue);
1796 callVM<Fn, CallDOMSetter>(masm);
1797
1798 stubFrame.leave(masm);
1799 return true;
1800 }
1801
1802 bool BaselineCacheIRCompiler::emitCallSetArrayLength(ObjOperandId objId,
1803 bool strict,
1804 ValOperandId rhsId) {
1805 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1806 Register obj = allocator.useRegister(masm, objId);
1807 ValueOperand val = allocator.useValueRegister(masm, rhsId);
1808
1809 AutoScratchRegister scratch(allocator, masm);
1810
1811 allocator.discardStack(masm);
1812
1813 AutoStubFrame stubFrame(*this);
1814 stubFrame.enter(masm, scratch);
1815
1816 masm.Push(Imm32(strict));
1817 masm.Push(val);
1818 masm.Push(obj);
1819
1820 using Fn = bool (*)(JSContext*, HandleObject, HandleValue, bool);
1821 callVM<Fn, jit::SetArrayLength>(masm);
1822
1823 stubFrame.leave(masm);
1824 return true;
1825 }
1826
1827 bool BaselineCacheIRCompiler::emitProxySet(ObjOperandId objId,
1828 uint32_t idOffset,
1829 ValOperandId rhsId, bool strict) {
1830 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1831 Register obj = allocator.useRegister(masm, objId);
1832 ValueOperand val = allocator.useValueRegister(masm, rhsId);
1833 Address idAddr(stubAddress(idOffset));
1834
1835 AutoScratchRegister scratch(allocator, masm);
1836
1837 allocator.discardStack(masm);
1838
1839 AutoStubFrame stubFrame(*this);
1840 stubFrame.enter(masm, scratch);
1841
1842 // Load the jsid in the scratch register.
1843 masm.loadPtr(idAddr, scratch);
1844
1845 masm.Push(Imm32(strict));
1846 masm.Push(val);
1847 masm.Push(scratch);
1848 masm.Push(obj);
1849
1850 using Fn = bool (*)(JSContext*, HandleObject, HandleId, HandleValue, bool);
1851 callVM<Fn, ProxySetProperty>(masm);
1852
1853 stubFrame.leave(masm);
1854 return true;
1855 }
1856
1857 bool BaselineCacheIRCompiler::emitProxySetByValue(ObjOperandId objId,
1858 ValOperandId idId,
1859 ValOperandId rhsId,
1860 bool strict) {
1861 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1862 Register obj = allocator.useRegister(masm, objId);
1863 ValueOperand idVal = allocator.useValueRegister(masm, idId);
1864 ValueOperand val = allocator.useValueRegister(masm, rhsId);
1865
1866 allocator.discardStack(masm);
1867
1868 // We need a scratch register but we don't have any registers available on
1869 // x86, so temporarily store |obj| in the frame's scratch slot.
1870 int scratchOffset = BaselineFrame::reverseOffsetOfScratchValue();
1871 masm.storePtr(obj, Address(baselineFrameReg(), scratchOffset));
1872
1873 AutoStubFrame stubFrame(*this);
1874 stubFrame.enter(masm, obj);
1875
1876 // Restore |obj|. Because we entered a stub frame we first have to load
1877 // the original frame pointer.
1878 masm.loadPtr(Address(FramePointer, 0), obj);
1879 masm.loadPtr(Address(obj, scratchOffset), obj);
1880
1881 masm.Push(Imm32(strict));
1882 masm.Push(val);
1883 masm.Push(idVal);
1884 masm.Push(obj);
1885
1886 using Fn = bool (*)(JSContext*, HandleObject, HandleValue, HandleValue, bool);
1887 callVM<Fn, ProxySetPropertyByValue>(masm);
1888
1889 stubFrame.leave(masm);
1890 return true;
1891 }
1892
1893 bool BaselineCacheIRCompiler::emitCallAddOrUpdateSparseElementHelper(
1894 ObjOperandId objId, Int32OperandId idId, ValOperandId rhsId, bool strict) {
1895 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1896 Register obj = allocator.useRegister(masm, objId);
1897 Register id = allocator.useRegister(masm, idId);
1898 ValueOperand val = allocator.useValueRegister(masm, rhsId);
1899 AutoScratchRegister scratch(allocator, masm);
1900
1901 allocator.discardStack(masm);
1902
1903 AutoStubFrame stubFrame(*this);
1904 stubFrame.enter(masm, scratch);
1905
1906 masm.Push(Imm32(strict));
1907 masm.Push(val);
1908 masm.Push(id);
1909 masm.Push(obj);
1910
1911 using Fn = bool (*)(JSContext* cx, Handle<NativeObject*> obj, int32_t int_id,
1912 HandleValue v, bool strict);
1913 callVM<Fn, AddOrUpdateSparseElementHelper>(masm);
1914
1915 stubFrame.leave(masm);
1916 return true;
1917 }
1918
1919 bool BaselineCacheIRCompiler::emitMegamorphicSetElement(ObjOperandId objId,
1920 ValOperandId idId,
1921 ValOperandId rhsId,
1922 bool strict) {
1923 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1924 Register obj = allocator.useRegister(masm, objId);
1925 ValueOperand idVal = allocator.useValueRegister(masm, idId);
1926 ValueOperand val = allocator.useValueRegister(masm, rhsId);
1927
1928 #ifdef JS_CODEGEN_X86
1929 allocator.discardStack(masm);
1930 // We need a scratch register but we don't have any registers available on
1931 // x86, so temporarily store |obj| in the frame's scratch slot.
1932 int scratchOffset = BaselineFrame::reverseOffsetOfScratchValue();
1933 masm.storePtr(obj, Address(baselineFrameReg_, scratchOffset));
1934
1935 AutoStubFrame stubFrame(*this);
1936 stubFrame.enter(masm, obj);
1937
1938 // Restore |obj|. Because we entered a stub frame we first have to load
1939 // the original frame pointer.
1940 masm.loadPtr(Address(FramePointer, 0), obj);
1941 masm.loadPtr(Address(obj, scratchOffset), obj);
1942 #else
1943 AutoScratchRegister scratch(allocator, masm);
1944
1945 allocator.discardStack(masm);
1946 AutoStubFrame stubFrame(*this);
1947 stubFrame.enter(masm, scratch);
1948 #endif
1949
1950 masm.Push(Imm32(strict));
1951 masm.Push(val);
1952 masm.Push(idVal);
1953 masm.Push(obj);
1954
1955 using Fn = bool (*)(JSContext*, HandleObject, HandleValue, HandleValue, bool);
1956 callVM<Fn, SetElementMegamorphic<false>>(masm);
1957
1958 stubFrame.leave(masm);
1959 return true;
1960 }
1961
1962 bool BaselineCacheIRCompiler::emitReturnFromIC() {
1963 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1964 allocator.discardStack(masm);
1965 if (JitOptions.enableICFramePointers) {
1966 PopICFrameRegs(masm);
1967 }
1968 EmitReturnFromIC(masm);
1969 return true;
1970 }
1971
1972 bool BaselineCacheIRCompiler::emitLoadArgumentFixedSlot(ValOperandId resultId,
1973 uint8_t slotIndex) {
1974 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1975 ValueOperand resultReg = allocator.defineValueRegister(masm, resultId);
1976 Address addr = allocator.addressOf(masm, BaselineFrameSlot(slotIndex));
1977 masm.loadValue(addr, resultReg);
1978 return true;
1979 }
1980
1981 bool BaselineCacheIRCompiler::emitLoadArgumentDynamicSlot(ValOperandId resultId,
1982 Int32OperandId argcId,
1983 uint8_t slotIndex) {
1984 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1985 ValueOperand resultReg = allocator.defineValueRegister(masm, resultId);
1986 Register argcReg = allocator.useRegister(masm, argcId);
1987 BaseValueIndex addr =
1988 allocator.addressOf(masm, argcReg, BaselineFrameSlot(slotIndex));
1989 masm.loadValue(addr, resultReg);
1990 return true;
1991 }
1992
1993 bool BaselineCacheIRCompiler::emitGuardDOMExpandoMissingOrGuardShape(
1994 ValOperandId expandoId, uint32_t shapeOffset) {
1995 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
1996 ValueOperand val = allocator.useValueRegister(masm, expandoId);
1997 AutoScratchRegister shapeScratch(allocator, masm);
1998 AutoScratchRegister objScratch(allocator, masm);
1999 Address shapeAddr(stubAddress(shapeOffset));
2000
2001 FailurePath* failure;
2002 if (!addFailurePath(&failure)) {
2003 return false;
2004 }
2005
2006 Label done;
2007 masm.branchTestUndefined(Assembler::Equal, val, &done);
2008
2009 masm.debugAssertIsObject(val);
2010 masm.loadPtr(shapeAddr, shapeScratch);
2011 masm.unboxObject(val, objScratch);
2012 // The expando object is not used in this case, so we don't need Spectre
2013 // mitigations.
2014 masm.branchTestObjShapeNoSpectreMitigations(Assembler::NotEqual, objScratch,
2015 shapeScratch, failure->label());
2016
2017 masm.bind(&done);
2018 return true;
2019 }
2020
2021 bool BaselineCacheIRCompiler::emitLoadDOMExpandoValueGuardGeneration(
2022 ObjOperandId objId, uint32_t expandoAndGenerationOffset,
2023 uint32_t generationOffset, ValOperandId resultId) {
2024 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
2025 Register obj = allocator.useRegister(masm, objId);
2026 Address expandoAndGenerationAddr(stubAddress(expandoAndGenerationOffset));
2027 Address generationAddr(stubAddress(generationOffset));
2028
2029 AutoScratchRegister scratch(allocator, masm);
2030 ValueOperand output = allocator.defineValueRegister(masm, resultId);
2031
2032 FailurePath* failure;
2033 if (!addFailurePath(&failure)) {
2034 return false;
2035 }
2036
2037 masm.loadPtr(Address(obj, ProxyObject::offsetOfReservedSlots()), scratch);
2038 Address expandoAddr(scratch,
2039 js::detail::ProxyReservedSlots::offsetOfPrivateSlot());
2040
2041 // Load the ExpandoAndGeneration* in the output scratch register and guard
2042 // it matches the proxy's ExpandoAndGeneration.
2043 masm.loadPtr(expandoAndGenerationAddr, output.scratchReg());
2044 masm.branchPrivatePtr(Assembler::NotEqual, expandoAddr, output.scratchReg(),
2045 failure->label());
2046
2047 // Guard expandoAndGeneration->generation matches the expected generation.
2048 masm.branch64(
2049 Assembler::NotEqual,
2050 Address(output.scratchReg(), ExpandoAndGeneration::offsetOfGeneration()),
2051 generationAddr, scratch, failure->label());
2052
2053 // Load expandoAndGeneration->expando into the output Value register.
2054 masm.loadValue(
2055 Address(output.scratchReg(), ExpandoAndGeneration::offsetOfExpando()),
2056 output);
2057 return true;
2058 }
2059
2060 bool BaselineCacheIRCompiler::init(CacheKind kind) {
2061 if (!allocator.init()) {
2062 return false;
2063 }
2064
2065 size_t numInputs = writer_.numInputOperands();
2066 MOZ_ASSERT(numInputs == NumInputsForCacheKind(kind));
2067
2068 // Baseline passes the first 2 inputs in R0/R1, other Values are stored on
2069 // the stack.
2070 size_t numInputsInRegs = std::min(numInputs, size_t(2));
2071 AllocatableGeneralRegisterSet available =
2072 BaselineICAvailableGeneralRegs(numInputsInRegs);
2073
2074 switch (kind) {
2075 case CacheKind::NewArray:
2076 case CacheKind::NewObject:
2077 case CacheKind::Lambda:
2078 case CacheKind::LazyConstant:
2079 case CacheKind::GetImport:
2080 MOZ_ASSERT(numInputs == 0);
2081 outputUnchecked_.emplace(R0);
2082 break;
2083 case CacheKind::GetProp:
2084 case CacheKind::TypeOf:
2085 case CacheKind::TypeOfEq:
2086 case CacheKind::ToPropertyKey:
2087 case CacheKind::GetIterator:
2088 case CacheKind::OptimizeSpreadCall:
2089 case CacheKind::OptimizeGetIterator:
2090 case CacheKind::ToBool:
2091 case CacheKind::UnaryArith:
2092 MOZ_ASSERT(numInputs == 1);
2093 allocator.initInputLocation(0, R0);
2094 outputUnchecked_.emplace(R0);
2095 break;
2096 case CacheKind::Compare:
2097 case CacheKind::GetElem:
2098 case CacheKind::GetPropSuper:
2099 case CacheKind::In:
2100 case CacheKind::HasOwn:
2101 case CacheKind::CheckPrivateField:
2102 case CacheKind::InstanceOf:
2103 case CacheKind::BinaryArith:
2104 MOZ_ASSERT(numInputs == 2);
2105 allocator.initInputLocation(0, R0);
2106 allocator.initInputLocation(1, R1);
2107 outputUnchecked_.emplace(R0);
2108 break;
2109 case CacheKind::SetProp:
2110 MOZ_ASSERT(numInputs == 2);
2111 allocator.initInputLocation(0, R0);
2112 allocator.initInputLocation(1, R1);
2113 break;
2114 case CacheKind::GetElemSuper:
2115 MOZ_ASSERT(numInputs == 3);
2116 allocator.initInputLocation(0, BaselineFrameSlot(0));
2117 allocator.initInputLocation(1, R1);
2118 allocator.initInputLocation(2, R0);
2119 outputUnchecked_.emplace(R0);
2120 break;
2121 case CacheKind::SetElem:
2122 MOZ_ASSERT(numInputs == 3);
2123 allocator.initInputLocation(0, R0);
2124 allocator.initInputLocation(1, R1);
2125 allocator.initInputLocation(2, BaselineFrameSlot(0));
2126 break;
2127 case CacheKind::GetName:
2128 case CacheKind::BindName:
2129 MOZ_ASSERT(numInputs == 1);
2130 allocator.initInputLocation(0, R0.scratchReg(), JSVAL_TYPE_OBJECT);
2131 #if defined(JS_NUNBOX32)
2132 // availableGeneralRegs can't know that GetName/BindName is only using
2133 // the payloadReg and not typeReg on x86.
2134 available.add(R0.typeReg());
2135 #endif
2136 outputUnchecked_.emplace(R0);
2137 break;
2138 case CacheKind::Call:
2139 MOZ_ASSERT(numInputs == 1);
2140 allocator.initInputLocation(0, R0.scratchReg(), JSVAL_TYPE_INT32);
2141 #if defined(JS_NUNBOX32)
2142 // availableGeneralRegs can't know that Call is only using
2143 // the payloadReg and not typeReg on x86.
2144 available.add(R0.typeReg());
2145 #endif
2146 outputUnchecked_.emplace(R0);
2147 break;
2148 case CacheKind::CloseIter:
2149 MOZ_ASSERT(numInputs == 1);
2150 allocator.initInputLocation(0, R0.scratchReg(), JSVAL_TYPE_OBJECT);
2151 #if defined(JS_NUNBOX32)
2152 // availableGeneralRegs can't know that CloseIter is only using
2153 // the payloadReg and not typeReg on x86.
2154 available.add(R0.typeReg());
2155 #endif
2156 break;
2157 }
2158
2159 // Baseline doesn't allocate float registers so none of them are live.
2160 liveFloatRegs_ = LiveFloatRegisterSet(FloatRegisterSet());
2161
2162 if (JitOptions.enableICFramePointers) {
2163 baselineFrameReg_ = available.takeAny();
2164 }
2165
2166 allocator.initAvailableRegs(available);
2167 return true;
2168 }
2169
2170 static void ResetEnteredCounts(const ICEntry* icEntry) {
2171 ICStub* stub = icEntry->firstStub();
2172 while (true) {
2173 stub->resetEnteredCount();
2174 if (stub->isFallback()) {
2175 return;
2176 }
2177 stub = stub->toCacheIRStub()->next();
2178 }
2179 }
2180
2181 static const uint32_t MaxFoldedShapes = 16;
2182
2183 const JSClass ShapeListObject::class_ = {
2184 "JIT ShapeList",
2185 0,
2186 &classOps_,
2187 };
2188
2189 const JSClassOps ShapeListObject::classOps_ = {
2190 nullptr, // addProperty
2191 nullptr, // delProperty
2192 nullptr, // enumerate
2193 nullptr, // newEnumerate
2194 nullptr, // resolve
2195 nullptr, // mayResolve
2196 nullptr, // finalize
2197 nullptr, // call
2198 nullptr, // construct
2199 ShapeListObject::trace, // trace
2200 };
2201
2202 /* static */ ShapeListObject* ShapeListObject::create(JSContext* cx) {
2203 NativeObject* obj = NewTenuredObjectWithGivenProto(cx, &class_, nullptr);
2204 if (!obj) {
2205 return nullptr;
2206 }
2207
2208 // Register this object so the GC can sweep its weak pointers.
2209 if (!cx->zone()->registerObjectWithWeakPointers(obj)) {
2210 ReportOutOfMemory(cx);
2211 return nullptr;
2212 }
2213
2214 return &obj->as<ShapeListObject>();
2215 }
2216
2217 Shape* ShapeListObject::get(uint32_t index) {
2218 Value value = ListObject::get(index);
2219 return static_cast<Shape*>(value.toPrivate());
2220 }
2221
2222 void ShapeListObject::trace(JSTracer* trc, JSObject* obj) {
2223 if (trc->traceWeakEdges()) {
2224 obj->as<ShapeListObject>().traceWeak(trc);
2225 }
2226 }
2227
2228 bool ShapeListObject::traceWeak(JSTracer* trc) {
2229 uint32_t length = getDenseInitializedLength();
2230 if (length == 0) {
2231 return false; // Object may be uninitialized.
2232 }
2233
2234 const HeapSlot* src = elements_;
2235 const HeapSlot* end = src + length;
2236 HeapSlot* dst = elements_;
2237 while (src != end) {
2238 Shape* shape = static_cast<Shape*>(src->toPrivate());
2239 MOZ_ASSERT(shape->is<Shape>());
2240 if (TraceManuallyBarrieredWeakEdge(trc, &shape, "ShapeListObject shape")) {
2241 dst->unbarrieredSet(PrivateValue(shape));
2242 dst++;
2243 }
2244 src++;
2245 }
2246
2247 MOZ_ASSERT(dst <= end);
2248 uint32_t newLength = dst - elements_;
2249 setDenseInitializedLength(newLength);
2250
2251 if (length != newLength) {
2252 JitSpew(JitSpew_StubFolding, "Cleared %u/%u shapes from %p",
2253 length - newLength, length, this);
2254 }
2255
2256 return length != 0;
2257 }
2258
2259 bool js::jit::TryFoldingStubs(JSContext* cx, ICFallbackStub* fallback,
2260 JSScript* script, ICScript* icScript) {
2261 ICEntry* icEntry = icScript->icEntryForStub(fallback);
2262 ICStub* entryStub = icEntry->firstStub();
2263
2264 // Don't fold unless there are at least two stubs.
2265 if (entryStub == fallback) {
2266 return true;
2267 }
2268 ICCacheIRStub* firstStub = entryStub->toCacheIRStub();
2269 if (firstStub->next()->isFallback()) {
2270 return true;
2271 }
2272
2273 const uint8_t* firstStubData = firstStub->stubDataStart();
2274 const CacheIRStubInfo* stubInfo = firstStub->stubInfo();
2275
2276 // Check to see if:
2277 // a) all of the stubs in this chain have the exact same code.
2278 // b) all of the stubs have the same stub field data, except
2279 // for a single GuardShape where they differ.
2280 // c) at least one stub after the first has a non-zero entry count.
2281 // d) All shapes in the GuardShape have the same realm.
2282 //
2283 // If all of these conditions hold, then we generate a single stub
2284 // that covers all the existing cases by replacing GuardShape with
2285 // GuardMultipleShapes.
2286
2287 uint32_t numActive = 0;
2288 Maybe<uint32_t> foldableFieldOffset;
2289 RootedValue shape(cx);
2290 RootedValueVector shapeList(cx);
2291
2292 // Try to add a shape to the list. Can fail on OOM or for cross-realm shapes.
2293 // Returns true if the shape was successfully added to the list, and false
2294 // (with no pending exception) otherwise.
2295 auto addShape = [&shapeList, cx](uintptr_t rawShape) -> bool {
2296 Shape* shape = reinterpret_cast<Shape*>(rawShape);
2297 // Only add same realm shapes.
2298 if (shape->realm() != cx->realm()) {
2299 return false;
2300 }
2301
2302 gc::ReadBarrier(shape);
2303
2304 if (!shapeList.append(PrivateValue(shape))) {
2305 cx->recoverFromOutOfMemory();
2306 return false;
2307 }
2308 return true;
2309 };
2310
2311 for (ICCacheIRStub* other = firstStub->nextCacheIR(); other;
2312 other = other->nextCacheIR()) {
2313 // Verify that the stubs share the same code.
2314 if (other->stubInfo() != stubInfo) {
2315 return true;
2316 }
2317 const uint8_t* otherStubData = other->stubDataStart();
2318
2319 if (other->enteredCount() > 0) {
2320 numActive++;
2321 }
2322
2323 uint32_t fieldIndex = 0;
2324 size_t offset = 0;
2325 while (stubInfo->fieldType(fieldIndex) != StubField::Type::Limit) {
2326 StubField::Type fieldType = stubInfo->fieldType(fieldIndex);
2327
2328 if (StubField::sizeIsWord(fieldType)) {
2329 uintptr_t firstRaw = stubInfo->getStubRawWord(firstStubData, offset);
2330 uintptr_t otherRaw = stubInfo->getStubRawWord(otherStubData, offset);
2331
2332 if (firstRaw != otherRaw) {
2333 if (fieldType != StubField::Type::WeakShape) {
2334 // Case 1: a field differs that is not a Shape. We only support
2335 // folding GuardShape to GuardMultipleShapes.
2336 return true;
2337 }
2338 if (foldableFieldOffset.isNothing()) {
2339 // Case 2: this is the first field where the stub data differs.
2340 foldableFieldOffset.emplace(offset);
2341 if (!addShape(firstRaw) || !addShape(otherRaw)) {
2342 return true;
2343 }
2344 } else if (*foldableFieldOffset == offset) {
2345 // Case 3: this is the corresponding offset in a different stub.
2346 if (!addShape(otherRaw)) {
2347 return true;
2348 }
2349 } else {
2350 // Case 4: we have found more than one field that differs.
2351 return true;
2352 }
2353 }
2354 } else {
2355 MOZ_ASSERT(StubField::sizeIsInt64(fieldType));
2356
2357 // We do not support folding any ops with int64-sized fields.
2358 if (stubInfo->getStubRawInt64(firstStubData, offset) !=
2359 stubInfo->getStubRawInt64(otherStubData, offset)) {
2360 return true;
2361 }
2362 }
2363
2364 offset += StubField::sizeInBytes(fieldType);
2365 fieldIndex++;
2366 }
2367
2368 // We should never attach two completely identical stubs.
2369 MOZ_ASSERT(foldableFieldOffset.isSome());
2370 }
2371
2372 if (numActive == 0) {
2373 return true;
2374 }
2375
2376 // Clone the CacheIR, replacing GuardShape with GuardMultipleShapes.
2377 CacheIRWriter writer(cx);
2378 CacheIRReader reader(stubInfo);
2379 CacheIRCloner cloner(firstStub);
2380
2381 // Initialize the operands.
2382 CacheKind cacheKind = stubInfo->kind();
2383 for (uint32_t i = 0; i < NumInputsForCacheKind(cacheKind); i++) {
2384 writer.setInputOperandId(i);
2385 }
2386
2387 bool success = false;
2388 while (reader.more()) {
2389 CacheOp op = reader.readOp();
2390 switch (op) {
2391 case CacheOp::GuardShape: {
2392 ObjOperandId objId = reader.objOperandId();
2393 uint32_t shapeOffset = reader.stubOffset();
2394 if (shapeOffset == *foldableFieldOffset) {
2395 // Ensure that the allocation of the ShapeListObject doesn't trigger a
2396 // GC and free the stubInfo we're currently reading. Note that
2397 // AutoKeepJitScripts isn't sufficient, because optimized stubs can be
2398 // discarded even if the JitScript is preserved.
2399 gc::AutoSuppressGC suppressGC(cx);
2400
2401 Rooted<ShapeListObject*> shapeObj(cx, ShapeListObject::create(cx));
2402 if (!shapeObj) {
2403 return false;
2404 }
2405 for (uint32_t i = 0; i < shapeList.length(); i++) {
2406 if (!shapeObj->append(cx, shapeList[i])) {
2407 return false;
2408 }
2409
2410 MOZ_ASSERT(static_cast<Shape*>(shapeList[i].toPrivate())->realm() ==
2411 shapeObj->realm());
2412 }
2413
2414 writer.guardMultipleShapes(objId, shapeObj);
2415 success = true;
2416 } else {
2417 WeakHeapPtr<Shape*>& ptr =
2418 stubInfo->getStubField<StubField::Type::WeakShape>(firstStub,
2419 shapeOffset);
2420 writer.guardShape(objId, ptr.unbarrieredGet());
2421 }
2422 break;
2423 }
2424 default:
2425 cloner.cloneOp(op, reader, writer);
2426 break;
2427 }
2428 }
2429 if (!success) {
2430 // If the shape field that differed was not part of a GuardShape,
2431 // we can't fold these stubs together.
2432 return true;
2433 }
2434
2435 // Replace the existing stubs with the new folded stub.
2436 fallback->discardStubs(cx->zone(), icEntry);
2437
2438 ICAttachResult result = AttachBaselineCacheIRStub(
2439 cx, writer, cacheKind, script, icScript, fallback, "StubFold");
2440 if (result == ICAttachResult::OOM) {
2441 ReportOutOfMemory(cx);
2442 return false;
2443 }
2444 MOZ_ASSERT(result == ICAttachResult::Attached);
2445
2446 JitSpew(JitSpew_StubFolding,
2447 "Folded stub at offset %u (icScript: %p) with %zu shapes (%s:%u:%u)",
2448 fallback->pcOffset(), icScript, shapeList.length(),
2449 script->filename(), script->lineno(),
2450 script->column().oneOriginValue());
2451
2452 fallback->setMayHaveFoldedStub();
2453 return true;
2454 }
2455
2456 static bool AddToFoldedStub(JSContext* cx, const CacheIRWriter& writer,
2457 ICScript* icScript, ICFallbackStub* fallback) {
2458 ICEntry* icEntry = icScript->icEntryForStub(fallback);
2459 ICStub* entryStub = icEntry->firstStub();
2460
2461 // We only update folded stubs if they're the only stub in the IC.
2462 if (entryStub == fallback) {
2463 return false;
2464 }
2465 ICCacheIRStub* stub = entryStub->toCacheIRStub();
2466 if (!stub->next()->isFallback()) {
2467 return false;
2468 }
2469
2470 const CacheIRStubInfo* stubInfo = stub->stubInfo();
2471 const uint8_t* stubData = stub->stubDataStart();
2472
2473 Maybe<uint32_t> shapeFieldOffset;
2474 RootedValue newShape(cx);
2475 Rooted<ShapeListObject*> foldedShapes(cx);
2476
2477 CacheIRReader stubReader(stubInfo);
2478 CacheIRReader newReader(writer);
2479 while (newReader.more() && stubReader.more()) {
2480 CacheOp newOp = newReader.readOp();
2481 CacheOp stubOp = stubReader.readOp();
2482 switch (stubOp) {
2483 case CacheOp::GuardMultipleShapes: {
2484 // Check that the new stub has a corresponding GuardShape.
2485 if (newOp != CacheOp::GuardShape) {
2486 return false;
2487 }
2488
2489 // Check that the object being guarded is the same.
2490 if (newReader.objOperandId() != stubReader.objOperandId()) {
2491 return false;
2492 }
2493
2494 // Check that the field offset is the same.
2495 uint32_t newShapeOffset = newReader.stubOffset();
2496 uint32_t stubShapesOffset = stubReader.stubOffset();
2497 if (newShapeOffset != stubShapesOffset) {
2498 return false;
2499 }
2500 MOZ_ASSERT(shapeFieldOffset.isNothing());
2501 shapeFieldOffset.emplace(newShapeOffset);
2502
2503 // Get the shape from the new stub
2504 StubField shapeField =
2505 writer.readStubField(newShapeOffset, StubField::Type::WeakShape);
2506 Shape* shape = reinterpret_cast<Shape*>(shapeField.asWord());
2507 newShape = PrivateValue(shape);
2508
2509 // Get the shape array from the old stub.
2510 JSObject* shapeList = stubInfo->getStubField<StubField::Type::JSObject>(
2511 stub, stubShapesOffset);
2512 foldedShapes = &shapeList->as<ShapeListObject>();
2513 MOZ_ASSERT(foldedShapes->compartment() == shape->compartment());
2514
2515 // Don't add a shape if it's from a different realm than the first
2516 // shape.
2517 //
2518 // Since the list was created in the realm which guarded all the shapes
2519 // added to it, we can use its realm to check and ensure we're not
2520 // adding a cross-realm shape.
2521 //
2522 // The assert verifies this property by checking the first element has
2523 // the same realm (and since everything in the list has the same realm,
2524 // checking the first element suffices)
2525 MOZ_ASSERT_IF(!foldedShapes->isEmpty(),
2526 foldedShapes->get(0)->realm() == foldedShapes->realm());
2527 if (foldedShapes->realm() != shape->realm()) {
2528 return false;
2529 }
2530
2531 break;
2532 }
2533 default: {
2534 // Check that the op is the same.
2535 if (newOp != stubOp) {
2536 return false;
2537 }
2538
2539 // Check that the arguments are the same.
2540 uint32_t argLength = CacheIROpInfos[size_t(newOp)].argLength;
2541 for (uint32_t i = 0; i < argLength; i++) {
2542 if (newReader.readByte() != stubReader.readByte()) {
2543 return false;
2544 }
2545 }
2546 }
2547 }
2548 }
2549
2550 if (shapeFieldOffset.isNothing()) {
2551 // The stub did not contain the GuardMultipleShapes op. This can happen if a
2552 // folded stub has been discarded by GC sweeping.
2553 return false;
2554 }
2555
2556 // Check to verify that all the other stub fields are the same.
2557 if (!writer.stubDataEqualsIgnoring(stubData, *shapeFieldOffset)) {
2558 return false;
2559 }
2560
2561 // Limit the maximum number of shapes we will add before giving up.
2562 if (foldedShapes->length() == MaxFoldedShapes) {
2563 return false;
2564 }
2565
2566 if (!foldedShapes->append(cx, newShape)) {
2567 cx->recoverFromOutOfMemory();
2568 return false;
2569 }
2570
2571 JitSpew(JitSpew_StubFolding, "ShapeListObject %p: new length: %u",
2572 foldedShapes.get(), foldedShapes->length());
2573
2574 return true;
2575 }
2576
2577 #ifdef ENABLE_JS_AOT_ICS
2578 void DumpNonAOTICStubAndQuit(CacheKind kind, const CacheIRWriter& writer) {
2579 // Generate a random filename (unlikely to conflict with others).
2580 char filename[64];
2581 snprintf(filename, sizeof(filename), "IC-%" PRIu64,
2582 mozilla::RandomUint64OrDie());
2583 FILE* f = fopen(filename, "w");
2584 MOZ_RELEASE_ASSERT(f);
2585
2586 // Generate the CacheIR text to dump to a file.
2587 {
2588 Fprinter printer(f);
2589 SpewCacheIROpsAsAOT(printer, kind, writer);
2590 }
2591 fflush(f);
2592 fclose(f);
2593 fprintf(stderr, "UNEXPECTED NEW IC BODY\n");
2594
2595 fprintf(stderr,
2596 "Please add the file '%s' to the ahead-of-time known IC bodies in "
2597 "js/src/ics/.\n"
2598 "\n"
2599 "To keep running and dump all new ICs (useful for updating with "
2600 "test-suites),\n"
2601 "set the environment variable AOT_ICS_KEEP_GOING=1 and rerun.\n",
2602 filename);
2603
2604 if (!getenv("AOT_ICS_KEEP_GOING")) {
2605 abort();
2606 }
2607 }
2608 #endif
2609
2610 static constexpr uint32_t StubDataOffset = sizeof(ICCacheIRStub);
2611 static_assert(StubDataOffset % sizeof(uint64_t) == 0,
2612 "Stub fields must be aligned");
2613
2614 static bool LookupOrCompileStub(JSContext* cx, CacheKind kind,
2615 const CacheIRWriter& writer,
2616 CacheIRStubInfo*& stubInfo, JitCode*& code,
2617 const char* name, bool isAOTFill,
2618 JitZone* jitZone) {
2619 CacheIRStubKey::Lookup lookup(kind, ICStubEngine::Baseline,
2620 writer.codeStart(), writer.codeLength());
2621
2622 code = jitZone->getBaselineCacheIRStubCode(lookup, &stubInfo);
2623
2624 #ifdef ENABLE_JS_AOT_ICS
2625 if (JitOptions.enableAOTICEnforce && !stubInfo && !isAOTFill &&
2626 !jitZone->isIncompleteAOTICs()) {
2627 DumpNonAOTICStubAndQuit(kind, writer);
2628 }
2629 #endif
2630
2631 if (!code && !IsPortableBaselineInterpreterEnabled()) {
2632 // We have to generate stub code.
2633 TempAllocator temp(&cx->tempLifoAlloc());
2634 JitContext jctx(cx);
2635 BaselineCacheIRCompiler comp(cx, temp, writer, StubDataOffset);
2636 if (!comp.init(kind)) {
2637 return false;
2638 }
2639
2640 code = comp.compile();
2641 if (!code) {
2642 return false;
2643 }
2644
2645 comp.perfSpewer().saveProfile(code, name);
2646
2647 // Allocate the shared CacheIRStubInfo. Note that the
2648 // putBaselineCacheIRStubCode call below will transfer ownership
2649 // to the stub code HashMap, so we don't have to worry about freeing
2650 // it below.
2651 MOZ_ASSERT(!stubInfo);
2652 stubInfo =
2653 CacheIRStubInfo::New(kind, ICStubEngine::Baseline, comp.makesGCCalls(),
2654 StubDataOffset, writer);
2655 if (!stubInfo) {
2656 return false;
2657 }
2658
2659 CacheIRStubKey key(stubInfo);
2660 if (!jitZone->putBaselineCacheIRStubCode(lookup, key, code)) {
2661 return false;
2662 }
2663 } else if (!stubInfo) {
2664 MOZ_ASSERT(IsPortableBaselineInterpreterEnabled());
2665
2666 // Portable baseline interpreter case. We want to generate the
2667 // CacheIR bytecode but not compile it to native code.
2668 //
2669 // We lie that all stubs make GC calls; this is simpler than
2670 // iterating over ops to determine if it is actually the base, and
2671 // we don't invoke the BaselineCacheIRCompiler so we otherwise
2672 // don't know for sure.
2673 stubInfo = CacheIRStubInfo::New(kind, ICStubEngine::Baseline,
2674 /* makes GC calls = */ true, StubDataOffset,
2675 writer);
2676 if (!stubInfo) {
2677 return false;
2678 }
2679
2680 CacheIRStubKey key(stubInfo);
2681 if (!jitZone->putBaselineCacheIRStubCode(lookup, key,
2682 /* stubCode = */ nullptr)) {
2683 return false;
2684 }
2685 }
2686 MOZ_ASSERT_IF(IsBaselineInterpreterEnabled(), code);
2687 MOZ_ASSERT(stubInfo);
2688 // Assert that the StubInfo recomputing its stub-data size exactly
2689 // matches the writer's stub-data size, but only if we're not
2690 // loading an AOT IC -- otherwise, trust the recomputation from
2691 // field types.
2692 //
2693 // Why ignore if AOT? Because the AOT corpus might have been dumped
2694 // on a machine with a different word size than our machine (e.g.,
2695 // 64 to 32 bits). The field types are serialized and deserialized,
2696 // and they are authoritative; the CacheIRWriter's stubDataSize is
2697 // computed during build and used only for this assert, so it is
2698 // strictly a redundant check.
2699 //
2700 // (This cross-machine movement of the corpus is acceptable/correct
2701 // because the CacheIR itself, and our encoding of it in the corpus
2702 // source code, is platform-independent. The worst that happens is
2703 // that some platforms may not generate all possible ICs for another
2704 // platform (e.g. due to limited registers on x86-32) but it is always
2705 // fine not to have an IC preloaded in the corpus.
2706 MOZ_ASSERT_IF(!isAOTFill, stubInfo->stubDataSize() == writer.stubDataSize());
2707
2708 return true;
2709 }
2710
2711 ICAttachResult js::jit::AttachBaselineCacheIRStub(
2712 JSContext* cx, const CacheIRWriter& writer, CacheKind kind,
2713 JSScript* outerScript, ICScript* icScript, ICFallbackStub* stub,
2714 const char* name) {
2715 // We shouldn't GC or report OOM (or any other exception) here.
2716 AutoAssertNoPendingException aanpe(cx);
2717 JS::AutoCheckCannotGC nogc;
2718
2719 if (writer.tooLarge()) {
2720 cx->runtime()->setUseCounter(cx->global(), JSUseCounter::IC_STUB_TOO_LARGE);
2721 return ICAttachResult::TooLarge;
2722 }
2723 if (writer.oom()) {
2724 cx->runtime()->setUseCounter(cx->global(), JSUseCounter::IC_STUB_OOM);
2725 return ICAttachResult::OOM;
2726 }
2727 MOZ_ASSERT(!writer.failed());
2728
2729 // Just a sanity check: the caller should ensure we don't attach an
2730 // unlimited number of stubs.
2731 #ifdef DEBUG
2732 static const size_t MaxOptimizedCacheIRStubs = 16;
2733 MOZ_ASSERT(stub->numOptimizedStubs() < MaxOptimizedCacheIRStubs);
2734 #endif
2735
2736 // Check if we already have JitCode for this stub.
2737 CacheIRStubInfo* stubInfo;
2738 JitCode* code;
2739
2740 if (!LookupOrCompileStub(cx, kind, writer, stubInfo, code, name,
2741 /* isAOTFill = */ false, cx->zone()->jitZone())) {
2742 return ICAttachResult::OOM;
2743 }
2744
2745 ICEntry* icEntry = icScript->icEntryForStub(stub);
2746
2747 // Ensure we don't attach duplicate stubs. This can happen if a stub failed
2748 // for some reason and the IR generator doesn't check for exactly the same
2749 // conditions.
2750 for (ICStub* iter = icEntry->firstStub(); iter != stub;
2751 iter = iter->toCacheIRStub()->next()) {
2752 auto otherStub = iter->toCacheIRStub();
2753 if (otherStub->stubInfo() != stubInfo) {
2754 continue;
2755 }
2756 if (!writer.stubDataEquals(otherStub->stubDataStart())) {
2757 continue;
2758 }
2759
2760 // We found a stub that's exactly the same as the stub we're about to
2761 // attach. Just return nullptr, the caller should do nothing in this
2762 // case.
2763 JitSpew(JitSpew_BaselineICFallback,
2764 "Tried attaching identical stub for (%s:%u:%u)",
2765 outerScript->filename(), outerScript->lineno(),
2766 outerScript->column().oneOriginValue());
2767 return ICAttachResult::DuplicateStub;
2768 }
2769
2770 // Try including this case in an existing folded stub.
2771 if (stub->mayHaveFoldedStub() &&
2772 AddToFoldedStub(cx, writer, icScript, stub)) {
2773 JitSpew(JitSpew_StubFolding,
2774 "Added to folded stub at offset %u (icScript: %p) (%s:%u:%u)",
2775 stub->pcOffset(), icScript, outerScript->filename(),
2776 outerScript->lineno(), outerScript->column().oneOriginValue());
2777
2778 // Instead of adding a new stub, we have added a new case to an existing
2779 // folded stub. We do not have to invalidate Warp, because the
2780 // ShapeListObject that stores the cases is shared between baseline and
2781 // Warp. Reset the entered count for the fallback stub so that we can still
2782 // transpile, and reset the bailout counter if we have already been
2783 // transpiled.
2784 stub->resetEnteredCount();
2785 JSScript* owningScript = nullptr;
2786 if (cx->zone()->jitZone()->hasStubFoldingBailoutData(outerScript)) {
2787 owningScript = cx->zone()->jitZone()->stubFoldingBailoutParent();
2788 JitSpew(JitSpew_StubFolding,
2789 "Found stub folding bailout parent: %s:%u:%u",
2790 owningScript->filename(), owningScript->lineno(),
2791 owningScript->column().oneOriginValue());
2792 } else {
2793 owningScript = icScript->isInlined()
2794 ? icScript->inliningRoot()->owningScript()
2795 : outerScript;
2796 }
2797 cx->zone()->jitZone()->clearStubFoldingBailoutData();
2798 if (stub->usedByTranspiler()) {
2799 if (owningScript->hasIonScript()) {
2800 owningScript->ionScript()->resetNumFixableBailouts();
2801 } else if (owningScript->hasJitScript()) {
2802 owningScript->jitScript()->clearFailedICHash();
2803 }
2804 } else {
2805 // Update the last IC counter if this is not a bailout from Ion.
2806 owningScript->updateLastICStubCounter();
2807 }
2808 return ICAttachResult::Attached;
2809 }
2810
2811 // Time to allocate and attach a new stub.
2812
2813 size_t bytesNeeded = stubInfo->stubDataOffset() + stubInfo->stubDataSize();
2814
2815 void* newStubMem = cx->zone()->jitZone()->stubSpace()->alloc(bytesNeeded);
2816 if (!newStubMem) {
2817 return ICAttachResult::OOM;
2818 }
2819
2820 // Resetting the entered counts on the IC chain makes subsequent reasoning
2821 // about the chain much easier.
2822 ResetEnteredCounts(icEntry);
2823
2824 switch (stub->trialInliningState()) {
2825 case TrialInliningState::Initial:
2826 case TrialInliningState::Candidate:
2827 stub->setTrialInliningState(writer.trialInliningState());
2828 break;
2829 case TrialInliningState::MonomorphicInlined:
2830 stub->setTrialInliningState(TrialInliningState::Failure);
2831 break;
2832 case TrialInliningState::Inlined:
2833 stub->setTrialInliningState(TrialInliningState::Failure);
2834 icScript->removeInlinedChild(stub->pcOffset());
2835 break;
2836 case TrialInliningState::Failure:
2837 break;
2838 }
2839
2840 auto newStub = new (newStubMem) ICCacheIRStub(code, stubInfo);
2841 writer.copyStubData(newStub->stubDataStart());
2842 newStub->setTypeData(writer.typeData());
2843
2844 #ifdef ENABLE_PORTABLE_BASELINE_INTERP
2845 newStub->updateRawJitCode(pbl::GetICInterpreter());
2846 #endif
2847
2848 stub->addNewStub(icEntry, newStub);
2849
2850 JSScript* owningScript = icScript->isInlined()
2851 ? icScript->inliningRoot()->owningScript()
2852 : outerScript;
2853 owningScript->updateLastICStubCounter();
2854 return ICAttachResult::Attached;
2855 }
2856
2857 #ifdef ENABLE_JS_AOT_ICS
2858
2859 # ifndef ENABLE_PORTABLE_BASELINE_INTERP
2860 // The AOT loading of ICs doesn't work (yet) in modes with a native
2861 // JIT enabled because compilation tries to access state that doesn't
2862 // exist yet (trampolines?) when we create the JitZone.
2863 # error AOT ICs are only supported (for now) in PBL builds.
2864 # endif
2865
2866 void js::jit::FillAOTICs(JSContext* cx, JitZone* zone) {
2867 if (JitOptions.enableAOTICs) {
2868 for (auto& stub : GetAOTStubs()) {
2869 CacheIRWriter writer(cx, stub);
2870 if (writer.failed()) {
2871 zone->setIncompleteAOTICs();
2872 break;
2873 }
2874 CacheIRStubInfo* stubInfo;
2875 JitCode* code;
2876 (void)LookupOrCompileStub(cx, stub.kind, writer, stubInfo, code,
2877 "aot stub",
2878 /* isAOTFill = */ true, zone);
2879 (void)stubInfo;
2880 (void)code;
2881 }
2882 }
2883 }
2884 #endif
2885
2886 uint8_t* ICCacheIRStub::stubDataStart() {
2887 return reinterpret_cast<uint8_t*>(this) + stubInfo_->stubDataOffset();
2888 }
2889
2890 bool BaselineCacheIRCompiler::emitCallStringObjectConcatResult(
2891 ValOperandId lhsId, ValOperandId rhsId) {
2892 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
2893 ValueOperand lhs = allocator.useValueRegister(masm, lhsId);
2894 ValueOperand rhs = allocator.useValueRegister(masm, rhsId);
2895
2896 AutoScratchRegister scratch(allocator, masm);
2897
2898 allocator.discardStack(masm);
2899
2900 AutoStubFrame stubFrame(*this);
2901 stubFrame.enter(masm, scratch);
2902
2903 masm.pushValue(rhs);
2904 masm.pushValue(lhs);
2905
2906 using Fn = bool (*)(JSContext*, HandleValue, HandleValue, MutableHandleValue);
2907 callVM<Fn, DoConcatStringObject>(masm);
2908
2909 stubFrame.leave(masm);
2910 return true;
2911 }
2912
2913 // The value of argc entering the call IC is not always the value of
2914 // argc entering the callee. (For example, argc for a spread call IC
2915 // is always 1, but argc for the callee is the length of the array.)
2916 // In these cases, we update argc as part of the call op itself, to
2917 // avoid modifying input operands while it is still possible to fail a
2918 // guard. We also limit callee argc to a reasonable value to avoid
2919 // blowing the stack limit.
2920 bool BaselineCacheIRCompiler::updateArgc(CallFlags flags, Register argcReg,
2921 Register scratch) {
2922 CallFlags::ArgFormat format = flags.getArgFormat();
2923 switch (format) {
2924 case CallFlags::Standard:
2925 // Standard calls have no extra guards, and argc is already correct.
2926 return true;
2927 case CallFlags::FunCall:
2928 // fun_call has no extra guards, and argc will be corrected in
2929 // pushFunCallArguments.
2930 return true;
2931 case CallFlags::FunApplyNullUndefined:
2932 // argc must be 0 if null or undefined is passed as second argument to
2933 // |apply|.
2934 masm.move32(Imm32(0), argcReg);
2935 return true;
2936 default:
2937 break;
2938 }
2939
2940 // We need to guard the length of the arguments.
2941 FailurePath* failure;
2942 if (!addFailurePath(&failure)) {
2943 return false;
2944 }
2945
2946 // Load callee argc into scratch.
2947 switch (flags.getArgFormat()) {
2948 case CallFlags::Spread:
2949 case CallFlags::FunApplyArray: {
2950 // Load the length of the elements.
2951 BaselineFrameSlot slot(flags.isConstructing());
2952 masm.unboxObject(allocator.addressOf(masm, slot), scratch);
2953 masm.loadPtr(Address(scratch, NativeObject::offsetOfElements()), scratch);
2954 masm.load32(Address(scratch, ObjectElements::offsetOfLength()), scratch);
2955 break;
2956 }
2957 case CallFlags::FunApplyArgsObj: {
2958 // Load the arguments object length.
2959 BaselineFrameSlot slot(0);
2960 masm.unboxObject(allocator.addressOf(masm, slot), scratch);
2961 masm.loadArgumentsObjectLength(scratch, scratch, failure->label());
2962 break;
2963 }
2964 default:
2965 MOZ_CRASH("Unknown arg format");
2966 }
2967
2968 // Ensure that callee argc does not exceed the limit.
2969 masm.branch32(Assembler::Above, scratch, Imm32(JIT_ARGS_LENGTH_MAX),
2970 failure->label());
2971
2972 // We're past the final guard. Update argc with the new value.
2973 masm.move32(scratch, argcReg);
2974
2975 return true;
2976 }
2977
2978 void BaselineCacheIRCompiler::pushArguments(Register argcReg,
2979 Register calleeReg,
2980 Register scratch, Register scratch2,
2981 CallFlags flags, uint32_t argcFixed,
2982 bool isJitCall) {
2983 bool isConstructing = flags.isConstructing();
2984
2985 // Push the formal arguments, and possibly `this` and/or `callee`.
2986 // There are three cases:
2987 // 1. Non-scripted call: all arguments are pushed here.
2988 // 2. Scripted call: all arguments except `callee` are pushed here. `callee`
2989 // must be passed as a CalleeToken, and is pushed below.
2990 // 3. Scripted constructor: only formal arguments are pushed here. We must
2991 // push a new `this` value using createThis, and then push `callee` as
2992 // a CalleeToken. Note that constructors must be Standard or Spread.
2993 switch (flags.getArgFormat()) {
2994 case CallFlags::Standard:
2995 pushStandardArguments(argcReg, scratch, scratch2, argcFixed, isJitCall,
2996 isConstructing);
2997 break;
2998 case CallFlags::Spread:
2999 pushArrayArguments(argcReg, scratch, scratch2, isJitCall, isConstructing);
3000 break;
3001 case CallFlags::FunCall:
3002 pushFunCallArguments(argcReg, calleeReg, scratch, scratch2, argcFixed,
3003 isJitCall);
3004 break;
3005 case CallFlags::FunApplyArgsObj:
3006 pushFunApplyArgsObj(argcReg, calleeReg, scratch, scratch2, isJitCall);
3007 break;
3008 case CallFlags::FunApplyArray:
3009 pushArrayArguments(argcReg, scratch, scratch2, isJitCall,
3010 /*isConstructing =*/false);
3011 break;
3012 case CallFlags::FunApplyNullUndefined:
3013 pushFunApplyNullUndefinedArguments(calleeReg, isJitCall);
3014 break;
3015 default:
3016 MOZ_CRASH("Invalid arg format");
3017 }
3018
3019 if (isJitCall) {
3020 if (isConstructing) {
3021 createThis(argcReg, calleeReg, scratch, scratch2, flags);
3022 }
3023
3024 // Note that we use Push, not push, so that callJit will align the stack
3025 // properly on ARM.
3026 masm.PushCalleeToken(calleeReg, isConstructing);
3027 }
3028 }
3029
3030 void BaselineCacheIRCompiler::pushStandardArguments(
3031 Register argcReg, Register scratch, Register scratch2, uint32_t argcFixed,
3032 bool isJitCall, bool isConstructing) {
3033 MOZ_ASSERT(enteredStubFrame_);
3034
3035 // The arguments to the call IC were pushed on the stack from left to right,
3036 // meaning that the first argument is at the highest address and the last
3037 // argument is at the lowest address. Our callee needs them to be in the
3038 // opposite order, so we duplicate them now.
3039
3040 bool shouldCopyCallee = !isJitCall;
3041 bool shouldCopyThis = shouldCopyCallee || !isConstructing;
3042 bool shouldCopyNewTarget = isConstructing;
3043 int additionalArgc = shouldCopyCallee + shouldCopyThis + shouldCopyNewTarget;
3044
3045 if (argcFixed < MaxUnrolledArgCopy) {
3046 #ifdef DEBUG
3047 Label ok;
3048 masm.branch32(Assembler::Equal, argcReg, Imm32(argcFixed), &ok);
3049 masm.assumeUnreachable("Invalid argcFixed value");
3050 masm.bind(&ok);
3051 #endif
3052
3053 size_t realArgc = argcFixed + additionalArgc;
3054
3055 if (isJitCall) {
3056 masm.alignJitStackBasedOnNArgs(realArgc,
3057 /*countIncludesThis = */ shouldCopyThis);
3058 }
3059
3060 for (size_t i = 0; i < realArgc; ++i) {
3061 masm.pushValue(Address(
3062 FramePointer, BaselineStubFrameLayout::Size() + i * sizeof(Value)));
3063 }
3064 } else {
3065 MOZ_ASSERT(argcFixed == MaxUnrolledArgCopy);
3066
3067 // argPtr initially points to the last argument. Skip the stub frame.
3068 Register argPtr = scratch2;
3069 Address argAddress(FramePointer, BaselineStubFrameLayout::Size());
3070 masm.computeEffectiveAddress(argAddress, argPtr);
3071
3072 // countReg contains the total number of arguments to copy.
3073 // In addition to the actual arguments, we have to copy hidden arguments.
3074 // We always have to copy |this|.
3075 // If we are constructing, we have to copy |newTarget|.
3076 // If we are not a jit call, we have to copy |callee|.
3077 // We use a scratch register to avoid clobbering argc, which is an input
3078 // reg.
3079 Register countReg = scratch;
3080 masm.add32(Imm32(additionalArgc), argcReg, countReg);
3081
3082 // Align the stack such that the JitFrameLayout is aligned on the
3083 // JitStackAlignment.
3084 if (isJitCall) {
3085 masm.alignJitStackBasedOnNArgs(countReg,
3086 /*countIncludesThis = */ shouldCopyThis);
3087 }
3088
3089 // Push all values, starting at the last one.
3090 Label loop, done;
3091 masm.branchTest32(Assembler::Zero, countReg, countReg, &done);
3092 masm.bind(&loop);
3093 {
3094 masm.pushValue(Address(argPtr, 0));
3095 masm.addPtr(Imm32(sizeof(Value)), argPtr);
3096
3097 masm.branchSub32(Assembler::NonZero, Imm32(1), countReg, &loop);
3098 }
3099 masm.bind(&done);
3100 }
3101 }
3102
3103 void BaselineCacheIRCompiler::pushArrayArguments(Register argcReg,
3104 Register scratch,
3105 Register scratch2,
3106 bool isJitCall,
3107 bool isConstructing) {
3108 MOZ_ASSERT(enteredStubFrame_);
3109
3110 // Pull the array off the stack before aligning.
3111 Register startReg = scratch;
3112 size_t arrayOffset =
3113 (isConstructing * sizeof(Value)) + BaselineStubFrameLayout::Size();
3114 masm.unboxObject(Address(FramePointer, arrayOffset), startReg);
3115 masm.loadPtr(Address(startReg, NativeObject::offsetOfElements()), startReg);
3116
3117 // Align the stack such that the JitFrameLayout is aligned on the
3118 // JitStackAlignment.
3119 if (isJitCall) {
3120 Register alignReg = argcReg;
3121 if (isConstructing) {
3122 // If we are constructing, we must take newTarget into account.
3123 alignReg = scratch2;
3124 masm.computeEffectiveAddress(Address(argcReg, 1), alignReg);
3125 }
3126 masm.alignJitStackBasedOnNArgs(alignReg, /*countIncludesThis =*/false);
3127 }
3128
3129 // Push newTarget, if necessary
3130 if (isConstructing) {
3131 masm.pushValue(Address(FramePointer, BaselineStubFrameLayout::Size()));
3132 }
3133
3134 // Push arguments: set up endReg to point to &array[argc]
3135 Register endReg = scratch2;
3136 BaseValueIndex endAddr(startReg, argcReg);
3137 masm.computeEffectiveAddress(endAddr, endReg);
3138
3139 // Copying pre-decrements endReg by 8 until startReg is reached
3140 Label copyDone;
3141 Label copyStart;
3142 masm.bind(&copyStart);
3143 masm.branchPtr(Assembler::Equal, endReg, startReg, &copyDone);
3144 masm.subPtr(Imm32(sizeof(Value)), endReg);
3145 masm.pushValue(Address(endReg, 0));
3146 masm.jump(&copyStart);
3147 masm.bind(&copyDone);
3148
3149 bool shouldPushCallee = !isJitCall;
3150 bool shouldPushThis = shouldPushCallee || !isConstructing;
3151
3152 if (shouldPushThis) {
3153 size_t thisvOffset = arrayOffset + sizeof(Value);
3154 masm.pushValue(Address(FramePointer, thisvOffset));
3155 }
3156 if (shouldPushCallee) {
3157 size_t calleeOffset = arrayOffset + 2 * sizeof(Value);
3158 masm.pushValue(Address(FramePointer, calleeOffset));
3159 }
3160 }
3161
3162 void BaselineCacheIRCompiler::pushFunApplyNullUndefinedArguments(
3163 Register calleeReg, bool isJitCall) {
3164 // argc is already set to 0, so we just have to push |this| and (for native
3165 // calls) the callee.
3166
3167 MOZ_ASSERT(enteredStubFrame_);
3168
3169 // Align the stack such that the JitFrameLayout is aligned on the
3170 // JitStackAlignment.
3171 if (isJitCall) {
3172 masm.alignJitStackBasedOnNArgs(0, /*countIncludesThis =*/false);
3173 }
3174
3175 // Push |this|.
3176 size_t thisvOffset = BaselineStubFrameLayout::Size() + 1 * sizeof(Value);
3177 masm.pushValue(Address(FramePointer, thisvOffset));
3178
3179 // Push |callee| if needed.
3180 if (!isJitCall) {
3181 masm.Push(TypedOrValueRegister(MIRType::Object, AnyRegister(calleeReg)));
3182 }
3183 }
3184
3185 void BaselineCacheIRCompiler::pushFunCallArguments(
3186 Register argcReg, Register calleeReg, Register scratch, Register scratch2,
3187 uint32_t argcFixed, bool isJitCall) {
3188 if (argcFixed == 0) {
3189 if (isJitCall) {
3190 // Align the stack to 0 args.
3191 masm.alignJitStackBasedOnNArgs(0, /*countIncludesThis = */ false);
3192 }
3193
3194 // Store the new |this|.
3195 masm.pushValue(UndefinedValue());
3196
3197 // Store |callee| if needed.
3198 if (!isJitCall) {
3199 masm.Push(TypedOrValueRegister(MIRType::Object, AnyRegister(calleeReg)));
3200 }
3201 } else if (argcFixed < MaxUnrolledArgCopy) {
3202 // See below for why we subtract 1 from argcFixed.
3203 argcFixed -= 1;
3204 masm.sub32(Imm32(1), argcReg);
3205 pushStandardArguments(argcReg, scratch, scratch2, argcFixed, isJitCall,
3206 /*isConstructing =*/false);
3207 } else {
3208 Label zeroArgs, done;
3209 masm.branchTest32(Assembler::Zero, argcReg, argcReg, &zeroArgs);
3210
3211 // When we call fun_call, the stack looks like the left column (note
3212 // that newTarget will not be present, because fun_call cannot be a
3213 // constructor call):
3214 //
3215 // ***Arguments to fun_call***
3216 // callee (fun_call) ***Arguments to target***
3217 // this (target function) -----> callee
3218 // arg0 (this of target) -----> this
3219 // arg1 (arg0 of target) -----> arg0
3220 // argN (argN-1 of target) -----> arg1
3221 //
3222 // As demonstrated in the right column, this is exactly what we need
3223 // the stack to look like when calling pushStandardArguments for target,
3224 // except with one more argument. If we subtract 1 from argc,
3225 // everything works out correctly.
3226 masm.sub32(Imm32(1), argcReg);
3227
3228 pushStandardArguments(argcReg, scratch, scratch2, argcFixed, isJitCall,
3229 /*isConstructing =*/false);
3230
3231 masm.jump(&done);
3232 masm.bind(&zeroArgs);
3233
3234 // The exception is the case where argc == 0:
3235 //
3236 // ***Arguments to fun_call***
3237 // callee (fun_call) ***Arguments to target***
3238 // this (target function) -----> callee
3239 // <nothing> -----> this
3240 //
3241 // In this case, we push |undefined| for |this|.
3242
3243 if (isJitCall) {
3244 // Align the stack to 0 args.
3245 masm.alignJitStackBasedOnNArgs(0, /*countIncludesThis = */ false);
3246 }
3247
3248 // Store the new |this|.
3249 masm.pushValue(UndefinedValue());
3250
3251 // Store |callee| if needed.
3252 if (!isJitCall) {
3253 masm.Push(TypedOrValueRegister(MIRType::Object, AnyRegister(calleeReg)));
3254 }
3255
3256 masm.bind(&done);
3257 }
3258 }
3259
3260 void BaselineCacheIRCompiler::pushFunApplyArgsObj(Register argcReg,
3261 Register calleeReg,
3262 Register scratch,
3263 Register scratch2,
3264 bool isJitCall) {
3265 MOZ_ASSERT(enteredStubFrame_);
3266
3267 // Load the arguments object off the stack before aligning.
3268 Register argsReg = scratch;
3269 masm.unboxObject(Address(FramePointer, BaselineStubFrameLayout::Size()),
3270 argsReg);
3271
3272 // Align the stack such that the JitFrameLayout is aligned on the
3273 // JitStackAlignment.
3274 if (isJitCall) {
3275 masm.alignJitStackBasedOnNArgs(argcReg, /*countIncludesThis =*/false);
3276 }
3277
3278 // Load ArgumentsData.
3279 masm.loadPrivate(Address(argsReg, ArgumentsObject::getDataSlotOffset()),
3280 argsReg);
3281
3282 // We push the arguments onto the stack last-to-first.
3283 // Compute the bounds of the arguments array.
3284 Register currReg = scratch2;
3285 Address argsStartAddr(argsReg, ArgumentsData::offsetOfArgs());
3286 masm.computeEffectiveAddress(argsStartAddr, argsReg);
3287 BaseValueIndex argsEndAddr(argsReg, argcReg);
3288 masm.computeEffectiveAddress(argsEndAddr, currReg);
3289
3290 // Loop until all arguments have been pushed.
3291 Label done, loop;
3292 masm.bind(&loop);
3293 masm.branchPtr(Assembler::Equal, currReg, argsReg, &done);
3294 masm.subPtr(Imm32(sizeof(Value)), currReg);
3295
3296 Address currArgAddr(currReg, 0);
3297 #ifdef DEBUG
3298 // Arguments are forwarded to the call object if they are closed over.
3299 // In this case, OVERRIDDEN_ELEMENTS_BIT should be set.
3300 Label notForwarded;
3301 masm.branchTestMagic(Assembler::NotEqual, currArgAddr, &notForwarded);
3302 masm.assumeUnreachable("Should have checked for overridden elements");
3303 masm.bind(&notForwarded);
3304 #endif
3305 masm.pushValue(currArgAddr);
3306
3307 masm.jump(&loop);
3308 masm.bind(&done);
3309
3310 // Push arg0 as |this| for call
3311 masm.pushValue(
3312 Address(FramePointer, BaselineStubFrameLayout::Size() + sizeof(Value)));
3313
3314 // Push |callee| if needed.
3315 if (!isJitCall) {
3316 masm.Push(TypedOrValueRegister(MIRType::Object, AnyRegister(calleeReg)));
3317 }
3318 }
3319
3320 void BaselineCacheIRCompiler::pushBoundFunctionArguments(
3321 Register argcReg, Register calleeReg, Register scratch, Register scratch2,
3322 CallFlags flags, uint32_t numBoundArgs, bool isJitCall) {
3323 bool isConstructing = flags.isConstructing();
3324 uint32_t additionalArgc = 1 + isConstructing; // |this| and newTarget
3325
3326 // Calculate total number of Values to push.
3327 Register countReg = scratch;
3328 masm.computeEffectiveAddress(Address(argcReg, numBoundArgs + additionalArgc),
3329 countReg);
3330
3331 // Align the stack such that the JitFrameLayout is aligned on the
3332 // JitStackAlignment.
3333 if (isJitCall) {
3334 masm.alignJitStackBasedOnNArgs(countReg, /*countIncludesThis = */ true);
3335 }
3336
3337 if (isConstructing) {
3338 // Push the bound function's target as newTarget.
3339 Address boundTarget(calleeReg, BoundFunctionObject::offsetOfTargetSlot());
3340 masm.pushValue(boundTarget);
3341 }
3342
3343 // Ensure argPtr initially points to the last argument. Skip the stub frame.
3344 Register argPtr = scratch2;
3345 Address argAddress(FramePointer, BaselineStubFrameLayout::Size());
3346 if (isConstructing) {
3347 // Skip newTarget.
3348 argAddress.offset += sizeof(Value);
3349 }
3350 masm.computeEffectiveAddress(argAddress, argPtr);
3351
3352 // Push all supplied arguments, starting at the last one.
3353 Label loop, done;
3354 masm.branchTest32(Assembler::Zero, argcReg, argcReg, &done);
3355 masm.move32(argcReg, countReg);
3356 masm.bind(&loop);
3357 {
3358 masm.pushValue(Address(argPtr, 0));
3359 masm.addPtr(Imm32(sizeof(Value)), argPtr);
3360
3361 masm.branchSub32(Assembler::NonZero, Imm32(1), countReg, &loop);
3362 }
3363 masm.bind(&done);
3364
3365 // Push the bound arguments, starting at the last one.
3366 constexpr size_t inlineArgsOffset =
3367 BoundFunctionObject::offsetOfFirstInlineBoundArg();
3368 if (numBoundArgs <= BoundFunctionObject::MaxInlineBoundArgs) {
3369 for (size_t i = 0; i < numBoundArgs; i++) {
3370 size_t argIndex = numBoundArgs - i - 1;
3371 Address argAddr(calleeReg, inlineArgsOffset + argIndex * sizeof(Value));
3372 masm.pushValue(argAddr);
3373 }
3374 } else {
3375 masm.unboxObject(Address(calleeReg, inlineArgsOffset), scratch);
3376 masm.loadPtr(Address(scratch, NativeObject::offsetOfElements()), scratch);
3377 for (size_t i = 0; i < numBoundArgs; i++) {
3378 size_t argIndex = numBoundArgs - i - 1;
3379 Address argAddr(scratch, argIndex * sizeof(Value));
3380 masm.pushValue(argAddr);
3381 }
3382 }
3383
3384 if (!isConstructing) {
3385 // Push the bound |this|.
3386 Address boundThis(calleeReg, BoundFunctionObject::offsetOfBoundThisSlot());
3387 masm.pushValue(boundThis);
3388 }
3389 }
3390
3391 bool BaselineCacheIRCompiler::emitCallNativeShared(
3392 NativeCallType callType, ObjOperandId calleeId, Int32OperandId argcId,
3393 CallFlags flags, uint32_t argcFixed, Maybe<bool> ignoresReturnValue,
3394 Maybe<uint32_t> targetOffset, ClearLocalAllocSite clearLocalAllocSite) {
3395 AutoOutputRegister output(*this);
3396 AutoScratchRegisterMaybeOutput scratch(allocator, masm, output);
3397 AutoScratchRegister scratch2(allocator, masm);
3398
3399 Register calleeReg = allocator.useRegister(masm, calleeId);
3400 Register argcReg = allocator.useRegister(masm, argcId);
3401
3402 bool isConstructing = flags.isConstructing();
3403 bool isSameRealm = flags.isSameRealm();
3404
3405 if (!updateArgc(flags, argcReg, scratch)) {
3406 return false;
3407 }
3408
3409 allocator.discardStack(masm);
3410
3411 // Push a stub frame so that we can perform a non-tail call.
3412 // Note that this leaves the return address in TailCallReg.
3413 AutoStubFrame stubFrame(*this);
3414 stubFrame.enter(masm, scratch);
3415
3416 if (!isSameRealm) {
3417 masm.switchToObjectRealm(calleeReg, scratch);
3418 }
3419
3420 pushArguments(argcReg, calleeReg, scratch, scratch2, flags, argcFixed,
3421 /*isJitCall =*/false);
3422
3423 // Native functions have the signature:
3424 //
3425 // bool (*)(JSContext*, unsigned, Value* vp)
3426 //
3427 // Where vp[0] is space for callee/return value, vp[1] is |this|, and vp[2]
3428 // onward are the function arguments.
3429
3430 // Initialize vp.
3431 masm.moveStackPtrTo(scratch2.get());
3432
3433 // Construct a native exit frame.
3434 masm.push(argcReg);
3435
3436 masm.pushFrameDescriptor(FrameType::BaselineStub);
3437 masm.push(ICTailCallReg);
3438 masm.push(FramePointer);
3439 masm.loadJSContext(scratch);
3440 masm.enterFakeExitFrameForNative(scratch, scratch, isConstructing);
3441
3442 // Execute call.
3443 masm.setupUnalignedABICall(scratch);
3444 masm.loadJSContext(scratch);
3445 masm.passABIArg(scratch);
3446 masm.passABIArg(argcReg);
3447 masm.passABIArg(scratch2);
3448
3449 switch (callType) {
3450 case NativeCallType::Native: {
3451 #ifdef JS_SIMULATOR
3452 // The simulator requires VM calls to be redirected to a special
3453 // swi instruction to handle them, so we store the redirected
3454 // pointer in the stub and use that instead of the original one.
3455 // (See CacheIRWriter::callNativeFunction.)
3456 Address redirectedAddr(stubAddress(*targetOffset));
3457 masm.callWithABI(redirectedAddr);
3458 #else
3459 if (*ignoresReturnValue) {
3460 masm.loadPrivate(
3461 Address(calleeReg, JSFunction::offsetOfJitInfoOrScript()),
3462 calleeReg);
3463 masm.callWithABI(
3464 Address(calleeReg, JSJitInfo::offsetOfIgnoresReturnValueNative()));
3465 } else {
3466 // This depends on the native function pointer being stored unchanged as
3467 // a PrivateValue.
3468 masm.callWithABI(Address(calleeReg, JSFunction::offsetOfNativeOrEnv()));
3469 }
3470 #endif
3471 } break;
3472 case NativeCallType::ClassHook: {
3473 Address nativeAddr(stubAddress(*targetOffset));
3474 masm.callWithABI(nativeAddr);
3475 } break;
3476 }
3477
3478 // Test for failure.
3479 masm.branchIfFalseBool(ReturnReg, masm.exceptionLabel());
3480
3481 // Load the return value.
3482 masm.loadValue(
3483 Address(masm.getStackPointer(), NativeExitFrameLayout::offsetOfResult()),
3484 output.valueReg());
3485
3486 stubFrame.leave(masm);
3487
3488 if (!isSameRealm) {
3489 masm.switchToBaselineFrameRealm(scratch2);
3490 }
3491
3492 // We will also unilaterally clear this on exception handling.
3493 if (clearLocalAllocSite == ClearLocalAllocSite::Yes) {
3494 masm.storeLocalAllocSite(ImmPtr(nullptr), scratch2);
3495 }
3496
3497 return true;
3498 }
3499
3500 void BaselineCacheIRCompiler::loadAllocSiteIntoContext(uint32_t siteOffset) {
3501 AutoScratchRegister scratch(allocator, masm);
3502 AutoScratchRegister site(allocator, masm);
3503
3504 StubFieldOffset siteField(siteOffset, StubField::Type::AllocSite);
3505 emitLoadStubField(siteField, site);
3506
3507 masm.storeLocalAllocSite(site.get(), scratch);
3508 }
3509
3510 #ifdef JS_SIMULATOR
3511 bool BaselineCacheIRCompiler::emitCallNativeFunction(ObjOperandId calleeId,
3512 Int32OperandId argcId,
3513 CallFlags flags,
3514 uint32_t argcFixed,
3515 uint32_t targetOffset) {
3516 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
3517 Maybe<bool> ignoresReturnValue;
3518 Maybe<uint32_t> targetOffset_ = mozilla::Some(targetOffset);
3519 return emitCallNativeShared(NativeCallType::Native, calleeId, argcId, flags,
3520 argcFixed, ignoresReturnValue, targetOffset_);
3521 }
3522
3523 bool BaselineCacheIRCompiler::emitCallDOMFunction(
3524 ObjOperandId calleeId, Int32OperandId argcId, ObjOperandId thisObjId,
3525 CallFlags flags, uint32_t argcFixed, uint32_t targetOffset) {
3526 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
3527 Maybe<bool> ignoresReturnValue;
3528 Maybe<uint32_t> targetOffset_ = mozilla::Some(targetOffset);
3529 return emitCallNativeShared(NativeCallType::Native, calleeId, argcId, flags,
3530 argcFixed, ignoresReturnValue, targetOffset_);
3531 }
3532
3533 bool BaselineCacheIRCompiler::emitCallDOMFunctionWithAllocSite(
3534 ObjOperandId calleeId, Int32OperandId argcId, ObjOperandId thisObjId,
3535 CallFlags flags, uint32_t argcFixed, uint32_t siteOffset,
3536 uint32_t targetOffset) {
3537 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
3538 loadAllocSiteIntoContext(siteOffset);
3539 Maybe<bool> ignoresReturnValue;
3540 Maybe<uint32_t> targetOffset_ = mozilla::Some(targetOffset);
3541 return emitCallNativeShared(NativeCallType::Native, calleeId, argcId, flags,
3542 argcFixed, ignoresReturnValue, targetOffset_,
3543 ClearLocalAllocSite::Yes);
3544 }
3545 #else
3546 bool BaselineCacheIRCompiler::emitCallNativeFunction(ObjOperandId calleeId,
3547 Int32OperandId argcId,
3548 CallFlags flags,
3549 uint32_t argcFixed,
3550 bool ignoresReturnValue) {
3551 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
3552 Maybe<bool> ignoresReturnValue_ = mozilla::Some(ignoresReturnValue);
3553 Maybe<uint32_t> targetOffset;
3554 return emitCallNativeShared(NativeCallType::Native, calleeId, argcId, flags,
3555 argcFixed, ignoresReturnValue_, targetOffset);
3556 }
3557
3558 bool BaselineCacheIRCompiler::emitCallDOMFunction(ObjOperandId calleeId,
3559 Int32OperandId argcId,
3560 ObjOperandId thisObjId,
3561 CallFlags flags,
3562 uint32_t argcFixed) {
3563 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
3564 Maybe<bool> ignoresReturnValue = mozilla::Some(false);
3565 Maybe<uint32_t> targetOffset;
3566 return emitCallNativeShared(NativeCallType::Native, calleeId, argcId, flags,
3567 argcFixed, ignoresReturnValue, targetOffset);
3568 }
3569
3570 bool BaselineCacheIRCompiler::emitCallDOMFunctionWithAllocSite(
3571 ObjOperandId calleeId, Int32OperandId argcId, ObjOperandId thisObjId,
3572 CallFlags flags, uint32_t argcFixed, uint32_t siteOffset) {
3573 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
3574 loadAllocSiteIntoContext(siteOffset);
3575 Maybe<bool> ignoresReturnValue = mozilla::Some(false);
3576 Maybe<uint32_t> targetOffset;
3577 return emitCallNativeShared(NativeCallType::Native, calleeId, argcId, flags,
3578 argcFixed, ignoresReturnValue, targetOffset,
3579 ClearLocalAllocSite::Yes);
3580 }
3581 #endif
3582
3583 bool BaselineCacheIRCompiler::emitCallClassHook(ObjOperandId calleeId,
3584 Int32OperandId argcId,
3585 CallFlags flags,
3586 uint32_t argcFixed,
3587 uint32_t targetOffset) {
3588 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
3589 Maybe<bool> ignoresReturnValue;
3590 Maybe<uint32_t> targetOffset_ = mozilla::Some(targetOffset);
3591 return emitCallNativeShared(NativeCallType::ClassHook, calleeId, argcId,
3592 flags, argcFixed, ignoresReturnValue,
3593 targetOffset_);
3594 }
3595
3596 // Helper function for loading call arguments from the stack. Loads
3597 // and unboxes an object from a specific slot.
3598 void BaselineCacheIRCompiler::loadStackObject(ArgumentKind kind,
3599 CallFlags flags, Register argcReg,
3600 Register dest,
3601 uint32_t extraArgs) {
3602 MOZ_ASSERT(enteredStubFrame_);
3603
3604 bool addArgc = false;
3605 int32_t slotIndex = GetIndexOfArgument(kind, flags, &addArgc);
3606
3607 if (addArgc) {
3608 int32_t slotOffset = (slotIndex - extraArgs) * sizeof(JS::Value) +
3609 BaselineStubFrameLayout::Size();
3610 BaseValueIndex slotAddr(FramePointer, argcReg, slotOffset);
3611 masm.unboxObject(slotAddr, dest);
3612 } else {
3613 int32_t slotOffset =
3614 slotIndex * sizeof(JS::Value) + BaselineStubFrameLayout::Size();
3615 Address slotAddr(FramePointer, slotOffset);
3616 masm.unboxObject(slotAddr, dest);
3617 }
3618 }
3619
3620 /*
3621 * Scripted constructors require a |this| object to be created prior to the
3622 * call. This is called after we have pushed the formal arguments, but before
3623 * pushing the callee token. When this is called, argcReg must contain the
3624 * number of actual arguments (including bound or spread arguments; not
3625 * including `undef` pushed in cases of argument underflow). calleeReg should
3626 * contain the actual callee.
3627 */
3628 void BaselineCacheIRCompiler::createThis(Register argcReg, Register calleeReg,
3629 Register scratch, Register scratch2,
3630 CallFlags flags,
3631 Maybe<uint32_t> numBoundArgs) {
3632 MOZ_ASSERT(flags.isConstructing());
3633 bool isBoundFunction = numBoundArgs.isSome();
3634
3635 // Derived constructors don't allocate a `this` object. They instead call
3636 // `super`, and the base class constructor will allocate `this`.
3637 if (flags.needsUninitializedThis()) {
3638 masm.Push(MagicValue(JS_UNINITIALIZED_LEXICAL));
3639 return;
3640 }
3641
3642 // Save a reference to the start of the arguments, so that we can root
3643 // them in CreateThisFromIC.
3644 Register argvReg = scratch2;
3645 masm.moveStackPtrTo(argvReg);
3646
3647 // Save live registers that don't have to be traced.
3648 LiveGeneralRegisterSet liveNonGCRegs;
3649 liveNonGCRegs.add(argcReg);
3650 masm.PushRegsInMask(liveNonGCRegs);
3651
3652 // CreateThis takes two arguments: callee, and newTarget.
3653
3654 // Push argv/argc for rooting in CreateThisFromIC
3655 masm.push(argcReg);
3656 masm.push(argvReg);
3657
3658 if (isBoundFunction) {
3659 // Push the bound function's target as callee and newTarget.
3660 masm.push(calleeReg);
3661 masm.push(calleeReg);
3662 } else {
3663 // Push newTarget:
3664 loadStackObject(ArgumentKind::NewTarget, flags, argcReg, scratch);
3665 masm.push(scratch);
3666
3667 // Push callee.
3668 masm.push(calleeReg);
3669 }
3670
3671 // Call CreateThisFromIC.
3672 using Fn =
3673 bool (*)(JSContext*, HandleObject, HandleObject, Value*, uint32_t,
3674 MutableHandleValue);
3675 callVM<Fn, CreateThisFromIC>(masm);
3676
3677 #ifdef DEBUG
3678 Label createdThisOK;
3679 masm.branchTestObject(Assembler::Equal, JSReturnOperand, &createdThisOK);
3680 masm.branchTestMagic(Assembler::Equal, JSReturnOperand, &createdThisOK);
3681 masm.assumeUnreachable(
3682 "The return of CreateThis must be an object or uninitialized.");
3683 masm.bind(&createdThisOK);
3684 #endif
3685
3686 // Restore saved registers.
3687 masm.PopRegsInMask(liveNonGCRegs);
3688
3689 // Restore ICStubReg. The stub might have been moved if CreateThisFromIC
3690 // discarded JIT code.
3691 Address stubAddr(FramePointer, BaselineStubFrameLayout::ICStubOffsetFromFP);
3692 masm.loadPtr(stubAddr, ICStubReg);
3693
3694 // Push |this|.
3695 MOZ_ASSERT(!liveNonGCRegs.aliases(JSReturnOperand));
3696 masm.Push(TypedOrValueRegister(JSReturnOperand));
3697
3698 // Restore calleeReg. CreateThisFromIC may trigger a GC, so we reload the
3699 // callee from the caller's frame (which is traced) instead of spilling it to
3700 // the stack.
3701 if (isBoundFunction) {
3702 // Load the callee (which is a bound function).
3703 // At this point, argcReg is the number of actual arguments being passed.
3704 // For bound functions, this includes bound arguments. However, to compute
3705 // the address of `callee` in the caller's frame, we need to know how many
3706 // arguments were passed by the caller. This is argcReg - numBoundArgs.
3707 // We pass in `numBoundArgs` so that loadStackObject can adjust accordingly.
3708 loadStackObject(ArgumentKind::Callee, flags, argcReg, calleeReg,
3709 *numBoundArgs);
3710
3711 // Load the target JSFunction.
3712 Address boundTarget(calleeReg, BoundFunctionObject::offsetOfTargetSlot());
3713 masm.unboxObject(boundTarget, calleeReg);
3714 } else {
3715 loadStackObject(ArgumentKind::Callee, flags, argcReg, calleeReg);
3716 }
3717 }
3718
3719 void BaselineCacheIRCompiler::updateReturnValue() {
3720 Label skipThisReplace;
3721 masm.branchTestObject(Assembler::Equal, JSReturnOperand, &skipThisReplace);
3722
3723 // If a constructor does not explicitly return an object, the return value
3724 // of the constructor is |this|. We load it out of the baseline stub frame.
3725
3726 // At this point, the stack looks like this:
3727 // newTarget
3728 // ArgN
3729 // ...
3730 // Arg0
3731 // ThisVal <---- We want this value.
3732 // Callee token | Skip two stack slots.
3733 // Frame descriptor v
3734 // [Top of stack]
3735 size_t thisvOffset =
3736 JitFrameLayout::offsetOfThis() - JitFrameLayout::bytesPoppedAfterCall();
3737 Address thisAddress(masm.getStackPointer(), thisvOffset);
3738 masm.loadValue(thisAddress, JSReturnOperand);
3739
3740 #ifdef DEBUG
3741 masm.branchTestObject(Assembler::Equal, JSReturnOperand, &skipThisReplace);
3742 masm.assumeUnreachable("Return of constructing call should be an object.");
3743 #endif
3744 masm.bind(&skipThisReplace);
3745 }
3746
3747 bool BaselineCacheIRCompiler::emitCallScriptedFunction(ObjOperandId calleeId,
3748 Int32OperandId argcId,
3749 CallFlags flags,
3750 uint32_t argcFixed) {
3751 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
3752 AutoOutputRegister output(*this);
3753 AutoScratchRegisterMaybeOutput scratch(allocator, masm, output);
3754 AutoScratchRegister scratch2(allocator, masm);
3755
3756 Register calleeReg = allocator.useRegister(masm, calleeId);
3757 Register argcReg = allocator.useRegister(masm, argcId);
3758
3759 bool isConstructing = flags.isConstructing();
3760 bool isSameRealm = flags.isSameRealm();
3761
3762 if (!updateArgc(flags, argcReg, scratch)) {
3763 return false;
3764 }
3765
3766 allocator.discardStack(masm);
3767
3768 // Push a stub frame so that we can perform a non-tail call.
3769 AutoStubFrame stubFrame(*this);
3770 stubFrame.enter(masm, scratch);
3771
3772 if (!isSameRealm) {
3773 masm.switchToObjectRealm(calleeReg, scratch);
3774 }
3775
3776 pushArguments(argcReg, calleeReg, scratch, scratch2, flags, argcFixed,
3777 /*isJitCall =*/true);
3778
3779 // Load the start of the target JitCode.
3780 Register code = scratch2;
3781 masm.loadJitCodeRaw(calleeReg, code);
3782
3783 // Note that we use Push, not push, so that callJit will align the stack
3784 // properly on ARM.
3785 masm.PushFrameDescriptorForJitCall(FrameType::BaselineStub, argcReg, scratch);
3786
3787 // Handle arguments underflow.
3788 Label noUnderflow;
3789 masm.loadFunctionArgCount(calleeReg, calleeReg);
3790 masm.branch32(Assembler::AboveOrEqual, argcReg, calleeReg, &noUnderflow);
3791 {
3792 // Call the arguments rectifier.
3793 TrampolinePtr argumentsRectifier =
3794 cx_->runtime()->jitRuntime()->getArgumentsRectifier();
3795 masm.movePtr(argumentsRectifier, code);
3796 }
3797
3798 masm.bind(&noUnderflow);
3799 masm.callJit(code);
3800
3801 // If this is a constructing call, and the callee returns a non-object,
3802 // replace it with the |this| object passed in.
3803 if (isConstructing) {
3804 updateReturnValue();
3805 }
3806
3807 stubFrame.leave(masm);
3808
3809 if (!isSameRealm) {
3810 masm.switchToBaselineFrameRealm(scratch2);
3811 }
3812
3813 return true;
3814 }
3815
3816 bool BaselineCacheIRCompiler::emitCallWasmFunction(
3817 ObjOperandId calleeId, Int32OperandId argcId, CallFlags flags,
3818 uint32_t argcFixed, uint32_t funcExportOffset, uint32_t instanceOffset) {
3819 return emitCallScriptedFunction(calleeId, argcId, flags, argcFixed);
3820 }
3821
3822 bool BaselineCacheIRCompiler::emitCallInlinedFunction(ObjOperandId calleeId,
3823 Int32OperandId argcId,
3824 uint32_t icScriptOffset,
3825 CallFlags flags,
3826 uint32_t argcFixed) {
3827 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
3828 AutoOutputRegister output(*this);
3829 AutoScratchRegisterMaybeOutput scratch(allocator, masm, output);
3830 AutoScratchRegisterMaybeOutputType scratch2(allocator, masm, output);
3831 AutoScratchRegister codeReg(allocator, masm);
3832
3833 Register calleeReg = allocator.useRegister(masm, calleeId);
3834 Register argcReg = allocator.useRegister(masm, argcId);
3835
3836 bool isConstructing = flags.isConstructing();
3837 bool isSameRealm = flags.isSameRealm();
3838
3839 FailurePath* failure;
3840 if (!addFailurePath(&failure)) {
3841 return false;
3842 }
3843
3844 masm.loadBaselineJitCodeRaw(calleeReg, codeReg, failure->label());
3845
3846 if (!updateArgc(flags, argcReg, scratch)) {
3847 return false;
3848 }
3849
3850 allocator.discardStack(masm);
3851
3852 // Push a stub frame so that we can perform a non-tail call.
3853 AutoStubFrame stubFrame(*this);
3854 stubFrame.enter(masm, scratch);
3855
3856 if (!isSameRealm) {
3857 masm.switchToObjectRealm(calleeReg, scratch);
3858 }
3859
3860 pushArguments(argcReg, calleeReg, scratch, scratch2, flags, argcFixed,
3861 /*isJitCall =*/true);
3862
3863 Label baselineScriptDiscarded;
3864 if (isConstructing) {
3865 // CreateThisFromIC may trigger a GC and discard the BaselineScript.
3866 // We have already called discardStack, so we can't use a FailurePath.
3867 // Instead, we skip storing the ICScript in the JSContext and use a
3868 // normal non-inlined call.
3869 masm.loadBaselineJitCodeRaw(calleeReg, codeReg, &baselineScriptDiscarded);
3870 }
3871
3872 // Store icScript in the context.
3873 Address icScriptAddr(stubAddress(icScriptOffset));
3874 masm.loadPtr(icScriptAddr, scratch);
3875 masm.storeICScriptInJSContext(scratch);
3876
3877 if (isConstructing) {
3878 Label skip;
3879 masm.jump(&skip);
3880 masm.bind(&baselineScriptDiscarded);
3881 masm.loadJitCodeRaw(calleeReg, codeReg);
3882 masm.bind(&skip);
3883 }
3884
3885 // Note that we use Push, not push, so that callJit will align the stack
3886 // properly on ARM.
3887 masm.PushFrameDescriptorForJitCall(FrameType::BaselineStub, argcReg, scratch);
3888
3889 // Handle arguments underflow.
3890 Label noUnderflow;
3891 masm.loadFunctionArgCount(calleeReg, calleeReg);
3892 masm.branch32(Assembler::AboveOrEqual, argcReg, calleeReg, &noUnderflow);
3893
3894 // Call the trial-inlining arguments rectifier.
3895 ArgumentsRectifierKind kind = ArgumentsRectifierKind::TrialInlining;
3896 TrampolinePtr argumentsRectifier =
3897 cx_->runtime()->jitRuntime()->getArgumentsRectifier(kind);
3898 masm.movePtr(argumentsRectifier, codeReg);
3899
3900 masm.bind(&noUnderflow);
3901 masm.callJit(codeReg);
3902
3903 // If this is a constructing call, and the callee returns a non-object,
3904 // replace it with the |this| object passed in.
3905 if (isConstructing) {
3906 updateReturnValue();
3907 }
3908
3909 stubFrame.leave(masm);
3910
3911 if (!isSameRealm) {
3912 masm.switchToBaselineFrameRealm(codeReg);
3913 }
3914
3915 return true;
3916 }
3917
3918 #ifdef JS_PUNBOX64
3919 template <typename IdType>
3920 bool BaselineCacheIRCompiler::emitCallScriptedProxyGetShared(
3921 ValOperandId targetId, ObjOperandId receiverId, ObjOperandId handlerId,
3922 ObjOperandId trapId, IdType id, uint32_t nargsAndFlags) {
3923 Register handler = allocator.useRegister(masm, handlerId);
3924 ValueOperand target = allocator.useValueRegister(masm, targetId);
3925 Register receiver = allocator.useRegister(masm, receiverId);
3926 Register callee = allocator.useRegister(masm, trapId);
3927 ValueOperand idVal;
3928 if constexpr (std::is_same_v<IdType, ValOperandId>) {
3929 idVal = allocator.useValueRegister(masm, id);
3930 }
3931
3932 AutoScratchRegister code(allocator, masm);
3933
3934 AutoScratchRegister scratch(allocator, masm);
3935 ValueOperand scratchVal(scratch);
3936
3937 allocator.discardStack(masm);
3938
3939 AutoStubFrame stubFrame(*this);
3940 stubFrame.enter(masm, scratch);
3941
3942 // We need to keep the target around to potentially validate the proxy result
3943 stubFrame.storeTracedValue(masm, target);
3944 if constexpr (std::is_same_v<IdType, ValOperandId>) {
3945 stubFrame.storeTracedValue(masm, idVal);
3946 } else {
3947 // We need to either trace the id here or grab the ICStubReg back from
3948 // FramePointer + sizeof(void*) after the call in order to load it again.
3949 // We elect to do this because it unifies the code path after the call.
3950 Address idAddr(stubAddress(id));
3951 masm.loadPtr(idAddr, scratch);
3952 masm.tagValue(JSVAL_TYPE_STRING, scratch, scratchVal);
3953 stubFrame.storeTracedValue(masm, scratchVal);
3954 }
3955
3956 uint16_t nargs = nargsAndFlags >> JSFunction::ArgCountShift;
3957 masm.alignJitStackBasedOnNArgs(std::max(uint16_t(3), nargs),
3958 /*countIncludesThis = */ false);
3959 for (size_t i = 3; i < nargs; i++) {
3960 masm.Push(UndefinedValue());
3961 }
3962
3963 masm.tagValue(JSVAL_TYPE_OBJECT, receiver, scratchVal);
3964 masm.Push(scratchVal);
3965
3966 if constexpr (std::is_same_v<IdType, ValOperandId>) {
3967 masm.Push(idVal);
3968 } else {
3969 stubFrame.loadTracedValue(masm, 1, scratchVal);
3970 masm.Push(scratchVal);
3971 }
3972
3973 masm.Push(target);
3974
3975 masm.tagValue(JSVAL_TYPE_OBJECT, handler, scratchVal);
3976 masm.Push(scratchVal);
3977
3978 masm.loadJitCodeRaw(callee, code);
3979
3980 masm.Push(callee);
3981 masm.PushFrameDescriptorForJitCall(FrameType::BaselineStub, 3);
3982
3983 masm.callJit(code);
3984
3985 Register scratch2 = code;
3986
3987 Label success;
3988 stubFrame.loadTracedValue(masm, 0, scratchVal);
3989 masm.unboxObject(scratchVal, scratch);
3990 masm.branchTestObjectNeedsProxyResultValidation(Assembler::Zero, scratch,
3991 scratch2, &success);
3992 ValueOperand scratchVal2(scratch2);
3993 stubFrame.loadTracedValue(masm, 1, scratchVal2);
3994 masm.Push(JSReturnOperand);
3995 masm.Push(scratchVal2);
3996 masm.Push(scratch);
3997 using Fn = bool (*)(JSContext*, HandleObject, HandleValue, HandleValue,
3998 MutableHandleValue);
3999 callVM<Fn, CheckProxyGetByValueResult>(masm);
4000
4001 masm.bind(&success);
4002
4003 stubFrame.leave(masm);
4004
4005 return true;
4006 }
4007
4008 bool BaselineCacheIRCompiler::emitCallScriptedProxyGetResult(
4009 ValOperandId targetId, ObjOperandId receiverId, ObjOperandId handlerId,
4010 ObjOperandId trapId, uint32_t idOffset, uint32_t nargsAndFlags) {
4011 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
4012
4013 return emitCallScriptedProxyGetShared(targetId, receiverId, handlerId, trapId,
4014 idOffset, nargsAndFlags);
4015 }
4016
4017 bool BaselineCacheIRCompiler::emitCallScriptedProxyGetByValueResult(
4018 ValOperandId targetId, ObjOperandId receiverId, ObjOperandId handlerId,
4019 ValOperandId idId, ObjOperandId trapId, uint32_t nargsAndFlags) {
4020 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
4021
4022 return emitCallScriptedProxyGetShared(targetId, receiverId, handlerId, trapId,
4023 idId, nargsAndFlags);
4024 }
4025 #endif
4026
4027 bool BaselineCacheIRCompiler::emitCallBoundScriptedFunction(
4028 ObjOperandId calleeId, ObjOperandId targetId, Int32OperandId argcId,
4029 CallFlags flags, uint32_t numBoundArgs) {
4030 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
4031
4032 AutoOutputRegister output(*this);
4033 AutoScratchRegisterMaybeOutput scratch(allocator, masm, output);
4034 AutoScratchRegister scratch2(allocator, masm);
4035
4036 Register calleeReg = allocator.useRegister(masm, calleeId);
4037 Register argcReg = allocator.useRegister(masm, argcId);
4038
4039 bool isConstructing = flags.isConstructing();
4040 bool isSameRealm = flags.isSameRealm();
4041
4042 allocator.discardStack(masm);
4043
4044 // Push a stub frame so that we can perform a non-tail call.
4045 AutoStubFrame stubFrame(*this);
4046 stubFrame.enter(masm, scratch);
4047
4048 // Push all arguments, including |this|.
4049 pushBoundFunctionArguments(argcReg, calleeReg, scratch, scratch2, flags,
4050 numBoundArgs, /* isJitCall = */ true);
4051
4052 // Load the target JSFunction.
4053 Address boundTarget(calleeReg, BoundFunctionObject::offsetOfTargetSlot());
4054 masm.unboxObject(boundTarget, calleeReg);
4055
4056 if (!isSameRealm) {
4057 masm.switchToObjectRealm(calleeReg, scratch);
4058 }
4059
4060 // Update argc.
4061 masm.add32(Imm32(numBoundArgs), argcReg);
4062
4063 if (isConstructing) {
4064 createThis(argcReg, calleeReg, scratch, scratch2, flags,
4065 mozilla::Some(numBoundArgs));
4066 }
4067
4068 // Load the start of the target JitCode.
4069 Register code = scratch2;
4070 masm.loadJitCodeRaw(calleeReg, code);
4071
4072 // Note that we use Push, not push, so that callJit will align the stack
4073 // properly on ARM.
4074 masm.PushCalleeToken(calleeReg, isConstructing);
4075 masm.PushFrameDescriptorForJitCall(FrameType::BaselineStub, argcReg, scratch);
4076
4077 // Handle arguments underflow.
4078 Label noUnderflow;
4079 masm.loadFunctionArgCount(calleeReg, calleeReg);
4080 masm.branch32(Assembler::AboveOrEqual, argcReg, calleeReg, &noUnderflow);
4081 {
4082 // Call the arguments rectifier.
4083 TrampolinePtr argumentsRectifier =
4084 cx_->runtime()->jitRuntime()->getArgumentsRectifier();
4085 masm.movePtr(argumentsRectifier, code);
4086 }
4087
4088 masm.bind(&noUnderflow);
4089 masm.callJit(code);
4090
4091 if (isConstructing) {
4092 updateReturnValue();
4093 }
4094
4095 stubFrame.leave(masm);
4096
4097 if (!isSameRealm) {
4098 masm.switchToBaselineFrameRealm(scratch2);
4099 }
4100
4101 return true;
4102 }
4103
4104 bool BaselineCacheIRCompiler::emitNewArrayObjectResult(uint32_t arrayLength,
4105 uint32_t shapeOffset,
4106 uint32_t siteOffset) {
4107 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
4108
4109 gc::AllocKind allocKind = GuessArrayGCKind(arrayLength);
4110 MOZ_ASSERT(gc::GetObjectFinalizeKind(&ArrayObject::class_) ==
4111 gc::FinalizeKind::None);
4112 MOZ_ASSERT(!IsFinalizedKind(allocKind));
4113
4114 uint32_t slotCount = GetGCKindSlots(allocKind);
4115 MOZ_ASSERT(slotCount >= ObjectElements::VALUES_PER_HEADER);
4116 uint32_t arrayCapacity = slotCount - ObjectElements::VALUES_PER_HEADER;
4117
4118 AutoOutputRegister output(*this);
4119 AutoScratchRegister result(allocator, masm);
4120 AutoScratchRegister scratch(allocator, masm);
4121 AutoScratchRegister site(allocator, masm);
4122 AutoScratchRegisterMaybeOutput shape(allocator, masm, output);
4123
4124 Address shapeAddr(stubAddress(shapeOffset));
4125 masm.loadPtr(shapeAddr, shape);
4126
4127 Address siteAddr(stubAddress(siteOffset));
4128 masm.loadPtr(siteAddr, site);
4129
4130 allocator.discardStack(masm);
4131
4132 Label done;
4133 Label fail;
4134
4135 masm.createArrayWithFixedElements(
4136 result, shape, scratch, InvalidReg, arrayLength, arrayCapacity, 0, 0,
4137 allocKind, gc::Heap::Default, &fail, AllocSiteInput(site));
4138 masm.jump(&done);
4139
4140 {
4141 masm.bind(&fail);
4142
4143 // We get here if the nursery is full (unlikely) but also for tenured
4144 // allocations if the current arena is full and we need to allocate a new
4145 // one (fairly common).
4146
4147 AutoStubFrame stubFrame(*this);
4148 stubFrame.enter(masm, scratch);
4149
4150 masm.Push(site);
4151 masm.Push(Imm32(int32_t(allocKind)));
4152 masm.Push(Imm32(arrayLength));
4153
4154 using Fn =
4155 ArrayObject* (*)(JSContext*, uint32_t, gc::AllocKind, gc::AllocSite*);
4156 callVM<Fn, NewArrayObjectBaselineFallback>(masm);
4157
4158 stubFrame.leave(masm);
4159 masm.storeCallPointerResult(result);
4160 }
4161
4162 masm.bind(&done);
4163 masm.tagValue(JSVAL_TYPE_OBJECT, result, output.valueReg());
4164 return true;
4165 }
4166
4167 bool BaselineCacheIRCompiler::emitNewPlainObjectResult(uint32_t numFixedSlots,
4168 uint32_t numDynamicSlots,
4169 gc::AllocKind allocKind,
4170 uint32_t shapeOffset,
4171 uint32_t siteOffset) {
4172 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
4173
4174 AutoOutputRegister output(*this);
4175 AutoScratchRegister obj(allocator, masm);
4176 AutoScratchRegister scratch(allocator, masm);
4177 AutoScratchRegister site(allocator, masm);
4178 AutoScratchRegisterMaybeOutput shape(allocator, masm, output);
4179
4180 Address shapeAddr(stubAddress(shapeOffset));
4181 masm.loadPtr(shapeAddr, shape);
4182
4183 Address siteAddr(stubAddress(siteOffset));
4184 masm.loadPtr(siteAddr, site);
4185
4186 allocator.discardStack(masm);
4187
4188 Label done;
4189 Label fail;
4190
4191 masm.createPlainGCObject(obj, shape, scratch, shape, numFixedSlots,
4192 numDynamicSlots, allocKind, gc::Heap::Default, &fail,
4193 AllocSiteInput(site));
4194 masm.jump(&done);
4195
4196 {
4197 masm.bind(&fail);
4198
4199 // We get here if the nursery is full (unlikely) but also for tenured
4200 // allocations if the current arena is full and we need to allocate a new
4201 // one (fairly common).
4202
4203 AutoStubFrame stubFrame(*this);
4204 stubFrame.enter(masm, scratch);
4205
4206 masm.Push(site);
4207 masm.Push(Imm32(int32_t(allocKind)));
4208 masm.loadPtr(shapeAddr, shape); // This might have been overwritten.
4209 masm.Push(shape);
4210
4211 using Fn = JSObject* (*)(JSContext*, Handle<SharedShape*>, gc::AllocKind,
4212 gc::AllocSite*);
4213 callVM<Fn, NewPlainObjectBaselineFallback>(masm);
4214
4215 stubFrame.leave(masm);
4216 masm.storeCallPointerResult(obj);
4217 }
4218
4219 masm.bind(&done);
4220 masm.tagValue(JSVAL_TYPE_OBJECT, obj, output.valueReg());
4221 return true;
4222 }
4223
4224 bool BaselineCacheIRCompiler::emitNewFunctionCloneResult(
4225 uint32_t canonicalOffset, gc::AllocKind allocKind, uint32_t siteOffset) {
4226 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
4227
4228 AutoOutputRegister output(*this);
4229 AutoScratchRegisterMaybeOutput result(allocator, masm, output);
4230 AutoScratchRegisterMaybeOutputType site(allocator, masm, output);
4231 AutoScratchRegister canonical(allocator, masm);
4232 AutoScratchRegister envChain(allocator, masm);
4233 AutoScratchRegister scratch(allocator, masm);
4234 MOZ_ASSERT(result.get() != site.get());
4235
4236 // Load the canonical function and the frame's environment chain.
4237 masm.loadPtr(stubAddress(canonicalOffset), canonical);
4238 Address envAddr(baselineFrameReg_,
4239 BaselineFrame::reverseOffsetOfEnvironmentChain());
4240 masm.loadPtr(envAddr, envChain);
4241
4242 Address siteAddr(stubAddress(siteOffset));
4243 masm.loadPtr(siteAddr, site);
4244
4245 allocator.discardStack(masm);
4246
4247 // Try to allocate a new function object in JIT code.
4248 Label done, fail;
4249
4250 masm.createFunctionClone(result, canonical, envChain, scratch, allocKind,
4251 &fail, AllocSiteInput(site));
4252 masm.jump(&done);
4253
4254 {
4255 masm.bind(&fail);
4256
4257 AutoStubFrame stubFrame(*this);
4258 stubFrame.enter(masm, scratch);
4259
4260 masm.Push(site);
4261 masm.Push(envChain);
4262 masm.Push(canonical);
4263
4264 using Fn =
4265 JSObject* (*)(JSContext*, HandleFunction, HandleObject, gc::AllocSite*);
4266 callVM<Fn, js::LambdaBaselineFallback>(masm);
4267
4268 stubFrame.leave(masm);
4269 masm.storeCallPointerResult(result);
4270 }
4271
4272 masm.bind(&done);
4273 masm.tagValue(JSVAL_TYPE_OBJECT, result, output.valueReg());
4274 return true;
4275 }
4276
4277 bool BaselineCacheIRCompiler::emitBindFunctionResult(
4278 ObjOperandId targetId, uint32_t argc, uint32_t templateObjectOffset) {
4279 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
4280
4281 AutoOutputRegister output(*this);
4282 AutoScratchRegister scratch(allocator, masm);
4283
4284 Register target = allocator.useRegister(masm, targetId);
4285
4286 allocator.discardStack(masm);
4287
4288 AutoStubFrame stubFrame(*this);
4289 stubFrame.enter(masm, scratch);
4290
4291 // Push the arguments in reverse order.
4292 for (uint32_t i = 0; i < argc; i++) {
4293 Address argAddress(FramePointer,
4294 BaselineStubFrameLayout::Size() + i * sizeof(Value));
4295 masm.pushValue(argAddress);
4296 }
4297 masm.moveStackPtrTo(scratch.get());
4298
4299 masm.Push(ImmWord(0)); // nullptr for maybeBound
4300 masm.Push(Imm32(argc));
4301 masm.Push(scratch);
4302 masm.Push(target);
4303
4304 using Fn = BoundFunctionObject* (*)(JSContext*, Handle<JSObject*>, Value*,
4305 uint32_t, Handle<BoundFunctionObject*>);
4306 callVM<Fn, BoundFunctionObject::functionBindImpl>(masm);
4307
4308 stubFrame.leave(masm);
4309 masm.storeCallPointerResult(scratch);
4310
4311 masm.tagValue(JSVAL_TYPE_OBJECT, scratch, output.valueReg());
4312 return true;
4313 }
4314
4315 bool BaselineCacheIRCompiler::emitSpecializedBindFunctionResult(
4316 ObjOperandId targetId, uint32_t argc, uint32_t templateObjectOffset) {
4317 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
4318
4319 AutoOutputRegister output(*this);
4320 AutoScratchRegisterMaybeOutput scratch1(allocator, masm);
4321 AutoScratchRegister scratch2(allocator, masm);
4322
4323 Register target = allocator.useRegister(masm, targetId);
4324
4325 StubFieldOffset objectField(templateObjectOffset, StubField::Type::JSObject);
4326 emitLoadStubField(objectField, scratch2);
4327
4328 allocator.discardStack(masm);
4329
4330 AutoStubFrame stubFrame(*this);
4331 stubFrame.enter(masm, scratch1);
4332
4333 // Push the arguments in reverse order.
4334 for (uint32_t i = 0; i < argc; i++) {
4335 Address argAddress(FramePointer,
4336 BaselineStubFrameLayout::Size() + i * sizeof(Value));
4337 masm.pushValue(argAddress);
4338 }
4339 masm.moveStackPtrTo(scratch1.get());
4340
4341 masm.Push(scratch2);
4342 masm.Push(Imm32(argc));
4343 masm.Push(scratch1);
4344 masm.Push(target);
4345
4346 using Fn = BoundFunctionObject* (*)(JSContext*, Handle<JSObject*>, Value*,
4347 uint32_t, Handle<BoundFunctionObject*>);
4348 callVM<Fn, BoundFunctionObject::functionBindSpecializedBaseline>(masm);
4349
4350 stubFrame.leave(masm);
4351 masm.storeCallPointerResult(scratch1);
4352
4353 masm.tagValue(JSVAL_TYPE_OBJECT, scratch1, output.valueReg());
4354 return true;
4355 }
4356
4357 bool BaselineCacheIRCompiler::emitCloseIterScriptedResult(
4358 ObjOperandId iterId, ObjOperandId calleeId, CompletionKind kind,
4359 uint32_t calleeNargs) {
4360 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
4361 Register iter = allocator.useRegister(masm, iterId);
4362 Register callee = allocator.useRegister(masm, calleeId);
4363
4364 AutoScratchRegister code(allocator, masm);
4365 AutoScratchRegister scratch(allocator, masm);
4366
4367 masm.loadJitCodeRaw(callee, code);
4368
4369 allocator.discardStack(masm);
4370
4371 AutoStubFrame stubFrame(*this);
4372 stubFrame.enter(masm, scratch);
4373
4374 // Call the return method.
4375 masm.alignJitStackBasedOnNArgs(calleeNargs, /*countIncludesThis = */ false);
4376 for (uint32_t i = 0; i < calleeNargs; i++) {
4377 masm.pushValue(UndefinedValue());
4378 }
4379 masm.Push(TypedOrValueRegister(MIRType::Object, AnyRegister(iter)));
4380 masm.Push(callee);
4381 masm.PushFrameDescriptorForJitCall(FrameType::BaselineStub, /* argc = */ 0);
4382
4383 masm.callJit(code);
4384
4385 if (kind != CompletionKind::Throw) {
4386 // Verify that the return value is an object.
4387 Label success;
4388 masm.branchTestObject(Assembler::Equal, JSReturnOperand, &success);
4389
4390 masm.Push(Imm32(int32_t(CheckIsObjectKind::IteratorReturn)));
4391 using Fn = bool (*)(JSContext*, CheckIsObjectKind);
4392 callVM<Fn, ThrowCheckIsObject>(masm);
4393
4394 masm.bind(&success);
4395 }
4396
4397 stubFrame.leave(masm);
4398 return true;
4399 }
4400
4401 static void CallRegExpStub(MacroAssembler& masm, size_t jitZoneStubOffset,
4402 Register temp, Label* vmCall) {
4403 // Call cx->zone()->jitZone()->regExpStub. We store a pointer to the RegExp
4404 // stub in the IC stub to keep it alive, but we shouldn't use it if the stub
4405 // has been discarded in the meantime (because we might have changed GC string
4406 // pretenuring heuristics that affect behavior of the stub). This is uncommon
4407 // but can happen if we discarded all JIT code but had some active (Baseline)
4408 // scripts on the stack.
4409 masm.loadJSContext(temp);
4410 masm.loadPtr(Address(temp, JSContext::offsetOfZone()), temp);
4411 masm.loadPtr(Address(temp, Zone::offsetOfJitZone()), temp);
4412 masm.loadPtr(Address(temp, jitZoneStubOffset), temp);
4413 masm.branchTestPtr(Assembler::Zero, temp, temp, vmCall);
4414 masm.call(Address(temp, JitCode::offsetOfCode()));
4415 }
4416
4417 // Used to move inputs to the registers expected by the RegExp stub.
4418 static void SetRegExpStubInputRegisters(MacroAssembler& masm,
4419 Register* regexpSrc,
4420 Register regexpDest, Register* inputSrc,
4421 Register inputDest,
4422 Register* lastIndexSrc,
4423 Register lastIndexDest) {
4424 MoveResolver& moves = masm.moveResolver();
4425 if (*regexpSrc != regexpDest) {
4426 masm.propagateOOM(moves.addMove(MoveOperand(*regexpSrc),
4427 MoveOperand(regexpDest), MoveOp::GENERAL));
4428 *regexpSrc = regexpDest;
4429 }
4430 if (*inputSrc != inputDest) {
4431 masm.propagateOOM(moves.addMove(MoveOperand(*inputSrc),
4432 MoveOperand(inputDest), MoveOp::GENERAL));
4433 *inputSrc = inputDest;
4434 }
4435 if (lastIndexSrc && *lastIndexSrc != lastIndexDest) {
4436 masm.propagateOOM(moves.addMove(MoveOperand(*lastIndexSrc),
4437 MoveOperand(lastIndexDest), MoveOp::INT32));
4438 *lastIndexSrc = lastIndexDest;
4439 }
4440
4441 masm.propagateOOM(moves.resolve());
4442
4443 MoveEmitter emitter(masm);
4444 emitter.emit(moves);
4445 emitter.finish();
4446 }
4447
4448 bool BaselineCacheIRCompiler::emitCallRegExpMatcherResult(
4449 ObjOperandId regexpId, StringOperandId inputId, Int32OperandId lastIndexId,
4450 uint32_t stubOffset) {
4451 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
4452
4453 AutoOutputRegister output(*this);
4454 Register regexp = allocator.useRegister(masm, regexpId);
4455 Register input = allocator.useRegister(masm, inputId);
4456 Register lastIndex = allocator.useRegister(masm, lastIndexId);
4457 Register scratch = output.valueReg().scratchReg();
4458
4459 allocator.discardStack(masm);
4460
4461 AutoStubFrame stubFrame(*this);
4462 stubFrame.enter(masm, scratch);
4463
4464 SetRegExpStubInputRegisters(masm, &regexp, RegExpMatcherRegExpReg, &input,
4465 RegExpMatcherStringReg, &lastIndex,
4466 RegExpMatcherLastIndexReg);
4467
4468 masm.reserveStack(RegExpReservedStack);
4469
4470 Label done, vmCall, vmCallNoMatches;
4471 CallRegExpStub(masm, JitZone::offsetOfRegExpMatcherStub(), scratch,
4472 &vmCallNoMatches);
4473 masm.branchTestUndefined(Assembler::Equal, JSReturnOperand, &vmCall);
4474
4475 masm.jump(&done);
4476
4477 {
4478 Label pushedMatches;
4479 masm.bind(&vmCallNoMatches);
4480 masm.push(ImmWord(0));
4481 masm.jump(&pushedMatches);
4482
4483 masm.bind(&vmCall);
4484 masm.computeEffectiveAddress(
4485 Address(masm.getStackPointer(), InputOutputDataSize), scratch);
4486 masm.Push(scratch);
4487
4488 masm.bind(&pushedMatches);
4489 masm.Push(lastIndex);
4490 masm.Push(input);
4491 masm.Push(regexp);
4492
4493 using Fn = bool (*)(JSContext*, HandleObject regexp, HandleString input,
4494 int32_t lastIndex, MatchPairs* pairs,
4495 MutableHandleValue output);
4496 callVM<Fn, RegExpMatcherRaw>(masm);
4497 }
4498
4499 masm.bind(&done);
4500
4501 static_assert(R0 == JSReturnOperand);
4502
4503 stubFrame.leave(masm);
4504 return true;
4505 }
4506
4507 bool BaselineCacheIRCompiler::emitCallRegExpSearcherResult(
4508 ObjOperandId regexpId, StringOperandId inputId, Int32OperandId lastIndexId,
4509 uint32_t stubOffset) {
4510 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
4511
4512 AutoOutputRegister output(*this);
4513 Register regexp = allocator.useRegister(masm, regexpId);
4514 Register input = allocator.useRegister(masm, inputId);
4515 Register lastIndex = allocator.useRegister(masm, lastIndexId);
4516 Register scratch = output.valueReg().scratchReg();
4517
4518 allocator.discardStack(masm);
4519
4520 AutoStubFrame stubFrame(*this);
4521 stubFrame.enter(masm, scratch);
4522
4523 SetRegExpStubInputRegisters(masm, &regexp, RegExpSearcherRegExpReg, &input,
4524 RegExpSearcherStringReg, &lastIndex,
4525 RegExpSearcherLastIndexReg);
4526 // Ensure `scratch` doesn't conflict with the stub's input registers.
4527 scratch = ReturnReg;
4528
4529 masm.reserveStack(RegExpReservedStack);
4530
4531 Label done, vmCall, vmCallNoMatches;
4532 CallRegExpStub(masm, JitZone::offsetOfRegExpSearcherStub(), scratch,
4533 &vmCallNoMatches);
4534 masm.branch32(Assembler::Equal, scratch, Imm32(RegExpSearcherResultFailed),
4535 &vmCall);
4536
4537 masm.jump(&done);
4538
4539 {
4540 Label pushedMatches;
4541 masm.bind(&vmCallNoMatches);
4542 masm.push(ImmWord(0));
4543 masm.jump(&pushedMatches);
4544
4545 masm.bind(&vmCall);
4546 masm.computeEffectiveAddress(
4547 Address(masm.getStackPointer(), InputOutputDataSize), scratch);
4548 masm.Push(scratch);
4549
4550 masm.bind(&pushedMatches);
4551 masm.Push(lastIndex);
4552 masm.Push(input);
4553 masm.Push(regexp);
4554
4555 using Fn = bool (*)(JSContext*, HandleObject regexp, HandleString input,
4556 int32_t lastIndex, MatchPairs* pairs, int32_t* result);
4557 callVM<Fn, RegExpSearcherRaw>(masm);
4558 }
4559
4560 masm.bind(&done);
4561
4562 masm.tagValue(JSVAL_TYPE_INT32, ReturnReg, output.valueReg());
4563
4564 stubFrame.leave(masm);
4565 return true;
4566 }
4567
4568 bool BaselineCacheIRCompiler::emitRegExpBuiltinExecMatchResult(
4569 ObjOperandId regexpId, StringOperandId inputId, uint32_t stubOffset) {
4570 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
4571
4572 AutoOutputRegister output(*this);
4573 Register regexp = allocator.useRegister(masm, regexpId);
4574 Register input = allocator.useRegister(masm, inputId);
4575 Register scratch = output.valueReg().scratchReg();
4576
4577 allocator.discardStack(masm);
4578
4579 AutoStubFrame stubFrame(*this);
4580 stubFrame.enter(masm, scratch);
4581
4582 SetRegExpStubInputRegisters(masm, &regexp, RegExpMatcherRegExpReg, &input,
4583 RegExpMatcherStringReg, nullptr, InvalidReg);
4584
4585 masm.reserveStack(RegExpReservedStack);
4586
4587 Label done, vmCall, vmCallNoMatches;
4588 CallRegExpStub(masm, JitZone::offsetOfRegExpExecMatchStub(), scratch,
4589 &vmCallNoMatches);
4590 masm.branchTestUndefined(Assembler::Equal, JSReturnOperand, &vmCall);
4591
4592 masm.jump(&done);
4593
4594 {
4595 Label pushedMatches;
4596 masm.bind(&vmCallNoMatches);
4597 masm.push(ImmWord(0));
4598 masm.jump(&pushedMatches);
4599
4600 masm.bind(&vmCall);
4601 masm.computeEffectiveAddress(
4602 Address(masm.getStackPointer(), InputOutputDataSize), scratch);
4603 masm.Push(scratch);
4604
4605 masm.bind(&pushedMatches);
4606 masm.Push(input);
4607 masm.Push(regexp);
4608
4609 using Fn =
4610 bool (*)(JSContext*, Handle<RegExpObject*> regexp, HandleString input,
4611 MatchPairs* pairs, MutableHandleValue output);
4612 callVM<Fn, RegExpBuiltinExecMatchFromJit>(masm);
4613 }
4614
4615 masm.bind(&done);
4616
4617 static_assert(R0 == JSReturnOperand);
4618
4619 stubFrame.leave(masm);
4620 return true;
4621 }
4622
4623 bool BaselineCacheIRCompiler::emitRegExpBuiltinExecTestResult(
4624 ObjOperandId regexpId, StringOperandId inputId, uint32_t stubOffset) {
4625 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
4626
4627 AutoOutputRegister output(*this);
4628 Register regexp = allocator.useRegister(masm, regexpId);
4629 Register input = allocator.useRegister(masm, inputId);
4630 Register scratch = output.valueReg().scratchReg();
4631
4632 allocator.discardStack(masm);
4633
4634 AutoStubFrame stubFrame(*this);
4635 stubFrame.enter(masm, scratch);
4636
4637 SetRegExpStubInputRegisters(masm, &regexp, RegExpExecTestRegExpReg, &input,
4638 RegExpExecTestStringReg, nullptr, InvalidReg);
4639 // Ensure `scratch` doesn't conflict with the stub's input registers.
4640 scratch = ReturnReg;
4641
4642 Label done, vmCall;
4643 CallRegExpStub(masm, JitZone::offsetOfRegExpExecTestStub(), scratch, &vmCall);
4644 masm.branch32(Assembler::Equal, scratch, Imm32(RegExpExecTestResultFailed),
4645 &vmCall);
4646
4647 masm.jump(&done);
4648
4649 {
4650 masm.bind(&vmCall);
4651
4652 masm.Push(input);
4653 masm.Push(regexp);
4654
4655 using Fn = bool (*)(JSContext*, Handle<RegExpObject*> regexp,
4656 HandleString input, bool* result);
4657 callVM<Fn, RegExpBuiltinExecTestFromJit>(masm);
4658 }
4659
4660 masm.bind(&done);
4661
4662 masm.tagValue(JSVAL_TYPE_BOOLEAN, ReturnReg, output.valueReg());
4663
4664 stubFrame.leave(masm);
4665 return true;
4666 }
4667
4668 bool BaselineCacheIRCompiler::emitRegExpHasCaptureGroupsResult(
4669 ObjOperandId regexpId, StringOperandId inputId) {
4670 JitSpew(JitSpew_Codegen, "%s", __FUNCTION__);
4671
4672 AutoOutputRegister output(*this);
4673 Register regexp = allocator.useRegister(masm, regexpId);
4674 Register input = allocator.useRegister(masm, inputId);
4675 AutoScratchRegisterMaybeOutput scratch(allocator, masm, output);
4676
4677 allocator.discardStack(masm);
4678
4679 // Load RegExpShared in |scratch|.
4680 Label vmCall;
4681 masm.loadParsedRegExpShared(regexp, scratch, &vmCall);
4682
4683 // Return true iff pairCount > 1.
4684 Label returnTrue, done;
4685 masm.branch32(Assembler::Above,
4686 Address(scratch, RegExpShared::offsetOfPairCount()), Imm32(1),
4687 &returnTrue);
4688 masm.moveValue(BooleanValue(false), output.valueReg());
4689 masm.jump(&done);
4690
4691 masm.bind(&returnTrue);
4692 masm.moveValue(BooleanValue(true), output.valueReg());
4693 masm.jump(&done);
4694
4695 {
4696 masm.bind(&vmCall);
4697
4698 AutoStubFrame stubFrame(*this);
4699 stubFrame.enter(masm, scratch);
4700
4701 masm.Push(input);
4702 masm.Push(regexp);
4703
4704 using Fn =
4705 bool (*)(JSContext*, Handle<RegExpObject*>, Handle<JSString*>, bool*);
4706 callVM<Fn, RegExpHasCaptureGroups>(masm);
4707
4708 stubFrame.leave(masm);
4709 masm.storeCallBoolResult(scratch);
4710 masm.tagValue(JSVAL_TYPE_BOOLEAN, scratch, output.valueReg());
4711 }
4712
4713 masm.bind(&done);
4714 return true;
4715 }