vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! Variadic functions. Under `SysV` and `AArch64` a function taking further
//! arguments saves, on entry, every argument register past its named
//! parameters to a block of its frame, and the floating-point ones too
//! (`SysV` only when al says a vector register holds an argument), where
//! the code `va_arg` expands to finds them. Those registers are no
//! parameters, and the pseudo-C reads `...` for them instead of their saves.

use std::collections::HashSet;

use vlk_ir::ir::{BinOp, Cond, Expr, FunctionIr, Stmt};
use vlk_types::types::Convention;

/// Where a function saves the argument registers it does not name.
pub struct RegisterSaves {
    /// The integer argument registers past the named ones.
    pub unnamed: Vec<u16>,
    /// The statements saving them and the floating-point ones, by block and
    /// position.
    pub stores: Vec<(usize, usize)>,
    /// `SysV`'s branch around the floating-point saves when al is zero, at
    /// the end of the entry block.
    pub guard: bool,
}

/// The register saves of a variadic function's entry, when it has them.
pub fn register_saves(ir: &FunctionIr) -> Option<RegisterSaves> {
    if !matches!(ir.convention, Convention::SysV | Convention::Aapcs64) || ir.blocks.is_empty() {
        return None;
    }
    let sp = vlk_arch::arch::stack_pointer(ir.isa);
    let index = |start: u64| ir.blocks.iter().position(|block| block.start == start);
    // SysV skips the floating-point saves, which come next, when al is zero.
    let guard = match ir.blocks[0].stmts.last() {
        Some(Stmt::Brif {
            cond: Cond::Eq,
            lhs:
                Expr::Bin {
                    op: BinOp::And,
                    lhs,
                    rhs,
                },
            rhs: Expr::Const(0),
            target,
            ..
        }) if ir.convention == Convention::SysV
            && matches!(
                lhs.as_ref(),
                Expr::Reg {
                    index: vlk_arch::arch::RETURN,
                    ..
                }
            )
            && matches!(rhs.as_ref(), Expr::Const(0xff)) =>
        {
            let Some(slot) = index(*target) else {
                return None;
            };
            Some(slot)
        }
        _ => None,
    };
    if ir.convention == Convention::SysV && guard.is_none() {
        return None;
    }
    // The blocks the saves are in, entered one after another: the entry
    // block, then SysV's floating-point saves and the block both ways
    // through them reach.
    let float_saves_block = if guard.is_some() { 1 } else { 0 };
    let blocks: Vec<usize> = match guard {
        Some(2) => vec![0, 1, 2],
        Some(_) => return None,
        None => vec![0],
    };
    let mut stores: Vec<(usize, usize)> = Vec::new();
    // Each register saved before anything writes it, with the offset.
    let mut saved: Vec<(u16, u64)> = Vec::new();
    let mut written: HashSet<u16> = HashSet::new();
    for &block in &blocks {
        for (position, stmt) in ir.blocks[block].stmts.iter().enumerate() {
            if let Stmt::Store {
                addr,
                value: Expr::Reg { index, width: 64 },
                width: 8,
                ..
            } = stmt
                && let Some(offset) = slot(addr, sp)
                && !written.contains(index)
            {
                saved.push((*index, offset));
                stores.push((block, position));
            }
            written.extend(vlk_ir::ir::visit::statement_registers(stmt).0);
        }
    }
    let offset_of = |register: u16| {
        saved
            .iter()
            .find(|(saved, _)| *saved == register)
            .map(|(_, offset)| *offset)
    };
    // The integer registers past the named ones, each 8 bytes past the one
    // before, up to the last.
    let arguments = ir.convention.arguments();
    let Some(first) = arguments
        .iter()
        .position(|register| offset_of(*register).is_some())
    else {
        return None;
    };
    if first == 0 {
        return None;
    }
    let Some(base) = offset_of(arguments[first]) else {
        return None;
    };
    let trailing_arguments = arguments.iter().enumerate().skip(first);
    for (position, register) in trailing_arguments {
        let Some(offset) = offset_of(*register) else {
            return None;
        };
        if offset != base.wrapping_add(8 * (position - first) as u64) {
            return None;
        }
    }
    // Every floating-point argument register, both halves, 16 bytes apart.
    let floats = ir.convention.float_arguments();
    let Some(float_base) = offset_of(floats[0]) else {
        return None;
    };
    for (position, register) in floats.iter().enumerate() {
        let low = float_base.wrapping_add(16 * position as u64);
        let Some(offset) = offset_of(*register) else {
            return None;
        };
        if offset != low {
            return None;
        }
        let Some(high) = offset_of(register + 1) else {
            return None;
        };
        if high != low.wrapping_add(8) {
            return None;
        }
    }
    let unnamed: Vec<u16> = arguments[first..].to_vec();
    let mut keep: HashSet<u16> = unnamed.iter().copied().collect();
    for register in floats {
        keep.insert(*register);
        keep.insert(register + 1);
    }
    stores.retain(|(block, position)| {
        matches!(&ir.blocks[*block].stmts[*position],
            Stmt::Store { value: Expr::Reg { index, .. }, .. } if keep.contains(index))
    });
    // SysV's floating-point block holds nothing but their saves.
    if guard.is_some()
        && stores
            .iter()
            .filter(|(block, _)| *block == float_saves_block)
            .count()
            != ir.blocks[float_saves_block].stmts.len()
    {
        return None;
    }
    // The unnamed registers are read nowhere else: they hold no parameter.
    let reads_elsewhere = ir.blocks.iter().enumerate().any(|(block, contents)| {
        contents.stmts.iter().enumerate().any(|(position, stmt)| {
            !stores.contains(&(block, position))
                && (stmt
                    .declared_call_reads()
                    .iter()
                    .any(|register| unnamed.contains(register))
                    || stmt.operands().into_iter().any(|operand| {
                        let mut read = HashSet::new();
                        vlk_ir::ir::visit::collect_reads(operand, &mut read);
                        unnamed.iter().any(|register| read.contains(register))
                    }))
        })
    });
    if reads_elsewhere {
        return None;
    }
    Some(RegisterSaves {
        unnamed,
        stores,
        guard: guard.is_some(),
    })
}

/// How many arguments an O32 function names before the further ones it
/// takes, or zero when it does not show that it takes any: as it starts
/// it stores every argument register from some one on, each not yet
/// written, to the place the caller leaves for it above the frame, and
/// takes the address of the first of those places, where its argument
/// list begins.
pub(crate) fn further_arguments_from(blocks: &[vlk_ir::ir::Block], convention: Convention) -> u8 {
    if convention != Convention::O32 {
        return 0;
    }
    let Some(entry) = blocks.first() else {
        return 0;
    };
    let sp = vlk_arch::arch::mips32::SP;
    let fp = vlk_arch::arch::mips32::FP;
    let based = |addr: &Expr| match addr {
        Expr::Bin {
            op: BinOp::Add,
            lhs,
            rhs,
        } => match (lhs.as_ref(), rhs.as_ref()) {
            (Expr::Reg { index, .. }, Expr::Const(offset)) if *index == sp || *index == fp => {
                Some(*offset)
            }
            _ => None,
        },
        _ => None,
    };
    let arguments = convention.arguments();
    let mut frame = None;
    let mut written: HashSet<u16> = HashSet::new();
    let mut saved: Vec<(usize, u64)> = Vec::new();
    let mut taken: Vec<u64> = Vec::new();
    for stmt in &entry.stmts {
        match stmt {
            Stmt::Assign { dest, value, .. } if dest.index == sp => {
                let size = match value {
                    Expr::Bin { op, lhs, rhs } => match (op, lhs.as_ref(), rhs.as_ref()) {
                        (BinOp::Sub, Expr::Reg { index, .. }, Expr::Const(size))
                            if *index == sp =>
                        {
                            Some(*size)
                        }
                        (BinOp::Add, Expr::Reg { index, .. }, Expr::Const(size))
                            if *index == sp && (*size as i64) < 0 =>
                        {
                            Some((*size as i64).unsigned_abs())
                        }
                        _ => None,
                    },
                    _ => None,
                };
                match (frame, size) {
                    (None, Some(size)) => frame = Some(size),
                    _ => break,
                }
            }
            Stmt::Store {
                addr,
                value: Expr::Reg { index, .. },
                width: 4,
                ..
            } => {
                if let Some(offset) = based(addr)
                    && let Some(position) = arguments.iter().position(|arg| arg == index)
                    && !written.contains(index)
                {
                    saved.push((position, offset));
                }
            }
            Stmt::Assign { value, .. } => {
                let address = match value {
                    Expr::Bin {
                        op: BinOp::And,
                        lhs,
                        rhs,
                    } if matches!(rhs.as_ref(), Expr::Const(0xffff_ffff)) => lhs.as_ref(),
                    other => other,
                };
                taken.extend(based(address));
            }
            Stmt::Call { .. } => break,
            _ => {}
        }
        written.extend(vlk_ir::ir::visit::statement_registers(stmt).0);
    }
    let Some(frame) = frame else {
        return 0;
    };
    // The address of the saved arguments may be taken in a later block,
    // where the list is only needed on some paths; the frame is the same
    // there until the stack pointer moves.
    for block in &blocks[1..] {
        for stmt in &block.stmts {
            if vlk_ir::ir::visit::statement_registers(stmt).0.contains(&sp) {
                break;
            }
            if let Stmt::Assign { value, .. } = stmt {
                let address = match value {
                    Expr::Bin {
                        op: BinOp::And,
                        lhs,
                        rhs,
                    } if matches!(rhs.as_ref(), Expr::Const(0xffff_ffff)) => lhs.as_ref(),
                    other => other,
                };
                taken.extend(based(address));
            }
        }
    }
    // The place of argument `position` above the frame.
    let place = |position: usize| frame + 4 * position as u64;
    (1..arguments.len())
        .find(|first| {
            (*first..arguments.len()).all(|position| saved.contains(&(position, place(position))))
                && taken.contains(&place(*first))
        })
        .map_or(0, |first| first as u8)
}

/// How many argument words an O32 call passes for a format's conversions
/// after `named` arguments, and which of those words hold no argument: a
/// 64-bit value or a double takes two words, the first of them at an even
/// position, and the word skipped to get there is left unset.
pub fn o32_argument_words(format: &str, named: usize) -> (usize, Vec<usize>) {
    let mut words = named;
    let mut skipped = Vec::new();
    for ty in vlk_prototypes::prototypes::all_conversion_types(format, false) {
        // A long is one word here; a long long and every float, which is
        // passed as a double, are two.
        let wide = matches!(&ty, vlk_types::types::CType::Named(name)
            if name.contains("long long") || name.contains("double") || name.contains("float"));
        if wide {
            if words % 2 == 1 {
                skipped.push(words);
                words += 1;
            }
            words += 2;
        } else {
            words += 1;
        }
    }
    (words, skipped)
}

/// The offset from the stack pointer an address names.
fn slot(addr: &Expr, sp: u16) -> Option<u64> {
    match addr {
        Expr::Reg { index, .. } if *index == sp => Some(0),
        Expr::Bin {
            op: BinOp::Add,
            lhs,
            rhs,
        } => match (lhs.as_ref(), rhs.as_ref()) {
            (Expr::Reg { index, .. }, Expr::Const(offset)) if *index == sp => Some(*offset),
            _ => None,
        },
        _ => None,
    }
}

/// Takes the argument registers a variadic function saves for its further
/// arguments out of its parameters.
pub(crate) fn mark_variadic(ir: &mut FunctionIr) {
    let Some(saves) = register_saves(ir) else {
        return;
    };
    ir.params
        .retain(|param| !saves.unnamed.contains(&param.index));
    ir.accesses
        .retain(|access| !saves.unnamed.contains(&access.register));
    ir.variadic = true;
}

/// Leaves out the saves of a variadic function's further arguments, and
/// `SysV`'s test of al around them, which the `...` of its declaration stands
/// for.
pub fn drop_register_saves(ir: &mut FunctionIr) {
    if !ir.variadic {
        return;
    }
    let Some(saves) = register_saves(ir) else {
        return;
    };
    for (block, position) in saves.stores.iter().rev() {
        ir.blocks[*block].stmts.remove(*position);
    }
    if saves.guard {
        ir.blocks[0].stmts.pop();
    }
}

#[cfg(test)]
mod tests;