lamina 0.0.10

High-performance compiler backend for Lamina Intermediate Representation
Documentation
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
//! Dead code elimination transform for MIR.

use super::super::{Block, Function, Instruction, Register};
use super::{Transform, TransformCategory, TransformLevel};
use std::collections::{HashMap, HashSet};

/// Statistics about dead code elimination
#[derive(Debug, Default)]
pub struct DeadCodeStats {
    /// Number of instructions removed
    pub instructions_removed: usize,
    /// Number of registers that became dead
    pub registers_freed: usize,
}

/// Dead Code Elimination transform
#[derive(Default)]
pub struct DeadCodeElimination;

impl Transform for DeadCodeElimination {
    fn name(&self) -> &'static str {
        "dead_code_elimination"
    }

    fn description(&self) -> &'static str {
        "Removes instructions that define registers which are never used"
    }

    fn category(&self) -> TransformCategory {
        TransformCategory::DeadCodeElimination
    }

    fn level(&self) -> TransformLevel {
        TransformLevel::Stable
    }

    fn apply(&self, func: &mut Function) -> Result<bool, String> {
        self.apply_internal(func)
            .map(|stats| stats.instructions_removed > 0)
    }
}

impl DeadCodeElimination {
    /// Apply dead code elimination to a function
    pub fn apply_internal(&self, func: &mut Function) -> Result<DeadCodeStats, String> {
        let mut stats = DeadCodeStats::default();

        // 1. Compute liveness analysis (inter-block)
        let live_out_map = self.compute_liveness(func)?;

        // 2. Remove dead instructions using liveness info
        for block in &mut func.blocks {
            // Start with registers live at the end of the block
            let mut live_regs = live_out_map.get(&block.label).cloned().unwrap_or_default();

            let removed = self.remove_dead_instructions_in_block(block, &mut live_regs);
            stats.instructions_removed += removed;
        }

        Ok(stats)
    }

    /// Compute liveness analysis (live-out sets for each block)
    fn compute_liveness(
        &self,
        func: &Function,
    ) -> Result<HashMap<String, HashSet<Register>>, String> {
        let mut live_in: HashMap<String, HashSet<Register>> = HashMap::new();
        let mut live_out: HashMap<String, HashSet<Register>> = HashMap::new();

        // Initialize sets
        for block in &func.blocks {
            live_in.insert(block.label.clone(), HashSet::new());
            live_out.insert(block.label.clone(), HashSet::new());
        }

        let mut changed = true;
        let mut iterations = 0;
        const MAX_ITERATIONS: usize = 1000;

        while changed {
            if iterations > MAX_ITERATIONS {
                return Err("Liveness analysis failed to converge".to_string());
            }
            iterations += 1;
            changed = false;

            // Process blocks in reverse order (heuristic for faster convergence)
            for block in func.blocks.iter().rev() {
                let label = &block.label;

                // 1. Calculate LiveOut = Union(LiveIn(successors))
                let mut current_live_out = HashSet::new();
                if let Some(terminator) = block.instructions.last() {
                    match terminator {
                        Instruction::Jmp { target } => {
                            if let Some(succ_live_in) = live_in.get(target) {
                                current_live_out.extend(succ_live_in.iter().cloned());
                            }
                        }
                        Instruction::Br {
                            true_target,
                            false_target,
                            ..
                        } => {
                            if let Some(succ_live_in) = live_in.get(true_target) {
                                current_live_out.extend(succ_live_in.iter().cloned());
                            }
                            if let Some(succ_live_in) = live_in.get(false_target) {
                                current_live_out.extend(succ_live_in.iter().cloned());
                            }
                        }
                        Instruction::Switch { cases, default, .. } => {
                            if let Some(succ_live_in) = live_in.get(default) {
                                current_live_out.extend(succ_live_in.iter().cloned());
                            }
                            for (_, case_target) in cases {
                                if let Some(succ_live_in) = live_in.get(case_target) {
                                    current_live_out.extend(succ_live_in.iter().cloned());
                                }
                            }
                        }
                        _ => {} // Return or others have no successors within function
                    }
                }

                // Safe: live_out is initialized for all blocks at function start
                // If this fails, it indicates a bug in the initialization logic
                let prev_live_out = live_out.get(label)
                    .ok_or_else(|| format!("Block '{}' not found in live_out map - internal error in liveness analysis", label))?;
                if current_live_out != *prev_live_out {
                    live_out.insert(label.clone(), current_live_out.clone());
                    changed = true;
                }

                // 2. Calculate LiveIn = Use U (LiveOut - Def)
                let mut current_live_in = current_live_out.clone();
                // Iterate backwards through instructions
                for instr in block.instructions.iter().rev() {
                    if let Some(def) = instr.def_reg() {
                        current_live_in.remove(def);
                    }
                    for use_reg in instr.use_regs() {
                        current_live_in.insert(use_reg.clone());
                    }
                }

                // Safe: live_in is initialized for all blocks at function start
                // If this fails, it indicates a bug in the initialization logic
                let prev_live_in = live_in.get(label).ok_or_else(|| {
                    format!(
                        "Block '{}' not found in live_in map - internal error in liveness analysis",
                        label
                    )
                })?;
                if current_live_in != *prev_live_in {
                    live_in.insert(label.clone(), current_live_in);
                    changed = true;
                }
            }
        }

        Ok(live_out)
    }

    /// Remove dead instructions within a single basic block
    fn remove_dead_instructions_in_block(
        &self,
        block: &mut Block,
        live_regs: &mut HashSet<Register>,
    ) -> usize {
        let mut removed_count = 0;
        let mut instructions_to_keep = Vec::new();

        // Iterate backwards
        // We collect instructions to keep, then reverse them back
        for instr in block.instructions.iter().rev() {
            if self.is_dead_instruction(instr, live_regs) {
                removed_count += 1;
                // Don't add to keep list
            } else {
                instructions_to_keep.push(instr.clone());

                // Update liveness for the kept instruction
                if let Some(def_reg) = instr.def_reg() {
                    live_regs.remove(def_reg);
                }
                for use_reg in instr.use_regs() {
                    live_regs.insert(use_reg.clone());
                }
            }
        }

        if removed_count > 0 {
            instructions_to_keep.reverse();
            block.instructions = instructions_to_keep;
        }

        removed_count
    }

    /// Check if an instruction is dead and can be safely removed
    fn is_dead_instruction(&self, instr: &Instruction, live_regs: &HashSet<Register>) -> bool {
        // Never remove terminators
        if instr.is_terminator() {
            return false;
        }

        // Check if instruction defines a register
        if let Some(def_reg) = instr.def_reg() {
            // If the defined register is not live, instruction is dead
            if !live_regs.contains(def_reg) {
                // Additional check: ensure instruction has no side effects
                return self.has_no_side_effects(instr);
            }
        } else {
            // Instructions that don't define a register are usually for side effects (e.g. stores)
            // But some might be useless?
            // Assuming has_no_side_effects check covers it.
            return self.has_no_side_effects(instr);
        }

        false
    }

    /// Check if an instruction has no side effects and can be safely removed
    fn has_no_side_effects(&self, instr: &Instruction) -> bool {
        match instr {
            // Pure arithmetic operations - safe to remove
            Instruction::IntBinary { .. }
            | Instruction::FloatBinary { .. }
            | Instruction::FloatUnary { .. }
            | Instruction::IntCmp { .. }
            | Instruction::FloatCmp { .. }
            | Instruction::Select { .. }
            | Instruction::VectorOp { .. }
            | Instruction::Lea { .. } => true,

            // SIMD register-only ops are also pure (nightly only)
            #[cfg(feature = "nightly")]
            Instruction::SimdBinary { .. }
            | Instruction::SimdUnary { .. }
            | Instruction::SimdTernary { .. }
            | Instruction::SimdShuffle { .. }
            | Instruction::SimdExtract { .. }
            | Instruction::SimdInsert { .. } => true,

            // Instructions with side effects - never remove
            Instruction::Load { .. } // Reads memory (could fault)
            | Instruction::Store { .. }
            | Instruction::Call { .. }
            | Instruction::TailCall { .. }
            | Instruction::Ret { .. }
            | Instruction::Jmp { .. }
            | Instruction::Br { .. }
            | Instruction::Switch { .. }
            | Instruction::Unreachable
            | Instruction::SafePoint
            | Instruction::StackMap { .. }
            | Instruction::PatchPoint { .. }
            | Instruction::Comment { .. } => false,

            // SIMD memory and atomic operations have side effects (nightly only)
            #[cfg(feature = "nightly")]
            Instruction::SimdLoad { .. }
            | Instruction::SimdStore { .. }
            | Instruction::AtomicLoad { .. }
            | Instruction::AtomicStore { .. }
            | Instruction::AtomicBinary { .. }
            | Instruction::AtomicCompareExchange { .. }
            | Instruction::Fence { .. } => false,
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;
    use crate::mir::{
        FunctionBuilder, Immediate, IntBinOp, MirType, Operand, ScalarType, VirtualReg,
    };

    #[test]
    fn test_dead_code_elimination_basic() {
        // Create a function with dead instructions
        let func = FunctionBuilder::new("test")
            .param(VirtualReg::gpr(0).into(), MirType::Scalar(ScalarType::I64))
            .returns(MirType::Scalar(ScalarType::I64))
            .block("entry")
            // Dead instruction: v1 = v0 + 42 (v1 never used)
            .instr(Instruction::IntBinary {
                op: IntBinOp::Add,
                ty: MirType::Scalar(ScalarType::I64),
                dst: VirtualReg::gpr(1).into(),
                lhs: Operand::Register(VirtualReg::gpr(0).into()),
                rhs: Operand::Immediate(Immediate::I64(42)),
            })
            // Live instruction: v2 = v0 + 10 (v2 used in ret)
            .instr(Instruction::IntBinary {
                op: IntBinOp::Add,
                ty: MirType::Scalar(ScalarType::I64),
                dst: VirtualReg::gpr(2).into(),
                lhs: Operand::Register(VirtualReg::gpr(0).into()),
                rhs: Operand::Immediate(Immediate::I64(10)),
            })
            .instr(Instruction::Ret {
                value: Some(Operand::Register(VirtualReg::gpr(2).into())),
            })
            .build();

        let mut func = func;
        let dce = DeadCodeElimination;

        let changed = dce.apply(&mut func).expect("DCE should succeed");

        assert!(changed);

        let entry = func.get_block("entry").expect("entry block exists");
        // Original: 3 instructions. Dead removed -> 2 remaining.
        assert_eq!(entry.instructions.len(), 2);

        // Verify content
        // First instr should be the live add
        match &entry.instructions[0] {
            Instruction::IntBinary { dst, .. } => {
                assert_eq!(dst, &VirtualReg::gpr(2).into());
            }
            _ => panic!("Expected IntBinary"),
        }
    }

    #[test]
    fn test_dce_empty_function() {
        // Test with empty function - should not panic
        let mut func = FunctionBuilder::new("empty")
            .returns(MirType::Scalar(ScalarType::I64))
            .block("entry")
            .instr(Instruction::Ret { value: None })
            .build();

        let dce = DeadCodeElimination;
        let result = dce.apply(&mut func);
        assert!(result.is_ok());
        assert!(!result.unwrap()); // No changes expected
    }

    #[test]
    fn test_dce_single_block_all_live() {
        // All instructions are live - nothing should be removed
        let mut func = FunctionBuilder::new("all_live")
            .param(VirtualReg::gpr(0).into(), MirType::Scalar(ScalarType::I64))
            .returns(MirType::Scalar(ScalarType::I64))
            .block("entry")
            .instr(Instruction::IntBinary {
                op: IntBinOp::Add,
                ty: MirType::Scalar(ScalarType::I64),
                dst: VirtualReg::gpr(1).into(),
                lhs: Operand::Register(VirtualReg::gpr(0).into()),
                rhs: Operand::Immediate(Immediate::I64(1)),
            })
            .instr(Instruction::Ret {
                value: Some(Operand::Register(VirtualReg::gpr(1).into())),
            })
            .build();

        let dce = DeadCodeElimination;
        let changed = dce.apply(&mut func).expect("should succeed");
        assert!(!changed);
        assert_eq!(func.blocks[0].instructions.len(), 2);
    }

    #[test]
    fn test_dce_preserves_terminators() {
        // Terminators must never be removed even if they define no live registers
        let mut func = FunctionBuilder::new("terminators")
            .returns(MirType::Scalar(ScalarType::I64))
            .block("entry")
            .instr(Instruction::Jmp {
                target: "exit".to_string(),
            })
            .block("exit")
            .instr(Instruction::Ret { value: None })
            .build();

        let dce = DeadCodeElimination;
        let result = dce.apply(&mut func);
        assert!(result.is_ok());

        // Jmp and Ret should still exist
        let entry = func.get_block("entry").unwrap();
        assert!(matches!(
            entry.instructions.last(),
            Some(Instruction::Jmp { .. })
        ));
    }

    #[test]
    fn test_dce_preserves_side_effects() {
        // Store and Call have side effects - must not be removed
        let mut func = FunctionBuilder::new("side_effects")
            .returns(MirType::Scalar(ScalarType::I64))
            .block("entry")
            .instr(Instruction::Store {
                ty: MirType::Scalar(ScalarType::I64),
                src: Operand::Immediate(Immediate::I64(42)),
                addr: crate::mir::AddressMode::BaseOffset {
                    base: VirtualReg::gpr(0).into(),
                    offset: 0,
                },
                attrs: crate::mir::MemoryAttrs::default(),
            })
            .instr(Instruction::Call {
                name: "print".to_string(),
                args: vec![Operand::Immediate(Immediate::I64(1))],
                ret: None,
            })
            .instr(Instruction::Ret {
                value: Some(Operand::Immediate(Immediate::I64(0))),
            })
            .build();

        let dce = DeadCodeElimination;
        let changed = dce.apply(&mut func).expect("should succeed");

        // Store and Call should remain
        assert!(!changed);
        assert_eq!(func.blocks[0].instructions.len(), 3);
    }

    #[test]
    fn test_dce_chain_of_dead_instructions() {
        // Chain of dead instructions: v1 = f(v0), v2 = f(v1), v3 = f(v2)
        // None used in return
        let mut func = FunctionBuilder::new("dead_chain")
            .param(VirtualReg::gpr(0).into(), MirType::Scalar(ScalarType::I64))
            .returns(MirType::Scalar(ScalarType::I64))
            .block("entry")
            .instr(Instruction::IntBinary {
                op: IntBinOp::Add,
                ty: MirType::Scalar(ScalarType::I64),
                dst: VirtualReg::gpr(1).into(),
                lhs: Operand::Register(VirtualReg::gpr(0).into()),
                rhs: Operand::Immediate(Immediate::I64(1)),
            })
            .instr(Instruction::IntBinary {
                op: IntBinOp::Add,
                ty: MirType::Scalar(ScalarType::I64),
                dst: VirtualReg::gpr(2).into(),
                lhs: Operand::Register(VirtualReg::gpr(1).into()),
                rhs: Operand::Immediate(Immediate::I64(2)),
            })
            .instr(Instruction::IntBinary {
                op: IntBinOp::Add,
                ty: MirType::Scalar(ScalarType::I64),
                dst: VirtualReg::gpr(3).into(),
                lhs: Operand::Register(VirtualReg::gpr(2).into()),
                rhs: Operand::Immediate(Immediate::I64(3)),
            })
            .instr(Instruction::Ret {
                value: Some(Operand::Immediate(Immediate::I64(99))),
            })
            .build();

        let dce = DeadCodeElimination;
        let changed = dce.apply(&mut func).expect("should succeed");
        assert!(changed);
        // Only return should remain
        assert_eq!(func.blocks[0].instructions.len(), 1);
    }

    #[test]
    fn test_dce_multi_block_liveness() {
        // Value defined in entry, used in exit block
        let mut func = FunctionBuilder::new("multi_block")
            .param(VirtualReg::gpr(0).into(), MirType::Scalar(ScalarType::I64))
            .returns(MirType::Scalar(ScalarType::I64))
            .block("entry")
            .instr(Instruction::IntBinary {
                op: IntBinOp::Add,
                ty: MirType::Scalar(ScalarType::I64),
                dst: VirtualReg::gpr(1).into(),
                lhs: Operand::Register(VirtualReg::gpr(0).into()),
                rhs: Operand::Immediate(Immediate::I64(10)),
            })
            .instr(Instruction::Jmp {
                target: "exit".to_string(),
            })
            .block("exit")
            .instr(Instruction::Ret {
                value: Some(Operand::Register(VirtualReg::gpr(1).into())),
            })
            .build();

        let dce = DeadCodeElimination;
        let changed = dce.apply(&mut func).expect("should succeed");

        // v1 is used in exit block, so entry's add should remain
        assert!(!changed);
        let entry = func.get_block("entry").unwrap();
        assert_eq!(entry.instructions.len(), 2);
    }

    #[test]
    fn test_dce_loop_back_edge_liveness() {
        // Test liveness across loop back-edge
        // v0 defined in entry, used in loop, loop branches back
        let mut func = FunctionBuilder::new("loop_liveness")
            .param(VirtualReg::gpr(0).into(), MirType::Scalar(ScalarType::I64))
            .returns(MirType::Scalar(ScalarType::I64))
            .block("entry")
            .instr(Instruction::Jmp {
                target: "loop".to_string(),
            })
            .block("loop")
            .instr(Instruction::IntBinary {
                op: IntBinOp::Add,
                ty: MirType::Scalar(ScalarType::I64),
                dst: VirtualReg::gpr(0).into(),
                lhs: Operand::Register(VirtualReg::gpr(0).into()),
                rhs: Operand::Immediate(Immediate::I64(1)),
            })
            .instr(Instruction::Br {
                cond: VirtualReg::gpr(0).into(),
                true_target: "loop".to_string(),
                false_target: "exit".to_string(),
            })
            .block("exit")
            .instr(Instruction::Ret {
                value: Some(Operand::Register(VirtualReg::gpr(0).into())),
            })
            .build();

        let dce = DeadCodeElimination;
        let result = dce.apply(&mut func);
        assert!(result.is_ok());

        // Loop body should be preserved (v0 is used)
        let loop_block = func.get_block("loop").unwrap();
        assert_eq!(loop_block.instructions.len(), 2);
    }

    #[test]
    fn test_dce_does_not_infinite_loop() {
        // Stress test: large function should not cause infinite loop
        let mut func = FunctionBuilder::new("stress")
            .returns(MirType::Scalar(ScalarType::I64))
            .block("entry")
            .build();

        // Add 500 dead instructions
        for i in 0..500 {
            func.blocks[0].instructions.insert(
                0,
                Instruction::IntBinary {
                    op: IntBinOp::Add,
                    ty: MirType::Scalar(ScalarType::I64),
                    dst: VirtualReg::gpr(i + 1).into(),
                    lhs: Operand::Immediate(Immediate::I64(i as i64)),
                    rhs: Operand::Immediate(Immediate::I64(1)),
                },
            );
        }
        func.blocks[0].instructions.push(Instruction::Ret {
            value: Some(Operand::Immediate(Immediate::I64(0))),
        });

        let dce = DeadCodeElimination;
        let result = dce.apply(&mut func);
        assert!(result.is_ok());
        // All dead instructions should be removed, only ret remains
        assert_eq!(func.blocks[0].instructions.len(), 1);
    }
}