forked from Shopify/ruby
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmod.rs
More file actions
2899 lines (2573 loc) · 118 KB
/
mod.rs
File metadata and controls
2899 lines (2573 loc) · 118 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::asm::{CodeBlock, Label};
use crate::asm::arm64::*;
use crate::codegen::split_patch_point;
use crate::cruby::*;
use crate::backend::lir::*;
use crate::options::asm_dump;
use crate::stats::CompileError;
use crate::virtualmem::CodePtr;
use crate::cast::*;
// Use the arm64 register type for this platform
pub type Reg = A64Reg;
/// Convert reg_no for MemBase::Reg into Reg, assuming it's a 64-bit register
pub fn mem_base_reg(reg_no: u8) -> Reg {
Reg { num_bits: 64, reg_no }
}
// Callee-saved registers
pub const CFP: Opnd = Opnd::Reg(X19_REG);
pub const EC: Opnd = Opnd::Reg(X20_REG);
pub const SP: Opnd = Opnd::Reg(X21_REG);
// C argument registers on this platform
pub const C_ARG_OPNDS: [Opnd; 6] = [
Opnd::Reg(X0_REG),
Opnd::Reg(X1_REG),
Opnd::Reg(X2_REG),
Opnd::Reg(X3_REG),
Opnd::Reg(X4_REG),
Opnd::Reg(X5_REG)
];
// C return value register on this platform
pub const C_RET_REG: Reg = X0_REG;
pub const C_RET_OPND: Opnd = Opnd::Reg(X0_REG);
pub const NATIVE_STACK_PTR: Opnd = Opnd::Reg(XZR_REG);
pub const NATIVE_BASE_PTR: Opnd = Opnd::Reg(X29_REG);
// These constants define the way we work with Arm64's stack pointer. The stack
// pointer always needs to be aligned to a 16-byte boundary.
pub const C_SP_REG: A64Opnd = X31;
pub const C_SP_STEP: i32 = 16;
impl CodeBlock {
// The maximum number of bytes that can be generated by emit_jmp_ptr.
pub fn jmp_ptr_bytes(&self) -> usize {
// b instruction's offset is encoded as imm26 times 4. It can jump to
// +/-128MiB, so this can be used when --yjit-exec-mem-size <= 128.
/*
let num_insns = if b_offset_fits_bits(self.virtual_region_size() as i64 / 4) {
1 // b instruction
} else {
5 // 4 instructions to load a 64-bit absolute address + br instruction
};
*/
let num_insns = 5; // TODO: support virtual_region_size() check
num_insns * 4
}
// The maximum number of instructions that can be generated by emit_conditional_jump.
fn conditional_jump_insns(&self) -> i32 {
// The worst case is instructions for a jump + bcond.
self.jmp_ptr_bytes() as i32 / 4 + 1
}
}
/// Map Opnd to A64Opnd
impl From<Opnd> for A64Opnd {
fn from(opnd: Opnd) -> Self {
match opnd {
Opnd::UImm(value) => A64Opnd::new_uimm(value),
Opnd::Imm(value) => A64Opnd::new_imm(value),
Opnd::Reg(reg) => A64Opnd::Reg(reg),
Opnd::Mem(Mem { base: MemBase::Reg(reg_no), num_bits, disp }) => {
A64Opnd::new_mem(num_bits, A64Opnd::Reg(A64Reg { num_bits, reg_no }), disp)
},
Opnd::Mem(Mem { base: MemBase::VReg(_), .. }) => {
panic!("attempted to lower an Opnd::Mem with a MemBase::VReg base")
},
Opnd::Mem(Mem { base: MemBase::Stack { .. }, .. }) => {
panic!("attempted to lower an Opnd::Mem with a MemBase::Stack base")
},
Opnd::VReg { .. } => panic!("attempted to lower an Opnd::VReg"),
Opnd::Value(_) => panic!("attempted to lower an Opnd::Value"),
Opnd::None => panic!(
"Attempted to lower an Opnd::None. This often happens when an out operand was not allocated for an instruction because the output of the instruction was not used. Please ensure you are using the output."
),
}
}
}
/// Also implement going from a reference to an operand for convenience.
impl From<&Opnd> for A64Opnd {
fn from(opnd: &Opnd) -> Self {
A64Opnd::from(*opnd)
}
}
/// Call emit_jmp_ptr and immediately invalidate the written range.
/// This is needed when next_page also moves other_cb that is not invalidated
/// by compile_with_regs. Doing it here allows you to avoid invalidating a lot
/// more than necessary when other_cb jumps from a position early in the page.
/// This invalidates a small range of cb twice, but we accept the small cost.
fn emit_jmp_ptr_with_invalidation(cb: &mut CodeBlock, dst_ptr: CodePtr) {
let start = cb.get_write_ptr();
emit_jmp_ptr(cb, dst_ptr, true);
let end = cb.get_write_ptr();
unsafe { rb_jit_icache_invalidate(start.raw_ptr(cb) as _, end.raw_ptr(cb) as _) };
}
fn emit_jmp_ptr(cb: &mut CodeBlock, dst_ptr: CodePtr, padding: bool) {
let src_addr = cb.get_write_ptr().as_offset();
let dst_addr = dst_ptr.as_offset();
// If the offset is short enough, then we'll use the
// branch instruction. Otherwise, we'll move the
// destination into a register and use the branch
// register instruction.
let num_insns = if b_offset_fits_bits((dst_addr - src_addr) / 4) {
b(cb, InstructionOffset::from_bytes((dst_addr - src_addr) as i32));
1
} else {
let num_insns = emit_load_value(cb, Assembler::EMIT_OPND, dst_addr as u64);
br(cb, Assembler::EMIT_OPND);
num_insns + 1
};
if padding {
// Make sure it's always a consistent number of
// instructions in case it gets patched and has to
// use the other branch.
assert!(num_insns * 4 <= cb.jmp_ptr_bytes());
for _ in num_insns..(cb.jmp_ptr_bytes() / 4) {
nop(cb);
}
}
}
/// Emit the required instructions to load the given value into the
/// given register. Our goal here is to use as few instructions as
/// possible to get this value into the register.
fn emit_load_value(cb: &mut CodeBlock, rd: A64Opnd, value: u64) -> usize {
let mut current = value;
if current <= 0xffff {
// If the value fits into a single movz
// instruction, then we'll use that.
movz(cb, rd, A64Opnd::new_uimm(current), 0);
1
} else if u16::try_from(!value).is_ok() {
// For small negative values, use a single movn
movn(cb, rd, A64Opnd::new_uimm(!value), 0);
1
} else if BitmaskImmediate::try_from(current).is_ok() {
// Otherwise, if the immediate can be encoded
// with the special bitmask immediate encoding,
// we'll use that.
mov(cb, rd, A64Opnd::new_uimm(current));
1
} else {
// Finally we'll fall back to encoding the value
// using movz for the first 16 bits and movk for
// each subsequent set of 16 bits as long we
// they are necessary.
movz(cb, rd, A64Opnd::new_uimm(current & 0xffff), 0);
let mut num_insns = 1;
// (We're sure this is necessary since we
// checked if it only fit into movz above).
current >>= 16;
movk(cb, rd, A64Opnd::new_uimm(current & 0xffff), 16);
num_insns += 1;
if current > 0xffff {
current >>= 16;
movk(cb, rd, A64Opnd::new_uimm(current & 0xffff), 32);
num_insns += 1;
}
if current > 0xffff {
current >>= 16;
movk(cb, rd, A64Opnd::new_uimm(current & 0xffff), 48);
num_insns += 1;
}
num_insns
}
}
/// List of registers that can be used for register allocation.
/// This has the same number of registers for x86_64 and arm64.
/// SCRATCH_OPND, SCRATCH1_OPND, and EMIT_OPND are excluded.
pub const ALLOC_REGS: &[Reg] = &[
X0_REG,
X1_REG,
X2_REG,
X3_REG,
X4_REG,
X5_REG,
X11_REG,
X12_REG,
];
/// Special scratch registers for intermediate processing. They should be used only by
/// [`Assembler::arm64_scratch_split`] or [`Assembler::new_with_scratch_reg`].
const SCRATCH0_OPND: Opnd = Opnd::Reg(X15_REG);
const SCRATCH1_OPND: Opnd = Opnd::Reg(X17_REG);
const SCRATCH2_OPND: Opnd = Opnd::Reg(X14_REG);
impl Assembler {
/// Special register for intermediate processing in arm64_emit. It should be used only by arm64_emit.
const EMIT_REG: Reg = X16_REG;
const EMIT_OPND: A64Opnd = A64Opnd::Reg(Self::EMIT_REG);
/// Return an Assembler with scratch registers disabled in the backend, and a scratch register.
pub fn new_with_scratch_reg() -> (Self, Opnd) {
(Self::new_with_accept_scratch_reg(true), SCRATCH0_OPND)
}
/// Return true if opnd contains a scratch reg
pub fn has_scratch_reg(opnd: Opnd) -> bool {
Self::has_reg(opnd, SCRATCH0_OPND.unwrap_reg())
}
/// Get the list of registers from which we will allocate on this platform
pub fn get_alloc_regs() -> Vec<Reg> {
ALLOC_REGS.to_vec()
}
/// Get a list of all of the caller-saved registers
pub fn get_caller_save_regs() -> Vec<Reg> {
vec![X1_REG, X9_REG, X10_REG, X11_REG, X12_REG, X13_REG, X14_REG, X15_REG]
}
/// How many bytes a call and a [Self::frame_setup] would change native SP
pub fn frame_size() -> i32 {
0x10
}
/// Split platform-specific instructions
/// The transformations done here are meant to make our lives simpler in later
/// stages of the compilation pipeline.
/// Here we may want to make sure that all instructions (except load and store)
/// have no memory operands.
fn arm64_split(mut self) -> Assembler
{
/// When you're storing a register into a memory location or loading a
/// memory location into a register, the displacement from the base
/// register of the memory location must fit into 9 bits. If it doesn't,
/// then we need to load that memory address into a register first.
fn split_memory_address(asm: &mut Assembler, opnd: Opnd) -> Opnd {
match opnd {
Opnd::Mem(mem) => {
if mem_disp_fits_bits(mem.disp) {
opnd
} else {
let base = asm.lea(Opnd::Mem(Mem { num_bits: 64, ..mem }));
Opnd::mem(mem.num_bits, base, 0)
}
},
_ => unreachable!("Can only split memory addresses.")
}
}
/// Any memory operands you're sending into an Op::Load instruction need
/// to be split in case their displacement doesn't fit into 9 bits.
fn split_load_operand(asm: &mut Assembler, opnd: Opnd) -> Opnd {
match opnd {
Opnd::Reg(_) | Opnd::VReg { .. } => opnd,
Opnd::Mem(_) => {
let split_opnd = split_memory_address(asm, opnd);
let out_opnd = asm.load(split_opnd);
// Many Arm insns support only 32-bit or 64-bit operands. asm.load with fewer
// bits zero-extends the value, so it's safe to recognize it as a 32-bit value.
if out_opnd.rm_num_bits() < 32 {
out_opnd.with_num_bits(32)
} else {
out_opnd
}
},
_ => asm.load(opnd)
}
}
/// Operands that take the place of bitmask immediates must follow a
/// certain encoding. In this function we ensure that those operands
/// do follow that encoding, and if they don't then we load them first.
fn split_bitmask_immediate(asm: &mut Assembler, opnd: Opnd, dest_num_bits: u8) -> Opnd {
match opnd {
Opnd::Reg(_) | Opnd::VReg { .. } => opnd,
Opnd::Mem(_) => split_load_operand(asm, opnd),
Opnd::Imm(imm) => {
if imm == 0 {
Opnd::Reg(XZR_REG)
} else if (dest_num_bits == 64 &&
BitmaskImmediate::try_from(imm as u64).is_ok()) ||
(dest_num_bits == 32 &&
u32::try_from(imm).is_ok() &&
BitmaskImmediate::new_32b_reg(imm as u32).is_ok()) {
Opnd::UImm(imm as u64)
} else {
asm.load(opnd).with_num_bits(dest_num_bits)
}
},
Opnd::UImm(uimm) => {
if (dest_num_bits == 64 && BitmaskImmediate::try_from(uimm).is_ok()) ||
(dest_num_bits == 32 &&
u32::try_from(uimm).is_ok() &&
BitmaskImmediate::new_32b_reg(uimm as u32).is_ok()) {
opnd
} else {
asm.load(opnd).with_num_bits(dest_num_bits)
}
},
Opnd::None | Opnd::Value(_) => unreachable!()
}
}
/// Operands that take the place of a shifted immediate must fit within
/// a certain size. If they don't then we need to load them first.
fn split_shifted_immediate(asm: &mut Assembler, opnd: Opnd) -> Opnd {
match opnd {
Opnd::Reg(_) | Opnd::VReg { .. } => opnd,
Opnd::Mem(_) => split_load_operand(asm, opnd),
Opnd::Imm(imm) => if ShiftedImmediate::try_from(imm as u64).is_ok() {
opnd
} else {
asm.load(opnd)
}
Opnd::UImm(uimm) => {
if ShiftedImmediate::try_from(uimm).is_ok() {
opnd
} else {
asm.load(opnd)
}
},
Opnd::None | Opnd::Value(_) => unreachable!()
}
}
/// Returns the operands that should be used for a boolean logic
/// instruction.
fn split_boolean_operands(asm: &mut Assembler, opnd0: Opnd, opnd1: Opnd) -> (Opnd, Opnd) {
match (opnd0, opnd1) {
(Opnd::Reg(_), Opnd::Reg(_)) => {
(opnd0, opnd1)
},
(reg_opnd @ Opnd::Reg(_), other_opnd) |
(other_opnd, reg_opnd @ Opnd::Reg(_)) => {
let opnd1 = split_bitmask_immediate(asm, other_opnd, reg_opnd.rm_num_bits());
(reg_opnd, opnd1)
},
_ => {
let opnd0 = split_load_operand(asm, opnd0);
let opnd1 = split_bitmask_immediate(asm, opnd1, opnd0.rm_num_bits());
(opnd0, opnd1)
}
}
}
/// Returns the operands that should be used for a csel instruction.
fn split_csel_operands(asm: &mut Assembler, opnd0: Opnd, opnd1: Opnd) -> (Opnd, Opnd) {
let opnd0 = match opnd0 {
Opnd::Reg(_) | Opnd::VReg { .. } => opnd0,
_ => split_load_operand(asm, opnd0)
};
let opnd1 = match opnd1 {
Opnd::Reg(_) | Opnd::VReg { .. } => opnd1,
_ => split_load_operand(asm, opnd1)
};
(opnd0, opnd1)
}
fn split_less_than_32_cmp(asm: &mut Assembler, opnd0: Opnd) -> Opnd {
match opnd0 {
Opnd::Reg(_) | Opnd::VReg { .. } => {
match opnd0.rm_num_bits() {
8 => asm.and(opnd0.with_num_bits(64), Opnd::UImm(0xff)),
16 => asm.and(opnd0.with_num_bits(64), Opnd::UImm(0xffff)),
32 | 64 => opnd0,
bits => unreachable!("Invalid number of bits. {}", bits)
}
}
_ => opnd0
}
}
let mut asm_local = Assembler::new_with_asm(&self);
let live_ranges = self.compute_live_ranges();
let mut iterator = self.instruction_iterator();
let asm = &mut asm_local;
while let Some((index, mut insn)) = iterator.next(asm) {
// Here we're going to map the operands of the instruction to load
// any Opnd::Value operands into registers if they are heap objects
// such that only the Op::Load instruction needs to handle that
// case. If the values aren't heap objects then we'll treat them as
// if they were just unsigned integer.
let is_load = matches!(insn, Insn::Load { .. } | Insn::LoadInto { .. });
let mut opnd_iter = insn.opnd_iter_mut();
while let Some(opnd) = opnd_iter.next() {
if let Opnd::Value(value) = opnd {
if value.special_const_p() {
*opnd = Opnd::UImm(value.as_u64());
} else if !is_load {
*opnd = asm.load(*opnd);
}
};
}
// We are replacing instructions here so we know they are already
// being used. It is okay not to use their output here.
#[allow(unused_must_use)]
match &mut insn {
Insn::Add { left, right, out } => {
match (*left, *right) {
// When one operand is a register, legalize the other operand
// into possibly an immdiate and swap the order if necessary.
// Only the rhs of ADD can be an immediate, but addition is commutative.
(reg_opnd @ (Opnd::Reg(_) | Opnd::VReg { .. }), other_opnd) |
(other_opnd, reg_opnd @ (Opnd::Reg(_) | Opnd::VReg { .. })) => {
*left = reg_opnd;
*right = split_shifted_immediate(asm, other_opnd);
// Now `right` is either a register or an immediate, both can try to
// merge with a subsequent mov.
merge_three_reg_mov(&live_ranges, &mut iterator, asm, left, left, out);
asm.push_insn(insn);
}
_ => {
*left = split_load_operand(asm, *left);
*right = split_shifted_immediate(asm, *right);
merge_three_reg_mov(&live_ranges, &mut iterator, asm, left, right, out);
asm.push_insn(insn);
}
}
}
Insn::Sub { left, right, out } => {
*left = split_load_operand(asm, *left);
*right = split_shifted_immediate(asm, *right);
// Now `right` is either a register or an immediate,
// both can try to merge with a subsequent mov.
merge_three_reg_mov(&live_ranges, &mut iterator, asm, left, left, out);
asm.push_insn(insn);
}
Insn::And { left, right, out } |
Insn::Or { left, right, out } |
Insn::Xor { left, right, out } => {
let (opnd0, opnd1) = split_boolean_operands(asm, *left, *right);
*left = opnd0;
*right = opnd1;
merge_three_reg_mov(&live_ranges, &mut iterator, asm, left, right, out);
asm.push_insn(insn);
}
/*
// Lower to Joz and Jonz for generating CBZ/CBNZ for compare-with-0-and-branch.
ref insn @ Insn::Cmp { ref left, right: ref right @ (Opnd::UImm(0) | Opnd::Imm(0)) } |
ref insn @ Insn::Test { ref left, right: ref right @ (Opnd::InsnOut { .. } | Opnd::Reg(_)) } if {
let same_opnd_if_test = if let Insn::Test { .. } = insn {
left == right
} else {
true
};
same_opnd_if_test && if let Some(
Insn::Jz(target) | Insn::Je(target) | Insn::Jnz(target) | Insn::Jne(target)
) = iterator.peek() {
matches!(target, Target::SideExit { .. })
} else {
false
}
} => {
let reg = split_load_operand(asm, *left);
match iterator.peek() {
Some(Insn::Jz(target) | Insn::Je(target)) => asm.push_insn(Insn::Joz(reg, *target)),
Some(Insn::Jnz(target) | Insn::Jne(target)) => asm.push_insn(Insn::Jonz(reg, *target)),
_ => ()
}
iterator.map_insn_index(asm);
iterator.next_unmapped(); // Pop merged jump instruction
}
*/
Insn::CCall { opnds, .. } => {
assert!(opnds.len() <= C_ARG_OPNDS.len());
// Load each operand into the corresponding argument
// register.
// Note: the iteration order is reversed to avoid corrupting x0,
// which is both the return value and first argument register
if !opnds.is_empty() {
let mut args: Vec<(Opnd, Opnd)> = vec![];
for (idx, opnd) in opnds.iter_mut().enumerate().rev() {
// If the value that we're sending is 0, then we can use
// the zero register, so in this case we'll just send
// a UImm of 0 along as the argument to the move.
let value = match opnd {
Opnd::UImm(0) | Opnd::Imm(0) => Opnd::UImm(0),
Opnd::Mem(_) => split_memory_address(asm, *opnd),
_ => *opnd
};
args.push((C_ARG_OPNDS[idx], value));
}
asm.parallel_mov(args);
}
// Now we push the CCall without any arguments so that it
// just performs the call.
*opnds = vec![];
asm.push_insn(insn);
},
Insn::Cmp { left, right } => {
let opnd0 = split_load_operand(asm, *left);
let opnd0 = split_less_than_32_cmp(asm, opnd0);
let split_right = split_shifted_immediate(asm, *right);
let opnd1 = match split_right {
Opnd::VReg { .. } if opnd0.num_bits() != split_right.num_bits() => {
split_right.with_num_bits(opnd0.num_bits().unwrap())
},
_ => split_right
};
asm.cmp(opnd0, opnd1);
},
Insn::CRet(opnd) => {
match opnd {
// If the value is already in the return register, then
// we don't need to do anything.
Opnd::Reg(C_RET_REG) => {},
// If the value is a memory address, we need to first
// make sure the displacement isn't too large and then
// load it into the return register.
Opnd::Mem(_) => {
let split = split_memory_address(asm, *opnd);
asm.load_into(C_RET_OPND, split);
},
// Otherwise we just need to load the value into the
// return register.
_ => {
asm.load_into(C_RET_OPND, *opnd);
}
}
asm.cret(C_RET_OPND);
},
Insn::CSelZ { truthy, falsy, out } |
Insn::CSelNZ { truthy, falsy, out } |
Insn::CSelE { truthy, falsy, out } |
Insn::CSelNE { truthy, falsy, out } |
Insn::CSelL { truthy, falsy, out } |
Insn::CSelLE { truthy, falsy, out } |
Insn::CSelG { truthy, falsy, out } |
Insn::CSelGE { truthy, falsy, out } => {
let (opnd0, opnd1) = split_csel_operands(asm, *truthy, *falsy);
*truthy = opnd0;
*falsy = opnd1;
// Merge `csel` and `mov` into a single `csel` when possible
match iterator.peek().map(|(_, insn)| insn) {
Some(Insn::Mov { dest: Opnd::Reg(reg), src })
if matches!(out, Opnd::VReg { .. }) && *out == *src && live_ranges[out.vreg_idx()].end() == index + 1 => {
*out = Opnd::Reg(*reg);
asm.push_insn(insn);
iterator.next(asm); // Pop merged Insn::Mov
}
_ => {
asm.push_insn(insn);
}
}
},
Insn::JmpOpnd(opnd) => {
if let Opnd::Mem(_) = opnd {
let opnd0 = split_load_operand(asm, *opnd);
asm.jmp_opnd(opnd0);
} else {
asm.jmp_opnd(*opnd);
}
},
Insn::Load { opnd, .. } |
Insn::LoadInto { opnd, .. } => {
*opnd = match opnd {
Opnd::Mem(_) => split_memory_address(asm, *opnd),
_ => *opnd
};
asm.push_insn(insn);
},
Insn::LoadSExt { opnd, out } => {
match opnd {
// We only want to sign extend if the operand is a
// register, instruction output, or memory address that
// is 32 bits. Otherwise we'll just load the value
// directly since there's no need to sign extend.
Opnd::Reg(Reg { num_bits: 32, .. }) |
Opnd::VReg { num_bits: 32, .. } |
Opnd::Mem(Mem { num_bits: 32, .. }) => {
asm.push_insn(insn);
},
_ => {
asm.push_insn(Insn::Load { opnd: *opnd, out: *out });
}
};
},
Insn::Mov { dest, src } => {
match (&dest, &src) {
// If we're attempting to load into a memory operand, then
// we'll switch over to the store instruction.
(Opnd::Mem(_), _) => {
let opnd0 = split_memory_address(asm, *dest);
let value = match *src {
// If the first operand is zero, then we can just use
// the zero register.
Opnd::UImm(0) | Opnd::Imm(0) => Opnd::Reg(XZR_REG),
// If the first operand is a memory operand, we're going
// to transform this into a store instruction, so we'll
// need to load this anyway.
Opnd::UImm(_) => asm.load(*src),
// The value that is being moved must be either a
// register or an immediate that can be encoded as a
// bitmask immediate. Otherwise, we'll need to split the
// move into multiple instructions.
_ => split_bitmask_immediate(asm, *src, dest.rm_num_bits())
};
asm.store(opnd0, value);
},
// If we're loading a memory operand into a register, then
// we'll switch over to the load instruction.
(Opnd::Reg(_) | Opnd::VReg { .. }, Opnd::Mem(_)) => {
let value = split_memory_address(asm, *src);
asm.load_into(*dest, value);
},
// Otherwise we'll use the normal mov instruction.
(Opnd::Reg(_), _) => {
let value = match *src {
// Unlike other instructions, we can avoid splitting this case, using movz.
Opnd::UImm(uimm) if uimm <= 0xffff => *src,
_ => split_bitmask_immediate(asm, *src, dest.rm_num_bits()),
};
asm.mov(*dest, value);
},
_ => unreachable!("unexpected combination of operands in Insn::Mov: {dest:?}, {src:?}")
};
},
Insn::Not { opnd, .. } => {
// The value that is being negated must be in a register, so
// if we get anything else we need to load it first.
*opnd = match opnd {
Opnd::Mem(_) => split_load_operand(asm, *opnd),
_ => *opnd
};
asm.push_insn(insn);
},
Insn::LShift { opnd, .. } |
Insn::RShift { opnd, .. } |
Insn::URShift { opnd, .. } => {
// The operand must be in a register, so
// if we get anything else we need to load it first.
*opnd = split_load_operand(asm, *opnd);
asm.push_insn(insn);
},
Insn::Mul { left, right, .. } => {
*left = split_load_operand(asm, *left);
*right = split_load_operand(asm, *right);
asm.push_insn(insn);
},
Insn::Test { left, right } => {
// The value being tested must be in a register, so if it's
// not already one we'll load it first.
let opnd0 = split_load_operand(asm, *left);
// The second value must be either a register or an
// unsigned immediate that can be encoded as a bitmask
// immediate. If it's not one of those, we'll need to load
// it first.
let opnd1 = split_bitmask_immediate(asm, *right, opnd0.rm_num_bits());
asm.test(opnd0, opnd1);
},
_ => {
asm.push_insn(insn);
}
}
}
asm_local
}
/// Split instructions using scratch registers. To maximize the use of the register pool for
/// VRegs, most splits should happen in [`Self::arm64_split`]. However, some instructions
/// need to be split with registers after `alloc_regs`, e.g. for `compile_exits`, so this
/// splits them and uses scratch registers for it.
/// Linearizes all blocks into a single giant block.
fn arm64_scratch_split(self) -> Assembler {
/// If opnd is Opnd::Mem with a too large disp, make the disp smaller using lea.
fn split_large_disp(asm: &mut Assembler, opnd: Opnd, scratch_opnd: Opnd) -> Opnd {
match opnd {
Opnd::Mem(Mem { num_bits, disp, .. }) if !mem_disp_fits_bits(disp) => {
asm.lea_into(scratch_opnd, opnd);
Opnd::mem(num_bits, scratch_opnd, 0)
}
_ => opnd,
}
}
/// If opnd is Opnd::Mem with MemBase::Stack, lower it to Opnd::Mem with MemBase::Reg, and split a large disp.
fn split_stack_membase(asm: &mut Assembler, opnd: Opnd, scratch_opnd: Opnd, stack_state: &StackState) -> Opnd {
let opnd = split_only_stack_membase(asm, opnd, scratch_opnd, stack_state);
split_large_disp(asm, opnd, scratch_opnd)
}
/// split_stack_membase but without split_large_disp. This should be used only by lea.
fn split_only_stack_membase(asm: &mut Assembler, opnd: Opnd, scratch_opnd: Opnd, stack_state: &StackState) -> Opnd {
if let Opnd::Mem(Mem { base: stack_membase @ MemBase::Stack { .. }, disp: opnd_disp, num_bits: opnd_num_bits }) = opnd {
let base = Opnd::Mem(stack_state.stack_membase_to_mem(stack_membase));
let base = split_large_disp(asm, base, scratch_opnd);
asm.load_into(scratch_opnd, base);
Opnd::Mem(Mem { base: MemBase::Reg(scratch_opnd.unwrap_reg().reg_no), disp: opnd_disp, num_bits: opnd_num_bits })
} else {
opnd
}
}
/// If opnd is Opnd::Mem, lower it to scratch_opnd. You should use this when `opnd` is read by the instruction, not written.
fn split_memory_read(asm: &mut Assembler, opnd: Opnd, scratch_opnd: Opnd) -> Opnd {
if let Opnd::Mem(_) = opnd {
let opnd = split_large_disp(asm, opnd, scratch_opnd);
let scratch_opnd = opnd.num_bits().map(|num_bits| scratch_opnd.with_num_bits(num_bits)).unwrap_or(scratch_opnd);
asm.load_into(scratch_opnd, opnd);
scratch_opnd
} else {
opnd
}
}
/// If opnd is Opnd::Mem, set scratch_reg to *opnd. Return Some(Opnd::Mem) if it needs to be written back from scratch_reg.
fn split_memory_write(opnd: &mut Opnd, scratch_opnd: Opnd) -> Option<Opnd> {
if let Opnd::Mem(_) = opnd {
let mem_opnd = opnd.clone();
*opnd = opnd.num_bits().map(|num_bits| scratch_opnd.with_num_bits(num_bits)).unwrap_or(scratch_opnd);
Some(mem_opnd)
} else {
None
}
}
// Prepare StackState to lower MemBase::Stack
let stack_state = StackState::new(self.stack_base_idx);
let mut asm_local = Assembler::new();
asm_local.accept_scratch_reg = true;
asm_local.stack_base_idx = self.stack_base_idx;
asm_local.label_names = self.label_names.clone();
asm_local.live_ranges = LiveRanges::new(self.live_ranges.len());
// Create one giant block to linearize everything into
asm_local.new_block_without_id();
let asm = &mut asm_local;
// Get linearized instructions with branch parameters expanded into ParallelMov
let linearized_insns = self.linearize_instructions();
// Process each linearized instruction
for (idx, insn) in linearized_insns.iter().enumerate() {
let mut insn = insn.clone();
match &mut insn {
Insn::Add { left, right, out } |
Insn::Sub { left, right, out } |
Insn::And { left, right, out } |
Insn::Or { left, right, out } |
Insn::Xor { left, right, out } |
Insn::CSelZ { truthy: left, falsy: right, out } |
Insn::CSelNZ { truthy: left, falsy: right, out } |
Insn::CSelE { truthy: left, falsy: right, out } |
Insn::CSelNE { truthy: left, falsy: right, out } |
Insn::CSelL { truthy: left, falsy: right, out } |
Insn::CSelLE { truthy: left, falsy: right, out } |
Insn::CSelG { truthy: left, falsy: right, out } |
Insn::CSelGE { truthy: left, falsy: right, out } => {
*left = split_memory_read(asm, *left, SCRATCH0_OPND);
*right = split_memory_read(asm, *right, SCRATCH1_OPND);
let mem_out = split_memory_write(out, SCRATCH0_OPND);
asm.push_insn(insn);
if let Some(mem_out) = mem_out {
let mem_out = split_large_disp(asm, mem_out, SCRATCH1_OPND);
asm.store(mem_out, SCRATCH0_OPND);
}
}
Insn::Mul { left, right, out } => {
*left = split_memory_read(asm, *left, SCRATCH0_OPND);
*right = split_memory_read(asm, *right, SCRATCH1_OPND);
let mem_out = split_memory_write(out, SCRATCH0_OPND);
let reg_out = out.clone();
asm.push_insn(insn);
if let Some(mem_out) = mem_out {
let mem_out = split_large_disp(asm, mem_out, SCRATCH1_OPND);
asm.store(mem_out, SCRATCH0_OPND);
};
// If the next instruction is JoMul
if idx + 1 < linearized_insns.len() && matches!(linearized_insns[idx + 1], Insn::JoMul(_)) {
// Produce a register that is all zeros or all ones
// Based on the sign bit of the 64-bit mul result
asm.push_insn(Insn::RShift { out: SCRATCH0_OPND, opnd: reg_out, shift: Opnd::UImm(63) });
}
}
Insn::LShift { opnd, out, .. } |
Insn::RShift { opnd, out, .. } => {
*opnd = split_memory_read(asm, *opnd, SCRATCH0_OPND);
let mem_out = split_memory_write(out, SCRATCH0_OPND);
asm.push_insn(insn);
if let Some(mem_out) = mem_out {
let mem_out = split_large_disp(asm, mem_out, SCRATCH1_OPND);
asm.store(mem_out, SCRATCH0_OPND);
}
}
Insn::Cmp { left, right } |
Insn::Test { left, right } => {
*left = split_memory_read(asm, *left, SCRATCH0_OPND);
*right = split_memory_read(asm, *right, SCRATCH1_OPND);
asm.push_insn(insn);
}
// For compile_exits, support splitting simple C arguments here
Insn::CCall { opnds, .. } if !opnds.is_empty() => {
for (i, opnd) in opnds.iter().enumerate() {
asm.load_into(C_ARG_OPNDS[i], *opnd);
}
*opnds = vec![];
asm.push_insn(insn);
}
// For compile_exits, support splitting simple return values here
Insn::CRet(opnd) => {
match opnd {
Opnd::Reg(C_RET_REG) => {},
_ => asm.load_into(C_RET_OPND, *opnd),
}
asm.cret(C_RET_OPND);
}
Insn::Lea { opnd, out } => {
*opnd = split_only_stack_membase(asm, *opnd, SCRATCH0_OPND, &stack_state);
let mem_out = split_memory_write(out, SCRATCH0_OPND);
asm.push_insn(insn);
if let Some(mem_out) = mem_out {
let mem_out = split_large_disp(asm, mem_out, SCRATCH1_OPND);
asm.store(mem_out, SCRATCH0_OPND);
}
}
Insn::Load { opnd, out } |
Insn::LoadInto { opnd, dest: out } => {
*opnd = split_stack_membase(asm, *opnd, SCRATCH0_OPND, &stack_state);
*out = split_stack_membase(asm, *out, SCRATCH1_OPND, &stack_state);
if let Opnd::Mem(_) = out {
// If NATIVE_STACK_PTR is used as a source for Store, it's handled as xzr, storeing zero.
// To save the content of NATIVE_STACK_PTR, we need to load it into another register first.
if *opnd == NATIVE_STACK_PTR {
asm.load_into(SCRATCH0_OPND, NATIVE_STACK_PTR);
*opnd = SCRATCH0_OPND;
}
asm.store(*out, *opnd);
} else {
asm.push_insn(insn);
}
}
&mut Insn::IncrCounter { mem, value } => {
// Convert Opnd::const_ptr into Opnd::Mem.
// It's split here to support IncrCounter in compile_exits.
assert!(matches!(mem, Opnd::UImm(_)));
asm.load_into(SCRATCH0_OPND, mem);
asm.lea_into(SCRATCH0_OPND, Opnd::mem(64, SCRATCH0_OPND, 0));
// Create a local loop to atomically increment a counter using SCRATCH1_OPND to check if it succeeded.
// Note that arm64_emit will peek at the next Cmp to set a status into SCRATCH1_OPND on IncrCounter.
let label = asm.new_label("incr_counter_loop");
asm.write_label(label.clone());
asm.incr_counter(SCRATCH0_OPND, value);
asm.cmp(SCRATCH1_OPND, 0.into());
asm.jne(label);
}
Insn::Store { dest, .. } => {
*dest = split_stack_membase(asm, *dest, SCRATCH0_OPND, &stack_state);
asm.push_insn(insn);
}
Insn::Mov { dest, src } => {
*src = split_stack_membase(asm, *src, SCRATCH0_OPND, &stack_state);
*dest = split_large_disp(asm, *dest, SCRATCH1_OPND);
match dest {
Opnd::Reg(_) => asm.load_into(*dest, *src),
Opnd::Mem(_) => asm.store(*dest, *src),
_ => asm.push_insn(insn),
}
}
// Resolve ParallelMov that couldn't be handled without a scratch register.
Insn::ParallelMov { moves } => {
for (dst, src) in Self::resolve_parallel_moves(moves, Some(SCRATCH0_OPND)).unwrap() {
let src = split_stack_membase(asm, src, SCRATCH1_OPND, &stack_state);
let dst = split_large_disp(asm, dst, SCRATCH2_OPND);
match dst {
Opnd::Reg(_) => asm.load_into(dst, src),
Opnd::Mem(_) => asm.store(dst, src),
_ => asm.mov(dst, src),
}
}
}
&mut Insn::PatchPoint { ref target, invariant, version } => {
split_patch_point(asm, target, invariant, version);
}
_ => {
asm.push_insn(insn);
}
}
}
asm_local
}
/// Emit platform-specific machine code
/// Returns a list of GC offsets. Can return failure to signal caller to retry.
fn arm64_emit(&mut self, cb: &mut CodeBlock) -> Option<Vec<CodePtr>> {
/// Determine how many instructions it will take to represent moving
/// this value into a register. Note that the return value of this
/// function must correspond to how many instructions are used to
/// represent this load in the emit_load_value function.
fn emit_load_size(value: u64) -> u8 {
if BitmaskImmediate::try_from(value).is_ok() {
return 1;
}
if value < (1 << 16) {
1
} else if value < (1 << 32) {
2
} else if value < (1 << 48) {
3
} else {
4
}
}
/// Emit a conditional jump instruction to a specific target. This is
/// called when lowering any of the conditional jump instructions.
fn emit_conditional_jump<const CONDITION: u8>(asm: &Assembler, cb: &mut CodeBlock, target: Target) {
fn generate_branch<const CONDITION: u8>(cb: &mut CodeBlock, src_addr: i64, dst_addr: i64) {
let num_insns = if bcond_offset_fits_bits((dst_addr - src_addr) / 4) {
// If the jump offset fits into the conditional jump as
// an immediate value and it's properly aligned, then we
// can use the b.cond instruction directly. We're safe
// to use as i32 here since we already checked that it
// fits.
let bytes = (dst_addr - src_addr) as i32;
bcond(cb, CONDITION, InstructionOffset::from_bytes(bytes));
// Here we're going to return 1 because we've only
// written out 1 instruction.
1
} else if b_offset_fits_bits((dst_addr - (src_addr + 4)) / 4) { // + 4 for bcond
// If the jump offset fits into the unconditional jump as
// an immediate value, we can use inverse b.cond + b.
//
// We're going to write out the inverse condition so
// that if it doesn't match it will skip over the
// instruction used for branching.
bcond(cb, Condition::inverse(CONDITION), 2.into());
b(cb, InstructionOffset::from_bytes((dst_addr - (src_addr + 4)) as i32)); // + 4 for bcond
// We've only written out 2 instructions.
2
} else {
// Otherwise, we need to load the address into a
// register and use the branch register instruction.
let load_insns: i32 = emit_load_size(dst_addr as u64).into();
// We're going to write out the inverse condition so
// that if it doesn't match it will skip over the
// instructions used for branching.
bcond(cb, Condition::inverse(CONDITION), (load_insns + 2).into());
emit_load_value(cb, Assembler::EMIT_OPND, dst_addr as u64);
br(cb, Assembler::EMIT_OPND);
// Here we'll return the number of instructions that it
// took to write out the destination address + 1 for the
// b.cond and 1 for the br.
load_insns + 2
};
// We need to make sure we have at least 6 instructions for
// every kind of jump for invalidation purposes, so we're
// going to write out padding nop instructions here.
assert!(num_insns <= cb.conditional_jump_insns());