Skip to main content

rucc_codegen/
pipeline.rs

1//! One IR function to one machine function, which is every pass in this crate in order.
2//!
3//! Design: `spec/10-backend.md` section 10.1, which is where the order comes from.
4//!
5//! Each pass here is written and tested on its own and each is useful on its own, but there is
6//! exactly one order they run in and until now that order lived in the tests. A caller outside
7//! this crate would have had to know that splitting critical edges comes after lowering and
8//! before allocation, that the frame is worked out after allocation because the spill slots are
9//! the largest thing in it, and that the prologue is written after the frame. None of that is a
10//! decision a driver should be making, so it is written down once, here.
11//!
12//! # What comes out
13//!
14//! A function whose every register is physical, whose every offset into the frame is a constant,
15//! and whose blocks are in the order they run in with the jumps that order needs. That is the
16//! point at which a function is one an encoder could read, and there is nothing left in it that
17//! is not an instruction of the machine it was compiled for.
18//!
19//! # What is still missing from the middle
20//!
21//! The optimizing path, all of it. What runs here is `spec/10-backend.md` section 10.3's fast
22//! path: one rule per term, a linear scan, and a block order from the shape of the CFG rather
23//! than from block frequency. No scheduling and no peepholes, so the redundant moves a coalescer
24//! would take out are still in the output.
25
26use rucc_base::Interner;
27use rucc_ir as ir;
28use rucc_mir as mir;
29use rucc_regalloc::assign::Env;
30use rucc_target::{Arch, BranchInsts, CallRegs, FrameInsts, PhysReg, RegFile, TargetInfo, x86_64};
31
32use crate::coverage::Fired;
33use crate::expand;
34use crate::finish::finish;
35use crate::frame::{Frame, Layout};
36use crate::layout;
37use crate::lower::{self, Unsupported};
38use crate::split;
39use crate::varargs;
40
41/// Everything about a machine that compiling a function for it needs.
42///
43/// The fields are different kinds of fact and they come from different places: where the
44/// convention puts things, what registers the machine has, which instructions build a frame,
45/// which instructions a branch becomes, and which registers the allocator may hand out. The last
46/// one is not a target fact on its own, because holding a register back as scratch is a decision
47/// about the allocator rather than about the machine, which is why it is built here rather than
48/// in [`rucc_target`].
49#[derive(Debug)]
50pub struct Machine {
51    /// Where the convention this function is compiled for puts things.
52    pub conv: &'static CallRegs,
53    /// The registers the machine has, which is what says how wide a spill slot of a class is.
54    pub file: RegFile,
55    /// The instructions that take a frame and give it back.
56    pub insts: &'static FrameInsts,
57    /// The instructions a branch becomes once the blocks are in an order.
58    pub branch: &'static BranchInsts,
59    /// What the allocator may hand out, and what it holds back.
60    pub env: Env,
61}
62
63/// The scratch registers held back from the allocator on x86-64.
64///
65/// Two, because a move on an edge may have to break a cycle and a spilled value has to be read
66/// into something, and those can want a register at the same instruction. Which two does not
67/// matter. These are the last two the convention would reach for, which is what makes holding
68/// them back cost the least.
69const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
70
71/// How many of each class are held back.
72const SCRATCH_COUNT: usize = SCRATCH.len();
73
74impl Machine {
75    /// The x86-64 machine under that convention.
76    ///
77    /// Both files are offered. A value the selector produces is in one or the other, which is
78    /// decided by its type: an integer and an address are general purpose and a `float` or a
79    /// `double` is in a vector register, and the allocator is given each file separately because
80    /// no move goes between them.
81    #[must_use]
82    pub fn x86_64(conv: &'static CallRegs) -> Self {
83        let order: Vec<PhysReg> =
84            conv.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
85        // The vector file wants its own two, for the same two jobs, and they have to be two the
86        // convention does not preserve: a scratch register is written by a move the rewriter puts
87        // in, which is after the prologue has already been decided, so one the callee owes back
88        // would be one nothing saved. That rules out the upper ten on Windows and nothing at all
89        // on SysV, and taking the last two that are left lands on `xmm14` and `xmm15` there and on
90        // `xmm4` and `xmm5` on Windows, neither of which any argument travels in.
91        let free: Vec<PhysReg> =
92            conv.sse_order.iter().copied().filter(|&reg| !conv.preserves_sse(reg)).collect();
93        let at = free.len().saturating_sub(SCRATCH_COUNT);
94        let sse_scratch: Vec<PhysReg> = free[at..].to_vec();
95        let sse_order: Vec<PhysReg> =
96            conv.sse_order.iter().copied().filter(|reg| !sse_scratch.contains(reg)).collect();
97        Self {
98            conv,
99            file: x86_64::REGS,
100            insts: &x86_64::FRAME,
101            branch: &x86_64::BRANCH,
102            env: Env::new().with(x86_64::GPR, &order, &SCRATCH).with(
103                x86_64::XMM,
104                &sse_order,
105                &sse_scratch,
106            ),
107        }
108    }
109
110    /// The machine a target describes, or `None` when no backend in this crate covers it.
111    ///
112    /// [`TargetInfo`] already carries the convention, because the front end needs it to lay a
113    /// `va_list` out, so the only thing this decides is which architecture's frame instructions
114    /// and register file go with it. AArch64 and RISC-V are `None` until M6 fills them in, and a
115    /// caller that gets one reports a target it cannot compile for rather than compiling wrongly.
116    #[must_use]
117    pub fn for_target(target: &TargetInfo) -> Option<Self> {
118        let conv = target.call_regs?;
119        match target.triple.arch {
120            Arch::X86_64 => Some(Self::x86_64(conv)),
121            Arch::Aarch64 | Arch::Riscv64 => None,
122        }
123    }
124}
125
126/// What the command line says about a frame, as opposed to what the machine says.
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub struct Flags {
129    /// Whether every function keeps a frame pointer, which `-fno-omit-frame-pointer` asks for.
130    pub frame_pointer: bool,
131    /// Whether the red zone may be used, which `-mno-red-zone` and every kernel turns off.
132    pub red_zone: bool,
133}
134
135impl Default for Flags {
136    /// No frame pointer and the red zone allowed, which is what a convention that has one says
137    /// when nobody on the command line has said otherwise.
138    fn default() -> Self {
139        Self { frame_pointer: false, red_zone: true }
140    }
141}
142
143/// Compiles one function, from the IR the middle end produced to machine instructions.
144///
145/// The function is taken by reference that can be written through, because the first pass is an
146/// IR to IR rewrite: a construct whose lowering is a new shape of control flow cannot be a rule,
147/// since a rule replaces a term with a term and has nowhere to put a block. So the IR that reaches
148/// selection is not quite the IR the middle end produced, and this is the only place that is true.
149/// `--emit=ir` prints before any of this runs.
150///
151/// # Errors
152///
153/// The first thing in it this cannot lower, which is what [`lower::func`] reports and is the only
154/// pass here that can refuse a function. Everything after lowering works on machine instructions
155/// that exist, so it either runs or it is a bug in this crate.
156pub fn compile(
157    source: &mut ir::Func,
158    names: &mut Interner,
159    machine: &Machine,
160    flags: Flags,
161) -> Result<mir::Func, Unsupported> {
162    compile_recording(source, names, machine, flags, &mut Fired::new())
163}
164
165/// The same compilation, with the lowering rules it fired recorded into `fired`.
166///
167/// Two functions rather than one that takes an option, because a caller that does not want the
168/// number should not have to say so. What `fired` is for is `-Zrule-coverage`, which is how the
169/// harness in `tamnd/rucc-compat` turns coverage of the rule set into a number over a corpus.
170///
171/// It is merged into rather than replaced, so a caller can pass the same one for every function of
172/// a module and every module of a command line and get the answer for all of them.
173///
174/// # Errors
175///
176/// The same as [`compile`]. A function that was refused contributes nothing, since a function that
177/// did not compile is not evidence that anything covered it.
178pub fn compile_recording(
179    source: &mut ir::Func,
180    names: &mut Interner,
181    machine: &Machine,
182    flags: Flags,
183    fired: &mut Fired,
184) -> Result<mir::Func, Unsupported> {
185    expand::switches(source);
186    expand::floats(source);
187    expand::bulk(source, names, machine.conv.word);
188    varargs::lists(source, machine.conv);
189    let lowered = lower::func(source, names, machine.conv)?;
190    fired.merge(&lowered.fired);
191    let lower::Lowered { mut func, stack, .. } = lowered;
192    let layout = Layout {
193        frame_pointer: flags.frame_pointer,
194        red_zone: flags.red_zone,
195        ..stack.layout(Layout::new(machine.conv, machine.file))
196    };
197
198    // Before allocation, because an edge that carries values into a block arrived at more than
199    // one way, out of a block that leaves more than one way, has nowhere to put the moves those
200    // values turn into, and the allocator asserts rather than guessing.
201    split::critical(&mut func);
202    let allocation = rucc_regalloc::run(&mut func, &machine.env);
203
204    // After allocation, because the largest area in most frames is the spill slots and nothing
205    // knows how many of those there are until the allocator has finished running out of registers.
206    let frame = Frame::of(&func, &allocation, &layout);
207    finish(&mut func, &allocation, &frame, &stack, machine.conv, machine.insts, names);
208
209    // Last, because everything before this finds the blocks a function returns from by looking
210    // for the ones that go nowhere, and after this a block that falls through goes nowhere too.
211    layout::blocks(&mut func, machine.branch, names);
212    Ok(func)
213}
214
215#[cfg(test)]
216mod tests {
217    use rucc_ir::{Builder, Flags as IrFlags, Func, Opcode, Signature, Type};
218    use rucc_target::x86_64::{REGS, SYSV, WIN64};
219
220    use super::*;
221
222    /// A function of two integers, and the block to fill.
223    fn blank(params: &[Type]) -> (Interner, Func, ir::Block, Vec<ir::Value>) {
224        let mut names = Interner::new();
225        let mut func = Func::new(names.intern("f"), Signature::new());
226        let block = func.create_block();
227        let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
228        (names, func, block, values)
229    }
230
231    #[test]
232    fn a_function_comes_out_with_no_virtual_register_left_in_it() {
233        let i32 = Type::int(32);
234        let (mut names, mut source, block, args) = blank(&[i32, i32]);
235        let mut build = Builder::new(&mut source, block);
236        let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
237        build.ret(&[sum]);
238
239        let machine = Machine::x86_64(&SYSV);
240        let out = compile(&mut source, &mut names, &machine, Flags::default())
241            .expect("every instruction has a rule");
242
243        // `int f(int a, int b) { return a + b; }` end to end. A leaf that spills nothing needs no
244        // frame at all, so there is no prologue to see. The one move left is the one the machine's
245        // addition needs, since the sum is written into the register the left operand was read
246        // from and the return wants it in `rax`.
247        assert_eq!(
248            mir::print_func(&out, &names, &REGS),
249            "mfunc @f {\n\
250             block0:\n    \
251             $rdi($rdi) = x64.arg_val_32\n    \
252             $rsi($rsi) = x64.arg_val_32\n    \
253             $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n    \
254             $rax = x64.mov_rr_64 $rdi\n    \
255             x64.ret_val_32 $rax($rax)\n    \
256             x64.ret\n\
257             }\n"
258        );
259    }
260
261    /// What `-Zrule-coverage` is built out of: the rules a compilation fired, recorded as it went.
262    /// The second function adds to the first rather than replacing it, which is what makes one of
263    /// these files the answer for a whole command line rather than for whichever function was last.
264    #[test]
265    fn which_rules_lowered_a_function_is_something_the_compilation_can_be_asked_for() {
266        let i32 = Type::int(32);
267        let (mut names, mut source, block, args) = blank(&[i32, i32]);
268        let mut build = Builder::new(&mut source, block);
269        let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
270        build.ret(&[sum]);
271
272        let machine = Machine::x86_64(&SYSV);
273        let mut fired = Fired::new();
274        compile_recording(&mut source, &mut names, &machine, Flags::default(), &mut fired)
275            .expect("every instruction has a rule");
276        let one = fired.count();
277        assert!(one > 0, "an add and a return went through the table and nothing was recorded");
278
279        let listing = fired.listing(&crate::select::x86_64::TABLE);
280        assert_eq!(listing.lines().filter(|line| line.starts_with("fired ")).count(), one);
281        assert!(
282            listing.contains(&format!("{one} of ")),
283            "{}",
284            listing.lines().next().unwrap_or("")
285        );
286
287        // The same rules again plus the ones a subtraction needs, into the same record.
288        let (mut names, mut source, block, args) = blank(&[i32, i32]);
289        let mut build = Builder::new(&mut source, block);
290        let difference = build.binary(Opcode::Sub, args[0], args[1], IrFlags::default());
291        build.ret(&[difference]);
292        compile_recording(&mut source, &mut names, &machine, Flags::default(), &mut fired)
293            .expect("every instruction has a rule");
294        assert!(fired.count() > one, "a subtraction is not an addition");
295    }
296
297    #[test]
298    fn a_function_that_calls_takes_a_frame_and_gives_it_back() {
299        let i32 = Type::int(32);
300        let (mut names, mut source, block, args) = blank(&[i32]);
301        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
302        let callee = names.intern("g");
303        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
304        let got = source[call].first_result.expect("an integer comes back");
305        let mut build = Builder::new(&mut source, block);
306        let sum = build.binary(Opcode::Add, got, args[0], IrFlags::default());
307        build.ret(&[sum]);
308
309        let machine = Machine::x86_64(&SYSV);
310        let out = compile(&mut source, &mut names, &machine, Flags::default())
311            .expect("every instruction has a rule");
312
313        // `int f(int a) { return g(a) + a; }`. Not a leaf, so the stack pointer moves and the
314        // register the value that outlives the call went to is one the prologue saves.
315        let text = mir::print_func(&out, &names, &REGS);
316        assert!(text.contains("x64.push_64 $rbx"), "{text}");
317        assert!(text.contains("$rbx = x64.pop_64"), "{text}");
318        assert!(text.contains("x64.call $rdi($rdi), @g"), "{text}");
319        assert!(!text.contains('%'), "{text}");
320    }
321
322    #[test]
323    fn the_other_convention_is_the_same_function_somewhere_else() {
324        let i32 = Type::int(32);
325        let (mut names, mut source, block, args) = blank(&[i32, i32]);
326        let mut build = Builder::new(&mut source, block);
327        let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
328        build.ret(&[sum]);
329
330        let machine = Machine::x86_64(&WIN64);
331        let out = compile(&mut source, &mut names, &machine, Flags::default())
332            .expect("every instruction has a rule");
333
334        // The arguments arrive in `rcx` and `rdx` here rather than in `rdi` and `rsi`, which is
335        // the whole of what changed, and it changed because the convention was asked.
336        let text = mir::print_func(&out, &names, &REGS);
337        assert!(text.contains("$rcx($rcx) = x64.arg_val_32"), "{text}");
338        assert!(text.contains("$rdx($rdx) = x64.arg_val_32"), "{text}");
339        assert!(!text.contains("$rdi"), "{text}");
340    }
341
342    #[test]
343    fn a_function_with_a_branch_in_it_goes_through_every_pass() {
344        let i32 = Type::int(32);
345        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
346        let then = source.create_block();
347        let join = source.create_block();
348        let got = source.append_param(join, i32);
349        let mut build = Builder::new(&mut source, entry);
350        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
351        build.br_if(cond, then, &[], join, &[args[1]]);
352        Builder::new(&mut source, then).jump(join, &[args[0]]);
353        Builder::new(&mut source, join).ret(&[got]);
354
355        let machine = Machine::x86_64(&SYSV);
356        let out = compile(&mut source, &mut names, &machine, Flags::default())
357            .expect("every instruction has a rule");
358
359        // The else arm is a critical edge carrying a value, so a block that nothing lowered is in
360        // there, which is the pass between lowering and allocation doing its job. Without it the
361        // allocator would have asserted rather than compiled this.
362        assert_eq!(out.block_count(), 4);
363
364        // `int f(int a, int b) { return a < b ? a : b; }` end to end, and the last pass is what
365        // this pins. The branch became a test and one jump, and it is the jump taken when the
366        // condition failed, because the arm the condition is true for is the block laid out next
367        // and a block falls into the block laid out next. The other arm is the empty block the
368        // edge splitting left, which is where the move the edge carries ended up, and it falls
369        // into the join as well. What is left is one jump in the whole function. Both arms write
370        // the join's parameter straight into `rax`, because the return at the bottom insists on
371        // that register and the moves the edges carry are free to name it.
372        let text = mir::print_func(&out, &names, &REGS);
373        assert_eq!(
374            text,
375            "mfunc @f {\n\
376             block0:\n    \
377             $rdi($rdi) = x64.arg_val_32\n    \
378             $rsi($rsi) = x64.arg_val_32\n    \
379             $rax = x64.cmp_set_l_32 $rdi, $rsi\n    \
380             x64.test_rr_8 $rax\n    \
381             x64.jcc_e block2, block1\n\
382             \nblock1:\n    \
383             $rax = x64.mov_rr_64 $rdi\n    \
384             x64.jmp block3\n\
385             \nblock2:\n    \
386             $rax = x64.mov_rr_64 $rsi, block3\n\
387             \nblock3:\n    \
388             x64.ret_val_32 $rax($rax)\n    \
389             x64.ret\n\
390             }\n"
391        );
392    }
393
394    /// A loop that swaps its two values round every time it goes, which is `gcd`, and which is
395    /// the smallest program that caught two ways of losing a value. Both were found by running
396    /// what came out rather than by reading it, and both are pinned here rather than only where
397    /// they were fixed, because what is wrong with either of them is only visible in the whole
398    /// function.
399    #[test]
400    fn a_loop_that_carries_its_values_round_keeps_all_of_them() {
401        let i32 = Type::int(32);
402        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
403        let head = source.create_block();
404        let body = source.create_block();
405        let exit = source.create_block();
406        let left = source.append_param(head, i32);
407        let right = source.append_param(head, i32);
408        Builder::new(&mut source, entry).jump(head, &[args[0], args[1]]);
409        let mut build = Builder::new(&mut source, head);
410        let zero = build.iconst(i32, 0);
411        let more = build.icmp(rucc_ir::IntPred::Ne, right, zero);
412        build.br_if(more, body, &[], exit, &[left]);
413        let mut build = Builder::new(&mut source, body);
414        let rest = build.binary(Opcode::SRem, left, right, IrFlags::default());
415        build.jump(head, &[right, rest]);
416        let result = source.append_param(exit, i32);
417        Builder::new(&mut source, exit).ret(&[result]);
418
419        let machine = Machine::x86_64(&SYSV);
420        let out = compile(&mut source, &mut names, &machine, Flags::default())
421            .expect("every instruction has a rule");
422
423        // `int gcd(int a, int b) { while (b) { int t = a % b; a = b; b = t; } return a; }`. Two
424        // things in here were wrong and each of them returned three from a program that gcc
425        // returns forty two from.
426        //
427        // The first is in the entry block. The move the edge into the loop asks for writes `rsi`,
428        // and the second argument has to be taken out of `rsi` before it does. An edit at the end
429        // of a block used to go in front of the last instruction, on the reasoning that the last
430        // instruction is the branch, and the block's jump is not an instruction until the layout
431        // has run, so it went in front of the `arg_val` whose own move had not been made yet.
432        //
433        // The second is in the loop body. A division writes both a quotient and a remainder, and
434        // only the remainder is wanted here, so the quotient is a value nothing reads. It used to
435        // be given the same register as the remainder, because a value written early was live at
436        // one point and that point is in front of where the remainder is written. The copy that
437        // takes the quotient nowhere then landed on top of the remainder.
438        assert_eq!(
439            mir::print_func(&out, &names, &REGS),
440            "mfunc @f {\n\
441             block0:\n    \
442             $rdi($rdi) = x64.arg_val_32\n    \
443             $rsi($rsi) = x64.arg_val_32\n    \
444             $rcx = x64.mov_rr_64 $rdi, block1\n\
445             \nblock1:\n    \
446             $rax = x64.mov_ri_32 0\n    \
447             $rax = x64.cmp_set_ne_32 $rsi, $rax\n    \
448             x64.test_rr_8 $rax\n    \
449             x64.jcc_e block3, block2\n\
450             \nblock2:\n    \
451             $rax = x64.mov_rr_64 $rcx\n    \
452             $rdx($rdx), early $rax($rax) = x64.idiv_rem_32 $rax($rax), $rsi\n    \
453             $rdi = x64.mov_rr_64 $rax\n    \
454             $rcx = x64.mov_rr_64 $rsi\n    \
455             $rsi = x64.mov_rr_64 $rdx\n    \
456             x64.jmp block1\n\
457             \nblock3:\n    \
458             $rax = x64.mov_rr_64 $rcx\n    \
459             x64.ret_val_32 $rax($rax)\n    \
460             x64.ret\n\
461             }\n"
462        );
463    }
464
465    /// `spec/10-backend.md` section 10.1 says `--emit=mir-final` round-trips, and a function with
466    /// a branch in it is the one where that is worth checking: after the layout has run, where a
467    /// jump goes is nowhere in the instruction, so the text has to carry it on the block and the
468    /// parser has to put it back on the block it came off.
469    #[test]
470    fn a_function_that_has_been_laid_out_reads_back_as_the_same_function() {
471        let i32 = Type::int(32);
472        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
473        let then = source.create_block();
474        let join = source.create_block();
475        let got = source.append_param(join, i32);
476        let mut build = Builder::new(&mut source, entry);
477        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
478        build.br_if(cond, then, &[], join, &[args[1]]);
479        Builder::new(&mut source, then).jump(join, &[args[0]]);
480        Builder::new(&mut source, join).ret(&[got]);
481
482        let machine = Machine::x86_64(&SYSV);
483        let out = compile(&mut source, &mut names, &machine, Flags::default())
484            .expect("every instruction has a rule");
485
486        let text = mir::print_func(&out, &names, &REGS);
487        let read = rucc_mir::parse(&text, &mut names, &REGS).expect("what the printer wrote");
488        assert_eq!(mir::print(&read, &names, &REGS), text);
489    }
490
491    #[test]
492    fn a_function_this_cannot_lower_is_reported_rather_than_compiled() {
493        let f80 = Type::float(rucc_ir::Float::F80);
494        let (mut names, mut source, block, args) = blank(&[f80]);
495        Builder::new(&mut source, block).ret(&[args[0]]);
496
497        let machine = Machine::x86_64(&SYSV);
498        let failed = compile(&mut source, &mut names, &machine, Flags::default())
499            .expect_err("a long double arrives on the x87 stack");
500        assert_eq!(failed.to_string(), "parameter 0 is on the x87 stack");
501    }
502
503    /// The whole of the second register class, end to end: two floats arrive in vector registers,
504    /// the arithmetic happens in one, and the answer goes back in the register the convention
505    /// names. Nothing here touches the general purpose file, which is the point.
506    #[test]
507    fn a_float_is_added_in_the_register_file_it_arrives_in() {
508        let f32 = Type::float(rucc_ir::Float::F32);
509        let (mut names, mut source, block, args) = blank(&[f32, f32]);
510        let mut build = Builder::new(&mut source, block);
511        let sum = build.binary(Opcode::FAdd, args[0], args[1], ir::Flags::default());
512        build.ret(&[sum]);
513
514        let machine = Machine::x86_64(&SYSV);
515        let out = compile(&mut source, &mut names, &machine, Flags::default())
516            .expect("every instruction has a rule");
517
518        let text = mir::print_func(&out, &names, &REGS);
519        assert!(text.contains("x64.addss_rr"), "{text}");
520        assert!(text.contains("$xmm0"), "{text}");
521        assert!(!text.contains("$rax"), "{text}");
522    }
523
524    /// A float moved between a register and memory, which is the instruction that decides which
525    /// file the value is in and is a different one from the `mov` that moves the same four bytes.
526    #[test]
527    fn a_float_read_from_memory_and_written_back_uses_the_scalar_moves() {
528        let f64 = Type::float(rucc_ir::Float::F64);
529        let (mut names, mut source, block, args) = blank(&[Type::PTR, f64]);
530        let mut build = Builder::new(&mut source, block);
531        let info =
532            rucc_ir::MemInfo { size: 8, align: 8, order: rucc_ir::MemOrder::NotAtomic, tbaa: None };
533        let read = build.load(f64, args[0], info, ir::Flags::default());
534        let sum = build.binary(Opcode::FAdd, read, args[1], ir::Flags::default());
535        build.store(sum, args[0], info, ir::Flags::default());
536        build.ret(&[sum]);
537
538        let machine = Machine::x86_64(&SYSV);
539        let out = compile(&mut source, &mut names, &machine, Flags::default())
540            .expect("every instruction has a rule");
541
542        let text = mir::print_func(&out, &names, &REGS);
543        assert!(text.contains("x64.movsd_rm"), "{text}");
544        assert!(text.contains("x64.movsd_mr"), "{text}");
545        // Not the aligned whole register move, which is what a spill uses and is the one
546        // instruction here that would read and write more than the program asked for.
547        assert!(!text.contains("x64.movaps_rm"), "{text}");
548        assert!(!text.contains("x64.movaps_mr"), "{text}");
549    }
550
551    /// A value carried from one register file to the other, which is what a conversion is. The
552    /// instruction reads one file and writes the other, and the allocator has to know that: a
553    /// conversion whose operands were both said to be in one file would put the answer in a
554    /// register the next instruction cannot reach.
555    #[test]
556    fn a_conversion_carries_the_value_into_the_other_register_file() {
557        let f64 = Type::float(rucc_ir::Float::F64);
558        let (mut names, mut source, block, args) = blank(&[f64]);
559        let mut build = Builder::new(&mut source, block);
560        let whole = build.unary(Opcode::FPToSI, args[0], Type::int(32));
561        let back = build.unary(Opcode::SIToFP, whole, f64);
562        build.ret(&[back]);
563
564        let machine = Machine::x86_64(&SYSV);
565        let out = compile(&mut source, &mut names, &machine, Flags::default())
566            .expect("every instruction has a rule");
567
568        // The conversion that cuts towards zero rather than the one that rounds, which is what C
569        // means by the cast, and the argument and the answer in the register the convention names.
570        let text = mir::print_func(&out, &names, &REGS);
571        assert!(text.contains("x64.cvttsd2si_32"), "{text}");
572        assert!(text.contains("x64.cvtsi2sd_32"), "{text}");
573        assert!(text.contains("$xmm0"), "{text}");
574    }
575
576    /// The other way of putting a float and a number together, which keeps every bit rather than
577    /// the value and is what a program reading the bits of a `double` asks for.
578    #[test]
579    fn a_bitcast_between_the_files_is_the_move_that_changes_no_bit() {
580        let f64 = Type::float(rucc_ir::Float::F64);
581        let (mut names, mut source, block, args) = blank(&[f64]);
582        let mut build = Builder::new(&mut source, block);
583        let bits = build.unary(Opcode::Bitcast, args[0], Type::int(64));
584        build.ret(&[bits]);
585
586        let machine = Machine::x86_64(&SYSV);
587        let out = compile(&mut source, &mut names, &machine, Flags::default())
588            .expect("every instruction has a rule");
589
590        let text = mir::print_func(&out, &names, &REGS);
591        assert!(text.contains("x64.movq_from_xmm"), "{text}");
592        assert!(!text.contains("cvt"), "{text}");
593    }
594
595    /// A comparison whose answer the machine has a condition for, which is most of them.
596    #[test]
597    fn a_float_comparison_is_the_compare_and_the_byte_a_condition_sets() {
598        let f64 = Type::float(rucc_ir::Float::F64);
599        let (mut names, mut source, block, args) = blank(&[f64, f64]);
600        let mut build = Builder::new(&mut source, block);
601        let less = build.fcmp(rucc_ir::FloatPred::Olt, args[0], args[1], ir::Flags::default());
602        let wide = build.unary(Opcode::ZExt, less, Type::int(32));
603        build.ret(&[wide]);
604
605        let machine = Machine::x86_64(&SYSV);
606        let out = compile(&mut source, &mut names, &machine, Flags::default())
607            .expect("every instruction has a rule");
608
609        // Less than is greater than with the operands the other way round, and the machine has no
610        // condition for the first, so the rule that fires is the one that swaps them.
611        let text = mir::print_func(&out, &names, &REGS);
612        assert!(text.contains("x64.ucomisd_set_a"), "{text}");
613    }
614
615    /// The two comparisons that are not one condition. An ordered equality is the flag that means
616    /// equal or unordered and the flag that says it was ordered, so the instruction writes a
617    /// second byte and reads it back, and what this is about is that the second byte gets a
618    /// register of its own rather than the one the answer is in.
619    #[test]
620    fn an_equality_between_floats_gets_a_register_for_the_byte_it_needs_twice() {
621        let f64 = Type::float(rucc_ir::Float::F64);
622        let (mut names, mut source, block, args) = blank(&[f64, f64]);
623        let mut build = Builder::new(&mut source, block);
624        let same = build.fcmp(rucc_ir::FloatPred::Oeq, args[0], args[1], ir::Flags::default());
625        let wide = build.unary(Opcode::ZExt, same, Type::int(32));
626        build.ret(&[wide]);
627
628        let machine = Machine::x86_64(&SYSV);
629        let out = compile(&mut source, &mut names, &machine, Flags::default())
630            .expect("every instruction has a rule");
631
632        let text = mir::print_func(&out, &names, &REGS);
633        let line = text
634            .lines()
635            .find(|line| line.contains("x64.ucomisd_set_e_and_np"))
636            .expect("the rule for an ordered equality fired");
637        let written: Vec<&str> = line
638            .split_once('=')
639            .expect("the instruction writes something")
640            .0
641            .split(',')
642            .map(str::trim)
643            .collect();
644        assert_eq!(written.len(), 2, "{line}");
645        assert_ne!(written[0], written[1], "{line}");
646    }
647
648    /// A float literal, which is the last float thing a C program writes that had no lowering.
649    /// The rewrite that puts it in reach is in `expand`, and what this is about is that the two
650    /// halves meet: the constant is spelled in a general purpose register and moved across.
651    #[test]
652    fn a_float_constant_is_the_bits_in_a_register_and_the_move_that_carries_them_over() {
653        let f64 = Type::float(rucc_ir::Float::F64);
654        let (mut names, mut source, block, _) = blank(&[]);
655        let mut build = Builder::new(&mut source, block);
656        let half = build.fconst(f64, 0x3fe0_0000_0000_0000);
657        build.ret(&[half]);
658
659        let machine = Machine::x86_64(&SYSV);
660        let out = compile(&mut source, &mut names, &machine, Flags::default())
661            .expect("every instruction has a rule");
662
663        let text = mir::print_func(&out, &names, &REGS);
664        assert!(text.contains("x64.mov_ri_64"), "{text}");
665        assert!(text.contains("x64.movq_to_xmm"), "{text}");
666    }
667
668    /// A negation, which is the sign bit flipped and nothing else touched, so what the machine
669    /// does is an exclusive or in a general purpose register rather than any float instruction.
670    #[test]
671    fn a_negation_is_the_sign_bit_flipped_and_no_float_instruction_at_all() {
672        let f64 = Type::float(rucc_ir::Float::F64);
673        let (mut names, mut source, block, args) = blank(&[f64]);
674        let mut build = Builder::new(&mut source, block);
675        let less = build.unary(Opcode::FNeg, args[0], f64);
676        build.ret(&[less]);
677
678        let machine = Machine::x86_64(&SYSV);
679        let out = compile(&mut source, &mut names, &machine, Flags::default())
680            .expect("every instruction has a rule");
681
682        let text = mir::print_func(&out, &names, &REGS);
683        assert!(text.contains("x64.xor_rr_64"), "{text}");
684        assert!(!text.contains("sub"), "a negation is not a subtraction: {text}");
685    }
686
687    #[test]
688    fn the_flags_reach_the_frame() {
689        let i32 = Type::int(32);
690        let (mut names, mut source, block, args) = blank(&[i32]);
691        Builder::new(&mut source, block).ret(&[args[0]]);
692
693        let machine = Machine::x86_64(&SYSV);
694        let flags = Flags { frame_pointer: true, red_zone: true };
695        let out = compile(&mut source, &mut names, &machine, flags)
696            .expect("every instruction has a rule");
697
698        // A function that keeps a frame pointer keeps it whether it needed one or not, which is
699        // what `-fno-omit-frame-pointer` is for and is the only thing this test is about.
700        let text = mir::print_func(&out, &names, &REGS);
701        assert!(text.contains("x64.push_64 $rbp"), "{text}");
702        assert!(text.contains("$rbp = x64.mov_rr_64 $rsp"), "{text}");
703    }
704
705    #[test]
706    fn a_target_says_which_machine_it_is_and_which_convention_it_uses() {
707        let triple = |text: &str| text.parse::<rucc_target::Triple>().expect("a triple");
708        let info = TargetInfo::new(triple("x86_64-unknown-linux-gnu"));
709        let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
710        assert!(std::ptr::eq(machine.conv, &SYSV));
711
712        let info = TargetInfo::new(triple("x86_64-pc-windows-msvc"));
713        let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
714        assert!(std::ptr::eq(machine.conv, &WIN64));
715
716        // Not a target this crate has a backend for, and saying so is the whole point: a caller
717        // that got a machine here would compile x86-64 instructions for an AArch64 program.
718        let info = TargetInfo::new(triple("aarch64-unknown-linux-gnu"));
719        assert!(Machine::for_target(&info).is_none());
720    }
721}