//! Runs MIPS32 integer and float code through a MIPS Linux emulator and the IR
//! interpreter.
use std::collections::HashSet;
use std::fmt::Write as _;
use std::fs;
use std::path::Path;
use std::process::Command;
use vlk_eval::eval;
use vlk_ir::ir::FunctionIr;
const SYSTEM: &str = "alpine:3.20";
/// Whether the C compiler on PATH can build MIPS code.
fn compiler_available() -> bool {
let probe = Command::new("clang")
.args(["--target=mipsel-linux-gnu", "--print-supported-cpus"])
.output();
match probe {
Ok(output) if output.status.success() => true,
other => {
eprintln!("skipping the MIPS hardware check: no MIPS compiler: {other:?}");
false
}
}
}
fn compile(assembly: &Path, executable: &Path, big: bool) {
let build = Command::new("clang")
.args([
if big {
"--target=mips-linux-gnu"
} else {
"--target=mipsel-linux-gnu"
},
"-march=mips32r2",
"-mhard-float",
"-mfp32",
"-fno-pic",
"-mno-abicalls",
"-fuse-ld=lld",
"-nostdlib",
"-static",
"-Wl,-e,__start",
])
.arg(assembly)
.arg("-o")
.arg(executable)
.output()
.unwrap();
assert!(
build.status.success(),
"{}",
String::from_utf8_lossy(&build.stderr)
);
}
/// Runs the program under a user-mode emulator installed in a container;
/// None when the container or the emulator cannot be had.
fn run(directory: &Path, executable: &str, big: bool) -> Option<Vec<u8>> {
let emulator = if big { "qemu-mips" } else { "qemu-mipsel" };
let output = Command::new("docker")
.args(["run", "--rm", "-v"])
.arg(format!("{}:/check:ro", directory.display()))
.args([
SYSTEM,
"sh",
"-c",
&format!(
"apk add -q --no-progress {emulator} >/dev/null 2>&1 && {emulator} /check/{executable}"
),
])
.output();
match output {
Ok(output) if output.status.success() => Some(output.stdout),
other => {
eprintln!("skipping the MIPS hardware check: no emulator: {other:?}");
None
}
}
}
/// The cases: the code of each takes a0 and a1 and leaves its result in
/// v0. Delay slots are written out.
fn cases() -> Vec<String> {
let mut cases: Vec<String> = Vec::new();
let mut case = |code: &str| cases.push(code.to_owned());
for name in [
"addu", "subu", "and", "or", "xor", "nor", "slt", "sltu", "sllv", "srlv", "srav", "rotrv",
"mul",
] {
case(&format!("{name} $v0, $a0, $a1"));
}
for (name, immediate) in [
("addiu", "-5"),
("addiu", "32767"),
("slti", "-1"),
("slti", "100"),
("sltiu", "1"),
("sltiu", "-1"),
("andi", "0xff0f"),
("ori", "0x8001"),
("xori", "0xffff"),
] {
case(&format!("{name} $v0, $a0, {immediate}"));
}
for name in ["sll", "srl", "sra", "rotr"] {
for amount in [0, 1, 13, 31] {
case(&format!("{name} $v0, $a0, {amount}"));
}
}
case("lui $v0, 0x1234");
case("lui $v0, 0xffff\naddu $v0, $v0, $a0");
for name in ["mult", "multu"] {
case(&format!("{name} $a0, $a1\nmflo $v0"));
case(&format!("{name} $a0, $a1\nmfhi $v0"));
}
for name in ["madd", "maddu", "msub", "msubu"] {
case(&format!("mthi $a1\nmtlo $a0\n{name} $a0, $a1\nmflo $v0"));
case(&format!("mthi $a1\nmtlo $a0\n{name} $a0, $a1\nmfhi $v0"));
}
for name in ["div", "divu"] {
case(&format!("{name} $zero, $a0, $a1\nmflo $v0"));
case(&format!("{name} $zero, $a0, $a1\nmfhi $v0"));
}
case("move $v0, $a0\nmovz $v0, $a1, $a0");
case("move $v0, $a0\nmovn $v0, $a1, $a0");
case("clz $v0, $a0");
case("clo $v0, $a0");
for (position, size) in [(0, 1), (4, 4), (7, 25), (31, 1), (0, 32)] {
case(&format!("ext $v0, $a0, {position}, {size}"));
case(&format!("move $v0, $a1\nins $v0, $a0, {position}, {size}"));
}
case("seb $v0, $a0");
case("seh $v0, $a0");
case("wsbh $v0, $a0");
for (load, store) in [
("lb", "sb"),
("lbu", "sb"),
("lh", "sh"),
("lhu", "sh"),
("lw", "sw"),
] {
case(&format!(
"addiu $sp, $sp, -16\nsw $a1, 4($sp)\n{store} $a0, 4($sp)\n{load} $v0, 4($sp)\naddiu $sp, $sp, 16"
));
}
// An unaligned word, written and read back one byte into the frame.
case(
"addiu $sp, $sp, -16\nsw $a1, 4($sp)\nsw $a1, 8($sp)\nswr $a0, 5($sp)\nswl $a0, 8($sp)\nlw $v0, 4($sp)\nlw $t0, 8($sp)\nxor $v0, $v0, $t0\naddiu $sp, $sp, 16",
);
case(
"addiu $sp, $sp, -16\nsw $a0, 4($sp)\nsw $a1, 8($sp)\nlwr $v0, 5($sp)\nlwl $v0, 8($sp)\naddiu $sp, $sp, 16",
);
// The same with other instructions between the two halves, and two
// accesses whose halves alternate.
case(
"addiu $sp, $sp, -16\nsw $a0, 4($sp)\nsw $a1, 8($sp)\nlwl $v0, 8($sp)\nlw $t1, 4($sp)\naddiu $t2, $a1, 3\nlwr $v0, 5($sp)\nxor $v0, $v0, $t1\naddu $v0, $v0, $t2\naddiu $sp, $sp, 16",
);
case(
"addiu $sp, $sp, -32\nsw $a0, 4($sp)\nsw $a1, 8($sp)\nsw $a1, 12($sp)\nsw $a0, 16($sp)\nlwl $v0, 8($sp)\nlwl $t0, 16($sp)\nlwr $v0, 5($sp)\nlwr $t0, 13($sp)\nxor $v0, $v0, $t0\naddiu $sp, $sp, 32",
);
case(
"addiu $sp, $sp, -32\nsw $a1, 4($sp)\nsw $a1, 8($sp)\nsw $a0, 12($sp)\nsw $a0, 16($sp)\nswl $a0, 8($sp)\nswl $a1, 16($sp)\naddiu $t2, $a1, 1\nswr $a0, 5($sp)\nswr $a1, 13($sp)\nlw $v0, 4($sp)\nlw $t0, 8($sp)\nxor $v0, $v0, $t0\nlw $t0, 12($sp)\nxor $v0, $v0, $t0\nlw $t0, 16($sp)\nxor $v0, $v0, $t0\naddu $v0, $v0, $t2\naddiu $sp, $sp, 32",
);
// Each half alone, at every place in a word: the frame is aligned,
// so the offsets are the places.
for offset in 0..4 {
for half in ["lwl", "lwr"] {
case(&format!(
"addiu $sp, $sp, -16\nsw $a0, 4($sp)\nmove $v0, $a1\n{half} $v0, {}($sp)\naddiu $sp, $sp, 16",
4 + offset
));
}
for half in ["swl", "swr"] {
case(&format!(
"addiu $sp, $sp, -16\nsw $a0, 4($sp)\n{half} $a1, {}($sp)\nlw $v0, 4($sp)\naddiu $sp, $sp, 16",
4 + offset
));
}
}
// A test for zero and for anything else, as a comparison below.
case("sltu $v0, $zero, $a0\nsltiu $t0, $a1, 1\nsll $t0, $t0, 4\nor $v0, $v0, $t0");
// Branches, each with a delay slot that changes an operand: the
// branch has read it already.
for branch in ["beq $a0, $a1", "bne $a0, $a1"] {
case(&format!(
"{branch}, 1f\naddiu $a0, $a0, 1\nli $v0, 0\njr $ra\naddu $v0, $v0, $a0\n1:\nli $v0, 0x1000\njr $ra\naddu $v0, $v0, $a0"
));
}
for branch in ["blez", "bgtz", "bltz", "bgez"] {
case(&format!(
"{branch} $a0, 1f\nxori $a0, $a0, 0xffff\nli $v0, 0\njr $ra\naddu $v0, $v0, $a0\n1:\nli $v0, 0x1000\njr $ra\naddu $v0, $v0, $a0"
));
}
// A branch that skips its delay slot when it is not taken.
for branch in ["beql $a0, $a1", "bnel $a0, $a1"] {
case(&format!(
"{branch}, 1f\naddiu $a0, $a0, 5\njr $ra\naddu $v0, $a0, $a1\n1:\naddiu $v0, $a0, 100"
));
}
for branch in ["blezl", "bgtzl", "bltzl", "bgezl"] {
case(&format!(
"{branch} $a0, 1f\naddiu $a0, $a0, 5\njr $ra\naddu $v0, $a0, $a1\n1:\naddiu $v0, $a0, 100"
));
}
float_cases(&mut case);
case("b 1f\naddiu $a0, $a0, 3\nli $a0, 9\n1:\naddu $v0, $a0, $a1");
case("j 1f\naddiu $a0, $a0, 3\nli $a0, 9\n1:\naddu $v0, $a0, $a1");
// The return's own delay slot.
case("li $v0, 7\njr $ra\naddu $v0, $v0, $a0");
cases
}
/// The float cases. A single takes its operands' bits from a0 and a1; a
/// double takes a0 as the high word of the first and the low word of the
/// second, and a1 as the other two. A NaN result is given as one fixed
/// value: the IR does not model which NaN an operation gives.
fn float_cases(case: &mut impl FnMut(&str)) {
const SINGLES: &str = "mtc1 $a0, $f0\nmtc1 $a1, $f2\n";
const DOUBLES: &str = "mtc1 $a1, $f0\nmtc1 $a0, $f1\nmtc1 $a0, $f2\nmtc1 $a1, $f3\n";
const SINGLE_RESULT: &str = "c.un.s $f4, $f4\nmfc1 $v0, $f4\nbc1f 9f\nnop\nlui $v0, 0x7fc0\n9:";
const DOUBLE_RESULT: &str = "c.un.d $f4, $f4\nmfc1 $v0, $f4\nmfc1 $t0, $f5\nbc1f 9f\nxor $v0, $v0, $t0\nlui $v0, 0x7ff8\n9:";
for name in ["add", "sub", "mul", "div"] {
case(&format!("{SINGLES}{name}.s $f4, $f0, $f2\n{SINGLE_RESULT}"));
case(&format!("{DOUBLES}{name}.d $f4, $f0, $f2\n{DOUBLE_RESULT}"));
}
for name in ["sqrt", "abs", "neg", "mov"] {
case(&format!("{SINGLES}{name}.s $f4, $f0\n{SINGLE_RESULT}"));
case(&format!("{DOUBLES}{name}.d $f4, $f0\n{DOUBLE_RESULT}"));
}
// The sign of a NaN is its own.
case(&format!("{SINGLES}neg.s $f4, $f0\nmfc1 $v0, $f4"));
case(&format!("{SINGLES}abs.s $f4, $f0\nmfc1 $v0, $f4"));
for name in ["madd", "msub", "nmadd", "nmsub"] {
case(&format!(
"{SINGLES}{name}.s $f4, $f0, $f2, $f0\n{SINGLE_RESULT}"
));
case(&format!(
"{DOUBLES}{name}.d $f4, $f2, $f0, $f2\n{DOUBLE_RESULT}"
));
}
case(&format!("{SINGLES}cvt.d.s $f4, $f0\n{DOUBLE_RESULT}"));
case(&format!("{DOUBLES}cvt.s.d $f4, $f0\n{SINGLE_RESULT}"));
case(&format!("{SINGLES}cvt.s.w $f4, $f0\n{SINGLE_RESULT}"));
case(&format!("{SINGLES}cvt.d.w $f4, $f2\n{DOUBLE_RESULT}"));
for name in ["round", "trunc", "ceil", "floor", "cvt"] {
case(&format!("{SINGLES}{name}.w.s $f4, $f0\nmfc1 $v0, $f4"));
case(&format!("{DOUBLES}{name}.w.d $f4, $f0\nmfc1 $v0, $f4"));
case(&format!("{DOUBLES}{name}.w.d $f4, $f2\nmfc1 $v0, $f4"));
}
for condition in [
"f", "un", "eq", "ueq", "olt", "ult", "ole", "ule", "sf", "ngle", "seq", "ngl", "lt",
"nge", "le", "ngt",
] {
case(&format!(
"{SINGLES}c.{condition}.s $f0, $f2\nli $v0, 5\nmovt $v0, $a0, $fcc0"
));
case(&format!(
"{DOUBLES}c.{condition}.d $f0, $f2\nli $v0, 5\nmovf $v0, $a1, $fcc0"
));
}
// A flag other than the first, and branches on flags; the delay slot
// of the second compares again after the branch has read the flag.
case(&format!(
"{SINGLES}c.lt.s $fcc3, $f0, $f2\nli $v0, 5\nbc1t $fcc3, 1f\nnop\nli $v0, 9\n1:"
));
case(&format!(
"{SINGLES}c.lt.s $f0, $f2\nli $v0, 5\nbc1f 1f\nc.lt.s $f2, $f0\nli $v0, 9\n1:\nmovt $v0, $a1, $fcc0"
));
for branch in ["bc1tl", "bc1fl"] {
case(&format!(
"{SINGLES}c.le.s $f0, $f2\n{branch} 1f\naddiu $a0, $a0, 5\njr $ra\naddu $v0, $a0, $a1\n1:\naddiu $v0, $a0, 100"
));
}
for name in ["movz", "movn"] {
case(&format!("{SINGLES}{name}.s $f0, $f2, $a0\nmfc1 $v0, $f0"));
case(&format!(
"{DOUBLES}{name}.d $f0, $f2, $a1\nmfc1 $v0, $f0\nmfc1 $t0, $f1\nxor $v0, $v0, $t0"
));
}
for name in ["movt", "movf"] {
case(&format!(
"{SINGLES}c.lt.s $f0, $f2\n{name}.s $f0, $f2, $fcc0\nmfc1 $v0, $f0"
));
case(&format!(
"{DOUBLES}c.lt.d $f0, $f2\n{name}.d $f0, $f2, $fcc0\nmfc1 $v0, $f0\nmfc1 $t0, $f1\nxor $v0, $v0, $t0"
));
}
// The two registers of a pair hold separate singles, and a single
// written to one leaves the other.
case(
"mtc1 $a0, $f1\nmtc1 $a1, $f0\nmov.s $f3, $f0\nmov.s $f2, $f1\nmtc1 $zero, $f0\nmfc1 $v0, $f3\nmfc1 $t0, $f2\nxor $v0, $v0, $t0\nmfc1 $t0, $f1\nxor $v0, $v0, $t0",
);
// Loads and stores, of each width and by an index.
case(
"addiu $sp, $sp, -16\nsw $a0, 4($sp)\nsw $a1, 8($sp)\nlwc1 $f0, 4($sp)\nlwc1 $f1, 8($sp)\nswc1 $f1, 0($sp)\nswc1 $f0, 12($sp)\nlw $v0, 0($sp)\nlw $t0, 12($sp)\nsll $t0, $t0, 1\nxor $v0, $v0, $t0\naddiu $sp, $sp, 16",
);
case(
"addiu $sp, $sp, -32\nsw $a0, 8($sp)\nsw $a1, 12($sp)\nldc1 $f0, 8($sp)\nsdc1 $f0, 16($sp)\nmfc1 $v0, $f1\nlw $t0, 16($sp)\nsll $t0, $t0, 1\nxor $v0, $v0, $t0\nlw $t0, 20($sp)\nxor $v0, $v0, $t0\naddiu $sp, $sp, 32",
);
case(
"addiu $sp, $sp, -32\nsw $a0, 8($sp)\nsw $a1, 12($sp)\nli $t1, 8\nlwxc1 $f0, $t1($sp)\nldxc1 $f2, $t1($sp)\nli $t1, 16\nsdxc1 $f2, $t1($sp)\nli $t1, 24\nswxc1 $f0, $t1($sp)\nlw $v0, 16($sp)\nlw $t0, 20($sp)\nsll $t0, $t0, 1\nxor $v0, $v0, $t0\nlw $t0, 24($sp)\nsll $t0, $t0, 2\nxor $v0, $v0, $t0\naddiu $sp, $sp, 32",
);
}
const EDGES: [u32; 38] = [
0,
1,
2,
7,
31,
32,
33,
255,
256,
0x7f,
0x80,
0x7fff,
0x8000,
0xffff,
0x1_0000,
0x1234_5678,
0x7fff_ffff,
0x8000_0000,
0x8000_0001,
0xffff_fffe,
0xffff_ffff,
0xdead_beef,
// Floats: 1, -1, pi, the infinities, a NaN, and the values about the
// range of a word as singles and as the high words of doubles.
0x3f80_0000,
0xbf80_0000,
0x4049_0fdb,
0x7f80_0000,
0xff80_0000,
0x7fc0_0000,
0x4f00_0000,
0xcf00_0000,
0xcf00_0001,
0x3fe0_0000,
0x3ff0_0000,
0xc1e0_0000,
0xc1e0_0000 | 0x0000_0001,
0x41df_ffff,
0x41e0_0000,
0x0020_0000,
];
#[test]
fn instructions_match_mips_linux() {
if !compiler_available() {
return;
}
matches_mips_linux(false);
}
/// The same with the most significant byte of a word first.
#[test]
fn instructions_match_big_endian_mips_linux() {
if !compiler_available() {
return;
}
matches_mips_linux(true);
}
fn matches_mips_linux(big: bool) {
let scratch = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../..")).join(if big {
"target/mips32-hardware-big"
} else {
"target/mips32-hardware"
});
fs::create_dir_all(&scratch).unwrap();
let cases = cases();
let size = cases.len() * EDGES.len() * EDGES.len() * 4;
let mut source = format!(
".set noreorder\n.set noat\n.text\n.globl __start\n.ent __start\n__start:\nlui $s0, %hi(cases)\naddiu $s0, $s0, %lo(cases)\nlui $s1, %hi(results)\naddiu $s1, $s1, %lo(results)\nli $s2, {}\n",
cases.len()
);
writeln!(
source,
"each_case:\nlw $s3, 0($s0)\nlui $s4, %hi(edges)\naddiu $s4, $s4, %lo(edges)\nli $s5, {count}\neach_left:\nlui $s6, %hi(edges)\naddiu $s6, $s6, %lo(edges)\nli $s7, {count}\neach_right:\nlw $a0, 0($s4)\nlw $a1, 0($s6)\njalr $s3\nnop\nsw $v0, 0($s1)\naddiu $s1, $s1, 4\naddiu $s6, $s6, 4\naddiu $s7, $s7, -1\nbnez $s7, each_right\nnop\naddiu $s4, $s4, 4\naddiu $s5, $s5, -1\nbnez $s5, each_left\nnop\naddiu $s0, $s0, 4\naddiu $s2, $s2, -1\nbnez $s2, each_case\nnop\nlui $s1, %hi(results)\naddiu $s1, $s1, %lo(results)\nli $s2, {size}\nwrite_more:\nli $v0, 4004\nli $a0, 1\nmove $a1, $s1\nmove $a2, $s2\nsyscall\nbnez $a3, done\nnop\nblez $v0, done\nnop\naddu $s1, $s1, $v0\nsubu $s2, $s2, $v0\nbnez $s2, write_more\nnop\ndone:\nli $v0, 4001\nli $a0, 0\nsyscall\n.end __start",
count = EDGES.len()
)
.unwrap();
for (index, code) in cases.iter().enumerate() {
// A case that leaves by itself ends with its own return.
let returns = if code.contains("jr $ra") && !code.ends_with(':') {
""
} else {
"jr $ra\nnop\n"
};
let tail = if code.contains("jr $ra") {
"jr $ra\nnop\n"
} else {
returns
};
writeln!(
source,
".balign 4\n.type case_{index}, %function\ncase_{index}:\n{code}\n{tail}.size case_{index}, .-case_{index}"
)
.unwrap();
}
source.push_str(".section .rodata\n.balign 4\ncases:\n");
for index in 0..cases.len() {
writeln!(source, ".word case_{index}").unwrap();
}
source.push_str("edges:\n");
for edge in EDGES {
writeln!(source, ".word {edge:#x}").unwrap();
}
writeln!(source, ".bss\n.balign 4\nresults: .space {size}").unwrap();
let assembly = scratch.join("cases.s");
let executable = scratch.join("cases.elf");
fs::write(&assembly, source).unwrap();
compile(&assembly, &executable, big);
let Some(output) = run(&scratch, "cases.elf", big) else {
return;
};
assert_eq!(output.len(), size);
let program = vlk_program::program::Program::new(crate::lift::load(&executable).unwrap());
let (results, remainder) = output.as_chunks::<4>();
assert!(remainder.is_empty());
let mut results = results.iter();
let mut compared = 0;
let mut undefined = 0;
let mut differences = Vec::new();
for (index, code) in cases.iter().enumerate() {
let name = format!("case_{index}");
let function = program
.image
.functions
.values()
.find(|function| function.name.as_deref() == Some(&name))
.unwrap();
let mut ir = FunctionIr::single_block(program.image.isa, Vec::new());
ir.big_endian = big;
ir.blocks = match super::lift(
&program,
function.addr,
function.size.unwrap(),
&HashSet::new(),
) {
Ok(blocks) => blocks,
Err(error) => panic!("{code}: not lifted: {error}"),
};
assert_eq!(super::unsupported(&ir), None, "{code}: {}", ir.render());
let mut reported = false;
for left in EDGES {
for right in EDGES {
let expected = if big {
u32::from_be_bytes(*results.next().unwrap())
} else {
u32::from_le_bytes(*results.next().unwrap())
};
// The processor leaves the result of dividing the lowest
// number by minus one undefined.
if code.starts_with("div $") && left == 0x8000_0000 && right == u32::MAX {
undefined += 1;
continue;
}
let registers = [
(2, u64::from(left)),
(3, u64::from(right)),
(vlk_arch::arch::mips32::SP, 0x7fff_0000),
];
match eval::run(&ir, &super::setup(®isters)) {
eval::Outcome::Return { value, .. } if value as u32 == expected => {
compared += 1
}
eval::Outcome::Unknown("division by zero") => undefined += 1,
outcome => {
if !reported {
reported = true;
differences.push(format!(
"{code}\n ({left:#x}, {right:#x}): processor {expected:#x}, IR {outcome:?}\n{}",
ir.render()
));
}
}
}
}
}
}
assert!(
differences.is_empty(),
"{} cases differ\n\n{}",
differences.len(),
differences.join("\n\n")
);
eprintln!(
"{compared} MIPS Linux results agree; {undefined} are divisions the processor or the IR leaves undefined"
);
}