Debian Codegraph @

js/src/jit/arm/Assembler-arm.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/arm/Assembler-arm.h"
8
9 #include "mozilla/DebugOnly.h"
10 #include "mozilla/MathAlgorithms.h"
11 #include "mozilla/Maybe.h"
12 #include "mozilla/Sprintf.h"
13
14 #include <type_traits>
15
16 #include "gc/Marking.h"
17 #include "jit/arm/disasm/Disasm-arm.h"
18 #include "jit/arm/MacroAssembler-arm.h"
19 #include "jit/AutoWritableJitCode.h"
20 #include "jit/ExecutableAllocator.h"
21 #include "jit/MacroAssembler.h"
22 #include "vm/Realm.h"
23
24 using namespace js;
25 using namespace js::jit;
26
27 using mozilla::CountLeadingZeroes32;
28 using mozilla::DebugOnly;
29
30 using LabelDoc = DisassemblerSpew::LabelDoc;
31 using LiteralDoc = DisassemblerSpew::LiteralDoc;
32
33 void dbg_break() {}
34
35 // The ABIArgGenerator is used for making system ABI calls and for inter-wasm
36 // calls. The system ABI can either be SoftFp or HardFp, and inter-wasm calls
37 // are always HardFp calls. The initialization defaults to HardFp, and the ABI
38 // choice is made before any system ABI calls with the method "setUseHardFp".
39 ABIArgGenerator::ABIArgGenerator()
40 : intRegIndex_(0),
41 floatRegIndex_(0),
42 stackOffset_(0),
43 current_(),
44 useHardFp_(true) {}
45
46 // See the "Parameter Passing" section of the "Procedure Call Standard for the
47 // ARM Architecture" documentation.
48 ABIArg ABIArgGenerator::softNext(MIRType type) {
49 switch (type) {
50 case MIRType::Int32:
51 case MIRType::Pointer:
52 case MIRType::WasmAnyRef:
53 case MIRType::WasmArrayData:
54 case MIRType::StackResults:
55 if (intRegIndex_ == NumIntArgRegs) {
56 current_ = ABIArg(stackOffset_);
57 stackOffset_ += sizeof(uint32_t);
58 break;
59 }
60 current_ = ABIArg(Register::FromCode(intRegIndex_));
61 intRegIndex_++;
62 break;
63 case MIRType::Int64:
64 // Make sure to use an even register index. Increase to next even number
65 // when odd.
66 intRegIndex_ = (intRegIndex_ + 1) & ~1;
67 if (intRegIndex_ == NumIntArgRegs) {
68 // Align the stack on 8 bytes.
69 static const uint32_t align = sizeof(uint64_t) - 1;
70 stackOffset_ = (stackOffset_ + align) & ~align;
71 current_ = ABIArg(stackOffset_);
72 stackOffset_ += sizeof(uint64_t);
73 break;
74 }
75 current_ = ABIArg(Register::FromCode(intRegIndex_),
76 Register::FromCode(intRegIndex_ + 1));
77 intRegIndex_ += 2;
78 break;
79 case MIRType::Float32:
80 if (intRegIndex_ == NumIntArgRegs) {
81 current_ = ABIArg(stackOffset_);
82 stackOffset_ += sizeof(uint32_t);
83 break;
84 }
85 current_ = ABIArg(Register::FromCode(intRegIndex_));
86 intRegIndex_++;
87 break;
88 case MIRType::Double:
89 // Make sure to use an even register index. Increase to next even number
90 // when odd.
91 intRegIndex_ = (intRegIndex_ + 1) & ~1;
92 if (intRegIndex_ == NumIntArgRegs) {
93 // Align the stack on 8 bytes.
94 static const uint32_t align = sizeof(double) - 1;
95 stackOffset_ = (stackOffset_ + align) & ~align;
96 current_ = ABIArg(stackOffset_);
97 stackOffset_ += sizeof(double);
98 break;
99 }
100 current_ = ABIArg(Register::FromCode(intRegIndex_),
101 Register::FromCode(intRegIndex_ + 1));
102 intRegIndex_ += 2;
103 break;
104 default:
105 MOZ_CRASH("Unexpected argument type");
106 }
107
108 return current_;
109 }
110
111 ABIArg ABIArgGenerator::hardNext(MIRType type) {
112 switch (type) {
113 case MIRType::Int32:
114 case MIRType::Pointer:
115 case MIRType::WasmAnyRef:
116 case MIRType::WasmArrayData:
117 case MIRType::StackResults:
118 if (intRegIndex_ == NumIntArgRegs) {
119 current_ = ABIArg(stackOffset_);
120 stackOffset_ += sizeof(uint32_t);
121 break;
122 }
123 current_ = ABIArg(Register::FromCode(intRegIndex_));
124 intRegIndex_++;
125 break;
126 case MIRType::Int64:
127 // Make sure to use an even register index. Increase to next even number
128 // when odd.
129 intRegIndex_ = (intRegIndex_ + 1) & ~1;
130 if (intRegIndex_ == NumIntArgRegs) {
131 // Align the stack on 8 bytes.
132 static const uint32_t align = sizeof(uint64_t) - 1;
133 stackOffset_ = (stackOffset_ + align) & ~align;
134 current_ = ABIArg(stackOffset_);
135 stackOffset_ += sizeof(uint64_t);
136 break;
137 }
138 current_ = ABIArg(Register::FromCode(intRegIndex_),
139 Register::FromCode(intRegIndex_ + 1));
140 intRegIndex_ += 2;
141 break;
142 case MIRType::Float32:
143 if (floatRegIndex_ == NumFloatArgRegs) {
144 current_ = ABIArg(stackOffset_);
145 stackOffset_ += sizeof(uint32_t);
146 break;
147 }
148 current_ = ABIArg(VFPRegister(floatRegIndex_, VFPRegister::Single));
149 floatRegIndex_++;
150 break;
151 case MIRType::Double:
152 // Double register are composed of 2 float registers, thus we have to
153 // skip any float register which cannot be used in a pair of float
154 // registers in which a double value can be stored.
155 floatRegIndex_ = (floatRegIndex_ + 1) & ~1;
156 if (floatRegIndex_ == NumFloatArgRegs) {
157 static const uint32_t align = sizeof(double) - 1;
158 stackOffset_ = (stackOffset_ + align) & ~align;
159 current_ = ABIArg(stackOffset_);
160 stackOffset_ += sizeof(uint64_t);
161 break;
162 }
163 current_ = ABIArg(VFPRegister(floatRegIndex_ >> 1, VFPRegister::Double));
164 floatRegIndex_ += 2;
165 break;
166 default:
167 MOZ_CRASH("Unexpected argument type");
168 }
169
170 return current_;
171 }
172
173 ABIArg ABIArgGenerator::next(MIRType type) {
174 if (useHardFp_) {
175 return hardNext(type);
176 }
177 return softNext(type);
178 }
179
180 bool js::jit::IsUnaligned(const wasm::MemoryAccessDesc& access) {
181 if (!access.align()) {
182 return false;
183 }
184
185 if (access.type() == Scalar::Float64 && access.align() >= 4) {
186 return false;
187 }
188
189 return access.align() < access.byteSize();
190 }
191
192 // Encode a standard register when it is being used as src1, the dest, and an
193 // extra register. These should never be called with an InvalidReg.
194 uint32_t js::jit::RT(Register r) {
195 MOZ_ASSERT((r.code() & ~0xf) == 0);
196 return r.code() << 12;
197 }
198
199 uint32_t js::jit::RN(Register r) {
200 MOZ_ASSERT((r.code() & ~0xf) == 0);
201 return r.code() << 16;
202 }
203
204 uint32_t js::jit::RD(Register r) {
205 MOZ_ASSERT((r.code() & ~0xf) == 0);
206 return r.code() << 12;
207 }
208
209 uint32_t js::jit::RM(Register r) {
210 MOZ_ASSERT((r.code() & ~0xf) == 0);
211 return r.code() << 8;
212 }
213
214 // Encode a standard register when it is being used as src1, the dest, and an
215 // extra register. For these, an InvalidReg is used to indicate a optional
216 // register that has been omitted.
217 uint32_t js::jit::maybeRT(Register r) {
218 if (r == InvalidReg) {
219 return 0;
220 }
221
222 MOZ_ASSERT((r.code() & ~0xf) == 0);
223 return r.code() << 12;
224 }
225
226 uint32_t js::jit::maybeRN(Register r) {
227 if (r == InvalidReg) {
228 return 0;
229 }
230
231 MOZ_ASSERT((r.code() & ~0xf) == 0);
232 return r.code() << 16;
233 }
234
235 uint32_t js::jit::maybeRD(Register r) {
236 if (r == InvalidReg) {
237 return 0;
238 }
239
240 MOZ_ASSERT((r.code() & ~0xf) == 0);
241 return r.code() << 12;
242 }
243
244 Register js::jit::toRD(Instruction i) {
245 return Register::FromCode((i.encode() >> 12) & 0xf);
246 }
247 Register js::jit::toR(Instruction i) {
248 return Register::FromCode(i.encode() & 0xf);
249 }
250
251 Register js::jit::toRM(Instruction i) {
252 return Register::FromCode((i.encode() >> 8) & 0xf);
253 }
254
255 Register js::jit::toRN(Instruction i) {
256 return Register::FromCode((i.encode() >> 16) & 0xf);
257 }
258
259 uint32_t js::jit::VD(VFPRegister vr) {
260 if (vr.isMissing()) {
261 return 0;
262 }
263
264 // Bits 15,14,13,12, 22.
265 VFPRegister::VFPRegIndexSplit s = vr.encode();
266 return s.bit << 22 | s.block << 12;
267 }
268 uint32_t js::jit::VN(VFPRegister vr) {
269 if (vr.isMissing()) {
270 return 0;
271 }
272
273 // Bits 19,18,17,16, 7.
274 VFPRegister::VFPRegIndexSplit s = vr.encode();
275 return s.bit << 7 | s.block << 16;
276 }
277 uint32_t js::jit::VM(VFPRegister vr) {
278 if (vr.isMissing()) {
279 return 0;
280 }
281
282 // Bits 5, 3,2,1,0.
283 VFPRegister::VFPRegIndexSplit s = vr.encode();
284 return s.bit << 5 | s.block;
285 }
286
287 VFPRegister::VFPRegIndexSplit jit::VFPRegister::encode() {
288 MOZ_ASSERT(!_isInvalid);
289
290 switch (kind) {
291 case Double:
292 return VFPRegIndexSplit(code_ & 0xf, code_ >> 4);
293 case Single:
294 return VFPRegIndexSplit(code_ >> 1, code_ & 1);
295 default:
296 // VFP register treated as an integer, NOT a gpr.
297 return VFPRegIndexSplit(code_ >> 1, code_ & 1);
298 }
299 }
300
301 bool InstDTR::IsTHIS(const Instruction& i) {
302 return (i.encode() & IsDTRMask) == (uint32_t)IsDTR;
303 }
304
305 InstDTR* InstDTR::AsTHIS(const Instruction& i) {
306 if (IsTHIS(i)) {
307 return (InstDTR*)&i;
308 }
309 return nullptr;
310 }
311
312 bool InstLDR::IsTHIS(const Instruction& i) {
313 return (i.encode() & IsDTRMask) == (uint32_t)IsDTR;
314 }
315
316 InstLDR* InstLDR::AsTHIS(const Instruction& i) {
317 if (IsTHIS(i)) {
318 return (InstLDR*)&i;
319 }
320 return nullptr;
321 }
322
323 InstNOP* InstNOP::AsTHIS(Instruction& i) {
324 if (IsTHIS(i)) {
325 return (InstNOP*)&i;
326 }
327 return nullptr;
328 }
329
330 bool InstNOP::IsTHIS(const Instruction& i) {
331 return (i.encode() & 0x0fffffff) == NopInst;
332 }
333
334 bool InstBranchReg::IsTHIS(const Instruction& i) {
335 return InstBXReg::IsTHIS(i) || InstBLXReg::IsTHIS(i);
336 }
337
338 InstBranchReg* InstBranchReg::AsTHIS(const Instruction& i) {
339 if (IsTHIS(i)) {
340 return (InstBranchReg*)&i;
341 }
342 return nullptr;
343 }
344 void InstBranchReg::extractDest(Register* dest) { *dest = toR(*this); }
345 bool InstBranchReg::checkDest(Register dest) { return dest == toR(*this); }
346
347 bool InstBranchImm::IsTHIS(const Instruction& i) {
348 return InstBImm::IsTHIS(i) || InstBLImm::IsTHIS(i);
349 }
350
351 InstBranchImm* InstBranchImm::AsTHIS(const Instruction& i) {
352 if (IsTHIS(i)) {
353 return (InstBranchImm*)&i;
354 }
355 return nullptr;
356 }
357
358 void InstBranchImm::extractImm(BOffImm* dest) { *dest = BOffImm(*this); }
359
360 bool InstBXReg::IsTHIS(const Instruction& i) {
361 return (i.encode() & IsBRegMask) == IsBX;
362 }
363
364 InstBXReg* InstBXReg::AsTHIS(const Instruction& i) {
365 if (IsTHIS(i)) {
366 return (InstBXReg*)&i;
367 }
368 return nullptr;
369 }
370
371 bool InstBLXReg::IsTHIS(const Instruction& i) {
372 return (i.encode() & IsBRegMask) == IsBLX;
373 }
374 InstBLXReg* InstBLXReg::AsTHIS(const Instruction& i) {
375 if (IsTHIS(i)) {
376 return (InstBLXReg*)&i;
377 }
378 return nullptr;
379 }
380
381 bool InstBImm::IsTHIS(const Instruction& i) {
382 return (i.encode() & IsBImmMask) == IsB;
383 }
384 InstBImm* InstBImm::AsTHIS(const Instruction& i) {
385 if (IsTHIS(i)) {
386 return (InstBImm*)&i;
387 }
388 return nullptr;
389 }
390
391 bool InstBLImm::IsTHIS(const Instruction& i) {
392 return (i.encode() & IsBImmMask) == IsBL;
393 }
394 InstBLImm* InstBLImm::AsTHIS(const Instruction& i) {
395 if (IsTHIS(i)) {
396 return (InstBLImm*)&i;
397 }
398 return nullptr;
399 }
400
401 bool InstMovWT::IsTHIS(Instruction& i) {
402 return InstMovW::IsTHIS(i) || InstMovT::IsTHIS(i);
403 }
404 InstMovWT* InstMovWT::AsTHIS(Instruction& i) {
405 if (IsTHIS(i)) {
406 return (InstMovWT*)&i;
407 }
408 return nullptr;
409 }
410
411 void InstMovWT::extractImm(Imm16* imm) { *imm = Imm16(*this); }
412 bool InstMovWT::checkImm(Imm16 imm) {
413 return imm.decode() == Imm16(*this).decode();
414 }
415
416 void InstMovWT::extractDest(Register* dest) { *dest = toRD(*this); }
417 bool InstMovWT::checkDest(Register dest) { return dest == toRD(*this); }
418
419 bool InstMovW::IsTHIS(const Instruction& i) {
420 return (i.encode() & IsWTMask) == IsW;
421 }
422
423 InstMovW* InstMovW::AsTHIS(const Instruction& i) {
424 if (IsTHIS(i)) {
425 return (InstMovW*)&i;
426 }
427 return nullptr;
428 }
429 InstMovT* InstMovT::AsTHIS(const Instruction& i) {
430 if (IsTHIS(i)) {
431 return (InstMovT*)&i;
432 }
433 return nullptr;
434 }
435
436 bool InstMovT::IsTHIS(const Instruction& i) {
437 return (i.encode() & IsWTMask) == IsT;
438 }
439
440 InstALU* InstALU::AsTHIS(const Instruction& i) {
441 if (IsTHIS(i)) {
442 return (InstALU*)&i;
443 }
444 return nullptr;
445 }
446 bool InstALU::IsTHIS(const Instruction& i) {
447 return (i.encode() & ALUMask) == 0;
448 }
449 void InstALU::extractOp(ALUOp* ret) { *ret = ALUOp(encode() & (0xf << 21)); }
450 bool InstALU::checkOp(ALUOp op) {
451 ALUOp mine;
452 extractOp(&mine);
453 return mine == op;
454 }
455 void InstALU::extractDest(Register* ret) { *ret = toRD(*this); }
456 bool InstALU::checkDest(Register rd) { return rd == toRD(*this); }
457 void InstALU::extractOp1(Register* ret) { *ret = toRN(*this); }
458 bool InstALU::checkOp1(Register rn) { return rn == toRN(*this); }
459 Operand2 InstALU::extractOp2() { return Operand2(encode()); }
460
461 InstCMP* InstCMP::AsTHIS(const Instruction& i) {
462 if (IsTHIS(i)) {
463 return (InstCMP*)&i;
464 }
465 return nullptr;
466 }
467
468 bool InstCMP::IsTHIS(const Instruction& i) {
469 return InstALU::IsTHIS(i) && InstALU::AsTHIS(i)->checkDest(r0) &&
470 InstALU::AsTHIS(i)->checkOp(OpCmp);
471 }
472
473 InstMOV* InstMOV::AsTHIS(const Instruction& i) {
474 if (IsTHIS(i)) {
475 return (InstMOV*)&i;
476 }
477 return nullptr;
478 }
479
480 bool InstMOV::IsTHIS(const Instruction& i) {
481 return InstALU::IsTHIS(i) && InstALU::AsTHIS(i)->checkOp1(r0) &&
482 InstALU::AsTHIS(i)->checkOp(OpMov);
483 }
484
485 Op2Reg Operand2::toOp2Reg() const { return *(Op2Reg*)this; }
486
487 Imm16::Imm16(Instruction& inst)
488 : lower_(inst.encode() & 0xfff),
489 upper_(inst.encode() >> 16),
490 invalid_(0xfff) {}
491
492 Imm16::Imm16(uint32_t imm)
493 : lower_(imm & 0xfff), pad_(0), upper_((imm >> 12) & 0xf), invalid_(0) {
494 MOZ_ASSERT(decode() == imm);
495 }
496
497 Imm16::Imm16() : invalid_(0xfff) {}
498
499 void Assembler::finish() {
500 flush();
501 MOZ_ASSERT(!isFinished);
502 isFinished = true;
503 }
504
505 bool Assembler::appendRawCode(const uint8_t* code, size_t numBytes) {
506 flush();
507 return m_buffer.appendRawCode(code, numBytes);
508 }
509
510 bool Assembler::reserve(size_t size) {
511 // This buffer uses fixed-size chunks so there's no point in reserving
512 // now vs. on-demand.
513 return !oom();
514 }
515
516 bool Assembler::swapBuffer(wasm::Bytes& bytes) {
517 // For now, specialize to the one use case. As long as wasm::Bytes is a
518 // Vector, not a linked-list of chunks, there's not much we can do other
519 // than copy.
520 MOZ_ASSERT(bytes.empty());
521 if (!bytes.resize(bytesNeeded())) {
522 return false;
523 }
524 m_buffer.executableCopy(bytes.begin());
525 return true;
526 }
527
528 void Assembler::executableCopy(uint8_t* buffer) {
529 MOZ_ASSERT(isFinished);
530 m_buffer.executableCopy(buffer);
531 }
532
533 class RelocationIterator {
534 CompactBufferReader reader_;
535 // Offset in bytes.
536 uint32_t offset_;
537
538 public:
539 explicit RelocationIterator(CompactBufferReader& reader) : reader_(reader) {}
540
541 bool read() {
542 if (!reader_.more()) {
543 return false;
544 }
545 offset_ = reader_.readUnsigned();
546 return true;
547 }
548
549 uint32_t offset() const { return offset_; }
550 };
551
552 template <class Iter>
553 const uint32_t* Assembler::GetCF32Target(Iter* iter) {
554 Instruction* inst1 = iter->cur();
555
556 if (inst1->is<InstBranchImm>()) {
557 // See if we have a simple case, b #offset.
558 BOffImm imm;
559 InstBranchImm* jumpB = inst1->as<InstBranchImm>();
560 jumpB->extractImm(&imm);
561 return imm.getDest(inst1)->raw();
562 }
563
564 if (inst1->is<InstMovW>()) {
565 // See if we have the complex case:
566 // movw r_temp, #imm1
567 // movt r_temp, #imm2
568 // bx r_temp
569 // OR
570 // movw r_temp, #imm1
571 // movt r_temp, #imm2
572 // str pc, [sp]
573 // bx r_temp
574
575 Imm16 targ_bot;
576 Imm16 targ_top;
577 Register temp;
578
579 // Extract both the temp register and the bottom immediate.
580 InstMovW* bottom = inst1->as<InstMovW>();
581 bottom->extractImm(&targ_bot);
582 bottom->extractDest(&temp);
583
584 // Extract the top part of the immediate.
585 Instruction* inst2 = iter->next();
586 MOZ_ASSERT(inst2->is<InstMovT>());
587 InstMovT* top = inst2->as<InstMovT>();
588 top->extractImm(&targ_top);
589
590 // Make sure they are being loaded into the same register.
591 MOZ_ASSERT(top->checkDest(temp));
592
593 // Make sure we're branching to the same register.
594 #ifdef DEBUG
595 // A toggled call sometimes has a NOP instead of a branch for the third
596 // instruction. No way to assert that it's valid in that situation.
597 Instruction* inst3 = iter->next();
598 if (!inst3->is<InstNOP>()) {
599 InstBranchReg* realBranch = nullptr;
600 if (inst3->is<InstBranchReg>()) {
601 realBranch = inst3->as<InstBranchReg>();
602 } else {
603 Instruction* inst4 = iter->next();
604 realBranch = inst4->as<InstBranchReg>();
605 }
606 MOZ_ASSERT(realBranch->checkDest(temp));
607 }
608 #endif
609
610 uint32_t* dest = (uint32_t*)(targ_bot.decode() | (targ_top.decode() << 16));
611 return dest;
612 }
613
614 if (inst1->is<InstLDR>()) {
615 return *(uint32_t**)inst1->as<InstLDR>()->dest();
616 }
617
618 MOZ_CRASH("unsupported branch relocation");
619 }
620
621 uintptr_t Assembler::GetPointer(uint8_t* instPtr) {
622 InstructionIterator iter((Instruction*)instPtr);
623 uintptr_t ret = (uintptr_t)GetPtr32Target(iter, nullptr, nullptr);
624 return ret;
625 }
626
627 template <class Iter>
628 const uint32_t* Assembler::GetPtr32Target(Iter iter, Register* dest,
629 RelocStyle* style) {
630 Instruction* load1 = iter.cur();
631 Instruction* load2 = iter.next();
632
633 if (load1->is<InstMovW>() && load2->is<InstMovT>()) {
634 if (style) {
635 *style = L_MOVWT;
636 }
637
638 // See if we have the complex case:
639 // movw r_temp, #imm1
640 // movt r_temp, #imm2
641
642 Imm16 targ_bot;
643 Imm16 targ_top;
644 Register temp;
645
646 // Extract both the temp register and the bottom immediate.
647 InstMovW* bottom = load1->as<InstMovW>();
648 bottom->extractImm(&targ_bot);
649 bottom->extractDest(&temp);
650
651 // Extract the top part of the immediate.
652 InstMovT* top = load2->as<InstMovT>();
653 top->extractImm(&targ_top);
654
655 // Make sure they are being loaded into the same register.
656 MOZ_ASSERT(top->checkDest(temp));
657
658 if (dest) {
659 *dest = temp;
660 }
661
662 uint32_t* value =
663 (uint32_t*)(targ_bot.decode() | (targ_top.decode() << 16));
664 return value;
665 }
666
667 if (load1->is<InstLDR>()) {
668 if (style) {
669 *style = L_LDR;
670 }
671 if (dest) {
672 *dest = toRD(*load1);
673 }
674 return *(uint32_t**)load1->as<InstLDR>()->dest();
675 }
676
677 MOZ_CRASH("unsupported relocation");
678 }
679
680 template const uint32_t* Assembler::GetPtr32Target<InstructionIterator>(
681 InstructionIterator iter, Register* dest, RelocStyle* style);
682 template const uint32_t* Assembler::GetPtr32Target<BufferInstructionIterator>(
683 BufferInstructionIterator iter, Register* dest, RelocStyle* style);
684
685 static JitCode* CodeFromJump(InstructionIterator* jump) {
686 uint8_t* target = (uint8_t*)Assembler::GetCF32Target(jump);
687 return JitCode::FromExecutable(target);
688 }
689
690 void Assembler::TraceJumpRelocations(JSTracer* trc, JitCode* code,
691 CompactBufferReader& reader) {
692 RelocationIterator iter(reader);
693 while (iter.read()) {
694 InstructionIterator institer((Instruction*)(code->raw() + iter.offset()));
695 JitCode* child = CodeFromJump(&institer);
696 TraceManuallyBarrieredEdge(trc, &child, "rel32");
697 }
698 }
699
700 static void TraceOneDataRelocation(JSTracer* trc,
701 mozilla::Maybe<AutoWritableJitCode>& awjc,
702 JitCode* code, InstructionIterator iter) {
703 Register dest;
704 Assembler::RelocStyle rs;
705 const void* prior = Assembler::GetPtr32Target(iter, &dest, &rs);
706 void* ptr = const_cast<void*>(prior);
707
708 // No barrier needed since these are constants.
709 TraceManuallyBarrieredGenericPointerEdge(
710 trc, reinterpret_cast<gc::Cell**>(&ptr), "jit-masm-ptr");
711
712 if (ptr != prior) {
713 if (awjc.isNothing()) {
714 awjc.emplace(code);
715 }
716
717 MacroAssemblerARM::ma_mov_patch(Imm32(int32_t(ptr)), dest,
718 Assembler::Always, rs, iter);
719 }
720 }
721
722 /* static */
723 void Assembler::TraceDataRelocations(JSTracer* trc, JitCode* code,
724 CompactBufferReader& reader) {
725 mozilla::Maybe<AutoWritableJitCode> awjc;
726 while (reader.more()) {
727 size_t offset = reader.readUnsigned();
728 InstructionIterator iter((Instruction*)(code->raw() + offset));
729 TraceOneDataRelocation(trc, awjc, code, iter);
730 }
731 }
732
733 void Assembler::copyJumpRelocationTable(uint8_t* dest) {
734 if (jumpRelocations_.length()) {
735 memcpy(dest, jumpRelocations_.buffer(), jumpRelocations_.length());
736 }
737 }
738
739 void Assembler::copyDataRelocationTable(uint8_t* dest) {
740 if (dataRelocations_.length()) {
741 memcpy(dest, dataRelocations_.buffer(), dataRelocations_.length());
742 }
743 }
744
745 void Assembler::processCodeLabels(uint8_t* rawCode) {
746 for (const CodeLabel& label : codeLabels_) {
747 Bind(rawCode, label);
748 }
749 }
750
751 void Assembler::writeCodePointer(CodeLabel* label) {
752 m_buffer.assertNoPoolAndNoNops();
753 BufferOffset off = writeInst(-1);
754 label->patchAt()->bind(off.getOffset());
755 }
756
757 void Assembler::Bind(uint8_t* rawCode, const CodeLabel& label) {
758 auto mode = label.linkMode();
759 size_t offset = label.patchAt().offset();
760 size_t target = label.target().offset();
761
762 if (mode == CodeLabel::MoveImmediate) {
763 uint32_t imm = uint32_t(rawCode + target);
764 Instruction* inst = (Instruction*)(rawCode + offset);
765 if (ARMFlags::HasMOVWT()) {
766 Assembler::PatchMovwt(inst, imm);
767 } else {
768 Assembler::WritePoolEntry(inst, Always, imm);
769 }
770 } else {
771 *reinterpret_cast<const void**>(rawCode + offset) = rawCode + target;
772 }
773 }
774
775 Assembler::Condition Assembler::InvertCondition(Condition cond) {
776 const uint32_t ConditionInversionBit = 0x10000000;
777 return Condition(ConditionInversionBit ^ cond);
778 }
779
780 Assembler::Condition Assembler::UnsignedCondition(Condition cond) {
781 switch (cond) {
782 case Zero:
783 case NonZero:
784 return cond;
785 case LessThan:
786 case Below:
787 return Below;
788 case LessThanOrEqual:
789 case BelowOrEqual:
790 return BelowOrEqual;
791 case GreaterThan:
792 case Above:
793 return Above;
794 case AboveOrEqual:
795 case GreaterThanOrEqual:
796 return AboveOrEqual;
797 default:
798 MOZ_CRASH("unexpected condition");
799 }
800 }
801
802 Assembler::Condition Assembler::ConditionWithoutEqual(Condition cond) {
803 switch (cond) {
804 case LessThan:
805 case LessThanOrEqual:
806 return LessThan;
807 case Below:
808 case BelowOrEqual:
809 return Below;
810 case GreaterThan:
811 case GreaterThanOrEqual:
812 return GreaterThan;
813 case Above:
814 case AboveOrEqual:
815 return Above;
816 default:
817 MOZ_CRASH("unexpected condition");
818 }
819 }
820
821 Assembler::DoubleCondition Assembler::InvertCondition(DoubleCondition cond) {
822 const uint32_t ConditionInversionBit = 0x10000000;
823 return DoubleCondition(ConditionInversionBit ^ cond);
824 }
825
826 Imm8::TwoImm8mData Imm8::EncodeTwoImms(uint32_t imm) {
827 // In the ideal case, we are looking for a number that (in binary) looks
828 // like:
829 // 0b((00)*)n_1((00)*)n_2((00)*)
830 // left n1 mid n2
831 // where both n_1 and n_2 fit into 8 bits.
832 // Since this is being done with rotates, we also need to handle the case
833 // that one of these numbers is in fact split between the left and right
834 // sides, in which case the constant will look like:
835 // 0bn_1a((00)*)n_2((00)*)n_1b
836 // n1a mid n2 rgh n1b
837 // Also remember, values are rotated by multiples of two, and left, mid or
838 // right can have length zero.
839 uint32_t imm1, imm2;
840 int left = CountLeadingZeroes32(imm) & 0x1E;
841 uint32_t no_n1 = imm & ~(0xff << (24 - left));
842
843 // Not technically needed: this case only happens if we can encode as a
844 // single imm8m. There is a perfectly reasonable encoding in this case, but
845 // we shouldn't encourage people to do things like this.
846 if (no_n1 == 0) {
847 return TwoImm8mData();
848 }
849
850 int mid = CountLeadingZeroes32(no_n1) & 0x1E;
851 uint32_t no_n2 =
852 no_n1 & ~((0xff << ((24 - mid) & 0x1f)) | 0xff >> ((8 + mid) & 0x1f));
853
854 if (no_n2 == 0) {
855 // We hit the easy case, no wraparound.
856 // Note: a single constant *may* look like this.
857 int imm1shift = left + 8;
858 int imm2shift = mid + 8;
859 imm1 = (imm >> (32 - imm1shift)) & 0xff;
860 if (imm2shift >= 32) {
861 imm2shift = 0;
862 // This assert does not always hold, in fact, this would lead to
863 // some incredibly subtle bugs.
864 // assert((imm & 0xff) == no_n1);
865 imm2 = no_n1;
866 } else {
867 imm2 = ((imm >> (32 - imm2shift)) | (imm << imm2shift)) & 0xff;
868 MOZ_ASSERT(((no_n1 >> (32 - imm2shift)) | (no_n1 << imm2shift)) == imm2);
869 }
870 MOZ_ASSERT((imm1shift & 0x1) == 0);
871 MOZ_ASSERT((imm2shift & 0x1) == 0);
872 return TwoImm8mData(datastore::Imm8mData(imm1, imm1shift >> 1),
873 datastore::Imm8mData(imm2, imm2shift >> 1));
874 }
875
876 // Either it wraps, or it does not fit. If we initially chopped off more
877 // than 8 bits, then it won't fit.
878 if (left >= 8) {
879 return TwoImm8mData();
880 }
881
882 int right = 32 - (CountLeadingZeroes32(no_n2) & 30);
883 // All remaining set bits *must* fit into the lower 8 bits.
884 // The right == 8 case should be handled by the previous case.
885 if (right > 8) {
886 return TwoImm8mData();
887 }
888
889 // Make sure the initial bits that we removed for no_n1 fit into the
890 // 8-(32-right) leftmost bits.
891 if (((imm & (0xff << (24 - left))) << (8 - right)) != 0) {
892 // BUT we may have removed more bits than we needed to for no_n1
893 // 0x04104001 e.g. we can encode 0x104 with a single op, then 0x04000001
894 // with a second, but we try to encode 0x0410000 and find that we need a
895 // second op for 0x4000, and 0x1 cannot be included in the encoding of
896 // 0x04100000.
897 no_n1 = imm & ~((0xff >> (8 - right)) | (0xff << (24 + right)));
898 mid = CountLeadingZeroes32(no_n1) & 30;
899 no_n2 = no_n1 & ~((0xff << ((24 - mid) & 31)) | 0xff >> ((8 + mid) & 31));
900 if (no_n2 != 0) {
901 return TwoImm8mData();
902 }
903 }
904
905 // Now assemble all of this information into a two coherent constants it is
906 // a rotate right from the lower 8 bits.
907 int imm1shift = 8 - right;
908 imm1 = 0xff & ((imm << imm1shift) | (imm >> (32 - imm1shift)));
909 MOZ_ASSERT((imm1shift & ~0x1e) == 0);
910 // left + 8 + mid is the position of the leftmost bit of n_2.
911 // We needed to rotate 0x000000ab right by 8 in order to get 0xab000000,
912 // then shift again by the leftmost bit in order to get the constant that we
913 // care about.
914 int imm2shift = mid + 8;
915 imm2 = ((imm >> (32 - imm2shift)) | (imm << imm2shift)) & 0xff;
916 MOZ_ASSERT((imm1shift & 0x1) == 0);
917 MOZ_ASSERT((imm2shift & 0x1) == 0);
918 return TwoImm8mData(datastore::Imm8mData(imm1, imm1shift >> 1),
919 datastore::Imm8mData(imm2, imm2shift >> 1));
920 }
921
922 ALUOp jit::ALUNeg(ALUOp op, Register dest, Register scratch, Imm32* imm,
923 Register* negDest) {
924 // Find an alternate ALUOp to get the job done, and use a different imm.
925 *negDest = dest;
926 switch (op) {
927 case OpMov:
928 *imm = Imm32(~imm->value);
929 return OpMvn;
930 case OpMvn:
931 *imm = Imm32(~imm->value);
932 return OpMov;
933 case OpAnd:
934 *imm = Imm32(~imm->value);
935 return OpBic;
936 case OpBic:
937 *imm = Imm32(~imm->value);
938 return OpAnd;
939 case OpAdd:
940 *imm = Imm32(-imm->value);
941 return OpSub;
942 case OpSub:
943 *imm = Imm32(-imm->value);
944 return OpAdd;
945 case OpCmp:
946 *imm = Imm32(-imm->value);
947 return OpCmn;
948 case OpCmn:
949 *imm = Imm32(-imm->value);
950 return OpCmp;
951 case OpTst:
952 MOZ_ASSERT(dest == InvalidReg);
953 *imm = Imm32(~imm->value);
954 *negDest = scratch;
955 return OpBic;
956 // orr has orn on thumb2 only.
957 default:
958 return OpInvalid;
959 }
960 }
961
962 bool jit::can_dbl(ALUOp op) {
963 // Some instructions can't be processed as two separate instructions such as
964 // and, and possibly add (when we're setting ccodes). There is also some
965 // hilarity with *reading* condition codes. For example, adc dest, src1,
966 // 0xfff; (add with carry) can be split up into adc dest, src1, 0xf00; add
967 // dest, dest, 0xff, since "reading" the condition code increments the
968 // result by one conditionally, that only needs to be done on one of the two
969 // instructions.
970 switch (op) {
971 case OpBic:
972 case OpAdd:
973 case OpSub:
974 case OpEor:
975 case OpOrr:
976 return true;
977 default:
978 return false;
979 }
980 }
981
982 bool jit::condsAreSafe(ALUOp op) {
983 // Even when we are setting condition codes, sometimes we can get away with
984 // splitting an operation into two. For example, if our immediate is
985 // 0x00ff00ff, and the operation is eors we can split this in half, since x
986 // ^ 0x00ff0000 ^ 0x000000ff should set all of its condition codes exactly
987 // the same as x ^ 0x00ff00ff. However, if the operation were adds, we
988 // cannot split this in half. If the source on the add is 0xfff00ff0, the
989 // result sholud be 0xef10ef, but do we set the overflow bit or not?
990 // Depending on which half is performed first (0x00ff0000 or 0x000000ff) the
991 // V bit will be set differently, and *not* updating the V bit would be
992 // wrong. Theoretically, the following should work:
993 // adds r0, r1, 0x00ff0000;
994 // addsvs r0, r1, 0x000000ff;
995 // addvc r0, r1, 0x000000ff;
996 // But this is 3 instructions, and at that point, we might as well use
997 // something else.
998 switch (op) {
999 case OpBic:
1000 case OpOrr:
1001 case OpEor:
1002 return true;
1003 default:
1004 return false;
1005 }
1006 }
1007
1008 ALUOp jit::getDestVariant(ALUOp op) {
1009 // All of the compare operations are dest-less variants of a standard
1010 // operation. Given the dest-less variant, return the dest-ful variant.
1011 switch (op) {
1012 case OpCmp:
1013 return OpSub;
1014 case OpCmn:
1015 return OpAdd;
1016 case OpTst:
1017 return OpAnd;
1018 case OpTeq:
1019 return OpEor;
1020 default:
1021 return op;
1022 }
1023 }
1024
1025 O2RegImmShift jit::O2Reg(Register r) { return O2RegImmShift(r, LSL, 0); }
1026
1027 O2RegImmShift jit::lsl(Register r, int amt) {
1028 MOZ_ASSERT(0 <= amt && amt <= 31);
1029 return O2RegImmShift(r, LSL, amt);
1030 }
1031
1032 O2RegImmShift jit::lsr(Register r, int amt) {
1033 MOZ_ASSERT(1 <= amt && amt <= 32);
1034 return O2RegImmShift(r, LSR, amt);
1035 }
1036
1037 O2RegImmShift jit::ror(Register r, int amt) {
1038 MOZ_ASSERT(1 <= amt && amt <= 31);
1039 return O2RegImmShift(r, ROR, amt);
1040 }
1041 O2RegImmShift jit::rol(Register r, int amt) {
1042 MOZ_ASSERT(1 <= amt && amt <= 31);
1043 return O2RegImmShift(r, ROR, 32 - amt);
1044 }
1045
1046 O2RegImmShift jit::asr(Register r, int amt) {
1047 MOZ_ASSERT(1 <= amt && amt <= 32);
1048 return O2RegImmShift(r, ASR, amt);
1049 }
1050
1051 O2RegRegShift jit::lsl(Register r, Register amt) {
1052 return O2RegRegShift(r, LSL, amt);
1053 }
1054
1055 O2RegRegShift jit::lsr(Register r, Register amt) {
1056 return O2RegRegShift(r, LSR, amt);
1057 }
1058
1059 O2RegRegShift jit::ror(Register r, Register amt) {
1060 return O2RegRegShift(r, ROR, amt);
1061 }
1062
1063 O2RegRegShift jit::asr(Register r, Register amt) {
1064 return O2RegRegShift(r, ASR, amt);
1065 }
1066
1067 static js::jit::DoubleEncoder doubleEncoder;
1068
1069 /* static */
1070 MOZ_RUNINIT const js::jit::VFPImm js::jit::VFPImm::One(0x3FF00000);
1071
1072 js::jit::VFPImm::VFPImm(uint32_t top) {
1073 data_ = -1;
1074 datastore::Imm8VFPImmData tmp;
1075 if (doubleEncoder.lookup(top, &tmp)) {
1076 data_ = tmp.encode();
1077 }
1078 }
1079
1080 BOffImm::BOffImm(const Instruction& inst) : data_(inst.encode() & 0x00ffffff) {}
1081
1082 Instruction* BOffImm::getDest(Instruction* src) const {
1083 // TODO: It is probably worthwhile to verify that src is actually a branch.
1084 // NOTE: This does not explicitly shift the offset of the destination left by
1085 // 2, since it is indexing into an array of instruction sized objects.
1086 return &src[((int32_t(data_) << 8) >> 8) + 2];
1087 }
1088
1089 const js::jit::DoubleEncoder::DoubleEntry js::jit::DoubleEncoder::table[256] = {
1090 #include "jit/arm/DoubleEntryTable.tbl"
1091 };
1092
1093 // VFPRegister implementation
1094 VFPRegister VFPRegister::doubleOverlay(unsigned int which) const {
1095 MOZ_ASSERT(!_isInvalid);
1096 MOZ_ASSERT(which == 0);
1097 if (kind != Double) {
1098 return VFPRegister(code_ >> 1, Double);
1099 }
1100 return *this;
1101 }
1102 VFPRegister VFPRegister::singleOverlay(unsigned int which) const {
1103 MOZ_ASSERT(!_isInvalid);
1104 if (kind == Double) {
1105 // There are no corresponding float registers for d16-d31.
1106 MOZ_ASSERT(code_ < 16);
1107 MOZ_ASSERT(which < 2);
1108 return VFPRegister((code_ << 1) + which, Single);
1109 }
1110 MOZ_ASSERT(which == 0);
1111 return VFPRegister(code_, Single);
1112 }
1113
1114 static_assert(
1115 FloatRegisters::TotalDouble <= 16,
1116 "We assume that every Double register also has an Integer personality");
1117
1118 VFPRegister VFPRegister::sintOverlay(unsigned int which) const {
1119 MOZ_ASSERT(!_isInvalid);
1120 if (kind == Double) {
1121 // There are no corresponding float registers for d16-d31.
1122 MOZ_ASSERT(code_ < 16);
1123 MOZ_ASSERT(which < 2);
1124 return VFPRegister((code_ << 1) + which, Int);
1125 }
1126 MOZ_ASSERT(which == 0);
1127 return VFPRegister(code_, Int);
1128 }
1129 VFPRegister VFPRegister::uintOverlay(unsigned int which) const {
1130 MOZ_ASSERT(!_isInvalid);
1131 if (kind == Double) {
1132 // There are no corresponding float registers for d16-d31.
1133 MOZ_ASSERT(code_ < 16);
1134 MOZ_ASSERT(which < 2);
1135 return VFPRegister((code_ << 1) + which, UInt);
1136 }
1137 MOZ_ASSERT(which == 0);
1138 return VFPRegister(code_, UInt);
1139 }
1140
1141 bool Assembler::oom() const {
1142 return AssemblerShared::oom() || m_buffer.oom() || jumpRelocations_.oom() ||
1143 dataRelocations_.oom();
1144 }
1145
1146 // Size of the instruction stream, in bytes. Including pools. This function
1147 // expects all pools that need to be placed have been placed. If they haven't
1148 // then we need to go an flush the pools :(
1149 size_t Assembler::size() const { return m_buffer.size(); }
1150 // Size of the relocation table, in bytes.
1151 size_t Assembler::jumpRelocationTableBytes() const {
1152 return jumpRelocations_.length();
1153 }
1154 size_t Assembler::dataRelocationTableBytes() const {
1155 return dataRelocations_.length();
1156 }
1157
1158 // Size of the data table, in bytes.
1159 size_t Assembler::bytesNeeded() const {
1160 return size() + jumpRelocationTableBytes() + dataRelocationTableBytes();
1161 }
1162
1163 // Allocate memory for a branch instruction, it will be overwritten
1164 // subsequently and should not be disassembled.
1165
1166 BufferOffset Assembler::allocBranchInst() {
1167 return m_buffer.putInt(Always | InstNOP::NopInst);
1168 }
1169
1170 void Assembler::WriteInstStatic(uint32_t x, uint32_t* dest) {
1171 MOZ_ASSERT(dest != nullptr);
1172 *dest = x;
1173 }
1174
1175 void Assembler::haltingAlign(int alignment) {
1176 // HLT with payload 0xBAAD
1177 m_buffer.align(alignment, 0xE1000070 | (0xBAA << 8) | 0xD);
1178 }
1179
1180 void Assembler::nopAlign(int alignment) { m_buffer.align(alignment); }
1181
1182 BufferOffset Assembler::as_nop() { return writeInst(0xe320f000); }
1183
1184 static uint32_t EncodeAlu(Register dest, Register src1, Operand2 op2, ALUOp op,
1185 SBit s, Assembler::Condition c) {
1186 return (int)op | (int)s | (int)c | op2.encode() |
1187 ((dest == InvalidReg) ? 0 : RD(dest)) |
1188 ((src1 == InvalidReg) ? 0 : RN(src1));
1189 }
1190
1191 BufferOffset Assembler::as_alu(Register dest, Register src1, Operand2 op2,
1192 ALUOp op, SBit s, Condition c) {
1193 return writeInst(EncodeAlu(dest, src1, op2, op, s, c));
1194 }
1195
1196 BufferOffset Assembler::as_mov(Register dest, Operand2 op2, SBit s,
1197 Condition c) {
1198 return as_alu(dest, InvalidReg, op2, OpMov, s, c);
1199 }
1200
1201 /* static */
1202 void Assembler::as_alu_patch(Register dest, Register src1, Operand2 op2,
1203 ALUOp op, SBit s, Condition c, uint32_t* pos) {
1204 WriteInstStatic(EncodeAlu(dest, src1, op2, op, s, c), pos);
1205 }
1206
1207 /* static */
1208 void Assembler::as_mov_patch(Register dest, Operand2 op2, SBit s, Condition c,
1209 uint32_t* pos) {
1210 as_alu_patch(dest, InvalidReg, op2, OpMov, s, c, pos);
1211 }
1212
1213 BufferOffset Assembler::as_mvn(Register dest, Operand2 op2, SBit s,
1214 Condition c) {
1215 return as_alu(dest, InvalidReg, op2, OpMvn, s, c);
1216 }
1217
1218 // Logical operations.
1219 BufferOffset Assembler::as_and(Register dest, Register src1, Operand2 op2,
1220 SBit s, Condition c) {
1221 return as_alu(dest, src1, op2, OpAnd, s, c);
1222 }
1223 BufferOffset Assembler::as_bic(Register dest, Register src1, Operand2 op2,
1224 SBit s, Condition c) {
1225 return as_alu(dest, src1, op2, OpBic, s, c);
1226 }
1227 BufferOffset Assembler::as_eor(Register dest, Register src1, Operand2 op2,
1228 SBit s, Condition c) {
1229 return as_alu(dest, src1, op2, OpEor, s, c);
1230 }
1231 BufferOffset Assembler::as_orr(Register dest, Register src1, Operand2 op2,
1232 SBit s, Condition c) {
1233 return as_alu(dest, src1, op2, OpOrr, s, c);
1234 }
1235
1236 // Reverse byte operations.
1237 BufferOffset Assembler::as_rev(Register dest, Register src, Condition c) {
1238 return writeInst((int)c | 0b0000'0110'1011'1111'0000'1111'0011'0000 |
1239 RD(dest) | src.code());
1240 }
1241 BufferOffset Assembler::as_rev16(Register dest, Register src, Condition c) {
1242 return writeInst((int)c | 0b0000'0110'1011'1111'0000'1111'1011'0000 |
1243 RD(dest) | src.code());
1244 }
1245 BufferOffset Assembler::as_revsh(Register dest, Register src, Condition c) {
1246 return writeInst((int)c | 0b0000'0110'1111'1111'0000'1111'1011'0000 |
1247 RD(dest) | src.code());
1248 }
1249
1250 // Mathematical operations.
1251 BufferOffset Assembler::as_adc(Register dest, Register src1, Operand2 op2,
1252 SBit s, Condition c) {
1253 return as_alu(dest, src1, op2, OpAdc, s, c);
1254 }
1255 BufferOffset Assembler::as_add(Register dest, Register src1, Operand2 op2,
1256 SBit s, Condition c) {
1257 return as_alu(dest, src1, op2, OpAdd, s, c);
1258 }
1259 BufferOffset Assembler::as_sbc(Register dest, Register src1, Operand2 op2,
1260 SBit s, Condition c) {
1261 return as_alu(dest, src1, op2, OpSbc, s, c);
1262 }
1263 BufferOffset Assembler::as_sub(Register dest, Register src1, Operand2 op2,
1264 SBit s, Condition c) {
1265 return as_alu(dest, src1, op2, OpSub, s, c);
1266 }
1267 BufferOffset Assembler::as_rsb(Register dest, Register src1, Operand2 op2,
1268 SBit s, Condition c) {
1269 return as_alu(dest, src1, op2, OpRsb, s, c);
1270 }
1271 BufferOffset Assembler::as_rsc(Register dest, Register src1, Operand2 op2,
1272 SBit s, Condition c) {
1273 return as_alu(dest, src1, op2, OpRsc, s, c);
1274 }
1275
1276 // Test operations.
1277 BufferOffset Assembler::as_cmn(Register src1, Operand2 op2, Condition c) {
1278 return as_alu(InvalidReg, src1, op2, OpCmn, SetCC, c);
1279 }
1280 BufferOffset Assembler::as_cmp(Register src1, Operand2 op2, Condition c) {
1281 return as_alu(InvalidReg, src1, op2, OpCmp, SetCC, c);
1282 }
1283 BufferOffset Assembler::as_teq(Register src1, Operand2 op2, Condition c) {
1284 return as_alu(InvalidReg, src1, op2, OpTeq, SetCC, c);
1285 }
1286 BufferOffset Assembler::as_tst(Register src1, Operand2 op2, Condition c) {
1287 return as_alu(InvalidReg, src1, op2, OpTst, SetCC, c);
1288 }
1289
1290 static constexpr Register NoAddend{Registers::pc};
1291
1292 static const int SignExtend = 0x06000070;
1293
1294 enum SignExtend {
1295 SxSxtb = 10 << 20,
1296 SxSxth = 11 << 20,
1297 SxUxtb = 14 << 20,
1298 SxUxth = 15 << 20
1299 };
1300
1301 // Sign extension operations.
1302 BufferOffset Assembler::as_sxtb(Register dest, Register src, int rotate,
1303 Condition c) {
1304 return writeInst((int)c | SignExtend | SxSxtb | RN(NoAddend) | RD(dest) |
1305 ((rotate & 3) << 10) | src.code());
1306 }
1307 BufferOffset Assembler::as_sxth(Register dest, Register src, int rotate,
1308 Condition c) {
1309 return writeInst((int)c | SignExtend | SxSxth | RN(NoAddend) | RD(dest) |
1310 ((rotate & 3) << 10) | src.code());
1311 }
1312 BufferOffset Assembler::as_uxtb(Register dest, Register src, int rotate,
1313 Condition c) {
1314 return writeInst((int)c | SignExtend | SxUxtb | RN(NoAddend) | RD(dest) |
1315 ((rotate & 3) << 10) | src.code());
1316 }
1317 BufferOffset Assembler::as_uxth(Register dest, Register src, int rotate,
1318 Condition c) {
1319 return writeInst((int)c | SignExtend | SxUxth | RN(NoAddend) | RD(dest) |
1320 ((rotate & 3) << 10) | src.code());
1321 }
1322
1323 static uint32_t EncodeMovW(Register dest, Imm16 imm, Assembler::Condition c) {
1324 MOZ_ASSERT(ARMFlags::HasMOVWT());
1325 return 0x03000000 | c | imm.encode() | RD(dest);
1326 }
1327
1328 static uint32_t EncodeMovT(Register dest, Imm16 imm, Assembler::Condition c) {
1329 MOZ_ASSERT(ARMFlags::HasMOVWT());
1330 return 0x03400000 | c | imm.encode() | RD(dest);
1331 }
1332
1333 // Not quite ALU worthy, but these are useful none the less. These also have
1334 // the isue of these being formatted completly differently from the standard ALU
1335 // operations.
1336 BufferOffset Assembler::as_movw(Register dest, Imm16 imm, Condition c) {
1337 return writeInst(EncodeMovW(dest, imm, c));
1338 }
1339
1340 /* static */
1341 void Assembler::as_movw_patch(Register dest, Imm16 imm, Condition c,
1342 Instruction* pos) {
1343 WriteInstStatic(EncodeMovW(dest, imm, c), (uint32_t*)pos);
1344 }
1345
1346 BufferOffset Assembler::as_movt(Register dest, Imm16 imm, Condition c) {
1347 return writeInst(EncodeMovT(dest, imm, c));
1348 }
1349
1350 /* static */
1351 void Assembler::as_movt_patch(Register dest, Imm16 imm, Condition c,
1352 Instruction* pos) {
1353 WriteInstStatic(EncodeMovT(dest, imm, c), (uint32_t*)pos);
1354 }
1355
1356 void Assembler::PatchMovwt(Instruction* addr, uint32_t imm) {
1357 InstructionIterator iter(addr);
1358 Instruction* movw = iter.cur();
1359 MOZ_ASSERT(movw->is<InstMovW>());
1360 Instruction* movt = iter.next();
1361 MOZ_ASSERT(movt->is<InstMovT>());
1362
1363 Register dest = toRD(*movw);
1364 Condition c = movw->extractCond();
1365 MOZ_ASSERT(toRD(*movt) == dest && movt->extractCond() == c);
1366
1367 Assembler::WriteInstStatic(EncodeMovW(dest, Imm16(imm & 0xffff), c),
1368 (uint32_t*)movw);
1369 Assembler::WriteInstStatic(EncodeMovT(dest, Imm16(imm >> 16 & 0xffff), c),
1370 (uint32_t*)movt);
1371 }
1372
1373 static const int mull_tag = 0x90;
1374
1375 BufferOffset Assembler::as_genmul(Register dhi, Register dlo, Register rm,
1376 Register rn, MULOp op, SBit s, Condition c) {
1377 return writeInst(RN(dhi) | maybeRD(dlo) | RM(rm) | rn.code() | op | s | c |
1378 mull_tag);
1379 }
1380 BufferOffset Assembler::as_mul(Register dest, Register src1, Register src2,
1381 SBit s, Condition c) {
1382 return as_genmul(dest, InvalidReg, src1, src2, OpmMul, s, c);
1383 }
1384 BufferOffset Assembler::as_mla(Register dest, Register acc, Register src1,
1385 Register src2, SBit s, Condition c) {
1386 return as_genmul(dest, acc, src1, src2, OpmMla, s, c);
1387 }
1388 BufferOffset Assembler::as_umaal(Register destHI, Register destLO,
1389 Register src1, Register src2, Condition c) {
1390 return as_genmul(destHI, destLO, src1, src2, OpmUmaal, LeaveCC, c);
1391 }
1392 BufferOffset Assembler::as_mls(Register dest, Register acc, Register src1,
1393 Register src2, Condition c) {
1394 return as_genmul(dest, acc, src1, src2, OpmMls, LeaveCC, c);
1395 }
1396
1397 BufferOffset Assembler::as_umull(Register destHI, Register destLO,
1398 Register src1, Register src2, SBit s,
1399 Condition c) {
1400 return as_genmul(destHI, destLO, src1, src2, OpmUmull, s, c);
1401 }
1402
1403 BufferOffset Assembler::as_umlal(Register destHI, Register destLO,
1404 Register src1, Register src2, SBit s,
1405 Condition c) {
1406 return as_genmul(destHI, destLO, src1, src2, OpmUmlal, s, c);
1407 }
1408
1409 BufferOffset Assembler::as_smull(Register destHI, Register destLO,
1410 Register src1, Register src2, SBit s,
1411 Condition c) {
1412 return as_genmul(destHI, destLO, src1, src2, OpmSmull, s, c);
1413 }
1414
1415 BufferOffset Assembler::as_smlal(Register destHI, Register destLO,
1416 Register src1, Register src2, SBit s,
1417 Condition c) {
1418 return as_genmul(destHI, destLO, src1, src2, OpmSmlal, s, c);
1419 }
1420
1421 BufferOffset Assembler::as_sdiv(Register rd, Register rn, Register rm,
1422 Condition c) {
1423 return writeInst(0x0710f010 | c | RN(rd) | RM(rm) | rn.code());
1424 }
1425
1426 BufferOffset Assembler::as_udiv(Register rd, Register rn, Register rm,
1427 Condition c) {
1428 return writeInst(0x0730f010 | c | RN(rd) | RM(rm) | rn.code());
1429 }
1430
1431 BufferOffset Assembler::as_clz(Register dest, Register src, Condition c) {
1432 MOZ_ASSERT(src != pc && dest != pc);
1433 return writeInst(RD(dest) | src.code() | c | 0x016f0f10);
1434 }
1435
1436 // Data transfer instructions: ldr, str, ldrb, strb. Using an int to
1437 // differentiate between 8 bits and 32 bits is overkill, but meh.
1438
1439 static uint32_t EncodeDtr(LoadStore ls, int size, Index mode, Register rt,
1440 DTRAddr addr, Assembler::Condition c) {
1441 MOZ_ASSERT(mode == Offset || (rt != addr.getBase() && pc != addr.getBase()));
1442 MOZ_ASSERT(size == 32 || size == 8);
1443 return 0x04000000 | ls | (size == 8 ? 0x00400000 : 0) | mode | c | RT(rt) |
1444 addr.encode();
1445 }
1446
1447 BufferOffset Assembler::as_dtr(LoadStore ls, int size, Index mode, Register rt,
1448 DTRAddr addr, Condition c) {
1449 return writeInst(EncodeDtr(ls, size, mode, rt, addr, c));
1450 }
1451
1452 /* static */
1453 void Assembler::as_dtr_patch(LoadStore ls, int size, Index mode, Register rt,
1454 DTRAddr addr, Condition c, uint32_t* dest) {
1455 WriteInstStatic(EncodeDtr(ls, size, mode, rt, addr, c), dest);
1456 }
1457
1458 class PoolHintData {
1459 public:
1460 enum LoadType {
1461 // Set 0 to bogus, since that is the value most likely to be
1462 // accidentally left somewhere.
1463 PoolBOGUS = 0,
1464 PoolDTR = 1,
1465 PoolBranch = 2,
1466 PoolVDTR = 3
1467 };
1468
1469 private:
1470 uint32_t index_ : 16;
1471 uint32_t cond_ : 4;
1472 uint32_t loadType_ : 2;
1473 uint32_t destReg_ : 5;
1474 uint32_t destType_ : 1;
1475 uint32_t ONES : 4;
1476
1477 static const uint32_t ExpectedOnes = 0xfu;
1478
1479 public:
1480 void init(uint32_t index, Assembler::Condition cond, LoadType lt,
1481 Register destReg) {
1482 index_ = index;
1483 MOZ_ASSERT(index_ == index);
1484 cond_ = cond >> 28;
1485 MOZ_ASSERT(cond_ == cond >> 28);
1486 loadType_ = lt;
1487 ONES = ExpectedOnes;
1488 destReg_ = destReg.code();
1489 destType_ = 0;
1490 }
1491 void init(uint32_t index, Assembler::Condition cond, LoadType lt,
1492 const VFPRegister& destReg) {
1493 MOZ_ASSERT(destReg.isFloat());
1494 index_ = index;
1495 MOZ_ASSERT(index_ == index);
1496 cond_ = cond >> 28;
1497 MOZ_ASSERT(cond_ == cond >> 28);
1498 loadType_ = lt;
1499 ONES = ExpectedOnes;
1500 destReg_ = destReg.id();
1501 destType_ = destReg.isDouble();
1502 }
1503 Assembler::Condition getCond() const {
1504 return Assembler::Condition(cond_ << 28);
1505 }
1506
1507 Register getReg() const { return Register::FromCode(destReg_); }
1508 VFPRegister getVFPReg() const {
1509 VFPRegister r = VFPRegister(
1510 destReg_, destType_ ? VFPRegister::Double : VFPRegister::Single);
1511 return r;
1512 }
1513
1514 int32_t getIndex() const { return index_; }
1515 void setIndex(uint32_t index) {
1516 MOZ_ASSERT(ONES == ExpectedOnes && loadType_ != PoolBOGUS);
1517 index_ = index;
1518 MOZ_ASSERT(index_ == index);
1519 }
1520
1521 LoadType getLoadType() const {
1522 // If this *was* a PoolBranch, but the branch has already been bound
1523 // then this isn't going to look like a real poolhintdata, but we still
1524 // want to lie about it so everyone knows it *used* to be a branch.
1525 if (ONES != ExpectedOnes) {
1526 return PoolHintData::PoolBranch;
1527 }
1528 return static_cast<LoadType>(loadType_);
1529 }
1530
1531 bool isValidPoolHint() const {
1532 // Most instructions cannot have a condition that is 0xf. Notable
1533 // exceptions are blx and the entire NEON instruction set. For the
1534 // purposes of pool loads, and possibly patched branches, the possible
1535 // instructions are ldr and b, neither of which can have a condition
1536 // code of 0xf.
1537 return ONES == ExpectedOnes;
1538 }
1539 };
1540
1541 union PoolHintPun {
1542 PoolHintData phd;
1543 uint32_t raw;
1544 };
1545
1546 // Handles all of the other integral data transferring functions: ldrsb, ldrsh,
1547 // ldrd, etc. The size is given in bits.
1548 BufferOffset Assembler::as_extdtr(LoadStore ls, int size, bool IsSigned,
1549 Index mode, Register rt, EDtrAddr addr,
1550 Condition c) {
1551 int extra_bits2 = 0;
1552 int extra_bits1 = 0;
1553 switch (size) {
1554 case 8:
1555 MOZ_ASSERT(IsSigned);
1556 MOZ_ASSERT(ls != IsStore);
1557 extra_bits1 = 0x1;
1558 extra_bits2 = 0x2;
1559 break;
1560 case 16:
1561 // 'case 32' doesn't need to be handled, it is handled by the default
1562 // ldr/str.
1563 extra_bits2 = 0x01;
1564 extra_bits1 = (ls == IsStore) ? 0 : 1;
1565 if (IsSigned) {
1566 MOZ_ASSERT(ls != IsStore);
1567 extra_bits2 |= 0x2;
1568 }
1569 break;
1570 case 64:
1571 extra_bits2 = (ls == IsStore) ? 0x3 : 0x2;
1572 extra_bits1 = 0;
1573 break;
1574 default:
1575 MOZ_CRASH("unexpected size in as_extdtr");
1576 }
1577 return writeInst(extra_bits2 << 5 | extra_bits1 << 20 | 0x90 | addr.encode() |
1578 RT(rt) | mode | c);
1579 }
1580
1581 BufferOffset Assembler::as_dtm(LoadStore ls, Register rn, uint32_t mask,
1582 DTMMode mode, DTMWriteBack wb, Condition c) {
1583 return writeInst(0x08000000 | RN(rn) | ls | mode | mask | c | wb);
1584 }
1585
1586 BufferOffset Assembler::allocLiteralLoadEntry(
1587 size_t numInst, unsigned numPoolEntries, PoolHintPun& php, uint8_t* data,
1588 const LiteralDoc& doc, ARMBuffer::PoolEntry* pe, bool loadToPC) {
1589 uint8_t* inst = (uint8_t*)&php.raw;
1590
1591 MOZ_ASSERT(inst);
1592 MOZ_ASSERT(numInst == 1); // Or fix the disassembly
1593
1594 BufferOffset offs =
1595 m_buffer.allocEntry(numInst, numPoolEntries, inst, data, pe);
1596 propagateOOM(offs.assigned());
1597 #ifdef JS_DISASM_ARM
1598 Instruction* instruction = m_buffer.getInstOrNull(offs);
1599 if (instruction) {
1600 spewLiteralLoad(php, loadToPC, instruction, doc);
1601 }
1602 #endif
1603 return offs;
1604 }
1605
1606 // This is also used for instructions that might be resolved into branches,
1607 // or might not. If dest==pc then it is effectively a branch.
1608
1609 BufferOffset Assembler::as_Imm32Pool(Register dest, uint32_t value,
1610 Condition c) {
1611 PoolHintPun php;
1612 php.phd.init(0, c, PoolHintData::PoolDTR, dest);
1613 BufferOffset offs = allocLiteralLoadEntry(
1614 1, 1, php, (uint8_t*)&value, LiteralDoc(value), nullptr, dest == pc);
1615 return offs;
1616 }
1617
1618 /* static */
1619 void Assembler::WritePoolEntry(Instruction* addr, Condition c, uint32_t data) {
1620 MOZ_ASSERT(addr->is<InstLDR>());
1621 *addr->as<InstLDR>()->dest() = data;
1622 MOZ_ASSERT(addr->extractCond() == c);
1623 }
1624
1625 BufferOffset Assembler::as_FImm64Pool(VFPRegister dest, double d, Condition c) {
1626 MOZ_ASSERT(dest.isDouble());
1627 PoolHintPun php;
1628 php.phd.init(0, c, PoolHintData::PoolVDTR, dest);
1629 return allocLiteralLoadEntry(1, 2, php, (uint8_t*)&d, LiteralDoc(d));
1630 }
1631
1632 BufferOffset Assembler::as_FImm32Pool(VFPRegister dest, float f, Condition c) {
1633 // Insert floats into the double pool as they have the same limitations on
1634 // immediate offset. This wastes 4 bytes padding per float. An alternative
1635 // would be to have a separate pool for floats.
1636 MOZ_ASSERT(dest.isSingle());
1637 PoolHintPun php;
1638 php.phd.init(0, c, PoolHintData::PoolVDTR, dest);
1639 return allocLiteralLoadEntry(1, 1, php, (uint8_t*)&f, LiteralDoc(f));
1640 }
1641
1642 // Pool callbacks stuff:
1643 void Assembler::InsertIndexIntoTag(uint8_t* load_, uint32_t index) {
1644 uint32_t* load = (uint32_t*)load_;
1645 PoolHintPun php;
1646 php.raw = *load;
1647 php.phd.setIndex(index);
1648 *load = php.raw;
1649 }
1650
1651 // patchConstantPoolLoad takes the address of the instruction that wants to be
1652 // patched, and the address of the start of the constant pool, and figures
1653 // things out from there.
1654 void Assembler::PatchConstantPoolLoad(void* loadAddr, void* constPoolAddr) {
1655 PoolHintData data = *(PoolHintData*)loadAddr;
1656 uint32_t* instAddr = (uint32_t*)loadAddr;
1657 int offset = (char*)constPoolAddr - (char*)loadAddr;
1658 switch (data.getLoadType()) {
1659 case PoolHintData::PoolBOGUS:
1660 MOZ_CRASH("bogus load type!");
1661 case PoolHintData::PoolDTR:
1662 Assembler::as_dtr_patch(
1663 IsLoad, 32, Offset, data.getReg(),
1664 DTRAddr(pc, DtrOffImm(offset + 4 * data.getIndex() - 8)),
1665 data.getCond(), instAddr);
1666 break;
1667 case PoolHintData::PoolBranch:
1668 // Either this used to be a poolBranch, and the label was already bound,
1669 // so it was replaced with a real branch, or this may happen in the
1670 // future. If this is going to happen in the future, then the actual
1671 // bits that are written here don't matter (except the condition code,
1672 // since that is always preserved across patchings) but if it does not
1673 // get bound later, then we want to make sure this is a load from the
1674 // pool entry (and the pool entry should be nullptr so it will crash).
1675 if (data.isValidPoolHint()) {
1676 Assembler::as_dtr_patch(
1677 IsLoad, 32, Offset, pc,
1678 DTRAddr(pc, DtrOffImm(offset + 4 * data.getIndex() - 8)),
1679 data.getCond(), instAddr);
1680 }
1681 break;
1682 case PoolHintData::PoolVDTR: {
1683 VFPRegister dest = data.getVFPReg();
1684 int32_t imm = offset + (data.getIndex() * 4) - 8;
1685 MOZ_ASSERT(-1024 < imm && imm < 1024);
1686 Assembler::as_vdtr_patch(IsLoad, dest, VFPAddr(pc, VFPOffImm(imm)),
1687 data.getCond(), instAddr);
1688 break;
1689 }
1690 }
1691 }
1692
1693 // Atomic instruction stuff:
1694
1695 BufferOffset Assembler::as_ldrexd(Register rt, Register rt2, Register rn,
1696 Condition c) {
1697 MOZ_ASSERT(!(rt.code() & 1) && rt2.code() == rt.code() + 1);
1698 MOZ_ASSERT(rt.code() != 14 && rn.code() != 15);
1699 return writeInst(0x01b00f9f | (int)c | RT(rt) | RN(rn));
1700 }
1701
1702 BufferOffset Assembler::as_ldrex(Register rt, Register rn, Condition c) {
1703 MOZ_ASSERT(rt.code() != 15 && rn.code() != 15);
1704 return writeInst(0x01900f9f | (int)c | RT(rt) | RN(rn));
1705 }
1706
1707 BufferOffset Assembler::as_ldrexh(Register rt, Register rn, Condition c) {
1708 MOZ_ASSERT(rt.code() != 15 && rn.code() != 15);
1709 return writeInst(0x01f00f9f | (int)c | RT(rt) | RN(rn));
1710 }
1711
1712 BufferOffset Assembler::as_ldrexb(Register rt, Register rn, Condition c) {
1713 MOZ_ASSERT(rt.code() != 15 && rn.code() != 15);
1714 return writeInst(0x01d00f9f | (int)c | RT(rt) | RN(rn));
1715 }
1716
1717 BufferOffset Assembler::as_strexd(Register rd, Register rt, Register rt2,
1718 Register rn, Condition c) {
1719 MOZ_ASSERT(!(rt.code() & 1) && rt2.code() == rt.code() + 1);
1720 MOZ_ASSERT(rt.code() != 14 && rn.code() != 15 && rd.code() != 15);
1721 MOZ_ASSERT(rd != rn && rd != rt && rd != rt2);
1722 return writeInst(0x01a00f90 | (int)c | RD(rd) | RN(rn) | rt.code());
1723 }
1724
1725 BufferOffset Assembler::as_strex(Register rd, Register rt, Register rn,
1726 Condition c) {
1727 MOZ_ASSERT(rd != rn && rd != rt); // True restriction on Cortex-A7 (RPi2)
1728 return writeInst(0x01800f90 | (int)c | RD(rd) | RN(rn) | rt.code());
1729 }
1730
1731 BufferOffset Assembler::as_strexh(Register rd, Register rt, Register rn,
1732 Condition c) {
1733 MOZ_ASSERT(rd != rn && rd != rt); // True restriction on Cortex-A7 (RPi2)
1734 return writeInst(0x01e00f90 | (int)c | RD(rd) | RN(rn) | rt.code());
1735 }
1736
1737 BufferOffset Assembler::as_strexb(Register rd, Register rt, Register rn,
1738 Condition c) {
1739 MOZ_ASSERT(rd != rn && rd != rt); // True restriction on Cortex-A7 (RPi2)
1740 return writeInst(0x01c00f90 | (int)c | RD(rd) | RN(rn) | rt.code());
1741 }
1742
1743 BufferOffset Assembler::as_clrex() { return writeInst(0xf57ff01f); }
1744
1745 // Memory barrier stuff:
1746
1747 BufferOffset Assembler::as_dmb(BarrierOption option) {
1748 return writeInst(0xf57ff050U | (int)option);
1749 }
1750 BufferOffset Assembler::as_dsb(BarrierOption option) {
1751 return writeInst(0xf57ff040U | (int)option);
1752 }
1753 BufferOffset Assembler::as_isb() {
1754 return writeInst(0xf57ff06fU); // option == SY
1755 }
1756 BufferOffset Assembler::as_dsb_trap() {
1757 // DSB is "mcr 15, 0, r0, c7, c10, 4".
1758 // See eg https://bugs.kde.org/show_bug.cgi?id=228060.
1759 // ARMv7 manual, "VMSA CP15 c7 register summary".
1760 // Flagged as "legacy" starting with ARMv8, may be disabled on chip, see
1761 // ARMv8 manual E2.7.3 and G3.18.16.
1762 return writeInst(0xee070f9a);
1763 }
1764 BufferOffset Assembler::as_dmb_trap() {
1765 // DMB is "mcr 15, 0, r0, c7, c10, 5".
1766 // ARMv7 manual, "VMSA CP15 c7 register summary".
1767 // Flagged as "legacy" starting with ARMv8, may be disabled on chip, see
1768 // ARMv8 manual E2.7.3 and G3.18.16.
1769 return writeInst(0xee070fba);
1770 }
1771 BufferOffset Assembler::as_isb_trap() {
1772 // ISB is "mcr 15, 0, r0, c7, c5, 4".
1773 // ARMv7 manual, "VMSA CP15 c7 register summary".
1774 // Flagged as "legacy" starting with ARMv8, may be disabled on chip, see
1775 // ARMv8 manual E2.7.3 and G3.18.16.
1776 return writeInst(0xee070f94);
1777 }
1778
1779 BufferOffset Assembler::as_csdb() {
1780 // NOP (see as_nop) on architectures where this instruction is not defined.
1781 //
1782 // https://developer.arm.com/-/media/developer/pdf/Cache_Speculation_Side-channels_22Feb18.pdf
1783 // CSDB A32: 1110_0011_0010_0000_1111_0000_0001_0100
1784 return writeInst(0xe320f000 | 0x14);
1785 }
1786
1787 // Move Special Register and Hints:
1788
1789 BufferOffset Assembler::as_yield() {
1790 // YIELD hint instruction.
1791 //
1792 // YIELD A32: 1110_0011_0010_0000_1111_0000_0000_0001
1793 return writeInst(0xe320f001);
1794 }
1795
1796 // Control flow stuff:
1797
1798 // bx can *only* branch to a register, never to an immediate.
1799 BufferOffset Assembler::as_bx(Register r, Condition c) {
1800 BufferOffset ret = writeInst(((int)c) | OpBx | r.code());
1801 return ret;
1802 }
1803
1804 void Assembler::WritePoolGuard(BufferOffset branch, Instruction* dest,
1805 BufferOffset afterPool) {
1806 BOffImm off = afterPool.diffB<BOffImm>(branch);
1807 if (off.isInvalid()) {
1808 MOZ_CRASH("BOffImm invalid");
1809 }
1810 *dest = InstBImm(off, Always);
1811 }
1812
1813 // Branch can branch to an immediate *or* to a register.
1814 // Branches to immediates are pc relative, branches to registers are absolute.
1815 BufferOffset Assembler::as_b(BOffImm off, Condition c, Label* documentation) {
1816 return writeBranchInst(((int)c) | OpB | off.encode(),
1817 refLabel(documentation));
1818 }
1819
1820 BufferOffset Assembler::as_b(Label* l, Condition c) {
1821 if (l->bound()) {
1822 // Note only one instruction is emitted here, the NOP is overwritten.
1823 BufferOffset ret = allocBranchInst();
1824 if (oom()) {
1825 return BufferOffset();
1826 }
1827
1828 BOffImm offset = BufferOffset(l).diffB<BOffImm>(ret);
1829 MOZ_RELEASE_ASSERT(!offset.isInvalid(),
1830 "Buffer size limit should prevent this");
1831 as_b(offset, c, ret);
1832 #ifdef JS_DISASM_ARM
1833 spewBranch(m_buffer.getInstOrNull(ret), refLabel(l));
1834 #endif
1835 return ret;
1836 }
1837
1838 if (oom()) {
1839 return BufferOffset();
1840 }
1841
1842 BufferOffset ret;
1843 if (l->used()) {
1844 int32_t old = l->offset();
1845 MOZ_RELEASE_ASSERT(BOffImm::IsInRange(old),
1846 "Buffer size limit should prevent this");
1847 ret = as_b(BOffImm(old), c, l);
1848 } else {
1849 BOffImm inv;
1850 ret = as_b(inv, c, l);
1851 }
1852
1853 if (oom()) {
1854 return BufferOffset();
1855 }
1856
1857 l->use(ret.getOffset());
1858 return ret;
1859 }
1860
1861 BufferOffset Assembler::as_b(BOffImm off, Condition c, BufferOffset inst) {
1862 // JS_DISASM_ARM NOTE: Can't disassemble here, because numerous callers use
1863 // this to patchup old code. Must disassemble in caller where it makes sense.
1864 // Not many callers.
1865 *editSrc(inst) = InstBImm(off, c);
1866 return inst;
1867 }
1868
1869 // blx can go to either an immediate or a register.
1870 // When blx'ing to a register, we change processor state depending on the low
1871 // bit of the register when blx'ing to an immediate, we *always* change
1872 // processor state.
1873
1874 BufferOffset Assembler::as_blx(Register r, Condition c) {
1875 return writeInst(((int)c) | OpBlx | r.code());
1876 }
1877
1878 // bl can only branch to an pc-relative immediate offset
1879 // It cannot change the processor state.
1880 BufferOffset Assembler::as_bl(BOffImm off, Condition c, Label* documentation) {
1881 return writeBranchInst(((int)c) | OpBl | off.encode(),
1882 refLabel(documentation));
1883 }
1884
1885 BufferOffset Assembler::as_bl(Label* l, Condition c) {
1886 if (l->bound()) {
1887 // Note only one instruction is emitted here, the NOP is overwritten.
1888 BufferOffset ret = allocBranchInst();
1889 if (oom()) {
1890 return BufferOffset();
1891 }
1892
1893 BOffImm offset = BufferOffset(l).diffB<BOffImm>(ret);
1894 MOZ_RELEASE_ASSERT(!offset.isInvalid(),
1895 "Buffer size limit should prevent this");
1896
1897 as_bl(offset, c, ret);
1898 #ifdef JS_DISASM_ARM
1899 spewBranch(m_buffer.getInstOrNull(ret), refLabel(l));
1900 #endif
1901 return ret;
1902 }
1903
1904 if (oom()) {
1905 return BufferOffset();
1906 }
1907
1908 BufferOffset ret;
1909 // See if the list was empty.
1910 if (l->used()) {
1911 int32_t old = l->offset();
1912 MOZ_RELEASE_ASSERT(BOffImm::IsInRange(old),
1913 "Buffer size limit should prevent this");
1914 ret = as_bl(BOffImm(old), c, l);
1915 } else {
1916 BOffImm inv;
1917 ret = as_bl(inv, c, l);
1918 }
1919
1920 if (oom()) {
1921 return BufferOffset();
1922 }
1923
1924 l->use(ret.getOffset());
1925 return ret;
1926 }
1927
1928 BufferOffset Assembler::as_bl(BOffImm off, Condition c, BufferOffset inst) {
1929 *editSrc(inst) = InstBLImm(off, c);
1930 return inst;
1931 }
1932
1933 BufferOffset Assembler::as_mrs(Register r, Condition c) {
1934 return writeInst(0x010f0000 | int(c) | RD(r));
1935 }
1936
1937 BufferOffset Assembler::as_msr(Register r, Condition c) {
1938 // Hardcode the 'mask' field to 0b11 for now. It is bits 18 and 19, which
1939 // are the two high bits of the 'c' in this constant.
1940 MOZ_ASSERT((r.code() & ~0xf) == 0);
1941 return writeInst(0x012cf000 | int(c) | r.code());
1942 }
1943
1944 // VFP instructions!
1945 enum vfp_tags { VfpTag = 0x0C000A00, VfpArith = 0x02000000 };
1946
1947 BufferOffset Assembler::writeVFPInst(vfp_size sz, uint32_t blob) {
1948 MOZ_ASSERT((sz & blob) == 0);
1949 MOZ_ASSERT((VfpTag & blob) == 0);
1950 return writeInst(VfpTag | std::underlying_type_t<vfp_size>(sz) | blob);
1951 }
1952
1953 /* static */
1954 void Assembler::WriteVFPInstStatic(vfp_size sz, uint32_t blob, uint32_t* dest) {
1955 MOZ_ASSERT((sz & blob) == 0);
1956 MOZ_ASSERT((VfpTag & blob) == 0);
1957 WriteInstStatic(VfpTag | std::underlying_type_t<vfp_size>(sz) | blob, dest);
1958 }
1959
1960 // Unityped variants: all registers hold the same (ieee754 single/double)
1961 // notably not included are vcvt; vmov vd, #imm; vmov rt, vn.
1962 BufferOffset Assembler::as_vfp_float(VFPRegister vd, VFPRegister vn,
1963 VFPRegister vm, VFPOp op, Condition c) {
1964 // Make sure we believe that all of our operands are the same kind.
1965 MOZ_ASSERT_IF(!vn.isMissing(), vd.equiv(vn));
1966 MOZ_ASSERT_IF(!vm.isMissing(), vd.equiv(vm));
1967 vfp_size sz = vd.isDouble() ? IsDouble : IsSingle;
1968 return writeVFPInst(sz, VD(vd) | VN(vn) | VM(vm) | op | VfpArith | c);
1969 }
1970
1971 BufferOffset Assembler::as_vadd(VFPRegister vd, VFPRegister vn, VFPRegister vm,
1972 Condition c) {
1973 return as_vfp_float(vd, vn, vm, OpvAdd, c);
1974 }
1975
1976 BufferOffset Assembler::as_vdiv(VFPRegister vd, VFPRegister vn, VFPRegister vm,
1977 Condition c) {
1978 return as_vfp_float(vd, vn, vm, OpvDiv, c);
1979 }
1980
1981 BufferOffset Assembler::as_vmul(VFPRegister vd, VFPRegister vn, VFPRegister vm,
1982 Condition c) {
1983 return as_vfp_float(vd, vn, vm, OpvMul, c);
1984 }
1985
1986 BufferOffset Assembler::as_vnmul(VFPRegister vd, VFPRegister vn, VFPRegister vm,
1987 Condition c) {
1988 return as_vfp_float(vd, vn, vm, OpvMul, c);
1989 }
1990
1991 BufferOffset Assembler::as_vnmla(VFPRegister vd, VFPRegister vn, VFPRegister vm,
1992 Condition c) {
1993 MOZ_CRASH("Feature NYI");
1994 }
1995
1996 BufferOffset Assembler::as_vnmls(VFPRegister vd, VFPRegister vn, VFPRegister vm,
1997 Condition c) {
1998 MOZ_CRASH("Feature NYI");
1999 }
2000
2001 BufferOffset Assembler::as_vneg(VFPRegister vd, VFPRegister vm, Condition c) {
2002 return as_vfp_float(vd, NoVFPRegister, vm, OpvNeg, c);
2003 }
2004
2005 BufferOffset Assembler::as_vsqrt(VFPRegister vd, VFPRegister vm, Condition c) {
2006 return as_vfp_float(vd, NoVFPRegister, vm, OpvSqrt, c);
2007 }
2008
2009 BufferOffset Assembler::as_vabs(VFPRegister vd, VFPRegister vm, Condition c) {
2010 return as_vfp_float(vd, NoVFPRegister, vm, OpvAbs, c);
2011 }
2012
2013 BufferOffset Assembler::as_vsub(VFPRegister vd, VFPRegister vn, VFPRegister vm,
2014 Condition c) {
2015 return as_vfp_float(vd, vn, vm, OpvSub, c);
2016 }
2017
2018 BufferOffset Assembler::as_vcmp(VFPRegister vd, VFPRegister vm, Condition c) {
2019 return as_vfp_float(vd, NoVFPRegister, vm, OpvCmp, c);
2020 }
2021
2022 BufferOffset Assembler::as_vcmpz(VFPRegister vd, Condition c) {
2023 return as_vfp_float(vd, NoVFPRegister, NoVFPRegister, OpvCmpz, c);
2024 }
2025
2026 // Specifically, a move between two same sized-registers.
2027 BufferOffset Assembler::as_vmov(VFPRegister vd, VFPRegister vsrc, Condition c) {
2028 return as_vfp_float(vd, NoVFPRegister, vsrc, OpvMov, c);
2029 }
2030
2031 // Transfer between Core and VFP.
2032
2033 // Unlike the next function, moving between the core registers and vfp registers
2034 // can't be *that* properly typed. Namely, since I don't want to munge the type
2035 // VFPRegister to also include core registers. Thus, the core and vfp registers
2036 // are passed in based on their type, and src/dest is determined by the
2037 // float2core.
2038
2039 BufferOffset Assembler::as_vxfer(Register vt1, Register vt2, VFPRegister vm,
2040 FloatToCore_ f2c, Condition c, int idx) {
2041 vfp_size sz = IsSingle;
2042 if (vm.isDouble()) {
2043 // Technically, this can be done with a vmov à la ARM ARM under vmov
2044 // however, that requires at least an extra bit saying if the operation
2045 // should be performed on the lower or upper half of the double. Moving
2046 // a single to/from 2N/2N+1 isn't equivalent, since there are 32 single
2047 // registers, and 32 double registers so there is no way to encode the
2048 // last 16 double registers.
2049 sz = IsDouble;
2050 MOZ_ASSERT(idx == 0 || idx == 1);
2051 // If we are transferring a single half of the double then it must be
2052 // moving a VFP reg to a core reg.
2053 MOZ_ASSERT_IF(vt2 == InvalidReg, f2c == FloatToCore);
2054 idx = idx << 21;
2055 } else {
2056 MOZ_ASSERT(idx == 0);
2057 }
2058
2059 if (vt2 == InvalidReg) {
2060 return writeVFPInst(sz, WordTransfer |
2061 std::underlying_type_t<FloatToCore_>(f2c) |
2062 std::underlying_type_t<Condition>(c) | RT(vt1) |
2063 maybeRN(vt2) | VN(vm) | idx);
2064 }
2065
2066 // We are doing a 64 bit transfer.
2067 return writeVFPInst(sz, DoubleTransfer |
2068 std::underlying_type_t<FloatToCore_>(f2c) |
2069 std::underlying_type_t<Condition>(c) | RT(vt1) |
2070 maybeRN(vt2) | VM(vm) | idx);
2071 }
2072
2073 enum vcvt_destFloatness { VcvtToInteger = 1 << 18, VcvtToFloat = 0 << 18 };
2074 enum vcvt_toZero {
2075 VcvtToZero =
2076 1 << 7, // Use the default rounding mode, which rounds truncates.
2077 VcvtToFPSCR = 0 << 7 // Use whatever rounding mode the fpscr specifies.
2078 };
2079 enum vcvt_Signedness {
2080 VcvtToSigned = 1 << 16,
2081 VcvtToUnsigned = 0 << 16,
2082 VcvtFromSigned = 1 << 7,
2083 VcvtFromUnsigned = 0 << 7
2084 };
2085
2086 // Our encoding actually allows just the src and the dest (and their types) to
2087 // uniquely specify the encoding that we are going to use.
2088 BufferOffset Assembler::as_vcvt(VFPRegister vd, VFPRegister vm, bool useFPSCR,
2089 Condition c) {
2090 // Unlike other cases, the source and dest types cannot be the same.
2091 MOZ_ASSERT(!vd.equiv(vm));
2092 vfp_size sz = IsDouble;
2093 if (vd.isFloat() && vm.isFloat()) {
2094 // Doing a float -> float conversion.
2095 if (vm.isSingle()) {
2096 sz = IsSingle;
2097 }
2098 return writeVFPInst(sz, c | 0x02B700C0 | VM(vm) | VD(vd));
2099 }
2100
2101 // At least one of the registers should be a float.
2102 vcvt_destFloatness destFloat;
2103 vcvt_Signedness opSign;
2104 vcvt_toZero doToZero = VcvtToFPSCR;
2105 MOZ_ASSERT(vd.isFloat() || vm.isFloat());
2106 if (vd.isSingle() || vm.isSingle()) {
2107 sz = IsSingle;
2108 }
2109
2110 if (vd.isFloat()) {
2111 destFloat = VcvtToFloat;
2112 opSign = (vm.isSInt()) ? VcvtFromSigned : VcvtFromUnsigned;
2113 } else {
2114 destFloat = VcvtToInteger;
2115 opSign = (vd.isSInt()) ? VcvtToSigned : VcvtToUnsigned;
2116 doToZero = useFPSCR ? VcvtToFPSCR : VcvtToZero;
2117 }
2118 return writeVFPInst(
2119 sz, c | 0x02B80040 | VD(vd) | VM(vm) | destFloat | opSign | doToZero);
2120 }
2121
2122 BufferOffset Assembler::as_vcvtFixed(VFPRegister vd, bool isSigned,
2123 uint32_t fixedPoint, bool toFixed,
2124 Condition c) {
2125 MOZ_ASSERT(vd.isFloat());
2126 uint32_t sx = 0x1;
2127 vfp_size sf = vd.isDouble() ? IsDouble : IsSingle;
2128 int32_t imm5 = fixedPoint;
2129 imm5 = (sx ? 32 : 16) - imm5;
2130 MOZ_ASSERT(imm5 >= 0);
2131 imm5 = imm5 >> 1 | (imm5 & 1) << 5;
2132 return writeVFPInst(sf, 0x02BA0040 | VD(vd) | toFixed << 18 | sx << 7 |
2133 (!isSigned) << 16 | imm5 | c);
2134 }
2135
2136 BufferOffset Assembler::as_vcvtb_s2h(VFPRegister vd, VFPRegister vm,
2137 Condition c) {
2138 MOZ_ASSERT(ARMFlags::HasFPHalfPrecision());
2139 MOZ_ASSERT(vd.isSingle());
2140 MOZ_ASSERT(vm.isSingle());
2141
2142 return writeVFPInst(IsSingle, c | 0x02B30040 | VM(vm) | VD(vd));
2143 }
2144
2145 BufferOffset Assembler::as_vcvtb_h2s(VFPRegister vd, VFPRegister vm,
2146 Condition c) {
2147 MOZ_ASSERT(ARMFlags::HasFPHalfPrecision());
2148 MOZ_ASSERT(vd.isSingle());
2149 MOZ_ASSERT(vm.isSingle());
2150
2151 return writeVFPInst(IsSingle, c | 0x02B20040 | VM(vm) | VD(vd));
2152 }
2153
2154 // Transfer between VFP and memory.
2155 static uint32_t EncodeVdtr(LoadStore ls, VFPRegister vd, VFPAddr addr,
2156 Assembler::Condition c) {
2157 return ls | 0x01000000 | addr.encode() | VD(vd) | c;
2158 }
2159
2160 BufferOffset Assembler::as_vdtr(
2161 LoadStore ls, VFPRegister vd, VFPAddr addr,
2162 Condition c /* vfp doesn't have a wb option */) {
2163 vfp_size sz = vd.isDouble() ? IsDouble : IsSingle;
2164 return writeVFPInst(sz, EncodeVdtr(ls, vd, addr, c));
2165 }
2166
2167 /* static */
2168 void Assembler::as_vdtr_patch(LoadStore ls, VFPRegister vd, VFPAddr addr,
2169 Condition c, uint32_t* dest) {
2170 vfp_size sz = vd.isDouble() ? IsDouble : IsSingle;
2171 WriteVFPInstStatic(sz, EncodeVdtr(ls, vd, addr, c), dest);
2172 }
2173
2174 // VFP's ldm/stm work differently from the standard arm ones. You can only
2175 // transfer a range.
2176
2177 BufferOffset Assembler::as_vdtm(LoadStore st, Register rn, VFPRegister vd,
2178 int length,
2179 /* also has update conditions */ Condition c) {
2180 MOZ_ASSERT(length <= 16 && length >= 0);
2181 vfp_size sz = vd.isDouble() ? IsDouble : IsSingle;
2182
2183 if (vd.isDouble()) {
2184 length *= 2;
2185 }
2186
2187 return writeVFPInst(sz, dtmLoadStore | RN(rn) | VD(vd) | length | dtmMode |
2188 dtmUpdate | dtmCond);
2189 }
2190
2191 BufferOffset Assembler::as_vldr_unaligned(VFPRegister vd, Register rn) {
2192 MOZ_ASSERT(ARMFlags::HasNEON());
2193 if (vd.isDouble()) {
2194 // vld1 (multiple single elements) with align=0, size=3, numregs=1
2195 return writeInst(0xF42007CF | RN(rn) | VD(vd));
2196 }
2197 // vld1 (single element to single lane) with index=0, size=2
2198 MOZ_ASSERT(vd.isFloat());
2199 MOZ_ASSERT((vd.code() & 1) == 0);
2200 return writeInst(0xF4A0080F | RN(rn) | VD(vd.asDouble()));
2201 }
2202
2203 BufferOffset Assembler::as_vstr_unaligned(VFPRegister vd, Register rn) {
2204 MOZ_ASSERT(ARMFlags::HasNEON());
2205 if (vd.isDouble()) {
2206 // vst1 (multiple single elements) with align=0, size=3, numregs=1
2207 return writeInst(0xF40007CF | RN(rn) | VD(vd));
2208 }
2209 // vst1 (single element from one lane) with index=0, size=2
2210 MOZ_ASSERT(vd.isFloat());
2211 MOZ_ASSERT((vd.code() & 1) == 0);
2212 return writeInst(0xF480080F | RN(rn) | VD(vd.asDouble()));
2213 }
2214
2215 BufferOffset Assembler::as_vimm(VFPRegister vd, VFPImm imm, Condition c) {
2216 MOZ_ASSERT(imm.isValid());
2217 vfp_size sz = vd.isDouble() ? IsDouble : IsSingle;
2218 return writeVFPInst(sz, c | imm.encode() | VD(vd) | 0x02B00000);
2219 }
2220
2221 BufferOffset Assembler::as_vmrs(Register r, Condition c) {
2222 return writeInst(c | 0x0ef10a10 | RT(r));
2223 }
2224
2225 BufferOffset Assembler::as_vmsr(Register r, Condition c) {
2226 return writeInst(c | 0x0ee10a10 | RT(r));
2227 }
2228
2229 bool Assembler::nextLink(BufferOffset b, BufferOffset* next) {
2230 Instruction branch = *editSrc(b);
2231 MOZ_ASSERT(branch.is<InstBranchImm>());
2232
2233 BOffImm destOff;
2234 branch.as<InstBranchImm>()->extractImm(&destOff);
2235 if (destOff.isInvalid()) {
2236 return false;
2237 }
2238
2239 // Propagate the next link back to the caller, by constructing a new
2240 // BufferOffset into the space they provided.
2241 new (next) BufferOffset(destOff.decode());
2242 return true;
2243 }
2244
2245 void Assembler::bind(Label* label, BufferOffset boff) {
2246 #ifdef JS_DISASM_ARM
2247 spew_.spewBind(label);
2248 #endif
2249 if (oom()) {
2250 // Ensure we always bind the label. This matches what we do on
2251 // x86/x64 and silences the assert in ~Label.
2252 label->bind(0);
2253 return;
2254 }
2255
2256 BufferOffset dest = boff.assigned() ? boff : nextOffset();
2257 if (label->used()) {
2258 bool more;
2259 // If our caller didn't give us an explicit target to bind to then we
2260 // want to bind to the location of the next instruction.
2261 BufferOffset b(label);
2262 do {
2263 BufferOffset next;
2264 more = nextLink(b, &next);
2265 Instruction branch = *editSrc(b);
2266 Condition c = branch.extractCond();
2267 BOffImm offset = dest.diffB<BOffImm>(b);
2268 MOZ_RELEASE_ASSERT(!offset.isInvalid(),
2269 "Buffer size limit should prevent this");
2270 if (branch.is<InstBImm>()) {
2271 as_b(offset, c, b);
2272 } else if (branch.is<InstBLImm>()) {
2273 as_bl(offset, c, b);
2274 } else {
2275 MOZ_CRASH("crazy fixup!");
2276 }
2277 b = next;
2278 } while (more);
2279 }
2280 label->bind(dest.getOffset());
2281 MOZ_ASSERT(!oom());
2282 }
2283
2284 void Assembler::retarget(Label* label, Label* target) {
2285 #ifdef JS_DISASM_ARM
2286 spew_.spewRetarget(label, target);
2287 #endif
2288 if (label->used() && !oom()) {
2289 if (target->bound()) {
2290 bind(label, BufferOffset(target));
2291 } else if (target->used()) {
2292 // The target is not bound but used. Prepend label's branch list
2293 // onto target's.
2294 BufferOffset labelBranchOffset(label);
2295 BufferOffset next;
2296
2297 // Find the head of the use chain for label.
2298 while (nextLink(labelBranchOffset, &next)) {
2299 labelBranchOffset = next;
2300 }
2301
2302 // Then patch the head of label's use chain to the tail of target's
2303 // use chain, prepending the entire use chain of target.
2304 Instruction branch = *editSrc(labelBranchOffset);
2305 Condition c = branch.extractCond();
2306 int32_t prev = target->offset();
2307 target->use(label->offset());
2308 if (branch.is<InstBImm>()) {
2309 as_b(BOffImm(prev), c, labelBranchOffset);
2310 } else if (branch.is<InstBLImm>()) {
2311 as_bl(BOffImm(prev), c, labelBranchOffset);
2312 } else {
2313 MOZ_CRASH("crazy fixup!");
2314 }
2315 } else {
2316 // The target is unbound and unused. We can just take the head of
2317 // the list hanging off of label, and dump that into target.
2318 target->use(label->offset());
2319 }
2320 }
2321 label->reset();
2322 }
2323
2324 static int stopBKPT = -1;
2325 void Assembler::as_bkpt() {
2326 // This is a count of how many times a breakpoint instruction has been
2327 // generated. It is embedded into the instruction for debugging
2328 // purposes. Gdb will print "bkpt xxx" when you attempt to dissassemble a
2329 // breakpoint with the number xxx embedded into it. If this breakpoint is
2330 // being hit, then you can run (in gdb):
2331 // >b dbg_break
2332 // >b main
2333 // >commands
2334 // >set stopBKPT = xxx
2335 // >c
2336 // >end
2337 // which will set a breakpoint on the function dbg_break above set a
2338 // scripted breakpoint on main that will set the (otherwise unmodified)
2339 // value to the number of the breakpoint, so dbg_break will actuall be
2340 // called and finally, when you run the executable, execution will halt when
2341 // that breakpoint is generated.
2342 static int hit = 0;
2343 if (stopBKPT == hit) {
2344 dbg_break();
2345 }
2346 writeInst(0xe1200070 | (hit & 0xf) | ((hit & 0xfff0) << 4));
2347 hit++;
2348 }
2349
2350 BufferOffset Assembler::as_illegal_trap() {
2351 // Encoding of the permanently-undefined 'udf' instruction, with the imm16
2352 // set to 0.
2353 return writeInst(0xe7f000f0);
2354 }
2355
2356 void Assembler::flushBuffer() { m_buffer.flushPool(); }
2357
2358 void Assembler::enterNoPool(size_t maxInst) { m_buffer.enterNoPool(maxInst); }
2359
2360 void Assembler::leaveNoPool() { m_buffer.leaveNoPool(); }
2361
2362 void Assembler::enterNoNops() { m_buffer.enterNoNops(); }
2363
2364 void Assembler::leaveNoNops() { m_buffer.leaveNoNops(); }
2365
2366 struct PoolHeader : Instruction {
2367 struct Header {
2368 // The size should take into account the pool header.
2369 // The size is in units of Instruction (4 bytes), not byte.
2370 uint32_t size : 15;
2371 uint32_t isNatural : 1;
2372 uint32_t ONES : 16;
2373
2374 Header(int size_, bool isNatural_)
2375 : size(size_), isNatural(isNatural_), ONES(0xffff) {}
2376
2377 explicit Header(const Instruction* i) {
2378 static_assert(sizeof(Header) == sizeof(uint32_t));
2379 memcpy(this, i, sizeof(Header));
2380 MOZ_ASSERT(ONES == 0xffff);
2381 }
2382
2383 uint32_t raw() const {
2384 static_assert(sizeof(Header) == sizeof(uint32_t));
2385 uint32_t dest;
2386 memcpy(&dest, this, sizeof(Header));
2387 return dest;
2388 }
2389 };
2390
2391 PoolHeader(int size_, bool isNatural_)
2392 : Instruction(Header(size_, isNatural_).raw(), true) {}
2393
2394 uint32_t size() const {
2395 Header tmp(this);
2396 return tmp.size;
2397 }
2398 uint32_t isNatural() const {
2399 Header tmp(this);
2400 return tmp.isNatural;
2401 }
2402
2403 static bool IsTHIS(const Instruction& i) {
2404 return (*i.raw() & 0xffff0000) == 0xffff0000;
2405 }
2406 static const PoolHeader* AsTHIS(const Instruction& i) {
2407 if (!IsTHIS(i)) {
2408 return nullptr;
2409 }
2410 return static_cast<const PoolHeader*>(&i);
2411 }
2412 };
2413
2414 void Assembler::WritePoolHeader(uint8_t* start, Pool* p, bool isNatural) {
2415 static_assert(sizeof(PoolHeader) == 4,
2416 "PoolHandler must have the correct size.");
2417 uint8_t* pool = start + 4;
2418 // Go through the usual rigmarole to get the size of the pool.
2419 pool += p->getPoolSize();
2420 uint32_t size = pool - start;
2421 MOZ_ASSERT((size & 3) == 0);
2422 size = size >> 2;
2423 MOZ_ASSERT(size < (1 << 15));
2424 PoolHeader header(size, isNatural);
2425 *(PoolHeader*)start = header;
2426 }
2427
2428 // The size of an arbitrary 32-bit call in the instruction stream. On ARM this
2429 // sequence is |pc = ldr pc - 4; imm32| given that we never reach the imm32.
2430 uint32_t Assembler::PatchWrite_NearCallSize() { return sizeof(uint32_t); }
2431
2432 void Assembler::PatchWrite_NearCall(CodeLocationLabel start,
2433 CodeLocationLabel toCall) {
2434 Instruction* inst = (Instruction*)start.raw();
2435 // Overwrite whatever instruction used to be here with a call. Since the
2436 // destination is in the same function, it will be within range of the
2437 // 24 << 2 byte bl instruction.
2438 uint8_t* dest = toCall.raw();
2439 new (inst) InstBLImm(BOffImm(dest - (uint8_t*)inst), Always);
2440 }
2441
2442 void Assembler::PatchDataWithValueCheck(CodeLocationLabel label,
2443 PatchedImmPtr newValue,
2444 PatchedImmPtr expectedValue) {
2445 Instruction* ptr = reinterpret_cast<Instruction*>(label.raw());
2446
2447 Register dest;
2448 Assembler::RelocStyle rs;
2449
2450 {
2451 InstructionIterator iter(ptr);
2452 DebugOnly<const uint32_t*> val = GetPtr32Target(iter, &dest, &rs);
2453 MOZ_ASSERT(uint32_t((const uint32_t*)val) == uint32_t(expectedValue.value));
2454 }
2455
2456 // Patch over actual instructions.
2457 {
2458 InstructionIterator iter(ptr);
2459 MacroAssembler::ma_mov_patch(Imm32(int32_t(newValue.value)), dest, Always,
2460 rs, iter);
2461 }
2462 }
2463
2464 void Assembler::PatchDataWithValueCheck(CodeLocationLabel label,
2465 ImmPtr newValue, ImmPtr expectedValue) {
2466 PatchDataWithValueCheck(label, PatchedImmPtr(newValue.value),
2467 PatchedImmPtr(expectedValue.value));
2468 }
2469
2470 // This just stomps over memory with 32 bits of raw data. Its purpose is to
2471 // overwrite the call of JITed code with 32 bits worth of an offset. This will
2472 // is only meant to function on code that has been invalidated, so it should be
2473 // totally safe. Since that instruction will never be executed again, a ICache
2474 // flush should not be necessary
2475 void Assembler::PatchWrite_Imm32(CodeLocationLabel label, Imm32 imm) {
2476 // Raw is going to be the return address.
2477 uint32_t* raw = (uint32_t*)label.raw();
2478 // Overwrite the 4 bytes before the return address, which will end up being
2479 // the call instruction.
2480 *(raw - 1) = imm.value;
2481 }
2482
2483 uint8_t* Assembler::NextInstruction(uint8_t* inst_, uint32_t* count) {
2484 if (count != nullptr) {
2485 *count += sizeof(Instruction);
2486 }
2487
2488 InstructionIterator iter(reinterpret_cast<Instruction*>(inst_));
2489 return reinterpret_cast<uint8_t*>(iter.next());
2490 }
2491
2492 static bool InstIsGuard(Instruction* inst, const PoolHeader** ph) {
2493 Assembler::Condition c = inst->extractCond();
2494 if (c != Assembler::Always) {
2495 return false;
2496 }
2497 if (!(inst->is<InstBXReg>() || inst->is<InstBImm>())) {
2498 return false;
2499 }
2500 // See if the next instruction is a pool header.
2501 *ph = (inst + 1)->as<const PoolHeader>();
2502 return *ph != nullptr;
2503 }
2504
2505 static bool InstIsGuard(BufferInstructionIterator& iter,
2506 const PoolHeader** ph) {
2507 Instruction* inst = iter.cur();
2508 Assembler::Condition c = inst->extractCond();
2509 if (c != Assembler::Always) {
2510 return false;
2511 }
2512 if (!(inst->is<InstBXReg>() || inst->is<InstBImm>())) {
2513 return false;
2514 }
2515 // See if the next instruction is a pool header.
2516 *ph = iter.peek()->as<const PoolHeader>();
2517 return *ph != nullptr;
2518 }
2519
2520 template <class T>
2521 static bool InstIsBNop(const T& iter) {
2522 // In some special situations, it is necessary to insert a NOP into the
2523 // instruction stream that nobody knows about, since nobody should know
2524 // about it, make sure it gets skipped when Instruction::next() is called.
2525 // this generates a very specific nop, namely a branch to the next
2526 // instruction.
2527 const Instruction* cur = iter.cur();
2528 Assembler::Condition c = cur->extractCond();
2529 if (c != Assembler::Always) {
2530 return false;
2531 }
2532 if (!cur->is<InstBImm>()) {
2533 return false;
2534 }
2535 InstBImm* b = cur->as<InstBImm>();
2536 BOffImm offset;
2537 b->extractImm(&offset);
2538 return offset.decode() == 4;
2539 }
2540
2541 Instruction* InstructionIterator::maybeSkipAutomaticInstructions() {
2542 // If the current instruction was automatically-inserted, skip past it.
2543 const PoolHeader* ph;
2544
2545 // Loop until an intentionally-placed instruction is found.
2546 while (true) {
2547 if (InstIsGuard(cur(), &ph)) {
2548 // Don't skip a natural guard.
2549 if (ph->isNatural()) {
2550 return cur();
2551 }
2552 advanceRaw(1 + ph->size());
2553 } else if (InstIsBNop<InstructionIterator>(*this)) {
2554 advanceRaw(1);
2555 } else {
2556 return cur();
2557 }
2558 }
2559 }
2560
2561 Instruction* BufferInstructionIterator::maybeSkipAutomaticInstructions() {
2562 const PoolHeader* ph;
2563 // If this is a guard, and the next instruction is a header, always work
2564 // around the pool. If it isn't a guard, then start looking ahead.
2565 if (InstIsGuard(*this, &ph)) {
2566 // Don't skip a natural guard.
2567 if (ph->isNatural()) {
2568 return cur();
2569 }
2570 advance(sizeof(Instruction) * ph->size());
2571 return next();
2572 }
2573 if (InstIsBNop<BufferInstructionIterator>(*this)) {
2574 return next();
2575 }
2576 return cur();
2577 }
2578
2579 // Cases to be handled:
2580 // 1) no pools or branches in sight => return this+1
2581 // 2) branch to next instruction => return this+2, because a nop needed to be
2582 // inserted into the stream.
2583 // 3) this+1 is an artificial guard for a pool => return first instruction
2584 // after the pool
2585 // 4) this+1 is a natural guard => return the branch
2586 // 5) this is a branch, right before a pool => return first instruction after
2587 // the pool
2588 // in assembly form:
2589 // 1) add r0, r0, r0 <= this
2590 // add r1, r1, r1 <= returned value
2591 // add r2, r2, r2
2592 //
2593 // 2) add r0, r0, r0 <= this
2594 // b foo
2595 // foo:
2596 // add r2, r2, r2 <= returned value
2597 //
2598 // 3) add r0, r0, r0 <= this
2599 // b after_pool;
2600 // .word 0xffff0002 # bit 15 being 0 indicates that the branch was not
2601 // # requested by the assembler
2602 // 0xdeadbeef # the 2 indicates that there is 1 pool entry, and the
2603 // # pool header
2604 // add r4, r4, r4 <= returned value
2605 // 4) add r0, r0, r0 <= this
2606 // b after_pool <= returned value
2607 // .word 0xffff8002 # bit 15 being 1 indicates that the branch was
2608 // # requested by the assembler
2609 // 0xdeadbeef
2610 // add r4, r4, r4
2611 // 5) b after_pool <= this
2612 // .word 0xffff8002 # bit 15 has no bearing on the returned value
2613 // 0xdeadbeef
2614 // add r4, r4, r4 <= returned value
2615
2616 Instruction* InstructionIterator::next() {
2617 const PoolHeader* ph;
2618
2619 // If the current instruction is followed by a pool header,
2620 // move past the current instruction and the pool.
2621 if (InstIsGuard(cur(), &ph)) {
2622 advanceRaw(1 + ph->size());
2623 return maybeSkipAutomaticInstructions();
2624 }
2625
2626 // The next instruction is then known to not be a PoolHeader.
2627 advanceRaw(1);
2628 return maybeSkipAutomaticInstructions();
2629 }
2630
2631 void Assembler::ToggleToJmp(CodeLocationLabel inst_) {
2632 uint32_t* ptr = (uint32_t*)inst_.raw();
2633
2634 DebugOnly<Instruction*> inst = (Instruction*)inst_.raw();
2635 MOZ_ASSERT(inst->is<InstCMP>());
2636
2637 // Zero bits 20-27, then set 24-27 to be correct for a branch.
2638 // 20-23 will be party of the B's immediate, and should be 0.
2639 *ptr = (*ptr & ~(0xff << 20)) | (0xa0 << 20);
2640 }
2641
2642 void Assembler::ToggleToCmp(CodeLocationLabel inst_) {
2643 uint32_t* ptr = (uint32_t*)inst_.raw();
2644
2645 DebugOnly<Instruction*> inst = (Instruction*)inst_.raw();
2646 MOZ_ASSERT(inst->is<InstBImm>());
2647
2648 // Ensure that this masking operation doesn't affect the offset of the
2649 // branch instruction when it gets toggled back.
2650 MOZ_ASSERT((*ptr & (0xf << 20)) == 0);
2651
2652 // Also make sure that the CMP is valid. Part of having a valid CMP is that
2653 // all of the bits describing the destination in most ALU instructions are
2654 // all unset (looks like it is encoding r0).
2655 MOZ_ASSERT(toRD(*inst) == r0);
2656
2657 // Zero out bits 20-27, then set them to be correct for a compare.
2658 *ptr = (*ptr & ~(0xff << 20)) | (0x35 << 20);
2659 }
2660
2661 void Assembler::ToggleCall(CodeLocationLabel inst_, bool enabled) {
2662 InstructionIterator iter(reinterpret_cast<Instruction*>(inst_.raw()));
2663 MOZ_ASSERT(iter.cur()->is<InstMovW>() || iter.cur()->is<InstLDR>());
2664
2665 if (iter.cur()->is<InstMovW>()) {
2666 // If it looks like the start of a movw/movt sequence, then make sure we
2667 // have all of it (and advance the iterator past the full sequence).
2668 iter.next();
2669 MOZ_ASSERT(iter.cur()->is<InstMovT>());
2670 }
2671
2672 iter.next();
2673 MOZ_ASSERT(iter.cur()->is<InstNOP>() || iter.cur()->is<InstBLXReg>());
2674
2675 if (enabled == iter.cur()->is<InstBLXReg>()) {
2676 // Nothing to do.
2677 return;
2678 }
2679
2680 Instruction* inst = iter.cur();
2681
2682 if (enabled) {
2683 *inst = InstBLXReg(ScratchRegister, Always);
2684 } else {
2685 *inst = InstNOP();
2686 }
2687 }
2688
2689 size_t Assembler::ToggledCallSize(uint8_t* code) {
2690 InstructionIterator iter(reinterpret_cast<Instruction*>(code));
2691 MOZ_ASSERT(iter.cur()->is<InstMovW>() || iter.cur()->is<InstLDR>());
2692
2693 if (iter.cur()->is<InstMovW>()) {
2694 // If it looks like the start of a movw/movt sequence, then make sure we
2695 // have all of it (and advance the iterator past the full sequence).
2696 iter.next();
2697 MOZ_ASSERT(iter.cur()->is<InstMovT>());
2698 }
2699
2700 iter.next();
2701 MOZ_ASSERT(iter.cur()->is<InstNOP>() || iter.cur()->is<InstBLXReg>());
2702 return uintptr_t(iter.cur()) + 4 - uintptr_t(code);
2703 }
2704
2705 uint32_t Assembler::NopFill = 0;
2706
2707 uint32_t Assembler::GetNopFill() {
2708 static bool isSet = false;
2709 if (!isSet) {
2710 char* fillStr = getenv("ARM_ASM_NOP_FILL");
2711 uint32_t fill;
2712 if (fillStr && sscanf(fillStr, "%u", &fill) == 1) {
2713 NopFill = fill;
2714 }
2715 if (NopFill > 8) {
2716 MOZ_CRASH("Nop fill > 8 is not supported");
2717 }
2718 isSet = true;
2719 }
2720 return NopFill;
2721 }
2722
2723 uint32_t Assembler::AsmPoolMaxOffset = 1024;
2724
2725 uint32_t Assembler::GetPoolMaxOffset() {
2726 static bool isSet = false;
2727 if (!isSet) {
2728 char* poolMaxOffsetStr = getenv("ASM_POOL_MAX_OFFSET");
2729 uint32_t poolMaxOffset;
2730 if (poolMaxOffsetStr &&
2731 sscanf(poolMaxOffsetStr, "%u", &poolMaxOffset) == 1) {
2732 AsmPoolMaxOffset = poolMaxOffset;
2733 }
2734 isSet = true;
2735 }
2736 return AsmPoolMaxOffset;
2737 }
2738
2739 SecondScratchRegisterScope::SecondScratchRegisterScope(MacroAssembler& masm)
2740 : AutoRegisterScope(masm, masm.getSecondScratchReg()) {}
2741
2742 AutoNonDefaultSecondScratchRegister::AutoNonDefaultSecondScratchRegister(
2743 MacroAssembler& masm, Register reg)
2744 : masm_(masm) {
2745 prevSecondScratch_ = masm.getSecondScratchReg();
2746 masm.setSecondScratchReg(reg);
2747 }
2748
2749 AutoNonDefaultSecondScratchRegister::~AutoNonDefaultSecondScratchRegister() {
2750 masm_.setSecondScratchReg(prevSecondScratch_);
2751 }
2752
2753 #ifdef JS_DISASM_ARM
2754
2755 /* static */
2756 void Assembler::disassembleInstruction(const Instruction* i,
2757 DisasmBuffer& buffer) {
2758 disasm::NameConverter converter;
2759 disasm::Disassembler dasm(converter);
2760 uint8_t* loc = reinterpret_cast<uint8_t*>(const_cast<uint32_t*>(i->raw()));
2761 dasm.InstructionDecode(buffer, loc);
2762 }
2763
2764 void Assembler::initDisassembler() {
2765 // The line is normally laid out like this:
2766 //
2767 // xxxxxxxx ldr r, op ; comment
2768 //
2769 // where xx...x is the instruction bit pattern.
2770 //
2771 // Labels are laid out by themselves to line up with the instructions above
2772 // and below:
2773 //
2774 // nnnn:
2775 //
2776 // Branch targets are normally on the same line as the branch instruction,
2777 // but when they cannot be they will be on a line by themselves, indented
2778 // significantly:
2779 //
2780 // -> label
2781
2782 spew_.setLabelIndent(" "); // 10
2783 spew_.setTargetIndent(" "); // 20
2784 }
2785
2786 void Assembler::finishDisassembler() { spew_.spewOrphans(); }
2787
2788 // Labels are named as they are encountered by adding names to a
2789 // table, using the Label address as the key. This is made tricky by
2790 // the (memory for) Label objects being reused, but reused label
2791 // objects are recognizable from being marked as not used or not
2792 // bound. See spew_.refLabel().
2793 //
2794 // In a number of cases there is no information about the target, and
2795 // we just end up printing "patchable constant load to PC". This is
2796 // true especially for jumps to bailout handlers (which have no
2797 // names). See allocLiteralLoadEntry() and its callers. In some cases
2798 // (loop back edges) some information about the intended target may be
2799 // propagated from higher levels, and if so it's printed here.
2800
2801 void Assembler::spew(Instruction* i) {
2802 if (spew_.isDisabled() || !i) {
2803 return;
2804 }
2805
2806 DisasmBuffer buffer;
2807 disassembleInstruction(i, buffer);
2808 spew_.spew("%s", buffer.start());
2809 }
2810
2811 // If a target label is known, always print that and do not attempt to
2812 // disassemble the branch operands, as they will often be encoding
2813 // metainformation (pointers for a chain of jump instructions), and
2814 // not actual branch targets.
2815
2816 void Assembler::spewBranch(Instruction* i, const LabelDoc& target) {
2817 if (spew_.isDisabled() || !i) {
2818 return;
2819 }
2820
2821 DisasmBuffer buffer;
2822 disassembleInstruction(i, buffer);
2823
2824 char labelBuf[128];
2825 labelBuf[0] = 0;
2826
2827 bool haveTarget = target.valid;
2828 if (!haveTarget) {
2829 SprintfLiteral(labelBuf, " -> (link-time target)");
2830 }
2831
2832 if (InstBranchImm::IsTHIS(*i)) {
2833 InstBranchImm* bimm = InstBranchImm::AsTHIS(*i);
2834 BOffImm destOff;
2835 bimm->extractImm(&destOff);
2836 if (destOff.isInvalid() || haveTarget) {
2837 // The target information in the instruction is likely garbage, so remove
2838 // it. The target label will in any case be printed if we have it.
2839 //
2840 // The format of the instruction disassembly is [0-9a-f]{8}\s+\S+\s+.*,
2841 // where the \S+ string is the opcode. Strip everything after the opcode,
2842 // and attach the label if we have it.
2843 int i;
2844 for (i = 8; i < buffer.length() && buffer[i] == ' '; i++) {
2845 }
2846 for (; i < buffer.length() && buffer[i] != ' '; i++) {
2847 }
2848 buffer[i] = 0;
2849 if (haveTarget) {
2850 SprintfLiteral(labelBuf, " -> %d%s", target.doc,
2851 !target.bound ? "f" : "");
2852 haveTarget = false;
2853 }
2854 }
2855 }
2856 spew_.spew("%s%s", buffer.start(), labelBuf);
2857
2858 if (haveTarget) {
2859 spew_.spewRef(target);
2860 }
2861 }
2862
2863 void Assembler::spewLiteralLoad(PoolHintPun& php, bool loadToPC,
2864 const Instruction* i, const LiteralDoc& doc) {
2865 if (spew_.isDisabled()) {
2866 return;
2867 }
2868
2869 char litbuf[2048];
2870 spew_.formatLiteral(doc, litbuf, sizeof(litbuf));
2871
2872 // See patchConstantPoolLoad, above. We assemble the instruction into a
2873 // buffer with a zero offset, as documentation, but the offset will be
2874 // patched later.
2875
2876 uint32_t inst;
2877 PoolHintData& data = php.phd;
2878 switch (php.phd.getLoadType()) {
2879 case PoolHintData::PoolDTR:
2880 Assembler::as_dtr_patch(IsLoad, 32, Offset, data.getReg(),
2881 DTRAddr(pc, DtrOffImm(0)), data.getCond(), &inst);
2882 break;
2883 case PoolHintData::PoolBranch:
2884 if (data.isValidPoolHint()) {
2885 Assembler::as_dtr_patch(IsLoad, 32, Offset, pc,
2886 DTRAddr(pc, DtrOffImm(0)), data.getCond(),
2887 &inst);
2888 }
2889 break;
2890 case PoolHintData::PoolVDTR:
2891 Assembler::as_vdtr_patch(IsLoad, data.getVFPReg(),
2892 VFPAddr(pc, VFPOffImm(0)), data.getCond(),
2893 &inst);
2894 break;
2895
2896 default:
2897 MOZ_CRASH();
2898 }
2899
2900 DisasmBuffer buffer;
2901 disasm::NameConverter converter;
2902 disasm::Disassembler dasm(converter);
2903 dasm.InstructionDecode(buffer, reinterpret_cast<uint8_t*>(&inst));
2904 spew_.spew("%s ; .const %s", buffer.start(), litbuf);
2905 }
2906
2907 #endif // JS_DISASM_ARM