-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
core.rs
3280 lines (2796 loc) · 114 KB
/
core.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
//! Code versioning, retained live control flow graph mutations, type tracking, etc.
// So we can comment on individual uses of `unsafe` in `unsafe` functions
#![warn(unsafe_op_in_unsafe_fn)]
use crate::asm::*;
use crate::backend::ir::*;
use crate::codegen::*;
use crate::virtualmem::CodePtr;
use crate::cruby::*;
use crate::options::*;
use crate::stats::*;
use crate::utils::*;
#[cfg(feature="disasm")]
use crate::disasm::*;
use core::ffi::c_void;
use std::cell::*;
use std::collections::HashSet;
use std::fmt;
use std::mem;
use std::ops::Range;
use std::rc::Rc;
use mem::MaybeUninit;
use std::ptr;
use ptr::NonNull;
use YARVOpnd::*;
use TempMapping::*;
use crate::invariants::*;
// Maximum number of temp value types we keep track of
pub const MAX_TEMP_TYPES: usize = 8;
// Maximum number of local variable types we keep track of
const MAX_LOCAL_TYPES: usize = 8;
/// An index into `ISEQ_BODY(iseq)->iseq_encoded`. Points
/// to a YARV instruction or an instruction operand.
pub type IseqIdx = u16;
// Represent the type of a value (local/stack/self) in YJIT
#[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
pub enum Type {
Unknown,
UnknownImm,
UnknownHeap,
Nil,
True,
False,
Fixnum,
Flonum,
Hash,
ImmSymbol,
#[allow(unused)]
HeapSymbol,
TString, // An object with the T_STRING flag set, possibly an rb_cString
CString, // An un-subclassed string of type rb_cString (can have instance vars in some cases)
TArray, // An object with the T_ARRAY flag set, possibly an rb_cArray
CArray, // An un-subclassed string of type rb_cArray (can have instance vars in some cases)
BlockParamProxy, // A special sentinel value indicating the block parameter should be read from
// the current surrounding cfp
}
// Default initialization
impl Default for Type {
fn default() -> Self {
Type::Unknown
}
}
impl Type {
/// This returns an appropriate Type based on a known value
pub fn from(val: VALUE) -> Type {
if val.special_const_p() {
if val.fixnum_p() {
Type::Fixnum
} else if val.nil_p() {
Type::Nil
} else if val == Qtrue {
Type::True
} else if val == Qfalse {
Type::False
} else if val.static_sym_p() {
Type::ImmSymbol
} else if val.flonum_p() {
Type::Flonum
} else {
unreachable!("Illegal value: {:?}", val)
}
} else {
// Core.rs can't reference rb_cString because it's linked by Rust-only tests.
// But CString vs TString is only an optimisation and shouldn't affect correctness.
#[cfg(not(test))]
if val.class_of() == unsafe { rb_cString } {
return Type::CString;
}
#[cfg(not(test))]
if val.class_of() == unsafe { rb_cArray } {
return Type::CArray;
}
// We likewise can't reference rb_block_param_proxy, but it's again an optimisation;
// we can just treat it as a normal Object.
#[cfg(not(test))]
if val == unsafe { rb_block_param_proxy } {
return Type::BlockParamProxy;
}
match val.builtin_type() {
RUBY_T_ARRAY => Type::TArray,
RUBY_T_HASH => Type::Hash,
RUBY_T_STRING => Type::TString,
_ => Type::UnknownHeap,
}
}
}
/// Check if the type is an immediate
pub fn is_imm(&self) -> bool {
match self {
Type::UnknownImm => true,
Type::Nil => true,
Type::True => true,
Type::False => true,
Type::Fixnum => true,
Type::Flonum => true,
Type::ImmSymbol => true,
_ => false,
}
}
/// Returns true when the type is not specific.
pub fn is_unknown(&self) -> bool {
match self {
Type::Unknown | Type::UnknownImm | Type::UnknownHeap => true,
_ => false,
}
}
/// Returns true when we know the VALUE is a specific handle type,
/// such as a static symbol ([Type::ImmSymbol], i.e. true from RB_STATIC_SYM_P()).
/// Opposite of [Self::is_unknown].
pub fn is_specific(&self) -> bool {
!self.is_unknown()
}
/// Check if the type is a heap object
pub fn is_heap(&self) -> bool {
match self {
Type::UnknownHeap => true,
Type::TArray => true,
Type::CArray => true,
Type::Hash => true,
Type::HeapSymbol => true,
Type::TString => true,
Type::CString => true,
Type::BlockParamProxy => true,
_ => false,
}
}
/// Check if it's a T_ARRAY object (both TArray and CArray are T_ARRAY)
pub fn is_array(&self) -> bool {
match self {
Type::TArray => true,
Type::CArray => true,
_ => false,
}
}
/// Check if it's a T_STRING object (both TString and CString are T_STRING)
pub fn is_string(&self) -> bool {
match self {
Type::TString => true,
Type::CString => true,
_ => false,
}
}
/// Returns an Option with the T_ value type if it is known, otherwise None
pub fn known_value_type(&self) -> Option<ruby_value_type> {
match self {
Type::Nil => Some(RUBY_T_NIL),
Type::True => Some(RUBY_T_TRUE),
Type::False => Some(RUBY_T_FALSE),
Type::Fixnum => Some(RUBY_T_FIXNUM),
Type::Flonum => Some(RUBY_T_FLOAT),
Type::TArray | Type::CArray => Some(RUBY_T_ARRAY),
Type::Hash => Some(RUBY_T_HASH),
Type::ImmSymbol | Type::HeapSymbol => Some(RUBY_T_SYMBOL),
Type::TString | Type::CString => Some(RUBY_T_STRING),
Type::Unknown | Type::UnknownImm | Type::UnknownHeap => None,
Type::BlockParamProxy => None,
}
}
/// Returns an Option with the class if it is known, otherwise None
pub fn known_class(&self) -> Option<VALUE> {
unsafe {
match self {
Type::Nil => Some(rb_cNilClass),
Type::True => Some(rb_cTrueClass),
Type::False => Some(rb_cFalseClass),
Type::Fixnum => Some(rb_cInteger),
Type::Flonum => Some(rb_cFloat),
Type::ImmSymbol | Type::HeapSymbol => Some(rb_cSymbol),
Type::CString => Some(rb_cString),
Type::CArray => Some(rb_cArray),
_ => None,
}
}
}
/// Returns an Option with the exact value if it is known, otherwise None
#[allow(unused)] // not yet used
pub fn known_exact_value(&self) -> Option<VALUE> {
match self {
Type::Nil => Some(Qnil),
Type::True => Some(Qtrue),
Type::False => Some(Qfalse),
_ => None,
}
}
/// Returns an Option boolean representing whether the value is truthy if known, otherwise None
pub fn known_truthy(&self) -> Option<bool> {
match self {
Type::Nil => Some(false),
Type::False => Some(false),
Type::UnknownHeap => Some(true),
Type::Unknown | Type::UnknownImm => None,
_ => Some(true)
}
}
/// Returns an Option boolean representing whether the value is equal to nil if known, otherwise None
pub fn known_nil(&self) -> Option<bool> {
match (self, self.known_truthy()) {
(Type::Nil, _) => Some(true),
(Type::False, _) => Some(false), // Qfalse is not nil
(_, Some(true)) => Some(false), // if truthy, can't be nil
(_, _) => None // otherwise unknown
}
}
/// Compute a difference between two value types
pub fn diff(self, dst: Self) -> TypeDiff {
// Perfect match, difference is zero
if self == dst {
return TypeDiff::Compatible(0);
}
// Any type can flow into an unknown type
if dst == Type::Unknown {
return TypeDiff::Compatible(1);
}
// A CString is also a TString.
if self == Type::CString && dst == Type::TString {
return TypeDiff::Compatible(1);
}
// A CArray is also a TArray.
if self == Type::CArray && dst == Type::TArray {
return TypeDiff::Compatible(1);
}
// Specific heap type into unknown heap type is imperfect but valid
if self.is_heap() && dst == Type::UnknownHeap {
return TypeDiff::Compatible(1);
}
// Specific immediate type into unknown immediate type is imperfect but valid
if self.is_imm() && dst == Type::UnknownImm {
return TypeDiff::Compatible(1);
}
// Incompatible types
return TypeDiff::Incompatible;
}
/// Upgrade this type into a more specific compatible type
/// The new type must be compatible and at least as specific as the previously known type.
fn upgrade(&mut self, new_type: Self) {
// We can only upgrade to a type that is more specific
assert!(new_type.diff(*self) != TypeDiff::Incompatible);
*self = new_type;
}
}
#[derive(Debug, Eq, PartialEq)]
pub enum TypeDiff {
// usize == 0: Same type
// usize >= 1: Different but compatible. The smaller, the more compatible.
Compatible(usize),
Incompatible,
}
// Potential mapping of a value on the temporary stack to
// self, a local variable or constant so that we can track its type
#[derive(Copy, Clone, Eq, Hash, PartialEq, Debug)]
pub enum TempMapping {
MapToStack, // Normal stack value
MapToSelf, // Temp maps to the self operand
MapToLocal(LocalIndex), // Temp maps to a local variable with index
//ConstMapping, // Small constant (0, 1, 2, Qnil, Qfalse, Qtrue)
}
// Index used by MapToLocal. Using this instead of u8 makes TempMapping 1 byte.
#[derive(Copy, Clone, Eq, Hash, PartialEq, Debug)]
pub enum LocalIndex {
Local0,
Local1,
Local2,
Local3,
Local4,
Local5,
Local6,
Local7,
}
impl From<LocalIndex> for u8 {
fn from(idx: LocalIndex) -> Self {
match idx {
LocalIndex::Local0 => 0,
LocalIndex::Local1 => 1,
LocalIndex::Local2 => 2,
LocalIndex::Local3 => 3,
LocalIndex::Local4 => 4,
LocalIndex::Local5 => 5,
LocalIndex::Local6 => 6,
LocalIndex::Local7 => 7,
}
}
}
impl From<u8> for LocalIndex {
fn from(idx: u8) -> Self {
match idx {
0 => LocalIndex::Local0,
1 => LocalIndex::Local1,
2 => LocalIndex::Local2,
3 => LocalIndex::Local3,
4 => LocalIndex::Local4,
5 => LocalIndex::Local5,
6 => LocalIndex::Local6,
7 => LocalIndex::Local7,
_ => unreachable!("{idx} was larger than {MAX_LOCAL_TYPES}"),
}
}
}
impl Default for TempMapping {
fn default() -> Self {
MapToStack
}
}
// Operand to a YARV bytecode instruction
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum YARVOpnd {
// The value is self
SelfOpnd,
// Temporary stack operand with stack index
StackOpnd(u8),
}
impl From<Opnd> for YARVOpnd {
fn from(value: Opnd) -> Self {
match value {
Opnd::Stack { idx, .. } => StackOpnd(idx.try_into().unwrap()),
_ => unreachable!("{:?} cannot be converted to YARVOpnd", value)
}
}
}
/// Maximum index of stack temps that could be in a register
pub const MAX_REG_TEMPS: u8 = 8;
/// Bitmap of which stack temps are in a register
#[derive(Copy, Clone, Default, Eq, Hash, PartialEq, Debug)]
pub struct RegTemps(u8);
impl RegTemps {
pub fn get(&self, index: u8) -> bool {
assert!(index < MAX_REG_TEMPS);
(self.0 >> index) & 1 == 1
}
pub fn set(&mut self, index: u8, value: bool) {
assert!(index < MAX_REG_TEMPS);
if value {
self.0 = self.0 | (1 << index);
} else {
self.0 = self.0 & !(1 << index);
}
}
pub fn as_u8(&self) -> u8 {
self.0
}
/// Return true if there's a register that conflicts with a given stack_idx.
pub fn conflicts_with(&self, stack_idx: u8) -> bool {
let mut other_idx = stack_idx as isize - get_option!(num_temp_regs) as isize;
while other_idx >= 0 {
if self.get(other_idx as u8) {
return true;
}
other_idx -= get_option!(num_temp_regs) as isize;
}
false
}
}
/// Code generation context
/// Contains information we can use to specialize/optimize code
/// There are a lot of context objects so we try to keep the size small.
#[derive(Clone, Copy, Default, Eq, Hash, PartialEq, Debug)]
pub struct Context {
// Number of values currently on the temporary stack
stack_size: u8,
// Offset of the JIT SP relative to the interpreter SP
// This represents how far the JIT's SP is from the "real" SP
sp_offset: i8,
/// Bitmap of which stack temps are in a register
reg_temps: RegTemps,
// Depth of this block in the sidechain (eg: inline-cache chain)
chain_depth: u8,
// Local variable types we keep track of
local_types: [Type; MAX_LOCAL_TYPES],
// Temporary variable types we keep track of
temp_types: [Type; MAX_TEMP_TYPES],
// Type we track for self
self_type: Type,
// Mapping of temp stack entries to types we track
temp_mapping: [TempMapping; MAX_TEMP_TYPES],
}
/// Tuple of (iseq, idx) used to identify basic blocks
/// There are a lot of blockid objects so we try to keep the size small.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[repr(packed)]
pub struct BlockId {
/// Instruction sequence
pub iseq: IseqPtr,
/// Index in the iseq where the block starts
pub idx: u16,
}
/// Branch code shape enumeration
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum BranchShape {
Next0, // Target 0 is next
Next1, // Target 1 is next
Default, // Neither target is next
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BranchGenFn {
BranchIf(Cell<BranchShape>),
BranchNil(Cell<BranchShape>),
BranchUnless(Cell<BranchShape>),
JumpToTarget0(Cell<BranchShape>),
JNZToTarget0,
JZToTarget0,
JBEToTarget0,
JITReturn,
}
impl BranchGenFn {
pub fn call(&self, asm: &mut Assembler, target0: Target, target1: Option<Target>) {
match self {
BranchGenFn::BranchIf(shape) => {
match shape.get() {
BranchShape::Next0 => asm.jz(target1.unwrap()),
BranchShape::Next1 => asm.jnz(target0),
BranchShape::Default => {
asm.jnz(target0.into());
asm.jmp(target1.unwrap().into());
}
}
}
BranchGenFn::BranchNil(shape) => {
match shape.get() {
BranchShape::Next0 => asm.jne(target1.unwrap()),
BranchShape::Next1 => asm.je(target0),
BranchShape::Default => {
asm.je(target0);
asm.jmp(target1.unwrap());
}
}
}
BranchGenFn::BranchUnless(shape) => {
match shape.get() {
BranchShape::Next0 => asm.jnz(target1.unwrap()),
BranchShape::Next1 => asm.jz(target0),
BranchShape::Default => {
asm.jz(target0);
asm.jmp(target1.unwrap());
}
}
}
BranchGenFn::JumpToTarget0(shape) => {
if shape.get() == BranchShape::Next1 {
panic!("Branch shape Next1 not allowed in JumpToTarget0!");
}
if shape.get() == BranchShape::Default {
asm.jmp(target0.into());
}
}
BranchGenFn::JNZToTarget0 => {
asm.jnz(target0.into())
}
BranchGenFn::JZToTarget0 => {
asm.jz(target0)
}
BranchGenFn::JBEToTarget0 => {
asm.jbe(target0)
}
BranchGenFn::JITReturn => {
asm.comment("update cfp->jit_return");
asm.mov(Opnd::mem(64, CFP, RUBY_OFFSET_CFP_JIT_RETURN), Opnd::const_ptr(target0.unwrap_code_ptr().raw_ptr()));
}
}
}
pub fn get_shape(&self) -> BranchShape {
match self {
BranchGenFn::BranchIf(shape) |
BranchGenFn::BranchNil(shape) |
BranchGenFn::BranchUnless(shape) |
BranchGenFn::JumpToTarget0(shape) => shape.get(),
BranchGenFn::JNZToTarget0 |
BranchGenFn::JZToTarget0 |
BranchGenFn::JBEToTarget0 |
BranchGenFn::JITReturn => BranchShape::Default,
}
}
pub fn set_shape(&self, new_shape: BranchShape) {
match self {
BranchGenFn::BranchIf(shape) |
BranchGenFn::BranchNil(shape) |
BranchGenFn::BranchUnless(shape) => {
shape.set(new_shape);
}
BranchGenFn::JumpToTarget0(shape) => {
if new_shape == BranchShape::Next1 {
panic!("Branch shape Next1 not allowed in JumpToTarget0!");
}
shape.set(new_shape);
}
BranchGenFn::JNZToTarget0 |
BranchGenFn::JZToTarget0 |
BranchGenFn::JBEToTarget0 |
BranchGenFn::JITReturn => {
assert_eq!(new_shape, BranchShape::Default);
}
}
}
}
/// A place that a branch could jump to
#[derive(Debug, Clone)]
enum BranchTarget {
Stub(Box<BranchStub>), // Not compiled yet
Block(BlockRef), // Already compiled
}
impl BranchTarget {
fn get_address(&self) -> Option<CodePtr> {
match self {
BranchTarget::Stub(stub) => stub.address,
BranchTarget::Block(blockref) => Some(unsafe { blockref.as_ref() }.start_addr),
}
}
fn get_blockid(&self) -> BlockId {
match self {
BranchTarget::Stub(stub) => BlockId { iseq: stub.iseq.get(), idx: stub.iseq_idx },
BranchTarget::Block(blockref) => unsafe { blockref.as_ref() }.get_blockid(),
}
}
fn get_ctx(&self) -> Context {
match self {
BranchTarget::Stub(stub) => stub.ctx.clone(),
BranchTarget::Block(blockref) => unsafe { blockref.as_ref() }.ctx.clone(),
}
}
fn get_block(&self) -> Option<BlockRef> {
match self {
BranchTarget::Stub(_) => None,
BranchTarget::Block(blockref) => Some(*blockref),
}
}
fn set_iseq(&self, iseq: IseqPtr) {
match self {
BranchTarget::Stub(stub) => stub.iseq.set(iseq),
BranchTarget::Block(blockref) => unsafe { blockref.as_ref() }.iseq.set(iseq),
}
}
}
#[derive(Debug, Clone)]
struct BranchStub {
address: Option<CodePtr>,
iseq: Cell<IseqPtr>,
iseq_idx: IseqIdx,
ctx: Context,
}
/// Store info about an outgoing branch in a code segment
/// Note: care must be taken to minimize the size of branch objects
pub struct Branch {
// Block this is attached to
block: BlockRef,
// Positions where the generated code starts and ends
start_addr: CodePtr,
end_addr: Cell<CodePtr>, // exclusive
// Branch target blocks and their contexts
targets: [Cell<Option<Box<BranchTarget>>>; 2],
// Branch code generation function
gen_fn: BranchGenFn,
}
/// A [Branch] for a [Block] that is under construction.
/// Fields correspond, but may be `None` during construction.
pub struct PendingBranch {
/// Allocation holder for the address of the constructed branch
/// in error paths Box deallocates it.
uninit_branch: Box<MaybeUninit<Branch>>,
/// Branch code generation function
gen_fn: BranchGenFn,
/// Positions where the generated code starts and ends
start_addr: Cell<Option<CodePtr>>,
end_addr: Cell<Option<CodePtr>>, // exclusive
/// Branch target blocks and their contexts
targets: [Cell<Option<Box<BranchTarget>>>; 2],
}
impl Branch {
// Compute the size of the branch code
fn code_size(&self) -> usize {
(self.end_addr.get().raw_ptr() as usize) - (self.start_addr.raw_ptr() as usize)
}
/// Get the address of one of the branch destination
fn get_target_address(&self, target_idx: usize) -> Option<CodePtr> {
unsafe {
self.targets[target_idx]
.ref_unchecked()
.as_ref()
.and_then(|target| target.get_address())
}
}
fn get_stub_count(&self) -> usize {
let mut count = 0;
for target in self.targets.iter() {
if unsafe {
// SAFETY: no mutation
matches!(
target.ref_unchecked().as_ref().map(Box::as_ref),
Some(BranchTarget::Stub(_))
)
} {
count += 1;
}
}
count
}
fn assert_layout(&self) {
let shape = self.gen_fn.get_shape();
assert!(
!(shape == BranchShape::Default && 0 == self.code_size()),
"zero-size branches are incorrect when code for neither targets are adjacent"
// One needs to issue some instruction to steer to the branch target
// when falling through isn't an option.
);
}
}
impl std::fmt::Debug for Branch {
// Can't derive this because `targets: !Copy` due to Cell.
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let targets = unsafe {
// SAFETY:
// While the references are live for the result of this function,
// no mutation happens because we are only calling derived fmt::Debug functions.
[self.targets[0].as_ptr().as_ref().unwrap(), self.targets[1].as_ptr().as_ref().unwrap()]
};
formatter
.debug_struct("Branch")
.field("block", &self.block)
.field("start", &self.start_addr)
.field("end", &self.end_addr)
.field("targets", &targets)
.field("gen_fn", &self.gen_fn)
.finish()
}
}
impl PendingBranch {
/// Set up a branch target at `target_idx`. Find an existing block to branch to
/// or generate a stub for one.
fn set_target(
&self,
target_idx: u32,
target: BlockId,
ctx: &Context,
ocb: &mut OutlinedCb,
) -> Option<CodePtr> {
// If the block already exists
if let Some(blockref) = find_block_version(target, ctx) {
let block = unsafe { blockref.as_ref() };
// Fill out the target with this block
self.targets[target_idx.as_usize()]
.set(Some(Box::new(BranchTarget::Block(blockref))));
return Some(block.start_addr);
}
// The branch struct is uninitialized right now but as a stable address.
// We make sure the stub runs after the branch is initialized.
let branch_struct_addr = self.uninit_branch.as_ptr() as usize;
let stub_addr = gen_branch_stub(ctx, ocb, branch_struct_addr, target_idx);
if let Some(stub_addr) = stub_addr {
// Fill the branch target with a stub
self.targets[target_idx.as_usize()].set(Some(Box::new(BranchTarget::Stub(Box::new(BranchStub {
address: Some(stub_addr),
iseq: Cell::new(target.iseq),
iseq_idx: target.idx,
ctx: ctx.clone(),
})))));
}
stub_addr
}
// Construct the branch and wire it up in the grpah
fn into_branch(mut self, uninit_block: BlockRef) -> BranchRef {
// Make the branch
let branch = Branch {
block: uninit_block,
start_addr: self.start_addr.get().unwrap(),
end_addr: Cell::new(self.end_addr.get().unwrap()),
targets: self.targets,
gen_fn: self.gen_fn,
};
// Move it to the designated place on
// the heap and unwrap MaybeUninit.
self.uninit_branch.write(branch);
let raw_branch: *mut MaybeUninit<Branch> = Box::into_raw(self.uninit_branch);
let branchref = NonNull::new(raw_branch as *mut Branch).expect("no null from Box");
// SAFETY: just allocated it
let branch = unsafe { branchref.as_ref() };
// For block branch targets, put the new branch in the
// appropriate incoming list.
for target in branch.targets.iter() {
// SAFETY: no mutation
let out_block: Option<BlockRef> = unsafe {
target.ref_unchecked().as_ref().and_then(|target| target.get_block())
};
if let Some(out_block) = out_block {
// SAFETY: These blockrefs come from set_target() which only puts blocks from
// ISeqs, which are all initialized. Note that uninit_block isn't in any ISeq
// payload yet.
unsafe { out_block.as_ref() }.incoming.push(branchref);
}
}
branch.assert_layout();
branchref
}
}
// Store info about code used on YJIT entry
pub struct Entry {
// Positions where the generated code starts and ends
start_addr: CodePtr,
end_addr: CodePtr, // exclusive
}
/// A [Branch] for a [Block] that is under construction.
pub struct PendingEntry {
pub uninit_entry: Box<MaybeUninit<Entry>>,
start_addr: Cell<Option<CodePtr>>,
end_addr: Cell<Option<CodePtr>>, // exclusive
}
impl PendingEntry {
// Construct the entry in the heap
pub fn into_entry(mut self) -> EntryRef {
// Make the entry
let entry = Entry {
start_addr: self.start_addr.get().unwrap(),
end_addr: self.end_addr.get().unwrap(),
};
// Move it to the designated place on the heap and unwrap MaybeUninit.
self.uninit_entry.write(entry);
let raw_entry: *mut MaybeUninit<Entry> = Box::into_raw(self.uninit_entry);
NonNull::new(raw_entry as *mut Entry).expect("no null from Box")
}
}
// In case a block is invalidated, this helps to remove all pointers to the block.
pub type CmePtr = *const rb_callable_method_entry_t;
/// Basic block version
/// Represents a portion of an iseq compiled with a given context
/// Note: care must be taken to minimize the size of block_t objects
#[derive(Debug)]
pub struct Block {
// The byte code instruction sequence this is a version of.
// Can change due to moving GC.
iseq: Cell<IseqPtr>,
// Index range covered by this version in `ISEQ_BODY(iseq)->iseq_encoded`.
iseq_range: Range<IseqIdx>,
// Context at the start of the block
// This should never be mutated
ctx: Context,
// Positions where the generated code starts and ends
start_addr: CodePtr,
end_addr: Cell<CodePtr>,
// List of incoming branches (from predecessors)
// These are reference counted (ownership shared between predecessor and successors)
incoming: MutableBranchList,
// NOTE: we might actually be able to store the branches here without refcounting
// however, using a RefCell makes it easy to get a pointer to Branch objects
//
// List of outgoing branches (to successors)
outgoing: Box<[BranchRef]>,
// FIXME: should these be code pointers instead?
// Offsets for GC managed objects in the mainline code block
gc_obj_offsets: Box<[u32]>,
// CME dependencies of this block, to help to remove all pointers to this
// block in the system.
cme_dependencies: Box<[Cell<CmePtr>]>,
// Code address of an exit for `ctx` and `blockid`.
// Used for block invalidation.
entry_exit: Option<CodePtr>,
}
/// Pointer to a [Block].
///
/// # Safety
///
/// _Never_ derive a `&mut Block` from this and always use
/// [std::ptr::NonNull::as_ref] to get a `&Block`. `&'a mut`
/// in Rust asserts that there are no other references live
/// over the lifetime `'a`. This uniqueness assertion does
/// not hold in many situations for us, even when you ignore
/// the fact that our control flow graph can have cycles.
/// Here are just two examples where we have overlapping references:
/// - Yielding to a different OS thread within the same
/// ractor during compilation
/// - The GC calling [rb_yjit_iseq_mark] during compilation
///
/// Technically, for soundness, we also need to ensure that
/// the we have the VM lock while the result of `as_ref()`
/// is live, so that no deallocation happens while the
/// shared reference is live. The vast majority of our code run while
/// holding the VM lock, though.
pub type BlockRef = NonNull<Block>;
/// Pointer to a [Branch]. See [BlockRef] for notes about
/// proper usage.
pub type BranchRef = NonNull<Branch>;
/// Pointer to an entry that is already added to an ISEQ
pub type EntryRef = NonNull<Entry>;
/// List of block versions for a given blockid
type VersionList = Vec<BlockRef>;
/// Map from iseq indices to lists of versions for that given blockid
/// An instance of this is stored on each iseq
type VersionMap = Vec<VersionList>;
/// [Interior mutability][1] wrapper for a list of branches.
/// O(n) insertion, but space efficient. We generally expect
/// blocks to have only a few branches.
///
/// [1]: https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html
#[repr(transparent)]
struct MutableBranchList(Cell<Box<[BranchRef]>>);
impl MutableBranchList {
fn push(&self, branch: BranchRef) {
// Temporary move the boxed slice out of self.
// oom=abort is load bearing here...
let mut current_list = self.0.take().into_vec();
current_list.push(branch);
self.0.set(current_list.into_boxed_slice());
}
}
impl fmt::Debug for MutableBranchList {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
// SAFETY: the derived Clone for boxed slices does not mutate this Cell
let branches = unsafe { self.0.ref_unchecked().clone() };
formatter.debug_list().entries(branches.into_iter()).finish()
}
}
/// This is all the data YJIT stores on an iseq
/// This will be dynamically allocated by C code
/// C code should pass an &mut IseqPayload to us
/// when calling into YJIT
#[derive(Default)]
pub struct IseqPayload {
// Basic block versions
pub version_map: VersionMap,
// Indexes of code pages used by this this ISEQ
pub pages: HashSet<usize>,
// List of ISEQ entry codes
pub entries: Vec<EntryRef>,
// Blocks that are invalidated but are not yet deallocated.
// The code GC will free them later.
pub dead_blocks: Vec<BlockRef>,
}
impl IseqPayload {
/// Remove all block versions from the payload and then return them as an iterator
pub fn take_all_blocks(&mut self) -> impl Iterator<Item = BlockRef> {
// Empty the blocks
let version_map = mem::take(&mut self.version_map);
// Turn it into an iterator that owns the blocks and return
version_map.into_iter().flatten()
}
}
/// Get the payload for an iseq. For safety it's up to the caller to ensure the returned `&mut`
/// upholds aliasing rules and that the argument is a valid iseq.
pub fn get_iseq_payload(iseq: IseqPtr) -> Option<&'static mut IseqPayload> {
let payload = unsafe { rb_iseq_get_yjit_payload(iseq) };
let payload: *mut IseqPayload = payload.cast();
unsafe { payload.as_mut() }
}
/// Get the payload object associated with an iseq. Create one if none exists.
pub fn get_or_create_iseq_payload(iseq: IseqPtr) -> &'static mut IseqPayload {
type VoidPtr = *mut c_void;
let payload_non_null = unsafe {
let payload = rb_iseq_get_yjit_payload(iseq);
if payload.is_null() {
// Increment the compiled iseq count
incr_counter!(compiled_iseq_count);
// Allocate a new payload with Box and transfer ownership to the GC.
// We drop the payload with Box::from_raw when the GC frees the iseq and calls us.
// NOTE(alan): Sometimes we read from an iseq without ever writing to it.
// We allocate in those cases anyways.
let new_payload = IseqPayload::default();
let new_payload = Box::into_raw(Box::new(new_payload));
rb_iseq_set_yjit_payload(iseq, new_payload as VoidPtr);
new_payload
} else {
payload as *mut IseqPayload