use rucc_base::Interner;
use rucc_ir as ir;
use rucc_mir as mir;
use rucc_regalloc::assign::Env;
use rucc_target::{Arch, BranchInsts, CallRegs, FrameInsts, PhysReg, RegFile, TargetInfo, x86_64};
use crate::expand;
use crate::finish::finish;
use crate::frame::{Frame, Layout};
use crate::layout;
use crate::lower::{self, Unsupported};
use crate::split;
#[derive(Debug)]
pub struct Machine {
pub conv: &'static CallRegs,
pub file: RegFile,
pub insts: &'static FrameInsts,
pub branch: &'static BranchInsts,
pub env: Env,
}
const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
impl Machine {
#[must_use]
pub fn x86_64(conv: &'static CallRegs) -> Self {
let order: Vec<PhysReg> =
conv.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
Self {
conv,
file: x86_64::REGS,
insts: &x86_64::FRAME,
branch: &x86_64::BRANCH,
env: Env::new().with(x86_64::GPR, &order, &SCRATCH),
}
}
#[must_use]
pub fn for_target(target: &TargetInfo) -> Option<Self> {
let conv = target.call_regs?;
match target.triple.arch {
Arch::X86_64 => Some(Self::x86_64(conv)),
Arch::Aarch64 | Arch::Riscv64 => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Flags {
pub frame_pointer: bool,
pub red_zone: bool,
}
impl Default for Flags {
fn default() -> Self {
Self { frame_pointer: false, red_zone: true }
}
}
pub fn compile(
source: &mut ir::Func,
names: &mut Interner,
machine: &Machine,
flags: Flags,
) -> Result<mir::Func, Unsupported> {
expand::switches(source);
let lower::Lowered { mut func, stack } = lower::func(source, names, machine.conv)?;
let layout = Layout {
frame_pointer: flags.frame_pointer,
red_zone: flags.red_zone,
..stack.layout(Layout::new(machine.conv, machine.file))
};
split::critical(&mut func);
let allocation = rucc_regalloc::run(&mut func, &machine.env);
let frame = Frame::of(&func, &allocation, &layout);
finish(&mut func, &allocation, &frame, &stack.addresses, machine.conv, machine.insts, names);
layout::blocks(&mut func, machine.branch, names);
Ok(func)
}
#[cfg(test)]
mod tests {
use rucc_ir::{Builder, Flags as IrFlags, Func, Opcode, Signature, Type};
use rucc_target::x86_64::{REGS, SYSV, WIN64};
use super::*;
fn blank(params: &[Type]) -> (Interner, Func, ir::Block, Vec<ir::Value>) {
let mut names = Interner::new();
let mut func = Func::new(names.intern("f"), Signature::new());
let block = func.create_block();
let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
(names, func, block, values)
}
#[test]
fn a_function_comes_out_with_no_virtual_register_left_in_it() {
let i32 = Type::int(32);
let (mut names, mut source, block, args) = blank(&[i32, i32]);
let mut build = Builder::new(&mut source, block);
let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
build.ret(&[sum]);
let machine = Machine::x86_64(&SYSV);
let out = compile(&mut source, &mut names, &machine, Flags::default())
.expect("every instruction has a rule");
assert_eq!(
mir::print_func(&out, &names, ®S),
"mfunc @f {\n\
block0:\n \
$rdi($rdi) = x64.arg_val_32\n \
$rax = x64.mov_rr_64 $rdi\n \
$rsi($rsi) = x64.arg_val_32\n \
$rcx = x64.mov_rr_64 $rsi\n \
$rdx = x64.mov_rr_64 $rax\n \
$rdx(reuse 1) = x64.add_rr_32 $rax, $rcx\n \
$rax = x64.mov_rr_64 $rdx\n \
x64.ret_val_32 $rax($rax)\n \
x64.ret\n\
}\n"
);
}
#[test]
fn a_function_that_calls_takes_a_frame_and_gives_it_back() {
let i32 = Type::int(32);
let (mut names, mut source, block, args) = blank(&[i32]);
let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
let callee = names.intern("g");
let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
let got = source[call].first_result.expect("an integer comes back");
let mut build = Builder::new(&mut source, block);
let sum = build.binary(Opcode::Add, got, args[0], IrFlags::default());
build.ret(&[sum]);
let machine = Machine::x86_64(&SYSV);
let out = compile(&mut source, &mut names, &machine, Flags::default())
.expect("every instruction has a rule");
let text = mir::print_func(&out, &names, ®S);
assert!(text.contains("x64.push_64 $rbx"), "{text}");
assert!(text.contains("$rbx = x64.pop_64"), "{text}");
assert!(text.contains("x64.call $rdi($rdi), @g"), "{text}");
assert!(!text.contains('%'), "{text}");
}
#[test]
fn the_other_convention_is_the_same_function_somewhere_else() {
let i32 = Type::int(32);
let (mut names, mut source, block, args) = blank(&[i32, i32]);
let mut build = Builder::new(&mut source, block);
let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
build.ret(&[sum]);
let machine = Machine::x86_64(&WIN64);
let out = compile(&mut source, &mut names, &machine, Flags::default())
.expect("every instruction has a rule");
let text = mir::print_func(&out, &names, ®S);
assert!(text.contains("$rcx($rcx) = x64.arg_val_32"), "{text}");
assert!(text.contains("$rdx($rdx) = x64.arg_val_32"), "{text}");
assert!(!text.contains("$rdi"), "{text}");
}
#[test]
fn a_function_with_a_branch_in_it_goes_through_every_pass() {
let i32 = Type::int(32);
let (mut names, mut source, entry, args) = blank(&[i32, i32]);
let then = source.create_block();
let join = source.create_block();
let got = source.append_param(join, i32);
let mut build = Builder::new(&mut source, entry);
let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
build.br_if(cond, then, &[], join, &[args[1]]);
Builder::new(&mut source, then).jump(join, &[args[0]]);
Builder::new(&mut source, join).ret(&[got]);
let machine = Machine::x86_64(&SYSV);
let out = compile(&mut source, &mut names, &machine, Flags::default())
.expect("every instruction has a rule");
assert_eq!(out.block_count(), 4);
let text = mir::print_func(&out, &names, ®S);
assert_eq!(
text,
"mfunc @f {\n\
block0:\n \
$rdi($rdi) = x64.arg_val_32\n \
$rax = x64.mov_rr_64 $rdi\n \
$rsi($rsi) = x64.arg_val_32\n \
$rcx = x64.mov_rr_64 $rsi\n \
$rdx = x64.cmp_set_l_32 $rax, $rcx\n \
x64.test_rr_8 $rdx\n \
x64.jcc_e block2, block1\n\
\nblock1:\n \
$rdx = x64.mov_rr_64 $rax\n \
x64.jmp block3\n\
\nblock2:\n \
$rdx = x64.mov_rr_64 $rcx, block3\n\
\nblock3:\n \
$rax = x64.mov_rr_64 $rdx\n \
x64.ret_val_32 $rax($rax)\n \
x64.ret\n\
}\n"
);
}
#[test]
fn a_loop_that_carries_its_values_round_keeps_all_of_them() {
let i32 = Type::int(32);
let (mut names, mut source, entry, args) = blank(&[i32, i32]);
let head = source.create_block();
let body = source.create_block();
let exit = source.create_block();
let left = source.append_param(head, i32);
let right = source.append_param(head, i32);
Builder::new(&mut source, entry).jump(head, &[args[0], args[1]]);
let mut build = Builder::new(&mut source, head);
let zero = build.iconst(i32, 0);
let more = build.icmp(rucc_ir::IntPred::Ne, right, zero);
build.br_if(more, body, &[], exit, &[left]);
let mut build = Builder::new(&mut source, body);
let rest = build.binary(Opcode::SRem, left, right, IrFlags::default());
build.jump(head, &[right, rest]);
let result = source.append_param(exit, i32);
Builder::new(&mut source, exit).ret(&[result]);
let machine = Machine::x86_64(&SYSV);
let out = compile(&mut source, &mut names, &machine, Flags::default())
.expect("every instruction has a rule");
assert_eq!(
mir::print_func(&out, &names, ®S),
"mfunc @f {\n\
block0:\n \
$rdi($rdi) = x64.arg_val_32\n \
$rax = x64.mov_rr_64 $rdi\n \
$rsi($rsi) = x64.arg_val_32\n \
$rcx = x64.mov_rr_64 $rsi\n \
$rsi = x64.mov_rr_64 $rcx\n \
$rcx = x64.mov_rr_64 $rax, block1\n\
\nblock1:\n \
$rax = x64.mov_ri_32 0\n \
$rax = x64.cmp_set_ne_32 $rsi, $rax\n \
x64.test_rr_8 $rax\n \
x64.jcc_e block3, block2\n\
\nblock2:\n \
$rax = x64.mov_rr_64 $rcx\n \
$rdx($rdx), early $rax($rax) = x64.idiv_rem_32 $rax($rax), $rsi\n \
$rcx = x64.mov_rr_64 $rdx\n \
$rdi = x64.mov_rr_64 $rax\n \
$r10 = x64.mov_rr_64 $rsi\n \
$rsi = x64.mov_rr_64 $rcx\n \
$rcx = x64.mov_rr_64 $r10\n \
x64.jmp block1\n\
\nblock3:\n \
$rax = x64.mov_rr_64 $rcx\n \
x64.ret_val_32 $rax($rax)\n \
x64.ret\n\
}\n"
);
}
#[test]
fn a_function_that_has_been_laid_out_reads_back_as_the_same_function() {
let i32 = Type::int(32);
let (mut names, mut source, entry, args) = blank(&[i32, i32]);
let then = source.create_block();
let join = source.create_block();
let got = source.append_param(join, i32);
let mut build = Builder::new(&mut source, entry);
let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
build.br_if(cond, then, &[], join, &[args[1]]);
Builder::new(&mut source, then).jump(join, &[args[0]]);
Builder::new(&mut source, join).ret(&[got]);
let machine = Machine::x86_64(&SYSV);
let out = compile(&mut source, &mut names, &machine, Flags::default())
.expect("every instruction has a rule");
let text = mir::print_func(&out, &names, ®S);
let read = rucc_mir::parse(&text, &mut names, ®S).expect("what the printer wrote");
assert_eq!(mir::print(&read, &names, ®S), text);
}
#[test]
fn a_function_this_cannot_lower_is_reported_rather_than_compiled() {
let f64 = Type::float(rucc_ir::Float::F64);
let (mut names, mut source, block, args) = blank(&[f64]);
Builder::new(&mut source, block).ret(&[args[0]]);
let machine = Machine::x86_64(&SYSV);
let failed = compile(&mut source, &mut names, &machine, Flags::default())
.expect_err("a double arrives in a vector register");
assert_eq!(failed.to_string(), "parameter 0 is in a vector register");
}
#[test]
fn the_flags_reach_the_frame() {
let i32 = Type::int(32);
let (mut names, mut source, block, args) = blank(&[i32]);
Builder::new(&mut source, block).ret(&[args[0]]);
let machine = Machine::x86_64(&SYSV);
let flags = Flags { frame_pointer: true, red_zone: true };
let out = compile(&mut source, &mut names, &machine, flags)
.expect("every instruction has a rule");
let text = mir::print_func(&out, &names, ®S);
assert!(text.contains("x64.push_64 $rbp"), "{text}");
assert!(text.contains("$rbp = x64.mov_rr_64 $rsp"), "{text}");
}
#[test]
fn a_target_says_which_machine_it_is_and_which_convention_it_uses() {
let triple = |text: &str| text.parse::<rucc_target::Triple>().expect("a triple");
let info = TargetInfo::new(triple("x86_64-unknown-linux-gnu"));
let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
assert!(std::ptr::eq(machine.conv, &SYSV));
let info = TargetInfo::new(triple("x86_64-pc-windows-msvc"));
let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
assert!(std::ptr::eq(machine.conv, &WIN64));
let info = TargetInfo::new(triple("aarch64-unknown-linux-gnu"));
assert!(Machine::for_target(&info).is_none());
}
}