forked from ruby/ruby
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhir.rs
3568 lines (3297 loc) · 130 KB
/
hir.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::{
cruby::*,
options::{get_option, DumpHIR},
profile::{self, get_or_create_iseq_payload},
state::ZJITState,
};
use std::{cell::RefCell, collections::{HashMap, HashSet, VecDeque}, ffi::c_void, mem::{align_of, size_of}, ptr, slice::Iter};
use crate::hir_type::{Type, types};
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]
pub struct InsnId(pub usize);
impl Into<usize> for InsnId {
fn into(self) -> usize {
self.0
}
}
impl std::fmt::Display for InsnId {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "v{}", self.0)
}
}
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct BlockId(pub usize);
impl std::fmt::Display for BlockId {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "bb{}", self.0)
}
}
fn write_vec<T: std::fmt::Display>(f: &mut std::fmt::Formatter, objs: &Vec<T>) -> std::fmt::Result {
write!(f, "[")?;
let mut prefix = "";
for obj in objs {
write!(f, "{prefix}{obj}")?;
prefix = ", ";
}
write!(f, "]")
}
impl std::fmt::Display for VALUE {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.print(&PtrPrintMap::identity()).fmt(f)
}
}
impl VALUE {
pub fn print(self, ptr_map: &PtrPrintMap) -> VALUEPrinter {
VALUEPrinter { inner: self, ptr_map }
}
}
/// Print adaptor for [`VALUE`]. See [`PtrPrintMap`].
pub struct VALUEPrinter<'a> {
inner: VALUE,
ptr_map: &'a PtrPrintMap,
}
impl<'a> std::fmt::Display for VALUEPrinter<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self.inner {
val if val.fixnum_p() => write!(f, "{}", val.as_fixnum()),
Qnil => write!(f, "nil"),
Qtrue => write!(f, "true"),
Qfalse => write!(f, "false"),
val => write!(f, "VALUE({:p})", self.ptr_map.map_ptr(val.as_ptr::<VALUE>())),
}
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct BranchEdge {
pub target: BlockId,
pub args: Vec<InsnId>,
}
impl std::fmt::Display for BranchEdge {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}(", self.target)?;
let mut prefix = "";
for arg in &self.args {
write!(f, "{prefix}{arg}")?;
prefix = ", ";
}
write!(f, ")")
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct CallInfo {
pub method_name: String,
}
/// Invalidation reasons
#[derive(Debug, Clone, Copy)]
pub enum Invariant {
/// Basic operation is redefined
BOPRedefined {
/// {klass}_REDEFINED_OP_FLAG
klass: RedefinitionFlag,
/// BOP_{bop}
bop: ruby_basic_operators,
},
MethodRedefined {
/// The class object whose method we want to assume unchanged
klass: VALUE,
/// The method ID of the method we want to assume unchanged
method: ID,
},
}
impl Invariant {
pub fn print(self, ptr_map: &PtrPrintMap) -> InvariantPrinter {
InvariantPrinter { inner: self, ptr_map }
}
}
/// Print adaptor for [`Invariant`]. See [`PtrPrintMap`].
pub struct InvariantPrinter<'a> {
inner: Invariant,
ptr_map: &'a PtrPrintMap,
}
impl<'a> std::fmt::Display for InvariantPrinter<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self.inner {
Invariant::BOPRedefined { klass, bop } => {
write!(f, "BOPRedefined(")?;
match klass {
INTEGER_REDEFINED_OP_FLAG => write!(f, "INTEGER_REDEFINED_OP_FLAG")?,
_ => write!(f, "{klass}")?,
}
write!(f, ", ")?;
match bop {
BOP_PLUS => write!(f, "BOP_PLUS")?,
BOP_MINUS => write!(f, "BOP_MINUS")?,
BOP_MULT => write!(f, "BOP_MULT")?,
BOP_DIV => write!(f, "BOP_DIV")?,
BOP_MOD => write!(f, "BOP_MOD")?,
BOP_EQ => write!(f, "BOP_EQ")?,
BOP_NEQ => write!(f, "BOP_NEQ")?,
BOP_LT => write!(f, "BOP_LT")?,
BOP_LE => write!(f, "BOP_LE")?,
BOP_GT => write!(f, "BOP_GT")?,
BOP_GE => write!(f, "BOP_GE")?,
_ => write!(f, "{bop}")?,
}
write!(f, ")")
}
Invariant::MethodRedefined { klass, method } => {
let class_name = get_class_name(klass);
write!(f, "MethodRedefined({class_name}@{:p}, {}@{:p})",
self.ptr_map.map_ptr(klass.as_ptr::<VALUE>()),
method.contents_lossy(),
self.ptr_map.map_id(method.0)
)
}
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Const {
Value(VALUE),
CBool(bool),
CInt8(i8),
CInt16(i16),
CInt32(i32),
CInt64(i64),
CUInt8(u8),
CUInt16(u16),
CUInt32(u32),
CUInt64(u64),
CPtr(*mut u8),
CDouble(f64),
}
impl std::fmt::Display for Const {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.print(&PtrPrintMap::identity()).fmt(f)
}
}
impl Const {
fn print<'a>(&'a self, ptr_map: &'a PtrPrintMap) -> ConstPrinter<'a> {
ConstPrinter { inner: self, ptr_map }
}
}
/// Print adaptor for [`Const`]. See [`PtrPrintMap`].
struct ConstPrinter<'a> {
inner: &'a Const,
ptr_map: &'a PtrPrintMap,
}
impl<'a> std::fmt::Display for ConstPrinter<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self.inner {
Const::Value(val) => write!(f, "Value({})", val.print(self.ptr_map)),
Const::CPtr(val) => write!(f, "CPtr({:p})", self.ptr_map.map_ptr(val)),
_ => write!(f, "{:?}", self.inner),
}
}
}
/// For output stability in tests, we assign each pointer with a stable
/// address the first time we see it. This mapping is off by default;
/// set [`PtrPrintMap::map_ptrs`] to switch it on.
///
/// Because this is extra state external to any pointer being printed, a
/// printing adapter struct that wraps the pointer along with this map is
/// required to make use of this effectly. The [`std::fmt::Display`]
/// implementation on the adapter struct can then be reused to implement
/// `Display` on the inner type with a default [`PtrPrintMap`], which
/// does not perform any mapping.
pub struct PtrPrintMap {
inner: RefCell<PtrPrintMapInner>,
map_ptrs: bool,
}
struct PtrPrintMapInner {
map: HashMap<*const c_void, *const c_void>,
next_ptr: *const c_void,
}
impl PtrPrintMap {
/// Return a mapper that maps the pointer to itself.
pub fn identity() -> Self {
Self {
map_ptrs: false,
inner: RefCell::new(PtrPrintMapInner {
map: HashMap::default(), next_ptr:
ptr::without_provenance(0x1000) // Simulate 4 KiB zero page
})
}
}
}
impl PtrPrintMap {
/// Map a pointer for printing
fn map_ptr<T>(&self, ptr: *const T) -> *const T {
// When testing, address stability is not a concern so print real address to enable code
// reuse
if !self.map_ptrs {
return ptr;
}
use std::collections::hash_map::Entry::*;
let ptr = ptr.cast();
let inner = &mut *self.inner.borrow_mut();
match inner.map.entry(ptr) {
Occupied(entry) => entry.get().cast(),
Vacant(entry) => {
// Pick a fake address that is suitably aligns for T and remember it in the map
let mapped = inner.next_ptr.wrapping_add(inner.next_ptr.align_offset(align_of::<T>()));
entry.insert(mapped);
// Bump for the next pointer
inner.next_ptr = mapped.wrapping_add(size_of::<T>());
mapped.cast()
}
}
}
/// Map a Ruby ID (index into intern table) for printing
fn map_id(&self, id: u64) -> *const c_void {
self.map_ptr(id as *const c_void)
}
}
#[derive(Debug, Clone)]
pub enum Insn {
PutSelf,
Const { val: Const },
// SSA block parameter. Also used for function parameters in the function's entry block.
Param { idx: usize },
StringCopy { val: InsnId },
StringIntern { val: InsnId },
NewArray { elements: Vec<InsnId>, state: InsnId },
ArraySet { array: InsnId, idx: usize, val: InsnId },
ArrayDup { val: InsnId, state: InsnId },
// Check if the value is truthy and "return" a C boolean. In reality, we will likely fuse this
// with IfTrue/IfFalse in the backend to generate jcc.
Test { val: InsnId },
Defined { op_type: usize, obj: VALUE, pushval: VALUE, v: InsnId },
GetConstantPath { ic: *const u8 },
//NewObject?
//SetIvar {},
//GetIvar {},
// Own a FrameState so that instructions can look up their dominating FrameState when
// generating deopt side-exits and frame reconstruction metadata. Does not directly generate
// any code.
Snapshot { state: FrameState },
// Unconditional jump
Jump(BranchEdge),
// Conditional branch instructions
IfTrue { val: InsnId, target: BranchEdge },
IfFalse { val: InsnId, target: BranchEdge },
// Call a C function
// `name` is for printing purposes only
CCall { cfun: *const u8, args: Vec<InsnId>, name: ID, return_type: Type },
// Send without block with dynamic dispatch
// Ignoring keyword arguments etc for now
SendWithoutBlock { self_val: InsnId, call_info: CallInfo, cd: *const rb_call_data, args: Vec<InsnId>, state: InsnId },
Send { self_val: InsnId, call_info: CallInfo, cd: *const rb_call_data, blockiseq: IseqPtr, args: Vec<InsnId>, state: InsnId },
SendWithoutBlockDirect { self_val: InsnId, call_info: CallInfo, cd: *const rb_call_data, iseq: IseqPtr, args: Vec<InsnId>, state: InsnId },
// Control flow instructions
Return { val: InsnId },
/// Fixnum +, -, *, /, %, ==, !=, <, <=, >, >=
FixnumAdd { left: InsnId, right: InsnId, state: InsnId },
FixnumSub { left: InsnId, right: InsnId, state: InsnId },
FixnumMult { left: InsnId, right: InsnId, state: InsnId },
FixnumDiv { left: InsnId, right: InsnId, state: InsnId },
FixnumMod { left: InsnId, right: InsnId, state: InsnId },
FixnumEq { left: InsnId, right: InsnId },
FixnumNeq { left: InsnId, right: InsnId },
FixnumLt { left: InsnId, right: InsnId },
FixnumLe { left: InsnId, right: InsnId },
FixnumGt { left: InsnId, right: InsnId },
FixnumGe { left: InsnId, right: InsnId },
/// Side-exit if val doesn't have the expected type.
GuardType { val: InsnId, guard_type: Type, state: InsnId },
/// Side-exit if val is not the expected VALUE.
GuardBitEquals { val: InsnId, expected: VALUE, state: InsnId },
/// Generate no code (or padding if necessary) and insert a patch point
/// that can be rewritten to a side exit when the Invariant is broken.
PatchPoint(Invariant),
}
impl Insn {
/// Not every instruction returns a value. Return true if the instruction does and false otherwise.
pub fn has_output(&self) -> bool {
match self {
Insn::ArraySet { .. } | Insn::Snapshot { .. } | Insn::Jump(_)
| Insn::IfTrue { .. } | Insn::IfFalse { .. } | Insn::Return { .. }
| Insn::PatchPoint { .. } => false,
_ => true,
}
}
/// Return true if the instruction ends a basic block and false otherwise.
pub fn is_terminator(&self) -> bool {
match self {
Insn::Jump(_) | Insn::Return { .. } => true,
_ => false,
}
}
pub fn print<'a>(&self, ptr_map: &'a PtrPrintMap) -> InsnPrinter<'a> {
InsnPrinter { inner: self.clone(), ptr_map }
}
/// Return true if the instruction needs to be kept around. For example, if the instruction
/// might have a side effect, or if the instruction may raise an exception.
fn has_effects(&self) -> bool {
match self {
Insn::PutSelf => false,
Insn::Const { .. } => false,
Insn::Param { .. } => false,
Insn::StringCopy { .. } => false,
Insn::NewArray { .. } => false,
Insn::ArrayDup { .. } => false,
Insn::Test { .. } => false,
Insn::Snapshot { .. } => false,
Insn::FixnumAdd { .. } => false,
Insn::FixnumSub { .. } => false,
Insn::FixnumMult { .. } => false,
// TODO(max): Consider adding a Guard that the rhs is non-zero before Div and Mod
// Div *is* critical unless we can prove the right hand side != 0
// Mod *is* critical unless we can prove the right hand side != 0
Insn::FixnumEq { .. } => false,
Insn::FixnumNeq { .. } => false,
Insn::FixnumLt { .. } => false,
Insn::FixnumLe { .. } => false,
Insn::FixnumGt { .. } => false,
Insn::FixnumGe { .. } => false,
_ => true,
}
}
}
/// Print adaptor for [`Insn`]. See [`PtrPrintMap`].
pub struct InsnPrinter<'a> {
inner: Insn,
ptr_map: &'a PtrPrintMap,
}
impl<'a> std::fmt::Display for InsnPrinter<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match &self.inner {
Insn::Const { val } => { write!(f, "Const {}", val.print(self.ptr_map)) }
Insn::Param { idx } => { write!(f, "Param {idx}") }
Insn::NewArray { elements, .. } => {
write!(f, "NewArray")?;
let mut prefix = " ";
for element in elements {
write!(f, "{prefix}{element}")?;
prefix = ", ";
}
Ok(())
}
Insn::ArraySet { array, idx, val } => { write!(f, "ArraySet {array}, {idx}, {val}") }
Insn::ArrayDup { val, .. } => { write!(f, "ArrayDup {val}") }
Insn::StringCopy { val } => { write!(f, "StringCopy {val}") }
Insn::Test { val } => { write!(f, "Test {val}") }
Insn::Jump(target) => { write!(f, "Jump {target}") }
Insn::IfTrue { val, target } => { write!(f, "IfTrue {val}, {target}") }
Insn::IfFalse { val, target } => { write!(f, "IfFalse {val}, {target}") }
Insn::SendWithoutBlock { self_val, call_info, args, .. } => {
write!(f, "SendWithoutBlock {self_val}, :{}", call_info.method_name)?;
for arg in args {
write!(f, ", {arg}")?;
}
Ok(())
}
Insn::SendWithoutBlockDirect { self_val, call_info, iseq, args, .. } => {
write!(f, "SendWithoutBlockDirect {self_val}, :{} ({:?})", call_info.method_name, self.ptr_map.map_ptr(iseq))?;
for arg in args {
write!(f, ", {arg}")?;
}
Ok(())
}
Insn::Send { self_val, call_info, args, blockiseq, .. } => {
// For tests, we want to check HIR snippets textually. Addresses change
// between runs, making tests fail. Instead, pick an arbitrary hex value to
// use as a "pointer" so we can check the rest of the HIR.
write!(f, "Send {self_val}, {:p}, :{}", self.ptr_map.map_ptr(blockiseq), call_info.method_name)?;
for arg in args {
write!(f, ", {arg}")?;
}
Ok(())
}
Insn::Return { val } => { write!(f, "Return {val}") }
Insn::FixnumAdd { left, right, .. } => { write!(f, "FixnumAdd {left}, {right}") },
Insn::FixnumSub { left, right, .. } => { write!(f, "FixnumSub {left}, {right}") },
Insn::FixnumMult { left, right, .. } => { write!(f, "FixnumMult {left}, {right}") },
Insn::FixnumDiv { left, right, .. } => { write!(f, "FixnumDiv {left}, {right}") },
Insn::FixnumMod { left, right, .. } => { write!(f, "FixnumMod {left}, {right}") },
Insn::FixnumEq { left, right, .. } => { write!(f, "FixnumEq {left}, {right}") },
Insn::FixnumNeq { left, right, .. } => { write!(f, "FixnumNeq {left}, {right}") },
Insn::FixnumLt { left, right, .. } => { write!(f, "FixnumLt {left}, {right}") },
Insn::FixnumLe { left, right, .. } => { write!(f, "FixnumLe {left}, {right}") },
Insn::FixnumGt { left, right, .. } => { write!(f, "FixnumGt {left}, {right}") },
Insn::FixnumGe { left, right, .. } => { write!(f, "FixnumGe {left}, {right}") },
Insn::GuardType { val, guard_type, .. } => { write!(f, "GuardType {val}, {}", guard_type.print(self.ptr_map)) },
Insn::GuardBitEquals { val, expected, .. } => { write!(f, "GuardBitEquals {val}, {}", expected.print(self.ptr_map)) },
Insn::PatchPoint(invariant) => { write!(f, "PatchPoint {}", invariant.print(self.ptr_map)) },
Insn::GetConstantPath { ic } => { write!(f, "GetConstantPath {:p}", self.ptr_map.map_ptr(ic)) },
Insn::CCall { cfun, args, name, return_type: _ } => {
write!(f, "CCall {}@{:p}", name.contents_lossy(), self.ptr_map.map_ptr(cfun))?;
for arg in args {
write!(f, ", {arg}")?;
}
Ok(())
},
Insn::Snapshot { state } => write!(f, "Snapshot {}", state),
insn => { write!(f, "{insn:?}") }
}
}
}
impl std::fmt::Display for Insn {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.print(&PtrPrintMap::identity()).fmt(f)
}
}
#[derive(Default, Debug)]
pub struct Block {
params: Vec<InsnId>,
insns: Vec<InsnId>,
}
impl Block {
/// Return an iterator over params
pub fn params(&self) -> Iter<InsnId> {
self.params.iter()
}
/// Return an iterator over insns
pub fn insns(&self) -> Iter<InsnId> {
self.insns.iter()
}
}
pub struct FunctionPrinter<'a> {
fun: &'a Function,
display_snapshot: bool,
ptr_map: PtrPrintMap,
}
impl<'a> FunctionPrinter<'a> {
pub fn without_snapshot(fun: &'a Function) -> Self {
let mut ptr_map = PtrPrintMap::identity();
if cfg!(test) {
ptr_map.map_ptrs = true;
}
Self { fun, display_snapshot: false, ptr_map }
}
pub fn with_snapshot(fun: &'a Function) -> FunctionPrinter<'a> {
let mut printer = Self::without_snapshot(fun);
printer.display_snapshot = true;
printer
}
}
/// Union-Find (Disjoint-Set) is a data structure for managing disjoint sets that has an interface
/// of two operations:
///
/// * find (what set is this item part of?)
/// * union (join these two sets)
///
/// Union-Find identifies sets by their *representative*, which is some chosen element of the set.
/// This is implemented by structuring each set as its own graph component with the representative
/// pointing at nothing. For example:
///
/// * A -> B -> C
/// * D -> E
///
/// This represents two sets `C` and `E`, with three and two members, respectively. In this
/// example, `find(A)=C`, `find(C)=C`, `find(D)=E`, and so on.
///
/// To union sets, call `make_equal_to` on any set element. That is, `make_equal_to(A, D)` and
/// `make_equal_to(B, E)` have the same result: the two sets are joined into the same graph
/// component. After this operation, calling `find` on any element will return `E`.
///
/// This is a useful data structure in compilers because it allows in-place rewriting without
/// linking/unlinking instructions and without replacing all uses. When calling `make_equal_to` on
/// any instruction, all of its uses now implicitly point to the replacement.
///
/// This does mean that pattern matching and analysis of the instruction graph must be careful to
/// call `find` whenever it is inspecting an instruction (or its operands). If not, this may result
/// in missing optimizations.
#[derive(Debug)]
struct UnionFind<T: Copy + Into<usize>> {
forwarded: Vec<Option<T>>,
}
impl<T: Copy + Into<usize> + PartialEq> UnionFind<T> {
fn new() -> UnionFind<T> {
UnionFind { forwarded: vec![] }
}
/// Private. Return the internal representation of the forwarding pointer for a given element.
fn at(&self, idx: T) -> Option<T> {
self.forwarded.get(idx.into()).map(|x| *x).flatten()
}
/// Private. Set the internal representation of the forwarding pointer for the given element
/// `idx`. Extend the internal vector if necessary.
fn set(&mut self, idx: T, value: T) {
if idx.into() >= self.forwarded.len() {
self.forwarded.resize(idx.into()+1, None);
}
self.forwarded[idx.into()] = Some(value);
}
/// Find the set representative for `insn`. Perform path compression at the same time to speed
/// up further find operations. For example, before:
///
/// `A -> B -> C`
///
/// and after `find(A)`:
///
/// ```
/// A -> C
/// B ---^
/// ```
pub fn find(&mut self, insn: T) -> T {
let result = self.find_const(insn);
if result != insn {
// Path compression
self.set(insn, result);
}
result
}
/// Find the set representative for `insn` without doing path compression.
pub fn find_const(&self, insn: T) -> T {
let mut result = insn;
loop {
match self.at(result) {
None => return result,
Some(insn) => result = insn,
}
}
}
/// Union the two sets containing `insn` and `target` such that every element in `insn`s set is
/// now part of `target`'s. Neither argument must be the representative in its set.
pub fn make_equal_to(&mut self, insn: T, target: T) {
let found = self.find(insn);
self.set(found, target);
}
}
#[derive(Debug)]
pub struct Function {
// ISEQ this function refers to
iseq: *const rb_iseq_t,
// TODO: get method name and source location from the ISEQ
insns: Vec<Insn>,
union_find: UnionFind<InsnId>,
insn_types: Vec<Type>,
blocks: Vec<Block>,
entry_block: BlockId,
}
impl Function {
fn new(iseq: *const rb_iseq_t) -> Function {
Function {
iseq,
insns: vec![],
insn_types: vec![],
union_find: UnionFind::new(),
blocks: vec![Block::default()],
entry_block: BlockId(0),
}
}
// Add an instruction to the function without adding it to any block
fn new_insn(&mut self, insn: Insn) -> InsnId {
let id = InsnId(self.insns.len());
self.insns.push(insn);
self.insn_types.push(types::Empty);
id
}
// Add an instruction to an SSA block
fn push_insn(&mut self, block: BlockId, insn: Insn) -> InsnId {
let is_param = matches!(insn, Insn::Param { .. });
let id = self.new_insn(insn);
if is_param {
self.blocks[block.0].params.push(id);
} else {
self.blocks[block.0].insns.push(id);
}
id
}
// Add an instruction to an SSA block
fn push_insn_id(&mut self, block: BlockId, insn_id: InsnId) -> InsnId {
self.blocks[block.0].insns.push(insn_id);
insn_id
}
/// Return the number of instructions
pub fn num_insns(&self) -> usize {
self.insns.len()
}
/// Return a FrameState at the given instruction index.
pub fn frame_state(&self, insn_id: InsnId) -> FrameState {
match self.find(insn_id) {
Insn::Snapshot { state } => state,
insn => panic!("Unexpected non-Snapshot {insn} when looking up FrameState"),
}
}
fn new_block(&mut self) -> BlockId {
let id = BlockId(self.blocks.len());
self.blocks.push(Block::default());
id
}
/// Return a reference to the Block at the given index.
pub fn block(&self, block_id: BlockId) -> &Block {
&self.blocks[block_id.0]
}
/// Return the number of blocks
pub fn num_blocks(&self) -> usize {
self.blocks.len()
}
/// Return a copy of the instruction where the instruction and its operands have been read from
/// the union-find table (to find the current most-optimized version of this instruction). See
/// [`UnionFind`] for more.
///
/// Use for pattern matching over instructions in a union-find-safe way. For example:
/// ```rust
/// match func.find(insn_id) {
/// IfTrue { val, target } if func.is_truthy(val) => {
/// let jump = self.new_insn(Insn::Jump(target));
/// func.make_equal_to(insn_id, jump);
/// }
/// _ => {}
/// }
/// ```
pub fn find(&self, insn_id: InsnId) -> Insn {
macro_rules! find {
( $x:expr ) => {
{
self.union_find.find_const($x)
}
};
}
let insn_id = self.union_find.find_const(insn_id);
use Insn::*;
match &self.insns[insn_id.0] {
result@(PutSelf | Const {..} | Param {..} | NewArray {..} | GetConstantPath {..}
| Jump(_) | PatchPoint {..}) => result.clone(),
Snapshot { state: FrameState { iseq, insn_idx, pc, stack, locals } } =>
Snapshot {
state: FrameState {
iseq: *iseq,
insn_idx: *insn_idx,
pc: *pc,
stack: stack.iter().map(|v| find!(*v)).collect(),
locals: locals.iter().map(|v| find!(*v)).collect(),
}
},
Return { val } => Return { val: find!(*val) },
StringCopy { val } => StringCopy { val: find!(*val) },
StringIntern { val } => StringIntern { val: find!(*val) },
Test { val } => Test { val: find!(*val) },
IfTrue { val, target } => IfTrue { val: find!(*val), target: target.clone() },
IfFalse { val, target } => IfFalse { val: find!(*val), target: target.clone() },
GuardType { val, guard_type, state } => GuardType { val: find!(*val), guard_type: *guard_type, state: *state },
GuardBitEquals { val, expected, state } => GuardBitEquals { val: find!(*val), expected: *expected, state: *state },
FixnumAdd { left, right, state } => FixnumAdd { left: find!(*left), right: find!(*right), state: *state },
FixnumSub { left, right, state } => FixnumSub { left: find!(*left), right: find!(*right), state: *state },
FixnumMult { left, right, state } => FixnumMult { left: find!(*left), right: find!(*right), state: *state },
FixnumDiv { left, right, state } => FixnumDiv { left: find!(*left), right: find!(*right), state: *state },
FixnumMod { left, right, state } => FixnumMod { left: find!(*left), right: find!(*right), state: *state },
FixnumNeq { left, right } => FixnumNeq { left: find!(*left), right: find!(*right) },
FixnumEq { left, right } => FixnumEq { left: find!(*left), right: find!(*right) },
FixnumGt { left, right } => FixnumGt { left: find!(*left), right: find!(*right) },
FixnumGe { left, right } => FixnumGe { left: find!(*left), right: find!(*right) },
FixnumLt { left, right } => FixnumLt { left: find!(*left), right: find!(*right) },
FixnumLe { left, right } => FixnumLe { left: find!(*left), right: find!(*right) },
SendWithoutBlock { self_val, call_info, cd, args, state } => SendWithoutBlock {
self_val: find!(*self_val),
call_info: call_info.clone(),
cd: *cd,
args: args.iter().map(|arg| find!(*arg)).collect(),
state: *state,
},
SendWithoutBlockDirect { self_val, call_info, cd, iseq, args, state } => SendWithoutBlockDirect {
self_val: find!(*self_val),
call_info: call_info.clone(),
cd: *cd,
iseq: *iseq,
args: args.iter().map(|arg| find!(*arg)).collect(),
state: *state,
},
Send { self_val, call_info, cd, blockiseq, args, state } => Send {
self_val: find!(*self_val),
call_info: call_info.clone(),
cd: *cd,
blockiseq: *blockiseq,
args: args.iter().map(|arg| find!(*arg)).collect(),
state: *state,
},
ArraySet { array, idx, val } => ArraySet { array: find!(*array), idx: *idx, val: find!(*val) },
ArrayDup { val , state } => ArrayDup { val: find!(*val), state: *state },
CCall { cfun, args, name, return_type } => CCall { cfun: *cfun, args: args.iter().map(|arg| find!(*arg)).collect(), name: *name, return_type: *return_type },
Defined { .. } => todo!("find(Defined)"),
}
}
/// Replace `insn` with the new instruction `replacement`, which will get appended to `insns`.
fn make_equal_to(&mut self, insn: InsnId, replacement: InsnId) {
// Don't push it to the block
self.union_find.make_equal_to(insn, replacement);
}
fn type_of(&self, insn: InsnId) -> Type {
assert!(self.insns[insn.0].has_output());
self.insn_types[self.union_find.find_const(insn).0]
}
/// Check if the type of `insn` is a subtype of `ty`.
fn is_a(&self, insn: InsnId, ty: Type) -> bool {
self.type_of(insn).is_subtype(ty)
}
fn infer_type(&self, insn: InsnId) -> Type {
assert!(self.insns[insn.0].has_output());
match &self.insns[insn.0] {
Insn::Param { .. } => unimplemented!("params should not be present in block.insns"),
Insn::ArraySet { .. } | Insn::Snapshot { .. } | Insn::Jump(_)
| Insn::IfTrue { .. } | Insn::IfFalse { .. } | Insn::Return { .. }
| Insn::PatchPoint { .. } =>
panic!("Cannot infer type of instruction with no output"),
Insn::Const { val: Const::Value(val) } => Type::from_value(*val),
Insn::Const { val: Const::CBool(val) } => Type::from_cbool(*val),
Insn::Const { val: Const::CInt8(val) } => Type::from_cint(types::CInt8, *val as i64),
Insn::Const { val: Const::CInt16(val) } => Type::from_cint(types::CInt16, *val as i64),
Insn::Const { val: Const::CInt32(val) } => Type::from_cint(types::CInt32, *val as i64),
Insn::Const { val: Const::CInt64(val) } => Type::from_cint(types::CInt64, *val),
Insn::Const { val: Const::CUInt8(val) } => Type::from_cint(types::CUInt8, *val as i64),
Insn::Const { val: Const::CUInt16(val) } => Type::from_cint(types::CUInt16, *val as i64),
Insn::Const { val: Const::CUInt32(val) } => Type::from_cint(types::CUInt32, *val as i64),
Insn::Const { val: Const::CUInt64(val) } => Type::from_cint(types::CUInt64, *val as i64),
Insn::Const { val: Const::CPtr(val) } => Type::from_cint(types::CPtr, *val as i64),
Insn::Const { val: Const::CDouble(val) } => Type::from_double(*val),
Insn::Test { val } if self.type_of(*val).is_known_falsy() => Type::from_cbool(false),
Insn::Test { val } if self.type_of(*val).is_known_truthy() => Type::from_cbool(true),
Insn::Test { .. } => types::CBool,
Insn::StringCopy { .. } => types::StringExact,
Insn::StringIntern { .. } => types::StringExact,
Insn::NewArray { .. } => types::ArrayExact,
Insn::ArrayDup { .. } => types::ArrayExact,
Insn::CCall { return_type, .. } => *return_type,
Insn::GuardType { val, guard_type, .. } => self.type_of(*val).intersection(*guard_type),
Insn::GuardBitEquals { val, expected, .. } => self.type_of(*val).intersection(Type::from_value(*expected)),
Insn::FixnumAdd { .. } => types::Fixnum,
Insn::FixnumSub { .. } => types::Fixnum,
Insn::FixnumMult { .. } => types::Fixnum,
Insn::FixnumDiv { .. } => types::Fixnum,
Insn::FixnumMod { .. } => types::Fixnum,
Insn::FixnumEq { .. } => types::BoolExact,
Insn::FixnumNeq { .. } => types::BoolExact,
Insn::FixnumLt { .. } => types::BoolExact,
Insn::FixnumLe { .. } => types::BoolExact,
Insn::FixnumGt { .. } => types::BoolExact,
Insn::FixnumGe { .. } => types::BoolExact,
Insn::SendWithoutBlock { .. } => types::BasicObject,
Insn::SendWithoutBlockDirect { .. } => types::BasicObject,
Insn::Send { .. } => types::BasicObject,
Insn::PutSelf => types::BasicObject,
Insn::Defined { .. } => types::BasicObject,
Insn::GetConstantPath { .. } => types::BasicObject,
}
}
fn infer_types(&mut self) {
// Reset all types
self.insn_types.fill(types::Empty);
for param in &self.blocks[self.entry_block.0].params {
// We know that function parameters are BasicObject or some subclass
self.insn_types[param.0] = types::BasicObject;
}
let rpo = self.rpo();
// Walk the graph, computing types until fixpoint
let mut reachable = vec![false; self.blocks.len()];
reachable[self.entry_block.0] = true;
loop {
let mut changed = false;
for block in &rpo {
if !reachable[block.0] { continue; }
for insn_id in &self.blocks[block.0].insns {
let insn = self.find(*insn_id);
let insn_type = match insn {
Insn::IfTrue { val, target: BranchEdge { target, args } } => {
assert!(!self.type_of(val).bit_equal(types::Empty));
if self.type_of(val).could_be(Type::from_cbool(true)) {
reachable[target.0] = true;
for (idx, arg) in args.iter().enumerate() {
let param = self.blocks[target.0].params[idx];
self.insn_types[param.0] = self.type_of(param).union(self.type_of(*arg));
}
}
continue;
}
Insn::IfFalse { val, target: BranchEdge { target, args } } => {
assert!(!self.type_of(val).bit_equal(types::Empty));
if self.type_of(val).could_be(Type::from_cbool(false)) {
reachable[target.0] = true;
for (idx, arg) in args.iter().enumerate() {
let param = self.blocks[target.0].params[idx];
self.insn_types[param.0] = self.type_of(param).union(self.type_of(*arg));
}
}
continue;
}
Insn::Jump(BranchEdge { target, args }) => {
reachable[target.0] = true;
for (idx, arg) in args.iter().enumerate() {
let param = self.blocks[target.0].params[idx];
self.insn_types[param.0] = self.type_of(param).union(self.type_of(*arg));
}
continue;
}
_ if insn.has_output() => self.infer_type(*insn_id),
_ => continue,
};
if !self.type_of(*insn_id).bit_equal(insn_type) {
self.insn_types[insn_id.0] = insn_type;
changed = true;
}
}
}
if !changed {
break;
}
}
}
fn likely_is_fixnum(&self, val: InsnId, profiled_type: Type) -> bool {
return self.is_a(val, types::Fixnum) || profiled_type.is_subtype(types::Fixnum);
}
fn coerce_to_fixnum(&mut self, block: BlockId, val: InsnId, state: InsnId) -> InsnId {
if self.is_a(val, types::Fixnum) { return val; }
return self.push_insn(block, Insn::GuardType { val, guard_type: types::Fixnum, state });
}
fn arguments_likely_fixnums(&mut self, payload: &profile:: IseqPayload, left: InsnId, right: InsnId, state: InsnId) -> bool {
let mut left_profiled_type = types::BasicObject;
let mut right_profiled_type = types::BasicObject;
let frame_state = self.frame_state(state);
let insn_idx = frame_state.insn_idx;
if let Some([left_type, right_type]) = payload.get_operand_types(insn_idx as usize) {
left_profiled_type = *left_type;
right_profiled_type = *right_type;
}
self.likely_is_fixnum(left, left_profiled_type) && self.likely_is_fixnum(right, right_profiled_type)
}
fn try_rewrite_fixnum_op(&mut self, block: BlockId, orig_insn_id: InsnId, f: &dyn Fn(InsnId, InsnId) -> Insn, bop: u32, left: InsnId, right: InsnId, payload: &profile::IseqPayload, state: InsnId) {
if self.arguments_likely_fixnums(payload, left, right, state) {
if bop == BOP_NEQ {
// For opt_neq, the interpreter checks that both neq and eq are unchanged.
self.push_insn(block, Insn::PatchPoint(Invariant::BOPRedefined { klass: INTEGER_REDEFINED_OP_FLAG, bop: BOP_EQ }));
}
self.push_insn(block, Insn::PatchPoint(Invariant::BOPRedefined { klass: INTEGER_REDEFINED_OP_FLAG, bop }));
let left = self.coerce_to_fixnum(block, left, state);
let right = self.coerce_to_fixnum(block, right, state);
let result = self.push_insn(block, f(left, right));
self.make_equal_to(orig_insn_id, result);
} else {
self.push_insn_id(block, orig_insn_id);
}
}
/// Rewrite SendWithoutBlock opcodes into SendWithoutBlockDirect opcodes if we know the target
/// ISEQ statically. This removes run-time method lookups and opens the door for inlining.
fn optimize_direct_sends(&mut self) {
let payload = get_or_create_iseq_payload(self.iseq);
for block in self.rpo() {
let old_insns = std::mem::take(&mut self.blocks[block.0].insns);
assert!(self.blocks[block.0].insns.is_empty());
for insn_id in old_insns {
match self.find(insn_id) {
Insn::SendWithoutBlock { self_val, call_info: CallInfo { method_name }, args, state, .. } if method_name == "+" && args.len() == 1 =>
self.try_rewrite_fixnum_op(block, insn_id, &|left, right| Insn::FixnumAdd { left, right, state }, BOP_PLUS, self_val, args[0], payload, state),
Insn::SendWithoutBlock { self_val, call_info: CallInfo { method_name }, args, state, .. } if method_name == "-" && args.len() == 1 =>
self.try_rewrite_fixnum_op(block, insn_id, &|left, right| Insn::FixnumSub { left, right, state }, BOP_MINUS, self_val, args[0], payload, state),
Insn::SendWithoutBlock { self_val, call_info: CallInfo { method_name }, args, state, .. } if method_name == "*" && args.len() == 1 =>
self.try_rewrite_fixnum_op(block, insn_id, &|left, right| Insn::FixnumMult { left, right, state }, BOP_MULT, self_val, args[0], payload, state),
Insn::SendWithoutBlock { self_val, call_info: CallInfo { method_name }, args, state, .. } if method_name == "/" && args.len() == 1 =>
self.try_rewrite_fixnum_op(block, insn_id, &|left, right| Insn::FixnumDiv { left, right, state }, BOP_DIV, self_val, args[0], payload, state),
Insn::SendWithoutBlock { self_val, call_info: CallInfo { method_name }, args, state, .. } if method_name == "%" && args.len() == 1 =>
self.try_rewrite_fixnum_op(block, insn_id, &|left, right| Insn::FixnumMod { left, right, state }, BOP_MOD, self_val, args[0], payload, state),
Insn::SendWithoutBlock { self_val, call_info: CallInfo { method_name }, args, state, .. } if method_name == "==" && args.len() == 1 =>
self.try_rewrite_fixnum_op(block, insn_id, &|left, right| Insn::FixnumEq { left, right }, BOP_EQ, self_val, args[0], payload, state),
Insn::SendWithoutBlock { self_val, call_info: CallInfo { method_name }, args, state, .. } if method_name == "!=" && args.len() == 1 =>
self.try_rewrite_fixnum_op(block, insn_id, &|left, right| Insn::FixnumNeq { left, right }, BOP_NEQ, self_val, args[0], payload, state),
Insn::SendWithoutBlock { self_val, call_info: CallInfo { method_name }, args, state, .. } if method_name == "<" && args.len() == 1 =>
self.try_rewrite_fixnum_op(block, insn_id, &|left, right| Insn::FixnumLt { left, right }, BOP_LT, self_val, args[0], payload, state),
Insn::SendWithoutBlock { self_val, call_info: CallInfo { method_name }, args, state, .. } if method_name == "<=" && args.len() == 1 =>
self.try_rewrite_fixnum_op(block, insn_id, &|left, right| Insn::FixnumLe { left, right }, BOP_LE, self_val, args[0], payload, state),
Insn::SendWithoutBlock { self_val, call_info: CallInfo { method_name }, args, state, .. } if method_name == ">" && args.len() == 1 =>
self.try_rewrite_fixnum_op(block, insn_id, &|left, right| Insn::FixnumGt { left, right }, BOP_GT, self_val, args[0], payload, state),
Insn::SendWithoutBlock { self_val, call_info: CallInfo { method_name }, args, state, .. } if method_name == ">=" && args.len() == 1 =>
self.try_rewrite_fixnum_op(block, insn_id, &|left, right| Insn::FixnumGe { left, right }, BOP_GE, self_val, args[0], payload, state),
Insn::SendWithoutBlock { mut self_val, call_info, cd, args, state } => {
let frame_state = self.frame_state(state);
let (klass, guard_equal_to) = if let Some(klass) = self.type_of(self_val).runtime_exact_ruby_class() {
// If we know the class statically, use it to fold the lookup at compile-time.
(klass, None)
} else {
// If we know that self is top-self from profile information, guard and use it to fold the lookup at compile-time.
match payload.get_operand_types(frame_state.insn_idx) {
Some([self_type, ..]) if self_type.is_top_self() => (self_type.exact_ruby_class().unwrap(), self_type.ruby_object()),
_ => { self.push_insn_id(block, insn_id); continue; }
}
};
let ci = unsafe { get_call_data_ci(cd) }; // info about the call site
let mid = unsafe { vm_ci_mid(ci) };
// Do method lookup
let mut cme = unsafe { rb_callable_method_entry(klass, mid) };
if cme.is_null() {
self.push_insn_id(block, insn_id); continue;
}
// Load an overloaded cme if applicable. See vm_search_cc().