vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! Results returned through a pointer the caller passes.

use std::collections::HashSet;

use vlk_ir::ir::{FunctionIr, Stmt};
use vlk_program::program::Program;

use super::summary;

/// A function returning a structure too large for registers writes it
/// through a pointer its caller passes first and returns that pointer: the
/// first parameter is the result, no parameter of the source.
pub(super) fn name_indirect_result(ir: &mut FunctionIr) {
    use vlk_ir::ir::Expr;
    use vlk_types::types::Convention;
    if ir.declared_signature.is_some() {
        return;
    }
    if !matches!(ir.convention, Convention::SysV | Convention::Win64) {
        return;
    }
    let first = ir.convention.arguments()[0];
    let Some(param) = ir.params.iter().position(|param| param.index == first) else {
        return;
    };
    let based = |addr: &Expr| match addr {
        Expr::Reg { index, .. } => *index == first,
        Expr::Bin { lhs, rhs, .. } => {
            matches!(lhs.as_ref(), Expr::Reg { index, .. } if *index == first)
                && matches!(rhs.as_ref(), Expr::Const(_))
        }
        _ => false,
    };
    let stmts = || ir.blocks.iter().flat_map(|block| &block.stmts);
    let returns_it = stmts()
        .filter_map(|stmt| match stmt {
            Stmt::Ret { value, .. } => Some(value),
            _ => None,
        })
        .all(|value| matches!(value, Expr::Reg { index, width: 64 } if *index == first));
    let writes_through =
        stmts().any(|stmt| matches!(stmt, Stmt::Store { addr, .. } if based(addr)));
    let returns = stmts().any(|stmt| matches!(stmt, Stmt::Ret { .. }));
    if returns && returns_it && writes_through {
        ir.params[param].name = "result".to_owned();
    }
}

/// Drops each value `AArch64` code leaves in x8, its indirect result
/// register, that no path reads before the register changes: a call reads
/// it unnamed only when its callee may return through memory, so a
/// compiler's scratch there, as a jump table's computed target, is dead
/// before calls of callees known to take no result address.
pub(super) fn drop_unread_indirect_result(ir: &mut FunctionIr, program: &Program) {
    const INDIRECT: u16 = 8;
    if ir.isa != vlk_base::target::Isa::AArch64 {
        return;
    }
    let reads = |expr: &vlk_ir::ir::Expr| {
        let mut read = HashSet::new();
        vlk_ir::ir::visit::collect_reads(expr, &mut read);
        read.contains(&INDIRECT)
    };
    // Whether x8's value is needed before the statement, given whether it
    // is after it. A call whose callee's summary takes no result address
    // reads it only where its expressions name it.
    let before = |stmt: &Stmt, after: bool| match stmt {
        _ if stmt.operands().into_iter().any(reads) => true,
        // A declared call reads x8 only for the result its declaration
        // returns through memory.
        Stmt::Call { abi: Some(_), .. } if !stmt.declared_call_reads().contains(&INDIRECT) => {
            after && !stmt.call_clobbers().contains(&INDIRECT)
        }
        Stmt::Call {
            target: Some(target),
            args: Some(_),
            abi: None,
            ..
        } if !summary::summary(program, *target).indirect_result => {
            after && !stmt.call_clobbers().contains(&INDIRECT)
        }
        _ => {
            let (writes, read) = vlk_ir::ir::visit::statement_registers(stmt);
            read.contains(&INDIRECT) || (after && !writes.contains(&INDIRECT))
        }
    };
    let count = ir.blocks.len();
    let successors: Vec<Vec<usize>> = (0..count)
        .map(|index| vlk_ir::ir::cfg::successors(ir, index))
        .collect();
    let out = |live: &[bool], index: usize| {
        vlk_ir::ir::cfg::opaque(&ir.blocks[index])
            || successors[index].iter().any(|next| live[*next])
    };
    let mut live = vec![false; count];
    loop {
        let mut changed = false;
        for index in (0..count).rev() {
            let entry = ir.blocks[index]
                .stmts
                .iter()
                .rev()
                .fold(out(&live, index), |after, stmt| before(stmt, after));
            if entry && !live[index] {
                live[index] = true;
                changed = true;
            }
        }
        if !changed {
            break;
        }
    }
    let outs: Vec<bool> = (0..count).map(|index| out(&live, index)).collect();
    for (block, mut after) in ir.blocks.iter_mut().zip(outs) {
        let mut dead = Vec::new();
        for (position, stmt) in block.stmts.iter().enumerate().rev() {
            if matches!(stmt, Stmt::Assign { dest, .. } if dest.index == INDIRECT) && !after {
                dead.push(position);
            }
            after = before(stmt, after);
        }
        for position in dead {
            block.stmts.remove(position);
        }
    }
}