Debian Codegraph @

js/src/jit/arm64/Assembler-arm64.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/arm64/Assembler-arm64.h"
8
9 #include "mozilla/DebugOnly.h"
10 #include "mozilla/MathAlgorithms.h"
11 #include "mozilla/Maybe.h"
12
13 #include "gc/Marking.h"
14 #include "jit/arm64/Architecture-arm64.h"
15 #include "jit/arm64/MacroAssembler-arm64.h"
16 #include "jit/arm64/vixl/Disasm-vixl.h"
17 #include "jit/AutoWritableJitCode.h"
18 #include "jit/ExecutableAllocator.h"
19 #include "vm/Realm.h"
20
21 #include "gc/StoreBuffer-inl.h"
22
23 using namespace js;
24 using namespace js::jit;
25
26 using mozilla::CountLeadingZeroes32;
27 using mozilla::DebugOnly;
28
29 // Note this is used for inter-wasm calls and may pass arguments and results
30 // in floating point registers even if the system ABI does not.
31
32 ABIArg ABIArgGenerator::next(MIRType type) {
33 switch (type) {
34 case MIRType::Int32:
35 case MIRType::Int64:
36 case MIRType::Pointer:
37 case MIRType::WasmAnyRef:
38 case MIRType::WasmArrayData:
39 case MIRType::StackResults:
40 if (intRegIndex_ == NumIntArgRegs) {
41 current_ = ABIArg(stackOffset_);
42 stackOffset_ += sizeof(uintptr_t);
43 break;
44 }
45 current_ = ABIArg(Register::FromCode(intRegIndex_));
46 intRegIndex_++;
47 break;
48
49 case MIRType::Float32:
50 case MIRType::Double:
51 if (floatRegIndex_ == NumFloatArgRegs) {
52 current_ = ABIArg(stackOffset_);
53 stackOffset_ += sizeof(double);
54 break;
55 }
56 current_ = ABIArg(FloatRegister(FloatRegisters::Encoding(floatRegIndex_),
57 type == MIRType::Double
58 ? FloatRegisters::Double
59 : FloatRegisters::Single));
60 floatRegIndex_++;
61 break;
62
63 #ifdef ENABLE_WASM_SIMD
64 case MIRType::Simd128:
65 if (floatRegIndex_ == NumFloatArgRegs) {
66 stackOffset_ = AlignBytes(stackOffset_, SimdMemoryAlignment);
67 current_ = ABIArg(stackOffset_);
68 stackOffset_ += FloatRegister::SizeOfSimd128;
69 break;
70 }
71 current_ = ABIArg(FloatRegister(FloatRegisters::Encoding(floatRegIndex_),
72 FloatRegisters::Simd128));
73 floatRegIndex_++;
74 break;
75 #endif
76
77 default:
78 // Note that in Assembler-x64.cpp there's a special case for Win64 which
79 // does not allow passing SIMD by value. Since there's Win64 on ARM64 we
80 // may need to duplicate that logic here.
81 MOZ_CRASH("Unexpected argument type");
82 }
83 return current_;
84 }
85
86 namespace js {
87 namespace jit {
88
89 void Assembler::finish() {
90 armbuffer_.flushPool();
91
92 // The extended jump table is part of the code buffer.
93 ExtendedJumpTable_ = emitExtendedJumpTable();
94 Assembler::FinalizeCode();
95 }
96
97 bool Assembler::appendRawCode(const uint8_t* code, size_t numBytes) {
98 flush();
99 return armbuffer_.appendRawCode(code, numBytes);
100 }
101
102 bool Assembler::reserve(size_t size) {
103 // This buffer uses fixed-size chunks so there's no point in reserving
104 // now vs. on-demand.
105 return !oom();
106 }
107
108 bool Assembler::swapBuffer(wasm::Bytes& bytes) {
109 // For now, specialize to the one use case. As long as wasm::Bytes is a
110 // Vector, not a linked-list of chunks, there's not much we can do other
111 // than copy.
112 MOZ_ASSERT(bytes.empty());
113 if (!bytes.resize(bytesNeeded())) {
114 return false;
115 }
116 armbuffer_.executableCopy(bytes.begin());
117 return true;
118 }
119
120 BufferOffset Assembler::emitExtendedJumpTable() {
121 if (!pendingJumps_.length() || oom()) {
122 return BufferOffset();
123 }
124
125 armbuffer_.flushPool();
126 armbuffer_.align(SizeOfJumpTableEntry);
127
128 BufferOffset tableOffset = armbuffer_.nextOffset();
129
130 for (size_t i = 0; i < pendingJumps_.length(); i++) {
131 // Each JumpTableEntry is of the form:
132 // LDR ip0 [PC, 8]
133 // BR ip0
134 // [Patchable 8-byte constant low bits]
135 // [Patchable 8-byte constant high bits]
136 DebugOnly<size_t> preOffset = size_t(armbuffer_.nextOffset().getOffset());
137
138 // The unguarded use of ScratchReg64 here is OK:
139 //
140 // - The present function is called from code that does not claim any
141 // scratch registers, we're done compiling user code and are emitting jump
142 // tables. Hence the scratch registers are available when we enter.
143 //
144 // - The pendingJumps_ represent jumps to other code sections that are not
145 // known to this MacroAssembler instance, and we're generating code to
146 // jump there. It is safe to assume that any code using such a generated
147 // branch to an unknown location did not store any valuable value in any
148 // scratch register. Hence the scratch registers can definitely be
149 // clobbered here.
150 //
151 // - Scratch register usage is restricted to sequential control flow within
152 // MacroAssembler functions. Hence the scratch registers will not be
153 // clobbered by ldr and br as they are Assembler primitives, not
154 // MacroAssembler functions.
155
156 ldr(ScratchReg64, ptrdiff_t(8 / vixl::kInstructionSize));
157 br(ScratchReg64);
158
159 DebugOnly<size_t> prePointer = size_t(armbuffer_.nextOffset().getOffset());
160 MOZ_ASSERT_IF(!oom(),
161 prePointer - preOffset == OffsetOfJumpTableEntryPointer);
162
163 brk(0x0);
164 brk(0x0);
165
166 DebugOnly<size_t> postOffset = size_t(armbuffer_.nextOffset().getOffset());
167
168 MOZ_ASSERT_IF(!oom(), postOffset - preOffset == SizeOfJumpTableEntry);
169 }
170
171 if (oom()) {
172 return BufferOffset();
173 }
174
175 return tableOffset;
176 }
177
178 void Assembler::executableCopy(uint8_t* buffer) {
179 // Copy the code and all constant pools into the output buffer.
180 armbuffer_.executableCopy(buffer);
181
182 // Patch any relative jumps that target code outside the buffer.
183 // The extended jump table may be used for distant jumps.
184 for (size_t i = 0; i < pendingJumps_.length(); i++) {
185 RelativePatch& rp = pendingJumps_[i];
186 MOZ_ASSERT(rp.target);
187
188 Instruction* target = (Instruction*)rp.target;
189 Instruction* branch = (Instruction*)(buffer + rp.offset.getOffset());
190 JumpTableEntry* extendedJumpTable = reinterpret_cast<JumpTableEntry*>(
191 buffer + ExtendedJumpTable_.getOffset());
192 if (branch->BranchType() != vixl::UnknownBranchType) {
193 if (branch->IsTargetReachable(target)) {
194 branch->SetImmPCOffsetTarget(target);
195 } else {
196 JumpTableEntry* entry = &extendedJumpTable[i];
197 branch->SetImmPCOffsetTarget(entry->getLdr());
198 entry->data = target;
199 }
200 } else {
201 // Currently a two-instruction call, it should be possible to optimize
202 // this into a single instruction call + nop in some instances, but this
203 // will work.
204 }
205 }
206 }
207
208 BufferOffset Assembler::immPool(ARMRegister dest, uint8_t* value,
209 vixl::LoadLiteralOp op, const LiteralDoc& doc,
210 ARMBuffer::PoolEntry* pe) {
211 uint32_t inst = op | Rt(dest);
212 const size_t numInst = 1;
213 const unsigned sizeOfPoolEntryInBytes = 4;
214 const unsigned numPoolEntries = sizeof(value) / sizeOfPoolEntryInBytes;
215 return allocLiteralLoadEntry(numInst, numPoolEntries, (uint8_t*)&inst, value,
216 doc, pe);
217 }
218
219 BufferOffset Assembler::immPool64(ARMRegister dest, uint64_t value,
220 ARMBuffer::PoolEntry* pe) {
221 return immPool(dest, (uint8_t*)&value, vixl::LDR_x_lit, LiteralDoc(value),
222 pe);
223 }
224
225 BufferOffset Assembler::fImmPool(ARMFPRegister dest, uint8_t* value,
226 vixl::LoadLiteralOp op,
227 const LiteralDoc& doc) {
228 uint32_t inst = op | Rt(dest);
229 const size_t numInst = 1;
230 const unsigned sizeOfPoolEntryInBits = 32;
231 const unsigned numPoolEntries = dest.size() / sizeOfPoolEntryInBits;
232 return allocLiteralLoadEntry(numInst, numPoolEntries, (uint8_t*)&inst, value,
233 doc);
234 }
235
236 BufferOffset Assembler::fImmPool64(ARMFPRegister dest, double value) {
237 return fImmPool(dest, (uint8_t*)&value, vixl::LDR_d_lit, LiteralDoc(value));
238 }
239
240 BufferOffset Assembler::fImmPool32(ARMFPRegister dest, float value) {
241 return fImmPool(dest, (uint8_t*)&value, vixl::LDR_s_lit, LiteralDoc(value));
242 }
243
244 void Assembler::bind(Label* label, BufferOffset targetOffset) {
245 #ifdef JS_DISASM_ARM64
246 spew_.spewBind(label);
247 #endif
248 // Nothing has seen the label yet: just mark the location.
249 // If we've run out of memory, don't attempt to modify the buffer which may
250 // not be there. Just mark the label as bound to the (possibly bogus)
251 // targetOffset.
252 if (!label->used() || oom()) {
253 label->bind(targetOffset.getOffset());
254 return;
255 }
256
257 // Get the most recent instruction that used the label, as stored in the
258 // label. This instruction is the head of an implicit linked list of label
259 // uses.
260 BufferOffset branchOffset(label);
261
262 while (branchOffset.assigned()) {
263 // Before overwriting the offset in this instruction, get the offset of
264 // the next link in the implicit branch list.
265 BufferOffset nextOffset = NextLink(branchOffset);
266
267 // Linking against the actual (Instruction*) would be invalid,
268 // since that Instruction could be anywhere in memory.
269 // Instead, just link against the correct relative offset, assuming
270 // no constant pools, which will be taken into consideration
271 // during finalization.
272 ptrdiff_t relativeByteOffset =
273 targetOffset.getOffset() - branchOffset.getOffset();
274 Instruction* link = getInstructionAt(branchOffset);
275
276 // This branch may still be registered for callbacks. Stop tracking it.
277 vixl::ImmBranchType branchType = link->BranchType();
278 vixl::ImmBranchRangeType branchRange =
279 Instruction::ImmBranchTypeToRange(branchType);
280 if (branchRange < vixl::NumShortBranchRangeTypes) {
281 BufferOffset deadline(
282 branchOffset.getOffset() +
283 Instruction::ImmBranchMaxForwardOffset(branchRange));
284 armbuffer_.unregisterBranchDeadline(branchRange, deadline);
285 }
286
287 // Is link able to reach the label?
288 if (link->IsPCRelAddressing() ||
289 link->IsTargetReachable(link + relativeByteOffset)) {
290 // Write a new relative offset into the instruction.
291 link->SetImmPCOffsetTarget(link + relativeByteOffset);
292 } else {
293 // This is a short-range branch, and it can't reach the label directly.
294 // Verify that it branches to a veneer: an unconditional branch.
295 MOZ_ASSERT(getInstructionAt(nextOffset)->BranchType() ==
296 vixl::UncondBranchType);
297 }
298
299 branchOffset = nextOffset;
300 }
301
302 // Bind the label, so that future uses may encode the offset immediately.
303 label->bind(targetOffset.getOffset());
304 }
305
306 void Assembler::addPendingJump(BufferOffset src, ImmPtr target,
307 RelocationKind reloc) {
308 MOZ_ASSERT(target.value != nullptr);
309
310 if (reloc == RelocationKind::JITCODE) {
311 jumpRelocations_.writeUnsigned(src.getOffset());
312 }
313
314 // This jump is not patchable at runtime. Extended jump table entry
315 // requirements cannot be known until finalization, so to be safe, give each
316 // jump and entry. This also causes GC tracing of the target.
317 enoughMemory_ &=
318 pendingJumps_.append(RelativePatch(src, target.value, reloc));
319 }
320
321 void Assembler::PatchWrite_NearCall(CodeLocationLabel start,
322 CodeLocationLabel toCall) {
323 Instruction* dest = (Instruction*)start.raw();
324 ptrdiff_t relTarget = (Instruction*)toCall.raw() - dest;
325 ptrdiff_t relTarget00 = relTarget >> 2;
326 MOZ_RELEASE_ASSERT((relTarget & 0x3) == 0);
327 MOZ_RELEASE_ASSERT(vixl::IsInt26(relTarget00));
328
329 bl(dest, relTarget00);
330 }
331
332 void Assembler::PatchDataWithValueCheck(CodeLocationLabel label,
333 PatchedImmPtr newValue,
334 PatchedImmPtr expected) {
335 Instruction* i = (Instruction*)label.raw();
336 void** pValue = i->LiteralAddress<void**>();
337 MOZ_ASSERT(*pValue == expected.value);
338 *pValue = newValue.value;
339 }
340
341 void Assembler::PatchDataWithValueCheck(CodeLocationLabel label,
342 ImmPtr newValue, ImmPtr expected) {
343 PatchDataWithValueCheck(label, PatchedImmPtr(newValue.value),
344 PatchedImmPtr(expected.value));
345 }
346
347 void Assembler::ToggleToJmp(CodeLocationLabel inst_) {
348 Instruction* i = (Instruction*)inst_.raw();
349 MOZ_ASSERT(i->IsAddSubImmediate());
350
351 // Refer to instruction layout in ToggleToCmp().
352 int imm19 = (int)i->Bits(23, 5);
353 MOZ_ASSERT(vixl::IsInt19(imm19));
354
355 b(i, imm19, Always);
356 }
357
358 void Assembler::ToggleToCmp(CodeLocationLabel inst_) {
359 Instruction* i = (Instruction*)inst_.raw();
360 MOZ_ASSERT(i->IsCondB());
361
362 int imm19 = i->ImmCondBranch();
363 // bit 23 is reserved, and the simulator throws an assertion when this happens
364 // It'll be messy to decode, but we can steal bit 30 or bit 31.
365 MOZ_ASSERT(vixl::IsInt18(imm19));
366
367 // 31 - 64-bit if set, 32-bit if unset. (OK!)
368 // 30 - sub if set, add if unset. (OK!)
369 // 29 - SetFlagsBit. Must be set.
370 // 22:23 - ShiftAddSub. (OK!)
371 // 10:21 - ImmAddSub. (OK!)
372 // 5:9 - First source register (Rn). (OK!)
373 // 0:4 - Destination Register. Must be xzr.
374
375 // From the above, there is a safe 19-bit contiguous region from 5:23.
376 Emit(i, vixl::ThirtyTwoBits | vixl::AddSubImmediateFixed | vixl::SUB |
377 Flags(vixl::SetFlags) | Rd(vixl::xzr) |
378 (imm19 << vixl::Rn_offset));
379 }
380
381 void Assembler::ToggleCall(CodeLocationLabel inst_, bool enabled) {
382 const Instruction* first = reinterpret_cast<Instruction*>(inst_.raw());
383 Instruction* load;
384 Instruction* call;
385
386 // There might be a constant pool at the very first instruction.
387 first = first->skipPool();
388
389 // Skip the stack pointer restore instruction.
390 if (first->IsStackPtrSync()) {
391 first = first->InstructionAtOffset(vixl::kInstructionSize)->skipPool();
392 }
393
394 load = const_cast<Instruction*>(first);
395
396 // The call instruction follows the load, but there may be an injected
397 // constant pool.
398 call = const_cast<Instruction*>(
399 load->InstructionAtOffset(vixl::kInstructionSize)->skipPool());
400
401 if (call->IsBLR() == enabled) {
402 return;
403 }
404
405 if (call->IsBLR()) {
406 // If the second instruction is blr(), then we have:
407 // ldr x17, [pc, offset]
408 // blr x17
409 MOZ_ASSERT(load->IsLDR());
410 // We want to transform this to:
411 // adr xzr, [pc, offset]
412 // nop
413 int32_t offset = load->ImmLLiteral();
414 adr(load, xzr, int32_t(offset));
415 nop(call);
416 } else {
417 // We have:
418 // adr xzr, [pc, offset] (or ldr x17, [pc, offset])
419 // nop
420 MOZ_ASSERT(load->IsADR() || load->IsLDR());
421 MOZ_ASSERT(call->IsNOP());
422 // Transform this to:
423 // ldr x17, [pc, offset]
424 // blr x17
425 int32_t offset = (int)load->ImmPCRawOffset();
426 MOZ_ASSERT(vixl::IsInt19(offset));
427 ldr(load, ScratchReg2_64, int32_t(offset));
428 blr(call, ScratchReg2_64);
429 }
430 }
431
432 // Patches loads generated by MacroAssemblerCompat::mov(CodeLabel*, Register).
433 // The loading code is implemented in movePatchablePtr().
434 void Assembler::UpdateLoad64Value(Instruction* inst0, uint64_t value) {
435 MOZ_ASSERT(inst0->IsLDR());
436 uint64_t* literal = inst0->LiteralAddress<uint64_t*>();
437 *literal = value;
438 }
439
440 class RelocationIterator {
441 CompactBufferReader reader_;
442 uint32_t offset_ = 0;
443
444 public:
445 explicit RelocationIterator(CompactBufferReader& reader) : reader_(reader) {}
446
447 bool read() {
448 if (!reader_.more()) {
449 return false;
450 }
451 offset_ = reader_.readUnsigned();
452 return true;
453 }
454
455 uint32_t offset() const { return offset_; }
456 };
457
458 static JitCode* CodeFromJump(JitCode* code, uint8_t* jump) {
459 const Instruction* inst = (const Instruction*)jump;
460 uint8_t* target;
461
462 // We're expecting a call created by MacroAssembler::call(JitCode*).
463 // It looks like:
464 //
465 // ldr scratch, [pc, offset]
466 // blr scratch
467 //
468 // If the call has been toggled by ToggleCall(), it looks like:
469 //
470 // adr xzr, [pc, offset]
471 // nop
472 //
473 // There might be a constant pool at the very first instruction.
474 // See also ToggleCall().
475 inst = inst->skipPool();
476
477 // Skip the stack pointer restore instruction.
478 if (inst->IsStackPtrSync()) {
479 inst = inst->InstructionAtOffset(vixl::kInstructionSize)->skipPool();
480 }
481
482 if (inst->BranchType() != vixl::UnknownBranchType) {
483 // This is an immediate branch.
484 target = (uint8_t*)inst->ImmPCOffsetTarget();
485 } else if (inst->IsLDR()) {
486 // This is an ldr+blr call that is enabled. See ToggleCall().
487 mozilla::DebugOnly<const Instruction*> nextInst =
488 inst->InstructionAtOffset(vixl::kInstructionSize)->skipPool();
489 MOZ_ASSERT(nextInst->IsNOP() || nextInst->IsBLR());
490 target = (uint8_t*)inst->Literal64();
491 } else if (inst->IsADR()) {
492 // This is a disabled call: adr+nop. See ToggleCall().
493 mozilla::DebugOnly<const Instruction*> nextInst =
494 inst->InstructionAtOffset(vixl::kInstructionSize)->skipPool();
495 MOZ_ASSERT(nextInst->IsNOP());
496 ptrdiff_t offset = inst->ImmPCRawOffset() << vixl::kLiteralEntrySizeLog2;
497 // This is what Literal64 would do with the corresponding ldr.
498 memcpy(&target, inst + offset, sizeof(target));
499 } else {
500 MOZ_CRASH("Unrecognized jump instruction.");
501 }
502
503 // If the jump is within the code buffer, it uses the extended jump table.
504 if (target >= code->raw() &&
505 target < code->raw() + code->instructionsSize()) {
506 MOZ_ASSERT(target + Assembler::SizeOfJumpTableEntry <=
507 code->raw() + code->instructionsSize());
508
509 uint8_t** patchablePtr =
510 (uint8_t**)(target + Assembler::OffsetOfJumpTableEntryPointer);
511 target = *patchablePtr;
512 }
513
514 return JitCode::FromExecutable(target);
515 }
516
517 void Assembler::TraceJumpRelocations(JSTracer* trc, JitCode* code,
518 CompactBufferReader& reader) {
519 RelocationIterator iter(reader);
520 while (iter.read()) {
521 JitCode* child = CodeFromJump(code, code->raw() + iter.offset());
522 TraceManuallyBarrieredEdge(trc, &child, "rel32");
523 MOZ_ASSERT(child == CodeFromJump(code, code->raw() + iter.offset()));
524 }
525 }
526
527 /* static */
528 void Assembler::TraceDataRelocations(JSTracer* trc, JitCode* code,
529 CompactBufferReader& reader) {
530 mozilla::Maybe<AutoWritableJitCode> awjc;
531
532 uint8_t* buffer = code->raw();
533
534 while (reader.more()) {
535 size_t offset = reader.readUnsigned();
536 Instruction* load = (Instruction*)&buffer[offset];
537
538 // The only valid traceable operation is a 64-bit load to an ARMRegister.
539 // Refer to movePatchablePtr() for generation.
540 MOZ_ASSERT(load->Mask(vixl::LoadLiteralMask) == vixl::LDR_x_lit);
541
542 uintptr_t* literalAddr = load->LiteralAddress<uintptr_t*>();
543 uintptr_t literal = *literalAddr;
544
545 // Data relocations can be for Values or for raw pointers. If a Value is
546 // zero-tagged, we can trace it as if it were a raw pointer. If a Value
547 // is not zero-tagged, we have to interpret it as a Value to ensure that the
548 // tag bits are masked off to recover the actual pointer.
549
550 if (literal >> JSVAL_TAG_SHIFT) {
551 // This relocation is a Value with a non-zero tag.
552 Value v = Value::fromRawBits(literal);
553 TraceManuallyBarrieredEdge(trc, &v, "jit-masm-value");
554 if (*literalAddr != v.asRawBits()) {
555 if (awjc.isNothing()) {
556 awjc.emplace(code);
557 }
558 *literalAddr = v.asRawBits();
559 }
560 continue;
561 }
562
563 // This relocation is a raw pointer or a Value with a zero tag.
564 // No barriers needed since the pointers are constants.
565 gc::Cell* cell = reinterpret_cast<gc::Cell*>(literal);
566 MOZ_ASSERT(gc::IsCellPointerValid(cell));
567 TraceManuallyBarrieredGenericPointerEdge(trc, &cell, "jit-masm-ptr");
568 if (uintptr_t(cell) != literal) {
569 if (awjc.isNothing()) {
570 awjc.emplace(code);
571 }
572 *literalAddr = uintptr_t(cell);
573 }
574 }
575 }
576
577 void Assembler::retarget(Label* label, Label* target) {
578 #ifdef JS_DISASM_ARM64
579 spew_.spewRetarget(label, target);
580 #endif
581 if (label->used()) {
582 if (target->bound()) {
583 bind(label, BufferOffset(target));
584 } else if (target->used()) {
585 // The target is not bound but used. Prepend label's branch list
586 // onto target's.
587 BufferOffset labelBranchOffset(label);
588
589 // Find the head of the use chain for label.
590 BufferOffset next = NextLink(labelBranchOffset);
591 while (next.assigned()) {
592 labelBranchOffset = next;
593 next = NextLink(next);
594 }
595
596 // Then patch the head of label's use chain to the tail of target's
597 // use chain, prepending the entire use chain of target.
598 SetNextLink(labelBranchOffset, BufferOffset(target));
599 target->use(label->offset());
600 } else {
601 // The target is unbound and unused. We can just take the head of
602 // the list hanging off of label, and dump that into target.
603 target->use(label->offset());
604 }
605 }
606 label->reset();
607 }
608
609 } // namespace jit
610 } // namespace js