vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! What Go code does on entry to every function.

use std::collections::HashSet;

use vlk_ir::ir::Stmt;
use vlk_loader::loader::Image;

/// Go code on x86-64 keeps xmm15 zero: it holds zero as a function starts
/// and after every call. It keeps the goroutine in r14 too, and reloading it
/// from thread-local storage after a call changes nothing.
pub(super) fn initialize_go_registers(
    blocks: &mut [vlk_ir::ir::Block],
    isa: vlk_base::target::Isa,
) {
    if isa != vlk_base::target::Isa::X86_64 {
        return;
    }
    for block in blocks.iter_mut() {
        block.stmts.retain(|stmt| {
            !matches!(stmt, vlk_ir::ir::Stmt::Assign {
                dest: vlk_ir::ir::RegRef { index: 14, width: 64 },
                value: vlk_ir::ir::Expr::Load { addr, width: 8, .. },
                ..
            } if matches!(addr.as_ref(), vlk_ir::ir::Expr::Bin {
                    op: vlk_ir::ir::BinOp::Add,
                    lhs,
                    rhs,
                } if matches!(lhs.as_ref(), vlk_ir::ir::Expr::Reg { index: vlk_arch::arch::x86::FS_BASE, .. })
                    && matches!(rhs.as_ref(), vlk_ir::ir::Expr::Const(0xffff_ffff_ffff_fff8))))
        });
    }
    let Some(first) = blocks.first_mut() else {
        return;
    };
    for half in [
        vlk_arch::arch::x86::XMM0 + 30,
        vlk_arch::arch::x86::XMM0 + 31,
    ] {
        first.stmts.insert(
            0,
            vlk_ir::ir::Stmt::Assign {
                dest: vlk_ir::ir::RegRef {
                    index: half,
                    width: 64,
                },
                value: vlk_ir::ir::Expr::constant(0),
                at: None,
            },
        );
    }
}

/// Drops the check a Go function starts with, which compares the stack
/// pointer with the goroutine's stack limit and, when it runs low, calls the
/// runtime to grow the stack and starts the function again. It is no part
/// of what the function does. The blocks that grow the stack and restart
/// go too.
pub(super) fn drop_stack_growth_check(blocks: &mut Vec<vlk_ir::ir::Block>, image: &Image) {
    let grows = |target: u64| {
        image
            .functions
            .get(&target)
            .and_then(|function| function.name.as_deref())
            .is_some_and(|name| name.starts_with("runtime.morestack"))
    };
    let Some(entry) = blocks.first().map(|block| block.start) else {
        return;
    };
    let mut dropped = HashSet::new();
    for index in 0..blocks.len() {
        let Some(Stmt::Brif { target, .. }) = blocks[index].stmts.last() else {
            continue;
        };
        let target = *target;
        let Some(growth) = blocks.iter().position(|block| block.start == target) else {
            continue;
        };
        let calls_growth = blocks[growth]
            .stmts
            .iter()
            .any(|stmt| matches!(stmt, Stmt::Call { target: Some(callee), .. } if grows(*callee)));
        let Some(next) = blocks.get(index + 1).map(|block| block.start) else {
            continue;
        };
        if !calls_growth {
            continue;
        }
        // What the check compares is read for it alone: the stack limit,
        // which AArch64 loads into a scratch register first, and for a
        // large frame the stack pointer less the frame.
        let Some(Stmt::Brif { lhs, rhs, .. }) = blocks[index].stmts.last() else {
            continue;
        };
        let sp = vlk_arch::arch::stack_pointer(image.isa);
        let mut compared = std::collections::HashSet::new();
        vlk_ir::ir::visit::collect_reads(lhs, &mut compared);
        vlk_ir::ir::visit::collect_reads(rhs, &mut compared);
        compared.remove(&sp);
        let stmts = &mut blocks[index].stmts;
        let mut kept = stmts.len() - 1;
        while kept > 0
            && let Stmt::Assign { dest, value, .. } = &stmts[kept - 1]
            && compared.contains(&dest.index)
        {
            vlk_ir::ir::visit::collect_reads(value, &mut compared);
            compared.remove(&sp);
            kept -= 1;
        }
        stmts.drain(kept..stmts.len() - 1);
        // The check falls through into the body.
        *blocks[index].stmts.last_mut().expect("a branch") = Stmt::Br {
            target: Some(next),
            at: None,
        };
        dropped.insert(growth);
        // The restart: arguments reloaded, then back to the entry.
        if let Some(next) = blocks.get(growth + 1)
            && matches!(next.stmts.last(), Some(Stmt::Br { target: Some(start), .. }) if *start == entry)
        {
            dropped.insert(growth + 1);
        }
    }
    let mut index = 0;
    blocks.retain(|_| {
        index += 1;
        !dropped.contains(&(index - 1))
    });
}