Debian Codegraph @

js/src/jit/BaselineBailouts.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 "mozilla/Assertions.h"
8 #include "mozilla/ScopeExit.h"
9
10 #include "builtin/ModuleObject.h"
11 #include "debugger/DebugAPI.h"
12 #include "gc/GC.h"
13 #include "jit/Bailouts.h"
14 #include "jit/BaselineFrame.h"
15 #include "jit/BaselineIC.h"
16 #include "jit/BaselineJIT.h"
17 #include "jit/CalleeToken.h"
18 #include "jit/Invalidation.h"
19 #include "jit/Ion.h"
20 #include "jit/IonScript.h"
21 #include "jit/JitFrames.h"
22 #include "jit/JitRuntime.h"
23 #include "jit/JitSpewer.h"
24 #include "jit/JitZone.h"
25 #include "jit/RematerializedFrame.h"
26 #include "jit/SharedICRegisters.h"
27 #include "jit/Simulator.h"
28 #include "js/friend/StackLimits.h" // js::AutoCheckRecursionLimit, js::ReportOverRecursed
29 #include "js/Utility.h"
30 #include "proxy/ScriptedProxyHandler.h"
31 #include "util/Memory.h"
32 #include "vm/ArgumentsObject.h"
33 #include "vm/BytecodeUtil.h"
34 #include "vm/JitActivation.h"
35
36 #include "jit/JitFrames-inl.h"
37 #include "vm/JSAtomUtils-inl.h"
38 #include "vm/JSContext-inl.h"
39 #include "vm/JSScript-inl.h"
40
41 using namespace js;
42 using namespace js::jit;
43
44 using mozilla::DebugOnly;
45 using mozilla::Maybe;
46
47 // BaselineStackBuilder may reallocate its buffer if the current one is too
48 // small. To avoid dangling pointers, BufferPointer represents a pointer into
49 // this buffer as a pointer to the header and a fixed offset.
50 template <typename T>
51 class BufferPointer {
52 const UniquePtr<BaselineBailoutInfo>& header_;
53 size_t offset_;
54 bool heap_;
55
56 public:
57 BufferPointer(const UniquePtr<BaselineBailoutInfo>& header, size_t offset,
58 bool heap)
59 : header_(header), offset_(offset), heap_(heap) {}
60
61 T* get() const {
62 BaselineBailoutInfo* header = header_.get();
63 if (!heap_) {
64 return (T*)(header->incomingStack + offset_);
65 }
66
67 uint8_t* p = header->copyStackTop - offset_;
68 MOZ_ASSERT(p >= header->copyStackBottom && p < header->copyStackTop);
69 return (T*)p;
70 }
71
72 void set(const T& value) { *get() = value; }
73
74 // Note: we return a copy instead of a reference, to avoid potential memory
75 // safety hazards when the underlying buffer gets resized.
76 const T operator*() const { return *get(); }
77 T* operator->() const { return get(); }
78 };
79
80 /**
81 * BaselineStackBuilder helps abstract the process of rebuilding the C stack on
82 * the heap. It takes a bailout iterator and keeps track of the point on the C
83 * stack from which the reconstructed frames will be written.
84 *
85 * It exposes methods to write data into the heap memory storing the
86 * reconstructed stack. It also exposes method to easily calculate addresses.
87 * This includes both the virtual address that a particular value will be at
88 * when it's eventually copied onto the stack, as well as the current actual
89 * address of that value (whether on the heap allocated portion being
90 * constructed or the existing stack).
91 *
92 * The abstraction handles transparent re-allocation of the heap memory when it
93 * needs to be enlarged to accommodate new data. Similarly to the C stack, the
94 * data that's written to the reconstructed stack grows from high to low in
95 * memory.
96 *
97 * The lowest region of the allocated memory contains a BaselineBailoutInfo
98 * structure that points to the start and end of the written data.
99 */
100 class MOZ_STACK_CLASS BaselineStackBuilder {
101 JSContext* cx_;
102 JitFrameLayout* frame_ = nullptr;
103 SnapshotIterator& iter_;
104 RootedValueVector outermostFrameFormals_;
105
106 size_t bufferTotal_ = 1024;
107 size_t bufferAvail_ = 0;
108 size_t bufferUsed_ = 0;
109 size_t framePushed_ = 0;
110
111 UniquePtr<BaselineBailoutInfo> header_;
112
113 JSScript* script_;
114 JSFunction* fun_;
115 const ExceptionBailoutInfo* excInfo_;
116 ICScript* icScript_;
117
118 jsbytecode* pc_ = nullptr;
119 JSOp op_ = JSOp::Nop;
120 mozilla::Maybe<ResumeMode> resumeMode_;
121 uint32_t exprStackSlots_ = 0;
122 void* prevFramePtr_ = nullptr;
123 Maybe<BufferPointer<BaselineFrame>> blFrame_;
124
125 size_t frameNo_ = 0;
126 JSFunction* nextCallee_ = nullptr;
127
128 BailoutKind bailoutKind_;
129
130 bool canUseTrialInlinedICScripts_ = true;
131
132 // The baseline frames we will reconstruct on the heap are not
133 // rooted, so GC must be suppressed.
134 gc::AutoSuppressGC suppress_;
135
136 public:
137 BaselineStackBuilder(JSContext* cx, const JSJitFrameIter& frameIter,
138 SnapshotIterator& iter,
139 const ExceptionBailoutInfo* excInfo,
140 BailoutReason reason);
141
142 [[nodiscard]] bool init() {
143 MOZ_ASSERT(!header_);
144 MOZ_ASSERT(bufferUsed_ == 0);
145
146 uint8_t* bufferRaw = cx_->pod_calloc<uint8_t>(bufferTotal_);
147 if (!bufferRaw) {
148 return false;
149 }
150 bufferAvail_ = bufferTotal_ - sizeof(BaselineBailoutInfo);
151
152 header_.reset(new (bufferRaw) BaselineBailoutInfo());
153 header_->incomingStack = reinterpret_cast<uint8_t*>(frame_);
154 header_->copyStackTop = bufferRaw + bufferTotal_;
155 header_->copyStackBottom = header_->copyStackTop;
156 return true;
157 }
158
159 [[nodiscard]] bool buildOneFrame();
160 bool done();
161 void nextFrame();
162
163 JSScript* script() const { return script_; }
164 size_t frameNo() const { return frameNo_; }
165 bool isOutermostFrame() const { return frameNo_ == 0; }
166 MutableHandleValueVector outermostFrameFormals() {
167 return &outermostFrameFormals_;
168 }
169 BailoutKind bailoutKind() const { return bailoutKind_; }
170
171 inline JitFrameLayout* startFrame() { return frame_; }
172
173 BaselineBailoutInfo* info() {
174 MOZ_ASSERT(header_);
175 return header_.get();
176 }
177
178 BaselineBailoutInfo* takeBuffer() {
179 MOZ_ASSERT(header_);
180 return header_.release();
181 }
182
183 private:
184 [[nodiscard]] bool initFrame();
185 [[nodiscard]] bool buildBaselineFrame();
186 [[nodiscard]] bool buildArguments();
187 [[nodiscard]] bool buildFixedSlots();
188 [[nodiscard]] bool fixUpCallerArgs(MutableHandleValueVector savedCallerArgs,
189 bool* fixedUp);
190 [[nodiscard]] bool buildFinallyException();
191 [[nodiscard]] bool buildExpressionStack();
192 [[nodiscard]] bool finishLastFrame();
193
194 [[nodiscard]] bool prepareForNextFrame(HandleValueVector savedCallerArgs);
195 [[nodiscard]] bool finishOuterFrame();
196 [[nodiscard]] bool buildStubFrame(uint32_t frameSize,
197 HandleValueVector savedCallerArgs);
198 [[nodiscard]] bool buildRectifierFrame(uint32_t actualArgc,
199 size_t endOfBaselineStubArgs);
200
201 #ifdef DEBUG
202 [[nodiscard]] bool validateFrame();
203 #endif
204
205 #ifdef DEBUG
206 bool envChainSlotCanBeOptimized();
207 #endif
208
209 bool isPrologueBailout();
210 jsbytecode* getResumePC();
211 void* getStubReturnAddress();
212
213 uint32_t exprStackSlots() const { return exprStackSlots_; }
214
215 // Returns true if we're bailing out to a catch or finally block in this frame
216 bool catchingException() const {
217 return excInfo_ && excInfo_->catchingException() &&
218 excInfo_->frameNo() == frameNo_;
219 }
220
221 // Returns true if we're bailing out to a finally block in this frame.
222 bool resumingInFinallyBlock() const {
223 return catchingException() && excInfo_->isFinally();
224 }
225
226 bool forcedReturn() const { return excInfo_ && excInfo_->forcedReturn(); }
227
228 // Returns true if we're bailing out in place for debug mode
229 bool propagatingIonExceptionForDebugMode() const {
230 return excInfo_ && excInfo_->propagatingIonExceptionForDebugMode();
231 }
232
233 void* prevFramePtr() const {
234 MOZ_ASSERT(prevFramePtr_);
235 return prevFramePtr_;
236 }
237 BufferPointer<BaselineFrame>& blFrame() { return blFrame_.ref(); }
238
239 void setNextCallee(JSFunction* nextCallee,
240 TrialInliningState trialInliningState);
241 JSFunction* nextCallee() const { return nextCallee_; }
242
243 jsbytecode* pc() const { return pc_; }
244 bool resumeAfter() const {
245 return !catchingException() && iter_.resumeAfter();
246 }
247
248 ResumeMode resumeMode() const { return *resumeMode_; }
249
250 bool needToSaveCallerArgs() const {
251 return resumeMode() == ResumeMode::InlinedAccessor;
252 }
253
254 [[nodiscard]] bool enlarge() {
255 MOZ_ASSERT(header_ != nullptr);
256 if (bufferTotal_ & mozilla::tl::MulOverflowMask<2>::value) {
257 ReportOutOfMemory(cx_);
258 return false;
259 }
260
261 size_t newSize = bufferTotal_ * 2;
262 uint8_t* newBufferRaw = cx_->pod_calloc<uint8_t>(newSize);
263 if (!newBufferRaw) {
264 return false;
265 }
266
267 // Initialize the new buffer.
268 //
269 // Before:
270 //
271 // [ Header | .. | Payload ]
272 //
273 // After:
274 //
275 // [ Header | ............... | Payload ]
276 //
277 // Size of Payload is |bufferUsed_|.
278 //
279 // We need to copy from the old buffer and header to the new buffer before
280 // we set header_ (this deletes the old buffer).
281 //
282 // We also need to update |copyStackBottom| and |copyStackTop| because these
283 // fields point to the Payload's start and end, respectively.
284 using BailoutInfoPtr = UniquePtr<BaselineBailoutInfo>;
285 BailoutInfoPtr newHeader(new (newBufferRaw) BaselineBailoutInfo(*header_));
286 newHeader->copyStackTop = newBufferRaw + newSize;
287 newHeader->copyStackBottom = newHeader->copyStackTop - bufferUsed_;
288 memcpy(newHeader->copyStackBottom, header_->copyStackBottom, bufferUsed_);
289 bufferTotal_ = newSize;
290 bufferAvail_ = newSize - (sizeof(BaselineBailoutInfo) + bufferUsed_);
291 header_ = std::move(newHeader);
292 return true;
293 }
294
295 void resetFramePushed() { framePushed_ = 0; }
296
297 size_t framePushed() const { return framePushed_; }
298
299 [[nodiscard]] bool subtract(size_t size, const char* info = nullptr) {
300 // enlarge the buffer if need be.
301 while (size > bufferAvail_) {
302 if (!enlarge()) {
303 return false;
304 }
305 }
306
307 // write out element.
308 header_->copyStackBottom -= size;
309 bufferAvail_ -= size;
310 bufferUsed_ += size;
311 framePushed_ += size;
312 if (info) {
313 JitSpew(JitSpew_BaselineBailouts, " SUB_%03d %p/%p %-15s",
314 (int)size, header_->copyStackBottom,
315 virtualPointerAtStackOffset(0), info);
316 }
317 return true;
318 }
319
320 template <typename T>
321 [[nodiscard]] bool write(const T& t) {
322 MOZ_ASSERT(!(uintptr_t(&t) >= uintptr_t(header_->copyStackBottom) &&
323 uintptr_t(&t) < uintptr_t(header_->copyStackTop)),
324 "Should not reference memory that can be freed");
325 if (!subtract(sizeof(T))) {
326 return false;
327 }
328 memcpy(header_->copyStackBottom, &t, sizeof(T));
329 return true;
330 }
331
332 template <typename T>
333 [[nodiscard]] bool writePtr(T* t, const char* info) {
334 if (!write<T*>(t)) {
335 return false;
336 }
337 if (info) {
338 JitSpew(JitSpew_BaselineBailouts, " WRITE_PTR %p/%p %-15s %p",
339 header_->copyStackBottom, virtualPointerAtStackOffset(0), info,
340 t);
341 }
342 return true;
343 }
344
345 [[nodiscard]] bool writeWord(size_t w, const char* info) {
346 if (!write<size_t>(w)) {
347 return false;
348 }
349 if (info) {
350 if (sizeof(size_t) == 4) {
351 JitSpew(JitSpew_BaselineBailouts, " WRITE_WRD %p/%p %-15s %08zx",
352 header_->copyStackBottom, virtualPointerAtStackOffset(0), info,
353 w);
354 } else {
355 JitSpew(JitSpew_BaselineBailouts, " WRITE_WRD %p/%p %-15s %016zx",
356 header_->copyStackBottom, virtualPointerAtStackOffset(0), info,
357 w);
358 }
359 }
360 return true;
361 }
362
363 [[nodiscard]] bool writeValue(const Value& val, const char* info) {
364 if (!write<Value>(val)) {
365 return false;
366 }
367 if (info) {
368 JitSpew(JitSpew_BaselineBailouts,
369 " WRITE_VAL %p/%p %-15s %016" PRIx64,
370 header_->copyStackBottom, virtualPointerAtStackOffset(0), info,
371 *((uint64_t*)&val));
372 }
373 return true;
374 }
375
376 [[nodiscard]] bool peekLastValue(Value* result) {
377 if (bufferUsed_ < sizeof(Value)) {
378 return false;
379 }
380
381 memcpy(result, header_->copyStackBottom, sizeof(Value));
382 return true;
383 }
384
385 [[nodiscard]] bool maybeWritePadding(size_t alignment, size_t after,
386 const char* info) {
387 MOZ_ASSERT(framePushed_ % sizeof(Value) == 0);
388 MOZ_ASSERT(after % sizeof(Value) == 0);
389 size_t offset = ComputeByteAlignment(after, alignment);
390 while (framePushed_ % alignment != offset) {
391 if (!writeValue(MagicValue(JS_ARG_POISON), info)) {
392 return false;
393 }
394 }
395
396 return true;
397 }
398
399 void setResumeFramePtr(void* resumeFramePtr) {
400 header_->resumeFramePtr = resumeFramePtr;
401 }
402
403 void setResumeAddr(void* resumeAddr) { header_->resumeAddr = resumeAddr; }
404
405 template <typename T>
406 BufferPointer<T> pointerAtStackOffset(size_t offset) {
407 if (offset < bufferUsed_) {
408 // Calculate offset from copyStackTop.
409 offset = header_->copyStackTop - (header_->copyStackBottom + offset);
410 return BufferPointer<T>(header_, offset, /* heap = */ true);
411 }
412
413 return BufferPointer<T>(header_, offset - bufferUsed_, /* heap = */ false);
414 }
415
416 BufferPointer<Value> valuePointerAtStackOffset(size_t offset) {
417 return pointerAtStackOffset<Value>(offset);
418 }
419
420 inline uint8_t* virtualPointerAtStackOffset(size_t offset) {
421 if (offset < bufferUsed_) {
422 return reinterpret_cast<uint8_t*>(frame_) - (bufferUsed_ - offset);
423 }
424 return reinterpret_cast<uint8_t*>(frame_) + (offset - bufferUsed_);
425 }
426 };
427
428 void BaselineBailoutInfo::trace(JSTracer* trc) {
429 TraceRoot(trc, &tempId, "BaselineBailoutInfo::tempId");
430 }
431
432 BaselineStackBuilder::BaselineStackBuilder(JSContext* cx,
433 const JSJitFrameIter& frameIter,
434 SnapshotIterator& iter,
435 const ExceptionBailoutInfo* excInfo,
436 BailoutReason reason)
437 : cx_(cx),
438 frame_(static_cast<JitFrameLayout*>(frameIter.current())),
439 iter_(iter),
440 outermostFrameFormals_(cx),
441 script_(frameIter.script()),
442 fun_(frameIter.maybeCallee()),
443 excInfo_(excInfo),
444 icScript_(script_->jitScript()->icScript()),
445 bailoutKind_(iter.bailoutKind()),
446 suppress_(cx) {
447 MOZ_ASSERT(bufferTotal_ >= sizeof(BaselineBailoutInfo));
448 if (reason == BailoutReason::Invalidate) {
449 bailoutKind_ = BailoutKind::OnStackInvalidation;
450 }
451 }
452
453 bool BaselineStackBuilder::initFrame() {
454 // Get the pc and ResumeMode. If we are handling an exception, resume at the
455 // pc of the catch or finally block.
456 if (catchingException()) {
457 pc_ = excInfo_->resumePC();
458 resumeMode_ = mozilla::Some(ResumeMode::ResumeAt);
459 } else {
460 pc_ = script_->offsetToPC(iter_.pcOffset());
461 resumeMode_ = mozilla::Some(iter_.resumeMode());
462 }
463 op_ = JSOp(*pc_);
464
465 // If we are catching an exception, we are bailing out to a catch or
466 // finally block and this is the frame where we will resume. Usually the
467 // expression stack should be empty in this case but there can be
468 // iterators on the stack.
469 if (catchingException()) {
470 exprStackSlots_ = excInfo_->numExprSlots();
471 } else {
472 uint32_t totalFrameSlots = iter_.numAllocations();
473 uint32_t fixedSlots = script_->nfixed();
474 uint32_t argSlots = CountArgSlots(script_, fun_);
475 uint32_t intermediates = NumIntermediateValues(resumeMode());
476 exprStackSlots_ = totalFrameSlots - fixedSlots - argSlots - intermediates;
477
478 // Verify that there was no underflow.
479 MOZ_ASSERT(exprStackSlots_ <= totalFrameSlots);
480 }
481
482 JitSpew(JitSpew_BaselineBailouts, " Unpacking %s:%u:%u",
483 script_->filename(), script_->lineno(),
484 script_->column().oneOriginValue());
485 JitSpew(JitSpew_BaselineBailouts, " [BASELINE-JS FRAME]");
486
487 // Write the previous frame pointer value. For the outermost frame we reuse
488 // the value in the JitFrameLayout already on the stack. Record the virtual
489 // stack offset at this location. Later on, if we end up writing out a
490 // BaselineStub frame for the next callee, we'll need to save the address.
491 if (!isOutermostFrame()) {
492 if (!writePtr(prevFramePtr(), "PrevFramePtr")) {
493 return false;
494 }
495 }
496 prevFramePtr_ = virtualPointerAtStackOffset(0);
497
498 resetFramePushed();
499
500 return true;
501 }
502
503 void BaselineStackBuilder::setNextCallee(
504 JSFunction* nextCallee, TrialInliningState trialInliningState) {
505 nextCallee_ = nextCallee;
506
507 if (trialInliningState == TrialInliningState::Inlined &&
508 !iter_.ionScript()->purgedICScripts() && canUseTrialInlinedICScripts_) {
509 // Update icScript_ to point to the icScript of nextCallee
510 const uint32_t pcOff = script_->pcToOffset(pc_);
511 icScript_ = icScript_->findInlinedChild(pcOff);
512 } else {
513 // If we don't know for certain that it's TrialInliningState::Inlined,
514 // just use the callee's own ICScript. We could still have the trial
515 // inlined ICScript available, but we also could not if we transitioned
516 // to TrialInliningState::Failure after being monomorphic inlined.
517 //
518 // Also use the callee's own ICScript if we purged callee ICScripts.
519 icScript_ = nextCallee->nonLazyScript()->jitScript()->icScript();
520
521 if (trialInliningState != TrialInliningState::MonomorphicInlined) {
522 // Don't use specialized ICScripts for any of the callees if we had an
523 // inlining failure. We're now using the generic ICScript but compilation
524 // might have used the trial-inlined ICScript and these can have very
525 // different inlining graphs.
526 canUseTrialInlinedICScripts_ = false;
527 }
528 }
529
530 // Assert the ICScript matches nextCallee.
531 JSScript* calleeScript = nextCallee->nonLazyScript();
532 MOZ_RELEASE_ASSERT(icScript_->numICEntries() == calleeScript->numICEntries());
533 MOZ_RELEASE_ASSERT(icScript_->bytecodeSize() == calleeScript->length());
534 }
535
536 bool BaselineStackBuilder::done() {
537 if (!iter_.moreFrames()) {
538 MOZ_ASSERT(!nextCallee_);
539 return true;
540 }
541 return catchingException();
542 }
543
544 void BaselineStackBuilder::nextFrame() {
545 MOZ_ASSERT(nextCallee_);
546 fun_ = nextCallee_;
547 script_ = fun_->nonLazyScript();
548 nextCallee_ = nullptr;
549
550 // Scripts with an IonScript must also have a BaselineScript.
551 MOZ_ASSERT(script_->hasBaselineScript());
552
553 frameNo_++;
554 iter_.nextInstruction();
555 }
556
557 // Build the BaselineFrame struct
558 bool BaselineStackBuilder::buildBaselineFrame() {
559 if (!subtract(BaselineFrame::Size(), "BaselineFrame")) {
560 return false;
561 }
562 blFrame_.reset();
563 blFrame_.emplace(pointerAtStackOffset<BaselineFrame>(0));
564
565 uint32_t flags = BaselineFrame::RUNNING_IN_INTERPRETER;
566
567 // If we are bailing to a script whose execution is observed, mark the
568 // baseline frame as a debuggee frame. This is to cover the case where we
569 // don't rematerialize the Ion frame via the Debugger.
570 if (script_->isDebuggee()) {
571 flags |= BaselineFrame::DEBUGGEE;
572 }
573
574 // Get |envChain|.
575 JSObject* envChain = nullptr;
576 Value envChainSlot = iter_.read();
577 if (envChainSlot.isObject()) {
578 // The env slot has been updated from UndefinedValue. It must be the
579 // complete initial environment.
580 envChain = &envChainSlot.toObject();
581
582 // Set the HAS_INITIAL_ENV flag if needed. See IsFrameInitialEnvironment.
583 MOZ_ASSERT(!script_->isForEval());
584 if (fun_ && fun_->needsFunctionEnvironmentObjects()) {
585 MOZ_ASSERT(fun_->nonLazyScript()->initialEnvironmentShape());
586 flags |= BaselineFrame::HAS_INITIAL_ENV;
587 }
588 } else {
589 MOZ_ASSERT(envChainSlot.isUndefined() ||
590 envChainSlot.isMagic(JS_OPTIMIZED_OUT));
591 MOZ_ASSERT(envChainSlotCanBeOptimized());
592
593 // The env slot has been optimized out.
594 // Get it from the function or script.
595 if (fun_) {
596 envChain = fun_->environment();
597 } else if (script_->isModule()) {
598 envChain = script_->module()->environment();
599 } else {
600 // For global scripts without a non-syntactic env the env
601 // chain is the script's global lexical environment. (We do
602 // not compile scripts with a non-syntactic global scope).
603 // Also note that it's invalid to resume into the prologue in
604 // this case because the prologue expects the env chain in R1
605 // for eval and global scripts.
606 MOZ_ASSERT(!script_->isForEval());
607 MOZ_ASSERT(!script_->hasNonSyntacticScope());
608 envChain = &(script_->global().lexicalEnvironment());
609 }
610 }
611
612 // Write |envChain|.
613 MOZ_ASSERT(envChain);
614 JitSpew(JitSpew_BaselineBailouts, " EnvChain=%p", envChain);
615 blFrame()->setEnvironmentChain(envChain);
616
617 // Get |returnValue| if present.
618 Value returnValue = UndefinedValue();
619 if (script_->noScriptRval()) {
620 // Don't use the return value (likely a JS_OPTIMIZED_OUT MagicValue) to
621 // not confuse Baseline.
622 iter_.skip();
623 } else {
624 returnValue = iter_.read();
625 flags |= BaselineFrame::HAS_RVAL;
626 }
627
628 // Write |returnValue|.
629 JitSpew(JitSpew_BaselineBailouts, " ReturnValue=%016" PRIx64,
630 *((uint64_t*)&returnValue));
631 blFrame()->setReturnValue(returnValue);
632
633 // Get |argsObj| if present.
634 ArgumentsObject* argsObj = nullptr;
635 if (script_->needsArgsObj()) {
636 Value maybeArgsObj = iter_.read();
637 MOZ_ASSERT(maybeArgsObj.isObject() || maybeArgsObj.isUndefined() ||
638 maybeArgsObj.isMagic(JS_OPTIMIZED_OUT));
639 if (maybeArgsObj.isObject()) {
640 argsObj = &maybeArgsObj.toObject().as<ArgumentsObject>();
641 }
642 }
643
644 // Note: we do not need to initialize the scratchValue field in BaselineFrame.
645
646 // Write |flags|.
647 blFrame()->setFlags(flags);
648
649 // Write |icScript|.
650 JitSpew(JitSpew_BaselineBailouts, " ICScript=%p", icScript_);
651 blFrame()->setICScript(icScript_);
652
653 // initArgsObjUnchecked modifies the frame's flags, so call it after setFlags.
654 if (argsObj) {
655 blFrame()->initArgsObjUnchecked(*argsObj);
656 }
657 return true;
658 }
659
660 // Overwrite the pushed args present in the calling frame with
661 // the unpacked |thisv| and argument values.
662 bool BaselineStackBuilder::buildArguments() {
663 Value thisv = iter_.read();
664 JitSpew(JitSpew_BaselineBailouts, " Is function!");
665 JitSpew(JitSpew_BaselineBailouts, " thisv=%016" PRIx64,
666 *((uint64_t*)&thisv));
667
668 size_t thisvOffset = framePushed() + JitFrameLayout::offsetOfThis();
669 valuePointerAtStackOffset(thisvOffset).set(thisv);
670
671 MOZ_ASSERT(iter_.numAllocations() >= CountArgSlots(script_, fun_));
672 JitSpew(JitSpew_BaselineBailouts,
673 " frame slots %u, nargs %zu, nfixed %zu", iter_.numAllocations(),
674 fun_->nargs(), script_->nfixed());
675
676 bool shouldStoreOutermostFormals =
677 isOutermostFrame() && !script_->argsObjAliasesFormals();
678 if (shouldStoreOutermostFormals) {
679 // This is the first (outermost) frame and we don't have an
680 // arguments object aliasing the formals. Due to UCE and phi
681 // elimination, we could store an UndefinedValue() here for
682 // formals we think are unused, but locals may still reference the
683 // original argument slot (MParameter/LArgument) and expect the
684 // original Value. To avoid this problem, store the formals in a
685 // Vector until we are done.
686 MOZ_ASSERT(outermostFrameFormals().empty());
687 if (!outermostFrameFormals().resize(fun_->nargs())) {
688 return false;
689 }
690 }
691
692 for (uint32_t i = 0; i < fun_->nargs(); i++) {
693 Value arg = iter_.read();
694 JitSpew(JitSpew_BaselineBailouts, " arg %d = %016" PRIx64, (int)i,
695 *((uint64_t*)&arg));
696 if (!isOutermostFrame()) {
697 size_t argOffset = framePushed() + JitFrameLayout::offsetOfActualArg(i);
698 valuePointerAtStackOffset(argOffset).set(arg);
699 } else if (shouldStoreOutermostFormals) {
700 outermostFrameFormals()[i].set(arg);
701 } else {
702 // When the arguments object aliases the formal arguments, then
703 // JSOp::SetArg mutates the argument object. In such cases, the
704 // list of arguments reported by the snapshot are only aliases
705 // of argument object slots which are optimized to only store
706 // differences compared to arguments which are on the stack.
707 }
708 }
709 return true;
710 }
711
712 bool BaselineStackBuilder::buildFixedSlots() {
713 for (uint32_t i = 0; i < script_->nfixed(); i++) {
714 Value slot = iter_.read();
715 if (!writeValue(slot, "FixedValue")) {
716 return false;
717 }
718 }
719 return true;
720 }
721
722 // The caller side of inlined js::fun_call and accessors must look
723 // like the function wasn't inlined.
724 bool BaselineStackBuilder::fixUpCallerArgs(
725 MutableHandleValueVector savedCallerArgs, bool* fixedUp) {
726 MOZ_ASSERT(!*fixedUp);
727
728 // Inlining of SpreadCall-like frames not currently supported.
729 MOZ_ASSERT(!IsSpreadOp(op_));
730
731 if (resumeMode() != ResumeMode::InlinedFunCall && !needToSaveCallerArgs()) {
732 return true;
733 }
734
735 // Calculate how many arguments are consumed by the inlined call.
736 // All calls pass |callee| and |this|.
737 uint32_t inlinedArgs = 2;
738 if (resumeMode() == ResumeMode::InlinedFunCall) {
739 // The first argument to an inlined FunCall becomes |this|,
740 // if it exists. The rest are passed normally.
741 MOZ_ASSERT(IsInvokeOp(op_));
742 inlinedArgs += GET_ARGC(pc_) > 0 ? GET_ARGC(pc_) - 1 : 0;
743 } else {
744 MOZ_ASSERT(resumeMode() == ResumeMode::InlinedAccessor);
745 MOZ_ASSERT(IsIonInlinableGetterOrSetterOp(op_));
746 // Setters are passed one argument. Getters are passed none.
747 if (IsSetPropOp(op_)) {
748 inlinedArgs++;
749 }
750 }
751
752 // Calculate how many values are live on the stack across the call,
753 // and push them.
754 MOZ_ASSERT(inlinedArgs <= exprStackSlots());
755 uint32_t liveStackSlots = exprStackSlots() - inlinedArgs;
756
757 JitSpew(JitSpew_BaselineBailouts,
758 " pushing %u expression stack slots before fixup",
759 liveStackSlots);
760 for (uint32_t i = 0; i < liveStackSlots; i++) {
761 Value v = iter_.read();
762 if (!writeValue(v, "StackValue")) {
763 return false;
764 }
765 }
766
767 // When we inline js::fun_call, we bypass the native and inline the
768 // target directly. When rebuilding the stack, we need to fill in
769 // the right number of slots to make it look like the js_native was
770 // actually called.
771 if (resumeMode() == ResumeMode::InlinedFunCall) {
772 // We must transform the stack from |target, this, args| to
773 // |js_fun_call, target, this, args|. The value of |js_fun_call|
774 // will never be observed, so we push |undefined| for it, followed
775 // by the remaining arguments.
776 JitSpew(JitSpew_BaselineBailouts,
777 " pushing undefined to fixup funcall");
778 if (!writeValue(UndefinedValue(), "StackValue")) {
779 return false;
780 }
781 if (GET_ARGC(pc_) > 0) {
782 JitSpew(JitSpew_BaselineBailouts,
783 " pushing %u expression stack slots", inlinedArgs);
784 for (uint32_t i = 0; i < inlinedArgs; i++) {
785 Value arg = iter_.read();
786 if (!writeValue(arg, "StackValue")) {
787 return false;
788 }
789 }
790 } else {
791 // When we inline FunCall with no arguments, we push an extra
792 // |undefined| value for |this|. That value should not appear
793 // in the rebuilt baseline frame.
794 JitSpew(JitSpew_BaselineBailouts, " pushing target of funcall");
795 Value target = iter_.read();
796 if (!writeValue(target, "StackValue")) {
797 return false;
798 }
799 // Skip |this|.
800 iter_.skip();
801 }
802 }
803
804 if (needToSaveCallerArgs()) {
805 // Save the actual arguments. They are needed to rebuild the callee frame.
806 if (!savedCallerArgs.resize(inlinedArgs)) {
807 return false;
808 }
809 for (uint32_t i = 0; i < inlinedArgs; i++) {
810 savedCallerArgs[i].set(iter_.read());
811 }
812
813 if (IsSetPropOp(op_)) {
814 // The RHS argument to SetProp remains on the stack after the
815 // operation and is observable, so we have to fill it in.
816 Value initialArg = savedCallerArgs[inlinedArgs - 1];
817 JitSpew(JitSpew_BaselineBailouts,
818 " pushing setter's initial argument");
819 if (!writeValue(initialArg, "StackValue")) {
820 return false;
821 }
822 }
823 }
824
825 *fixedUp = true;
826 return true;
827 }
828
829 bool BaselineStackBuilder::buildExpressionStack() {
830 JitSpew(JitSpew_BaselineBailouts, " pushing %u expression stack slots",
831 exprStackSlots());
832
833 for (uint32_t i = 0; i < exprStackSlots(); i++) {
834 Value v;
835 // If we're at the newest frame and in the middle of throwing an exception,
836 // some expression stack slots might not be available.
837 //
838 // For example, if we call a function that throws, and then catch the
839 // exception, the return value won't be available. This isn't usually a
840 // problem, because the expression stack is generally empty when we enter a
841 // catch block. However, if a catch is inside a for-of, there are
842 // iterator-related values on the stack. If one of those values is defined
843 // by the function that threw, then its value will be unavailable. This is
844 // not possible for a user-written catch, but can happen for synthetic
845 // catches generated via desugaring. See bug 1934425 for a case involving
846 // `for (await using ...)`.
847 //
848 // Similar issues of trying to recover the result of a throwing function can
849 // also occur when bailing out while propagating an exception due to debug
850 // mode.
851 //
852 // We therefore use a fallible read here.
853 if (!iter_.tryRead(&v)) {
854 MOZ_ASSERT(
855 !iter_.moreFrames() &&
856 (catchingException() || propagatingIonExceptionForDebugMode()));
857 v = MagicValue(JS_OPTIMIZED_OUT);
858 }
859 if (!writeValue(v, "StackValue")) {
860 return false;
861 }
862 }
863
864 if (resumeMode() == ResumeMode::ResumeAfterCheckProxyGetResult) {
865 JitSpew(JitSpew_BaselineBailouts,
866 " Checking that the proxy's get trap result matches "
867 "expectations.");
868 Value returnVal;
869 if (peekLastValue(&returnVal) && !returnVal.isMagic(JS_OPTIMIZED_OUT)) {
870 Value idVal = iter_.read();
871 Value targetVal = iter_.read();
872
873 MOZ_RELEASE_ASSERT(!idVal.isMagic());
874 MOZ_RELEASE_ASSERT(targetVal.isObject());
875 RootedObject target(cx_, &targetVal.toObject());
876 RootedValue rootedIdVal(cx_, idVal);
877 RootedId id(cx_);
878 if (!PrimitiveValueToId<CanGC>(cx_, rootedIdVal, &id)) {
879 return false;
880 }
881 RootedValue value(cx_, returnVal);
882
883 auto validation =
884 ScriptedProxyHandler::checkGetTrapResult(cx_, target, id, value);
885 if (validation != ScriptedProxyHandler::GetTrapValidationResult::OK) {
886 header_->tempId = id.get();
887
888 JitSpew(
889 JitSpew_BaselineBailouts,
890 " Proxy get trap result mismatch! Overwriting bailout kind");
891 if (validation == ScriptedProxyHandler::GetTrapValidationResult::
892 MustReportSameValue) {
893 bailoutKind_ = BailoutKind::ThrowProxyTrapMustReportSameValue;
894 } else if (validation == ScriptedProxyHandler::GetTrapValidationResult::
895 MustReportUndefined) {
896 bailoutKind_ = BailoutKind::ThrowProxyTrapMustReportUndefined;
897 } else {
898 return false;
899 }
900 }
901 }
902
903 return true;
904 }
905
906 if (resumeMode() == ResumeMode::ResumeAfterCheckIsObject) {
907 JitSpew(JitSpew_BaselineBailouts,
908 " Checking that intermediate value is an object");
909 Value returnVal;
910 if (iter_.tryRead(&returnVal) && !returnVal.isObject()) {
911 MOZ_ASSERT(!returnVal.isMagic());
912 JitSpew(JitSpew_BaselineBailouts,
913 " Not an object! Overwriting bailout kind");
914 bailoutKind_ = BailoutKind::ThrowCheckIsObject;
915 }
916 }
917
918 return true;
919 }
920
921 bool BaselineStackBuilder::buildFinallyException() {
922 MOZ_ASSERT(resumingInFinallyBlock());
923
924 if (!writeValue(excInfo_->finallyException(), "Exception")) {
925 return false;
926 }
927 if (!writeValue(excInfo_->finallyExceptionStack(), "ExceptionStack")) {
928 return false;
929 }
930 if (!writeValue(BooleanValue(true), "throwing")) {
931 return false;
932 }
933
934 return true;
935 }
936
937 bool BaselineStackBuilder::prepareForNextFrame(
938 HandleValueVector savedCallerArgs) {
939 const uint32_t frameSize = framePushed();
940
941 // Write out descriptor and return address for the baseline frame.
942 // The icEntry in question MUST have an inlinable fallback stub.
943 if (!finishOuterFrame()) {
944 return false;
945 }
946
947 return buildStubFrame(frameSize, savedCallerArgs);
948 }
949
950 bool BaselineStackBuilder::finishOuterFrame() {
951 // . .
952 // | Descr(BLJS) |
953 // +---------------+
954 // | ReturnAddr |
955 // +===============+
956
957 const BaselineInterpreter& baselineInterp =
958 cx_->runtime()->jitRuntime()->baselineInterpreter();
959
960 blFrame()->setInterpreterFields(script_, pc_);
961
962 // Write out descriptor of BaselineJS frame.
963 size_t baselineFrameDescr = MakeFrameDescriptor(FrameType::BaselineJS);
964 if (!writeWord(baselineFrameDescr, "Descriptor")) {
965 return false;
966 }
967
968 uint8_t* retAddr = baselineInterp.retAddrForIC(op_);
969 return writePtr(retAddr, "ReturnAddr");
970 }
971
972 bool BaselineStackBuilder::buildStubFrame(uint32_t frameSize,
973 HandleValueVector savedCallerArgs) {
974 // Build baseline stub frame:
975 // +===============+
976 // | FramePtr |
977 // +---------------+
978 // | StubPtr |
979 // +---------------+
980 // | Padding? |
981 // +---------------+
982 // | ArgA |
983 // +---------------+
984 // | ... |
985 // +---------------+
986 // | Arg0 |
987 // +---------------+
988 // | ThisV |
989 // +---------------+
990 // | CalleeToken |
991 // +---------------+
992 // | Descr(BLStub) |
993 // +---------------+
994 // | ReturnAddr |
995 // +===============+
996
997 JitSpew(JitSpew_BaselineBailouts, " [BASELINE-STUB FRAME]");
998
999 // Write previous frame pointer (saved earlier).
1000 if (!writePtr(prevFramePtr(), "PrevFramePtr")) {
1001 return false;
1002 }
1003 prevFramePtr_ = virtualPointerAtStackOffset(0);
1004
1005 // Write stub pointer.
1006 uint32_t pcOff = script_->pcToOffset(pc_);
1007 JitScript* jitScript = script_->jitScript();
1008 const ICEntry& icEntry = jitScript->icEntryFromPCOffset(pcOff);
1009 ICFallbackStub* fallback = jitScript->fallbackStubForICEntry(&icEntry);
1010 if (!writePtr(fallback, "StubPtr")) {
1011 return false;
1012 }
1013
1014 // Write out the arguments, copied from the baseline frame. The order
1015 // of the arguments is reversed relative to the baseline frame's stack
1016 // values.
1017 MOZ_ASSERT(IsIonInlinableOp(op_));
1018 bool pushedNewTarget = IsConstructPC(pc_);
1019 unsigned actualArgc;
1020 Value callee;
1021 if (needToSaveCallerArgs()) {
1022 // For accessors, the arguments are not on the stack anymore,
1023 // but they are copied in a vector and are written here.
1024 callee = savedCallerArgs[0];
1025 actualArgc = IsSetPropOp(op_) ? 1 : 0;
1026
1027 // Align the stack based on the number of arguments.
1028 size_t afterFrameSize =
1029 (actualArgc + 1) * sizeof(Value) + JitFrameLayout::Size();
1030 if (!maybeWritePadding(JitStackAlignment, afterFrameSize, "Padding")) {
1031 return false;
1032 }
1033
1034 // Push arguments.
1035 MOZ_ASSERT(actualArgc + 2 <= exprStackSlots());
1036 MOZ_ASSERT(savedCallerArgs.length() == actualArgc + 2);
1037 for (unsigned i = 0; i < actualArgc + 1; i++) {
1038 size_t arg = savedCallerArgs.length() - (i + 1);
1039 if (!writeValue(savedCallerArgs[arg], "ArgVal")) {
1040 return false;
1041 }
1042 }
1043 } else if (resumeMode() == ResumeMode::InlinedFunCall && GET_ARGC(pc_) == 0) {
1044 // When calling FunCall with 0 arguments, we push |undefined|
1045 // for this. See BaselineCacheIRCompiler::pushFunCallArguments.
1046 MOZ_ASSERT(!pushedNewTarget);
1047 actualArgc = 0;
1048 // Align the stack based on pushing |this| and 0 arguments.
1049 size_t afterFrameSize = sizeof(Value) + JitFrameLayout::Size();
1050 if (!maybeWritePadding(JitStackAlignment, afterFrameSize, "Padding")) {
1051 return false;
1052 }
1053 // Push an undefined value for |this|.
1054 if (!writeValue(UndefinedValue(), "ThisValue")) {
1055 return false;
1056 }
1057 size_t calleeSlot = blFrame()->numValueSlots(frameSize) - 1;
1058 callee = *blFrame()->valueSlot(calleeSlot);
1059
1060 } else {
1061 MOZ_ASSERT(resumeMode() == ResumeMode::InlinedStandardCall ||
1062 resumeMode() == ResumeMode::InlinedFunCall);
1063 actualArgc = GET_ARGC(pc_);
1064 if (resumeMode() == ResumeMode::InlinedFunCall) {
1065 // See BaselineCacheIRCompiler::pushFunCallArguments.
1066 MOZ_ASSERT(actualArgc > 0);
1067 actualArgc--;
1068 }
1069
1070 // In addition to the formal arguments, we must also push |this|.
1071 // When calling a constructor, we must also push |newTarget|.
1072 uint32_t numArguments = actualArgc + 1 + pushedNewTarget;
1073
1074 // Align the stack based on the number of arguments.
1075 size_t afterFrameSize =
1076 numArguments * sizeof(Value) + JitFrameLayout::Size();
1077 if (!maybeWritePadding(JitStackAlignment, afterFrameSize, "Padding")) {
1078 return false;
1079 }
1080
1081 // Copy the arguments and |this| from the BaselineFrame, in reverse order.
1082 size_t valueSlot = blFrame()->numValueSlots(frameSize) - 1;
1083 size_t calleeSlot = valueSlot - numArguments;
1084
1085 for (size_t i = valueSlot; i > calleeSlot; i--) {
1086 Value v = *blFrame()->valueSlot(i);
1087 if (!writeValue(v, "ArgVal")) {
1088 return false;
1089 }
1090 }
1091
1092 callee = *blFrame()->valueSlot(calleeSlot);
1093 }
1094
1095 // In case these arguments need to be copied on the stack again for a
1096 // rectifier frame, save the framePushed values here for later use.
1097 size_t endOfBaselineStubArgs = framePushed();
1098
1099 // Push callee token (must be a JS Function)
1100 JitSpew(JitSpew_BaselineBailouts, " Callee = %016" PRIx64,
1101 callee.asRawBits());
1102
1103 JSFunction* calleeFun = &callee.toObject().as<JSFunction>();
1104 if (!writePtr(CalleeToToken(calleeFun, pushedNewTarget), "CalleeToken")) {
1105 return false;
1106 }
1107 const ICEntry& icScriptEntry = icScript_->icEntryFromPCOffset(pcOff);
1108 ICFallbackStub* icScriptFallback =
1109 icScript_->fallbackStubForICEntry(&icScriptEntry);
1110 setNextCallee(calleeFun, icScriptFallback->trialInliningState());
1111
1112 // Push BaselineStub frame descriptor
1113 size_t baselineStubFrameDescr =
1114 MakeFrameDescriptorForJitCall(FrameType::BaselineStub, actualArgc);
1115 if (!writeWord(baselineStubFrameDescr, "Descriptor")) {
1116 return false;
1117 }
1118
1119 // Push return address into ICCall_Scripted stub, immediately after the call.
1120 void* baselineCallReturnAddr = getStubReturnAddress();
1121 MOZ_ASSERT(baselineCallReturnAddr);
1122 if (!writePtr(baselineCallReturnAddr, "ReturnAddr")) {
1123 return false;
1124 }
1125
1126 // The stack must be aligned after the callee pushes the frame pointer.
1127 MOZ_ASSERT((framePushed() + sizeof(void*)) % JitStackAlignment == 0);
1128
1129 // Build a rectifier frame if necessary
1130 if (actualArgc < calleeFun->nargs() &&
1131 !buildRectifierFrame(actualArgc, endOfBaselineStubArgs)) {
1132 return false;
1133 }
1134
1135 return true;
1136 }
1137
1138 bool BaselineStackBuilder::buildRectifierFrame(uint32_t actualArgc,
1139 size_t endOfBaselineStubArgs) {
1140 // Push a reconstructed rectifier frame.
1141 // +===============+
1142 // | Padding? |
1143 // +---------------+
1144 // | UndefinedU |
1145 // +---------------+
1146 // | ... |
1147 // +---------------+
1148 // | Undefined0 |
1149 // +---------------+
1150 // | ArgA |
1151 // +---------------+
1152 // | ... |
1153 // +---------------+
1154 // | Arg0 |
1155 // +---------------+
1156 // | ThisV |
1157 // +---------------+
1158 // | CalleeToken |
1159 // +---------------+
1160 // | Descr(Rect) |
1161 // +---------------+
1162 // | ReturnAddr |
1163 // +===============+
1164
1165 JitSpew(JitSpew_BaselineBailouts, " [RECTIFIER FRAME]");
1166 bool pushedNewTarget = IsConstructPC(pc_);
1167
1168 if (!writePtr(prevFramePtr(), "PrevFramePtr")) {
1169 return false;
1170 }
1171 prevFramePtr_ = virtualPointerAtStackOffset(0);
1172
1173 // Align the stack based on the number of arguments.
1174 size_t afterFrameSize =
1175 (nextCallee()->nargs() + 1 + pushedNewTarget) * sizeof(Value) +
1176 RectifierFrameLayout::Size();
1177 if (!maybeWritePadding(JitStackAlignment, afterFrameSize, "Padding")) {
1178 return false;
1179 }
1180
1181 // Copy new.target, if necessary.
1182 if (pushedNewTarget) {
1183 size_t newTargetOffset = (framePushed() - endOfBaselineStubArgs) +
1184 (actualArgc + 1) * sizeof(Value);
1185 Value newTargetValue = *valuePointerAtStackOffset(newTargetOffset);
1186 if (!writeValue(newTargetValue, "CopiedNewTarget")) {
1187 return false;
1188 }
1189 }
1190
1191 // Push undefined for missing arguments.
1192 for (unsigned i = 0; i < (nextCallee()->nargs() - actualArgc); i++) {
1193 if (!writeValue(UndefinedValue(), "FillerVal")) {
1194 return false;
1195 }
1196 }
1197
1198 // Copy arguments + thisv from BaselineStub frame.
1199 if (!subtract((actualArgc + 1) * sizeof(Value), "CopiedArgs")) {
1200 return false;
1201 }
1202 BufferPointer<uint8_t> stubArgsEnd =
1203 pointerAtStackOffset<uint8_t>(framePushed() - endOfBaselineStubArgs);
1204 JitSpew(JitSpew_BaselineBailouts, " MemCpy from %p", stubArgsEnd.get());
1205 memcpy(pointerAtStackOffset<uint8_t>(0).get(), stubArgsEnd.get(),
1206 (actualArgc + 1) * sizeof(Value));
1207
1208 // Push calleeToken again.
1209 if (!writePtr(CalleeToToken(nextCallee(), pushedNewTarget), "CalleeToken")) {
1210 return false;
1211 }
1212
1213 // Push rectifier frame descriptor
1214 size_t rectifierFrameDescr =
1215 MakeFrameDescriptorForJitCall(FrameType::Rectifier, actualArgc);
1216 if (!writeWord(rectifierFrameDescr, "Descriptor")) {
1217 return false;
1218 }
1219
1220 // Push return address into the ArgumentsRectifier code, immediately after the
1221 // ioncode call.
1222 void* rectReturnAddr =
1223 cx_->runtime()->jitRuntime()->getArgumentsRectifierReturnAddr().value;
1224 MOZ_ASSERT(rectReturnAddr);
1225 if (!writePtr(rectReturnAddr, "ReturnAddr")) {
1226 return false;
1227 }
1228
1229 // The stack must be aligned after the callee pushes the frame pointer.
1230 MOZ_ASSERT((framePushed() + sizeof(void*)) % JitStackAlignment == 0);
1231
1232 return true;
1233 }
1234
1235 bool BaselineStackBuilder::finishLastFrame() {
1236 const BaselineInterpreter& baselineInterp =
1237 cx_->runtime()->jitRuntime()->baselineInterpreter();
1238
1239 setResumeFramePtr(prevFramePtr());
1240
1241 // Compute the native address (within the Baseline Interpreter) that we will
1242 // resume at and initialize the frame's interpreter fields.
1243 uint8_t* resumeAddr;
1244 if (isPrologueBailout()) {
1245 JitSpew(JitSpew_BaselineBailouts, " Resuming into prologue.");
1246 MOZ_ASSERT(pc_ == script_->code());
1247 blFrame()->setInterpreterFieldsForPrologue(script_);
1248 resumeAddr = baselineInterp.bailoutPrologueEntryAddr();
1249 } else if (propagatingIonExceptionForDebugMode()) {
1250 // When propagating an exception for debug mode, set the
1251 // resume pc to the throwing pc, so that Debugger hooks report
1252 // the correct pc offset of the throwing op instead of its
1253 // successor.
1254 jsbytecode* throwPC = script_->offsetToPC(iter_.pcOffset());
1255 blFrame()->setInterpreterFields(script_, throwPC);
1256 resumeAddr = baselineInterp.interpretOpAddr().value;
1257 } else {
1258 jsbytecode* resumePC = getResumePC();
1259 blFrame()->setInterpreterFields(script_, resumePC);
1260 resumeAddr = baselineInterp.interpretOpAddr().value;
1261 }
1262 setResumeAddr(resumeAddr);
1263 JitSpew(JitSpew_BaselineBailouts, " Set resumeAddr=%p", resumeAddr);
1264
1265 if (cx_->runtime()->geckoProfiler().enabled()) {
1266 // Register bailout with profiler.
1267 const char* filename = script_->filename();
1268 if (filename == nullptr) {
1269 filename = "<unknown>";
1270 }
1271 unsigned len = strlen(filename) + 200;
1272 UniqueChars buf(js_pod_malloc<char>(len));
1273 if (buf == nullptr) {
1274 ReportOutOfMemory(cx_);
1275 return false;
1276 }
1277 snprintf(buf.get(), len, "%s %s %s on line %u of %s:%u",
1278 BailoutKindString(bailoutKind()), resumeAfter() ? "after" : "at",
1279 CodeName(op_), PCToLineNumber(script_, pc_), filename,
1280 script_->lineno());
1281 cx_->runtime()->geckoProfiler().markEvent("Bailout", buf.get());
1282 }
1283
1284 return true;
1285 }
1286
1287 #ifdef DEBUG
1288 // The |envChain| slot must not be optimized out if the currently
1289 // active scope requires any EnvironmentObjects beyond what is
1290 // available at body scope. This checks that scope chain does not
1291 // require any such EnvironmentObjects.
1292 // See also: |CompileInfo::isObservableFrameSlot|
1293 bool BaselineStackBuilder::envChainSlotCanBeOptimized() {
1294 jsbytecode* pc = script_->offsetToPC(iter_.pcOffset());
1295 Scope* scopeIter = script_->innermostScope(pc);
1296 while (scopeIter != script_->bodyScope()) {
1297 if (!scopeIter || scopeIter->hasEnvironment()) {
1298 return false;
1299 }
1300 scopeIter = scopeIter->enclosing();
1301 }
1302 return true;
1303 }
1304
1305 bool jit::AssertBailoutStackDepth(JSContext* cx, JSScript* script,
1306 jsbytecode* pc, ResumeMode mode,
1307 uint32_t exprStackSlots) {
1308 if (IsResumeAfter(mode)) {
1309 pc = GetNextPc(pc);
1310 }
1311
1312 uint32_t expectedDepth;
1313 bool reachablePC;
1314 if (!ReconstructStackDepth(cx, script, pc, &expectedDepth, &reachablePC)) {
1315 return false;
1316 }
1317 if (!reachablePC) {
1318 return true;
1319 }
1320
1321 JSOp op = JSOp(*pc);
1322
1323 if (mode == ResumeMode::InlinedFunCall) {
1324 // For inlined fun.call(this, ...); the reconstructed stack depth will
1325 // include the |this|, but the exprStackSlots won't.
1326 // Exception: if there are no arguments, the depths do match.
1327 MOZ_ASSERT(IsInvokeOp(op));
1328 if (GET_ARGC(pc) > 0) {
1329 MOZ_ASSERT(expectedDepth == exprStackSlots + 1);
1330 } else {
1331 MOZ_ASSERT(expectedDepth == exprStackSlots);
1332 }
1333 return true;
1334 }
1335
1336 if (mode == ResumeMode::InlinedAccessor) {
1337 // Accessors coming out of ion are inlined via a complete lie perpetrated by
1338 // the compiler internally. Ion just rearranges the stack, and pretends that
1339 // it looked like a call all along.
1340 // This means that the depth is actually one *more* than expected by the
1341 // interpreter, as there is now a JSFunction, |this| and [arg], rather than
1342 // the expected |this| and [arg].
1343 // If the inlined accessor is a GetElem operation, the numbers do match, but
1344 // that's just because GetElem expects one more item on the stack. Note that
1345 // none of that was pushed, but it's still reflected in exprStackSlots.
1346 MOZ_ASSERT(IsIonInlinableGetterOrSetterOp(op));
1347 if (IsGetElemOp(op)) {
1348 MOZ_ASSERT(exprStackSlots == expectedDepth);
1349 } else {
1350 MOZ_ASSERT(exprStackSlots == expectedDepth + 1);
1351 }
1352 return true;
1353 }
1354
1355 // In all other cases, the depth must match.
1356 MOZ_ASSERT(exprStackSlots == expectedDepth);
1357 return true;
1358 }
1359
1360 bool BaselineStackBuilder::validateFrame() {
1361 const uint32_t frameSize = framePushed();
1362 blFrame()->setDebugFrameSize(frameSize);
1363 JitSpew(JitSpew_BaselineBailouts, " FrameSize=%u", frameSize);
1364
1365 // debugNumValueSlots() is based on the frame size, do some sanity checks.
1366 MOZ_ASSERT(blFrame()->debugNumValueSlots() >= script_->nfixed());
1367 MOZ_ASSERT(blFrame()->debugNumValueSlots() <= script_->nslots());
1368
1369 uint32_t expectedSlots = exprStackSlots();
1370 if (resumingInFinallyBlock()) {
1371 // If we are resuming in a finally block, we push three extra values on the
1372 // stack (the exception, the exception stack, and |throwing|), so the depth
1373 // at the resume PC should be the depth at the fault PC plus three.
1374 expectedSlots += 3;
1375 }
1376 return AssertBailoutStackDepth(cx_, script_, pc_, resumeMode(),
1377 expectedSlots);
1378 }
1379 #endif
1380
1381 void* BaselineStackBuilder::getStubReturnAddress() {
1382 const BaselineICFallbackCode& code =
1383 cx_->runtime()->jitRuntime()->baselineICFallbackCode();
1384
1385 if (IsGetPropOp(op_)) {
1386 return code.bailoutReturnAddr(BailoutReturnKind::GetProp);
1387 }
1388 if (IsSetPropOp(op_)) {
1389 return code.bailoutReturnAddr(BailoutReturnKind::SetProp);
1390 }
1391 if (IsGetElemOp(op_)) {
1392 return code.bailoutReturnAddr(BailoutReturnKind::GetElem);
1393 }
1394
1395 // This should be a call op of some kind, now.
1396 MOZ_ASSERT(IsInvokeOp(op_) && !IsSpreadOp(op_));
1397 if (IsConstructOp(op_)) {
1398 return code.bailoutReturnAddr(BailoutReturnKind::New);
1399 }
1400 return code.bailoutReturnAddr(BailoutReturnKind::Call);
1401 }
1402
1403 static inline jsbytecode* GetNextNonLoopHeadPc(jsbytecode* pc) {
1404 JSOp op = JSOp(*pc);
1405 switch (op) {
1406 case JSOp::Goto:
1407 return pc + GET_JUMP_OFFSET(pc);
1408
1409 case JSOp::LoopHead:
1410 case JSOp::Nop:
1411 return GetNextPc(pc);
1412
1413 default:
1414 return pc;
1415 }
1416 }
1417
1418 // Returns the pc to resume execution at in Baseline after a bailout.
1419 jsbytecode* BaselineStackBuilder::getResumePC() {
1420 if (resumeAfter()) {
1421 return GetNextPc(pc_);
1422 }
1423
1424 // If we are resuming at a LoopHead op, resume at the next op to avoid
1425 // a bailout -> enter Ion -> bailout loop with --ion-eager.
1426 //
1427 // Cycles can cause the loop below to not terminate. Empty loops are one
1428 // such example:
1429 //
1430 // L: loophead
1431 // goto L
1432 //
1433 // We do cycle detection below with the "tortoise and the hare" algorithm.
1434 jsbytecode* slowerPc = pc_;
1435 jsbytecode* fasterPc = pc_;
1436 while (true) {
1437 // Advance fasterPc twice as fast as slowerPc.
1438 slowerPc = GetNextNonLoopHeadPc(slowerPc);
1439 fasterPc = GetNextNonLoopHeadPc(fasterPc);
1440 fasterPc = GetNextNonLoopHeadPc(fasterPc);
1441
1442 // Break on cycles or at the end of goto sequences.
1443 if (fasterPc == slowerPc) {
1444 break;
1445 }
1446 }
1447
1448 return slowerPc;
1449 }
1450
1451 bool BaselineStackBuilder::isPrologueBailout() {
1452 // If we are propagating an exception for debug mode, we will not resume
1453 // into baseline code, but instead into HandleExceptionBaseline (i.e.,
1454 // never before the prologue).
1455 return iter_.pcOffset() == 0 && !iter_.resumeAfter() &&
1456 !propagatingIonExceptionForDebugMode();
1457 }
1458
1459 // Build a baseline stack frame.
1460 bool BaselineStackBuilder::buildOneFrame() {
1461 // Build a baseline frame:
1462 // +===============+
1463 // | PrevFramePtr | <-- initFrame()
1464 // +---------------+
1465 // | Baseline | <-- buildBaselineFrame()
1466 // | Frame |
1467 // +---------------+
1468 // | Fixed0 | <-- buildFixedSlots()
1469 // +---------------+
1470 // | ... |
1471 // +---------------+
1472 // | FixedF |
1473 // +---------------+
1474 // | Stack0 | <-- buildExpressionStack() -or- fixupCallerArgs()
1475 // +---------------+
1476 // | ... |
1477 // +---------------+ If we are building the frame in which we will
1478 // | StackS | <-- resume, we stop here.
1479 // +---------------+ finishLastFrame() sets up the interpreter fields.
1480 // . .
1481 // . .
1482 // . . <-- If there are additional frames inlined into this
1483 // | Descr(BLJS) | one, we finish this frame. We generate a stub
1484 // +---------------+ frame (and maybe also a rectifier frame) between
1485 // | ReturnAddr | this frame and the inlined frame.
1486 // +===============+ See: prepareForNextFrame()
1487
1488 if (!initFrame()) {
1489 return false;
1490 }
1491
1492 if (!buildBaselineFrame()) {
1493 return false;
1494 }
1495
1496 if (fun_ && !buildArguments()) {
1497 return false;
1498 }
1499
1500 if (!buildFixedSlots()) {
1501 return false;
1502 }
1503
1504 bool fixedUp = false;
1505 RootedValueVector savedCallerArgs(cx_);
1506 if (iter_.moreFrames() && !fixUpCallerArgs(&savedCallerArgs, &fixedUp)) {
1507 return false;
1508 }
1509
1510 if (!fixedUp) {
1511 if (!buildExpressionStack()) {
1512 return false;
1513 }
1514 if (resumingInFinallyBlock() && !buildFinallyException()) {
1515 return false;
1516 }
1517 }
1518
1519 #ifdef DEBUG
1520 if (!validateFrame()) {
1521 return false;
1522 }
1523 #endif
1524
1525 #ifdef JS_JITSPEW
1526 const uint32_t pcOff = script_->pcToOffset(pc());
1527 JitSpew(JitSpew_BaselineBailouts,
1528 " Resuming %s pc offset %d (op %s) (line %u) of %s:%u:%u",
1529 resumeAfter() ? "after" : "at", (int)pcOff, CodeName(op_),
1530 PCToLineNumber(script_, pc()), script_->filename(), script_->lineno(),
1531 script_->column().oneOriginValue());
1532 JitSpew(JitSpew_BaselineBailouts, " Bailout kind: %s",
1533 BailoutKindString(bailoutKind()));
1534 #endif
1535
1536 // If this was the last inline frame, or we are bailing out to a catch or
1537 // finally block in this frame, then unpacking is almost done.
1538 if (done()) {
1539 return finishLastFrame();
1540 }
1541
1542 // Otherwise, this is an outer frame for an inlined call or
1543 // accessor. We will be building an inner frame. Before that,
1544 // we must create a stub frame, and potentially a rectifier frame.
1545 return prepareForNextFrame(savedCallerArgs);
1546 }
1547
1548 bool jit::BailoutIonToBaseline(JSContext* cx, JitActivation* activation,
1549 const JSJitFrameIter& iter,
1550 BaselineBailoutInfo** bailoutInfo,
1551 const ExceptionBailoutInfo* excInfo,
1552 BailoutReason reason) {
1553 MOZ_ASSERT(bailoutInfo != nullptr);
1554 MOZ_ASSERT(*bailoutInfo == nullptr);
1555 MOZ_ASSERT(iter.isBailoutJS());
1556
1557 // Caller should have saved the exception while we perform the bailout.
1558 MOZ_ASSERT(!cx->isExceptionPending());
1559
1560 // Ion bailout can fail due to overrecursion and OOM. In such cases we
1561 // cannot honor any further Debugger hooks on the frame, and need to
1562 // ensure that its Debugger.Frame entry is cleaned up.
1563 auto guardRemoveRematerializedFramesFromDebugger =
1564 mozilla::MakeScopeExit([&] {
1565 activation->removeRematerializedFramesFromDebugger(cx, iter.fp());
1566 });
1567
1568 // Always remove the RInstructionResults from the JitActivation, even in
1569 // case of failures as the stack frame is going away after the bailout.
1570 auto removeIonFrameRecovery = mozilla::MakeScopeExit(
1571 [&] { activation->removeIonFrameRecovery(iter.jsFrame()); });
1572
1573 // The caller of the top frame must be one of the following:
1574 // IonJS - Ion calling into Ion.
1575 // BaselineStub - Baseline calling into Ion.
1576 // Entry / WasmToJSJit - Interpreter or other (wasm) calling into Ion.
1577 // Rectifier - Arguments rectifier calling into Ion.
1578 // BaselineJS - Resume'd Baseline, then likely OSR'd into Ion.
1579 MOZ_ASSERT(iter.isBailoutJS());
1580 #if defined(DEBUG) || defined(JS_JITSPEW)
1581 FrameType prevFrameType = iter.prevType();
1582 MOZ_ASSERT(JSJitFrameIter::isEntry(prevFrameType) ||
1583 prevFrameType == FrameType::IonJS ||
1584 prevFrameType == FrameType::BaselineStub ||
1585 prevFrameType == FrameType::Rectifier ||
1586 prevFrameType == FrameType::TrampolineNative ||
1587 prevFrameType == FrameType::IonICCall ||
1588 prevFrameType == FrameType::BaselineJS ||
1589 prevFrameType == FrameType::BaselineInterpreterEntry);
1590 #endif
1591
1592 // All incoming frames are going to look like this:
1593 //
1594 // +---------------+
1595 // | ... |
1596 // +---------------+
1597 // | Args |
1598 // | ... |
1599 // +---------------+
1600 // | ThisV |
1601 // +---------------+
1602 // | ActualArgC |
1603 // +---------------+
1604 // | CalleeToken |
1605 // +---------------+
1606 // | Descriptor |
1607 // +---------------+
1608 // | ReturnAddr |
1609 // +---------------+
1610 // | ||||| | <---- Overwrite starting here.
1611 // | ||||| |
1612 // | ||||| |
1613 // +---------------+
1614
1615 JitSpew(JitSpew_BaselineBailouts,
1616 "Bailing to baseline %s:%u:%u (IonScript=%p) (FrameType=%d)",
1617 iter.script()->filename(), iter.script()->lineno(),
1618 iter.script()->column().oneOriginValue(), (void*)iter.ionScript(),
1619 (int)prevFrameType);
1620
1621 if (excInfo) {
1622 if (excInfo->catchingException()) {
1623 JitSpew(JitSpew_BaselineBailouts, "Resuming in catch or finally block");
1624 }
1625 if (excInfo->propagatingIonExceptionForDebugMode()) {
1626 JitSpew(JitSpew_BaselineBailouts, "Resuming in-place for debug mode");
1627 }
1628 }
1629
1630 JitSpew(JitSpew_BaselineBailouts,
1631 " Reading from snapshot offset %u size %zu", iter.snapshotOffset(),
1632 iter.ionScript()->snapshotsListSize());
1633
1634 iter.script()->updateJitCodeRaw(cx->runtime());
1635
1636 // Under a bailout, there is no need to invalidate the frame after
1637 // evaluating the recover instruction, as the invalidation is only needed in
1638 // cases where the frame is introspected ahead of the bailout.
1639 MaybeReadFallback recoverBailout(cx, activation, &iter,
1640 MaybeReadFallback::Fallback_DoNothing);
1641
1642 // Ensure that all value locations are readable from the SnapshotIterator.
1643 // Get the RInstructionResults from the JitActivation if the frame got
1644 // recovered ahead of the bailout.
1645 SnapshotIterator snapIter(iter, activation->bailoutData()->machineState());
1646 if (!snapIter.initInstructionResults(recoverBailout)) {
1647 return false;
1648 }
1649
1650 #ifdef TRACK_SNAPSHOTS
1651 snapIter.spewBailingFrom();
1652 #endif
1653
1654 BaselineStackBuilder builder(cx, iter, snapIter, excInfo, reason);
1655 if (!builder.init()) {
1656 return false;
1657 }
1658
1659 JitSpew(JitSpew_BaselineBailouts, " Incoming frame ptr = %p",
1660 builder.startFrame());
1661 if (iter.maybeCallee()) {
1662 JitSpew(JitSpew_BaselineBailouts, " Callee function (%s:%u:%u)",
1663 iter.script()->filename(), iter.script()->lineno(),
1664 iter.script()->column().oneOriginValue());
1665 } else {
1666 JitSpew(JitSpew_BaselineBailouts, " No callee!");
1667 }
1668
1669 if (iter.isConstructing()) {
1670 JitSpew(JitSpew_BaselineBailouts, " Constructing!");
1671 } else {
1672 JitSpew(JitSpew_BaselineBailouts, " Not constructing!");
1673 }
1674
1675 JitSpew(JitSpew_BaselineBailouts, " Restoring frames:");
1676
1677 while (true) {
1678 // Skip recover instructions as they are already recovered by
1679 // |initInstructionResults|.
1680 snapIter.settleOnFrame();
1681
1682 JitSpew(JitSpew_BaselineBailouts, " FrameNo %zu", builder.frameNo());
1683
1684 if (!builder.buildOneFrame()) {
1685 MOZ_ASSERT(cx->isExceptionPending());
1686 return false;
1687 }
1688
1689 if (builder.done()) {
1690 break;
1691 }
1692
1693 builder.nextFrame();
1694 }
1695 JitSpew(JitSpew_BaselineBailouts, " Done restoring frames");
1696
1697 BailoutKind bailoutKind = builder.bailoutKind();
1698
1699 if (!builder.outermostFrameFormals().empty()) {
1700 // Set the first frame's formals, see the comment in InitFromBailout.
1701 Value* argv = builder.startFrame()->actualArgs();
1702 mozilla::PodCopy(argv, builder.outermostFrameFormals().begin(),
1703 builder.outermostFrameFormals().length());
1704 }
1705
1706 // Do stack check.
1707 bool overRecursed = false;
1708 BaselineBailoutInfo* info = builder.info();
1709 size_t numBytesToPush = info->copyStackTop - info->copyStackBottom;
1710 MOZ_ASSERT((numBytesToPush % sizeof(uintptr_t)) == 0);
1711 uint8_t* newsp = info->incomingStack - numBytesToPush;
1712 #ifdef JS_SIMULATOR
1713 if (Simulator::Current()->overRecursed(uintptr_t(newsp))) {
1714 overRecursed = true;
1715 }
1716 #else
1717 AutoCheckRecursionLimit recursion(cx);
1718 if (!recursion.checkWithStackPointerDontReport(cx, newsp)) {
1719 overRecursed = true;
1720 }
1721 #endif
1722 if (overRecursed) {
1723 JitSpew(JitSpew_BaselineBailouts, " Overrecursion check failed!");
1724 ReportOverRecursed(cx);
1725 return false;
1726 }
1727
1728 // Take the reconstructed baseline stack so it doesn't get freed when builder
1729 // destructs.
1730 info = builder.takeBuffer();
1731 info->numFrames = builder.frameNo() + 1;
1732 info->bailoutKind.emplace(bailoutKind);
1733 *bailoutInfo = info;
1734 guardRemoveRematerializedFramesFromDebugger.release();
1735 return true;
1736 }
1737
1738 static void InvalidateAfterBailout(JSContext* cx, HandleScript outerScript,
1739 const char* reason) {
1740 // In some cases, the computation of recover instruction can invalidate the
1741 // Ion script before we reach the end of the bailout. Thus, if the outer
1742 // script no longer have any Ion script attached, then we just skip the
1743 // invalidation.
1744 //
1745 // For example, such case can happen if the template object for an unboxed
1746 // objects no longer match the content of its properties (see Bug 1174547)
1747 if (!outerScript->hasIonScript()) {
1748 JitSpew(JitSpew_BaselineBailouts, "Ion script is already invalidated");
1749 return;
1750 }
1751
1752 // Record a invalidation for this script in the jit hints map
1753 if (cx->runtime()->jitRuntime()->hasJitHintsMap()) {
1754 JitHintsMap* jitHints = cx->runtime()->jitRuntime()->getJitHintsMap();
1755 jitHints->recordInvalidation(outerScript);
1756 }
1757
1758 MOZ_ASSERT(!outerScript->ionScript()->invalidated());
1759
1760 JitSpew(JitSpew_BaselineBailouts, "Invalidating due to %s", reason);
1761 Invalidate(cx, outerScript);
1762 }
1763
1764 static void HandleLexicalCheckFailure(JSContext* cx, HandleScript outerScript,
1765 HandleScript innerScript) {
1766 JitSpew(JitSpew_IonBailouts,
1767 "Lexical check failure %s:%u:%u, inlined into %s:%u:%u",
1768 innerScript->filename(), innerScript->lineno(),
1769 innerScript->column().oneOriginValue(), outerScript->filename(),
1770 outerScript->lineno(), outerScript->column().oneOriginValue());
1771
1772 if (!innerScript->failedLexicalCheck()) {
1773 innerScript->setFailedLexicalCheck();
1774 }
1775
1776 InvalidateAfterBailout(cx, outerScript, "lexical check failure");
1777 if (innerScript->hasIonScript()) {
1778 Invalidate(cx, innerScript);
1779 }
1780 }
1781
1782 static bool CopyFromRematerializedFrame(JSContext* cx, JitActivation* act,
1783 uint8_t* fp, size_t inlineDepth,
1784 BaselineFrame* frame) {
1785 RematerializedFrame* rematFrame =
1786 act->lookupRematerializedFrame(fp, inlineDepth);
1787
1788 // We might not have rematerialized a frame if the user never requested a
1789 // Debugger.Frame for it.
1790 if (!rematFrame) {
1791 return true;
1792 }
1793
1794 MOZ_ASSERT(rematFrame->script() == frame->script());
1795 MOZ_ASSERT(rematFrame->numActualArgs() == frame->numActualArgs());
1796
1797 frame->setEnvironmentChain(rematFrame->environmentChain());
1798
1799 if (frame->isFunctionFrame()) {
1800 frame->thisArgument() = rematFrame->thisArgument();
1801 }
1802
1803 for (unsigned i = 0; i < frame->numActualArgs(); i++) {
1804 frame->argv()[i] = rematFrame->argv()[i];
1805 }
1806
1807 for (size_t i = 0; i < frame->script()->nfixed(); i++) {
1808 *frame->valueSlot(i) = rematFrame->locals()[i];
1809 }
1810
1811 if (frame->script()->noScriptRval()) {
1812 frame->setReturnValue(UndefinedValue());
1813 } else {
1814 frame->setReturnValue(rematFrame->returnValue());
1815 }
1816
1817 // Don't copy over the hasCachedSavedFrame bit. The new BaselineFrame we're
1818 // building has a different AbstractFramePtr, so it won't be found in the
1819 // LiveSavedFrameCache if we look there.
1820
1821 JitSpew(JitSpew_BaselineBailouts,
1822 " Copied from rematerialized frame at (%p,%zu)", fp, inlineDepth);
1823
1824 // Propagate the debuggee frame flag. For the case where the Debugger did
1825 // not rematerialize an Ion frame, the baseline frame has its debuggee
1826 // flag set iff its script is considered a debuggee. See the debuggee case
1827 // in InitFromBailout.
1828 if (rematFrame->isDebuggee()) {
1829 frame->setIsDebuggee();
1830 return DebugAPI::handleIonBailout(cx, rematFrame, frame);
1831 }
1832
1833 return true;
1834 }
1835
1836 enum class BailoutAction {
1837 InvalidateImmediately,
1838 InvalidateIfFrequent,
1839 DisableIfFrequent,
1840 NoAction
1841 };
1842
1843 bool jit::FinishBailoutToBaseline(BaselineBailoutInfo* bailoutInfoArg) {
1844 JitSpew(JitSpew_BaselineBailouts, " Done restoring frames");
1845
1846 JSContext* cx = TlsContext.get();
1847 // Use UniquePtr to free the bailoutInfo before we return, and root it for
1848 // the tempId field.
1849 Rooted<UniquePtr<BaselineBailoutInfo>> bailoutInfo(cx, bailoutInfoArg);
1850 bailoutInfoArg = nullptr;
1851
1852 MOZ_DIAGNOSTIC_ASSERT(*bailoutInfo->bailoutKind != BailoutKind::Unreachable);
1853
1854 // jit::Bailout(), jit::InvalidationBailout(), and jit::HandleException()
1855 // should have reset the counter to zero.
1856 MOZ_ASSERT(!cx->isInUnsafeRegion());
1857
1858 BaselineFrame* topFrame = GetTopBaselineFrame(cx);
1859
1860 // We have to get rid of the rematerialized frame, whether it is
1861 // restored or unwound.
1862 uint8_t* incomingStack = bailoutInfo->incomingStack;
1863 auto guardRemoveRematerializedFramesFromDebugger =
1864 mozilla::MakeScopeExit([&] {
1865 JitActivation* act = cx->activation()->asJit();
1866 act->removeRematerializedFramesFromDebugger(cx, incomingStack);
1867 });
1868
1869 // Ensure the frame has a call object if it needs one.
1870 if (!EnsureHasEnvironmentObjects(cx, topFrame)) {
1871 return false;
1872 }
1873
1874 // Create arguments objects for bailed out frames, to maintain the invariant
1875 // that script->needsArgsObj() implies frame->hasArgsObj().
1876 RootedScript innerScript(cx, nullptr);
1877 RootedScript outerScript(cx, nullptr);
1878
1879 MOZ_ASSERT(cx->currentlyRunningInJit());
1880 JSJitFrameIter iter(cx->activation()->asJit());
1881 uint8_t* outerFp = nullptr;
1882
1883 // Iter currently points at the exit frame. Get the previous frame
1884 // (which must be a baseline frame), and set it as the last profiling
1885 // frame.
1886 if (cx->runtime()->jitRuntime()->isProfilerInstrumentationEnabled(
1887 cx->runtime())) {
1888 MOZ_ASSERT(iter.prevType() == FrameType::BaselineJS);
1889 JitFrameLayout* fp = reinterpret_cast<JitFrameLayout*>(iter.prevFp());
1890 cx->jitActivation->setLastProfilingFrame(fp);
1891 }
1892
1893 uint32_t numFrames = bailoutInfo->numFrames;
1894 MOZ_ASSERT(numFrames > 0);
1895
1896 uint32_t frameno = 0;
1897 while (frameno < numFrames) {
1898 MOZ_ASSERT(!iter.isIonJS());
1899
1900 if (iter.isBaselineJS()) {
1901 BaselineFrame* frame = iter.baselineFrame();
1902 MOZ_ASSERT(frame->script()->hasBaselineScript());
1903
1904 // If the frame doesn't even have a env chain set yet, then it's resuming
1905 // into the the prologue before the env chain is initialized. Any
1906 // necessary args object will also be initialized there.
1907 if (frame->environmentChain() && frame->script()->needsArgsObj()) {
1908 ArgumentsObject* argsObj;
1909 if (frame->hasArgsObj()) {
1910 argsObj = &frame->argsObj();
1911 } else {
1912 argsObj = ArgumentsObject::createExpected(cx, frame);
1913 if (!argsObj) {
1914 return false;
1915 }
1916 }
1917
1918 // The arguments is a local binding and needsArgsObj does not
1919 // check if it is clobbered. Ensure that the local binding
1920 // restored during bailout before storing the arguments object
1921 // to the slot.
1922 RootedScript script(cx, frame->script());
1923 SetFrameArgumentsObject(cx, frame, script, argsObj);
1924 }
1925
1926 if (frameno == 0) {
1927 innerScript = frame->script();
1928 }
1929
1930 if (frameno == numFrames - 1) {
1931 outerScript = frame->script();
1932 outerFp = iter.fp();
1933 MOZ_ASSERT(outerFp == incomingStack);
1934 }
1935
1936 frameno++;
1937 }
1938
1939 ++iter;
1940 }
1941
1942 MOZ_ASSERT(innerScript);
1943 MOZ_ASSERT(outerScript);
1944 MOZ_ASSERT(outerFp);
1945
1946 // If we rematerialized Ion frames due to debug mode toggling, copy their
1947 // values into the baseline frame. We need to do this even when debug mode
1948 // is off, as we should respect the mutations made while debug mode was
1949 // on.
1950 JitActivation* act = cx->activation()->asJit();
1951 if (act->hasRematerializedFrame(outerFp)) {
1952 JSJitFrameIter iter(act);
1953 size_t inlineDepth = numFrames;
1954 bool ok = true;
1955 while (inlineDepth > 0) {
1956 if (iter.isBaselineJS()) {
1957 // We must attempt to copy all rematerialized frames over,
1958 // even if earlier ones failed, to invoke the proper frame
1959 // cleanup in the Debugger.
1960 if (!CopyFromRematerializedFrame(cx, act, outerFp, --inlineDepth,
1961 iter.baselineFrame())) {
1962 ok = false;
1963 }
1964 }
1965 ++iter;
1966 }
1967
1968 if (!ok) {
1969 return false;
1970 }
1971
1972 // After copying from all the rematerialized frames, remove them from
1973 // the table to keep the table up to date.
1974 guardRemoveRematerializedFramesFromDebugger.release();
1975 act->removeRematerializedFrame(outerFp);
1976 }
1977
1978 // If we are unwinding for an exception, we need to unwind scopes.
1979 // See |SettleOnTryNote|
1980 if (bailoutInfo->faultPC) {
1981 EnvironmentIter ei(cx, topFrame, bailoutInfo->faultPC);
1982 UnwindEnvironment(cx, ei, bailoutInfo->tryPC);
1983 }
1984
1985 BailoutKind bailoutKind = *bailoutInfo->bailoutKind;
1986 JitSpew(JitSpew_BaselineBailouts,
1987 " Restored outerScript=(%s:%u:%u,%u) innerScript=(%s:%u:%u,%u) "
1988 "(bailoutKind=%u)",
1989 outerScript->filename(), outerScript->lineno(),
1990 outerScript->column().oneOriginValue(), outerScript->getWarmUpCount(),
1991 innerScript->filename(), innerScript->lineno(),
1992 innerScript->column().oneOriginValue(), innerScript->getWarmUpCount(),
1993 (unsigned)bailoutKind);
1994
1995 BailoutAction action = BailoutAction::InvalidateImmediately;
1996 DebugOnly<bool> saveFailedICHash = false;
1997 switch (bailoutKind) {
1998 case BailoutKind::TranspiledCacheIR:
1999 // A transpiled guard failed. If this happens often enough, we will
2000 // invalidate and recompile.
2001 action = BailoutAction::InvalidateIfFrequent;
2002 saveFailedICHash = true;
2003 break;
2004
2005 case BailoutKind::MonomorphicInlinedStubFolding:
2006 action = BailoutAction::InvalidateIfFrequent;
2007 saveFailedICHash = true;
2008 if (innerScript != outerScript) {
2009 // In the case where this instruction comes from a monomorphic-inlined
2010 // ICScript, we need to ensure that we note the connection between the
2011 // inner script and the outer script, so that we can properly track if
2012 // we add a new case to the folded stub and avoid invalidating the
2013 // outer script.
2014 cx->zone()->jitZone()->noteStubFoldingBailout(innerScript, outerScript);
2015 }
2016 break;
2017
2018 case BailoutKind::SpeculativePhi:
2019 // A value of an unexpected type flowed into a phi.
2020 MOZ_ASSERT(!outerScript->hadSpeculativePhiBailout());
2021 if (!outerScript->hasIonScript() ||
2022 outerScript->ionScript()->numFixableBailouts() == 0) {
2023 outerScript->setHadSpeculativePhiBailout();
2024 }
2025 InvalidateAfterBailout(cx, outerScript, "phi specialization failure");
2026 break;
2027
2028 case BailoutKind::TypePolicy:
2029 // A conversion inserted by a type policy failed.
2030 // We will invalidate and disable recompilation if this happens too often.
2031 action = BailoutAction::DisableIfFrequent;
2032 break;
2033
2034 case BailoutKind::LICM:
2035 // LICM may cause spurious bailouts by hoisting unreachable
2036 // guards past branches. To prevent bailout loops, when an
2037 // instruction hoisted by LICM bails out, we update the
2038 // IonScript and resume in baseline. If the guard would have
2039 // been executed anyway, then we will hit the baseline fallback,
2040 // and call noteBaselineFallback. If that does not happen,
2041 // then the next time we reach this point, we will disable LICM
2042 // for this script.
2043 MOZ_ASSERT(!outerScript->hadLICMInvalidation());
2044 if (outerScript->hasIonScript()) {
2045 switch (outerScript->ionScript()->licmState()) {
2046 case IonScript::LICMState::NeverBailed:
2047 outerScript->ionScript()->setHadLICMBailout();
2048 action = BailoutAction::NoAction;
2049 break;
2050 case IonScript::LICMState::Bailed:
2051 outerScript->setHadLICMInvalidation();
2052 InvalidateAfterBailout(cx, outerScript, "LICM failure");
2053 break;
2054 case IonScript::LICMState::BailedAndHitFallback:
2055 // This bailout is not due to LICM. Treat it like a
2056 // regular TranspiledCacheIR bailout.
2057 action = BailoutAction::InvalidateIfFrequent;
2058 break;
2059 }
2060 }
2061 break;
2062
2063 case BailoutKind::InstructionReordering:
2064 // An instruction moved up by instruction reordering bailed out.
2065 outerScript->setHadReorderingBailout();
2066 action = BailoutAction::InvalidateIfFrequent;
2067 break;
2068
2069 case BailoutKind::HoistBoundsCheck:
2070 // An instruction hoisted or generated by tryHoistBoundsCheck bailed out.
2071 MOZ_ASSERT(!outerScript->failedBoundsCheck());
2072 outerScript->setFailedBoundsCheck();
2073 InvalidateAfterBailout(cx, outerScript, "bounds check failure");
2074 break;
2075
2076 case BailoutKind::EagerTruncation:
2077 // An eager truncation generated by range analysis bailed out.
2078 // To avoid bailout loops, we set a flag to avoid generating
2079 // eager truncations next time we recompile.
2080 MOZ_ASSERT(!outerScript->hadEagerTruncationBailout());
2081 outerScript->setHadEagerTruncationBailout();
2082 InvalidateAfterBailout(cx, outerScript, "eager range analysis failure");
2083 break;
2084
2085 case BailoutKind::UnboxFolding:
2086 // An unbox that was hoisted to fold with a load bailed out.
2087 // To avoid bailout loops, we set a flag to avoid folding
2088 // loads with unboxes next time we recompile.
2089 MOZ_ASSERT(!outerScript->hadUnboxFoldingBailout());
2090 outerScript->setHadUnboxFoldingBailout();
2091 InvalidateAfterBailout(cx, outerScript, "unbox folding failure");
2092 break;
2093
2094 case BailoutKind::TooManyArguments:
2095 // A funapply or spread call had more than JIT_ARGS_LENGTH_MAX arguments.
2096 // We will invalidate and disable recompilation if this happens too often.
2097 action = BailoutAction::DisableIfFrequent;
2098 break;
2099
2100 case BailoutKind::DuringVMCall:
2101 if (cx->isExceptionPending()) {
2102 // We are bailing out to catch an exception. We will invalidate
2103 // and disable recompilation if this happens too often.
2104 action = BailoutAction::DisableIfFrequent;
2105 }
2106 break;
2107
2108 case BailoutKind::Finally:
2109 // We are bailing out for a finally block. We will invalidate
2110 // and disable recompilation if this happens too often.
2111 action = BailoutAction::DisableIfFrequent;
2112 break;
2113
2114 case BailoutKind::Inevitable:
2115 case BailoutKind::Debugger:
2116 // Do nothing.
2117 action = BailoutAction::NoAction;
2118 break;
2119
2120 case BailoutKind::FirstExecution:
2121 // We reached an instruction that had not been executed yet at
2122 // the time we compiled. If this happens often enough, we will
2123 // invalidate and recompile.
2124 action = BailoutAction::InvalidateIfFrequent;
2125 saveFailedICHash = true;
2126 break;
2127
2128 case BailoutKind::UninitializedLexical:
2129 HandleLexicalCheckFailure(cx, outerScript, innerScript);
2130 break;
2131
2132 case BailoutKind::ThrowCheckIsObject:
2133 MOZ_ASSERT(!cx->isExceptionPending());
2134 return ThrowCheckIsObject(cx, CheckIsObjectKind::IteratorReturn);
2135
2136 case BailoutKind::ThrowProxyTrapMustReportSameValue:
2137 case BailoutKind::ThrowProxyTrapMustReportUndefined: {
2138 MOZ_ASSERT(!cx->isExceptionPending());
2139 RootedId rootedId(cx, bailoutInfo->tempId);
2140 ScriptedProxyHandler::reportGetTrapValidationError(
2141 cx, rootedId,
2142 bailoutKind == BailoutKind::ThrowProxyTrapMustReportSameValue
2143 ? ScriptedProxyHandler::GetTrapValidationResult::
2144 MustReportSameValue
2145 : ScriptedProxyHandler::GetTrapValidationResult::
2146 MustReportUndefined);
2147 return false;
2148 }
2149
2150 case BailoutKind::IonExceptionDebugMode:
2151 // Return false to resume in HandleException with reconstructed
2152 // baseline frame.
2153 return false;
2154
2155 case BailoutKind::OnStackInvalidation:
2156 // The script has already been invalidated. There is nothing left to do.
2157 action = BailoutAction::NoAction;
2158 break;
2159
2160 default:
2161 MOZ_CRASH("Unknown bailout kind!");
2162 }
2163
2164 #ifdef DEBUG
2165 if (MOZ_UNLIKELY(cx->runtime()->jitRuntime()->ionBailAfterEnabled())) {
2166 action = BailoutAction::NoAction;
2167 }
2168 #endif
2169
2170 if (outerScript->hasIonScript()) {
2171 IonScript* ionScript = outerScript->ionScript();
2172 switch (action) {
2173 case BailoutAction::InvalidateImmediately:
2174 // The IonScript should already have been invalidated.
2175 MOZ_ASSERT(false);
2176 break;
2177 case BailoutAction::InvalidateIfFrequent:
2178 ionScript->incNumFixableBailouts();
2179 if (ionScript->shouldInvalidate()) {
2180 #ifdef DEBUG
2181 // To detect bailout loops, we save a hash of the CacheIR used to
2182 // compile this script, and assert that we don't recompile with the
2183 // exact same inputs. Some of our bailout detection strategies, like
2184 // LICM and stub folding, rely on bailing out, updating some state
2185 // when we hit the baseline fallback, and using that information when
2186 // we invalidate. If the frequentBailoutThreshold is set too low, we
2187 // will instead invalidate the first time we bail out, so we don't
2188 // have the chance to make those decisions. That doesn't happen in
2189 // regular code, so we just skip bailout loop detection in that case.
2190 if (saveFailedICHash && !JitOptions.disableBailoutLoopCheck &&
2191 JitOptions.frequentBailoutThreshold > 1) {
2192 outerScript->jitScript()->setFailedICHash(ionScript->icHash());
2193 }
2194 #endif
2195 InvalidateAfterBailout(cx, outerScript, "fixable bailouts");
2196 }
2197 break;
2198 case BailoutAction::DisableIfFrequent:
2199 ionScript->incNumUnfixableBailouts();
2200 if (ionScript->shouldInvalidateAndDisable()) {
2201 InvalidateAfterBailout(cx, outerScript, "unfixable bailouts");
2202 outerScript->disableIon();
2203 }
2204 break;
2205 case BailoutAction::NoAction:
2206 break;
2207 }
2208 }
2209
2210 return true;
2211 }