-
Notifications
You must be signed in to change notification settings - Fork 7
/
mod.rs
3295 lines (3100 loc) · 118 KB
/
mod.rs
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
//! The X64 JIT Code Generator.
//!
//! Conventions used in this module:
//! * Functions with a `cg_X` prefix generate code for a [jit_ir] construct `X`.
//! * Helper functions arguments are in order `(<destination>, <source_1>, ... <source_n>)`.
//!
//! FIXME: the code generator clobbers registers willy-nilly because at the time of writing we have
//! a register allocator that doesn't actually use any registers. Later we will have to audit the
//! backend and insert register save/restore for clobbered registers.
use super::{
super::{
int_signs::{SignExtend, Truncate},
jit_ir::{self, BinOp, FloatTy, InstIdx, Module, Operand, Ty},
CompilationError,
},
reg_alloc::{self, StackDirection, VarLocation},
CodeGen,
};
#[cfg(any(debug_assertions, test))]
use crate::compile::jitc_yk::gdb::{self, GdbCtx};
use crate::{
aotsmp::AOT_STACKMAPS,
compile::{
jitc_yk::{
aot_ir,
jit_ir::{Const, IndirectCallIdx, InlinedFrame},
RootTracePtr, YkSideTraceInfo,
},
CompiledTrace, Guard, GuardIdx, SideTraceInfo,
},
location::{HotLocation, HotLocationKind},
mt::MT,
};
use dynasmrt::{
components::StaticLabel,
dynasm,
x64::{Rq, Rx},
AssemblyOffset, DynamicLabel, DynasmApi, DynasmError, DynasmLabelApi, ExecutableBuffer,
Register,
};
use indexmap::IndexMap;
use parking_lot::Mutex;
use std::sync::{Arc, Weak};
use std::{cell::Cell, slice};
use std::{collections::HashMap, error::Error};
use ykaddr::addr::symbol_to_ptr;
use yksmp;
mod deopt;
mod lsregalloc;
use deopt::{__yk_deopt, __yk_guardcheck, __yk_reenter_jit};
use lsregalloc::{LSRegAlloc, RegConstraint, RegSet};
/// General purpose argument registers as defined by the x64 SysV ABI.
static ARG_GP_REGS: [Rq; 6] = [Rq::RDI, Rq::RSI, Rq::RDX, Rq::RCX, Rq::R8, Rq::R9];
/// The registers clobbered by a function call in the x64 SysV ABI.
static CALLER_CLOBBER_REGS: [Rq; 9] = [
Rq::RAX,
Rq::RCX,
Rq::RDX,
Rq::RSI,
Rq::RDI,
Rq::R8,
Rq::R9,
Rq::R10,
Rq::R11,
];
/// Floating point argument registers as defined by the x64 SysV ABI.
static ARG_FP_REGS: [Rx; 8] = [
Rx::XMM0,
Rx::XMM1,
Rx::XMM2,
Rx::XMM3,
Rx::XMM4,
Rx::XMM5,
Rx::XMM6,
Rx::XMM7,
];
/// Registers used by stackmaps to store live variables.
static STACKMAP_GP_REGS: [Rq; 7] = [
Rq::RBX,
Rq::R12,
Rq::R13,
Rq::R14,
Rq::R15,
Rq::RSI,
Rq::RDI,
];
/// The argument index of the live variables struct argument in the JITted code function.
static JITFUNC_LIVEVARS_ARGIDX: usize = 0;
/// The size of a 64-bit register in bytes.
pub(crate) static REG64_SIZE: usize = 8;
static RBP_DWARF_NUM: u16 = 6;
/// The x64 SysV ABI requires a 16-byte aligned stack prior to any call.
const SYSV_CALL_STACK_ALIGN: usize = 16;
/// On x64 the stack grows down.
const STACK_DIRECTION: StackDirection = StackDirection::GrowsDown;
/// A function that we can put a debugger breakpoint on.
/// FIXME: gross hack.
#[cfg(debug_assertions)]
#[no_mangle]
#[inline(never)]
pub extern "C" fn __yk_break() {}
/// A simple front end for the X64 code generator.
pub(crate) struct X64CodeGen;
impl CodeGen for X64CodeGen {
fn codegen(
&self,
m: Module,
mt: Arc<MT>,
hl: Arc<Mutex<HotLocation>>,
sp_offset: Option<usize>,
) -> Result<Arc<dyn CompiledTrace>, CompilationError> {
Assemble::new(&m, sp_offset)?.codegen(mt, hl, sp_offset.is_some())
}
}
impl X64CodeGen {
pub(crate) fn new() -> Result<Arc<Self>, Box<dyn Error>> {
Ok(Arc::new(Self))
}
}
/// The x64 code generator.
struct Assemble<'a> {
m: &'a jit_ir::Module,
ra: LSRegAlloc<'a>,
/// The locations of the live variables at the beginning of the loop.
loop_start_locs: Vec<VarLocation>,
asm: dynasmrt::x64::Assembler,
/// Deopt info, with one entry per guard, in the order that the guards appear in the trace.
deoptinfo: HashMap<usize, DeoptInfo>,
///
/// Maps assembly offsets to comments.
///
/// Comments used by the trace printer for debugging and testing only.
///
/// Each assembly offset can have zero or more comment lines.
comments: Cell<IndexMap<usize, Vec<String>>>,
/// Stack pointer offset from the base pointer of the interpreter frame. If this is a root
/// trace it's initialised to the size of the interpreter frame. Otherwise its value is passed
/// in via [YkSideTraceInfo::sp_offset].
sp_offset: usize,
}
impl<'a> Assemble<'a> {
fn new(
m: &'a jit_ir::Module,
sp_offset: Option<usize>,
) -> Result<Box<Assemble<'a>>, CompilationError> {
#[cfg(debug_assertions)]
m.assert_well_formed();
let asm = dynasmrt::x64::Assembler::new()
.map_err(|e| CompilationError::ResourceExhausted(Box::new(e)))?;
// Since we are executing the trace in the main interpreter frame we need this to
// initialise the trace's register allocator in order to access local variables.
let sp_offset = if let Some(off) = sp_offset {
// This is a side-trace. Use the passed in stack size to initialise the register
// allocator.
off
} else {
// This is a normal trace, so we need to retrieve the stack size of the main
// interpreter frame.
// FIXME: For now the control point stackmap id is always 0. Though
// we likely want to support multiple control points in the future. We can either pass
// the correct stackmap id in via the control point, or compute the stack size
// dynamically upon entering the control point (e.g. by subtracting the current RBP
// from the previous RBP).
if let Ok(sm) = AOT_STACKMAPS.as_ref() {
let (rec, pinfo) = sm.get(0);
let size = if pinfo.hasfp {
// The frame size includes the pushed RBP, but since we only care about the size of
// the local variables we need to subtract it again.
rec.size - u64::try_from(REG64_SIZE).unwrap()
} else {
rec.size
};
usize::try_from(size).unwrap()
} else {
// The unit tests in this file don't have AOT code. So if we don't find stackmaps here
// that's ok. In real-world programs and our C-tests this shouldn't happen though.
#[cfg(not(test))]
panic!("Couldn't find AOT stackmaps.");
#[cfg(test)]
0
}
};
Ok(Box::new(Self {
m,
ra: LSRegAlloc::new(m, sp_offset),
asm,
loop_start_locs: Vec::new(),
deoptinfo: HashMap::new(),
comments: Cell::new(IndexMap::new()),
sp_offset,
}))
}
fn codegen(
mut self: Box<Self>,
mt: Arc<MT>,
hl: Arc<Mutex<HotLocation>>,
issidetrace: bool,
) -> Result<Arc<dyn CompiledTrace>, CompilationError> {
if issidetrace {
// Recover registers.
for reg in lsregalloc::FP_REGS.iter() {
dynasm!(self.asm
; pop rcx
; movq Rx(reg.code()), rcx
);
}
for reg in lsregalloc::GP_REGS.iter() {
dynasm!(self.asm; pop Rq(reg.code()));
}
// Re-align stack. This was misaligned when we pushed RSI in the guard failure routine.
// This isn't really neccessary since we are aligning the stack when we calculate the
// stack size for this trace. However, this removes the pushed RSI register which
// serves no further pupose at this point.
dynasm!(self.asm; add rsp, 8);
}
let alloc_off = self.emit_prologue();
for (iidx, inst) in self.m.iter_skipping_insts() {
self.ra.expire_regs(iidx);
self.cg_inst(iidx, inst)?;
}
if !self.deoptinfo.is_empty() {
// We now have to construct the "full" deopt points. Inside the trace itself, are just
// a pair of instructions: a `cmp` followed by a `jnz` to a `fail_label` that has not
// yet been defined. We now have to construct a full call to `__yk_deopt` for each of
// those labels. Since, in general, we'll have multiple guards, we construct a simple
// stub which puts an ID in a register then JMPs to (shared amongst all guards) code
// which does the full call to __yk_deopt.
#[allow(unused_mut)] // `mut` required in debug builds. See below.
let mut infos = self
.deoptinfo
.iter()
.map(|(id, l)| (*id, l.fail_label))
.collect::<Vec<_>>();
// Debugging deopt asm is much easier if the stubs are in order.
#[cfg(debug_assertions)]
infos.sort_by(|a, b| a.0.cmp(&b.0));
let guardcheck_label = self.asm.new_dynamic_label();
for (deoptid, fail_label) in infos {
self.comment(
self.asm.offset(),
format!("Deopt ID for guard {:?}", deoptid),
);
// FIXME: Why are `deoptid`s 64 bit? We're not going to have that many guards!
let deoptid = i32::try_from(deoptid).unwrap();
dynasm!(self.asm
;=> fail_label
; push rsi // FIXME: We push RSI now so we can fish it back out in
// `deopt_label`.
; mov rsi, deoptid
; jmp => guardcheck_label
);
}
let deopt_label = self.asm.new_dynamic_label();
self.comment(self.asm.offset(), "Call __yk_deopt".to_string());
// Clippy points out that `__yk_depot as i64` isn't portable, but since this entire module
// is x86 only, we don't need to worry about portability.
#[allow(clippy::fn_to_numeric_cast)]
{
dynasm!(self.asm; => guardcheck_label);
// Push all the general purpose registers to the stack.
for (i, reg) in lsregalloc::GP_REGS.iter().rev().enumerate() {
if *reg == Rq::RSI {
// RSI is handled differently in `fail_label`: RSI now contains the deopt
// ID, so we have to fish the actual value out of the stack. See the FIXME
// in `fail_label`.
let off = i32::try_from(i * 8).unwrap();
dynasm!(self.asm; push QWORD [rsp + off]);
} else {
dynasm!(self.asm; push Rq(reg.code()));
}
}
dynasm!(self.asm; mov rdx, rsp);
for reg in lsregalloc::FP_REGS.iter().rev() {
dynasm!(self.asm
; movq rcx, Rx(reg.code())
; push rcx
);
}
dynasm!(self.asm; mov rcx, rsp);
// Check whether we need to deoptimise or jump into a side-trace.
dynasm!(self.asm
; push rsi // Save `deoptid`.
; push rdx // Save `gp_regs` pointer.
; push rcx // Save `fp_regs` pointer.
; mov rdi, rsi
; mov rax, QWORD __yk_guardcheck as i64
; call rax
; pop rcx
; pop rdx
; pop rsi
; cmp rax, 0
; je => deopt_label
);
// Jump into side-trace. The side-trace takes care of recovering the saved
// registers.
dynasm!(self.asm
; jmp rax
);
// Deoptimise.
dynasm!(self.asm; => deopt_label);
dynasm!(self.asm
; mov rdi, rbp
; mov rax, QWORD __yk_deopt as i64
; sub rsp, 8 // Align the stack
; call rax
);
}
}
// Now we know the size of the stack frame (i.e. self.asp), patch the allocation with the
// correct amount.
self.patch_frame_allocation(alloc_off);
// If an error happens here, we've made a mistake in the assembly we generate.
self.asm
.commit()
.map_err(|e| CompilationError::InternalError(format!("When committing: {e}")))?;
// This unwrap cannot fail if `commit` (above) succeeded.
let buf = self.asm.finalize().unwrap();
#[cfg(any(debug_assertions, test))]
let gdb_ctx = gdb::register_jitted_code(
self.m.ctr_id(),
buf.ptr(AssemblyOffset(0)),
buf.size(),
self.comments.get_mut(),
)?;
Ok(Arc::new(X64CompiledTrace {
mt,
buf,
deoptinfo: self.deoptinfo,
sp_offset: self.ra.stack_size(),
entry_vars: self.loop_start_locs.clone(),
hl: Arc::downgrade(&hl),
comments: self.comments.take(),
#[cfg(any(debug_assertions, test))]
gdb_ctx,
}))
}
/// Codegen an instruction.
fn cg_inst(
&mut self,
iidx: jit_ir::InstIdx,
inst: &jit_ir::Inst,
) -> Result<(), CompilationError> {
self.comment(self.asm.offset(), inst.display(iidx, self.m).to_string());
match inst {
#[cfg(test)]
jit_ir::Inst::BlackBox(_) => unreachable!(),
jit_ir::Inst::Const(_) | jit_ir::Inst::Copy(_) | jit_ir::Inst::Tombstone => {
unreachable!();
}
jit_ir::Inst::BinOp(i) => self.cg_binop(iidx, i),
jit_ir::Inst::LoadTraceInput(i) => self.cg_loadtraceinput(iidx, i),
jit_ir::Inst::Load(i) => self.cg_load(iidx, i),
jit_ir::Inst::PtrAdd(i) => self.cg_ptradd(iidx, i),
jit_ir::Inst::DynPtrAdd(i) => self.cg_dynptradd(iidx, i),
jit_ir::Inst::Store(i) => self.cg_store(iidx, i),
jit_ir::Inst::LookupGlobal(i) => self.cg_lookupglobal(iidx, i),
jit_ir::Inst::Call(i) => self.cg_call(iidx, i)?,
jit_ir::Inst::IndirectCall(i) => self.cg_indirectcall(iidx, i)?,
jit_ir::Inst::ICmp(i) => self.cg_icmp(iidx, i),
jit_ir::Inst::Guard(i) => self.cg_guard(iidx, i),
jit_ir::Inst::TraceLoopStart => self.cg_traceloopstart(),
jit_ir::Inst::TraceLoopJump => self.cg_traceloopjump(),
jit_ir::Inst::RootJump => self.cg_rootjump(self.m.root_jump_addr()),
jit_ir::Inst::SExt(i) => self.cg_sext(iidx, i),
jit_ir::Inst::ZeroExtend(i) => self.cg_zeroextend(iidx, i),
jit_ir::Inst::Trunc(i) => self.cg_trunc(iidx, i),
jit_ir::Inst::Select(i) => self.cg_select(iidx, i),
jit_ir::Inst::SIToFP(i) => self.cg_sitofp(iidx, i),
jit_ir::Inst::FPExt(i) => self.cg_fpext(iidx, i),
jit_ir::Inst::FCmp(i) => self.cg_fcmp(iidx, i),
jit_ir::Inst::FPToSI(i) => self.cg_fptosi(iidx, i),
}
Ok(())
}
/// Add a comment to the trace, for use when disassembling its native code.
fn comment(&mut self, off: AssemblyOffset, line: String) {
self.comments.get_mut().entry(off.0).or_default().push(line);
}
/// Emit the prologue of the JITted code.
///
/// The JITted code is executed inside the same frame as the main interpreter loop. This allows
/// us to easily access live variables on that frame's stack. Because of this we don't need to
/// create a new frame here, though we do need to make space for any extra stack space this
/// trace needs.
///
/// Note that there is no correspoinding `emit_epilogue()`. This is because the only way out of
/// JITted code is via deoptimisation, which will rewrite the whole stack anyway.
///
/// Returns the offset at which to patch up the stack allocation later.
fn emit_prologue(&mut self) -> AssemblyOffset {
self.comment(self.asm.offset(), "prologue".to_owned());
// Emit a dummy frame allocation instruction that initially allocates 0 bytes, but will be
// patched later when we know how big the frame needs to be.
let alloc_off = self.asm.offset();
dynasm!(self.asm
; sub rsp, DWORD 0
);
// In debug mode, add a call to `__yk_break` to make debugging easier. Note that this
// clobbers r11 (a caller saved register).
#[cfg(debug_assertions)]
{
self.comment(self.asm.offset(), "Breakpoint hack".into());
// Clippy points out that `__yk_depot as i64` isn't portable, but since this entire
// module is x86 only, we don't need to worry about portability.
#[allow(clippy::fn_to_numeric_cast)]
{
dynasm!(self.asm
; push r11
; mov r11, QWORD __yk_break as i64
; call r11
; pop r11
);
}
}
alloc_off
}
fn patch_frame_allocation(&mut self, asm_off: AssemblyOffset) {
// The stack should be 16-byte aligned after allocation. This ensures that calls in the
// trace also get a 16-byte aligned stack, as per the SysV ABI.
// Since we initialise the register allocator with interpreter frame and parent trace
// frames, the actual size we need to substract from RSP is the difference between the
// current stack size and the base size we inherited.
let stack_size = self.ra.align_stack(SYSV_CALL_STACK_ALIGN) - self.sp_offset;
match i32::try_from(stack_size) {
Ok(asp) => {
let mut patchup = self.asm.alter_uncommitted();
patchup.goto(asm_off);
dynasm!(patchup
// The size of this instruction must be the exactly the same as the dummy
// allocation instruction that was emitted during `emit_prologue()`.
; sub rsp, DWORD asp
);
}
Err(_) => {
// If we get here, then the frame was so big that the dummy instruction we had
// planned to patch isn't big enough to encode the desired allocation size. Cross
// this bridge if/when we get to it.
todo!();
}
}
}
fn cg_binop(&mut self, iidx: jit_ir::InstIdx, inst: &jit_ir::BinOpInst) {
let lhs = inst.lhs(self.m);
let rhs = inst.rhs(self.m);
match inst.binop() {
BinOp::Add => {
let byte_size = lhs.byte_size(self.m);
match (&lhs, &rhs) {
(Operand::Const(cidx), Operand::Var(_))
| (Operand::Var(_), Operand::Const(cidx)) => {
// Addition involves a constant. We may be able to emit more optimal code.
let Const::Int(ctyidx, v) = self.m.const_(*cidx) else {
unreachable!()
};
let Ty::Integer(bit_size) = self.m.type_(*ctyidx) else {
unreachable!()
};
// If it's a 64-bit add and the numeric value of the constant can be
// expressed in 32-bits...
//
// We are only optimising (exactly) 64-bit add operations for now, but
// there is certainly oppertunity to optimised other cases later.
//
// We could have used Rust `as` casts to truncate and sign-extend here,
// since we are currently only dealing with i32s and i64s, but if/when we
// want to cover operations on other "odd-bit-size" integers we will need
// these custom implementations.
if *bit_size == 64 && v.truncate(32).sign_extend(32, 64) == *v {
let v32 = v.truncate(32);
let [lhs_reg] = self.ra.assign_gp_regs(
&mut self.asm,
iidx,
[RegConstraint::InputOutput(lhs)],
);
dynasm!(self.asm; add Rq(lhs_reg.code()), v32 as i32);
return;
}
// Same optimisation, but for 32-bit add.
//
// This time the constant fits by definition.
if *bit_size == 32 {
let v32 = v.truncate(32);
let [lhs_reg] = self.ra.assign_gp_regs(
&mut self.asm,
iidx,
[RegConstraint::InputOutput(lhs)],
);
dynasm!(self.asm; add Rd(lhs_reg.code()), v32 as i32);
return;
}
}
_ => (),
}
let [lhs_reg, rhs_reg] = self.ra.assign_gp_regs(
&mut self.asm,
iidx,
[RegConstraint::InputOutput(lhs), RegConstraint::Input(rhs)],
);
match byte_size {
1 => dynasm!(self.asm; add Rb(lhs_reg.code()), Rb(rhs_reg.code())),
2 => dynasm!(self.asm; add Rw(lhs_reg.code()), Rw(rhs_reg.code())),
4 => dynasm!(self.asm; add Rd(lhs_reg.code()), Rd(rhs_reg.code())),
8 => dynasm!(self.asm; add Rq(lhs_reg.code()), Rq(rhs_reg.code())),
_ => todo!(),
}
}
BinOp::And => {
let size = lhs.byte_size(self.m);
let [lhs_reg, rhs_reg] = self.ra.assign_gp_regs(
&mut self.asm,
iidx,
[RegConstraint::InputOutput(lhs), RegConstraint::Input(rhs)],
);
match size {
1 => dynasm!(self.asm; and Rb(lhs_reg.code()), Rb(rhs_reg.code())),
2 => dynasm!(self.asm; and Rw(lhs_reg.code()), Rw(rhs_reg.code())),
4 => dynasm!(self.asm; and Rd(lhs_reg.code()), Rd(rhs_reg.code())),
8 => dynasm!(self.asm; and Rq(lhs_reg.code()), Rq(rhs_reg.code())),
_ => todo!(),
}
}
BinOp::AShr => {
let size = lhs.byte_size(self.m);
let [lhs_reg, _rhs_reg] = self.ra.assign_gp_regs(
&mut self.asm,
iidx,
[
RegConstraint::InputOutput(lhs),
RegConstraint::InputIntoReg(rhs, Rq::RCX),
],
);
debug_assert_eq!(_rhs_reg, Rq::RCX);
match size {
1 => dynasm!(self.asm; sar Rb(lhs_reg.code()), cl),
2 => dynasm!(self.asm; sar Rw(lhs_reg.code()), cl),
4 => dynasm!(self.asm; sar Rd(lhs_reg.code()), cl),
8 => dynasm!(self.asm; sar Rq(lhs_reg.code()), cl),
_ => todo!(),
}
}
BinOp::LShr => {
let size = lhs.byte_size(self.m);
let [lhs_reg, _rhs_reg] = self.ra.assign_gp_regs(
&mut self.asm,
iidx,
[
RegConstraint::InputOutput(lhs),
RegConstraint::InputIntoReg(rhs, Rq::RCX),
],
);
debug_assert_eq!(_rhs_reg, Rq::RCX);
match size {
1 => dynasm!(self.asm; shr Rb(lhs_reg.code()), cl),
2 => dynasm!(self.asm; shr Rw(lhs_reg.code()), cl),
4 => dynasm!(self.asm; shr Rd(lhs_reg.code()), cl),
8 => dynasm!(self.asm; shr Rq(lhs_reg.code()), cl),
_ => todo!(),
}
}
BinOp::Shl => {
let size = lhs.byte_size(self.m);
let [lhs_reg, _rhs_reg] = self.ra.assign_gp_regs(
&mut self.asm,
iidx,
[
RegConstraint::InputOutput(lhs),
RegConstraint::InputIntoReg(rhs, Rq::RCX),
],
);
debug_assert_eq!(_rhs_reg, Rq::RCX);
match size {
1 => dynasm!(self.asm; shl Rb(lhs_reg.code()), cl),
2 => dynasm!(self.asm; shl Rw(lhs_reg.code()), cl),
4 => dynasm!(self.asm; shl Rd(lhs_reg.code()), cl),
8 => dynasm!(self.asm; shl Rq(lhs_reg.code()), cl),
_ => todo!(),
}
}
BinOp::Mul => {
let size = lhs.byte_size(self.m);
self.ra
.clobber_gp_regs_hack(&mut self.asm, iidx, &[Rq::RDX]);
let [_lhs_reg, rhs_reg] = self.ra.assign_gp_regs_avoiding(
&mut self.asm,
iidx,
[
RegConstraint::InputOutputIntoReg(lhs, Rq::RAX),
RegConstraint::Input(rhs),
],
RegSet::from(Rq::RDX),
);
debug_assert_eq!(_lhs_reg, Rq::RAX);
match size {
1 => dynasm!(self.asm; mul Rb(rhs_reg.code())),
2 => dynasm!(self.asm; mul Rw(rhs_reg.code())),
4 => dynasm!(self.asm; mul Rd(rhs_reg.code())),
8 => dynasm!(self.asm; mul Rq(rhs_reg.code())),
_ => todo!(),
}
// Note that because we are code-genning an unchecked multiply, the higher-order part of
// the result in RDX is entirely ignored.
}
BinOp::Or => {
let size = lhs.byte_size(self.m);
let [lhs_reg, rhs_reg] = self.ra.assign_gp_regs(
&mut self.asm,
iidx,
[RegConstraint::InputOutput(lhs), RegConstraint::Input(rhs)],
);
match size {
1 => dynasm!(self.asm; or Rb(lhs_reg.code()), Rb(rhs_reg.code())),
2 => dynasm!(self.asm; or Rw(lhs_reg.code()), Rw(rhs_reg.code())),
4 => dynasm!(self.asm; or Rd(lhs_reg.code()), Rd(rhs_reg.code())),
8 => dynasm!(self.asm; or Rq(lhs_reg.code()), Rq(rhs_reg.code())),
_ => todo!(),
}
}
BinOp::SDiv => {
let size = lhs.byte_size(self.m);
self.ra
.clobber_gp_regs_hack(&mut self.asm, iidx, &[Rq::RDX]);
let [_lhs_reg, rhs_reg] = self.ra.assign_gp_regs_avoiding(
&mut self.asm,
iidx,
[
// The quotient is stored in RAX. We don't care about the remainder stored
// in RDX.
RegConstraint::InputOutputIntoReg(lhs, Rq::RAX),
RegConstraint::Input(rhs),
],
RegSet::from(Rq::RDX),
);
// The dividend is hard-coded into DX:AX/EDX:EAX/RDX:RAX. However unless we have 128bit
// values or want to optimise register usage, we won't be needing this, and just zero out
// RDX.
// Signed division (idiv) operates on the DX:AX, EDX:EAX, RDX:RAX registers, so we
// use `cdq`/`cqo` to double the size via sign extension and store the result in
// DX:AX, EDX:EAX, RDX:RAX.
match size {
// There's no `cwd` equivalent for byte-sized values, so we use `movsx`
// (sign-extend) instead.
1 => dynasm!(self.asm; movsx ax, al; idiv Rb(rhs_reg.code())),
2 => dynasm!(self.asm; cwd; idiv Rw(rhs_reg.code())),
4 => dynasm!(self.asm; cdq; idiv Rd(rhs_reg.code())),
8 => dynasm!(self.asm; cqo; idiv Rq(rhs_reg.code())),
_ => todo!(),
}
}
BinOp::SRem => {
// The dividend is hard-coded into DX:AX/EDX:EAX/RDX:RAX. However unless we have 128bit
// values or want to optimise register usage, we won't be needing this, and just zero out
// RDX.
let size = lhs.byte_size(self.m);
debug_assert!(size == 4 || size == 8);
let [_lhs_reg, rhs_reg, _rem_reg] = self.ra.assign_gp_regs(
&mut self.asm,
iidx,
[
RegConstraint::InputIntoRegAndClobber(lhs, Rq::RAX),
RegConstraint::Input(rhs),
RegConstraint::OutputFromReg(Rq::RDX),
],
);
debug_assert_eq!(_lhs_reg, Rq::RAX);
debug_assert_eq!(_rem_reg, Rq::RDX);
dynasm!(self.asm; xor rdx, rdx);
match size {
1 => dynasm!(self.asm; idiv Rb(rhs_reg.code())),
2 => dynasm!(self.asm; idiv Rw(rhs_reg.code())),
4 => dynasm!(self.asm; idiv Rd(rhs_reg.code())),
8 => dynasm!(self.asm; idiv Rq(rhs_reg.code())),
_ => todo!(),
}
// The remainder is stored in RDX. We don't care about the quotient stored in RAX.
}
BinOp::Sub => {
let size = lhs.byte_size(self.m);
let [lhs_reg, rhs_reg] = self.ra.assign_gp_regs(
&mut self.asm,
iidx,
[RegConstraint::InputOutput(lhs), RegConstraint::Input(rhs)],
);
match size {
1 => dynasm!(self.asm; sub Rb(lhs_reg.code()), Rb(rhs_reg.code())),
2 => dynasm!(self.asm; sub Rw(lhs_reg.code()), Rw(rhs_reg.code())),
4 => dynasm!(self.asm; sub Rd(lhs_reg.code()), Rd(rhs_reg.code())),
8 => dynasm!(self.asm; sub Rq(lhs_reg.code()), Rq(rhs_reg.code())),
_ => todo!(),
}
}
BinOp::Xor => {
let size = lhs.byte_size(self.m);
let [lhs_reg, rhs_reg] = self.ra.assign_gp_regs(
&mut self.asm,
iidx,
[RegConstraint::InputOutput(lhs), RegConstraint::Input(rhs)],
);
match size {
1 => dynasm!(self.asm; xor Rb(lhs_reg.code()), Rb(rhs_reg.code())),
2 => dynasm!(self.asm; xor Rw(lhs_reg.code()), Rw(rhs_reg.code())),
4 => dynasm!(self.asm; xor Rd(lhs_reg.code()), Rd(rhs_reg.code())),
8 => dynasm!(self.asm; xor Rq(lhs_reg.code()), Rq(rhs_reg.code())),
_ => todo!(),
}
}
BinOp::UDiv => {
let size = lhs.byte_size(self.m);
self.ra
.clobber_gp_regs_hack(&mut self.asm, iidx, &[Rq::RDX]);
let [_lhs_reg, rhs_reg] = self.ra.assign_gp_regs_avoiding(
&mut self.asm,
iidx,
[
// The quotient is stored in RAX. We don't care about the remainder stored
// in RDX.
RegConstraint::InputOutputIntoReg(lhs, Rq::RAX),
RegConstraint::Input(rhs),
],
RegSet::from(Rq::RDX),
);
debug_assert_eq!(_lhs_reg, Rq::RAX);
// Like SDiv the dividend goes into AX, DX:AX, EDX:EAX, RDX:RAX. But since the
// values aren't signed we don't need to sign-extend them and can just zero out
// `rdx`.
dynasm!(self.asm; xor rdx, rdx);
match size {
1 => dynasm!(self.asm; div Rb(rhs_reg.code())),
2 => dynasm!(self.asm; div Rw(rhs_reg.code())),
4 => dynasm!(self.asm; div Rd(rhs_reg.code())),
8 => dynasm!(self.asm; div Rq(rhs_reg.code())),
_ => todo!(),
}
}
BinOp::FDiv => {
let size = lhs.byte_size(self.m);
let [lhs_reg, rhs_reg] = self.ra.assign_fp_regs(
&mut self.asm,
iidx,
[RegConstraint::InputOutput(lhs), RegConstraint::Input(rhs)],
);
match size {
4 => dynasm!(self.asm; divss Rx(lhs_reg.code()), Rx(rhs_reg.code())),
8 => dynasm!(self.asm; divsd Rx(lhs_reg.code()), Rx(rhs_reg.code())),
_ => todo!(),
}
}
BinOp::FAdd => {
let size = lhs.byte_size(self.m);
let [lhs_reg, rhs_reg] = self.ra.assign_fp_regs(
&mut self.asm,
iidx,
[RegConstraint::InputOutput(lhs), RegConstraint::Input(rhs)],
);
match size {
4 => dynasm!(self.asm; addss Rx(lhs_reg.code()), Rx(rhs_reg.code())),
8 => dynasm!(self.asm; addsd Rx(lhs_reg.code()), Rx(rhs_reg.code())),
_ => todo!(),
}
}
BinOp::FMul => {
let size = lhs.byte_size(self.m);
let [lhs_reg, rhs_reg] = self.ra.assign_fp_regs(
&mut self.asm,
iidx,
[RegConstraint::InputOutput(lhs), RegConstraint::Input(rhs)],
);
match size {
4 => dynasm!(self.asm; mulss Rx(lhs_reg.code()), Rx(rhs_reg.code())),
8 => dynasm!(self.asm; mulsd Rx(lhs_reg.code()), Rx(rhs_reg.code())),
_ => todo!(),
}
}
BinOp::FSub => {
let size = lhs.byte_size(self.m);
let [lhs_reg, rhs_reg] = self.ra.assign_fp_regs(
&mut self.asm,
iidx,
[RegConstraint::InputOutput(lhs), RegConstraint::Input(rhs)],
);
match size {
4 => dynasm!(self.asm; subss Rx(lhs_reg.code()), Rx(rhs_reg.code())),
8 => dynasm!(self.asm; subsd Rx(lhs_reg.code()), Rx(rhs_reg.code())),
_ => todo!(),
}
}
x => todo!("{x:?}"),
}
}
/// Codegen a [jit_ir::LoadTraceInputInst]. This only informs the register allocator about the
/// locations of live variables without generating any actual machine code.
fn cg_loadtraceinput(&mut self, iidx: jit_ir::InstIdx, inst: &jit_ir::LoadTraceInputInst) {
let m = match &self.m.tilocs()[usize::try_from(inst.locidx()).unwrap()] {
yksmp::Location::Register(0, ..) => {
VarLocation::Register(reg_alloc::Register::GP(Rq::RAX))
}
yksmp::Location::Register(1, ..) => {
// Since the control point passes the stackmap ID via RDX this case only happens in
// side-traces.
VarLocation::Register(reg_alloc::Register::GP(Rq::RDX))
}
yksmp::Location::Register(2, ..) => {
VarLocation::Register(reg_alloc::Register::GP(Rq::RCX))
}
yksmp::Location::Register(3, ..) => {
VarLocation::Register(reg_alloc::Register::GP(Rq::RBX))
}
yksmp::Location::Register(4, ..) => {
VarLocation::Register(reg_alloc::Register::GP(Rq::RSI))
}
yksmp::Location::Register(5, ..) => {
VarLocation::Register(reg_alloc::Register::GP(Rq::RDI))
}
yksmp::Location::Register(8, ..) => {
VarLocation::Register(reg_alloc::Register::GP(Rq::R8))
}
yksmp::Location::Register(9, ..) => {
VarLocation::Register(reg_alloc::Register::GP(Rq::R9))
}
yksmp::Location::Register(10, ..) => {
VarLocation::Register(reg_alloc::Register::GP(Rq::R10))
}
yksmp::Location::Register(11, ..) => {
VarLocation::Register(reg_alloc::Register::GP(Rq::R11))
}
yksmp::Location::Register(12, ..) => {
VarLocation::Register(reg_alloc::Register::GP(Rq::R12))
}
yksmp::Location::Register(13, ..) => {
VarLocation::Register(reg_alloc::Register::GP(Rq::R13))
}
yksmp::Location::Register(14, ..) => {
VarLocation::Register(reg_alloc::Register::GP(Rq::R14))
}
yksmp::Location::Register(15, ..) => {
VarLocation::Register(reg_alloc::Register::GP(Rq::R15))
}
yksmp::Location::Register(x, ..) if *x >= 17 && *x <= 32 => VarLocation::Register(
reg_alloc::Register::FP(lsregalloc::FP_REGS[usize::from(x - 17)]),
),
yksmp::Location::Direct(6, off, size) => VarLocation::Direct {
frame_off: *off,
size: usize::from(*size),
},
// Since the trace shares the same stack frame as the main interpreter loop, we can
// translate indirect locations into normal stack locations. Note that while stackmaps
// use negative offsets, we use positive offsets for stack locations.
yksmp::Location::Indirect(6, off, size) => VarLocation::Stack {
frame_off: u32::try_from(*off * -1).unwrap(),
size: usize::from(*size),
},
yksmp::Location::Constant(v) => {
// FIXME: This isn't fine-grained enough, as there may be constants of any
// bit-size.
let size = self.m.inst_no_copies(iidx).def_byte_size(self.m);
match size {
4 => VarLocation::ConstInt {
bits: 32,
v: u64::from(*v),
},
_ => todo!(),
}
}
e => {
todo!("{:?}", e);
}
};
let size = self.m.inst_no_copies(iidx).def_byte_size(self.m);
debug_assert!(size <= REG64_SIZE);
match m {
VarLocation::Register(reg_alloc::Register::GP(reg)) => {
self.ra.force_assign_inst_gp_reg(iidx, reg);
}
VarLocation::Register(reg_alloc::Register::FP(reg)) => {
self.ra.force_assign_inst_fp_reg(iidx, reg);
}
VarLocation::Direct { frame_off, size: _ } => {
self.ra.force_assign_inst_direct(iidx, frame_off);
}
VarLocation::Stack { frame_off, size: _ } => {
self.ra
.force_assign_inst_indirect(iidx, i32::try_from(frame_off).unwrap());
}
VarLocation::ConstInt { bits, v } => {
self.ra.assign_const(iidx, bits, v);
}
e => panic!("{:?}", e),
}
}
fn cg_load(&mut self, iidx: jit_ir::InstIdx, inst: &jit_ir::LoadInst) {
match self.m.type_(inst.tyidx()) {
Ty::Integer(_) | Ty::Ptr => {
let [reg] = self.ra.assign_gp_regs(
&mut self.asm,
iidx,
[RegConstraint::InputOutput(inst.operand(self.m))],
);
let size = self.m.inst_no_copies(iidx).def_byte_size(self.m);
debug_assert!(size <= REG64_SIZE);
match size {
1 => dynasm!(self.asm ; movzx Rq(reg.code()), BYTE [Rq(reg.code())]),
2 => dynasm!(self.asm ; movzx Rq(reg.code()), WORD [Rq(reg.code())]),
4 => dynasm!(self.asm ; mov Rd(reg.code()), [Rq(reg.code())]),
8 => dynasm!(self.asm ; mov Rq(reg.code()), [Rq(reg.code())]),
_ => todo!("{}", size),
};
}
Ty::Float(fty) => {
let [src_reg] = self.ra.assign_gp_regs(
&mut self.asm,
iidx,
[RegConstraint::Input(inst.operand(self.m))],
);
let [tgt_reg] =
self.ra
.assign_fp_regs(&mut self.asm, iidx, [RegConstraint::Output]);
match fty {
FloatTy::Float => {
dynasm!(self.asm; movss Rx(tgt_reg.code()), [Rq(src_reg.code())])
}
FloatTy::Double => {
dynasm!(self.asm; movsd Rx(tgt_reg.code()), [Rq(src_reg.code())])
}
}
}
x => todo!("{x:?}"),
}
}
fn cg_ptradd(&mut self, iidx: jit_ir::InstIdx, inst: &jit_ir::PtrAddInst) {
// LLVM semantics dictate that the offset should be sign-extended/truncated up/down to the
// size of the LLVM pointer index type. For address space zero on x86, truncation can't
// happen, and when an immediate second operand is used for x86_64 `add`, it is implicitly
// sign extended.
let [reg] = self.ra.assign_gp_regs(
&mut self.asm,
iidx,
[RegConstraint::InputOutput(inst.ptr(self.m))],
);
dynasm!(self.asm ; add Rq(reg.code()), inst.off());
}
fn cg_dynptradd(&mut self, iidx: jit_ir::InstIdx, inst: &jit_ir::DynPtrAddInst) {
let [num_elems_reg, ptr_reg] = self.ra.assign_gp_regs(
&mut self.asm,
iidx,
[
RegConstraint::InputOutput(inst.num_elems(self.m)),
RegConstraint::Input(inst.ptr(self.m)),
],
);