vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! How many bits the values of the IR fit in.

use std::collections::HashMap;

use vlk_ir::ir::{BinOp, Expr, FunctionIr, Operation, Stmt};

/// The bits each variable's values fit in, from what is assigned to it:
/// the least such widths that hold for every assignment.
pub fn value_bits(ir: &FunctionIr) -> HashMap<u16, u32> {
    let variable = |index: u16| (vlk_ir::ir::TEMP_BASE..vlk_ir::ir::VALUE_BASE).contains(&index);
    let mut known: HashMap<u16, u32> = HashMap::new();
    let mut assigned = Vec::new();
    for stmt in ir.blocks.iter().flat_map(|block| &block.stmts) {
        match stmt {
            Stmt::Assign { dest, value, .. } if variable(dest.index) => {
                known.entry(dest.index).or_insert(0);
                assigned.push((dest.index, value));
            }
            Stmt::Call { .. } => {
                for output in stmt.call_outputs() {
                    let bits = known.entry(output.dest.index).or_insert(0);
                    *bits = (*bits).max(u32::from(output.dest.width));
                }
            }
            _ => {}
        }
    }
    // Each round widens what an assignment shows to be wider, until none
    // does. A value that keeps growing, as a counter does a bit a round,
    // grows to the next width of an integer type at once.
    let mut grown: HashMap<u16, u32> = HashMap::new();
    for _ in 0..=64 {
        let mut changed = false;
        for (index, value) in &assigned {
            let mut bits = value_width_in(value, &known).min(range_bits(value, &known));
            let entry = known.entry(*index).or_insert(0);
            if bits > *entry {
                let times = grown.entry(*index).or_insert(0);
                *times += 1;
                if *times > 2 {
                    bits = [8, 16, 32, 64]
                        .into_iter()
                        .find(|width| *width >= bits)
                        .unwrap_or(64);
                }
                *entry = bits;
                changed = true;
            }
        }
        if !changed {
            return known;
        }
    }
    for bits in known.values_mut() {
        *bits = 64;
    }
    known
}

/// The bits the value of `expr` fits in as the value ranges bound it, each
/// register within the bits `known` gives it.
fn range_bits(expr: &Expr, known: &HashMap<u16, u32>) -> u32 {
    let read = |index: u16, width: u32| {
        Some(crate::ssa::ranges::Fact::width(
            width.min(known.get(&index).copied().unwrap_or(64)),
        ))
    };
    crate::ssa::ranges::expression(expr, &read).map_or(64, |fact| 64 - fact.hi.leading_zeros())
}

pub fn value_width_in(expr: &Expr, known: &HashMap<u16, u32>) -> u32 {
    let bits = |expr| value_width_in(expr, known);
    match expr {
        Expr::Reg { index, width } => {
            u32::from(*width).min(known.get(index).copied().unwrap_or(64))
        }
        Expr::Const(value) => 64 - value.leading_zeros(),
        Expr::Load { width, signed, .. } => {
            if *signed {
                64
            } else {
                u32::from(*width) * 8
            }
        }
        Expr::SignExtend { value, width } => {
            let zero = bits(value);
            if zero < u32::from(*width) * 8 {
                zero
            } else {
                64
            }
        }
        Expr::Bin { op, lhs, rhs } => match op {
            BinOp::And => bits(lhs).min(bits(rhs)),
            BinOp::Or | BinOp::Xor => bits(lhs).max(bits(rhs)),
            BinOp::Add => (bits(lhs).max(bits(rhs)) + 1).min(64),
            BinOp::Mul => (bits(lhs) + bits(rhs)).min(64),
            BinOp::Shl => match rhs.as_ref() {
                Expr::Const(amount) => (bits(lhs) + (amount & 63) as u32).min(64),
                _ => 64,
            },
            BinOp::Shr => match rhs.as_ref() {
                Expr::Const(amount) => bits(lhs).saturating_sub((amount & 63) as u32),
                _ => bits(lhs),
            },
            BinOp::DivU => bits(lhs),
            BinOp::ModU => bits(lhs).min(bits(rhs)),
            // The IR keeps the signed result to the operands' width.
            BinOp::Sar | BinOp::DivS | BinOp::ModS => {
                vlk_ir::ir::semantics::operand_width(lhs, rhs)
            }
            BinOp::Sub | BinOp::MulHigh | BinOp::MulHighS => 64,
        },
        Expr::Select { then, els, .. } => bits(then).max(bits(els)),
        Expr::Apply { op, .. } => match op {
            Operation::CountLeadingZeros(_)
            | Operation::CountTrailingZeros(_)
            | Operation::PopCount(_)
            | Operation::ReverseBits(_)
            | Operation::Crc32 { .. } => vlk_ir::ir::semantics::width(expr),
            _ => 64,
        },
    }
}

/// The width the IR's value of `expr` is sign-extended from, when it is.
pub fn sign_bits(expr: &Expr) -> Option<u32> {
    match expr {
        Expr::SignExtend { width, .. }
        | Expr::Load {
            width,
            signed: true,
            ..
        } => Some(u32::from(*width) * 8),
        _ => None,
    }
}