Debian Codegraph @

js/src/jit/shared/CodeGenerator-shared.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/shared/CodeGenerator-shared-inl.h"
8
9 #include "mozilla/DebugOnly.h"
10
11 #include <utility>
12
13 #include "jit/CodeGenerator.h"
14 #include "jit/CompactBuffer.h"
15 #include "jit/CompileInfo.h"
16 #include "jit/InlineScriptTree.h"
17 #include "jit/JitcodeMap.h"
18 #include "jit/JitFrames.h"
19 #include "jit/JitSpewer.h"
20 #include "jit/MacroAssembler.h"
21 #include "jit/MIR-wasm.h"
22 #include "jit/MIR.h"
23 #include "jit/MIRGenerator.h"
24 #include "jit/SafepointIndex.h"
25 #include "js/Conversions.h"
26 #include "util/Memory.h"
27
28 #include "jit/MacroAssembler-inl.h"
29 #include "vm/JSScript-inl.h"
30
31 using namespace js;
32 using namespace js::jit;
33
34 using mozilla::BitwiseCast;
35 using mozilla::DebugOnly;
36
37 namespace js {
38 namespace jit {
39
40 MacroAssembler& CodeGeneratorShared::ensureMasm(MacroAssembler* masmArg,
41 TempAllocator& alloc,
42 CompileRealm* realm) {
43 if (masmArg) {
44 return *masmArg;
45 }
46 maybeMasm_.emplace(alloc, realm);
47 return *maybeMasm_;
48 }
49
50 CodeGeneratorShared::CodeGeneratorShared(MIRGenerator* gen, LIRGraph* graph,
51 MacroAssembler* masmArg,
52 const wasm::CodeMetadata* wasmCodeMeta)
53 : masm(ensureMasm(masmArg, gen->alloc(), gen->realm)),
54 gen(gen),
55 graph(*graph),
56 wasmCodeMeta_(wasmCodeMeta),
57 current(nullptr),
58 recovers_(),
59 #ifdef DEBUG
60 pushedArgs_(0),
61 #endif
62 lastOsiPointOffset_(0),
63 safepoints_(graph->localSlotsSize(),
64 (gen->outerInfo().nargs() + 1) * sizeof(Value)),
65 returnLabel_(),
66 inboundStackArgBytes_(0),
67 safepointIndices_(gen->alloc()),
68 nativeToBytecodeMap_(nullptr),
69 nativeToBytecodeMapSize_(0),
70 nativeToBytecodeTableOffset_(0),
71 #ifdef CHECK_OSIPOINT_REGISTERS
72 checkOsiPointRegisters(JitOptions.checkOsiPointRegisters),
73 #endif
74 frameDepth_(0) {
75 if (gen->isProfilerInstrumentationEnabled()) {
76 masm.enableProfilingInstrumentation();
77 }
78
79 if (gen->compilingWasm()) {
80 offsetOfArgsFromFP_ = sizeof(wasm::Frame);
81
82 #ifdef JS_CODEGEN_ARM64
83 // Ensure SP is aligned to 16 bytes.
84 frameDepth_ = AlignBytes(graph->localSlotsSize(), WasmStackAlignment);
85 #else
86 frameDepth_ = AlignBytes(graph->localSlotsSize(), sizeof(uintptr_t));
87 #endif
88
89 #ifdef ENABLE_WASM_SIMD
90 # if defined(JS_CODEGEN_X64) || defined(JS_CODEGEN_X86) || \
91 defined(JS_CODEGEN_ARM64)
92 // On X64/x86 and ARM64, we don't need alignment for Wasm SIMD at this time.
93 # else
94 # error \
95 "we may need padding so that local slots are SIMD-aligned and the stack must be kept SIMD-aligned too."
96 # endif
97 #endif
98
99 if (gen->needsStaticStackAlignment()) {
100 // Since wasm uses the system ABI which does not necessarily use a
101 // regular array where all slots are sizeof(Value), it maintains the max
102 // argument stack depth separately.
103 MOZ_ASSERT(graph->argumentSlotCount() == 0);
104
105 // An MWasmCall does not align the stack pointer at calls sites but
106 // instead relies on the a priori stack adjustment. We need to insert
107 // padding so that pushing the callee's frame maintains frame alignment.
108 uint32_t calleeFramePadding = ComputeByteAlignment(
109 sizeof(wasm::Frame) + frameDepth_, WasmStackAlignment);
110
111 // Tail calls expect the size of stack arguments to be a multiple of
112 // stack alignment when collapsing frames. This ensures that future tail
113 // calls don't overwrite any locals.
114 uint32_t stackArgsWithPadding =
115 AlignBytes(gen->wasmMaxStackArgBytes(), WasmStackAlignment);
116
117 // Add the callee frame padding and stack args to frameDepth.
118 frameDepth_ += calleeFramePadding + stackArgsWithPadding;
119 }
120
121 #ifdef JS_CODEGEN_ARM64
122 MOZ_ASSERT((frameDepth_ % WasmStackAlignment) == 0,
123 "Trap exit stub needs 16-byte aligned stack pointer");
124 #endif
125 } else {
126 offsetOfArgsFromFP_ = sizeof(JitFrameLayout);
127
128 // Allocate space for local slots (register allocator spills). Round to
129 // JitStackAlignment, and implicitly to sizeof(Value) as JitStackAlignment
130 // is a multiple of sizeof(Value). This was originally implemented for
131 // SIMD.js, but now lets us use faster ABI calls via setupAlignedABICall.
132 frameDepth_ = AlignBytes(graph->localSlotsSize(), JitStackAlignment);
133
134 // Allocate space for argument Values passed to callee functions.
135 offsetOfPassedArgSlots_ = frameDepth_;
136 MOZ_ASSERT((offsetOfPassedArgSlots_ % sizeof(JS::Value)) == 0);
137 frameDepth_ += graph->argumentSlotCount() * sizeof(JS::Value);
138
139 MOZ_ASSERT((frameDepth_ % JitStackAlignment) == 0);
140 }
141 }
142
143 bool CodeGeneratorShared::generatePrologue() {
144 MOZ_ASSERT(masm.framePushed() == 0);
145 MOZ_ASSERT(!gen->compilingWasm());
146
147 #ifdef JS_USE_LINK_REGISTER
148 masm.pushReturnAddress();
149 #endif
150
151 // Frame prologue.
152 masm.push(FramePointer);
153 masm.moveStackPtrTo(FramePointer);
154
155 // Ensure that the Ion frame is properly aligned.
156 masm.assertStackAlignment(JitStackAlignment, 0);
157
158 // If profiling, save the current frame pointer to a per-thread global field.
159 if (isProfilerInstrumentationEnabled()) {
160 masm.profilerEnterFrame(FramePointer, CallTempReg0);
161 }
162
163 // Note that this automatically sets MacroAssembler::framePushed().
164 masm.reserveStack(frameSize());
165 MOZ_ASSERT(masm.framePushed() == frameSize());
166 masm.checkStackAlignment();
167
168 return true;
169 }
170
171 bool CodeGeneratorShared::generateEpilogue() {
172 MOZ_ASSERT(!gen->compilingWasm());
173 masm.bind(&returnLabel_);
174
175 // If profiling, jump to a trampoline to reset the JitActivation's
176 // lastProfilingFrame to point to the previous frame and return to the caller.
177 if (isProfilerInstrumentationEnabled()) {
178 masm.profilerExitFrame();
179 }
180
181 MOZ_ASSERT(masm.framePushed() == frameSize());
182 masm.moveToStackPtr(FramePointer);
183 masm.pop(FramePointer);
184 masm.setFramePushed(0);
185
186 masm.ret();
187
188 // On systems that use a constant pool, this is a good time to emit.
189 masm.flushBuffer();
190 return true;
191 }
192
193 bool CodeGeneratorShared::generateOutOfLineCode() {
194 AutoCreatedBy acb(masm, "CodeGeneratorShared::generateOutOfLineCode");
195
196 // OOL paths should not attempt to use |current| as it's the last block
197 // instead of the block corresponding to the OOL path.
198 current = nullptr;
199
200 for (OutOfLineCode* ool : outOfLineCode_) {
201 if (gen->shouldCancel("Generate Code (OOL code loop)")) {
202 return false;
203 }
204
205 // Add native => bytecode mapping entries for OOL->sites.
206 // Not enabled on wasm yet since it doesn't contain bytecode mappings.
207 if (!gen->compilingWasm()) {
208 if (!addNativeToBytecodeEntry(ool->bytecodeSite())) {
209 return false;
210 }
211 }
212
213 if (!gen->alloc().ensureBallast()) {
214 return false;
215 }
216
217 JitSpew(JitSpew_Codegen, "# Emitting out of line code");
218
219 masm.setFramePushed(ool->framePushed());
220 ool->bind(&masm);
221
222 ool->generate(this);
223 }
224
225 return !masm.oom();
226 }
227
228 void CodeGeneratorShared::addOutOfLineCode(OutOfLineCode* code,
229 const MInstruction* mir) {
230 MOZ_ASSERT(mir);
231 addOutOfLineCode(code, mir->trackedSite());
232 }
233
234 void CodeGeneratorShared::addOutOfLineCode(OutOfLineCode* code,
235 const BytecodeSite* site) {
236 MOZ_ASSERT_IF(!gen->compilingWasm(), site->script()->containsPC(site->pc()));
237 code->setFramePushed(masm.framePushed());
238 code->setBytecodeSite(site);
239 outOfLineCode_.pushBack(code);
240 }
241
242 bool CodeGeneratorShared::addNativeToBytecodeEntry(const BytecodeSite* site) {
243 MOZ_ASSERT(site);
244 MOZ_ASSERT(site->tree());
245 MOZ_ASSERT(site->pc());
246
247 // Skip the table entirely if profiling is not enabled.
248 if (!isProfilerInstrumentationEnabled()) {
249 return true;
250 }
251
252 // Fails early if the last added instruction caused the macro assembler to
253 // run out of memory as continuity assumption below do not hold.
254 if (masm.oom()) {
255 return false;
256 }
257
258 InlineScriptTree* tree = site->tree();
259 jsbytecode* pc = site->pc();
260 uint32_t nativeOffset = masm.currentOffset();
261
262 MOZ_ASSERT_IF(nativeToBytecodeList_.empty(), nativeOffset == 0);
263
264 if (!nativeToBytecodeList_.empty()) {
265 size_t lastIdx = nativeToBytecodeList_.length() - 1;
266 NativeToBytecode& lastEntry = nativeToBytecodeList_[lastIdx];
267
268 MOZ_ASSERT(nativeOffset >= lastEntry.nativeOffset.offset());
269
270 // If the new entry is for the same inlineScriptTree and same
271 // bytecodeOffset, but the nativeOffset has changed, do nothing.
272 // The same site just generated some more code.
273 if (lastEntry.tree == tree && lastEntry.pc == pc) {
274 JitSpew(JitSpew_Profiling, " => In-place update [%zu-%" PRIu32 "]",
275 lastEntry.nativeOffset.offset(), nativeOffset);
276 return true;
277 }
278
279 // If the new entry is for the same native offset, then update the
280 // previous entry with the new bytecode site, since the previous
281 // bytecode site did not generate any native code.
282 if (lastEntry.nativeOffset.offset() == nativeOffset) {
283 lastEntry.tree = tree;
284 lastEntry.pc = pc;
285 JitSpew(JitSpew_Profiling, " => Overwriting zero-length native region.");
286
287 // This overwrite might have made the entry merge-able with a
288 // previous one. If so, merge it.
289 if (lastIdx > 0) {
290 NativeToBytecode& nextToLastEntry = nativeToBytecodeList_[lastIdx - 1];
291 if (nextToLastEntry.tree == lastEntry.tree &&
292 nextToLastEntry.pc == lastEntry.pc) {
293 JitSpew(JitSpew_Profiling, " => Merging with previous region");
294 nativeToBytecodeList_.erase(&lastEntry);
295 }
296 }
297
298 dumpNativeToBytecodeEntry(nativeToBytecodeList_.length() - 1);
299 return true;
300 }
301 }
302
303 // Otherwise, some native code was generated for the previous bytecode site.
304 // Add a new entry for code that is about to be generated.
305 NativeToBytecode entry;
306 entry.nativeOffset = CodeOffset(nativeOffset);
307 entry.tree = tree;
308 entry.pc = pc;
309 if (!nativeToBytecodeList_.append(entry)) {
310 return false;
311 }
312
313 JitSpew(JitSpew_Profiling, " => Push new entry.");
314 dumpNativeToBytecodeEntry(nativeToBytecodeList_.length() - 1);
315 return true;
316 }
317
318 void CodeGeneratorShared::dumpNativeToBytecodeEntries() {
319 #ifdef JS_JITSPEW
320 InlineScriptTree* topTree = gen->outerInfo().inlineScriptTree();
321 JitSpewStart(JitSpew_Profiling, "Native To Bytecode Entries for %s:%u:%u\n",
322 topTree->script()->filename(), topTree->script()->lineno(),
323 topTree->script()->column().oneOriginValue());
324 for (unsigned i = 0; i < nativeToBytecodeList_.length(); i++) {
325 dumpNativeToBytecodeEntry(i);
326 }
327 #endif
328 }
329
330 void CodeGeneratorShared::dumpNativeToBytecodeEntry(uint32_t idx) {
331 #ifdef JS_JITSPEW
332 NativeToBytecode& ref = nativeToBytecodeList_[idx];
333 InlineScriptTree* tree = ref.tree;
334 JSScript* script = tree->script();
335 uint32_t nativeOffset = ref.nativeOffset.offset();
336 unsigned nativeDelta = 0;
337 unsigned pcDelta = 0;
338 if (idx + 1 < nativeToBytecodeList_.length()) {
339 NativeToBytecode* nextRef = &ref + 1;
340 nativeDelta = nextRef->nativeOffset.offset() - nativeOffset;
341 if (nextRef->tree == ref.tree) {
342 pcDelta = nextRef->pc - ref.pc;
343 }
344 }
345 JitSpewStart(
346 JitSpew_Profiling, " %08zx [+%-6u] => %-6ld [%-4u] {%-10s} (%s:%u:%u",
347 ref.nativeOffset.offset(), nativeDelta, (long)(ref.pc - script->code()),
348 pcDelta, CodeName(JSOp(*ref.pc)), script->filename(), script->lineno(),
349 script->column().oneOriginValue());
350
351 for (tree = tree->caller(); tree; tree = tree->caller()) {
352 JitSpewCont(JitSpew_Profiling, " <= %s:%u:%u", tree->script()->filename(),
353 tree->script()->lineno(),
354 tree->script()->column().oneOriginValue());
355 }
356 JitSpewCont(JitSpew_Profiling, ")");
357 JitSpewFin(JitSpew_Profiling);
358 #endif
359 }
360
361 // see OffsetOfFrameSlot
362 static inline int32_t ToStackIndex(LAllocation* a) {
363 if (a->isStackSlot()) {
364 MOZ_ASSERT(a->toStackSlot()->slot() >= 1);
365 return a->toStackSlot()->slot();
366 }
367 return -int32_t(sizeof(JitFrameLayout) + a->toArgument()->index());
368 }
369
370 void CodeGeneratorShared::encodeAllocation(LSnapshot* snapshot,
371 MDefinition* mir,
372 uint32_t* allocIndex,
373 bool hasSideEffects) {
374 if (mir->isBox()) {
375 mir = mir->toBox()->getOperand(0);
376 }
377
378 MIRType type = mir->isRecoveredOnBailout() ? MIRType::None
379 : mir->isUnused() ? MIRType::MagicOptimizedOut
380 : mir->type();
381
382 RValueAllocation alloc;
383
384 switch (type) {
385 case MIRType::None: {
386 MOZ_ASSERT(mir->isRecoveredOnBailout());
387 uint32_t index = 0;
388 LRecoverInfo* recoverInfo = snapshot->recoverInfo();
389 MNode** it = recoverInfo->begin();
390 MNode** end = recoverInfo->end();
391 while (it != end && mir != *it) {
392 ++it;
393 ++index;
394 }
395
396 // This MDefinition is recovered, thus it should be listed in the
397 // LRecoverInfo.
398 MOZ_ASSERT(it != end && mir == *it);
399
400 // Lambda should have a default value readable for iterating over the
401 // inner frames.
402 MConstant* functionOperand = nullptr;
403 if (mir->isLambda()) {
404 functionOperand = mir->toLambda()->functionOperand();
405 } else if (mir->isFunctionWithProto()) {
406 functionOperand = mir->toFunctionWithProto()->functionOperand();
407 }
408 if (functionOperand) {
409 uint32_t cstIndex;
410 masm.propagateOOM(
411 graph.addConstantToPool(functionOperand->toJSValue(), &cstIndex));
412 alloc = RValueAllocation::RecoverInstruction(index, cstIndex);
413 break;
414 }
415
416 alloc = RValueAllocation::RecoverInstruction(index);
417 break;
418 }
419 case MIRType::Undefined:
420 alloc = RValueAllocation::Undefined();
421 break;
422 case MIRType::Null:
423 alloc = RValueAllocation::Null();
424 break;
425 case MIRType::Int32:
426 case MIRType::String:
427 case MIRType::Symbol:
428 case MIRType::BigInt:
429 case MIRType::Object:
430 case MIRType::Shape:
431 case MIRType::Boolean:
432 case MIRType::Double: {
433 LAllocation* payload = snapshot->payloadOfSlot(*allocIndex);
434 if (payload->isConstant()) {
435 MConstant* constant = mir->toConstant();
436 uint32_t index;
437 masm.propagateOOM(
438 graph.addConstantToPool(constant->toJSValue(), &index));
439 alloc = RValueAllocation::ConstantPool(index);
440 break;
441 }
442
443 JSValueType valueType = ValueTypeFromMIRType(type);
444
445 MOZ_DIAGNOSTIC_ASSERT(payload->isMemory() || payload->isAnyRegister());
446 if (payload->isMemory()) {
447 MOZ_ASSERT_IF(payload->isStackSlot(),
448 payload->toStackSlot()->width() ==
449 LStackSlot::width(LDefinition::TypeFrom(type)));
450 alloc = RValueAllocation::Typed(valueType, ToStackIndex(payload));
451 } else if (payload->isGeneralReg()) {
452 alloc = RValueAllocation::Typed(valueType, ToRegister(payload));
453 } else if (payload->isFloatReg()) {
454 alloc = RValueAllocation::Double(ToFloatRegister(payload));
455 } else {
456 MOZ_CRASH("Unexpected payload type.");
457 }
458 break;
459 }
460 case MIRType::Float32: {
461 LAllocation* payload = snapshot->payloadOfSlot(*allocIndex);
462 if (payload->isConstant()) {
463 MConstant* constant = mir->toConstant();
464 uint32_t index;
465 masm.propagateOOM(
466 graph.addConstantToPool(constant->toJSValue(), &index));
467 alloc = RValueAllocation::ConstantPool(index);
468 break;
469 }
470
471 if (payload->isFloatReg()) {
472 alloc = RValueAllocation::Float32(ToFloatRegister(payload));
473 } else if (payload->isMemory()) {
474 MOZ_ASSERT_IF(payload->isStackSlot(),
475 payload->toStackSlot()->width() ==
476 LStackSlot::width(LDefinition::TypeFrom(type)));
477 alloc = RValueAllocation::Float32(ToStackIndex(payload));
478 } else {
479 MOZ_CRASH("Unexpected payload type.");
480 }
481 break;
482 }
483 case MIRType::IntPtr: {
484 LAllocation* payload = snapshot->payloadOfSlot(*allocIndex);
485 if (payload->isConstant()) {
486 intptr_t constant = mir->toConstant()->toIntPtr();
487 #if !defined(JS_64BIT)
488 uint32_t index;
489 masm.propagateOOM(
490 graph.addConstantToPool(Int32Value(constant), &index));
491
492 alloc = RValueAllocation::IntPtrConstant(index);
493 #else
494 uint32_t lowIndex;
495 masm.propagateOOM(
496 graph.addConstantToPool(Int32Value(constant), &lowIndex));
497
498 uint32_t highIndex;
499 masm.propagateOOM(
500 graph.addConstantToPool(Int32Value(constant >> 32), &highIndex));
501
502 alloc = RValueAllocation::IntPtrConstant(lowIndex, highIndex);
503 #endif
504 break;
505 }
506
507 if (payload->isGeneralReg()) {
508 alloc = RValueAllocation::IntPtr(ToRegister(payload));
509 } else if (payload->isStackSlot()) {
510 LStackSlot::Width width = payload->toStackSlot()->width();
511 MOZ_ASSERT(width == LStackSlot::width(LDefinition::GENERAL) ||
512 width == LStackSlot::width(LDefinition::INT32));
513
514 if (width == LStackSlot::width(LDefinition::GENERAL)) {
515 alloc = RValueAllocation::IntPtr(ToStackIndex(payload));
516 } else {
517 alloc = RValueAllocation::IntPtrInt32(ToStackIndex(payload));
518 }
519 } else {
520 MOZ_CRASH("Unexpected payload type.");
521 }
522 break;
523 }
524 case MIRType::MagicOptimizedOut:
525 case MIRType::MagicUninitializedLexical:
526 case MIRType::MagicIsConstructing: {
527 uint32_t index;
528 JSWhyMagic why = JS_GENERIC_MAGIC;
529 switch (type) {
530 case MIRType::MagicOptimizedOut:
531 why = JS_OPTIMIZED_OUT;
532 break;
533 case MIRType::MagicUninitializedLexical:
534 why = JS_UNINITIALIZED_LEXICAL;
535 break;
536 case MIRType::MagicIsConstructing:
537 why = JS_IS_CONSTRUCTING;
538 break;
539 default:
540 MOZ_CRASH("Invalid Magic MIRType");
541 }
542
543 Value v = MagicValue(why);
544 masm.propagateOOM(graph.addConstantToPool(v, &index));
545 alloc = RValueAllocation::ConstantPool(index);
546 break;
547 }
548 case MIRType::Int64: {
549 LAllocation* payload = snapshot->payloadOfSlot(*allocIndex);
550 if (payload->isConstant()) {
551 int64_t constant = mir->toConstant()->toInt64();
552
553 uint32_t lowIndex;
554 masm.propagateOOM(
555 graph.addConstantToPool(Int32Value(constant), &lowIndex));
556
557 uint32_t highIndex;
558 masm.propagateOOM(
559 graph.addConstantToPool(Int32Value(constant >> 32), &highIndex));
560
561 alloc = RValueAllocation::Int64Constant(lowIndex, highIndex);
562 break;
563 }
564
565 #ifdef JS_NUNBOX32
566 LAllocation* type = snapshot->typeOfSlot(*allocIndex);
567
568 MOZ_ASSERT_IF(payload->isStackSlot(),
569 payload->toStackSlot()->width() ==
570 LStackSlot::width(LDefinition::GENERAL));
571 MOZ_ASSERT_IF(type->isStackSlot(),
572 type->toStackSlot()->width() ==
573 LStackSlot::width(LDefinition::GENERAL));
574
575 if (payload->isGeneralReg()) {
576 if (type->isGeneralReg()) {
577 alloc =
578 RValueAllocation::Int64(ToRegister(type), ToRegister(payload));
579 } else if (type->isStackSlot()) {
580 alloc =
581 RValueAllocation::Int64(ToStackIndex(type), ToRegister(payload));
582 } else {
583 MOZ_CRASH("Unexpected payload type.");
584 }
585 } else if (payload->isStackSlot()) {
586 if (type->isGeneralReg()) {
587 alloc =
588 RValueAllocation::Int64(ToRegister(type), ToStackIndex(payload));
589 } else if (type->isStackSlot()) {
590 alloc = RValueAllocation::Int64(ToStackIndex(type),
591 ToStackIndex(payload));
592 } else {
593 MOZ_CRASH("Unexpected payload type.");
594 }
595 } else {
596 MOZ_CRASH("Unexpected payload type.");
597 }
598 #elif JS_PUNBOX64
599 if (payload->isGeneralReg()) {
600 alloc = RValueAllocation::Int64(ToRegister(payload));
601 } else if (payload->isStackSlot()) {
602 LStackSlot::Width width = payload->toStackSlot()->width();
603 MOZ_ASSERT(width == LStackSlot::width(LDefinition::GENERAL) ||
604 width == LStackSlot::width(LDefinition::INT32));
605 if (width == LStackSlot::width(LDefinition::GENERAL)) {
606 alloc = RValueAllocation::Int64(ToStackIndex(payload));
607 } else {
608 alloc = RValueAllocation::Int64Int32(ToStackIndex(payload));
609 }
610 } else {
611 MOZ_CRASH("Unexpected payload type.");
612 }
613 #endif
614 break;
615 }
616 case MIRType::Value: {
617 LAllocation* payload = snapshot->payloadOfSlot(*allocIndex);
618 #ifdef JS_NUNBOX32
619 LAllocation* type = snapshot->typeOfSlot(*allocIndex);
620 if (type->isGeneralReg()) {
621 if (payload->isGeneralReg()) {
622 alloc =
623 RValueAllocation::Untyped(ToRegister(type), ToRegister(payload));
624 } else {
625 alloc = RValueAllocation::Untyped(ToRegister(type),
626 ToStackIndex(payload));
627 }
628 } else {
629 if (payload->isGeneralReg()) {
630 alloc = RValueAllocation::Untyped(ToStackIndex(type),
631 ToRegister(payload));
632 } else {
633 alloc = RValueAllocation::Untyped(ToStackIndex(type),
634 ToStackIndex(payload));
635 }
636 }
637 #elif JS_PUNBOX64
638 if (payload->isGeneralReg()) {
639 alloc = RValueAllocation::Untyped(ToRegister(payload));
640 } else {
641 alloc = RValueAllocation::Untyped(ToStackIndex(payload));
642 }
643 #endif
644 break;
645 }
646 default:
647 MOZ_CRASH("Unexpected MIR type");
648 }
649 MOZ_DIAGNOSTIC_ASSERT(alloc.valid());
650
651 // This set an extra bit as part of the RValueAllocation, such that we know
652 // that recover instruction have to be executed without wrapping the
653 // instruction in a no-op recover instruction.
654 //
655 // If the instruction claims to have side-effect but none are registered in
656 // the list of recover instructions, then omit the annotation of the
657 // RValueAllocation as requiring the execution of these side effects before
658 // being readable.
659 if (mir->isIncompleteObject() && hasSideEffects) {
660 alloc.setNeedSideEffect();
661 }
662
663 masm.propagateOOM(snapshots_.add(alloc));
664
665 *allocIndex += mir->isRecoveredOnBailout() ? 0 : 1;
666 }
667
668 void CodeGeneratorShared::encode(LRecoverInfo* recover) {
669 if (recover->recoverOffset() != INVALID_RECOVER_OFFSET) {
670 return;
671 }
672
673 uint32_t numInstructions = recover->numInstructions();
674 JitSpew(JitSpew_IonSnapshots,
675 "Encoding LRecoverInfo %p (frameCount %u, instructions %u)",
676 (void*)recover, recover->mir()->frameCount(), numInstructions);
677
678 RecoverOffset offset = recovers_.startRecover(numInstructions);
679
680 for (MNode* insn : *recover) {
681 recovers_.writeInstruction(insn);
682 }
683
684 recovers_.endRecover();
685 recover->setRecoverOffset(offset);
686 masm.propagateOOM(!recovers_.oom());
687 }
688
689 void CodeGeneratorShared::encode(LSnapshot* snapshot) {
690 if (snapshot->snapshotOffset() != INVALID_SNAPSHOT_OFFSET) {
691 return;
692 }
693
694 LRecoverInfo* recoverInfo = snapshot->recoverInfo();
695 encode(recoverInfo);
696
697 RecoverOffset recoverOffset = recoverInfo->recoverOffset();
698 MOZ_ASSERT(recoverOffset != INVALID_RECOVER_OFFSET);
699
700 JitSpew(JitSpew_IonSnapshots, "Encoding LSnapshot %p (LRecover %p)",
701 (void*)snapshot, (void*)recoverInfo);
702
703 SnapshotOffset offset =
704 snapshots_.startSnapshot(recoverOffset, snapshot->bailoutKind());
705
706 #ifdef TRACK_SNAPSHOTS
707 uint32_t pcOpcode = 0;
708 uint32_t lirOpcode = 0;
709 uint32_t lirId = 0;
710 uint32_t mirOpcode = 0;
711 uint32_t mirId = 0;
712
713 if (LInstruction* ins = instruction()) {
714 lirOpcode = uint32_t(ins->op());
715 lirId = ins->id();
716 if (MDefinition* mir = ins->mirRaw()) {
717 mirOpcode = uint32_t(mir->op());
718 mirId = mir->id();
719 if (jsbytecode* pc = mir->trackedSite()->pc()) {
720 pcOpcode = *pc;
721 }
722 }
723 }
724 snapshots_.trackSnapshot(pcOpcode, mirOpcode, mirId, lirOpcode, lirId);
725 #endif
726
727 bool hasSideEffects = recoverInfo->hasSideEffects();
728 uint32_t allocIndex = 0;
729 for (LRecoverInfo::OperandIter it(recoverInfo); !it; ++it) {
730 DebugOnly<uint32_t> allocWritten = snapshots_.allocWritten();
731 encodeAllocation(snapshot, *it, &allocIndex, hasSideEffects);
732 MOZ_ASSERT_IF(!snapshots_.oom(),
733 allocWritten + 1 == snapshots_.allocWritten());
734 }
735
736 MOZ_ASSERT(allocIndex == snapshot->numSlots());
737 snapshots_.endSnapshot();
738 snapshot->setSnapshotOffset(offset);
739 masm.propagateOOM(!snapshots_.oom());
740 }
741
742 bool CodeGeneratorShared::encodeSafepoints() {
743 for (CodegenSafepointIndex& index : safepointIndices_) {
744 LSafepoint* safepoint = index.safepoint();
745
746 if (!safepoint->encoded()) {
747 safepoints_.encode(safepoint);
748 }
749 }
750
751 return !safepoints_.oom();
752 }
753
754 bool CodeGeneratorShared::createNativeToBytecodeScriptList(
755 JSContext* cx, IonEntry::ScriptList& scripts) {
756 MOZ_ASSERT(scripts.empty());
757
758 InlineScriptTree* tree = gen->outerInfo().inlineScriptTree();
759 for (;;) {
760 // Add script from current tree.
761 bool found = false;
762 for (uint32_t i = 0; i < scripts.length(); i++) {
763 if (scripts[i].script == tree->script()) {
764 found = true;
765 break;
766 }
767 }
768 if (!found) {
769 UniqueChars str =
770 GeckoProfilerRuntime::allocProfileString(cx, tree->script());
771 if (!str) {
772 return false;
773 }
774 if (!scripts.emplaceBack(tree->script(), std::move(str))) {
775 return false;
776 }
777 }
778
779 // Process rest of tree
780
781 // If children exist, emit children.
782 if (tree->hasChildren()) {
783 tree = tree->firstChild();
784 continue;
785 }
786
787 // Otherwise, find the first tree up the chain (including this one)
788 // that contains a next sibling.
789 while (!tree->hasNextCallee() && tree->hasCaller()) {
790 tree = tree->caller();
791 }
792
793 // If we found a sibling, use it.
794 if (tree->hasNextCallee()) {
795 tree = tree->nextCallee();
796 continue;
797 }
798
799 // Otherwise, we must have reached the top without finding any siblings.
800 MOZ_ASSERT(tree->isOutermostCaller());
801 break;
802 }
803
804 return true;
805 }
806
807 bool CodeGeneratorShared::generateCompactNativeToBytecodeMap(
808 JSContext* cx, JitCode* code, IonEntry::ScriptList& scripts) {
809 MOZ_ASSERT(nativeToBytecodeMap_ == nullptr);
810 MOZ_ASSERT(nativeToBytecodeMapSize_ == 0);
811 MOZ_ASSERT(nativeToBytecodeTableOffset_ == 0);
812
813 if (!createNativeToBytecodeScriptList(cx, scripts)) {
814 return false;
815 }
816
817 CompactBufferWriter writer;
818 uint32_t tableOffset = 0;
819 uint32_t numRegions = 0;
820
821 if (!JitcodeIonTable::WriteIonTable(
822 writer, scripts, &nativeToBytecodeList_[0],
823 &nativeToBytecodeList_[0] + nativeToBytecodeList_.length(),
824 &tableOffset, &numRegions)) {
825 return false;
826 }
827
828 MOZ_ASSERT(tableOffset > 0);
829 MOZ_ASSERT(numRegions > 0);
830
831 // Writer is done, copy it to sized buffer.
832 uint8_t* data = cx->pod_malloc<uint8_t>(writer.length());
833 if (!data) {
834 return false;
835 }
836
837 memcpy(data, writer.buffer(), writer.length());
838 nativeToBytecodeMap_.reset(data);
839 nativeToBytecodeMapSize_ = writer.length();
840 nativeToBytecodeTableOffset_ = tableOffset;
841
842 verifyCompactNativeToBytecodeMap(code, scripts, numRegions);
843
844 JitSpew(JitSpew_Profiling, "Compact Native To Bytecode Map [%p-%p]", data,
845 data + nativeToBytecodeMapSize_);
846
847 return true;
848 }
849
850 void CodeGeneratorShared::verifyCompactNativeToBytecodeMap(
851 JitCode* code, const IonEntry::ScriptList& scripts, uint32_t numRegions) {
852 #ifdef DEBUG
853 MOZ_ASSERT(nativeToBytecodeMap_ != nullptr);
854 MOZ_ASSERT(nativeToBytecodeMapSize_ > 0);
855 MOZ_ASSERT(nativeToBytecodeTableOffset_ > 0);
856 MOZ_ASSERT(numRegions > 0);
857
858 // The pointer to the table must be 4-byte aligned
859 const uint8_t* tablePtr =
860 nativeToBytecodeMap_.get() + nativeToBytecodeTableOffset_;
861 MOZ_ASSERT(uintptr_t(tablePtr) % sizeof(uint32_t) == 0);
862
863 // Verify that numRegions was encoded correctly.
864 const JitcodeIonTable* ionTable =
865 reinterpret_cast<const JitcodeIonTable*>(tablePtr);
866 MOZ_ASSERT(ionTable->numRegions() == numRegions);
867
868 // Region offset for first region should be at the start of the payload
869 // region. Since the offsets are backward from the start of the table, the
870 // first entry backoffset should be equal to the forward table offset from the
871 // start of the allocated data.
872 MOZ_ASSERT(ionTable->regionOffset(0) == nativeToBytecodeTableOffset_);
873
874 // Verify each region.
875 for (uint32_t i = 0; i < ionTable->numRegions(); i++) {
876 // Back-offset must point into the payload region preceding the table, not
877 // before it.
878 MOZ_ASSERT(ionTable->regionOffset(i) <= nativeToBytecodeTableOffset_);
879
880 // Back-offset must point to a later area in the payload region than
881 // previous back-offset. This means that back-offsets decrease
882 // monotonically.
883 MOZ_ASSERT_IF(i > 0,
884 ionTable->regionOffset(i) < ionTable->regionOffset(i - 1));
885
886 JitcodeRegionEntry entry = ionTable->regionEntry(i);
887
888 // Ensure native code offset for region falls within jitcode.
889 MOZ_ASSERT(entry.nativeOffset() <= code->instructionsSize());
890
891 // Read out script/pc stack and verify.
892 JitcodeRegionEntry::ScriptPcIterator scriptPcIter =
893 entry.scriptPcIterator();
894 while (scriptPcIter.hasMore()) {
895 uint32_t scriptIdx = 0, pcOffset = 0;
896 scriptPcIter.readNext(&scriptIdx, &pcOffset);
897
898 // Ensure scriptIdx refers to a valid script in the list.
899 JSScript* script = scripts[scriptIdx].script;
900
901 // Ensure pcOffset falls within the script.
902 MOZ_ASSERT(pcOffset < script->length());
903 }
904
905 // Obtain the original nativeOffset and pcOffset and script.
906 uint32_t curNativeOffset = entry.nativeOffset();
907 JSScript* script = nullptr;
908 uint32_t curPcOffset = 0;
909 {
910 uint32_t scriptIdx = 0;
911 scriptPcIter.reset();
912 scriptPcIter.readNext(&scriptIdx, &curPcOffset);
913 script = scripts[scriptIdx].script;
914 }
915
916 // Read out nativeDeltas and pcDeltas and verify.
917 JitcodeRegionEntry::DeltaIterator deltaIter = entry.deltaIterator();
918 while (deltaIter.hasMore()) {
919 uint32_t nativeDelta = 0;
920 int32_t pcDelta = 0;
921 deltaIter.readNext(&nativeDelta, &pcDelta);
922
923 curNativeOffset += nativeDelta;
924 curPcOffset = uint32_t(int32_t(curPcOffset) + pcDelta);
925
926 // Ensure that nativeOffset still falls within jitcode after delta.
927 MOZ_ASSERT(curNativeOffset <= code->instructionsSize());
928
929 // Ensure that pcOffset still falls within bytecode after delta.
930 MOZ_ASSERT(curPcOffset < script->length());
931 }
932 }
933 #endif // DEBUG
934 }
935
936 void CodeGeneratorShared::markSafepoint(LInstruction* ins) {
937 markSafepointAt(masm.currentOffset(), ins);
938 }
939
940 void CodeGeneratorShared::markSafepointAt(uint32_t offset, LInstruction* ins) {
941 MOZ_ASSERT_IF(
942 !safepointIndices_.empty() && !masm.oom(),
943 offset - safepointIndices_.back().displacement() >= sizeof(uint32_t));
944 masm.propagateOOM(safepointIndices_.append(
945 CodegenSafepointIndex(offset, ins->safepoint())));
946 }
947
948 void CodeGeneratorShared::ensureOsiSpace() {
949 // For a refresher, an invalidation point is of the form:
950 // 1: call <target>
951 // 2: ...
952 // 3: <osipoint>
953 //
954 // The four bytes *before* instruction 2 are overwritten with an offset.
955 // Callers must ensure that the instruction itself has enough bytes to
956 // support this.
957 //
958 // The bytes *at* instruction 3 are overwritten with an invalidation jump.
959 // jump. These bytes may be in a completely different IR sequence, but
960 // represent the join point of the call out of the function.
961 //
962 // At points where we want to ensure that invalidation won't corrupt an
963 // important instruction, we make sure to pad with nops.
964 if (masm.currentOffset() - lastOsiPointOffset_ <
965 Assembler::PatchWrite_NearCallSize()) {
966 int32_t paddingSize = Assembler::PatchWrite_NearCallSize();
967 paddingSize -= masm.currentOffset() - lastOsiPointOffset_;
968 for (int32_t i = 0; i < paddingSize; ++i) {
969 masm.nop();
970 }
971 }
972 MOZ_ASSERT_IF(!masm.oom(), masm.currentOffset() - lastOsiPointOffset_ >=
973 Assembler::PatchWrite_NearCallSize());
974 }
975
976 uint32_t CodeGeneratorShared::markOsiPoint(LOsiPoint* ins) {
977 encode(ins->snapshot());
978 ensureOsiSpace();
979
980 uint32_t offset = masm.currentOffset();
981 SnapshotOffset so = ins->snapshot()->snapshotOffset();
982 masm.propagateOOM(osiIndices_.append(OsiIndex(offset, so)));
983 lastOsiPointOffset_ = offset;
984
985 return offset;
986 }
987
988 class OutOfLineTruncateSlow : public OutOfLineCodeBase<CodeGeneratorShared> {
989 FloatRegister src_;
990 Register dest_;
991 bool widenFloatToDouble_;
992 wasm::BytecodeOffset bytecodeOffset_;
993
994 public:
995 OutOfLineTruncateSlow(FloatRegister src, Register dest,
996 bool widenFloatToDouble,
997 wasm::BytecodeOffset bytecodeOffset)
998 : src_(src),
999 dest_(dest),
1000 widenFloatToDouble_(widenFloatToDouble),
1001 bytecodeOffset_(bytecodeOffset) {}
1002
1003 void accept(CodeGeneratorShared* codegen) override {
1004 codegen->visitOutOfLineTruncateSlow(this);
1005 }
1006 FloatRegister src() const { return src_; }
1007 Register dest() const { return dest_; }
1008 bool widenFloatToDouble() const { return widenFloatToDouble_; }
1009 wasm::BytecodeOffset bytecodeOffset() const { return bytecodeOffset_; }
1010 };
1011
1012 OutOfLineCode* CodeGeneratorShared::oolTruncateDouble(
1013 FloatRegister src, Register dest, MInstruction* mir,
1014 wasm::BytecodeOffset bytecodeOffset) {
1015 MOZ_ASSERT_IF(IsCompilingWasm(), bytecodeOffset.isValid());
1016
1017 OutOfLineTruncateSlow* ool = new (alloc())
1018 OutOfLineTruncateSlow(src, dest, /* float32 */ false, bytecodeOffset);
1019 addOutOfLineCode(ool, mir);
1020 return ool;
1021 }
1022
1023 void CodeGeneratorShared::emitTruncateDouble(FloatRegister src, Register dest,
1024 MInstruction* mir) {
1025 MOZ_ASSERT(mir->isTruncateToInt32() || mir->isWasmBuiltinTruncateToInt32());
1026 wasm::BytecodeOffset bytecodeOffset =
1027 mir->isTruncateToInt32()
1028 ? mir->toTruncateToInt32()->trapSiteDesc().bytecodeOffset
1029 : mir->toWasmBuiltinTruncateToInt32()->trapSiteDesc().bytecodeOffset;
1030 OutOfLineCode* ool = oolTruncateDouble(src, dest, mir, bytecodeOffset);
1031
1032 masm.branchTruncateDoubleMaybeModUint32(src, dest, ool->entry());
1033 masm.bind(ool->rejoin());
1034 }
1035
1036 void CodeGeneratorShared::emitTruncateFloat32(FloatRegister src, Register dest,
1037 MInstruction* mir) {
1038 MOZ_ASSERT(mir->isTruncateToInt32() || mir->isWasmBuiltinTruncateToInt32());
1039 wasm::BytecodeOffset bytecodeOffset =
1040 mir->isTruncateToInt32()
1041 ? mir->toTruncateToInt32()->trapSiteDesc().bytecodeOffset
1042 : mir->toWasmBuiltinTruncateToInt32()->trapSiteDesc().bytecodeOffset;
1043 OutOfLineTruncateSlow* ool = new (alloc())
1044 OutOfLineTruncateSlow(src, dest, /* float32 */ true, bytecodeOffset);
1045 addOutOfLineCode(ool, mir);
1046
1047 masm.branchTruncateFloat32MaybeModUint32(src, dest, ool->entry());
1048 masm.bind(ool->rejoin());
1049 }
1050
1051 void CodeGeneratorShared::visitOutOfLineTruncateSlow(
1052 OutOfLineTruncateSlow* ool) {
1053 FloatRegister src = ool->src();
1054 Register dest = ool->dest();
1055
1056 saveVolatile(dest);
1057 masm.outOfLineTruncateSlow(src, dest, ool->widenFloatToDouble(),
1058 gen->compilingWasm(), ool->bytecodeOffset());
1059 restoreVolatile(dest);
1060
1061 masm.jump(ool->rejoin());
1062 }
1063
1064 bool CodeGeneratorShared::omitOverRecursedCheck() const {
1065 // If the current function makes no calls (which means it isn't recursive)
1066 // and it uses only a small amount of stack space, it doesn't need a
1067 // stack overflow check. Note that the actual number here is somewhat
1068 // arbitrary, and codegen actually uses small bounded amounts of
1069 // additional stack space in some cases too.
1070 return frameSize() < MAX_UNCHECKED_LEAF_FRAME_SIZE &&
1071 !gen->needsOverrecursedCheck();
1072 }
1073
1074 void CodeGeneratorShared::emitPreBarrier(Register elements,
1075 const LAllocation* index) {
1076 if (index->isConstant()) {
1077 Address address(elements, ToInt32(index) * sizeof(Value));
1078 masm.guardedCallPreBarrier(address, MIRType::Value);
1079 } else {
1080 BaseObjectElementIndex address(elements, ToRegister(index));
1081 masm.guardedCallPreBarrier(address, MIRType::Value);
1082 }
1083 }
1084
1085 void CodeGeneratorShared::emitPreBarrier(Address address) {
1086 masm.guardedCallPreBarrier(address, MIRType::Value);
1087 }
1088
1089 void CodeGeneratorShared::jumpToBlock(MBasicBlock* mir) {
1090 // Skip past trivial blocks.
1091 mir = skipTrivialBlocks(mir);
1092
1093 // No jump necessary if we can fall through to the next block.
1094 if (isNextBlock(mir->lir())) {
1095 return;
1096 }
1097
1098 masm.jump(mir->lir()->label());
1099 }
1100
1101 Label* CodeGeneratorShared::getJumpLabelForBranch(MBasicBlock* block) {
1102 // Skip past trivial blocks.
1103 return skipTrivialBlocks(block)->lir()->label();
1104 }
1105
1106 // This function is not used for MIPS64/LOONG64/RISCV64. They have
1107 // branchToBlock.
1108 #if !defined(JS_CODEGEN_MIPS64) && !defined(JS_CODEGEN_LOONG64) && \
1109 !defined(JS_CODEGEN_RISCV64)
1110 void CodeGeneratorShared::jumpToBlock(MBasicBlock* mir,
1111 Assembler::Condition cond) {
1112 // Skip past trivial blocks.
1113 masm.j(cond, skipTrivialBlocks(mir)->lir()->label());
1114 }
1115 #endif
1116
1117 } // namespace jit
1118 } // namespace js