llvm-native-core 0.1.12

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
//! RISC-V Peephole Optimizer — machine-level peephole optimizations.
//!
//! Applies peephole patterns to `MachineInstr` sequences within a
//! `MachineFunction`. Transformations include:
//!
//! - NOP / trivial self-move elimination
//! - Redundant MV elimination
//! - Branch-over-jump inversion
//! - LUI+ADDI and AUIPC+ADDI fusion
//! - Zero-shift removal (SLLI rd, rs, 0 → MV)
//! - Dead ADD elimination
//! - Canonical pseudo recognition (NEG, NOT)

use super::riscv_instr_info::RiscVOpcode;
use super::riscv_register_info::GPR_BASE;
use crate::codegen::{MachineFunction, MachineInstr, MachineOperand};

// ============================================================================
// Optimization statistics
// ============================================================================

/// Statistics collected during peephole optimization.
#[derive(Debug, Clone, Default)]
pub struct RiscVOptStats {
    pub nops_eliminated: usize,
    pub redundant_moves_eliminated: usize,
    pub compare_branches_folded: usize,
    pub lui_addi_fusions: usize,
    pub auipc_addi_fusions: usize,
    pub branch_chains_optimized: usize,
    pub dead_adds_eliminated: usize,
    pub zero_shifts_removed: usize,
    pub canonical_pseudos_recognized: usize,
    pub total_instructions_before: usize,
    pub total_instructions_after: usize,
}

impl RiscVOptStats {
    pub fn new() -> Self {
        Self::default()
    }

    /// Return total number of instructions removed.
    pub fn total_removed(&self) -> usize {
        self.total_instructions_before
            .saturating_sub(self.total_instructions_after)
    }
}

// ============================================================================
// RiscVPeepholeOptimizer
// ============================================================================

/// RISC-V peephole optimizer.
///
/// Applies multiple passes in order to optimize machine instruction sequences.
pub struct RiscVPeepholeOptimizer {
    pub stats: RiscVOptStats,
    pub is_64bit: bool,
}

impl RiscVPeepholeOptimizer {
    pub fn new(is_64bit: bool) -> Self {
        Self {
            stats: RiscVOptStats::new(),
            is_64bit,
        }
    }

    /// Run all peephole optimizations on a `MachineFunction`.
    pub fn optimize(&mut self, mf: &mut MachineFunction) -> RiscVOptStats {
        self.stats.total_instructions_before = mf.blocks.iter().map(|b| b.instructions.len()).sum();

        for block in &mut mf.blocks {
            self.eliminate_nop_moves(&mut block.instructions);
            self.fold_redundant_ops(&mut block.instructions);
            self.optimize_branch_chains(&mut block.instructions);
            self.eliminate_zero_shifts(&mut block.instructions);
            self.eliminate_dead_adds(&mut block.instructions);
            self.recognize_canonical_pseudos(&mut block.instructions);
            self.fuse_lui_addi(&mut block.instructions);
            self.eliminate_redundant_moves(&mut block.instructions);
        }

        self.stats.total_instructions_after = mf.blocks.iter().map(|b| b.instructions.len()).sum();

        self.stats.clone()
    }

    // ------------------------------------------------------------------
    // Pass 1: NOP and trivial self-move elimination
    // ------------------------------------------------------------------

    /// Eliminate explicit NOPs, `ADDI x0, x0, 0`, self-moves, and
    /// zero-shifts where rd == rs and the shift amount is 0.
    pub fn eliminate_nop_moves(&mut self, instructions: &mut Vec<MachineInstr>) {
        let mut i = 0;
        while i < instructions.len() {
            let op = instructions[i].opcode;
            let remove = if op == RiscVOpcode::NOP as u32 {
                true
            } else if op == RiscVOpcode::ADDI as u32 {
                let rd = get_rd_field(&instructions[i]);
                let rs1 = get_rs1_field(&instructions[i]);
                // ADDI x0, x0, 0 → NOP
                rd == 0 && rs1 == 0 && get_imm_field(&instructions[i]) == Some(0)
                    // ADDI rd, rs, 0 where rd == rs → self-move
                    || (rd == rs1 && get_imm_field(&instructions[i]) == Some(0))
            } else if op == RiscVOpcode::SLLI as u32 {
                let rd = get_rd_field(&instructions[i]);
                let rs1 = get_rs1_field(&instructions[i]);
                rd == rs1 && get_imm_field(&instructions[i]) == Some(0)
            } else {
                false
            };

            if remove {
                instructions.remove(i);
                self.stats.nops_eliminated += 1;
            } else {
                i += 1;
            }
        }
    }

    // ------------------------------------------------------------------
    // Pass 2: Fold redundant operations and compare-branch sequences
    // ------------------------------------------------------------------

    /// Fold redundant operations:
    /// - `XORI rd, rd, -1` → `NOT rd` (canonical NOT)
    /// - `ADDI rd, rs, 0` where rd == rs → removed (self-add)
    pub fn fold_redundant_ops(&mut self, instructions: &mut Vec<MachineInstr>) {
        for instr in instructions.iter_mut() {
            let op = instr.opcode;

            // XORI rd, rs, -1 → NOT rd, rs
            if op == RiscVOpcode::XORI as u32 {
                if get_imm_field(instr) == Some(-1) {
                    let rd = get_rd_field(instr);
                    let rs1 = get_rs1_field(instr);
                    let mut not_instr = MachineInstr::new(RiscVOpcode::NOT as u32);
                    not_instr.operands.push(MachineOperand::Reg(to_reg_id(rd)));
                    not_instr.operands.push(MachineOperand::Reg(to_reg_id(rs1)));
                    *instr = not_instr;
                    self.stats.canonical_pseudos_recognized += 1;
                }
            }
        }
    }

    // ------------------------------------------------------------------
    // Pass 3: Branch chain optimization
    // ------------------------------------------------------------------

    /// Invert branch-over-jump patterns.
    ///
    /// Pattern: `BEQ x, y, L1; J target; L1:` → `BNE x, y, target; L1:`
    ///
    /// A conditional branch followed by an unconditional jump can be folded
    /// into an inverted branch that targets the jump's destination.
    pub fn optimize_branch_chains(&mut self, instructions: &mut Vec<MachineInstr>) {
        let mut i = 0;
        while i + 1 < instructions.len() {
            let branch_op = instructions[i].opcode;
            let next_op = instructions[i + 1].opcode;

            if is_conditional_branch_op(branch_op) && is_unconditional_jump_op(next_op) {
                let inverted = invert_branch_op(branch_op);
                if let Some(inv_op) = inverted {
                    // Get the jump target offset from the J instruction
                    let j_target = get_imm_field(&instructions[i + 1]).unwrap_or(0);

                    // Build the inverted branch with the jump's target
                    let mut new_branch = MachineInstr::new(inv_op);
                    // Copy rs1 and rs2 from the original branch (operands 0 and 1)
                    for idx in 0..2.min(instructions[i].operands.len()) {
                        new_branch
                            .operands
                            .push(instructions[i].operands[idx].clone());
                    }
                    // Add the jump target as the branch offset
                    new_branch
                        .operands
                        .push(MachineOperand::Imm(j_target as i64));

                    instructions[i] = new_branch;
                    instructions.remove(i + 1);
                    self.stats.branch_chains_optimized += 1;
                }
            }
            i += 1;
        }
    }

    // ------------------------------------------------------------------
    // Pass 4: Zero-shift elimination
    // ------------------------------------------------------------------

    /// Replace shifts by zero with MV:
    /// `SLLI rd, rs, 0` → `MV rd, rs`
    /// `SRLI rd, rs, 0` → `MV rd, rs`
    /// `SRAI rd, rs, 0` → `MV rd, rs`
    fn eliminate_zero_shifts(&mut self, instructions: &mut Vec<MachineInstr>) {
        for instr in instructions.iter_mut() {
            let op = instr.opcode;
            let is_shift = op == RiscVOpcode::SLLI as u32
                || op == RiscVOpcode::SRLI as u32
                || op == RiscVOpcode::SRAI as u32;

            if is_shift && get_imm_field(instr) == Some(0) {
                let rd = get_rd_field(instr);
                let rs1 = get_rs1_field(instr);
                let mut mv = MachineInstr::new(RiscVOpcode::MV as u32);
                mv.operands.push(MachineOperand::Reg(to_reg_id(rd)));
                mv.operands.push(MachineOperand::Reg(to_reg_id(rs1)));
                *instr = mv;
                self.stats.zero_shifts_removed += 1;
            }
        }
    }

    // ------------------------------------------------------------------
    // Pass 5: Dead ADD elimination
    // ------------------------------------------------------------------

    /// Remove `ADDI x0, x0, 0` (writes to x0, always dead).
    fn eliminate_dead_adds(&mut self, instructions: &mut Vec<MachineInstr>) {
        let mut i = 0;
        while i < instructions.len() {
            let op = instructions[i].opcode;
            if op == RiscVOpcode::ADDI as u32 {
                let rd = get_rd_field(&instructions[i]);
                let rs1 = get_rs1_field(&instructions[i]);
                let imm = get_imm_field(&instructions[i]).unwrap_or(0);
                if rd == 0 && rs1 == 0 && imm == 0 {
                    instructions.remove(i);
                    self.stats.dead_adds_eliminated += 1;
                    continue;
                }
            }
            i += 1;
        }
    }

    // ------------------------------------------------------------------
    // Pass 6: Canonical pseudo recognition
    // ------------------------------------------------------------------

    /// Recognize canonical pseudo-instruction patterns:
    /// - `ADDI rd, rs, 0` where rd != rs → `MV rd, rs`
    /// - `SUB rd, x0, rs` → `NEG rd, rs`
    /// - `SLLI rd, rs, 0` → `MV rd, rs` (already handled by zero-shift pass,
    ///   but this handles the case where rd != rs and shift is 0)
    fn recognize_canonical_pseudos(&mut self, instructions: &mut Vec<MachineInstr>) {
        for instr in instructions.iter_mut() {
            let op = instr.opcode;

            // ADDI rd, rs, 0 → MV rd, rs
            if op == RiscVOpcode::ADDI as u32 && get_imm_field(instr) == Some(0) {
                let rd = get_rd_field(instr);
                let rs1 = get_rs1_field(instr);
                if rd != rs1 {
                    let mut mv = MachineInstr::new(RiscVOpcode::MV as u32);
                    mv.operands.push(MachineOperand::Reg(to_reg_id(rd)));
                    mv.operands.push(MachineOperand::Reg(to_reg_id(rs1)));
                    *instr = mv;
                    self.stats.canonical_pseudos_recognized += 1;
                }
            }

            // SUB rd, x0, rs → NEG rd, rs
            if op == RiscVOpcode::SUB as u32 && get_rs1_field(instr) == 0 {
                let rd = get_rd_field(instr);
                let rs2 = get_rs2_field(instr);
                let mut neg = MachineInstr::new(RiscVOpcode::NEG as u32);
                neg.operands.push(MachineOperand::Reg(to_reg_id(rd)));
                neg.operands.push(MachineOperand::Reg(to_reg_id(rs2)));
                *instr = neg;
                self.stats.canonical_pseudos_recognized += 1;
            }

            // SLLI rd, rs, 0 → MV rd, rs (for cases where rd != rs)
            if op == RiscVOpcode::SLLI as u32 && get_imm_field(instr) == Some(0) {
                let rd = get_rd_field(instr);
                let rs1 = get_rs1_field(instr);
                if rd != rs1 {
                    let mut mv = MachineInstr::new(RiscVOpcode::MV as u32);
                    mv.operands.push(MachineOperand::Reg(to_reg_id(rd)));
                    mv.operands.push(MachineOperand::Reg(to_reg_id(rs1)));
                    *instr = mv;
                    self.stats.canonical_pseudos_recognized += 1;
                }
            }
        }
    }

    // ------------------------------------------------------------------
    // Pass 7: LUI + ADDI fusion
    // ------------------------------------------------------------------

    /// Fuse `LUI rd, upper; ADDI rd, rd, lower` → `LI rd, full_imm`.
    fn fuse_lui_addi(&mut self, instructions: &mut Vec<MachineInstr>) {
        let mut i = 0;
        while i + 1 < instructions.len() {
            if instructions[i].opcode == RiscVOpcode::LUI as u32
                && instructions[i + 1].opcode == RiscVOpcode::ADDI as u32
            {
                let lui_rd = get_rd_field(&instructions[i]);
                let addi_rd = get_rd_field(&instructions[i + 1]);
                let addi_rs1 = get_rs1_field(&instructions[i + 1]);

                if lui_rd == addi_rd && addi_rs1 == lui_rd {
                    let lui_imm = get_imm_field(&instructions[i]).unwrap_or(0) as u32;
                    let addi_imm = get_imm_field(&instructions[i + 1]).unwrap_or(0);
                    let full_imm = (lui_imm as i64) + (addi_imm as i64);

                    let mut li = MachineInstr::new(RiscVOpcode::LI as u32);
                    li.operands.push(MachineOperand::Reg(to_reg_id(lui_rd)));
                    li.operands.push(MachineOperand::Imm(full_imm));

                    instructions[i] = li;
                    instructions.remove(i + 1);
                    self.stats.lui_addi_fusions += 1;
                }
            }
            i += 1;
        }
    }

    // ------------------------------------------------------------------
    // Pass 8: Redundant move elimination
    // ------------------------------------------------------------------

    /// Redirect consecutive moves from the same source.
    ///
    /// Pattern: `MV rd1, rs; MV rd2, rs` → `MV rd1, rs; MV rd2, rd1`
    pub fn eliminate_redundant_moves(&mut self, instructions: &mut Vec<MachineInstr>) {
        let mut i = 0;
        while i + 1 < instructions.len() {
            let a_op = instructions[i].opcode;
            let b_op = instructions[i + 1].opcode;

            let a_is_move = a_op == RiscVOpcode::MV as u32
                || (a_op == RiscVOpcode::ADDI as u32 && get_imm_field(&instructions[i]) == Some(0));
            let b_is_move = b_op == RiscVOpcode::MV as u32
                || (b_op == RiscVOpcode::ADDI as u32
                    && get_imm_field(&instructions[i + 1]) == Some(0));

            if a_is_move && b_is_move {
                let a_rd = get_rd_field(&instructions[i]);
                let a_rs1 = get_rs1_field(&instructions[i]);
                let b_rs1 = get_rs1_field(&instructions[i + 1]);

                // If second MV reads same source as first, redirect to first's dest
                if b_rs1 == a_rs1 && a_rd != a_rs1 && a_rd != b_rs1 {
                    if instructions[i + 1].operands.len() > 1 {
                        instructions[i + 1].operands[1] = MachineOperand::Reg(to_reg_id(a_rd));
                    }
                    self.stats.redundant_moves_eliminated += 1;
                }
            }

            i += 1;
        }
    }
}

// ============================================================================
// Instruction inspection helpers
// ============================================================================

/// Extract the rd field (operand 0) as a 0–31 register index.
fn get_rd_field(mi: &MachineInstr) -> u8 {
    mi.operands.first().and_then(get_reg).unwrap_or(0)
}

/// Extract the rs1 field (operand 1) as a 0–31 register index.
fn get_rs1_field(mi: &MachineInstr) -> u8 {
    mi.operands.get(1).and_then(get_reg).unwrap_or(0)
}

/// Extract the rs2 field (operand 2) as a 0–31 register index.
fn get_rs2_field(mi: &MachineInstr) -> u8 {
    mi.operands.get(2).and_then(get_reg).unwrap_or(0)
}

/// Find the first immediate operand and return its value.
fn get_imm_field(mi: &MachineInstr) -> Option<i32> {
    mi.operands.iter().find_map(|op| match op {
        MachineOperand::Imm(v) => Some(*v as i32),
        _ => None,
    })
}

/// Extract a 0–31 register index from a MachineOperand.
fn get_reg(op: &MachineOperand) -> Option<u8> {
    match op {
        MachineOperand::Reg(v) => {
            let v = *v as u16;
            if v >= GPR_BASE && v < GPR_BASE + 32 {
                Some((v - GPR_BASE) as u8)
            } else {
                Some(0)
            }
        }
        MachineOperand::PhysReg(v) => {
            let v = *v as u16;
            if v >= GPR_BASE && v < GPR_BASE + 32 {
                Some((v - GPR_BASE) as u8)
            } else {
                Some(0)
            }
        }
        _ => None,
    }
}

/// Convert a 0–31 register field back to a full 3000-series register ID.
fn to_reg_id(field: u8) -> u32 {
    (GPR_BASE + field as u16) as u32
}

/// Check if an opcode value is a conditional branch.
fn is_conditional_branch_op(op: u32) -> bool {
    matches!(
        op,
        x if x == RiscVOpcode::BEQ as u32
            || x == RiscVOpcode::BNE as u32
            || x == RiscVOpcode::BLT as u32
            || x == RiscVOpcode::BGE as u32
            || x == RiscVOpcode::BLTU as u32
            || x == RiscVOpcode::BGEU as u32
    )
}

/// Check if an opcode value is an unconditional jump.
fn is_unconditional_jump_op(op: u32) -> bool {
    op == RiscVOpcode::JAL as u32 || op == RiscVOpcode::J as u32
}

/// Invert the condition of a branch opcode.
fn invert_branch_op(op: u32) -> Option<u32> {
    if op == RiscVOpcode::BEQ as u32 {
        Some(RiscVOpcode::BNE as u32)
    } else if op == RiscVOpcode::BNE as u32 {
        Some(RiscVOpcode::BEQ as u32)
    } else if op == RiscVOpcode::BLT as u32 {
        Some(RiscVOpcode::BGE as u32)
    } else if op == RiscVOpcode::BGE as u32 {
        Some(RiscVOpcode::BLT as u32)
    } else if op == RiscVOpcode::BLTU as u32 {
        Some(RiscVOpcode::BGEU as u32)
    } else if op == RiscVOpcode::BGEU as u32 {
        Some(RiscVOpcode::BLTU as u32)
    } else {
        None
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    fn mi(opcode: u32, ops: Vec<MachineOperand>) -> MachineInstr {
        let mut m = MachineInstr::new(opcode);
        m.operands = ops;
        m
    }

    fn reg(id: u16) -> MachineOperand {
        MachineOperand::Reg(id as u32)
    }

    fn imm(v: i32) -> MachineOperand {
        MachineOperand::Imm(v as i64)
    }

    #[test]
    fn test_eliminate_nop() {
        // NOP removal
        let mut instrs = vec![
            mi(RiscVOpcode::NOP as u32, vec![]),
            mi(
                RiscVOpcode::ADDI as u32,
                vec![reg(3005), reg(3010), imm(42)],
            ),
            mi(RiscVOpcode::NOP as u32, vec![]),
        ];
        let mut opt = RiscVPeepholeOptimizer::new(true);
        opt.eliminate_nop_moves(&mut instrs);
        assert_eq!(instrs.len(), 1);
        assert_eq!(opt.stats.nops_eliminated, 2);
    }

    #[test]
    fn test_eliminate_addi_x0_x0_0() {
        // ADDI x0, x0, 0 is a NOP
        let mut instrs = vec![mi(
            RiscVOpcode::ADDI as u32,
            vec![reg(3000), reg(3000), imm(0)],
        )];
        let mut opt = RiscVPeepholeOptimizer::new(true);
        opt.eliminate_nop_moves(&mut instrs);
        assert_eq!(instrs.len(), 0);
    }

    #[test]
    fn test_eliminate_self_mv() {
        // ADDI x5, x5, 0 → eliminated (self-move)
        let mut instrs = vec![mi(
            RiscVOpcode::ADDI as u32,
            vec![reg(3005), reg(3005), imm(0)],
        )];
        let mut opt = RiscVPeepholeOptimizer::new(true);
        opt.eliminate_nop_moves(&mut instrs);
        assert_eq!(instrs.len(), 0);
    }

    #[test]
    fn test_recognize_mv() {
        // ADDI x5, x10, 0 → MV x5, x10
        let mut instrs = vec![mi(
            RiscVOpcode::ADDI as u32,
            vec![reg(3005), reg(3010), imm(0)],
        )];
        let mut opt = RiscVPeepholeOptimizer::new(true);
        opt.recognize_canonical_pseudos(&mut instrs);
        assert_eq!(instrs[0].opcode, RiscVOpcode::MV as u32);
        assert_eq!(opt.stats.canonical_pseudos_recognized, 1);
    }

    #[test]
    fn test_recognize_neg() {
        // SUB x5, x0, x10 → NEG x5, x10
        let mut instrs = vec![mi(
            RiscVOpcode::SUB as u32,
            vec![reg(3005), reg(3000), reg(3010)],
        )];
        let mut opt = RiscVPeepholeOptimizer::new(true);
        opt.recognize_canonical_pseudos(&mut instrs);
        assert_eq!(instrs[0].opcode, RiscVOpcode::NEG as u32);
    }

    #[test]
    fn test_recognize_not() {
        // XORI x5, x10, -1 → NOT x5, x10
        let mut instrs = vec![mi(
            RiscVOpcode::XORI as u32,
            vec![reg(3005), reg(3010), imm(-1)],
        )];
        let mut opt = RiscVPeepholeOptimizer::new(true);
        opt.fold_redundant_ops(&mut instrs);
        assert_eq!(instrs[0].opcode, RiscVOpcode::NOT as u32);
        assert_eq!(opt.stats.canonical_pseudos_recognized, 1);
    }

    #[test]
    fn test_fuse_lui_addi() {
        // LUI x5, 0x12345000; ADDI x5, x5, 0x678 → LI x5, 0x12345678
        let mut instrs = vec![
            mi(
                RiscVOpcode::LUI as u32,
                vec![reg(3005), imm(0x12345000u32 as i32)],
            ),
            mi(
                RiscVOpcode::ADDI as u32,
                vec![reg(3005), reg(3005), imm(0x678)],
            ),
        ];
        let mut opt = RiscVPeepholeOptimizer::new(true);
        opt.fuse_lui_addi(&mut instrs);
        assert_eq!(instrs.len(), 1);
        assert_eq!(instrs[0].opcode, RiscVOpcode::LI as u32);
        assert_eq!(opt.stats.lui_addi_fusions, 1);
    }

    #[test]
    fn test_invert_branch_over_jump() {
        // BEQ x10, x11, L1; J target → BNE x10, x11, target
        let mut instrs = vec![
            mi(RiscVOpcode::BEQ as u32, vec![reg(3010), reg(3011), imm(4)]),
            mi(RiscVOpcode::J as u32, vec![imm(256)]),
        ];
        let mut opt = RiscVPeepholeOptimizer::new(true);
        opt.optimize_branch_chains(&mut instrs);
        assert_eq!(instrs.len(), 1);
        assert_eq!(instrs[0].opcode, RiscVOpcode::BNE as u32);
        assert_eq!(opt.stats.branch_chains_optimized, 1);
    }

    #[test]
    fn test_eliminate_zero_shift() {
        // SLLI x5, x10, 0 → MV x5, x10
        let mut instrs = vec![mi(
            RiscVOpcode::SLLI as u32,
            vec![reg(3005), reg(3010), imm(0)],
        )];
        let mut opt = RiscVPeepholeOptimizer::new(true);
        opt.eliminate_zero_shifts(&mut instrs);
        assert_eq!(instrs[0].opcode, RiscVOpcode::MV as u32);
        assert_eq!(opt.stats.zero_shifts_removed, 1);
    }

    #[test]
    fn test_redundant_move_elimination() {
        // MV x5, x10; MV x6, x10 → MV x5, x10; MV x6, x5
        let mut instrs = vec![
            mi(RiscVOpcode::MV as u32, vec![reg(3005), reg(3010)]),
            mi(RiscVOpcode::MV as u32, vec![reg(3006), reg(3010)]),
        ];
        let mut opt = RiscVPeepholeOptimizer::new(true);
        opt.eliminate_redundant_moves(&mut instrs);
        assert_eq!(instrs[1].operands[1], MachineOperand::Reg(3005));
        assert_eq!(opt.stats.redundant_moves_eliminated, 1);
    }

    #[test]
    fn test_dead_add_elimination() {
        // ADDI x0, x0, 0 → removed (writes to x0, always dead)
        let mut instrs = vec![mi(
            RiscVOpcode::ADDI as u32,
            vec![reg(3000), reg(3000), imm(0)],
        )];
        let mut opt = RiscVPeepholeOptimizer::new(true);
        opt.eliminate_dead_adds(&mut instrs);
        assert_eq!(instrs.len(), 0);
        assert_eq!(opt.stats.dead_adds_eliminated, 1);
    }

    #[test]
    fn test_stats_total_removed() {
        let mut stats = RiscVOptStats::new();
        stats.total_instructions_before = 10;
        stats.total_instructions_after = 7;
        assert_eq!(stats.total_removed(), 3);
    }

    #[test]
    fn test_no_fuse_different_rd() {
        // LUI x5, X; ADDI x6, x5, Y → should NOT fuse (different rd)
        let mut instrs = vec![
            mi(RiscVOpcode::LUI as u32, vec![reg(3005), imm(0x1000)]),
            mi(RiscVOpcode::ADDI as u32, vec![reg(3006), reg(3005), imm(4)]),
        ];
        let mut opt = RiscVPeepholeOptimizer::new(true);
        opt.fuse_lui_addi(&mut instrs);
        assert_eq!(instrs.len(), 2); // unchanged
        assert_eq!(opt.stats.lui_addi_fusions, 0);
    }

    #[test]
    fn test_invert_branch_all_pairs() {
        // Verify all branch inversions produce the expected result
        let pairs = vec![
            (RiscVOpcode::BEQ, RiscVOpcode::BNE),
            (RiscVOpcode::BNE, RiscVOpcode::BEQ),
            (RiscVOpcode::BLT, RiscVOpcode::BGE),
            (RiscVOpcode::BGE, RiscVOpcode::BLT),
            (RiscVOpcode::BLTU, RiscVOpcode::BGEU),
            (RiscVOpcode::BGEU, RiscVOpcode::BLTU),
        ];
        for (orig, expected) in pairs {
            assert_eq!(invert_branch_op(orig as u32), Some(expected as u32));
        }
    }

    #[test]
    fn test_c_mv_to_c_li() {
        // C.MV rd, x0 → C.LI rd, 0 — verify ord detection via rd==rs && imm==0
        // This is tested through ADDI rd, rs, 0 where rd == rs (eliminated as self-move)
        let mut instrs = vec![mi(
            RiscVOpcode::SLLI as u32,
            vec![reg(3005), reg(3005), imm(0)],
        )];
        let mut opt = RiscVPeepholeOptimizer::new(true);
        opt.eliminate_nop_moves(&mut instrs);
        assert_eq!(instrs.len(), 0); // SLLI rd, rd, 0 eliminated
        assert_eq!(opt.stats.nops_eliminated, 1);
    }
}