-
Notifications
You must be signed in to change notification settings - Fork 5.4k
/
Copy pathcodegen.rs
9403 lines (7944 loc) · 317 KB
/
codegen.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
// We use the YARV bytecode constants which have a CRuby-style name
#![allow(non_upper_case_globals)]
use crate::asm::*;
use crate::backend::ir::*;
use crate::core::*;
use crate::cruby::*;
use crate::invariants::*;
use crate::options::*;
use crate::stats::*;
use crate::utils::*;
use CodegenStatus::*;
use YARVOpnd::*;
use std::cell::Cell;
use std::cmp;
use std::cmp::min;
use std::collections::HashMap;
use std::ffi::CStr;
use std::mem;
use std::os::raw::c_int;
use std::ptr;
use std::rc::Rc;
use std::cell::RefCell;
use std::slice;
pub use crate::virtualmem::CodePtr;
/// Status returned by code generation functions
#[derive(PartialEq, Debug)]
enum CodegenStatus {
KeepCompiling,
EndBlock,
}
/// Code generation function signature
type InsnGenFn = fn(
jit: &mut JITState,
asm: &mut Assembler,
ocb: &mut OutlinedCb,
) -> Option<CodegenStatus>;
/// Ephemeral code generation state.
/// Represents a [core::Block] while we build it.
pub struct JITState {
/// Instruction sequence for the compiling block
iseq: IseqPtr,
/// The iseq index of the first instruction in the block
starting_insn_idx: IseqIdx,
/// The [Context] entering into the first instruction of the block
starting_ctx: Context,
/// The placement for the machine code of the [Block]
output_ptr: CodePtr,
/// Index of the current instruction being compiled
insn_idx: IseqIdx,
/// Opcode for the instruction being compiled
opcode: usize,
/// PC of the instruction being compiled
pc: *mut VALUE,
/// stack_size when it started to compile the current instruction.
stack_size_for_pc: u8,
/// Execution context when compilation started
/// This allows us to peek at run-time values
ec: EcPtr,
/// The outgoing branches the block will have
pub pending_outgoing: Vec<PendingBranchRef>,
// --- Fields for block invalidation and invariants tracking below:
// Public mostly so into_block defined in the sibling module core
// can partially move out of Self.
/// Whether we need to record the code address at
/// the end of this bytecode instruction for global invalidation
pub record_boundary_patch_point: bool,
/// Code for immediately exiting upon entry to the block.
/// Required for invalidation.
pub block_entry_exit: Option<CodePtr>,
/// A list of callable method entries that must be valid for the block to be valid.
pub method_lookup_assumptions: Vec<CmePtr>,
/// A list of basic operators that not be redefined for the block to be valid.
pub bop_assumptions: Vec<(RedefinitionFlag, ruby_basic_operators)>,
/// A list of constant expression path segments that must have
/// not been written to for the block to be valid.
pub stable_constant_names_assumption: Option<*const ID>,
/// When true, the block is valid only when there is a total of one ractor running
pub block_assumes_single_ractor: bool,
/// Address range for Linux perf's [JIT interface](https://github.com/torvalds/linux/blob/master/tools/perf/Documentation/jit-interface.txt)
perf_map: Rc::<RefCell::<Vec<(CodePtr, Option<CodePtr>, String)>>>,
}
impl JITState {
pub fn new(blockid: BlockId, starting_ctx: Context, output_ptr: CodePtr, ec: EcPtr) -> Self {
JITState {
iseq: blockid.iseq,
starting_insn_idx: blockid.idx,
starting_ctx,
output_ptr,
insn_idx: 0,
opcode: 0,
pc: ptr::null_mut::<VALUE>(),
stack_size_for_pc: starting_ctx.get_stack_size(),
pending_outgoing: vec![],
ec,
record_boundary_patch_point: false,
block_entry_exit: None,
method_lookup_assumptions: vec![],
bop_assumptions: vec![],
stable_constant_names_assumption: None,
block_assumes_single_ractor: false,
perf_map: Rc::default(),
}
}
pub fn get_insn_idx(&self) -> IseqIdx {
self.insn_idx
}
pub fn get_iseq(self: &JITState) -> IseqPtr {
self.iseq
}
pub fn get_opcode(self: &JITState) -> usize {
self.opcode
}
pub fn get_pc(self: &JITState) -> *mut VALUE {
self.pc
}
pub fn get_starting_insn_idx(&self) -> IseqIdx {
self.starting_insn_idx
}
pub fn get_block_entry_exit(&self) -> Option<CodePtr> {
self.block_entry_exit
}
pub fn get_starting_ctx(&self) -> Context {
self.starting_ctx
}
pub fn get_arg(&self, arg_idx: isize) -> VALUE {
// insn_len require non-test config
#[cfg(not(test))]
assert!(insn_len(self.get_opcode()) > (arg_idx + 1).try_into().unwrap());
unsafe { *(self.pc.offset(arg_idx + 1)) }
}
// Get the index of the next instruction
fn next_insn_idx(&self) -> u16 {
self.insn_idx + insn_len(self.get_opcode()) as u16
}
// Check if we are compiling the instruction at the stub PC
// Meaning we are compiling the instruction that is next to execute
pub fn at_current_insn(&self) -> bool {
let ec_pc: *mut VALUE = unsafe { get_cfp_pc(self.get_cfp()) };
ec_pc == self.pc
}
// Peek at the nth topmost value on the Ruby stack.
// Returns the topmost value when n == 0.
pub fn peek_at_stack(&self, ctx: &Context, n: isize) -> VALUE {
assert!(self.at_current_insn());
assert!(n < ctx.get_stack_size() as isize);
// Note: this does not account for ctx->sp_offset because
// this is only available when hitting a stub, and while
// hitting a stub, cfp->sp needs to be up to date in case
// codegen functions trigger GC. See :stub-sp-flush:.
return unsafe {
let sp: *mut VALUE = get_cfp_sp(self.get_cfp());
*(sp.offset(-1 - n))
};
}
fn peek_at_self(&self) -> VALUE {
unsafe { get_cfp_self(self.get_cfp()) }
}
fn peek_at_local(&self, n: i32) -> VALUE {
assert!(self.at_current_insn());
let local_table_size: isize = unsafe { get_iseq_body_local_table_size(self.iseq) }
.try_into()
.unwrap();
assert!(n < local_table_size.try_into().unwrap());
unsafe {
let ep = get_cfp_ep(self.get_cfp());
let n_isize: isize = n.try_into().unwrap();
let offs: isize = -(VM_ENV_DATA_SIZE as isize) - local_table_size + n_isize + 1;
*ep.offset(offs)
}
}
fn peek_at_block_handler(&self, level: u32) -> VALUE {
assert!(self.at_current_insn());
unsafe {
let ep = get_cfp_ep_level(self.get_cfp(), level);
*ep.offset(VM_ENV_DATA_INDEX_SPECVAL as isize)
}
}
pub fn assume_method_lookup_stable(&mut self, asm: &mut Assembler, ocb: &mut OutlinedCb, cme: CmePtr) -> Option<()> {
jit_ensure_block_entry_exit(self, asm, ocb)?;
self.method_lookup_assumptions.push(cme);
Some(())
}
fn get_cfp(&self) -> *mut rb_control_frame_struct {
unsafe { get_ec_cfp(self.ec) }
}
pub fn assume_stable_constant_names(&mut self, asm: &mut Assembler, ocb: &mut OutlinedCb, id: *const ID) -> Option<()> {
jit_ensure_block_entry_exit(self, asm, ocb)?;
self.stable_constant_names_assumption = Some(id);
Some(())
}
pub fn queue_outgoing_branch(&mut self, branch: PendingBranchRef) {
self.pending_outgoing.push(branch)
}
/// Mark the start address of a symbol to be reported to perf
fn perf_symbol_range_start(&self, asm: &mut Assembler, symbol_name: &str) {
let symbol_name = symbol_name.to_string();
let syms = self.perf_map.clone();
asm.pos_marker(move |start, _| syms.borrow_mut().push((start, None, symbol_name.clone())));
}
/// Mark the end address of a symbol to be reported to perf
fn perf_symbol_range_end(&self, asm: &mut Assembler) {
let syms = self.perf_map.clone();
asm.pos_marker(move |end, _| {
if let Some((_, ref mut end_store, _)) = syms.borrow_mut().last_mut() {
assert_eq!(None, *end_store);
*end_store = Some(end);
}
});
}
/// Flush addresses and symbols to /tmp/perf-{pid}.map
fn flush_perf_symbols(&self, cb: &CodeBlock) {
let path = format!("/tmp/perf-{}.map", std::process::id());
let mut f = std::fs::File::options().create(true).append(true).open(path).unwrap();
for sym in self.perf_map.borrow().iter() {
if let (start, Some(end), name) = sym {
// In case the code straddles two pages, part of it belongs to the symbol.
for (inline_start, inline_end) in cb.writable_addrs(*start, *end) {
use std::io::Write;
let code_size = inline_end - inline_start;
writeln!(f, "{inline_start:x} {code_size:x} {name}").unwrap();
}
}
}
}
}
use crate::codegen::JCCKinds::*;
#[allow(non_camel_case_types, unused)]
pub enum JCCKinds {
JCC_JNE,
JCC_JNZ,
JCC_JZ,
JCC_JE,
JCC_JB,
JCC_JBE,
JCC_JNA,
JCC_JNAE,
JCC_JO_MUL,
}
#[inline(always)]
fn gen_counter_incr(asm: &mut Assembler, counter: Counter) {
// Assert that default counters are not incremented by generated code as this would impact performance
assert!(!DEFAULT_COUNTERS.contains(&counter), "gen_counter_incr incremented {:?}", counter);
if get_option!(gen_stats) {
asm_comment!(asm, "increment counter {}", counter.get_name());
let ptr = get_counter_ptr(&counter.get_name());
let ptr_reg = asm.load(Opnd::const_ptr(ptr as *const u8));
let counter_opnd = Opnd::mem(64, ptr_reg, 0);
// Increment and store the updated value
asm.incr_counter(counter_opnd, Opnd::UImm(1));
}
}
// Save the incremented PC on the CFP
// This is necessary when callees can raise or allocate
fn jit_save_pc(jit: &JITState, asm: &mut Assembler) {
let pc: *mut VALUE = jit.get_pc();
let ptr: *mut VALUE = unsafe {
let cur_insn_len = insn_len(jit.get_opcode()) as isize;
pc.offset(cur_insn_len)
};
asm_comment!(asm, "save PC to CFP");
asm.mov(Opnd::mem(64, CFP, RUBY_OFFSET_CFP_PC), Opnd::const_ptr(ptr as *const u8));
}
/// Save the current SP on the CFP
/// This realigns the interpreter SP with the JIT SP
/// Note: this will change the current value of REG_SP,
/// which could invalidate memory operands
fn gen_save_sp(asm: &mut Assembler) {
gen_save_sp_with_offset(asm, 0);
}
/// Save the current SP + offset on the CFP
fn gen_save_sp_with_offset(asm: &mut Assembler, offset: i8) {
if asm.ctx.get_sp_offset() != -offset {
asm_comment!(asm, "save SP to CFP");
let stack_pointer = asm.ctx.sp_opnd((offset as i32 * SIZEOF_VALUE_I32) as isize);
let sp_addr = asm.lea(stack_pointer);
asm.mov(SP, sp_addr);
let cfp_sp_opnd = Opnd::mem(64, CFP, RUBY_OFFSET_CFP_SP);
asm.mov(cfp_sp_opnd, SP);
asm.ctx.set_sp_offset(-offset);
}
}
/// jit_save_pc() + gen_save_sp(). Should be used before calling a routine that
/// could:
/// - Perform GC allocation
/// - Take the VM lock through RB_VM_LOCK_ENTER()
/// - Perform Ruby method call
fn jit_prepare_routine_call(
jit: &mut JITState,
asm: &mut Assembler
) {
jit.record_boundary_patch_point = true;
jit_save_pc(jit, asm);
gen_save_sp(asm);
// In case the routine calls Ruby methods, it can set local variables
// through Kernel#binding and other means.
asm.ctx.clear_local_types();
}
/// Record the current codeblock write position for rewriting into a jump into
/// the outlined block later. Used to implement global code invalidation.
fn record_global_inval_patch(asm: &mut Assembler, outline_block_target_pos: CodePtr) {
// We add a padding before pos_marker so that the previous patch will not overlap this.
// jump_to_next_insn() puts a patch point at the end of the block in fallthrough cases.
// In the fallthrough case, the next block should start with the same Context, so the
// patch is fine, but it should not overlap another patch.
asm.pad_inval_patch();
asm.pos_marker(move |code_ptr, cb| {
CodegenGlobals::push_global_inval_patch(code_ptr, outline_block_target_pos, cb);
});
}
/// Verify the ctx's types and mappings against the compile-time stack, self,
/// and locals.
fn verify_ctx(jit: &JITState, ctx: &Context) {
fn obj_info_str<'a>(val: VALUE) -> &'a str {
unsafe { CStr::from_ptr(rb_obj_info(val)).to_str().unwrap() }
}
// Only able to check types when at current insn
assert!(jit.at_current_insn());
let self_val = jit.peek_at_self();
let self_val_type = Type::from(self_val);
// Verify self operand type
if self_val_type.diff(ctx.get_opnd_type(SelfOpnd)) == TypeDiff::Incompatible {
panic!(
"verify_ctx: ctx self type ({:?}) incompatible with actual value of self {}",
ctx.get_opnd_type(SelfOpnd),
obj_info_str(self_val)
);
}
// Verify stack operand types
let top_idx = cmp::min(ctx.get_stack_size(), MAX_TEMP_TYPES as u8);
for i in 0..top_idx {
let learned_mapping = ctx.get_opnd_mapping(StackOpnd(i));
let learned_type = ctx.get_opnd_type(StackOpnd(i));
let stack_val = jit.peek_at_stack(ctx, i as isize);
let val_type = Type::from(stack_val);
match learned_mapping.get_kind() {
TempMappingKind::MapToSelf => {
if self_val != stack_val {
panic!(
"verify_ctx: stack value was mapped to self, but values did not match!\n stack: {}\n self: {}",
obj_info_str(stack_val),
obj_info_str(self_val)
);
}
}
TempMappingKind::MapToLocal => {
let local_idx: u8 = learned_mapping.get_local_idx();
let local_val = jit.peek_at_local(local_idx.into());
if local_val != stack_val {
panic!(
"verify_ctx: stack value was mapped to local, but values did not match\n stack: {}\n local {}: {}",
obj_info_str(stack_val),
local_idx,
obj_info_str(local_val)
);
}
}
TempMappingKind::MapToStack => {}
}
// If the actual type differs from the learned type
if val_type.diff(learned_type) == TypeDiff::Incompatible {
panic!(
"verify_ctx: ctx type ({:?}) incompatible with actual value on stack: {} ({:?})",
learned_type,
obj_info_str(stack_val),
val_type,
);
}
}
// Verify local variable types
let local_table_size = unsafe { get_iseq_body_local_table_size(jit.iseq) };
let top_idx: usize = cmp::min(local_table_size as usize, MAX_TEMP_TYPES);
for i in 0..top_idx {
let learned_type = ctx.get_local_type(i);
let local_val = jit.peek_at_local(i as i32);
let local_type = Type::from(local_val);
if local_type.diff(learned_type) == TypeDiff::Incompatible {
panic!(
"verify_ctx: ctx type ({:?}) incompatible with actual value of local: {} (type {:?})",
learned_type,
obj_info_str(local_val),
local_type
);
}
}
}
// Fill code_for_exit_from_stub. This is used by branch_stub_hit() to exit
// to the interpreter when it cannot service a stub by generating new code.
// Before coming here, branch_stub_hit() takes care of fully reconstructing
// interpreter state.
fn gen_stub_exit(ocb: &mut OutlinedCb) -> Option<CodePtr> {
let ocb = ocb.unwrap();
let mut asm = Assembler::new();
gen_counter_incr(&mut asm, Counter::exit_from_branch_stub);
asm_comment!(asm, "exit from branch stub");
asm.cpop_into(SP);
asm.cpop_into(EC);
asm.cpop_into(CFP);
asm.frame_teardown();
asm.cret(Qundef.into());
asm.compile(ocb, None).map(|(code_ptr, _)| code_ptr)
}
/// Generate an exit to return to the interpreter
fn gen_exit(exit_pc: *mut VALUE, asm: &mut Assembler) {
#[cfg(all(feature = "disasm", not(test)))]
{
let opcode = unsafe { rb_vm_insn_addr2opcode((*exit_pc).as_ptr()) };
asm_comment!(asm, "exit to interpreter on {}", insn_name(opcode as usize));
}
if asm.ctx.is_return_landing() {
asm.mov(SP, Opnd::mem(64, CFP, RUBY_OFFSET_CFP_SP));
let top = asm.stack_push(Type::Unknown);
asm.mov(top, C_RET_OPND);
}
// Spill stack temps before returning to the interpreter
asm.spill_temps();
// Generate the code to exit to the interpreters
// Write the adjusted SP back into the CFP
if asm.ctx.get_sp_offset() != 0 {
let sp_opnd = asm.lea(asm.ctx.sp_opnd(0));
asm.mov(
Opnd::mem(64, CFP, RUBY_OFFSET_CFP_SP),
sp_opnd
);
}
// Update CFP->PC
asm.mov(
Opnd::mem(64, CFP, RUBY_OFFSET_CFP_PC),
Opnd::const_ptr(exit_pc as *const u8)
);
// Accumulate stats about interpreter exits
if get_option!(gen_stats) {
asm.ccall(
rb_yjit_count_side_exit_op as *const u8,
vec![Opnd::const_ptr(exit_pc as *const u8)]
);
// If --yjit-trace-exits option is enabled, record the exit stack
// while recording the side exits.
if get_option!(gen_trace_exits) {
asm.ccall(
rb_yjit_record_exit_stack as *const u8,
vec![Opnd::const_ptr(exit_pc as *const u8)]
);
}
}
asm.cpop_into(SP);
asm.cpop_into(EC);
asm.cpop_into(CFP);
asm.frame_teardown();
asm.cret(Qundef.into());
}
/// :side-exit:
/// Get an exit for the current instruction in the outlined block. The code
/// for each instruction often begins with several guards before proceeding
/// to do work. When guards fail, an option we have is to exit to the
/// interpreter at an instruction boundary. The piece of code that takes
/// care of reconstructing interpreter state and exiting out of generated
/// code is called the side exit.
///
/// No guards change the logic for reconstructing interpreter state at the
/// moment, so there is one unique side exit for each context. Note that
/// it's incorrect to jump to the side exit after any ctx stack push operations
/// since they change the logic required for reconstructing interpreter state.
pub fn gen_outlined_exit(exit_pc: *mut VALUE, ctx: &Context, ocb: &mut OutlinedCb) -> Option<CodePtr> {
let mut cb = ocb.unwrap();
let mut asm = Assembler::new();
asm.ctx = *ctx;
asm.set_reg_temps(ctx.get_reg_temps());
gen_exit(exit_pc, &mut asm);
asm.compile(&mut cb, None).map(|(code_ptr, _)| code_ptr)
}
/// Get a side exit. Increment a counter in it if --yjit-stats is enabled.
pub fn gen_counted_exit(side_exit: CodePtr, ocb: &mut OutlinedCb, counter: Option<Counter>) -> Option<CodePtr> {
// The counter is only incremented when stats are enabled
if !get_option!(gen_stats) {
return Some(side_exit);
}
let counter = match counter {
Some(counter) => counter,
None => return Some(side_exit),
};
let mut asm = Assembler::new();
// Load the pointer into a register
asm_comment!(asm, "increment counter {}", counter.get_name());
let ptr_reg = asm.load(Opnd::const_ptr(get_counter_ptr(&counter.get_name()) as *const u8));
let counter_opnd = Opnd::mem(64, ptr_reg, 0);
// Increment and store the updated value
asm.incr_counter(counter_opnd, Opnd::UImm(1));
// Jump to the existing side exit
asm.jmp(Target::CodePtr(side_exit));
let ocb = ocb.unwrap();
asm.compile(ocb, None).map(|(code_ptr, _)| code_ptr)
}
// Ensure that there is an exit for the start of the block being compiled.
// Block invalidation uses this exit.
#[must_use]
pub fn jit_ensure_block_entry_exit(jit: &mut JITState, asm: &mut Assembler, ocb: &mut OutlinedCb) -> Option<()> {
if jit.block_entry_exit.is_some() {
return Some(());
}
let block_starting_context = &jit.get_starting_ctx();
// If we're compiling the first instruction in the block.
if jit.insn_idx == jit.starting_insn_idx {
// Generate the exit with the cache in Assembler.
let side_exit_context = SideExitContext::new(jit.pc, *block_starting_context);
let entry_exit = asm.get_side_exit(&side_exit_context, None, ocb);
jit.block_entry_exit = Some(entry_exit?);
} else {
let block_entry_pc = unsafe { rb_iseq_pc_at_idx(jit.iseq, jit.starting_insn_idx.into()) };
jit.block_entry_exit = Some(gen_outlined_exit(block_entry_pc, block_starting_context, ocb)?);
}
Some(())
}
// Landing code for when c_return tracing is enabled. See full_cfunc_return().
fn gen_full_cfunc_return(ocb: &mut OutlinedCb) -> Option<CodePtr> {
let ocb = ocb.unwrap();
let mut asm = Assembler::new();
// This chunk of code expects REG_EC to be filled properly and
// RAX to contain the return value of the C method.
asm_comment!(asm, "full cfunc return");
asm.ccall(
rb_full_cfunc_return as *const u8,
vec![EC, C_RET_OPND]
);
// Count the exit
gen_counter_incr(&mut asm, Counter::traced_cfunc_return);
// Return to the interpreter
asm.cpop_into(SP);
asm.cpop_into(EC);
asm.cpop_into(CFP);
asm.frame_teardown();
asm.cret(Qundef.into());
asm.compile(ocb, None).map(|(code_ptr, _)| code_ptr)
}
/// Generate a continuation for leave that exits to the interpreter at REG_CFP->pc.
/// This is used by gen_leave() and gen_entry_prologue()
fn gen_leave_exit(ocb: &mut OutlinedCb) -> Option<CodePtr> {
let ocb = ocb.unwrap();
let mut asm = Assembler::new();
// gen_leave() fully reconstructs interpreter state and leaves the
// return value in C_RET_OPND before coming here.
let ret_opnd = asm.live_reg_opnd(C_RET_OPND);
// Every exit to the interpreter should be counted
gen_counter_incr(&mut asm, Counter::leave_interp_return);
asm_comment!(asm, "exit from leave");
asm.cpop_into(SP);
asm.cpop_into(EC);
asm.cpop_into(CFP);
asm.frame_teardown();
asm.cret(ret_opnd);
asm.compile(ocb, None).map(|(code_ptr, _)| code_ptr)
}
// Increment SP and transfer the execution to the interpreter after jit_exec_exception().
// On jit_exec_exception(), you need to return Qundef to keep executing caller non-FINISH
// frames on the interpreter. You also need to increment SP to push the return value to
// the caller's stack, which is different from gen_stub_exit().
fn gen_leave_exception(ocb: &mut OutlinedCb) -> Option<CodePtr> {
let ocb = ocb.unwrap();
let mut asm = Assembler::new();
// gen_leave() leaves the return value in C_RET_OPND before coming here.
let ruby_ret_val = asm.live_reg_opnd(C_RET_OPND);
// Every exit to the interpreter should be counted
gen_counter_incr(&mut asm, Counter::leave_interp_return);
asm_comment!(asm, "push return value through cfp->sp");
let cfp_sp = Opnd::mem(64, CFP, RUBY_OFFSET_CFP_SP);
let sp = asm.load(cfp_sp);
asm.mov(Opnd::mem(64, sp, 0), ruby_ret_val);
let new_sp = asm.add(sp, SIZEOF_VALUE.into());
asm.mov(cfp_sp, new_sp);
asm_comment!(asm, "exit from exception");
asm.cpop_into(SP);
asm.cpop_into(EC);
asm.cpop_into(CFP);
asm.frame_teardown();
// Execute vm_exec_core
asm.cret(Qundef.into());
asm.compile(ocb, None).map(|(code_ptr, _)| code_ptr)
}
// Generate a runtime guard that ensures the PC is at the expected
// instruction index in the iseq, otherwise takes an entry stub
// that generates another check and entry.
// This is to handle the situation of optional parameters.
// When a function with optional parameters is called, the entry
// PC for the method isn't necessarily 0.
pub fn gen_entry_chain_guard(
asm: &mut Assembler,
ocb: &mut OutlinedCb,
iseq: IseqPtr,
insn_idx: u16,
) -> Option<PendingEntryRef> {
let entry = new_pending_entry();
let stub_addr = gen_entry_stub(entry.uninit_entry.as_ptr() as usize, ocb)?;
let pc_opnd = Opnd::mem(64, CFP, RUBY_OFFSET_CFP_PC);
let expected_pc = unsafe { rb_iseq_pc_at_idx(iseq, insn_idx.into()) };
let expected_pc_opnd = Opnd::const_ptr(expected_pc as *const u8);
asm_comment!(asm, "guard expected PC");
asm.cmp(pc_opnd, expected_pc_opnd);
asm.mark_entry_start(&entry);
asm.jne(stub_addr.into());
asm.mark_entry_end(&entry);
return Some(entry);
}
/// Compile an interpreter entry block to be inserted into an iseq
/// Returns None if compilation fails.
/// If jit_exception is true, compile JIT code for handling exceptions.
/// See [jit_compile_exception] for details.
pub fn gen_entry_prologue(
cb: &mut CodeBlock,
ocb: &mut OutlinedCb,
iseq: IseqPtr,
insn_idx: u16,
jit_exception: bool,
) -> Option<CodePtr> {
let code_ptr = cb.get_write_ptr();
let mut asm = Assembler::new();
if get_option_ref!(dump_disasm).is_some() {
asm_comment!(asm, "YJIT entry point: {}", iseq_get_location(iseq, 0));
} else {
asm_comment!(asm, "YJIT entry");
}
asm.frame_setup();
// Save the CFP, EC, SP registers to the C stack
asm.cpush(CFP);
asm.cpush(EC);
asm.cpush(SP);
// We are passed EC and CFP as arguments
asm.mov(EC, C_ARG_OPNDS[0]);
asm.mov(CFP, C_ARG_OPNDS[1]);
// Load the current SP from the CFP into REG_SP
asm.mov(SP, Opnd::mem(64, CFP, RUBY_OFFSET_CFP_SP));
// Setup cfp->jit_return
// If this is an exception handler entry point
if jit_exception {
// On jit_exec_exception(), it's NOT safe to return a non-Qundef value
// from a non-FINISH frame. This function fixes that problem.
// See [jit_compile_exception] for details.
asm.ccall(
rb_yjit_set_exception_return as *mut u8,
vec![
CFP,
Opnd::const_ptr(CodegenGlobals::get_leave_exit_code().raw_ptr(cb)),
Opnd::const_ptr(CodegenGlobals::get_leave_exception_code().raw_ptr(cb)),
],
);
} else {
// On jit_exec() or JIT_EXEC(), it's safe to return a non-Qundef value
// on the entry frame. See [jit_compile] for details.
asm.mov(
Opnd::mem(64, CFP, RUBY_OFFSET_CFP_JIT_RETURN),
Opnd::const_ptr(CodegenGlobals::get_leave_exit_code().raw_ptr(cb)),
);
}
// We're compiling iseqs that we *expect* to start at `insn_idx`.
// But in the case of optional parameters or when handling exceptions,
// the interpreter can set the pc to a different location. For
// such scenarios, we'll add a runtime check that the PC we've
// compiled for is the same PC that the interpreter wants us to run with.
// If they don't match, then we'll jump to an entry stub and generate
// another PC check and entry there.
let pending_entry = if unsafe { get_iseq_flags_has_opt(iseq) } || jit_exception {
Some(gen_entry_chain_guard(&mut asm, ocb, iseq, insn_idx)?)
} else {
None
};
asm.compile(cb, Some(ocb))?;
if cb.has_dropped_bytes() {
None
} else {
// Mark code pages for code GC
let iseq_payload = get_or_create_iseq_payload(iseq);
for page in cb.addrs_to_pages(code_ptr, cb.get_write_ptr()) {
iseq_payload.pages.insert(page);
}
// Write an entry to the heap and push it to the ISEQ
if let Some(pending_entry) = pending_entry {
let pending_entry = Rc::try_unwrap(pending_entry)
.ok().expect("PendingEntry should be unique");
iseq_payload.entries.push(pending_entry.into_entry());
}
Some(code_ptr)
}
}
// Generate code to check for interrupts and take a side-exit.
// Warning: this function clobbers REG0
fn gen_check_ints(
asm: &mut Assembler,
counter: Counter,
) {
// Check for interrupts
// see RUBY_VM_CHECK_INTS(ec) macro
asm_comment!(asm, "RUBY_VM_CHECK_INTS(ec)");
// Not checking interrupt_mask since it's zero outside finalize_deferred_heap_pages,
// signal_exec, or rb_postponed_job_flush.
let interrupt_flag = asm.load(Opnd::mem(32, EC, RUBY_OFFSET_EC_INTERRUPT_FLAG));
asm.test(interrupt_flag, interrupt_flag);
asm.jnz(Target::side_exit(counter));
}
// Generate a stubbed unconditional jump to the next bytecode instruction.
// Blocks that are part of a guard chain can use this to share the same successor.
fn jump_to_next_insn(
jit: &mut JITState,
asm: &mut Assembler,
ocb: &mut OutlinedCb,
) -> Option<()> {
// Reset the depth since in current usages we only ever jump to to
// chain_depth > 0 from the same instruction.
let mut reset_depth = asm.ctx;
reset_depth.reset_chain_depth();
let jump_block = BlockId {
iseq: jit.iseq,
idx: jit.next_insn_idx(),
};
// We are at the end of the current instruction. Record the boundary.
if jit.record_boundary_patch_point {
jit.record_boundary_patch_point = false;
let exit_pc = unsafe { jit.pc.offset(insn_len(jit.opcode).try_into().unwrap()) };
let exit_pos = gen_outlined_exit(exit_pc, &reset_depth, ocb);
record_global_inval_patch(asm, exit_pos?);
}
// Generate the jump instruction
gen_direct_jump(jit, &reset_depth, jump_block, asm);
Some(())
}
// Compile a sequence of bytecode instructions for a given basic block version.
// Part of gen_block_version().
// Note: this function will mutate its context while generating code,
// but the input start_ctx argument should remain immutable.
pub fn gen_single_block(
blockid: BlockId,
start_ctx: &Context,
ec: EcPtr,
cb: &mut CodeBlock,
ocb: &mut OutlinedCb,
) -> Result<BlockRef, ()> {
// Limit the number of specialized versions for this block
let ctx = limit_block_versions(blockid, start_ctx);
verify_blockid(blockid);
assert!(!(blockid.idx == 0 && ctx.get_stack_size() > 0));
// Save machine code placement of the block. `cb` might page switch when we
// generate code in `ocb`.
let block_start_addr = cb.get_write_ptr();
// Instruction sequence to compile
let iseq = blockid.iseq;
let iseq_size = unsafe { get_iseq_encoded_size(iseq) };
let iseq_size: IseqIdx = if let Ok(size) = iseq_size.try_into() {
size
} else {
// ISeq too large to compile
return Err(());
};
let mut insn_idx: IseqIdx = blockid.idx;
// Initialize a JIT state object
let mut jit = JITState::new(blockid, ctx, cb.get_write_ptr(), ec);
jit.iseq = blockid.iseq;
// Create a backend assembler instance
let mut asm = Assembler::new();
asm.ctx = ctx;
#[cfg(feature = "disasm")]
if get_option_ref!(dump_disasm).is_some() {
let blockid_idx = blockid.idx;
let chain_depth = if asm.ctx.get_chain_depth() > 0 { format!("(chain_depth: {})", asm.ctx.get_chain_depth()) } else { "".to_string() };
asm_comment!(asm, "Block: {} {}", iseq_get_location(blockid.iseq, blockid_idx), chain_depth);
asm_comment!(asm, "reg_temps: {:08b}", asm.ctx.get_reg_temps().as_u8());
}
// Mark the start of a method name symbol for --yjit-perf
if get_option!(perf_map) {
let comptime_recv_class = jit.peek_at_self().class_of();
let class_name = unsafe { cstr_to_rust_string(rb_class2name(comptime_recv_class)) };
match (class_name, unsafe { rb_iseq_label(iseq) }) {
(Some(class_name), iseq_label) if iseq_label != Qnil => {
let iseq_label = ruby_str_to_rust(iseq_label);
jit.perf_symbol_range_start(&mut asm, &format!("[JIT] {}#{}", class_name, iseq_label));
}
_ => {},
}
}
if asm.ctx.is_return_landing() {
// Continuation of the end of gen_leave().
// Reload REG_SP for the current frame and transfer the return value
// to the stack top.
asm.mov(SP, Opnd::mem(64, CFP, RUBY_OFFSET_CFP_SP));
let top = asm.stack_push(Type::Unknown);
asm.mov(top, C_RET_OPND);
asm.ctx.clear_return_landing();
}
// For each instruction to compile
// NOTE: could rewrite this loop with a std::iter::Iterator
while insn_idx < iseq_size {
// Get the current pc and opcode
let pc = unsafe { rb_iseq_pc_at_idx(iseq, insn_idx.into()) };
// try_into() call below is unfortunate. Maybe pick i32 instead of usize for opcodes.
let opcode: usize = unsafe { rb_iseq_opcode_at_pc(iseq, pc) }
.try_into()
.unwrap();
// We need opt_getconstant_path to be in a block all on its own. Cut the block short
// if we run into it. This is necessary because we want to invalidate based on the
// instruction's index.
if opcode == YARVINSN_opt_getconstant_path.as_usize() && insn_idx > jit.starting_insn_idx {
jump_to_next_insn(&mut jit, &mut asm, ocb);
break;
}
// Set the current instruction
jit.insn_idx = insn_idx;
jit.opcode = opcode;
jit.pc = pc;
jit.stack_size_for_pc = asm.ctx.get_stack_size();
asm.set_side_exit_context(pc, asm.ctx.get_stack_size());
// stack_pop doesn't immediately deallocate a register for stack temps,
// but it's safe to do so at this instruction boundary.
for stack_idx in asm.ctx.get_stack_size()..MAX_REG_TEMPS {
asm.ctx.dealloc_temp_reg(stack_idx);
}
// If previous instruction requested to record the boundary
if jit.record_boundary_patch_point {
// Generate an exit to this instruction and record it
let exit_pos = gen_outlined_exit(jit.pc, &asm.ctx, ocb).ok_or(())?;
record_global_inval_patch(&mut asm, exit_pos);
jit.record_boundary_patch_point = false;
}
// In debug mode, verify our existing assumption
if cfg!(debug_assertions) && get_option!(verify_ctx) && jit.at_current_insn() {
verify_ctx(&jit, &asm.ctx);
}
// :count-placement:
// Count bytecode instructions that execute in generated code.
// Note that the increment happens even when the output takes side exit.
gen_counter_incr(&mut asm, Counter::yjit_insns_count);
// Lookup the codegen function for this instruction
let mut status = None;
if let Some(gen_fn) = get_gen_fn(VALUE(opcode)) {
// Add a comment for the name of the YARV instruction
asm_comment!(asm, "Insn: {:04} {} (stack_size: {})", insn_idx, insn_name(opcode), asm.ctx.get_stack_size());
// If requested, dump instructions for debugging
if get_option!(dump_insns) {