use super::{copy_propagate, copy_propagate_guarded, inline_local_copies, truncated};
use vlk_base::target::Isa;
use vlk_eval::eval::{self, Outcome};
use vlk_ir::ir::{BinOp, Block, Cond, Expr, FunctionIr, Operation, RegRef, Stmt, VARIABLE_BASE};
use vlk_types::types::{CType, Convention, Param, Precision};
fn run(ir: &FunctionIr, address: u64, word: u64) -> Outcome {
let registers = [(7, 0x3000_0000_2000)];
let memory = [(address, word)];
let outcome = eval::run(
ir,
&eval::Setup {
seed: 0,
convention: eval::Convention {
arguments: &[7],
clobbered: &[],
},
registers: ®isters,
memory: &memory,
step_limit: 100,
},
);
assert!(matches!(&outcome, Outcome::Return { .. }), "{outcome:?}");
outcome
}
fn copy_passes() -> [fn(&mut FunctionIr); 3] {
[inline_local_copies, copy_propagate, copy_propagate_guarded]
}
fn stack_load(bytes: u8, signed: bool) -> Expr {
Expr::Load {
addr: Box::new(Expr::bin(BinOp::Add, Expr::reg(4, 64), Expr::Const(8))),
width: bytes,
signed,
}
}
fn with_copy(value: Expr, width: u8, consumer: Stmt) -> FunctionIr {
FunctionIr::single_block(
Isa::X86_64,
vec![
Stmt::Assign {
dest: RegRef {
index: VARIABLE_BASE,
width,
},
value,
at: None,
},
consumer,
],
)
}
#[test]
fn folded_reads_keep_their_own_truncation() {
let cases = [
(
stack_load(4, true),
Expr::reg(VARIABLE_BASE, 32),
0x8000_0080,
),
(
Expr::bin(BinOp::Add, stack_load(4, false), Expr::Const(1)),
Expr::reg(VARIABLE_BASE, 32),
0xffff_ffff,
),
(
stack_load(4, true),
Expr::bin(BinOp::And, Expr::reg(VARIABLE_BASE, 8), Expr::Const(0xffff)),
0x8000_1280,
),
];
for (value, returned, word) in cases {
let before = with_copy(
value,
64,
Stmt::Ret {
value: returned,
at: None,
},
);
let expected = run(&before, eval::STACK_TOP + 8, word);
for pass in copy_passes() {
let mut after = before.clone();
pass(&mut after);
assert!(
matches!(after.blocks[0].stmts.as_slice(), [Stmt::Ret { .. }]),
"{}",
after.render()
);
assert_eq!(
run(&after, eval::STACK_TOP + 8, word),
expected,
"{}",
after.render()
);
}
}
}
#[test]
fn copy_folding_preserves_signed_operation_and_comparison_widths() {
let check = |before: &FunctionIr| {
let expected = run(before, eval::STACK_TOP + 8, 0x80);
for pass in copy_passes() {
let mut after = before.clone();
pass(&mut after);
assert_eq!(
run(&after, eval::STACK_TOP + 8, 0x80),
expected,
"{}",
after.render()
);
}
};
for op in [BinOp::Sar, BinOp::DivS, BinOp::ModS] {
for rhs in [
Expr::Const(3),
Expr::bin(BinOp::Add, Expr::reg(7, 8), Expr::Const(3)),
] {
let before = with_copy(
stack_load(1, true),
32,
Stmt::Ret {
value: Expr::bin(op, Expr::reg(VARIABLE_BASE, 64), rhs),
at: None,
},
);
check(&before);
}
}
for (cond, rhs) in [
(Cond::Lt, Expr::Const(0)),
(Cond::Eq, Expr::Const(0x1_ffff_ff80)),
] {
let before = with_copy(
stack_load(1, true),
32,
Stmt::Ret {
value: Expr::Select {
cond,
lhs: Box::new(Expr::reg(VARIABLE_BASE, 64)),
rhs: Box::new(rhs.clone()),
then: Box::new(Expr::Const(1)),
els: Box::new(Expr::Const(2)),
},
at: None,
},
);
check(&before);
let mut branch = with_copy(
stack_load(1, true),
32,
Stmt::Brif {
cond,
lhs: Expr::reg(VARIABLE_BASE, 64),
rhs,
target: 0x20,
at: None,
},
);
branch.blocks.extend([
Block {
start: 0x10,
stmts: vec![Stmt::Ret {
value: Expr::Const(2),
at: None,
}],
},
Block {
start: 0x20,
stmts: vec![Stmt::Ret {
value: Expr::Const(1),
at: None,
}],
},
]);
check(&branch);
}
}
#[test]
fn equality_folds_when_both_values_fit_the_smaller_comparison_width() {
for cond in [Cond::Eq, Cond::Ne] {
let before = with_copy(
stack_load(1, true),
32,
Stmt::Ret {
value: Expr::Select {
cond,
lhs: Box::new(Expr::bin(
BinOp::And,
Expr::reg(VARIABLE_BASE, 64),
Expr::Const(4),
)),
rhs: Box::new(Expr::Const(0)),
then: Box::new(Expr::Const(1)),
els: Box::new(Expr::Const(2)),
},
at: None,
},
);
for word in [0x80, 0x84] {
let expected = run(&before, eval::STACK_TOP + 8, word);
for pass in copy_passes() {
let mut after = before.clone();
pass(&mut after);
assert!(
matches!(after.blocks[0].stmts.as_slice(), [Stmt::Ret { .. }]),
"{}",
after.render()
);
assert_eq!(
run(&after, eval::STACK_TOP + 8, word),
expected,
"{}",
after.render()
);
}
}
}
}
#[test]
fn a_rejected_substitution_leaves_the_consumer_unchanged() {
let before = with_copy(
Expr::reg(7, 32),
32,
Stmt::Ret {
value: Expr::bin(
BinOp::Add,
Expr::reg(VARIABLE_BASE, 64),
Expr::reg(VARIABLE_BASE, 16),
),
at: None,
},
);
for pass in copy_passes() {
let mut after = before.clone();
pass(&mut after);
assert_eq!(after.render(), before.render());
assert_eq!(
run(&after, eval::STACK_TOP + 8, 0),
run(&before, eval::STACK_TOP + 8, 0)
);
}
}
#[test]
fn folded_signed_loads_keep_assignment_truncation() {
let passes = [
(
"local copies",
inline_local_copies as fn(&mut FunctionIr),
false,
),
("copy propagation", copy_propagate, true),
("guarded copies", copy_propagate_guarded, true),
];
for (name, pass, stack) in passes {
let (address, location) = if stack {
(
Expr::bin(BinOp::Add, Expr::reg(4, 64), Expr::Const(8)),
eval::STACK_TOP + 8,
)
} else {
(Expr::reg(7, 64), 0x3000_0000_2000)
};
for bytes in [1u8, 2, 4] {
let sign = 1u64 << (bytes * 8 - 1);
let source_mask = (1u64 << (bytes * 8)) - 1;
for word in [5, sign | 5, source_mask] {
let mut ir = FunctionIr::single_block(
Isa::X86_64,
vec![
Stmt::Assign {
dest: RegRef {
index: VARIABLE_BASE,
width: 32,
},
value: Expr::Load {
addr: Box::new(address.clone()),
width: bytes,
signed: true,
},
at: None,
},
Stmt::Ret {
value: Expr::reg(VARIABLE_BASE, 64),
at: None,
},
],
);
if !stack {
ir.params = vec![Param {
index: 7,
name: "p".to_owned(),
ty: CType::pointer_to(CType::int(bytes, false)),
}];
}
let before = run(&ir, location, word);
let expected = if word & sign != 0 {
(word | !source_mask) & 0xffff_ffff
} else {
word
};
assert!(matches!(&before, Outcome::Return { value, .. } if *value == expected));
pass(&mut ir);
assert!(
matches!(ir.blocks[0].stmts.as_slice(), [Stmt::Ret { .. }]),
"{name}: {}",
ir.render()
);
assert_eq!(
run(&ir, location, word),
before,
"{name}: signed {bytes}-byte load of {word:x}"
);
}
}
}
}
#[test]
fn a_single_precision_result_needs_no_integer_mask() {
for bits in [
0,
0x8000_0000,
0x3f80_0000,
0xbf80_0000,
0x7f80_0000,
0x7fc0_0080,
] {
let value = Expr::apply(
Operation::FloatAdd(Precision::Single),
vec![Expr::Const(bits), Expr::Const(0x3f00_0000)],
);
assert_eq!(truncated(&value, 32), value);
let mut before = with_copy(
value.clone(),
32,
Stmt::Ret {
value: Expr::reg(VARIABLE_BASE, 32),
at: None,
},
);
before.ret_type = CType::Named("float".to_owned());
let expected = run(&before, eval::STACK_TOP + 8, 0);
for pass in copy_passes() {
let mut after = before.clone();
pass(&mut after);
assert!(
matches!(after.blocks[0].stmts.as_slice(), [Stmt::Ret { value: returned, .. }] if *returned == value),
"{}",
after.render()
);
assert_eq!(run(&after, eval::STACK_TOP + 8, 0), expected);
}
}
}
#[test]
fn load_truncation_retains_bits_without_changing_full_width_values() {
let address = 0x3000_0000_2000;
for bytes in [1u8, 2, 4, 8] {
let source_bits = u32::from(bytes) * 8;
let source_mask = u64::MAX >> (64 - source_bits);
let sign = 1u64 << (source_bits - 1);
for signed in [false, true] {
let value = Expr::Load {
addr: Box::new(Expr::Const(address)),
width: bytes,
signed,
};
for width in [8u8, 16, 32, 64] {
let retained = truncated(&value, width);
if width == 64 || (!signed && source_bits <= u32::from(width)) {
assert_eq!(retained, value);
} else {
assert_ne!(retained, value);
}
for word in [5, sign | 5, source_mask] {
let before = FunctionIr::single_block(
Isa::X86_64,
vec![
Stmt::Assign {
dest: RegRef {
index: VARIABLE_BASE,
width,
},
value: value.clone(),
at: None,
},
Stmt::Ret {
value: Expr::reg(VARIABLE_BASE, 64),
at: None,
},
],
);
let after = FunctionIr::single_block(
Isa::X86_64,
vec![Stmt::Ret {
value: retained.clone(),
at: None,
}],
);
assert_eq!(run(&before, address, word), run(&after, address, word));
}
}
}
}
}
#[test]
fn shifted_signed_loads_still_need_the_assignment_mask() {
let address = 0x3000_0000_2000;
for bytes in [1u8, 2, 4] {
for count in [0, 1, 63, 64, 65] {
let value = Expr::bin(
BinOp::Shr,
Expr::Load {
addr: Box::new(Expr::Const(address)),
width: bytes,
signed: true,
},
Expr::Const(count),
);
let before = FunctionIr::single_block(
Isa::X86_64,
vec![
Stmt::Assign {
dest: RegRef {
index: VARIABLE_BASE,
width: 32,
},
value: value.clone(),
at: None,
},
Stmt::Ret {
value: Expr::reg(VARIABLE_BASE, 64),
at: None,
},
],
);
let after = FunctionIr::single_block(
Isa::X86_64,
vec![Stmt::Ret {
value: truncated(&value, 32),
at: None,
}],
);
let word = 1u64 << (bytes * 8 - 1);
assert_eq!(run(&before, address, word), run(&after, address, word));
}
}
}
#[test]
fn a_folded_narrow_sum_keeps_its_truncation() {
let mut ir = FunctionIr::single_block(
Isa::X86_64,
vec![
Stmt::Assign {
dest: RegRef {
index: 0,
width: 32,
},
value: Expr::bin(BinOp::Add, Expr::reg(1, 32), Expr::reg(2, 32)),
at: None,
},
Stmt::Ret {
value: Expr::reg(0, 32),
at: None,
},
],
);
copy_propagate(&mut ir);
let sum = Expr::bin(BinOp::Add, Expr::reg(1, 32), Expr::reg(2, 32));
let truncated = Expr::bin(BinOp::And, sum, Expr::Const(0xffff_ffff));
assert!(
matches!(ir.blocks[0].stmts.as_slice(), [Stmt::Ret { value, .. }] if *value == truncated),
"{}",
ir.render()
);
}
#[test]
fn a_further_result_in_a_parameter_register_stays_in_its_variable() {
let (first, second) = (VARIABLE_BASE, VARIABLE_BASE + 1);
let mut ir = FunctionIr::single_block(
Isa::X86_64,
vec![
Stmt::Call {
kind: vlk_types::types::CallKind::Invoke,
target: Some(0x1000),
through: None,
convention: Convention::GoAmd64,
args: Some(vec![Expr::reg(3, 64)]),
floats_named: false,
abi: None,
clobbers: None,
outputs: vlk_ir::ir::fallback_call_outputs(Convention::GoAmd64, None),
via: None,
at: None,
},
Stmt::Assign {
dest: RegRef {
index: first,
width: 64,
},
value: Expr::reg(0, 64),
at: None,
},
Stmt::Assign {
dest: RegRef {
index: second,
width: 64,
},
value: Expr::reg(3, 64),
at: None,
},
Stmt::Ret {
value: Expr::reg(second, 64),
at: None,
},
],
);
ir.params = vec![Param {
index: 3,
name: "a0".to_owned(),
ty: CType::I64,
}];
copy_propagate(&mut ir);
assert!(
matches!(ir.blocks[0].stmts.as_slice(), [Stmt::Call { .. }, Stmt::Assign { dest, value: copied, .. }, Stmt::Assign { .. }, Stmt::Ret { value, .. }] if dest.index == first && *copied == Expr::reg(0, 64) && *value == Expr::reg(second, 64)),
"{}",
ir.render()
);
}
#[test]
fn a_load_does_not_move_past_a_store() {
let load = |index| Expr::Load {
addr: Box::new(Expr::reg(index, 64)),
width: 4,
signed: false,
};
let assign = |index, value| Stmt::Assign {
dest: RegRef { index, width: 64 },
value,
at: None,
};
let store = |value, addr| Stmt::Store {
addr: Expr::reg(addr, 64),
value: Expr::reg(value, 64),
width: 4,
at: None,
};
let mut ir = FunctionIr::single_block(
Isa::AArch64,
vec![
assign(8, load(1)),
assign(9, load(0)),
store(8, 0),
store(9, 1),
Stmt::Ret {
value: Expr::Const(0),
at: None,
},
],
);
inline_local_copies(&mut ir);
let stmts = &ir.blocks[0].stmts;
let saved = stmts
.iter()
.position(|stmt| matches!(stmt, Stmt::Assign { dest, .. } if dest.index == 9));
let overwritten = stmts
.iter()
.position(|stmt| matches!(stmt, Stmt::Store { addr, .. } if *addr == Expr::reg(0, 64)));
assert!(
saved.is_some_and(|saved| Some(saved) < overwritten),
"the load of *a stays before the store to *a:\n{}",
ir.render()
);
}
#[test]
fn keeps_a_definition_a_later_block_reads() {
let load = Expr::Load {
addr: Box::new(Expr::reg(1, 64)),
width: 8,
signed: false,
};
let mut ir = FunctionIr::single_block(
Isa::AArch64,
vec![
Stmt::Assign {
dest: RegRef {
index: 8,
width: 64,
},
value: load,
at: None,
},
Stmt::Brif {
cond: Cond::Eq,
lhs: Expr::reg(8, 64),
rhs: Expr::Const(0),
target: 0x10,
at: None,
},
],
);
ir.blocks.push(Block {
start: 0x8,
stmts: vec![Stmt::Ret {
value: Expr::reg(8, 64),
at: None,
}],
});
ir.blocks.push(Block {
start: 0x10,
stmts: vec![Stmt::Ret {
value: Expr::Const(0),
at: None,
}],
});
inline_local_copies(&mut ir);
assert!(
matches!(ir.blocks[0].stmts[0], Stmt::Assign { dest, .. } if dest.index == 8),
"{}",
ir.render()
);
}
#[test]
fn inlines_a_masked_temporary() {
let masked = |index| Expr::bin(BinOp::And, Expr::reg(index, 64), Expr::Const(0xffff_ffff));
let mut ir = FunctionIr::single_block(
Isa::X86_64,
vec![
Stmt::Assign {
dest: RegRef {
index: 0,
width: 64,
},
value: masked(1),
at: None,
},
Stmt::Assign {
dest: RegRef {
index: 2,
width: 64,
},
value: Expr::bin(BinOp::ModS, masked(0), masked(2)),
at: None,
},
Stmt::Ret {
value: masked(2),
at: None,
},
],
);
copy_propagate(&mut ir);
assert!(
!matches!(ir.blocks[0].stmts.first(), Some(Stmt::Assign { dest, .. }) if dest.index == 0),
"the masked copy should inline: {:?}",
ir.blocks[0].stmts
);
}
#[test]
fn copies_keep_a_precise_calls_preserved_output_source() {
let mut ir = FunctionIr::single_block(
Isa::AArch64,
vec![
Stmt::Assign {
dest: RegRef {
index: 1,
width: 64,
},
value: Expr::Const(17),
at: None,
},
Stmt::Call {
kind: vlk_types::types::CallKind::Invoke,
target: Some(0x1000),
through: None,
convention: Convention::Aapcs64,
args: Some(Vec::new()),
floats_named: true,
abi: None,
clobbers: Some(Default::default()),
outputs: vec![vlk_ir::ir::CallOutput {
register: 1,
dest: RegRef {
index: VARIABLE_BASE,
width: 64,
},
}],
via: None,
at: None,
},
Stmt::Ret {
value: Expr::reg(VARIABLE_BASE, 64),
at: None,
},
],
);
let before = ir.clone();
for pass in [copy_propagate, inline_local_copies] {
ir = before.clone();
pass(&mut ir);
assert!(
matches!(ir.blocks[0].stmts.first(), Some(Stmt::Assign { dest, value: Expr::Const(17), .. }) if dest.index == 1),
"{}",
ir.render()
);
let setup = eval::Setup {
seed: 5,
convention: eval::Convention {
arguments: &[],
clobbered: &[],
},
registers: &[],
memory: &[],
step_limit: 32,
};
let expected = eval::run(&before, &setup);
assert!(matches!(&expected, Outcome::Return { value: 17, .. }));
assert_eq!(eval::run(&ir, &setup), expected);
}
}
#[test]
fn declared_inputs_keep_their_load_producer_and_fallback_arguments() {
for arguments in [Vec::new(), vec![Expr::reg(7, 64)]] {
let call = Stmt::Call {
kind: vlk_types::types::CallKind::Invoke,
target: Some(0x1000),
through: None,
convention: Convention::SysV,
args: Some(arguments),
floats_named: true,
clobbers: Some(Default::default()),
outputs: Vec::new(),
abi: Some(crate::passes::test_call_abi(vec![7], false)),
via: None,
at: None,
};
let load = Expr::Load {
addr: Box::new(Expr::reg(2, 64)),
width: 8,
signed: false,
};
let producer = Stmt::Assign {
dest: RegRef {
index: 7,
width: 64,
},
value: load.clone(),
at: None,
};
let before = FunctionIr::single_block(
Isa::X86_64,
vec![
producer.clone(),
call.clone(),
Stmt::Ret {
value: Expr::Const(0),
at: None,
},
],
);
for pass in copy_passes() {
let mut ir = before.clone();
pass(&mut ir);
assert!(
matches!(&ir.blocks[0].stmts[0], Stmt::Assign { dest, value, .. }
if dest.index == 7 && *value == load)
);
assert_eq!(format!("{:?}", ir.blocks[0].stmts[1]), format!("{call:?}"));
}
}
}
#[test]
fn declared_reads_refuse_substitution_but_unattached_calls_allow_it() {
let mut call = Stmt::Call {
kind: vlk_types::types::CallKind::Invoke,
target: Some(0x1000),
through: None,
convention: Convention::SysV,
args: Some(vec![Expr::reg(7, 64)]),
floats_named: true,
clobbers: Some(Default::default()),
outputs: Vec::new(),
abi: Some(crate::passes::test_call_abi(vec![7], false)),
via: None,
at: None,
};
assert_eq!(super::count_register_reads(&call, 7), 2);
let original = call.clone();
assert!(!super::substitute_statement(
&mut call,
7,
64,
&Expr::Const(9)
));
assert_eq!(format!("{call:?}"), format!("{original:?}"));
if let Stmt::Call { abi, .. } = &mut call {
*abi = None;
}
assert_eq!(super::count_register_reads(&call, 7), 1);
if let Stmt::Call { through, .. } = &mut call {
*through = Some(Expr::bin(BinOp::Add, Expr::reg(7, 64), Expr::reg(7, 64)));
}
assert_eq!(super::count_register_reads(&call, 7), 3);
if let Stmt::Call { through, .. } = &mut call {
*through = None;
}
assert!(super::substitute_statement(
&mut call,
7,
64,
&Expr::Const(9)
));
assert!(matches!(call, Stmt::Call { args: Some(args), .. } if args == [Expr::Const(9)]));
}