-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Expand file tree
/
Copy pathcodegen.rs
More file actions
3601 lines (3106 loc) · 153 KB
/
codegen.rs
File metadata and controls
3601 lines (3106 loc) · 153 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
//! This module is for native code generation.
#![allow(clippy::let_and_return)]
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::ffi::{c_int, c_long, c_void};
use std::slice;
use crate::backend::current::ALLOC_REGS;
use crate::invariants::{
track_bop_assumption, track_cme_assumption, track_no_ep_escape_assumption, track_no_trace_point_assumption,
track_single_ractor_assumption, track_stable_constant_names_assumption, track_no_singleton_class_assumption,
track_root_box_assumption
};
use crate::gc::append_gc_offsets;
use crate::payload::{IseqCodePtrs, IseqStatus, IseqVersion, IseqVersionRef, JITFrame, get_or_create_iseq_payload};
use crate::state::ZJITState;
use crate::stats::{CompileError, exit_counter_for_compile_error, exit_counter_for_unhandled_hir_insn, incr_counter, incr_counter_by, send_fallback_counter, send_fallback_counter_for_method_type, send_fallback_counter_for_super_method_type, send_fallback_counter_ptr_for_opcode, send_without_block_fallback_counter_for_method_type, send_without_block_fallback_counter_for_optimized_method_type};
use crate::stats::{counter_ptr, with_time_stat, Counter, Counter::{compile_time_ns, exit_compile_error}};
use crate::{asm::CodeBlock, cruby::*, options::debug, virtualmem::CodePtr};
use crate::backend::lir::{self, Assembler, C_ARG_OPNDS, C_RET_OPND, CFP, EC, NATIVE_STACK_PTR, Opnd, SP, SideExit, SideExitRecompile, Target, asm_ccall, asm_comment};
use crate::hir::{iseq_to_hir, BlockId, Invariant, RangeType, SideExitReason::{self, *}, SpecialBackrefSymbol, SpecialObjectType};
use crate::hir::{BlockHandler, Const, FrameState, Function, Insn, InsnId, SendFallbackReason};
use crate::hir_type::{types, Type};
use crate::options::{get_option, PerfMap};
use crate::cast::IntoUsize;
/// Default maximum number of compiled versions per ISEQ.
const DEFAULT_MAX_VERSIONS: usize = 2;
/// Maximum number of compiled versions per ISEQ.
/// Configurable via --zjit-max-versions (default: 2).
pub fn max_iseq_versions() -> usize {
unsafe { crate::options::OPTIONS.as_ref() }
.map_or(DEFAULT_MAX_VERSIONS, |opts| opts.max_versions)
}
/// Sentinel program counter stored in C frames when runtime checks are enabled.
const PC_POISON: Option<*const VALUE> = if cfg!(feature = "runtime_checks") {
Some(usize::MAX as *const VALUE)
} else {
None
};
/// Sentinel jit_return stored on ISEQ frame push when runtime checks are enabled.
const JIT_RETURN_POISON: Option<usize> = if cfg!(feature = "runtime_checks") {
Some(ZJIT_JIT_RETURN_POISON as usize)
} else {
None
};
/// Ephemeral code generation state
struct JITState {
/// Instruction sequence for the method being compiled
iseq: IseqPtr,
/// ISEQ version that is being compiled, which will be used by PatchPoint
version: IseqVersionRef,
/// Low-level IR Operands indexed by High-level IR's Instruction ID
opnds: Vec<Option<Opnd>>,
/// Labels for each basic block indexed by the BlockId
labels: Vec<Option<Target>>,
/// JIT entry point for the `iseq`
jit_entries: Vec<Rc<RefCell<JITEntry>>>,
/// ISEQ calls that need to be compiled later
iseq_calls: Vec<IseqCallRef>,
}
impl JITState {
/// Create a new JITState instance
fn new(iseq: IseqPtr, version: IseqVersionRef, num_insns: usize, num_blocks: usize) -> Self {
JITState {
iseq,
version,
opnds: vec![None; num_insns],
labels: vec![None; num_blocks],
jit_entries: Vec::default(),
iseq_calls: Vec::default(),
}
}
/// Retrieve the output of a given instruction that has been compiled
fn get_opnd(&self, insn_id: InsnId) -> lir::Opnd {
self.opnds[insn_id.0].unwrap_or_else(|| panic!("Failed to get_opnd({insn_id})"))
}
/// Find or create a label for a given BlockId
fn get_label(&mut self, asm: &mut Assembler, lir_block_id: lir::BlockId, hir_block_id: BlockId) -> Target {
// Extend labels vector if the requested index is out of bounds
if lir_block_id.0 >= self.labels.len() {
self.labels.resize(lir_block_id.0 + 1, None);
}
match &self.labels[lir_block_id.0] {
Some(label) => label.clone(),
None => {
let label = asm.new_label(&format!("{hir_block_id}_{lir_block_id}"));
self.labels[lir_block_id.0] = Some(label.clone());
label
}
}
}
}
impl Assembler {
/// Emit a conditional jump that splits the current block, creating a new
/// fall-through block for instructions that follow.
fn split_block_jump(&mut self, jit: &mut JITState, emit: impl FnOnce(&mut Assembler, Target), target: Target) {
let hir_block_id = self.current_block().hir_block_id;
let rpo_idx = self.current_block().rpo_index;
let fall_through_target = self.new_block(hir_block_id, false, rpo_idx);
let fall_through_edge = lir::BranchEdge {
target: fall_through_target,
args: vec![],
};
emit(self, target);
self.jmp(Target::Block(fall_through_edge));
self.set_current_block(fall_through_target);
let label = jit.get_label(self, fall_through_target, hir_block_id);
self.write_label(label);
}
}
macro_rules! define_split_jumps {
($($name:ident => $insn:ident),+ $(,)?) => {
impl Assembler {
$(
fn $name(&mut self, jit: &mut JITState, target: Target) {
self.split_block_jump(jit, |asm, target| asm.push_insn(lir::Insn::$insn(target)), target);
}
)+
}
};
}
define_split_jumps! {
jbe => Jbe,
je => Je,
jge => Jge,
jl => Jl,
jne => Jne,
jnz => Jnz,
jo => Jo,
jo_mul => JoMul,
jz => Jz,
}
/// CRuby API to compile a given ISEQ.
/// If jit_exception is true, compile JIT code for handling exceptions.
/// See jit_compile_exception() for details.
#[unsafe(no_mangle)]
pub extern "C" fn rb_zjit_iseq_gen_entry_point(iseq: IseqPtr, ec: EcPtr, jit_exception: bool) -> *const u8 {
// Don't compile when there is insufficient native stack space
if unsafe { rb_ec_stack_check(ec as _) } != 0 {
incr_counter!(skipped_native_stack_full);
return std::ptr::null();
}
// Take a lock to avoid writing to ISEQ in parallel with Ractors.
// with_vm_lock() does nothing if the program doesn't use Ractors.
with_vm_lock(src_loc!(), || {
let cb = ZJITState::get_code_block();
let mut code_ptr = with_time_stat(compile_time_ns, || gen_iseq_entry_point(cb, iseq, jit_exception));
if let Err(err) = &code_ptr {
// Assert that the ISEQ compiles if RubyVM::ZJIT.assert_compiles is enabled.
// We assert only `jit_exception: false` cases until we support exception handlers.
if ZJITState::assert_compiles_enabled() && !jit_exception {
let iseq_location = iseq_get_location(iseq, 0);
panic!("Failed to compile: {iseq_location}");
}
// For --zjit-stats, generate an entry that just increments exit_compilation_failure and exits
if get_option!(stats) {
code_ptr = gen_compile_error_counter(cb, err);
}
}
// Always mark the code region executable if asm.compile() has been used.
// We need to do this even if code_ptr is None because gen_iseq() may have already used asm.compile().
cb.mark_all_executable();
code_ptr.map_or(std::ptr::null(), |ptr| ptr.raw_ptr(cb))
})
}
/// Compile an entry point for a given ISEQ
fn gen_iseq_entry_point(cb: &mut CodeBlock, iseq: IseqPtr, jit_exception: bool) -> Result<CodePtr, CompileError> {
// We don't support exception handlers yet
if jit_exception {
return Err(CompileError::ExceptionHandler);
}
// Compile ISEQ into High-level IR
let function = crate::stats::with_time_stat(Counter::compile_hir_time_ns, || compile_iseq(iseq).inspect_err(|_| {
incr_counter!(failed_iseq_count);
}))?;
// Compile the High-level IR
let IseqCodePtrs { start_ptr, .. } = gen_iseq(cb, iseq, Some(&function)).inspect_err(|err| {
debug!("{err:?}: gen_iseq failed: {}", iseq_get_location(iseq, 0));
})?;
Ok(start_ptr)
}
/// Invalidate an ISEQ version and allow it to be recompiled on the next call.
/// Both PatchPoint invalidation and exit-profiling recompilation go through this
/// function, serving as the central point for all invalidation/recompile decisions.
///
/// TODO: evolve this into a general `handle_event(iseq, event)` state machine that
/// handles all compile lifecycle events (interpreter profiles, JIT profiles, invalidation,
/// GC) so that all compile/recompile tuning decisions live in one place.
pub fn invalidate_iseq_version(cb: &mut CodeBlock, iseq: IseqPtr, version: &mut IseqVersionRef) {
let payload = get_or_create_iseq_payload(iseq);
if unsafe { version.as_ref() }.status != IseqStatus::Invalidated
&& payload.versions.len() < max_iseq_versions()
{
unsafe { version.as_mut() }.status = IseqStatus::Invalidated;
unsafe { rb_iseq_reset_jit_func(iseq) };
// Recompile JIT-to-JIT calls into the invalidated ISEQ
for incoming in unsafe { version.as_ref() }.incoming.iter() {
if let Err(err) = gen_iseq_call(cb, incoming) {
debug!("{err:?}: gen_iseq_call failed during invalidation: {}", iseq_get_location(incoming.iseq.get(), 0));
}
}
}
}
/// Stub a branch for a JIT-to-JIT call
pub fn gen_iseq_call(cb: &mut CodeBlock, iseq_call: &IseqCallRef) -> Result<(), CompileError> {
// Compile a function stub
let stub_ptr = gen_function_stub(cb, iseq_call.clone()).inspect_err(|err| {
debug!("{err:?}: gen_function_stub failed: {}", iseq_get_location(iseq_call.iseq.get(), 0));
})?;
// Update the JIT-to-JIT call to call the stub
let stub_addr = stub_ptr.raw_ptr(cb);
let iseq = iseq_call.iseq.get();
iseq_call.regenerate(cb, |asm| {
asm_comment!(asm, "call function stub: {}", iseq_get_location(iseq, 0));
asm.ccall_into(C_RET_OPND, stub_addr, vec![]);
});
Ok(())
}
/// Write an entry to the perf map in /tmp
fn register_with_perf(symbol_name: String, start_ptr: usize, code_size: usize) {
use std::io::Write;
let perf_map = format!("/tmp/perf-{}.map", std::process::id());
let Ok(file) = std::fs::OpenOptions::new().create(true).append(true).open(&perf_map) else {
debug!("Failed to open perf map file: {perf_map}");
return;
};
let mut file = std::io::BufWriter::new(file);
let Ok(_) = writeln!(file, "{start_ptr:#x} {code_size:#x} ZJIT: {symbol_name}") else {
debug!("Failed to write {symbol_name} to perf map file: {perf_map}");
return;
};
}
/// Compile a shared JIT entry trampoline
pub fn gen_entry_trampoline(cb: &mut CodeBlock) -> Result<CodePtr, CompileError> {
// Set up registers for CFP, EC, SP, and basic block arguments
let mut asm = Assembler::new();
asm.new_block_without_id("gen_entry_trampoline");
gen_entry_prologue(&mut asm);
// Jump to the first block using a call instruction. This trampoline is used
// as rb_zjit_func_t in jit_exec(), which takes (EC, CFP, rb_jit_func_t).
// So C_ARG_OPNDS[2] is rb_jit_func_t, which is (EC, CFP) -> VALUE.
let out = asm.ccall_reg(C_ARG_OPNDS[2], VALUE_BITS);
// Restore registers for CFP, EC, and SP after use
asm_comment!(asm, "return to the interpreter");
asm.frame_teardown(lir::JIT_PRESERVED_REGS);
asm.cret(out);
let (code_ptr, gc_offsets) = asm.compile(cb)?;
assert!(gc_offsets.is_empty());
if get_option!(perf).is_some() {
let start_ptr = code_ptr.raw_addr(cb);
let end_ptr = cb.get_write_ptr().raw_addr(cb);
let code_size = end_ptr - start_ptr;
register_with_perf("entry trampoline".into(), start_ptr, code_size);
}
Ok(code_ptr)
}
/// Compile an ISEQ into machine code if not compiled yet
fn gen_iseq(cb: &mut CodeBlock, iseq: IseqPtr, function: Option<&Function>) -> Result<IseqCodePtrs, CompileError> {
// Return an existing pointer if it's already compiled
let payload = get_or_create_iseq_payload(iseq);
let last_status = payload.versions.last().map(|version| &unsafe { version.as_ref() }.status);
match last_status {
Some(IseqStatus::Compiled(code_ptrs)) => return Ok(code_ptrs.clone()),
Some(IseqStatus::CantCompile(err)) => return Err(err.clone()),
_ => {},
}
// If the ISEQ already has max versions, do not compile a new version.
if payload.versions.len() >= max_iseq_versions() {
return Err(CompileError::IseqVersionLimitReached);
}
// Compile the ISEQ
let mut version = IseqVersion::new(iseq);
let code_ptrs = gen_iseq_body(cb, iseq, version, function);
match &code_ptrs {
Ok(code_ptrs) => {
unsafe { version.as_mut() }.status = IseqStatus::Compiled(code_ptrs.clone());
incr_counter!(compiled_iseq_count);
}
Err(err) => {
unsafe { version.as_mut() }.status = IseqStatus::CantCompile(err.clone());
incr_counter!(failed_iseq_count);
}
}
payload.versions.push(version);
code_ptrs
}
/// Compile an ISEQ into machine code
fn gen_iseq_body(cb: &mut CodeBlock, iseq: IseqPtr, mut version: IseqVersionRef, function: Option<&Function>) -> Result<IseqCodePtrs, CompileError> {
// If we ran out of code region, we shouldn't attempt to generate new code.
if cb.has_dropped_bytes() {
return Err(CompileError::OutOfMemory);
}
// Convert ISEQ into optimized High-level IR if not given
let function = match function {
Some(function) => function,
None => &crate::stats::with_time_stat(Counter::compile_hir_time_ns, || compile_iseq(iseq))?,
};
// Compile the High-level IR
let (iseq_code_ptrs, gc_offsets, iseq_calls) =
crate::stats::with_time_stat(Counter::compile_lir_time_ns, || gen_function(cb, iseq, version, function))?;
// Stub callee ISEQs for JIT-to-JIT calls
for iseq_call in iseq_calls.iter() {
gen_iseq_call(cb, iseq_call)?;
}
// Prepare for GC
unsafe { version.as_mut() }.outgoing.extend(iseq_calls);
append_gc_offsets(iseq, version, &gc_offsets);
Ok(iseq_code_ptrs)
}
/// Compile a function
fn gen_function(cb: &mut CodeBlock, iseq: IseqPtr, version: IseqVersionRef, function: &Function) -> Result<(IseqCodePtrs, Vec<CodePtr>, Vec<IseqCallRef>), CompileError> {
let num_spilled_params = max_num_params(function).saturating_sub(ALLOC_REGS.len());
let mut jit = JITState::new(iseq, version, function.num_insns(), function.num_blocks());
let mut asm = Assembler::new_with_stack_slots(num_spilled_params);
// Mapping from HIR block IDs to LIR block IDs.
// This is is a one-to-one mapping from HIR to LIR blocks used for finding
// jump targets in LIR (LIR should always jump to the head of an HIR block)
let mut hir_to_lir: Vec<Option<lir::BlockId>> = vec![None; function.num_blocks()];
let reverse_post_order = function.rpo();
// Create all LIR basic blocks corresponding to HIR basic blocks
for (rpo_idx, &block_id) in reverse_post_order.iter().enumerate() {
// Skip the entries superblock — it's an internal CFG artifact
if block_id == function.entries_block { continue; }
let lir_block_id = asm.new_block(block_id, function.is_entry_block(block_id), rpo_idx);
hir_to_lir[block_id.0] = Some(lir_block_id);
}
// Compile each basic block
for (rpo_idx, &block_id) in reverse_post_order.iter().enumerate() {
// Skip the entries superblock — it's an internal CFG artifact
if block_id == function.entries_block { continue; }
// Set the current block to the LIR block that corresponds to this
// HIR block.
let lir_block_id = hir_to_lir[block_id.0].unwrap();
asm.set_current_block(lir_block_id);
// Write a label to jump to the basic block
let label = jit.get_label(&mut asm, lir_block_id, block_id);
asm.write_label(label);
let block = function.block(block_id);
asm_comment!(
asm, "{block_id}({}): {}",
block.params().map(|param| format!("{param}")).collect::<Vec<_>>().join(", "),
iseq_get_location(iseq, block.insn_idx),
);
// Compile all parameters
for (idx, &insn_id) in block.params().enumerate() {
match function.find(insn_id) {
Insn::Param => {
jit.opnds[insn_id.0] = Some(gen_param(&mut asm, idx));
},
insn => unreachable!("Non-param insn found in block.params: {insn:?}"),
}
}
// In JIT entry blocks, compile LoadArg instructions before other instructions
// so that calling convention registers are reserved early, like Param.
if function.is_entry_block(block_id) {
for &insn_id in block.insns() {
if let Insn::LoadArg { idx, .. } = function.find(insn_id) {
jit.opnds[insn_id.0] = Some(gen_param(&mut asm, idx as usize));
}
}
}
// Compile all instructions
for (insn_idx, &insn_id) in block.insns().enumerate() {
let insn = function.find(insn_id);
// IfTrue and IfFalse should never be terminators
if matches!(insn, Insn::IfTrue {..} | Insn::IfFalse {..}) {
assert!(!insn.is_terminator(), "IfTrue/IfFalse should not be terminators");
}
match insn {
Insn::IfFalse { val, target } => {
let val_opnd = jit.get_opnd(val);
let lir_target = hir_to_lir[target.target.0].unwrap();
let fall_through_target = asm.new_block(block_id, false, rpo_idx);
let branch_edge = lir::BranchEdge {
target: lir_target,
args: target.args.iter().map(|insn_id| jit.get_opnd(*insn_id)).collect()
};
let fall_through_edge = lir::BranchEdge {
target: fall_through_target,
args: vec![]
};
gen_if_false(&mut asm, val_opnd, branch_edge, fall_through_edge);
assert!(asm.current_block().insns.last().unwrap().is_terminator());
asm.set_current_block(fall_through_target);
let label = jit.get_label(&mut asm, fall_through_target, block_id);
asm.write_label(label);
},
Insn::IfTrue { val, target } => {
let val_opnd = jit.get_opnd(val);
let lir_target = hir_to_lir[target.target.0].unwrap();
let fall_through_target = asm.new_block(block_id, false, rpo_idx);
let branch_edge = lir::BranchEdge {
target: lir_target,
args: target.args.iter().map(|insn_id| jit.get_opnd(*insn_id)).collect()
};
let fall_through_edge = lir::BranchEdge {
target: fall_through_target,
args: vec![]
};
gen_if_true(&mut asm, val_opnd, branch_edge, fall_through_edge);
assert!(asm.current_block().insns.last().unwrap().is_terminator());
asm.set_current_block(fall_through_target);
let label = jit.get_label(&mut asm, fall_through_target, block_id);
asm.write_label(label);
}
Insn::Jump(target) => {
let lir_target = hir_to_lir[target.target.0].unwrap();
let branch_edge = lir::BranchEdge {
target: lir_target,
args: target.args.iter().map(|insn_id| jit.get_opnd(*insn_id)).collect()
};
gen_jump(&mut asm, branch_edge);
assert!(asm.current_block().insns.last().unwrap().is_terminator());
// Jump should always be the last instruction in an HIR block
assert!(insn_idx == block.insns().len() - 1, "Jump must be the last instruction in HIR block");
},
_ => {
// Start a new perf range for the HIR instruction. For now, we do this only for
// non-terminator instructions because LIR blocks must end with a terminator instruction.
let perf_symbol = if get_option!(perf) == Some(PerfMap::HIR) && !insn.is_terminator() {
let insn_name = format!("{insn}").split_whitespace().next().unwrap().to_string();
Some(perf_symbol_range_start(&mut asm, &insn_name))
} else {
None
};
let result = gen_insn(cb, &mut jit, &mut asm, function, insn_id, &insn);
// Close the current perf range for the HIR instruction.
if let Some(perf_symbol) = &perf_symbol {
perf_symbol_range_end(&mut asm, perf_symbol);
}
if let Err(last_snapshot) = result {
debug!("ZJIT: gen_function: Failed to compile insn: {insn_id} {insn}. Generating side-exit.");
gen_incr_counter(&mut asm, exit_counter_for_unhandled_hir_insn(&insn));
let reason = match insn {
Insn::ArrayMax { .. } => SideExitReason::UnhandledHIRArrayMax,
Insn::FixnumDiv { .. } => SideExitReason::UnhandledHIRFixnumDiv,
Insn::Throw { .. } => SideExitReason::UnhandledHIRThrow,
Insn::InvokeBuiltin { .. } => SideExitReason::UnhandledHIRInvokeBuiltin,
_ => SideExitReason::UnhandledHIRUnknown(insn_id),
};
gen_side_exit(&mut jit, &mut asm, &reason, &None, &function.frame_state(last_snapshot));
// Don't bother generating code after a side-exit. We won't run it.
// TODO(max): Generate ud2 or equivalent.
break;
};
// It's fine; we generated the instruction
}
}
}
// Blocks should always end with control flow
assert!(asm.current_block().insns.last().unwrap().is_terminator());
}
assert!(!asm.rpo().is_empty());
// Validate CFG invariants after HIR to LIR lowering
asm.validate_jump_positions();
// Generate code if everything can be compiled
let result = asm.compile(cb);
if let Ok((start_ptr, _)) = result {
if get_option!(perf) == Some(PerfMap::ISEQ) {
let start_usize = start_ptr.raw_addr(cb);
let end_usize = cb.get_write_ptr().raw_addr(cb);
let code_size = end_usize - start_usize;
let iseq_name = iseq_get_location(iseq, 0);
register_with_perf(iseq_name, start_usize, code_size);
}
if ZJITState::should_log_compiled_iseqs() {
let iseq_name = iseq_get_location(iseq, 0);
ZJITState::log_compile(iseq_name);
}
}
result.map(|(start_ptr, gc_offsets)| {
// Make sure jit_entry_ptrs can be used as a parallel vector to jit_entry_insns()
jit.jit_entries.sort_by_key(|jit_entry| jit_entry.borrow().jit_entry_idx);
let jit_entry_ptrs = jit.jit_entries.iter().map(|jit_entry|
jit_entry.borrow().start_addr.get().expect("start_addr should have been set by pos_marker in gen_entry_point")
).collect();
(IseqCodePtrs { start_ptr, jit_entry_ptrs }, gc_offsets, jit.iseq_calls)
})
}
/// Compile an instruction
fn gen_insn(cb: &mut CodeBlock, jit: &mut JITState, asm: &mut Assembler, function: &Function, insn_id: InsnId, insn: &Insn) -> Result<(), InsnId> {
// Convert InsnId to lir::Opnd
macro_rules! opnd {
($insn_id:ident) => {
jit.get_opnd($insn_id.clone())
};
}
macro_rules! opnds {
($insn_ids:ident) => {
{
$insn_ids.iter().map(|insn_id| jit.get_opnd(*insn_id)).collect::<Vec<_>>()
}
};
}
macro_rules! no_output {
($call:expr) => {
{ let () = $call; return Ok(()); }
};
}
if !matches!(*insn, Insn::Snapshot { .. }) {
asm_comment!(asm, "Insn: {insn_id} {insn}");
}
let out_opnd = match insn {
&Insn::Const { val: Const::Value(val) } => gen_const_value(val),
&Insn::Const { val: Const::CPtr(val) } => gen_const_cptr(val),
&Insn::Const { val: Const::CInt64(val) } => gen_const_long(val),
&Insn::Const { val: Const::CUInt16(val) } => gen_const_uint16(val),
&Insn::Const { val: Const::CUInt32(val) } => gen_const_uint32(val),
&Insn::Const { val: Const::CShape(val) } => {
assert_eq!(SHAPE_ID_NUM_BITS, 32);
gen_const_uint32(val.0)
}
Insn::Const { .. } => panic!("Unexpected Const in gen_insn: {insn}"),
Insn::NewArray { elements, state } => gen_new_array(asm, opnds!(elements), &function.frame_state(*state)),
Insn::NewHash { elements, state } => gen_new_hash(jit, asm, opnds!(elements), &function.frame_state(*state)),
Insn::NewRange { low, high, flag, state } => gen_new_range(jit, asm, opnd!(low), opnd!(high), *flag, &function.frame_state(*state)),
Insn::NewRangeFixnum { low, high, flag, state } => gen_new_range_fixnum(asm, opnd!(low), opnd!(high), *flag, &function.frame_state(*state)),
Insn::ArrayDup { val, state } => gen_array_dup(asm, opnd!(val), &function.frame_state(*state)),
Insn::AdjustBounds { index, length } => gen_adjust_bounds(asm, opnd!(index), opnd!(length)),
Insn::ArrayAref { array, index, .. } => gen_array_aref(asm, opnd!(array), opnd!(index)),
Insn::ArrayAset { array, index, val } => {
no_output!(gen_array_aset(asm, opnd!(array), opnd!(index), opnd!(val)))
}
Insn::ArrayPop { array, state } => gen_array_pop(asm, opnd!(array), &function.frame_state(*state)),
Insn::ArrayLength { array } => gen_array_length(asm, opnd!(array)),
Insn::ObjectAlloc { val, state } => gen_object_alloc(jit, asm, opnd!(val), &function.frame_state(*state)),
&Insn::ObjectAllocClass { class, state } => gen_object_alloc_class(asm, class, &function.frame_state(state)),
Insn::StringCopy { val, chilled, state } => gen_string_copy(asm, opnd!(val), *chilled, &function.frame_state(*state)),
// concatstrings shouldn't have 0 strings
// If it happens we abort the compilation for now
Insn::StringConcat { strings, state, .. } if strings.is_empty() => return Err(*state),
Insn::StringConcat { strings, state } => gen_string_concat(jit, asm, opnds!(strings), &function.frame_state(*state)),
&Insn::StringGetbyte { string, index } => gen_string_getbyte(asm, opnd!(string), opnd!(index)),
Insn::StringSetbyteFixnum { string, index, value } => gen_string_setbyte_fixnum(asm, opnd!(string), opnd!(index), opnd!(value)),
Insn::StringAppend { recv, other, state } => gen_string_append(jit, asm, opnd!(recv), opnd!(other), &function.frame_state(*state)),
Insn::StringAppendCodepoint { recv, other, state } => gen_string_append_codepoint(jit, asm, opnd!(recv), opnd!(other), &function.frame_state(*state)),
Insn::StringEqual { left, right } => gen_string_equal(asm, opnd!(left), opnd!(right)),
Insn::StringIntern { val, state } => gen_intern(asm, opnd!(val), &function.frame_state(*state)),
Insn::ToRegexp { opt, values, state } => gen_toregexp(jit, asm, *opt, opnds!(values), &function.frame_state(*state)),
Insn::Param => unreachable!("block.insns should not have Insn::Param"),
Insn::LoadArg { .. } => return Ok(()), // compiled in the LoadArg pre-pass above
Insn::Snapshot { .. } => return Ok(()), // we don't need to do anything for this instruction at the moment
&Insn::Send { cd, block: None, state, reason, .. } => gen_send_without_block(jit, asm, cd, &function.frame_state(state), reason),
&Insn::Send { cd, block: Some(BlockHandler::BlockIseq(blockiseq)), state, reason, .. } => gen_send(jit, asm, cd, blockiseq, &function.frame_state(state), reason),
&Insn::Send { cd, block: Some(BlockHandler::BlockArg), state, reason, .. } => gen_send(jit, asm, cd, std::ptr::null(), &function.frame_state(state), reason),
&Insn::SendForward { cd, blockiseq, state, reason, .. } => gen_send_forward(jit, asm, cd, blockiseq, &function.frame_state(state), reason),
&Insn::SendDirect { cme, iseq, recv, ref args, kw_bits, block, state, .. } => gen_send_iseq_direct(
cb, jit, asm, cme, iseq, opnd!(recv), opnds!(args),
kw_bits, &function.frame_state(state), block,
),
&Insn::InvokeSuper { cd, blockiseq, state, reason, .. } => gen_invokesuper(jit, asm, cd, blockiseq, &function.frame_state(state), reason),
&Insn::InvokeSuperForward { cd, blockiseq, state, reason, .. } => gen_invokesuperforward(jit, asm, cd, blockiseq, &function.frame_state(state), reason),
&Insn::InvokeBlock { cd, state, reason, .. } => gen_invokeblock(jit, asm, cd, &function.frame_state(state), reason),
Insn::InvokeBlockIfunc { cd, block_handler, args, state, .. } => gen_invokeblock_ifunc(jit, asm, *cd, opnd!(block_handler), opnds!(args), &function.frame_state(*state)),
Insn::InvokeProc { recv, args, state, kw_splat } => gen_invokeproc(jit, asm, opnd!(recv), opnds!(args), *kw_splat, &function.frame_state(*state)),
// Ensure we have enough room fit ec, self, and arguments
// TODO remove this check when we have stack args (we can use Time.new to test it)
Insn::InvokeBuiltin { bf, state, .. } if bf.argc + 2 > (C_ARG_OPNDS.len() as i32) => return Err(*state),
Insn::InvokeBuiltin { bf, leaf, args, state, .. } => gen_invokebuiltin(jit, asm, &function.frame_state(*state), bf, *leaf, opnds!(args)),
&Insn::EntryPoint { jit_entry_idx } => no_output!(gen_entry_point(jit, asm, jit_entry_idx)),
Insn::Return { val } => no_output!(gen_return(asm, opnd!(val))),
Insn::FixnumAdd { left, right, state } => gen_fixnum_add(jit, asm, opnd!(left), opnd!(right), &function.frame_state(*state)),
Insn::FixnumSub { left, right, state } => gen_fixnum_sub(jit, asm, opnd!(left), opnd!(right), &function.frame_state(*state)),
Insn::FixnumMult { left, right, state } => gen_fixnum_mult(jit, asm, opnd!(left), opnd!(right), &function.frame_state(*state)),
Insn::FixnumDiv { left, right, state } => gen_fixnum_div(jit, asm, opnd!(left), opnd!(right), &function.frame_state(*state)),
Insn::FixnumEq { left, right } => gen_fixnum_eq(asm, opnd!(left), opnd!(right)),
Insn::FixnumNeq { left, right } => gen_fixnum_neq(asm, opnd!(left), opnd!(right)),
Insn::FixnumLt { left, right } => gen_fixnum_lt(asm, opnd!(left), opnd!(right)),
Insn::FixnumLe { left, right } => gen_fixnum_le(asm, opnd!(left), opnd!(right)),
Insn::FixnumGt { left, right } => gen_fixnum_gt(asm, opnd!(left), opnd!(right)),
Insn::FixnumGe { left, right } => gen_fixnum_ge(asm, opnd!(left), opnd!(right)),
Insn::FixnumAnd { left, right } => gen_fixnum_and(asm, opnd!(left), opnd!(right)),
Insn::FixnumOr { left, right } => gen_fixnum_or(asm, opnd!(left), opnd!(right)),
Insn::FixnumXor { left, right } => gen_fixnum_xor(asm, opnd!(left), opnd!(right)),
Insn::IntAnd { left, right } => asm.and(opnd!(left), opnd!(right)),
Insn::IntOr { left, right } => gen_int_or(asm, opnd!(left), opnd!(right)),
&Insn::FixnumLShift { left, right, state } => {
// We only create FixnumLShift when we know the shift amount statically and it's in [0,
// 63].
let shift_amount = function.type_of(right).fixnum_value().unwrap() as u64;
gen_fixnum_lshift(jit, asm, opnd!(left), shift_amount, &function.frame_state(state))
}
&Insn::FixnumRShift { left, right } => {
// We only create FixnumRShift when we know the shift amount statically and it's in [0,
// 63].
let shift_amount = function.type_of(right).fixnum_value().unwrap() as u64;
gen_fixnum_rshift(asm, opnd!(left), shift_amount)
}
&Insn::FixnumMod { left, right, state } => gen_fixnum_mod(jit, asm, opnd!(left), opnd!(right), &function.frame_state(state)),
&Insn::FixnumAref { recv, index } => gen_fixnum_aref(asm, opnd!(recv), opnd!(index)),
Insn::IsNil { val } => gen_isnil(asm, opnd!(val)),
&Insn::IsMethodCfunc { val, cd, cfunc, state: _ } => gen_is_method_cfunc(jit, asm, opnd!(val), cd, cfunc),
&Insn::IsBitEqual { left, right } => gen_is_bit_equal(asm, opnd!(left), opnd!(right)),
&Insn::IsBitNotEqual { left, right } => gen_is_bit_not_equal(asm, opnd!(left), opnd!(right)),
&Insn::BoxBool { val } => gen_box_bool(asm, opnd!(val)),
&Insn::BoxFixnum { val, state } => gen_box_fixnum(jit, asm, opnd!(val), &function.frame_state(state)),
&Insn::UnboxFixnum { val } => gen_unbox_fixnum(asm, opnd!(val)),
Insn::Test { val } => gen_test(asm, opnd!(val)),
Insn::RefineType { val, .. } => opnd!(val),
Insn::HasType { val, expected } => gen_has_type(jit, asm, opnd!(val), *expected),
Insn::GuardType { val, guard_type, state } => gen_guard_type(jit, asm, opnd!(val), *guard_type, &function.frame_state(*state)),
Insn::GuardTypeNot { val, guard_type, state } => gen_guard_type_not(jit, asm, opnd!(val), *guard_type, &function.frame_state(*state)),
&Insn::GuardBitEquals { val, expected, reason, state } => gen_guard_bit_equals(jit, asm, opnd!(val), expected, reason, &function.frame_state(state)),
&Insn::GuardAnyBitSet { val, mask, reason, state, .. } => gen_guard_any_bit_set(jit, asm, opnd!(val), mask, reason, &function.frame_state(state)),
&Insn::GuardNoBitsSet { val, mask, reason, state, .. } => gen_guard_no_bits_set(jit, asm, opnd!(val), mask, reason, &function.frame_state(state)),
&Insn::GuardLess { left, right, state } => gen_guard_less(jit, asm, opnd!(left), opnd!(right), &function.frame_state(state)),
&Insn::GuardGreaterEq { left, right, state, .. } => gen_guard_greater_eq(jit, asm, opnd!(left), opnd!(right), &function.frame_state(state)),
Insn::PatchPoint { invariant, state } => no_output!(gen_patch_point(jit, asm, invariant, &function.frame_state(*state))),
Insn::CCall { cfunc, recv, args, name, owner: _, return_type: _, elidable: _ } => gen_ccall(asm, *cfunc, *name, opnd!(recv), opnds!(args)),
// Give up CCallWithFrame for 7+ args since asm.ccall() supports at most 6 args (recv + args).
// There's no test case for this because no core cfuncs have this many parameters. But C extensions could have such methods.
Insn::CCallWithFrame { cd, state, args, .. } if args.len() + 1 > C_ARG_OPNDS.len() =>
gen_send_without_block(jit, asm, *cd, &function.frame_state(*state), SendFallbackReason::CCallWithFrameTooManyArgs),
Insn::CCallWithFrame { cfunc, recv, name, args, cme, state, block, .. } =>
gen_ccall_with_frame(jit, asm, *cfunc, *name, opnd!(recv), opnds!(args), *cme, *block, &function.frame_state(*state)),
Insn::CCallVariadic { cfunc, recv, name, args, cme, state, block, return_type: _, elidable: _ } => {
gen_ccall_variadic(jit, asm, *cfunc, *name, opnd!(recv), opnds!(args), *cme, *block, &function.frame_state(*state))
}
Insn::GetIvar { self_val, id, ic, state: _ } => gen_getivar(jit, asm, opnd!(self_val), *id, *ic),
Insn::SetGlobal { id, val, state } => no_output!(gen_setglobal(jit, asm, *id, opnd!(val), &function.frame_state(*state))),
Insn::GetGlobal { id, state } => gen_getglobal(jit, asm, *id, &function.frame_state(*state)),
&Insn::IsBlockParamModified { ep } => gen_is_block_param_modified(asm, opnd!(ep)),
&Insn::GetBlockParam { ep_offset, level, state } => gen_getblockparam(jit, asm, ep_offset, level, &function.frame_state(state)),
&Insn::SetLocal { val, ep_offset, level } => no_output!(gen_setlocal(asm, opnd!(val), function.type_of(val), ep_offset, level)),
Insn::GetConstant { klass, id, allow_nil, state } => gen_getconstant(jit, asm, opnd!(klass), *id, opnd!(allow_nil), &function.frame_state(*state)),
Insn::GetConstantPath { ic, state } => gen_get_constant_path(jit, asm, *ic, &function.frame_state(*state)),
Insn::GetClassVar { id, ic, state } => gen_getclassvar(jit, asm, *id, *ic, &function.frame_state(*state)),
Insn::SetClassVar { id, val, ic, state } => no_output!(gen_setclassvar(jit, asm, *id, opnd!(val), *ic, &function.frame_state(*state))),
Insn::SetIvar { self_val, id, ic, val, state } => no_output!(gen_setivar(jit, asm, opnd!(self_val), *id, *ic, opnd!(val), &function.frame_state(*state))),
Insn::FixnumBitCheck { val, index } => gen_fixnum_bit_check(asm, opnd!(val), *index),
Insn::SideExit { state, reason, recompile } => no_output!(gen_side_exit(jit, asm, reason, recompile, &function.frame_state(*state))),
Insn::PutSpecialObject { value_type } => gen_putspecialobject(asm, *value_type),
Insn::AnyToString { val, str, state } => gen_anytostring(asm, opnd!(val), opnd!(str), &function.frame_state(*state)),
Insn::Defined { op_type, obj, pushval, v, state } => gen_defined(jit, asm, *op_type, *obj, *pushval, opnd!(v), &function.frame_state(*state)),
Insn::CheckMatch { target, pattern, flag, state } => gen_checkmatch(jit, asm, opnd!(target), opnd!(pattern), *flag, &function.frame_state(*state)),
Insn::GetSpecialSymbol { symbol_type, state: _ } => gen_getspecial_symbol(asm, *symbol_type),
Insn::GetSpecialNumber { nth, state } => gen_getspecial_number(asm, *nth, &function.frame_state(*state)),
&Insn::IncrCounter(counter) => no_output!(gen_incr_counter(asm, counter)),
Insn::IncrCounterPtr { counter_ptr } => no_output!(gen_incr_counter_ptr(asm, *counter_ptr)),
Insn::ObjToString { val, cd, state, .. } => gen_objtostring(jit, asm, opnd!(val), *cd, &function.frame_state(*state)),
&Insn::CheckInterrupts { state } => no_output!(gen_check_interrupts(jit, asm, &function.frame_state(state))),
Insn::BreakPoint => no_output!(asm.breakpoint()),
&Insn::HashDup { val, state } => { gen_hash_dup(asm, opnd!(val), &function.frame_state(state)) },
&Insn::HashAref { hash, key, state } => { gen_hash_aref(jit, asm, opnd!(hash), opnd!(key), &function.frame_state(state)) },
&Insn::HashAset { hash, key, val, state } => { no_output!(gen_hash_aset(jit, asm, opnd!(hash), opnd!(key), opnd!(val), &function.frame_state(state))) },
&Insn::ArrayPush { array, val, state } => { no_output!(gen_array_push(asm, opnd!(array), opnd!(val), &function.frame_state(state))) },
&Insn::ToNewArray { val, state } => { gen_to_new_array(jit, asm, opnd!(val), &function.frame_state(state)) },
&Insn::ToArray { val, state } => { gen_to_array(jit, asm, opnd!(val), &function.frame_state(state)) },
&Insn::DefinedIvar { self_val, id, pushval, .. } => { gen_defined_ivar(asm, opnd!(self_val), id, pushval) },
&Insn::ArrayExtend { left, right, state } => { no_output!(gen_array_extend(jit, asm, opnd!(left), opnd!(right), &function.frame_state(state))) },
Insn::LoadPC => gen_load_pc(asm),
Insn::LoadEC => gen_load_ec(),
Insn::LoadSP => gen_load_sp(),
&Insn::GetEP { level } => gen_get_ep(asm, level),
Insn::LoadSelf => gen_load_self(),
&Insn::LoadField { recv, id, offset, return_type } => gen_load_field(asm, opnd!(recv), id, offset, return_type),
&Insn::StoreField { recv, id, offset, val } => no_output!(gen_store_field(asm, opnd!(recv), id, offset, opnd!(val), function.type_of(val))),
&Insn::WriteBarrier { recv, val } => no_output!(gen_write_barrier(jit, asm, opnd!(recv), opnd!(val), function.type_of(val))),
&Insn::IsBlockGiven { lep } => gen_is_block_given(asm, opnd!(lep)),
Insn::ArrayInclude { elements, target, state } => gen_array_include(jit, asm, opnds!(elements), opnd!(target), &function.frame_state(*state)),
Insn::ArrayPackBuffer { elements, fmt, buffer, state } => gen_array_pack_buffer(jit, asm, opnds!(elements), opnd!(fmt), opnd!(buffer), &function.frame_state(*state)),
&Insn::DupArrayInclude { ary, target, state } => gen_dup_array_include(jit, asm, ary, opnd!(target), &function.frame_state(state)),
Insn::ArrayHash { elements, state } => gen_opt_newarray_hash(jit, asm, opnds!(elements), &function.frame_state(*state)),
&Insn::IsA { val, class } => gen_is_a(jit, asm, opnd!(val), opnd!(class)),
&Insn::ArrayMax { ref elements, state } => gen_array_max(jit, asm, opnds!(elements), &function.frame_state(state)),
&Insn::ArrayMin { ref elements, state } => gen_array_min(jit, asm, opnds!(elements), &function.frame_state(state)),
&Insn::Throw { state, .. } => return Err(state),
&Insn::IfFalse { .. } | Insn::IfTrue { .. }
| &Insn::Jump { .. } | Insn::Entries { .. } => unreachable!(),
};
assert!(insn.has_output(), "Cannot write LIR output of HIR instruction with no output: {insn}");
// If the instruction has an output, remember it in jit.opnds
jit.opnds[insn_id.0] = Some(out_opnd);
Ok(())
}
/// Gets the EP of the ISeq of the containing method, or "local level".
/// Equivalent of GET_LEP() macro.
fn gen_get_lep(jit: &JITState, asm: &mut Assembler) -> Opnd {
let level = get_lvar_level(jit.iseq);
gen_get_ep(asm, level)
}
// Get EP at `level` from CFP
fn gen_get_ep(asm: &mut Assembler, level: u32) -> Opnd {
// Load environment pointer EP from CFP into a register
let ep_opnd = Opnd::mem(64, CFP, RUBY_OFFSET_CFP_EP);
let mut ep_opnd = asm.load(ep_opnd);
for _ in 0..level {
// Get the previous EP from the current EP
// See GET_PREV_EP(ep) macro
// VALUE *prev_ep = ((VALUE *)((ep)[VM_ENV_DATA_INDEX_SPECVAL] & ~0x03))
const UNTAGGING_MASK: Opnd = Opnd::Imm(!0x03);
let offset = SIZEOF_VALUE_I32 * VM_ENV_DATA_INDEX_SPECVAL;
ep_opnd = asm.load(Opnd::mem(64, ep_opnd, offset));
ep_opnd = asm.and(ep_opnd, UNTAGGING_MASK);
}
ep_opnd
}
fn gen_objtostring(jit: &mut JITState, asm: &mut Assembler, val: Opnd, cd: *const rb_call_data, state: &FrameState) -> Opnd {
gen_prepare_non_leaf_call(jit, asm, state);
// TODO: Specialize for immediate types
// Call rb_vm_objtostring(cfp, recv, cd)
let ret = asm_ccall!(asm, rb_vm_objtostring, CFP, val, Opnd::const_ptr(cd));
// TODO: Call `to_s` on the receiver if rb_vm_objtostring returns Qundef
// Need to replicate what CALL_SIMPLE_METHOD does
asm_comment!(asm, "side-exit if rb_vm_objtostring returns Qundef");
asm.cmp(ret, Qundef.into());
asm.je(jit, side_exit(jit, state, ObjToStringFallback));
ret
}
fn gen_defined(jit: &JITState, asm: &mut Assembler, op_type: usize, obj: VALUE, pushval: VALUE, tested_value: Opnd, state: &FrameState) -> Opnd {
match op_type as defined_type {
DEFINED_YIELD => {
// `yield` goes to the block handler stowed in the "local" iseq which is
// the current iseq or a parent. Only the "method" iseq type can be passed a
// block handler. (e.g. `yield` in the top level script is a syntax error.)
//
// Similar to gen_is_block_given
let local_iseq = unsafe { rb_get_iseq_body_local_iseq(jit.iseq) };
assert_eq!(unsafe { rb_get_iseq_body_type(local_iseq) }, ISEQ_TYPE_METHOD,
"defined?(yield) in non-method iseq should be handled by HIR construction");
let lep = gen_get_lep(jit, asm);
let block_handler = asm.load(Opnd::mem(64, lep, SIZEOF_VALUE_I32 * VM_ENV_DATA_INDEX_SPECVAL));
let pushval = asm.load(pushval.into());
asm.cmp(block_handler, VM_BLOCK_HANDLER_NONE.into());
asm.csel_e(Qnil.into(), pushval)
}
_ => {
// Save the PC and SP because the callee may allocate or call #respond_to?
gen_prepare_non_leaf_call(jit, asm, state);
// TODO: Inline the cases for each op_type
// Call vm_defined(ec, reg_cfp, op_type, obj, v)
let def_result = asm_ccall!(asm, rb_vm_defined, EC, CFP, op_type.into(), obj.into(), tested_value);
asm.cmp(def_result.with_num_bits(8), 0.into());
asm.csel_ne(pushval.into(), Qnil.into())
}
}
}
/// Similar to gen_defined for DEFINED_YIELD
fn gen_is_block_given(asm: &mut Assembler, lep: Opnd) -> Opnd {
let block_handler = asm.load(Opnd::mem(64, lep, SIZEOF_VALUE_I32 * VM_ENV_DATA_INDEX_SPECVAL));
asm.cmp(block_handler, VM_BLOCK_HANDLER_NONE.into());
asm.csel_e(Qfalse.into(), Qtrue.into())
}
fn gen_unbox_fixnum(asm: &mut Assembler, val: Opnd) -> Opnd {
asm.rshift(val, Opnd::UImm(1))
}
/// Set a local variable from a higher scope or the heap. `local_ep_offset` is in number of VALUEs.
/// We generate this instruction with level=0 only when the local variable is on the heap, so we
/// can't optimize the level=0 case using the SP register.
fn gen_setlocal(asm: &mut Assembler, val: Opnd, val_type: Type, local_ep_offset: u32, level: u32) {
let local_ep_offset = c_int::try_from(local_ep_offset).unwrap_or_else(|_| panic!("Could not convert local_ep_offset {local_ep_offset} to i32"));
if level > 0 {
gen_incr_counter(asm, Counter::vm_write_to_parent_iseq_local_count);
}
let ep = gen_get_ep(asm, level);
// When we've proved that we're writing an immediate,
// we can skip the write barrier.
if val_type.is_immediate() {
let offset = -(SIZEOF_VALUE_I32 * local_ep_offset);
asm.mov(Opnd::mem(64, ep, offset), val);
} else {
// We're potentially writing a reference to an IMEMO/env object,
// so take care of the write barrier with a function.
let local_index = -local_ep_offset;
asm_ccall!(asm, rb_vm_env_write, ep, local_index.into(), val);
}
}
/// Returns 1 (as CBool) when VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM is set; returns 0 otherwise.
fn gen_is_block_param_modified(asm: &mut Assembler, ep: Opnd) -> Opnd {
let flags = asm.load(Opnd::mem(VALUE_BITS, ep, SIZEOF_VALUE_I32 * (VM_ENV_DATA_INDEX_FLAGS as i32)));
asm.test(flags, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM.into());
asm.csel_nz(Opnd::Imm(1), Opnd::Imm(0))
}
/// Get the block parameter as a Proc, write it to the environment,
/// and mark the flag as modified.
fn gen_getblockparam(jit: &mut JITState, asm: &mut Assembler, ep_offset: u32, level: u32, state: &FrameState) -> Opnd {
gen_prepare_leaf_call_with_gc(asm, state);
// Bail out if write barrier is required.
let ep = gen_get_ep(asm, level);
let flags = Opnd::mem(VALUE_BITS, ep, SIZEOF_VALUE_I32 * (VM_ENV_DATA_INDEX_FLAGS as i32));
asm.test(flags, VM_ENV_FLAG_WB_REQUIRED.into());
asm.jnz(jit, side_exit(jit, state, SideExitReason::BlockParamWbRequired));
// Convert block handler to Proc.
let block_handler = asm.load(Opnd::mem(VALUE_BITS, ep, SIZEOF_VALUE_I32 * VM_ENV_DATA_INDEX_SPECVAL));
let proc = asm_ccall!(asm, rb_vm_bh_to_procval, EC, block_handler);
// Write Proc to EP and mark modified.
let ep = gen_get_ep(asm, level);
let local_ep_offset = c_int::try_from(ep_offset).unwrap_or_else(|_| {
panic!("Could not convert local_ep_offset {ep_offset} to i32")
});
let offset = -(SIZEOF_VALUE_I32 * local_ep_offset);
asm.mov(Opnd::mem(VALUE_BITS, ep, offset), proc);
let flags = Opnd::mem(VALUE_BITS, ep, SIZEOF_VALUE_I32 * (VM_ENV_DATA_INDEX_FLAGS as i32));
let flags_val = asm.load(flags);
let modified = asm.or(flags_val, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM.into());
asm.store(flags, modified);
// Read the Proc from EP.
let ep = gen_get_ep(asm, level);
asm.load(Opnd::mem(VALUE_BITS, ep, offset))
}
fn gen_guard_less(jit: &mut JITState, asm: &mut Assembler, left: Opnd, right: Opnd, state: &FrameState) -> Opnd {
asm.cmp(left, right);
asm.jge(jit, side_exit(jit, state, SideExitReason::GuardLess));
left
}
fn gen_guard_greater_eq(jit: &mut JITState, asm: &mut Assembler, left: Opnd, right: Opnd, state: &FrameState) -> Opnd {
asm.cmp(left, right);
asm.jl(jit, side_exit(jit, state, SideExitReason::GuardGreaterEq));
left
}
fn gen_get_constant_path(jit: &JITState, asm: &mut Assembler, ic: *const iseq_inline_constant_cache, state: &FrameState) -> Opnd {
unsafe extern "C" {
fn rb_vm_opt_getconstant_path(ec: EcPtr, cfp: CfpPtr, ic: *const iseq_inline_constant_cache) -> VALUE;
}
// Anything could be called on const_missing
gen_prepare_non_leaf_call(jit, asm, state);
asm_ccall!(asm, rb_vm_opt_getconstant_path, EC, CFP, Opnd::const_ptr(ic))
}
fn gen_getconstant(jit: &mut JITState, asm: &mut Assembler, klass: Opnd, id: ID, allow_nil: Opnd, state: &FrameState) -> Opnd {
unsafe extern "C" {
fn rb_vm_get_ev_const(ec: EcPtr, klass: VALUE, id: ID, allow_nil: VALUE) -> VALUE;
}
// Constant lookup can raise and run arbitrary Ruby code via const_missing.
gen_prepare_non_leaf_call(jit, asm, state);
asm_ccall!(asm, rb_vm_get_ev_const, EC, klass, id.0.into(), allow_nil)
}
fn gen_fixnum_bit_check(asm: &mut Assembler, val: Opnd, index: u8) -> Opnd {
let bit_test: u64 = 0x01 << (index + 1);
asm.test(val, bit_test.into());
asm.csel_z(Qtrue.into(), Qfalse.into())
}
fn gen_invokebuiltin(jit: &JITState, asm: &mut Assembler, state: &FrameState, bf: &rb_builtin_function, leaf: bool, args: Vec<Opnd>) -> lir::Opnd {
assert!(bf.argc + 2 <= C_ARG_OPNDS.len() as i32,
"gen_invokebuiltin should not be called for builtin function {} with too many arguments: {}",
unsafe { std::ffi::CStr::from_ptr(bf.name).to_str().unwrap() },
bf.argc);
if leaf {
gen_prepare_leaf_call_with_gc(asm, state);
} else {
// Anything can happen inside builtin functions
gen_prepare_non_leaf_call(jit, asm, state);
}
let mut cargs = vec![EC];
cargs.extend(args);
asm.count_call_to(unsafe { std::ffi::CStr::from_ptr(bf.name).to_str().unwrap() });
asm.ccall(bf.func_ptr as *const u8, cargs)
}
/// Record a patch point that should be invalidated on a given invariant
fn gen_patch_point(jit: &mut JITState, asm: &mut Assembler, invariant: &Invariant, state: &FrameState) {
let invariant = *invariant;
let exit = build_side_exit(jit, state);
// Let compile_exits compile a side exit. Let scratch_split lower it with split_patch_point.
asm.patch_point(Target::SideExit { exit, reason: PatchPoint(invariant) }, invariant, jit.version);
}
/// This is used by scratch_split to lower PatchPoint into PadPatchPoint and PosMarker.
/// It's called at scratch_split so that we can use the Label after side-exit deduplication in compile_exits.
pub fn split_patch_point(asm: &mut Assembler, target: &Target, invariant: Invariant, version: IseqVersionRef) {
let Target::Label(exit_label) = *target else {
unreachable!("PatchPoint's target should have been lowered to Target::Label by compile_exits: {target:?}");
};
// Fill nop instructions if the last patch point is too close.
asm.pad_patch_point();
// Remember the current address as a patch point
asm.pos_marker(move |code_ptr, cb| {
let side_exit_ptr = cb.resolve_label(exit_label);
match invariant {
Invariant::BOPRedefined { klass, bop } => {
track_bop_assumption(klass, bop, code_ptr, side_exit_ptr, version);
}
Invariant::MethodRedefined { klass: _, method: _, cme } => {
track_cme_assumption(cme, code_ptr, side_exit_ptr, version);