Debian Codegraph @

js/src/jit/arm64/Assembler-arm64.h

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 #ifndef A64_ASSEMBLER_A64_H_
8 #define A64_ASSEMBLER_A64_H_
9
10 #include <iterator>
11
12 #include "jit/arm64/vixl/Assembler-vixl.h"
13
14 #include "jit/CompactBuffer.h"
15 #include "jit/shared/Disassembler-shared.h"
16 #include "wasm/WasmTypeDecls.h"
17
18 namespace js {
19 namespace jit {
20
21 // VIXL imports.
22 using ARMRegister = vixl::Register;
23 using ARMFPRegister = vixl::FPRegister;
24 using vixl::ARMBuffer;
25 using vixl::Instruction;
26
27 using LabelDoc = DisassemblerSpew::LabelDoc;
28 using LiteralDoc = DisassemblerSpew::LiteralDoc;
29
30 static const uint32_t AlignmentAtPrologue = 0;
31 static const uint32_t AlignmentMidPrologue = 8;
32 static const Scale ScalePointer = TimesEight;
33
34 // The MacroAssembler uses scratch registers extensively and unexpectedly.
35 // For safety, scratch registers should always be acquired using
36 // vixl::UseScratchRegisterScope.
37 static constexpr Register ScratchReg{Registers::ip0};
38 static constexpr ARMRegister ScratchReg64 = {ScratchReg, 64};
39
40 static constexpr Register ScratchReg2{Registers::ip1};
41 static constexpr ARMRegister ScratchReg2_64 = {ScratchReg2, 64};
42
43 static constexpr FloatRegister ReturnDoubleReg = {FloatRegisters::d0,
44 FloatRegisters::Double};
45 static constexpr FloatRegister ScratchDoubleReg_ = {FloatRegisters::d31,
46 FloatRegisters::Double};
47 struct ScratchDoubleScope : public AutoFloatRegisterScope {
48 explicit ScratchDoubleScope(MacroAssembler& masm)
49 : AutoFloatRegisterScope(masm, ScratchDoubleReg_) {}
50 };
51
52 static constexpr FloatRegister ReturnFloat32Reg = {FloatRegisters::s0,
53 FloatRegisters::Single};
54 static constexpr FloatRegister ScratchFloat32Reg_ = {FloatRegisters::s31,
55 FloatRegisters::Single};
56 struct ScratchFloat32Scope : public AutoFloatRegisterScope {
57 explicit ScratchFloat32Scope(MacroAssembler& masm)
58 : AutoFloatRegisterScope(masm, ScratchFloat32Reg_) {}
59 };
60
61 #ifdef ENABLE_WASM_SIMD
62 static constexpr FloatRegister ReturnSimd128Reg = {FloatRegisters::v0,
63 FloatRegisters::Simd128};
64 static constexpr FloatRegister ScratchSimd128Reg = {FloatRegisters::v31,
65 FloatRegisters::Simd128};
66 struct ScratchSimd128Scope : public AutoFloatRegisterScope {
67 explicit ScratchSimd128Scope(MacroAssembler& masm)
68 : AutoFloatRegisterScope(masm, ScratchSimd128Reg) {}
69 };
70 #else
71 struct ScratchSimd128Scope : public AutoFloatRegisterScope {
72 explicit ScratchSimd128Scope(MacroAssembler& masm)
73 : AutoFloatRegisterScope(masm, ScratchDoubleReg_) {
74 MOZ_CRASH("SIMD not enabled");
75 }
76 };
77 #endif
78
79 static constexpr Register InvalidReg{Registers::Invalid};
80 static constexpr FloatRegister InvalidFloatReg = {};
81
82 static constexpr Register OsrFrameReg{Registers::x3};
83 static constexpr Register CallTempReg0{Registers::x9};
84 static constexpr Register CallTempReg1{Registers::x10};
85 static constexpr Register CallTempReg2{Registers::x11};
86 static constexpr Register CallTempReg3{Registers::x12};
87 static constexpr Register CallTempReg4{Registers::x13};
88 static constexpr Register CallTempReg5{Registers::x14};
89
90 static constexpr Register PreBarrierReg{Registers::x1};
91
92 static constexpr Register InterpreterPCReg{Registers::x9};
93
94 static constexpr Register ReturnReg{Registers::x0};
95 static constexpr Register64 ReturnReg64(ReturnReg);
96 static constexpr Register JSReturnReg{Registers::x2};
97 static constexpr Register FramePointer{Registers::fp};
98 static constexpr ARMRegister FramePointer64{FramePointer, 64};
99 static constexpr Register ZeroRegister{Registers::sp};
100 static constexpr ARMRegister ZeroRegister64{Registers::sp, 64};
101 static constexpr ARMRegister ZeroRegister32{Registers::sp, 32};
102
103 // [SMDOC] AArch64 Stack Pointer and Pseudo Stack Pointer conventions
104 //
105 // ================
106 //
107 // Stack pointer (SP), PseudoStackPointer (PSP), and RealStackPointer:
108 //
109 // The ARM64 real SP has a constraint: it must be 16-byte aligned whenever it
110 // is used as the base pointer for a memory access. (SP+offset need not be
111 // 16-byte aligned, but the SP value itself must be.) The SP register may
112 // take on unaligned values but may not be used for a memory access while it
113 // is unaligned.
114 //
115 // Stack-alignment checking can be enabled or disabled by a control register;
116 // however that register cannot be modified by user space. We have to assume
117 // stack alignment checking is enabled, and that does usually appear to be the
118 // case. See the ARM Architecture Reference Manual, "D1.8.2 SP alignment
119 // checking", for further details.
120 //
121 // A second constraint is forced upon us by the ARM64 ABI. This requires that
122 // all accesses to the stack must be at or above SP. Accesses below SP are
123 // strictly forbidden, presumably because the kernel might use that area of
124 // memory for its own purposes -- in particular, signal delivery -- and hence
125 // it may get trashed at any time.
126 //
127 // Note this doesn't mean that accesses to the stack must be based off
128 // register SP. Only that the effective addresses must be >= SP, regardless
129 // of how the address is formed.
130 //
131 // In order to allow word-wise pushes and pops, some of our ARM64 jits
132 // (JS-Baseline, JS-Ion, and Wasm-Ion, but not Wasm-Baseline) dedicate x28 to
133 // be used as a PseudoStackPointer (PSP).
134 //
135 // Initially the PSP will have the same value as the SP. Code can, if it
136 // wants, push a single word by subtracting 8 from the PSP, doing SP := PSP,
137 // then storing the value at PSP+0. Given other constraints on the alignment
138 // of the SP at function call boundaries, this works out OK, at the cost of
139 // the two extra instructions per push / pop.
140 //
141 // This is all a bit messy, and is probably not robustly adhered to. However,
142 // the following appear to be the intended, and mostly implemented, current
143 // invariants:
144 //
145 // (1) PSP is "primary", SP is "secondary". Most stack refs are
146 // PSP-relative. SP-relative is rare and (obviously) only done when we
147 // know that SP is aligned.
148 //
149 // (2) At all times, the relationship SP <= PSP is maintained. The fact that
150 // SP may validly be less than PSP means that pushes on the stack force
151 // the two values to become equal, by copying PSP into SP. However, pops
152 // behave differently: PSP moves back up and SP stays the same, since that
153 // doesn't break the SP <= PSP invariant.
154 //
155 // (3) However, immediately before a call instruction, SP and PSP must be the
156 // same. To enforce this, PSP is copied into SP by the arm64-specific
157 // MacroAssembler::call routines.
158 //
159 // (4) Also, after a function has returned, it is expected that SP holds the
160 // "primary" value. How exactly this is implemented remains not entirely
161 // clear and merits further investigation. The following points are
162 // believed to be relevant:
163 //
164 // - For calls to functions observing the system AArch64 ABI, PSP (x28) is
165 // callee-saved. That, combined with (3) above, implies SP == PSP
166 // immediately after the call returns.
167 //
168 // - JIT-generated routines return using MacroAssemblerCompat::retn, and
169 // that copies PSP into SP (bizarrely; this would make more sense if it
170 // copied SP into PSP); but in any case, the point is that they are the
171 // same at the point that the return instruction executes.
172 //
173 // - MacroAssembler::callWithABIPost copies PSP into SP after the return
174 // of a call requiring dynamic alignment.
175 //
176 // Given the above, it is unclear exactly where in the return sequence it
177 // is expected that SP == PSP, and also whether it is the callee or caller
178 // that is expected to enforce it.
179 //
180 // In general it would be nice to be able to move (at some time in the future,
181 // not now) to a world where *every* assignment to PSP or SP is followed
182 // immediately by a copy into the other register. That would make all
183 // required correctness proofs trivial in the sense that it would require only
184 // local inspection of code immediately following (dominated by) any such
185 // assignment. For the moment, however, this is a guideline, not a hard
186 // requirement.
187 //
188 // ================
189 //
190 // Mechanics of keeping the stack pointers in sync:
191 //
192 // The following two methods require that the masm's SP has been set to the PSP
193 // with MacroAssembler::SetStackPointer64(PseudoStackPointer64), or they will be
194 // no-ops. The setup is performed manually by the jits after creating the masm.
195 //
196 // * MacroAssembler::syncStackPtr() performs SP := PSP, presumably after PSP has
197 // been updated, so SP needs to move too. This is used pretty liberally
198 // throughout the code base.
199 //
200 // * MacroAssembler::initPseudoStackPtr() performs PSP := SP. This can be used
201 // after calls to non-ABI compliant code; it's not used much.
202 //
203 // In the ARM64 assembler there is a function Instruction::IsStackPtrSync() that
204 // recognizes the instruction emitted by syncStackPtr(), and this is used to
205 // skip that instruction a few places, should it be present, in the JS JIT where
206 // code is generated to deal with toggled calls.
207 //
208 // In various places there are calls to MacroAssembler::syncStackPtr() which
209 // appear to be redundant. Investigation shows that they often are redundant,
210 // but not always. Finding and removing such redundancies would be quite some
211 // work, so we live for now with the occasional redundant update. Perusal of
212 // the Cortex-A55 and -A72 optimization guides shows no evidence that such
213 // assignments are any more expensive than assignments between vanilla integer
214 // registers, so the costs of such redundant updates are assumed to be small.
215 //
216 // Invariants on the PSP at function call boundaries:
217 //
218 // It *appears* that the following invariants exist:
219 //
220 // * On entry to JIT code, PSP == SP, ie the stack pointer is transmitted via
221 // both registers.
222 //
223 // * On entry to C++ code, PSP == SP. Certainly it appears that all calls
224 // created by the MacroAssembler::call(..) routines perform 'syncStackPtr'
225 // immediately before the call, and all ABI calls are routed through the
226 // MacroAssembler::call layer.
227 //
228 // * The stubs generated by WasmStubs.cpp assume that, on entry, SP is the
229 // active stack pointer and that PSP is dead.
230 //
231 // * The PSP is non-volatile (callee-saved). Along a normal return path from
232 // JIT code, simply having PSP == SP on exit is correct, since the exit SP is
233 // the same as the entry SP by the JIT ABI.
234 //
235 // * Call-outs to non-JIT C++ code do not need to set up the PSP (it won't be
236 // used), and will not need to restore the PSP on return because x28 is
237 // non-volatile in the ARM64 ABI.
238 //
239 // ================
240 //
241 // Future cleanups to the SP-vs-PSP machinery:
242 //
243 // Currently we have somewhat unclear invariants, which are not obviously
244 // always enforced, and which may require complex non-local reasoning.
245 // Auditing the code to ensure that the invariants always hold, whilst not
246 // generating duplicate syncs, is close to impossible. A future rework to
247 // tidy this might be as follows. (This suggestion pertains the the entire
248 // JIT complex: all of the JS compilers, wasm compilers, stub generators,
249 // regexp compilers, etc).
250 //
251 // Currently we have that, in JIT-generated code, PSP is "primary" and SP is
252 // "secondary", meaning that PSP has the "real" stack pointer value and SP is
253 // updated whenever PSP acquires a lower value, so as to ensure that SP <= PSP.
254 // An exception to this scheme is the stubs code generated by WasmStubs.cpp,
255 // which assumes that SP is "primary" and PSP is dead.
256 //
257 // It might give us an easier incremental path to eventually removing PSP
258 // entirely if we switched to having SP always be the primary. That is:
259 //
260 // (1) SP is primary, PSP is secondary
261 // (2) After any assignment to SP, it is copied into PSP
262 // (3) All (non-frame-pointer-based) stack accesses are PSP-relative
263 // (as at present)
264 //
265 // This would have the effect that:
266 //
267 // * It would reinstate the invariant that on all targets, the "real" SP value
268 // is in the ABI-and-or-hardware-mandated stack pointer register.
269 //
270 // * It would give us a simple story about calls and returns:
271 // - for calls to non-JIT generated code (viz, C++ etc), we need no extra
272 // copies, because PSP (x28) is callee-saved
273 // - for calls to JIT-generated code, we need no extra copies, because of (2)
274 // above
275 //
276 // * We could incrementally migrate those parts of the code generator where we
277 // know that SP is 16-aligned, to use SP- rather than PSP-relative accesses
278 //
279 // * The consistent use of (2) would remove the requirement to have to perform
280 // path-dependent reasoning (for paths in the generated code, not in the
281 // compiler) when reading/understanding the code.
282 //
283 // * x28 would become free for use by stubs and the baseline compiler without
284 // having to worry about interoperating with code that expects x28 to hold a
285 // valid PSP.
286 //
287 // One might ask what mechanical checks we can add to ensure correctness, rather
288 // than having to verify these invariants by hand indefinitely. Maybe some
289 // combination of:
290 //
291 // * In debug builds, compiling-in assert(SP == PSP) at critical places. This
292 // can be done using the existing `assertStackPtrsSynced` function.
293 //
294 // * In debug builds, scanning sections of generated code to ensure no
295 // SP-relative stack accesses have been created -- for some sections, at
296 // least every assignment to SP is immediately followed by a copy to x28.
297 // This would also facilitate detection of duplicate syncs.
298 //
299 // ================
300 //
301 // Other investigative notes, for the code base at present:
302 //
303 // * Some disassembly dumps suggest that we sync the stack pointer too often.
304 // This could be the result of various pieces of code working at cross
305 // purposes when syncing the stack pointer, or of not paying attention to the
306 // precise invariants.
307 //
308 // * As documented in RegExpNativeMacroAssembler.cpp, function
309 // SMRegExpMacroAssembler::createStackFrame:
310 //
311 // // ARM64 communicates stack address via SP, but uses a pseudo-sp (PSP) for
312 // // addressing. The register we use for PSP may however also be used by
313 // // calling code, and it is nonvolatile, so save it. Do this as a special
314 // // case first because the generic save/restore code needs the PSP to be
315 // // initialized already.
316 //
317 // and also in function SMRegExpMacroAssembler::exitHandler:
318 //
319 // // Restore the saved value of the PSP register, this value is whatever the
320 // // caller had saved in it, not any actual SP value, and it must not be
321 // // overwritten subsequently.
322 //
323 // The original source for these comments was a patch for bug 1445907.
324 //
325 // * MacroAssembler-arm64.h has an interesting comment in the retn()
326 // function:
327 //
328 // syncStackPtr(); // SP is always used to transmit the stack between calls.
329 //
330 // Same comment at abiret() in that file, and in MacroAssembler-arm64.cpp,
331 // at callWithABIPre and callWithABIPost.
332 //
333 // * In Trampoline-arm64.cpp function JitRuntime::generateVMWrapper we find
334 //
335 // // SP is used to transfer stack across call boundaries.
336 // masm.initPseudoStackPtr();
337 //
338 // after the return point of a callWithVMWrapper. The only reasonable
339 // conclusion from all those (assuming they are right) is that SP == PSP.
340 //
341 // * Wasm-Baseline does not use the PSP, but as Wasm-Ion code requires SP==PSP
342 // and tiered code can have Baseline->Ion calls, Baseline will set PSP=SP
343 // before a call to wasm code.
344 //
345 // ================
346
347 // StackPointer is intentionally undefined on ARM64 to prevent misuse: using
348 // sp as a base register is only valid if sp % 16 == 0.
349 static constexpr Register RealStackPointer{Registers::sp};
350
351 static constexpr Register PseudoStackPointer{Registers::x28};
352 static constexpr ARMRegister PseudoStackPointer64 = {Registers::x28, 64};
353 static constexpr ARMRegister PseudoStackPointer32 = {Registers::x28, 32};
354
355 static constexpr Register IntArgReg0{Registers::x0};
356 static constexpr Register IntArgReg1{Registers::x1};
357 static constexpr Register IntArgReg2{Registers::x2};
358 static constexpr Register IntArgReg3{Registers::x3};
359 static constexpr Register IntArgReg4{Registers::x4};
360 static constexpr Register IntArgReg5{Registers::x5};
361 static constexpr Register IntArgReg6{Registers::x6};
362 static constexpr Register IntArgReg7{Registers::x7};
363 static constexpr Register HeapReg{Registers::x21};
364
365 // Define unsized Registers.
366 #define DEFINE_UNSIZED_REGISTERS(N) \
367 static constexpr Register r##N{Registers::x##N};
368 REGISTER_CODE_LIST(DEFINE_UNSIZED_REGISTERS)
369 #undef DEFINE_UNSIZED_REGISTERS
370 static constexpr Register ip0{Registers::x16};
371 static constexpr Register ip1{Registers::x17};
372 static constexpr Register fp{Registers::x29};
373 static constexpr Register lr{Registers::x30};
374 static constexpr Register rzr{Registers::xzr};
375
376 // Import VIXL registers into the js::jit namespace.
377 #define IMPORT_VIXL_REGISTERS(N) \
378 static constexpr ARMRegister w##N = vixl::w##N; \
379 static constexpr ARMRegister x##N = vixl::x##N;
380 REGISTER_CODE_LIST(IMPORT_VIXL_REGISTERS)
381 #undef IMPORT_VIXL_REGISTERS
382 static constexpr ARMRegister wzr = vixl::wzr;
383 static constexpr ARMRegister xzr = vixl::xzr;
384 static constexpr ARMRegister wsp = vixl::wsp;
385 static constexpr ARMRegister sp = vixl::sp;
386
387 // Import VIXL VRegisters into the js::jit namespace.
388 #define IMPORT_VIXL_VREGISTERS(N) \
389 static constexpr ARMFPRegister s##N = vixl::s##N; \
390 static constexpr ARMFPRegister d##N = vixl::d##N;
391 REGISTER_CODE_LIST(IMPORT_VIXL_VREGISTERS)
392 #undef IMPORT_VIXL_VREGISTERS
393
394 static constexpr ValueOperand JSReturnOperand = ValueOperand(JSReturnReg);
395
396 // Registers used by RegExpMatcher and RegExpExecMatch stubs (do not use
397 // JSReturnOperand).
398 static constexpr Register RegExpMatcherRegExpReg = CallTempReg0;
399 static constexpr Register RegExpMatcherStringReg = CallTempReg1;
400 static constexpr Register RegExpMatcherLastIndexReg = CallTempReg2;
401
402 // Registers used by RegExpExecTest stub (do not use ReturnReg).
403 static constexpr Register RegExpExecTestRegExpReg = CallTempReg0;
404 static constexpr Register RegExpExecTestStringReg = CallTempReg1;
405
406 // Registers used by RegExpSearcher stub (do not use ReturnReg).
407 static constexpr Register RegExpSearcherRegExpReg = CallTempReg0;
408 static constexpr Register RegExpSearcherStringReg = CallTempReg1;
409 static constexpr Register RegExpSearcherLastIndexReg = CallTempReg2;
410
411 static constexpr Register JSReturnReg_Type = r3;
412 static constexpr Register JSReturnReg_Data = r2;
413
414 static constexpr FloatRegister NANReg = {FloatRegisters::d14,
415 FloatRegisters::Single};
416 // N.B. r8 isn't listed as an aapcs temp register, but we can use it as such
417 // because we never use return-structs.
418 static constexpr Register CallTempNonArgRegs[] = {r8, r9, r10, r11,
419 r12, r13, r14, r15};
420 static const uint32_t NumCallTempNonArgRegs = std::size(CallTempNonArgRegs);
421
422 static constexpr uint32_t JitStackAlignment = 16;
423
424 static constexpr uint32_t JitStackValueAlignment =
425 JitStackAlignment / sizeof(Value);
426 static_assert(JitStackAlignment % sizeof(Value) == 0 &&
427 JitStackValueAlignment >= 1,
428 "Stack alignment should be a non-zero multiple of sizeof(Value)");
429
430 static constexpr uint32_t SimdMemoryAlignment = 16;
431
432 static_assert(CodeAlignment % SimdMemoryAlignment == 0,
433 "Code alignment should be larger than any of the alignments "
434 "which are used for "
435 "the constant sections of the code buffer. Thus it should be "
436 "larger than the "
437 "alignment for SIMD constants.");
438
439 static const uint32_t WasmStackAlignment = SimdMemoryAlignment;
440 static const uint32_t WasmTrapInstructionLength = 4;
441
442 // See comments in wasm::GenerateFunctionPrologue. The difference between these
443 // is the size of the largest callable prologue on the platform.
444 static constexpr uint32_t WasmCheckedCallEntryOffset = 0u;
445
446 class Assembler : public vixl::Assembler {
447 public:
448 Assembler() : vixl::Assembler() {}
449
450 using Condition = vixl::Condition;
451
452 void finish();
453 bool appendRawCode(const uint8_t* code, size_t numBytes);
454 bool reserve(size_t size);
455 bool swapBuffer(wasm::Bytes& bytes);
456
457 // Emit the jump table, returning the BufferOffset to the first entry in the
458 // table.
459 BufferOffset emitExtendedJumpTable();
460 BufferOffset ExtendedJumpTable_;
461 void executableCopy(uint8_t* buffer);
462
463 BufferOffset immPool(ARMRegister dest, uint8_t* value, vixl::LoadLiteralOp op,
464 const LiteralDoc& doc,
465 ARMBuffer::PoolEntry* pe = nullptr);
466 BufferOffset immPool64(ARMRegister dest, uint64_t value,
467 ARMBuffer::PoolEntry* pe = nullptr);
468 BufferOffset fImmPool(ARMFPRegister dest, uint8_t* value,
469 vixl::LoadLiteralOp op, const LiteralDoc& doc);
470 BufferOffset fImmPool64(ARMFPRegister dest, double value);
471 BufferOffset fImmPool32(ARMFPRegister dest, float value);
472
473 uint32_t currentOffset() const { return nextOffset().getOffset(); }
474
475 void bind(Label* label) { bind(label, nextOffset()); }
476 void bind(Label* label, BufferOffset boff);
477 void bind(CodeLabel* label) { label->target()->bind(currentOffset()); }
478
479 void setUnlimitedBuffer() { armbuffer_.setUnlimited(); }
480 bool oom() const {
481 return AssemblerShared::oom() || armbuffer_.oom() ||
482 jumpRelocations_.oom() || dataRelocations_.oom();
483 }
484
485 void copyJumpRelocationTable(uint8_t* dest) const {
486 if (jumpRelocations_.length()) {
487 memcpy(dest, jumpRelocations_.buffer(), jumpRelocations_.length());
488 }
489 }
490 void copyDataRelocationTable(uint8_t* dest) const {
491 if (dataRelocations_.length()) {
492 memcpy(dest, dataRelocations_.buffer(), dataRelocations_.length());
493 }
494 }
495
496 size_t jumpRelocationTableBytes() const { return jumpRelocations_.length(); }
497 size_t dataRelocationTableBytes() const { return dataRelocations_.length(); }
498 size_t bytesNeeded() const {
499 return SizeOfCodeGenerated() + jumpRelocationTableBytes() +
500 dataRelocationTableBytes();
501 }
502
503 void processCodeLabels(uint8_t* rawCode) {
504 for (const CodeLabel& label : codeLabels_) {
505 Bind(rawCode, label);
506 }
507 }
508
509 static void UpdateLoad64Value(Instruction* inst0, uint64_t value);
510
511 static void Bind(uint8_t* rawCode, const CodeLabel& label) {
512 auto mode = label.linkMode();
513 size_t patchAtOffset = label.patchAt().offset();
514 size_t targetOffset = label.target().offset();
515
516 if (mode == CodeLabel::MoveImmediate) {
517 Instruction* inst = (Instruction*)(rawCode + patchAtOffset);
518 Assembler::UpdateLoad64Value(inst, (uint64_t)(rawCode + targetOffset));
519 } else {
520 *reinterpret_cast<const void**>(rawCode + patchAtOffset) =
521 rawCode + targetOffset;
522 }
523 }
524
525 void retarget(Label* cur, Label* next);
526
527 // The buffer is about to be linked. Ensure any constant pools or
528 // excess bookkeeping has been flushed to the instruction stream.
529 void flush() { armbuffer_.flushPool(); }
530
531 void comment(const char* msg) {
532 #ifdef JS_DISASM_ARM64
533 spew_.spew("; %s", msg);
534 #endif
535 }
536
537 void setPrinter(Sprinter* sp) {
538 #ifdef JS_DISASM_ARM64
539 spew_.setPrinter(sp);
540 #endif
541 }
542
543 static bool SupportsFloatingPoint() { return true; }
544 static bool SupportsUnalignedAccesses() { return true; }
545 static bool SupportsFastUnalignedFPAccesses() { return true; }
546 static bool SupportsWasmSimd() { return true; }
547 static bool SupportsFloat64To16() { return true; }
548 static bool SupportsFloat32To16() { return true; }
549
550 static bool HasRoundInstruction(RoundingMode mode) {
551 switch (mode) {
552 case RoundingMode::Up:
553 case RoundingMode::Down:
554 case RoundingMode::NearestTiesToEven:
555 case RoundingMode::TowardsZero:
556 return true;
557 }
558 MOZ_CRASH("unexpected mode");
559 }
560
561 protected:
562 // Add a jump whose target is unknown until finalization.
563 // The jump may not be patched at runtime.
564 void addPendingJump(BufferOffset src, ImmPtr target, RelocationKind kind);
565
566 public:
567 static uint32_t PatchWrite_NearCallSize() { return 4; }
568
569 static uint32_t NopSize() { return 4; }
570
571 static void PatchWrite_NearCall(CodeLocationLabel start,
572 CodeLocationLabel toCall);
573 static void PatchDataWithValueCheck(CodeLocationLabel label,
574 PatchedImmPtr newValue,
575 PatchedImmPtr expected);
576
577 static void PatchDataWithValueCheck(CodeLocationLabel label, ImmPtr newValue,
578 ImmPtr expected);
579
580 static void PatchWrite_Imm32(CodeLocationLabel label, Imm32 imm) {
581 // Raw is going to be the return address.
582 uint32_t* raw = (uint32_t*)label.raw();
583 // Overwrite the 4 bytes before the return address, which will end up being
584 // the call instruction.
585 *(raw - 1) = imm.value;
586 }
587 static uint32_t AlignDoubleArg(uint32_t offset) {
588 MOZ_CRASH("AlignDoubleArg()");
589 }
590 static uintptr_t GetPointer(uint8_t* ptr) {
591 Instruction* i = reinterpret_cast<Instruction*>(ptr);
592 uint64_t ret = i->Literal64();
593 return ret;
594 }
595
596 // Toggle a jmp or cmp emitted by toggledJump().
597 static void ToggleToJmp(CodeLocationLabel inst_);
598 static void ToggleToCmp(CodeLocationLabel inst_);
599 static void ToggleCall(CodeLocationLabel inst_, bool enabled);
600
601 static void TraceJumpRelocations(JSTracer* trc, JitCode* code,
602 CompactBufferReader& reader);
603 static void TraceDataRelocations(JSTracer* trc, JitCode* code,
604 CompactBufferReader& reader);
605
606 void assertNoGCThings() const {
607 #ifdef DEBUG
608 MOZ_ASSERT(dataRelocations_.length() == 0);
609 for (auto& j : pendingJumps_) {
610 MOZ_ASSERT(j.kind == RelocationKind::HARDCODED);
611 }
612 #endif
613 }
614
615 public:
616 // A Jump table entry is 2 instructions, with 8 bytes of raw data
617 static const size_t SizeOfJumpTableEntry = 16;
618
619 struct JumpTableEntry {
620 uint32_t ldr;
621 uint32_t br;
622 void* data;
623
624 Instruction* getLdr() { return reinterpret_cast<Instruction*>(&ldr); }
625 };
626
627 // Offset of the patchable target for the given entry.
628 static const size_t OffsetOfJumpTableEntryPointer = 8;
629
630 public:
631 void writeCodePointer(CodeLabel* label) {
632 armbuffer_.assertNoPoolAndNoNops();
633 uintptr_t x = uintptr_t(-1);
634 BufferOffset off = EmitData(&x, sizeof(uintptr_t));
635 label->patchAt()->bind(off.getOffset());
636 }
637
638 void verifyHeapAccessDisassembly(uint32_t begin, uint32_t end,
639 const Disassembler::HeapAccess& heapAccess) {
640 MOZ_CRASH("verifyHeapAccessDisassembly");
641 }
642
643 protected:
644 // Structure for fixing up pc-relative loads/jumps when the machine
645 // code gets moved (executable copy, gc, etc.).
646 struct RelativePatch {
647 BufferOffset offset;
648 void* target;
649 RelocationKind kind;
650
651 RelativePatch(BufferOffset offset, void* target, RelocationKind kind)
652 : offset(offset), target(target), kind(kind) {}
653 };
654
655 // List of jumps for which the target is either unknown until finalization,
656 // or cannot be known due to GC. Each entry here requires a unique entry
657 // in the extended jump table, and is patched at finalization.
658 js::Vector<RelativePatch, 8, SystemAllocPolicy> pendingJumps_;
659
660 // Final output formatters.
661 CompactBufferWriter jumpRelocations_;
662 CompactBufferWriter dataRelocations_;
663 };
664
665 static const uint32_t NumIntArgRegs = 8;
666 static const uint32_t NumFloatArgRegs = 8;
667
668 class ABIArgGenerator {
669 public:
670 ABIArgGenerator()
671 : intRegIndex_(0), floatRegIndex_(0), stackOffset_(0), current_() {}
672
673 ABIArg next(MIRType argType);
674 ABIArg& current() { return current_; }
675 uint32_t stackBytesConsumedSoFar() const { return stackOffset_; }
676 void increaseStackOffset(uint32_t bytes) { stackOffset_ += bytes; }
677
678 protected:
679 unsigned intRegIndex_;
680 unsigned floatRegIndex_;
681 uint32_t stackOffset_;
682 ABIArg current_;
683 };
684
685 // These registers may be volatile or nonvolatile.
686 static constexpr Register ABINonArgReg0 = r8;
687 static constexpr Register ABINonArgReg1 = r9;
688 static constexpr Register ABINonArgReg2 = r10;
689 static constexpr Register ABINonArgReg3 = r11;
690
691 // This register may be volatile or nonvolatile. Avoid d31 which is the
692 // ScratchDoubleReg_.
693 static constexpr FloatRegister ABINonArgDoubleReg = {FloatRegisters::s16,
694 FloatRegisters::Single};
695
696 // These registers may be volatile or nonvolatile.
697 // Note: these three registers are all guaranteed to be different
698 static constexpr Register ABINonArgReturnReg0 = r8;
699 static constexpr Register ABINonArgReturnReg1 = r9;
700 static constexpr Register ABINonVolatileReg{Registers::x19};
701
702 // This register is guaranteed to be clobberable during the prologue and
703 // epilogue of an ABI call which must preserve both ABI argument, return
704 // and non-volatile registers.
705 static constexpr Register ABINonArgReturnVolatileReg = lr;
706
707 // Instance pointer argument register for WebAssembly functions. This must not
708 // alias any other register used for passing function arguments or return
709 // values. Preserved by WebAssembly functions. Must be nonvolatile.
710 static constexpr Register InstanceReg{Registers::x23};
711
712 // Registers used for wasm table calls. These registers must be disjoint
713 // from the ABI argument registers, InstanceReg and each other.
714 static constexpr Register WasmTableCallScratchReg0 = ABINonArgReg0;
715 static constexpr Register WasmTableCallScratchReg1 = ABINonArgReg1;
716 static constexpr Register WasmTableCallSigReg = ABINonArgReg2;
717 static constexpr Register WasmTableCallIndexReg = ABINonArgReg3;
718
719 // Registers used for ref calls.
720 static constexpr Register WasmCallRefCallScratchReg0 = ABINonArgReg0;
721 static constexpr Register WasmCallRefCallScratchReg1 = ABINonArgReg1;
722 static constexpr Register WasmCallRefCallScratchReg2 = ABINonArgReg2;
723 static constexpr Register WasmCallRefReg = ABINonArgReg3;
724
725 // Registers used for wasm tail calls operations.
726 static constexpr Register WasmTailCallInstanceScratchReg = ABINonArgReg1;
727 static constexpr Register WasmTailCallRAScratchReg = lr;
728 static constexpr Register WasmTailCallFPScratchReg = ABINonArgReg3;
729
730 // Register used as a scratch along the return path in the fast js -> wasm stub
731 // code. This must not overlap ReturnReg, JSReturnOperand, or InstanceReg.
732 // It must be a volatile register.
733 static constexpr Register WasmJitEntryReturnScratch = r9;
734
735 static inline bool GetIntArgReg(uint32_t usedIntArgs, uint32_t usedFloatArgs,
736 Register* out) {
737 if (usedIntArgs >= NumIntArgRegs) {
738 return false;
739 }
740 *out = Register::FromCode(usedIntArgs);
741 return true;
742 }
743
744 static inline bool GetFloatArgReg(uint32_t usedIntArgs, uint32_t usedFloatArgs,
745 FloatRegister* out) {
746 if (usedFloatArgs >= NumFloatArgRegs) {
747 return false;
748 }
749 *out = FloatRegister::FromCode(usedFloatArgs);
750 return true;
751 }
752
753 // Get a register in which we plan to put a quantity that will be used as an
754 // integer argument. This differs from GetIntArgReg in that if we have no more
755 // actual argument registers to use we will fall back on using whatever
756 // CallTempReg* don't overlap the argument registers, and only fail once those
757 // run out too.
758 static inline bool GetTempRegForIntArg(uint32_t usedIntArgs,
759 uint32_t usedFloatArgs, Register* out) {
760 if (GetIntArgReg(usedIntArgs, usedFloatArgs, out)) {
761 return true;
762 }
763 // Unfortunately, we have to assume things about the point at which
764 // GetIntArgReg returns false, because we need to know how many registers it
765 // can allocate.
766 usedIntArgs -= NumIntArgRegs;
767 if (usedIntArgs >= NumCallTempNonArgRegs) {
768 return false;
769 }
770 *out = CallTempNonArgRegs[usedIntArgs];
771 return true;
772 }
773
774 // Forbids nop filling for testing purposes. Nestable, but nested calls have
775 // no effect on the no-nops status; it is only the top level one that counts.
776 class AutoForbidNops {
777 protected:
778 Assembler* asm_;
779
780 public:
781 explicit AutoForbidNops(Assembler* asm_) : asm_(asm_) { asm_->enterNoNops(); }
782 ~AutoForbidNops() { asm_->leaveNoNops(); }
783 };
784
785 // Forbids pool generation during a specified interval. Nestable, but nested
786 // calls must imply a no-pool area of the assembler buffer that is completely
787 // contained within the area implied by the outermost level call.
788 class AutoForbidPoolsAndNops : public AutoForbidNops {
789 public:
790 AutoForbidPoolsAndNops(Assembler* asm_, size_t maxInst)
791 : AutoForbidNops(asm_) {
792 asm_->enterNoPool(maxInst);
793 }
794 ~AutoForbidPoolsAndNops() { asm_->leaveNoPool(); }
795 };
796
797 } // namespace jit
798 } // namespace js
799
800 #endif // A64_ASSEMBLER_A64_H_