vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! Registers MIPS code reads after a call.

use std::collections::HashSet;

/// Takes a call to leave alone the argument and temporary registers the
/// code reads after it before writing them.
///
/// The convention lets a callee change those registers, and none of them
/// returns a value. Compiled code reads one after a call only where the
/// compiler knows the callee and that it leaves the register as it was,
/// which it does for the functions of its own module. Here the callee of
/// a call through a pointer is not known, and the summary of a known one
/// may say more than the compiler found, as when it calls through a
/// pointer itself; the read says what the compiler knew.
pub(super) fn keep_registers_read_after_calls(blocks: &mut [vlk_ir::ir::Block]) {
    use vlk_ir::ir::Stmt;
    use vlk_types::types::{CallKind, Convention, Registers};
    // a0 to a3, t0 to t9 and at.
    let candidates: Registers = (2..=15).chain([24]).collect();
    let unknown = |stmt: &Stmt| {
        matches!(
            stmt,
            Stmt::Call {
                kind: CallKind::Invoke,
                convention: Convention::O32,
                ..
            }
        ) && !stmt.has_declared_call()
    };
    if !blocks.iter().flat_map(|block| &block.stmts).any(unknown) {
        return;
    }
    // The candidates a statement reads, other than as what a call or a
    // return passes on, and those it writes.
    let reads = |stmt: &Stmt| -> Registers {
        if matches!(stmt, Stmt::Call { .. } | Stmt::Ret { .. }) {
            return Registers::default();
        }
        let mut read = HashSet::new();
        for operand in stmt.operands() {
            vlk_ir::ir::visit::collect_reads(operand, &mut read);
        }
        read.into_iter()
            .filter(|register| candidates.contains(*register))
            .collect()
    };
    let writes = |stmt: &Stmt| -> Registers {
        vlk_ir::ir::visit::statement_registers(stmt)
            .0
            .into_iter()
            .filter(|register| candidates.contains(*register))
            .collect()
    };
    // The registers read before they are written from `position` on in
    // a block, given those read after it.
    let live_from = |block: &vlk_ir::ir::Block, position: usize, after: Registers| {
        let mut live = after;
        for stmt in block.stmts[position..].iter().rev() {
            live = Registers(live.0 & !writes(stmt).0 | reads(stmt).0);
        }
        live
    };
    let successors: Vec<Vec<usize>> = (0..blocks.len())
        .map(|index| vlk_ir::ir::cfg::block_successors(blocks, index))
        .collect();
    // A call that keeps a register lets a read after it reach the calls
    // before it: once more for each call found to keep one.
    while {
        let mut entering = vec![Registers::default(); blocks.len()];
        loop {
            let mut changed = false;
            for index in (0..blocks.len()).rev() {
                let after = successors[index]
                    .iter()
                    .fold(Registers::default(), |all, next| {
                        Registers(all.0 | entering[*next].0)
                    });
                let live = live_from(&blocks[index], 0, after);
                if live != entering[index] {
                    entering[index] = live;
                    changed = true;
                }
            }
            if !changed {
                break;
            }
        }
        let mut found = false;
        for index in 0..blocks.len() {
            let after = successors[index]
                .iter()
                .fold(Registers::default(), |all, next| {
                    Registers(all.0 | entering[*next].0)
                });
            for position in 0..blocks[index].stmts.len() {
                if !unknown(&blocks[index].stmts[position]) {
                    continue;
                }
                let kept = live_from(&blocks[index], position + 1, after);
                if kept.0 == 0 {
                    continue;
                }
                if let Stmt::Call {
                    convention,
                    clobbers,
                    ..
                } = &mut blocks[index].stmts[position]
                {
                    let changed: Registers =
                        convention.clobbered_by(*clobbers).into_iter().collect();
                    if changed.0 & kept.0 != 0 {
                        *clobbers = Some(Registers(changed.0 & !kept.0));
                        found = true;
                    }
                }
            }
        }
        found
    } {}
}