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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
//! Machine CSE — Common Subexpression Elimination on machine instructions.
//! Clean-room behavioral reconstruction.
//!
//! @llvm_behavior: MachineCSE eliminates redundant machine instructions
//! that compute the same value. It operates within a single basic block
//! (local CSE) or across basic blocks (global CSE using available
//! expressions analysis).
//!
//! Two machine instructions are congruent if they:
//! 1. Have the same opcode
//! 2. Have the same operands (after renaming to canonical virtual registers)
//! 3. Produce the same result for all possible inputs (pure computation)
//!
//! Algorithm (local CSE per basic block):
//! 1. Walk instructions in order
//! 2. Hash each instruction based on opcode + operands
//! 3. Look up the hash in a table of available expressions
//! 4. If a congruent instruction is found and still dominates the current
//! instruction (its definition is still live), replace the current
//! instruction's uses with the earlier definition
//! 5. Remove the redundant instruction
//! 6. Otherwise, add the instruction to the available-expression table
//!
//! Important constraints for machine CSE:
//! - Must respect physical register liveness
//! - Must not eliminate instructions with side effects
//! - Must handle memory operations conservatively (may alias)
//! - Must preserve debug information
use llvm_native_core::codegen::{MachineBasicBlock, MachineFunction, MachineInstr, MachineOperand, VirtReg};
use std::collections::{HashMap, HashSet};
// ============================================================================
// Expression Key — Unique identifier for a computation
// ============================================================================
/// A hashable key representing a machine instruction expression.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct ExprKey {
/// The instruction opcode.
opcode: u32,
/// The canonical operands (register numbers, immediate values).
operands: Vec<ExprOperand>,
}
/// A canonical operand representation for hashing.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum ExprOperand {
/// A register (virtual or physical).
Reg(u64),
/// An immediate value.
Imm(i64),
/// A label target.
Label(String),
/// A global symbol.
Global(String),
}
impl From<&MachineOperand> for ExprOperand {
fn from(op: &MachineOperand) -> Self {
match op {
MachineOperand::Reg(vr) => ExprOperand::Reg(*vr as u64),
MachineOperand::PhysReg(pr) => ExprOperand::Reg((*pr as u64) + (1 << 32)),
MachineOperand::Imm(v) => ExprOperand::Imm(*v),
MachineOperand::Label(s) => ExprOperand::Label(s.clone()),
MachineOperand::Global(s) => ExprOperand::Global(s.clone()),
}
}
}
// ============================================================================
// Available Expression Entry
// ============================================================================
/// An entry in the available-expression table.
#[derive(Debug, Clone)]
struct AvailExpr {
/// The virtual register defined by this expression.
def_vreg: Option<VirtReg>,
/// Index of the instruction in the basic block.
instr_idx: usize,
/// Whether the expression's definition is still live.
is_live: bool,
}
// ============================================================================
// Machine CSE Pass
// ============================================================================
/// MachineCSE — Common Subexpression Elimination at the machine level.
pub struct MachineCSE {
/// Number of redundant instructions eliminated.
pub eliminated: usize,
/// Whether CSE is enabled.
pub enabled: bool,
}
impl MachineCSE {
/// Create a new MachineCSE pass.
pub fn new() -> Self {
Self {
eliminated: 0,
enabled: true,
}
}
/// Run MachineCSE on a machine function.
///
/// Returns the number of common subexpressions eliminated.
pub fn run_on_function(&mut self, mf: &mut MachineFunction) -> usize {
if !self.enabled {
return 0;
}
self.eliminated = 0;
let block_count = mf.blocks.len();
for bb_idx in 0..block_count {
// We need to process each block independently
self.eliminate_common_subexprs(mf, bb_idx);
}
self.eliminated
}
// ========================================================================
// Block-level CSE
// ========================================================================
/// Eliminate common subexpressions within a single basic block.
pub fn eliminate_common_subexprs(&mut self, mf: &mut MachineFunction, bb: usize) {
if bb >= mf.blocks.len() {
return;
}
let mut avail: HashMap<ExprKey, AvailExpr> = HashMap::new();
let block = &mf.blocks[bb];
let num_insts = block.instructions.len();
// We need to know which instructions to remove.
// Strategy: first pass — identify redundancies.
let mut redundant: Vec<usize> = Vec::new();
let mut replacements: Vec<(usize, usize)> = Vec::new(); // (redundant_idx, canonical_idx)
for (idx, mi) in block.instructions.iter().enumerate() {
// Skip instructions with side effects
if self.has_side_effects(mi) {
// Side-effecting instructions must not be CSE'd.
// However, they may kill available expressions if they
// modify memory that expressions depend on.
self.kill_memory_expressions(&mut avail);
continue;
}
// Skip instructions that don't define a value
if mi.def.is_none() {
// Instructions that don't define a register can still kill
// memory expressions (e.g., stores)
if self.is_memory_store(mi) {
self.kill_memory_expressions(&mut avail);
}
continue;
}
let key = self.build_expr_key(mi);
if key.operands.is_empty() && !self.is_constant_like(mi) {
// Skip instructions with no operands that aren't constants
// (they may have implicit operands we can't track)
self.add_to_avail(&mut avail, key, mi.def, idx);
continue;
}
if let Some(avail_expr) = avail.get(&key) {
if avail_expr.is_live {
// Found a congruent expression! This instruction is redundant.
redundant.push(idx);
replacements.push((idx, avail_expr.instr_idx));
} else {
// Congruent expression exists but its definition is dead.
// Reuse this slot.
self.add_to_avail(&mut avail, key, mi.def, idx);
}
} else {
// New expression — add it
self.add_to_avail(&mut avail, key, mi.def, idx);
}
}
// Second pass: actually remove redundant instructions
// Process in reverse order to preserve indices
redundant.sort_by(|a, b| b.cmp(a)); // descending
for &redundant_idx in &redundant {
if redundant_idx < mf.blocks[bb].instructions.len() {
mf.blocks[bb].instructions.remove(redundant_idx);
self.eliminated += 1;
}
}
}
// ========================================================================
// Expression key construction
// ========================================================================
/// Build a hashable expression key from a machine instruction.
fn build_expr_key(&self, mi: &MachineInstr) -> ExprKey {
let operands: Vec<ExprOperand> = mi.operands.iter().map(ExprOperand::from).collect();
ExprKey {
opcode: mi.opcode,
operands,
}
}
/// Hash a machine instruction into a u64 for quick lookup.
pub fn hash_instruction(&self, mi: &MachineInstr) -> u64 {
let mut hash: u64 = (mi.opcode as u64).wrapping_mul(0x9E3779B97F4A7C15);
hash = hash.rotate_left(17);
for op in &mi.operands {
let op_hash = match op {
MachineOperand::Reg(vr) => (*vr as u64).wrapping_mul(0xBF58476D1CE4E5B9),
MachineOperand::PhysReg(pr) => {
((*pr as u64) + (1u64 << 32)).wrapping_mul(0x94D049BB133111EB)
}
MachineOperand::Imm(v) => (*v as u64).wrapping_mul(0xC6A4A7935BD1E995),
MachineOperand::Label(s) => Self::hash_string(s).wrapping_mul(0x9E3779B97F4A7C15),
MachineOperand::Global(s) => Self::hash_string(s).wrapping_mul(0xBF58476D1CE4E5B9),
};
hash = hash.wrapping_add(op_hash);
hash = hash.rotate_left(13);
}
if let Some(def) = mi.def {
// The def register itself doesn't affect the expression identity,
// but we include it for uniqueness of the key.
hash = hash.wrapping_add((def as u64).wrapping_mul(0x94D049BB133111EB));
}
hash
}
/// Simple string hash.
fn hash_string(s: &str) -> u64 {
let mut hash: u64 = 0;
for byte in s.bytes() {
hash = hash.wrapping_mul(31).wrapping_add(byte as u64);
}
hash
}
// ========================================================================
// Congruence checking
// ========================================================================
/// Check if two machine instructions are congruent.
///
/// Two instructions are congruent if they have the same opcode and
/// the same operands (after canonicalization).
pub fn are_congruent(&self, a: &MachineInstr, b: &MachineInstr) -> bool {
if a.opcode != b.opcode {
return false;
}
if a.operands.len() != b.operands.len() {
return false;
}
for (op_a, op_b) in a.operands.iter().zip(b.operands.iter()) {
if !Self::operand_eq(op_a, op_b) {
return false;
}
}
true
}
/// Check if two machine operands are equal.
fn operand_eq(a: &MachineOperand, b: &MachineOperand) -> bool {
match (a, b) {
(MachineOperand::Reg(va), MachineOperand::Reg(vb)) => va == vb,
(MachineOperand::PhysReg(pa), MachineOperand::PhysReg(pb)) => pa == pb,
(MachineOperand::Imm(ia), MachineOperand::Imm(ib)) => ia == ib,
(MachineOperand::Label(la), MachineOperand::Label(lb)) => la == lb,
(MachineOperand::Global(ga), MachineOperand::Global(gb)) => ga == gb,
_ => false,
}
}
// ========================================================================
// Side effect analysis
// ========================================================================
/// Check if a machine instruction has side effects that prevent CSE.
fn has_side_effects(&self, mi: &MachineInstr) -> bool {
// Branches, calls, and memory stores have side effects
self.is_branch_or_call(mi) || self.is_memory_store(mi)
}
/// Check if an instruction is a branch or call.
fn is_branch_or_call(&self, mi: &MachineInstr) -> bool {
// Approximate opcode classification:
// 7-12: typically branches and calls
let opcode = mi.opcode;
(7..=12).contains(&opcode) || opcode == 0 // call often maps to 0 in some models
}
/// Check if an instruction is a memory store.
fn is_memory_store(&self, mi: &MachineInstr) -> bool {
// Approximate: opcodes 20-21 typically are store operations
let opcode = mi.opcode;
opcode == 20 || opcode == 21
}
/// Check if an instruction is a memory load.
fn is_memory_load(&self, mi: &MachineInstr) -> bool {
let opcode = mi.opcode;
opcode == 2 || opcode == 3
}
/// Check if an instruction is a constant-like value.
fn is_constant_like(&self, mi: &MachineInstr) -> bool {
// Instructions with no register operands (only immediates)
// that define a value are constant-like
mi.operands
.iter()
.all(|op| matches!(op, MachineOperand::Imm(_)))
&& mi.def.is_some()
}
// ========================================================================
// Available expression management
// ========================================================================
/// Add an expression to the available-expression table.
fn add_to_avail(
&self,
avail: &mut HashMap<ExprKey, AvailExpr>,
key: ExprKey,
def: Option<VirtReg>,
idx: usize,
) {
avail.insert(
key,
AvailExpr {
def_vreg: def,
instr_idx: idx,
is_live: true,
},
);
}
/// Kill memory-dependent expressions from the available set.
///
/// When a store occurs, expressions that depend on memory (loads)
/// may no longer be valid. We conservatively kill all memory loads
/// from the available set.
fn kill_memory_expressions(&self, avail: &mut HashMap<ExprKey, AvailExpr>) {
// In a full implementation, we'd use alias analysis to only
// kill expressions that may alias with the store.
// Here we conservatively mark all as potentially invalid.
// For a more precise implementation, we'd only kill loads.
for entry in avail.values_mut() {
// Keep the entry but mark it as potentially invalid
// In practice, store kills loads but not pure computations
}
// More precise: remove only load expressions
avail.retain(|key, _| {
// Keep non-load expressions
!self.is_load_opcode(key.opcode)
});
}
/// Check if an opcode corresponds to a memory load.
fn is_load_opcode(&self, opcode: u32) -> bool {
opcode == 2 || opcode == 3
}
}
impl Default for MachineCSE {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Value Numbering Info (VNInfo)
// ============================================================================
/// VNInfo associates a value number with a machine instruction.
/// Used by global CSE to track congruence classes across blocks.
#[derive(Debug, Clone)]
pub struct VNInfo {
/// The value number (congruence class ID).
pub value_number: u32,
/// Whether this value is available at this point.
pub available: bool,
/// The virtual register that holds this value.
pub vreg: VirtReg,
/// The block where this value was defined.
pub defining_block: usize,
/// The instruction index within the defining block.
pub defining_instr: usize,
/// Whether this value is a constant.
pub is_constant: bool,
/// The constant value (if applicable).
pub constant_value: Option<i64>,
}
impl VNInfo {
/// Create a new VNInfo entry.
pub fn new(value_number: u32, vreg: VirtReg, block: usize, instr: usize) -> Self {
Self {
value_number,
available: true,
vreg,
defining_block: block,
defining_instr: instr,
is_constant: false,
constant_value: None,
}
}
/// Create a VNInfo for a constant value.
pub fn constant(value_number: u32, value: i64) -> Self {
Self {
value_number,
available: true,
vreg: 0,
defining_block: 0,
defining_instr: 0,
is_constant: true,
constant_value: Some(value),
}
}
/// Invalidate this value (e.g., due to a memory clobber).
pub fn invalidate(&mut self) {
self.available = false;
}
}
/// ValueNumberTable maps expression keys to value numbers for global CSE.
#[derive(Debug, Clone)]
pub struct ValueNumberTable {
/// Mapping from expression key to value number.
pub key_to_vn: HashMap<ExprKey, u32>,
/// Mapping from value number to VNInfo.
pub vn_to_info: HashMap<u32, VNInfo>,
/// Next value number to assign.
pub next_vn: u32,
}
impl ValueNumberTable {
/// Create a new value number table.
pub fn new() -> Self {
Self {
key_to_vn: HashMap::new(),
vn_to_info: HashMap::new(),
next_vn: 1,
}
}
/// Look up or create a value number for an expression.
pub fn lookup_or_create(
&mut self,
key: &ExprKey,
vreg: VirtReg,
block: usize,
instr: usize,
) -> (u32, bool) {
if let Some(&vn) = self.key_to_vn.get(key) {
// Existing value number found
if let Some(info) = self.vn_to_info.get(&vn) {
if info.available {
return (vn, true);
}
}
}
// Create new value number
let vn = self.next_vn;
self.next_vn += 1;
self.key_to_vn.insert(key.clone(), vn);
self.vn_to_info
.insert(vn, VNInfo::new(vn, vreg, block, instr));
(vn, false)
}
/// Look up a value number for an expression key.
pub fn lookup(&self, key: &ExprKey) -> Option<u32> {
self.key_to_vn.get(key).copied()
}
/// Get VNInfo for a value number.
pub fn get_info(&self, vn: u32) -> Option<&VNInfo> {
self.vn_to_info.get(&vn)
}
/// Invalidate all values (e.g., after a memory write).
pub fn invalidate_all(&mut self) {
for info in self.vn_to_info.values_mut() {
info.available = false;
}
}
}
impl Default for ValueNumberTable {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Def-Use Chain Analysis for Machine Instructions
// ============================================================================
/// DefUseInfo tracks definition-use relationships for virtual registers.
#[derive(Debug, Clone)]
pub struct DefUseInfo {
/// The virtual register.
pub vreg: VirtReg,
/// Position of the single definition.
pub def_pos: Option<(usize, usize)>,
/// All use positions.
pub uses: Vec<(usize, usize)>,
/// Whether this register is live across blocks.
pub is_global: bool,
/// Whether this is a single-def, single-use temp.
pub is_single_use: bool,
}
impl DefUseInfo {
/// Create a new def-use info entry.
pub fn new(vreg: VirtReg) -> Self {
Self {
vreg,
def_pos: None,
uses: Vec::new(),
is_global: false,
is_single_use: false,
}
}
/// Check if this value can be trivially forwarded.
pub fn is_trivially_replaceable(&self) -> bool {
self.def_pos.is_some() && self.uses.len() == 1 && !self.is_global
}
/// Check if this is a dead definition (no uses).
pub fn is_dead(&self) -> bool {
self.def_pos.is_some() && self.uses.is_empty() && !self.is_global
}
}
/// DefUseChain computes def-use chains for all virtual registers
/// within a machine function.
pub struct DefUseChain {
/// Per-register def-use info.
pub chains: HashMap<VirtReg, DefUseInfo>,
}
impl DefUseChain {
/// Create a new def-use chain analyzer.
pub fn new() -> Self {
Self {
chains: HashMap::new(),
}
}
/// Compute def-use chains for all registers in the function.
pub fn compute(&mut self, mf: &MachineFunction) {
self.chains.clear();
for (block_idx, block) in mf.blocks.iter().enumerate() {
for (instr_idx, instr) in block.instructions.iter().enumerate() {
// Record definition
if let Some(def_vreg) = instr.def {
let entry = self
.chains
.entry(def_vreg)
.or_insert_with(|| DefUseInfo::new(def_vreg));
if entry.def_pos.is_none() {
entry.def_pos = Some((block_idx, instr_idx));
} else {
// Multiple definitions — mark as global
entry.is_global = true;
}
}
// Record uses
for op in &instr.operands {
if let MachineOperand::Reg(vreg) = *op {
let entry = self
.chains
.entry(vreg)
.or_insert_with(|| DefUseInfo::new(vreg));
entry.uses.push((block_idx, instr_idx));
}
}
}
// Check if any register is live-out (used in successor blocks)
for &succ_idx in &block.successors {
{
if succ_idx != block_idx {
// Mark all defs in this block that reach uses in
// successor blocks as global
for instr in &block.instructions {
if let Some(def_vreg) = instr.def {
if let Some(entry) = self.chains.get_mut(&def_vreg) {
if entry.uses.iter().any(|(bi, _)| *bi == succ_idx) {
entry.is_global = true;
}
}
}
}
}
}
}
}
// Set single-use flag
for entry in self.chains.values_mut() {
entry.is_single_use = entry.uses.len() == 1;
}
}
/// Get the def-use info for a virtual register.
pub fn get_info(&self, vreg: VirtReg) -> Option<&DefUseInfo> {
self.chains.get(&vreg)
}
/// Check if a definition dominates all uses.
pub fn dominates_all_uses(&self, vreg: VirtReg) -> bool {
if let Some(info) = self.chains.get(&vreg) {
if let Some((def_block, _def_instr)) = info.def_pos {
info.uses
.iter()
.all(|(use_block, _)| *use_block >= def_block)
} else {
false
}
} else {
false
}
}
/// Get all registers that are dead (defined but never used).
pub fn dead_registers(&self) -> Vec<VirtReg> {
self.chains
.iter()
.filter(|(_, info)| info.is_dead())
.map(|(&vreg, _)| vreg)
.collect()
}
/// Get all registers that are trivially replaceable.
pub fn trivially_replaceable(&self) -> Vec<VirtReg> {
self.chains
.iter()
.filter(|(_, info)| info.is_trivially_replaceable())
.map(|(&vreg, _)| vreg)
.collect()
}
}
impl Default for DefUseChain {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Register Liveness-Aware CSE
// ============================================================================
/// LivenessAwareCSE extends MachineCSE with register liveness tracking.
/// It ensures that CSE replacements only occur when the original
/// definition is still live at the point of the redundant computation.
pub struct LivenessAwareCSE {
/// Core CSE pass.
pub cse: MachineCSE,
/// Def-use chains for the function.
pub def_use: DefUseChain,
/// Per-block live register sets at each instruction.
pub live_sets: Vec<Vec<HashSet<VirtReg>>>,
/// Whether liveness has been computed.
pub liveness_computed: bool,
}
impl LivenessAwareCSE {
/// Create a new liveness-aware CSE pass.
pub fn new() -> Self {
Self {
cse: MachineCSE::new(),
def_use: DefUseChain::new(),
live_sets: Vec::new(),
liveness_computed: false,
}
}
/// Run CSE with liveness awareness.
pub fn run_on_function(&mut self, mf: &mut MachineFunction) -> usize {
// Step 1: Compute def-use chains
self.def_use.compute(mf);
// Step 2: Compute liveness per instruction
self.compute_liveness(mf);
// Step 3: Run CSE with liveness checks
let mut eliminated = 0;
for (block_idx, block) in mf.blocks.iter_mut().enumerate() {
let mut avail: HashMap<ExprKey, (VirtReg, usize)> = HashMap::new();
// We need to track which instructions to remove
let mut to_remove: Vec<usize> = Vec::new();
let mut replacements: Vec<(usize, VirtReg)> = Vec::new();
for (instr_idx, instr) in block.instructions.iter().enumerate() {
if self.cse.has_side_effects(instr) {
// Side-effecting instructions kill available expressions
// that may be affected (memory ops kill memory expressions)
if self.cse.is_memory_store(instr) {
// Kill memory-dependent expressions (opcodes 2,3 = loads)
avail.retain(|key, _| key.opcode != 2 && key.opcode != 3);
}
continue;
}
let key = self.cse.build_expr_key(instr);
if let Some(&(def_vreg, _def_instr_idx)) = avail.get(&key) {
// Found congruent expression — check if the original
// definition is still live at this point
if self.is_live_at(def_vreg, block_idx, instr_idx) {
// Replace use: forward the earlier definition
replacements.push((instr_idx, def_vreg));
to_remove.push(instr_idx);
eliminated += 1;
continue;
}
}
// Add to available expressions
if let Some(def_vreg) = instr.def {
avail.insert(key, (def_vreg, instr_idx));
}
}
// Apply replacements: update uses of the removed definitions
// First, collect the def_vreg for each removed instruction
let def_map: HashMap<usize, VirtReg> = replacements
.iter()
.map(|&(removed_idx, _)| {
let def = block.instructions[removed_idx].def;
(removed_idx, def)
})
.filter(|(_, def)| def.is_some())
.map(|(idx, def)| (idx, def.unwrap()))
.collect();
for &(removed_idx, replacement_vreg) in &replacements {
let removed_def = def_map.get(&removed_idx).copied();
for instr in block.instructions.iter_mut().skip(removed_idx + 1) {
for op in &mut instr.operands {
if let MachineOperand::Reg(vreg) = *op {
if Some(vreg) == removed_def {
*op = MachineOperand::Reg(replacement_vreg);
}
}
}
}
}
// Remove redundant instructions (in reverse order)
to_remove.sort_unstable();
to_remove.dedup();
for &idx in to_remove.iter().rev() {
if idx < block.instructions.len() {
block.instructions.remove(idx);
}
}
}
self.cse.eliminated += eliminated;
eliminated
}
/// Compute live sets for each instruction in each block.
fn compute_liveness(&mut self, mf: &MachineFunction) {
self.live_sets.clear();
for block in &mf.blocks {
let mut block_live: Vec<HashSet<VirtReg>> = Vec::new();
let mut live: HashSet<VirtReg> = HashSet::new();
// Process in reverse within block to compute liveness
for instr in block.instructions.iter().rev() {
// Record current live set
block_live.push(live.clone());
// A definition kills the register (remove from live set)
if let Some(def_vreg) = instr.def {
live.remove(&def_vreg);
}
// Uses add registers to the live set
for op in &instr.operands {
if let MachineOperand::Reg(vreg) = *op {
live.insert(vreg);
}
}
}
// Reverse back so index 0 = before first instruction
block_live.reverse();
self.live_sets.push(block_live);
}
self.liveness_computed = true;
}
/// Check if a virtual register is live at a given block/instruction point.
fn is_live_at(&self, vreg: VirtReg, block_idx: usize, instr_idx: usize) -> bool {
if let Some(block_live) = self.live_sets.get(block_idx) {
if let Some(live_set) = block_live.get(instr_idx) {
return live_set.contains(&vreg);
}
}
false
}
/// Print liveness debug info.
pub fn print_liveness(&self) {
for (block_idx, block_live) in self.live_sets.iter().enumerate() {
eprintln!("Block {}:", block_idx);
for (instr_idx, live_set) in block_live.iter().enumerate() {
if !live_set.is_empty() {
eprintln!(
" instr {}: live = {:?}",
instr_idx,
live_set.iter().collect::<Vec<_>>()
);
}
}
}
}
}
impl Default for LivenessAwareCSE {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Global Machine CSE with Value Numbering
// ============================================================================
/// GlobalMachineCSE extends local CSE to operate across basic blocks
/// using value numbering and availability analysis.
///
/// Algorithm:
/// 1. Compute value numbers for all expressions in all blocks.
/// 2. Propagate availability of expressions across CFG edges.
/// 3. For each instruction, check if a congruent expression is available
/// from a dominating definition.
/// 4. Replace redundant instructions with copies from the dominating def.
pub struct GlobalMachineCSE {
/// Core CSE pass.
pub local_cse: MachineCSE,
/// Value number table.
pub vn_table: ValueNumberTable,
/// Set of expressions available at the start of each block.
pub avail_in: Vec<HashSet<u32>>,
/// Set of expressions available at the end of each block.
pub avail_out: Vec<HashSet<u32>>,
/// Number of global redundancies eliminated.
pub global_eliminated: usize,
}
impl GlobalMachineCSE {
/// Create a new global CSE pass.
pub fn new() -> Self {
Self {
local_cse: MachineCSE::new(),
vn_table: ValueNumberTable::new(),
avail_in: Vec::new(),
avail_out: Vec::new(),
global_eliminated: 0,
}
}
/// Run global CSE on a machine function.
pub fn run_on_function(&mut self, mf: &mut MachineFunction) -> usize {
self.global_eliminated = 0;
if mf.blocks.is_empty() {
return 0;
}
// Step 1: Build value numbers for all expressions
self.build_value_numbers(mf);
// Step 2: Compute availability via iterative dataflow
self.compute_availability(mf);
// Step 3: Eliminate globally redundant expressions
self.eliminate_global_redundancies(mf);
self.global_eliminated
}
/// Assign value numbers to all expressions in all blocks.
fn build_value_numbers(&mut self, mf: &mut MachineFunction) {
self.vn_table = ValueNumberTable::new();
for (block_idx, block) in mf.blocks.iter_mut().enumerate() {
for (instr_idx, instr) in block.instructions.iter().enumerate() {
if self.local_cse.has_side_effects(instr) {
// Invalidate memory-related value numbers on stores
if self.local_cse.is_memory_store(instr) {
self.vn_table.invalidate_all();
}
continue;
}
let key = self.local_cse.build_expr_key(instr);
let def_vreg = instr.def.unwrap_or(0);
// Look up or create value number
self.vn_table
.lookup_or_create(&key, def_vreg, block_idx, instr_idx);
}
}
}
/// Compute available expressions at block boundaries using iterative
/// dataflow analysis.
fn compute_availability(&mut self, mf: &MachineFunction) {
let n = mf.blocks.len();
// Initialize: avail_in[0] = empty, others = all VNs (top)
self.avail_in = vec![HashSet::new(); n];
self.avail_out = vec![HashSet::new(); n];
// Collect all value numbers
let all_vns: HashSet<u32> = self.vn_table.vn_to_info.keys().copied().collect();
// Initialize all non-entry blocks with all VNs (optimistic)
for i in 1..n {
self.avail_in[i] = all_vns.clone();
}
// Iterative dataflow
let mut changed = true;
let mut iterations = 0;
while changed && iterations < 100 {
changed = false;
iterations += 1;
for block_idx in 0..n {
// Compute avail_in from predecessors' avail_out
let mut new_in: HashSet<u32> = if block_idx == 0 {
HashSet::new()
} else {
// Intersection of predecessors' avail_out
let pred_indices: Vec<usize> = (0..n)
.filter(|&i| mf.blocks[i].successors.contains(&block_idx))
.collect();
if pred_indices.is_empty() {
HashSet::new()
} else {
let mut inter = self.avail_out[pred_indices[0]].clone();
for &pi in &pred_indices[1..] {
inter = inter.intersection(&self.avail_out[pi]).copied().collect();
}
inter
}
};
// Compute avail_out = GEN ∪ (avail_in - KILL)
let mut new_out = new_in.clone();
for instr in &mf.blocks[block_idx].instructions {
if self.local_cse.has_side_effects(instr) {
if self.local_cse.is_memory_store(instr) {
// Kill all memory-dependent expressions
new_out.clear();
}
continue;
}
let key = self.local_cse.build_expr_key(instr);
if let Some(vn) = self.vn_table.lookup(&key) {
new_out.insert(vn); // GEN
}
}
if new_in != self.avail_in[block_idx] {
self.avail_in[block_idx] = new_in;
changed = true;
}
if new_out != self.avail_out[block_idx] {
self.avail_out[block_idx] = new_out;
changed = true;
}
}
}
}
/// Eliminate globally redundant expressions.
fn eliminate_global_redundancies(&mut self, mf: &mut MachineFunction) {
for (block_idx, block) in mf.blocks.iter_mut().enumerate() {
let mut avail = self.avail_in[block_idx].clone();
let mut to_remove: Vec<usize> = Vec::new();
for (instr_idx, instr) in block.instructions.iter().enumerate() {
if self.local_cse.has_side_effects(instr) {
if self.local_cse.is_memory_store(instr) {
avail.clear();
}
continue;
}
let key = self.local_cse.build_expr_key(instr);
if let Some(vn) = self.vn_table.lookup(&key) {
if avail.contains(&vn) {
// Redundant! Mark for removal
to_remove.push(instr_idx);
self.global_eliminated += 1;
} else {
// Not redundant — add to available set
avail.insert(vn);
}
}
}
// Remove redundant instructions
to_remove.sort_unstable();
to_remove.dedup();
for &idx in to_remove.iter().rev() {
if idx < block.instructions.len() {
block.instructions.remove(idx);
}
}
}
}
/// Get statistics for the global CSE pass.
pub fn print_stats(&self) {
eprintln!(
"GlobalMachineCSE: {} global redundancies eliminated",
self.global_eliminated
);
eprintln!(" Value numbers: {}", self.vn_table.vn_to_info.len());
eprintln!(" Expression keys: {}", self.vn_table.key_to_vn.len());
}
}
impl Default for GlobalMachineCSE {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
fn make_mi(opcode: u32, def: Option<u32>, operands: Vec<MachineOperand>) -> MachineInstr {
MachineInstr {
opcode,
operands,
def,
}
}
fn make_alu(def: u32, op1: u32, op2: u32) -> MachineInstr {
MachineInstr {
opcode: 1,
operands: vec![MachineOperand::Reg(op1), MachineOperand::Reg(op2)],
def: Some(def),
}
}
#[test]
fn test_machine_cse_new() {
let cse = MachineCSE::new();
assert_eq!(cse.eliminated, 0);
assert!(cse.enabled);
}
#[test]
fn test_default() {
let cse = MachineCSE::default();
assert!(cse.enabled);
}
#[test]
fn test_hash_instruction_different() {
let cse = MachineCSE::new();
let mi1 = make_mi(1, Some(1), vec![MachineOperand::Reg(2)]);
let mi2 = make_mi(2, Some(1), vec![MachineOperand::Reg(2)]);
assert_ne!(cse.hash_instruction(&mi1), cse.hash_instruction(&mi2));
}
#[test]
fn test_hash_instruction_same() {
let cse = MachineCSE::new();
let mi1 = make_mi(1, Some(1), vec![MachineOperand::Reg(2)]);
let mi2 = make_mi(1, Some(1), vec![MachineOperand::Reg(2)]);
// Same opcode, same operands, same def → same hash
assert_eq!(cse.hash_instruction(&mi1), cse.hash_instruction(&mi2));
}
#[test]
fn test_are_congruent_true() {
let cse = MachineCSE::new();
let mi1 = make_mi(
1,
Some(1),
vec![MachineOperand::Reg(2), MachineOperand::Imm(5)],
);
let mi2 = make_mi(
1,
Some(3),
vec![MachineOperand::Reg(2), MachineOperand::Imm(5)],
);
assert!(cse.are_congruent(&mi1, &mi2));
}
#[test]
fn test_are_congruent_false_opcode() {
let cse = MachineCSE::new();
let mi1 = make_mi(1, Some(1), vec![MachineOperand::Reg(2)]);
let mi2 = make_mi(2, Some(1), vec![MachineOperand::Reg(2)]);
assert!(!cse.are_congruent(&mi1, &mi2));
}
#[test]
fn test_are_congruent_false_operands() {
let cse = MachineCSE::new();
let mi1 = make_mi(1, Some(1), vec![MachineOperand::Reg(2)]);
let mi2 = make_mi(1, Some(1), vec![MachineOperand::Reg(3)]);
assert!(!cse.are_congruent(&mi1, &mi2));
}
#[test]
fn test_are_congruent_different_len() {
let cse = MachineCSE::new();
let mi1 = make_mi(1, Some(1), vec![MachineOperand::Reg(2)]);
let mi2 = make_mi(
1,
Some(1),
vec![MachineOperand::Reg(2), MachineOperand::Reg(3)],
);
assert!(!cse.are_congruent(&mi1, &mi2));
}
#[test]
fn test_has_side_effects_branch() {
let cse = MachineCSE::new();
let mi = make_mi(7, None, vec![]);
assert!(cse.has_side_effects(&mi));
}
#[test]
fn test_has_side_effects_store() {
let cse = MachineCSE::new();
let mi = make_mi(20, None, vec![MachineOperand::Reg(1)]);
assert!(cse.has_side_effects(&mi));
}
#[test]
fn test_has_side_effects_alu() {
let cse = MachineCSE::new();
let mi = make_mi(1, Some(1), vec![MachineOperand::Reg(2)]);
assert!(!cse.has_side_effects(&mi));
}
#[test]
fn test_is_memory_load() {
let cse = MachineCSE::new();
assert!(cse.is_memory_load(&make_mi(2, None, vec![])));
assert!(!cse.is_memory_load(&make_mi(1, None, vec![])));
}
#[test]
fn test_is_memory_store() {
let cse = MachineCSE::new();
assert!(cse.is_memory_store(&make_mi(20, None, vec![])));
assert!(!cse.is_memory_store(&make_mi(2, None, vec![])));
}
#[test]
fn test_operand_eq() {
assert!(MachineCSE::operand_eq(
&MachineOperand::Reg(5),
&MachineOperand::Reg(5)
));
assert!(!MachineCSE::operand_eq(
&MachineOperand::Reg(5),
&MachineOperand::Reg(3)
));
assert!(MachineCSE::operand_eq(
&MachineOperand::Imm(42),
&MachineOperand::Imm(42)
));
assert!(!MachineCSE::operand_eq(
&MachineOperand::Imm(1),
&MachineOperand::Imm(2)
));
assert!(!MachineCSE::operand_eq(
&MachineOperand::Reg(1),
&MachineOperand::Imm(1)
));
}
#[test]
fn test_eliminate_block_no_redundancy() {
let mut cse = MachineCSE::new();
let mut mf = MachineFunction::new("func");
let mbb = MachineBasicBlock {
name: "entry".to_string(),
instructions: vec![make_alu(1, 10, 11), make_alu(2, 12, 13)],
successors: Vec::new(),
};
mf.push_block(mbb);
cse.eliminate_common_subexprs(&mut mf, 0);
assert_eq!(cse.eliminated, 0);
assert_eq!(mf.blocks[0].instructions.len(), 2);
}
#[test]
fn test_eliminate_block_with_redundancy() {
let mut cse = MachineCSE::new();
let mut mf = MachineFunction::new("func");
let mbb = MachineBasicBlock {
name: "entry".to_string(),
instructions: vec![
make_alu(1, 10, 11),
make_alu(2, 10, 11), // Redundant: same as first
],
successors: Vec::new(),
};
mf.push_block(mbb);
cse.eliminate_common_subexprs(&mut mf, 0);
assert_eq!(cse.eliminated, 1);
assert_eq!(mf.blocks[0].instructions.len(), 1);
}
#[test]
fn test_run_on_function_disabled() {
let mut cse = MachineCSE::new();
cse.enabled = false;
let mut mf = MachineFunction::new("func");
let mbb = MachineBasicBlock {
name: "entry".to_string(),
instructions: vec![make_alu(1, 10, 11), make_alu(2, 10, 11)],
successors: Vec::new(),
};
mf.push_block(mbb);
let count = cse.run_on_function(&mut mf);
assert_eq!(count, 0);
assert_eq!(mf.blocks[0].instructions.len(), 2);
}
#[test]
fn test_run_on_empty_function() {
let mut cse = MachineCSE::new();
let mut mf = MachineFunction::new("empty");
let count = cse.run_on_function(&mut mf);
assert_eq!(count, 0);
}
#[test]
fn test_hash_string() {
let h1 = MachineCSE::hash_string("hello");
let h2 = MachineCSE::hash_string("hello");
let h3 = MachineCSE::hash_string("world");
assert_eq!(h1, h2);
assert_ne!(h1, h3);
}
}