vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
use super::{Fate, fate};
use vlk_ir::ir::{Block, Expr, RegRef, Stmt};

fn after_call(rest: Vec<Stmt>) -> Fate {
    let blocks = vec![Block {
        start: 0,
        stmts: rest,
    }];
    fate(&blocks, 0, 0, &mut std::collections::HashMap::new())
}

fn assign(index: u16, value: Expr) -> Stmt {
    Stmt::Assign {
        dest: RegRef { index, width: 64 },
        value,
        at: None,
    }
}

#[test]
fn a_go_function_returns_as_many_values_as_its_callers_read() {
    for file in ["go_probe", "go_probe_arm64", "go_probe_arm64_1_27"] {
        let path = std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../.."))
            .join("tests/fixtures")
            .join(file);
        let program = vlk_program::program::Program::new(crate::lift::load(&path).unwrap());
        let further = |name: &str| {
            let address = program
                .image
                .functions
                .values()
                .find(|function| function.name.as_deref() == Some(name))
                .expect("named function")
                .addr;
            super::further_results(&program, address)
        };
        assert_eq!(further("main.divmod"), 1, "{file}");
        assert_eq!(further("main.add"), 0, "{file}");
        assert_eq!(further("main.sumSlice"), 0, "{file}");
        // A slice: pointer, length and capacity.
        assert_eq!(further("runtime.growslice"), 2, "{file}");
        // The write barrier keeps every register but its own.
        assert_eq!(further("runtime.gcWriteBarrier2"), 0, "{file}");
    }
}

#[test]
fn a_register_compared_with_itself_is_not_read() {
    let reads = |expr: &Expr| {
        let mut found = std::collections::HashSet::new();
        super::value_reads(expr, &mut found);
        let mut found: Vec<u16> = found.into_iter().collect();
        found.sort_unstable();
        found
    };
    // carry ? 1 : 0 as `sbb` of a register and itself spreads it.
    let spread = Expr::Select {
        cond: vlk_ir::ir::Cond::Cc,
        lhs: Box::new(Expr::reg(10, 64)),
        rhs: Box::new(Expr::reg(10, 64)),
        then: Box::new(Expr::reg(3, 64)),
        els: Box::new(Expr::Const(0)),
    };
    assert_eq!(reads(&spread), [3]);
    let cleared = Expr::bin(vlk_ir::ir::BinOp::Xor, Expr::reg(9, 64), Expr::reg(9, 64));
    assert_eq!(reads(&cleared), [0u16; 0]);
    let sum = Expr::bin(vlk_ir::ir::BinOp::Add, Expr::reg(9, 64), Expr::reg(8, 64));
    assert_eq!(reads(&sum), [8, 9]);
}

#[test]
fn results_count_while_every_path_to_a_return_sets_them() {
    let returns = || Stmt::Ret {
        value: Expr::reg(0, 64),
        at: None,
    };
    let branch = |target| Stmt::Brif {
        cond: vlk_ir::ir::Cond::Eq,
        lhs: Expr::reg(0, 64),
        rhs: Expr::Const(0),
        target,
        at: None,
    };
    // One path sets registers 1 and 2, the other only 1.
    let blocks = vec![
        Block {
            start: 0,
            stmts: vec![assign(1, Expr::Const(7)), branch(0x20)],
        },
        Block {
            start: 0x10,
            stmts: vec![assign(2, Expr::Const(8)), returns()],
        },
        Block {
            start: 0x20,
            stmts: vec![returns()],
        },
    ];
    assert_eq!(super::set_before_returning(&blocks, &[1, 2, 3], 0), 1);
    // An argument may be returned as it came.
    assert_eq!(super::set_before_returning(&blocks, &[2, 1, 3], 1), 2);
    assert_eq!(super::set_before_returning(&blocks, &[2, 1, 3], 0), 0);
    // What is written after the return does not count.
    let blocks = vec![Block {
        start: 0,
        stmts: vec![returns(), assign(1, Expr::Const(7))],
    }];
    assert_eq!(super::set_before_returning(&blocks, &[1], 0), 0);
}

#[test]
fn explicit_return_assignment_is_not_an_incidental_result() {
    let ret = Stmt::Ret {
        value: Expr::reg(vlk_arch::arch::RETURN, 64),
        at: None,
    };
    let result = assign(vlk_arch::arch::RETURN, Expr::reg(8, 64));
    let store = Stmt::Store {
        addr: Expr::Const(0x2000),
        value: Expr::reg(vlk_arch::arch::RETURN, 64),
        width: 8,
        at: None,
    };
    let block = |stmts| [Block { start: 0, stmts }];
    assert!(super::returns_value(&block(vec![
        result.clone(),
        ret.clone()
    ])));
    assert!(!super::returns_value(&block(vec![
        result.clone(),
        store.clone(),
        ret.clone()
    ])));
    assert!(super::returns_value(&block(vec![
        assign(vlk_arch::arch::RETURN, Expr::Const(0)),
        store,
        ret.clone()
    ])));
    assert!(!super::returns_value(&block(vec![ret.clone()])));
    let call = Stmt::Call {
        abi: None,
        kind: vlk_types::types::CallKind::Invoke,
        target: Some(0x1000),
        through: None,
        convention: vlk_types::types::Convention::Aapcs64,
        args: Some(Vec::new()),
        floats_named: true,
        outputs: vlk_ir::ir::fallback_call_outputs(vlk_types::types::Convention::Aapcs64, None),
        clobbers: None,
        via: None,
        at: None,
    };
    assert!(!super::returns_value(&block(vec![
        result.clone(),
        call.clone(),
        ret.clone()
    ])));
    assert!(super::returns_value(&block(vec![call, result, ret])));
}

#[test]
fn a_result_is_read_only_before_the_register_is_written() {
    let ret = Stmt::Ret {
        value: Expr::reg(0, 64),
        at: None,
    };
    assert_eq!(
        after_call(vec![assign(3, Expr::reg(0, 64)), ret.clone()]),
        Fate::Read
    );
    assert_eq!(
        after_call(vec![assign(0, Expr::Const(1)), ret.clone()]),
        Fate::Unused
    );
    assert_eq!(after_call(vec![ret]), Fate::Returned);
}

#[test]
fn result_liveness_distinguishes_preserving_calls_and_named_destinations() {
    let mut call = Stmt::Call {
        kind: vlk_types::types::CallKind::Invoke,
        target: Some(0x1000),
        through: None,
        convention: vlk_types::types::Convention::SysV,
        args: Some(Vec::new()),
        floats_named: true,
        abi: None,
        outputs: vlk_ir::ir::fallback_call_outputs(
            vlk_types::types::Convention::SysV,
            Some(Default::default()),
        ),
        clobbers: Some(Default::default()),
        via: None,
        at: None,
    };
    assert_eq!(super::event(&call), None);
    let Stmt::Call {
        outputs, clobbers, ..
    } = &mut call
    else {
        unreachable!()
    };
    *clobbers = Some([2].into_iter().collect());
    *outputs = vec![vlk_ir::ir::CallOutput {
        register: 2,
        dest: RegRef {
            index: 0,
            width: 64,
        },
    }];
    assert_eq!(super::event(&call), Some(Fate::Unused));
    let Stmt::Call {
        outputs, clobbers, ..
    } = &mut call
    else {
        unreachable!()
    };
    *clobbers = Some(Default::default());
    *outputs = vec![vlk_ir::ir::CallOutput {
        register: 0,
        dest: RegRef {
            index: vlk_ir::ir::VARIABLE_BASE,
            width: 64,
        },
    }];
    assert_eq!(super::event(&call), Some(Fate::Read));
}