vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! Removal of blocks no path reaches and of reads nothing uses.

use std::collections::HashSet;

use vlk_ir::ir::{FunctionIr, Stmt};
use vlk_loader::loader::Image;

/// Drops the blocks no path from the entry reaches, unless an indirect jump
/// may reach any of them.
pub(super) fn drop_unreached(blocks: &mut Vec<vlk_ir::ir::Block>) {
    use vlk_ir::ir::Stmt;
    if blocks.iter().any(|block| {
        matches!(
            block.stmts.last(),
            Some(Stmt::BrIndirect { .. } | Stmt::Br { target: None, .. })
        )
    }) {
        return;
    }
    let index: std::collections::HashMap<u64, usize> = blocks
        .iter()
        .enumerate()
        .map(|(position, block)| (block.start, position))
        .collect();
    let mut seen = vec![false; blocks.len()];
    let mut pending = vec![0];
    while let Some(at) = pending.pop() {
        if at >= blocks.len() || std::mem::replace(&mut seen[at], true) {
            continue;
        }
        pending.extend(vlk_ir::ir::cfg::normal_successors(
            blocks[at].stmts.last(),
            (at + 1 < blocks.len()).then_some(at + 1),
            |address| index.get(&address).copied(),
            vlk_ir::ir::cfg::UnknownBranch::Fallthrough,
        ));
    }
    let mut position = 0;
    blocks.retain(|_| {
        position += 1;
        seen[position - 1]
    });
}

/// Drops the blocks of `reached`, those a path reached before optimizing,
/// that none does now: a branch folded to one way leaves the other dead.
/// Code no path reached to begin with, as a landing pad's the unwind
/// tables do not lead to, stays.
pub(super) fn drop_folded_away(ir: &mut FunctionIr, reached: &HashSet<u64>) {
    if ir
        .blocks
        .iter()
        .any(|block| matches!(block.stmts.last(), Some(Stmt::BrIndirect { .. })))
    {
        return;
    }
    let now = vlk_ir::ir::cfg::reached(ir);
    ir.blocks
        .retain(|block| now.contains(&block.start) || !reached.contains(&block.start));
}

/// Drops a value nothing reads that loads only from memory the program
/// cannot change, such as the jump table entry a switch no longer needs:
/// code, or constant data, at addresses that may take an index read from
/// the function's own frame. Other loads may touch a device and stay.
pub(super) fn drop_dead_constant_reads(ir: &mut FunctionIr, image: &Image) {
    use vlk_ir::ir::Expr;
    let constant = |address: u64| {
        image.section_at(address).is_some_and(|section| {
            section.executable
                || section.read_only
                || section.name.contains("rodata")
                || section.name.contains("rel.ro")
                || section.name.contains("__const")
        })
    };
    // Every load reads at a constant base inside such memory, plus offsets,
    // or in the function's own frame, as an index spilled there.
    let sp = vlk_arch::arch::stack_pointer(ir.isa);
    fn constant_loads(expr: &Expr, constant: &dyn Fn(u64) -> bool, sp: u16) -> bool {
        match expr {
            Expr::Load { addr, .. } => {
                let mut base = None;
                let mut frame = false;
                let mut indexed = false;
                let mut terms = vec![addr.as_ref()];
                while let Some(term) = terms.pop() {
                    match term {
                        Expr::Bin {
                            op: vlk_ir::ir::BinOp::Add,
                            lhs,
                            rhs,
                        } => terms.extend([lhs.as_ref(), rhs.as_ref()]),
                        Expr::Const(value) => base = Some(*value),
                        Expr::Reg { index, .. } if *index == sp => frame = true,
                        other if !constant_loads(other, constant, sp) => return false,
                        _ => indexed = true,
                    }
                }
                match (frame, base) {
                    (true, offset) => {
                        !indexed && offset.is_none_or(|offset| (offset as i64).abs() < 0x1_0000)
                    }
                    (false, base) => base.is_some_and(constant),
                }
            }
            other => vlk_ir::ir::visit::children(other)
                .into_iter()
                .all(|child| constant_loads(child, constant, sp)),
        }
    }
    let live_in = vlk_ir::ir::cfg::live_in(ir);
    for index in 0..ir.blocks.len() {
        let mut live = vlk_ir::ir::cfg::live_out(ir, &live_in, index);
        let mut keep = vec![true; ir.blocks[index].stmts.len()];
        for (position, stmt) in ir.blocks[index].stmts.iter().enumerate().rev() {
            let (writes, reads) = vlk_ir::ir::visit::statement_registers(stmt);
            if let Stmt::Assign { dest, value, .. } = stmt
                && !live.contains(&dest.index)
                && constant_loads(value, &constant, sp)
            {
                keep[position] = false;
                continue;
            }
            for written in &writes {
                live.remove(written);
            }
            live.extend(reads);
        }
        let mut position = 0;
        ir.blocks[index].stmts.retain(|_| {
            position += 1;
            keep[position - 1]
        });
    }
}