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::finish::finish;
33use crate::frame::{Frame, Layout};
34use crate::layout;
35use crate::lower::{self, Unsupported};
36use crate::split;
37
38/// Everything about a machine that compiling a function for it needs.
39///
40/// The fields are different kinds of fact and they come from different places: where the
41/// convention puts things, what registers the machine has, which instructions build a frame,
42/// which instructions a branch becomes, and which registers the allocator may hand out. The last
43/// one is not a target fact on its own, because holding a register back as scratch is a decision
44/// about the allocator rather than about the machine, which is why it is built here rather than
45/// in [`rucc_target`].
46#[derive(Debug)]
47pub struct Machine {
48    /// Where the convention this function is compiled for puts things.
49    pub conv: &'static CallRegs,
50    /// The registers the machine has, which is what says how wide a spill slot of a class is.
51    pub file: RegFile,
52    /// The instructions that take a frame and give it back.
53    pub insts: &'static FrameInsts,
54    /// The instructions a branch becomes once the blocks are in an order.
55    pub branch: &'static BranchInsts,
56    /// What the allocator may hand out, and what it holds back.
57    pub env: Env,
58}
59
60/// The scratch registers held back from the allocator on x86-64.
61///
62/// Two, because a move on an edge may have to break a cycle and a spilled value has to be read
63/// into something, and those can want a register at the same instruction. Which two does not
64/// matter. These are the last two the convention would reach for, which is what makes holding
65/// them back cost the least.
66const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
67
68impl Machine {
69    /// The x86-64 machine under that convention.
70    ///
71    /// Only the general purpose registers are offered, because every rule in the set is about an
72    /// integer and no value the selector produces is in any other class. A call still destroys the
73    /// vector registers and still says so, and that costs nothing while nothing is in one.
74    #[must_use]
75    pub fn x86_64(conv: &'static CallRegs) -> Self {
76        let order: Vec<PhysReg> =
77            conv.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
78        Self {
79            conv,
80            file: x86_64::REGS,
81            insts: &x86_64::FRAME,
82            branch: &x86_64::BRANCH,
83            env: Env::new().with(x86_64::GPR, &order, &SCRATCH),
84        }
85    }
86
87    /// The machine a target describes, or `None` when no backend in this crate covers it.
88    ///
89    /// [`TargetInfo`] already carries the convention, because the front end needs it to lay a
90    /// `va_list` out, so the only thing this decides is which architecture's frame instructions
91    /// and register file go with it. AArch64 and RISC-V are `None` until M6 fills them in, and a
92    /// caller that gets one reports a target it cannot compile for rather than compiling wrongly.
93    #[must_use]
94    pub fn for_target(target: &TargetInfo) -> Option<Self> {
95        let conv = target.call_regs?;
96        match target.triple.arch {
97            Arch::X86_64 => Some(Self::x86_64(conv)),
98            Arch::Aarch64 | Arch::Riscv64 => None,
99        }
100    }
101}
102
103/// What the command line says about a frame, as opposed to what the machine says.
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub struct Flags {
106    /// Whether every function keeps a frame pointer, which `-fno-omit-frame-pointer` asks for.
107    pub frame_pointer: bool,
108    /// Whether the red zone may be used, which `-mno-red-zone` and every kernel turns off.
109    pub red_zone: bool,
110}
111
112impl Default for Flags {
113    /// No frame pointer and the red zone allowed, which is what a convention that has one says
114    /// when nobody on the command line has said otherwise.
115    fn default() -> Self {
116        Self { frame_pointer: false, red_zone: true }
117    }
118}
119
120/// Compiles one function, from the IR the middle end produced to machine instructions.
121///
122/// # Errors
123///
124/// The first thing in it this cannot lower, which is what [`lower::func`] reports and is the only
125/// pass here that can refuse a function. Everything after lowering works on machine instructions
126/// that exist, so it either runs or it is a bug in this crate.
127pub fn compile(
128    source: &ir::Func,
129    names: &mut Interner,
130    machine: &Machine,
131    flags: Flags,
132) -> Result<mir::Func, Unsupported> {
133    let lowered = lower::func(source, names, machine.conv)?;
134    let stack = Layout {
135        frame_pointer: flags.frame_pointer,
136        red_zone: flags.red_zone,
137        ..lowered.layout(Layout::new(machine.conv, machine.file))
138    };
139    let mut func = lowered.func;
140
141    // Before allocation, because an edge that carries values into a block arrived at more than
142    // one way, out of a block that leaves more than one way, has nowhere to put the moves those
143    // values turn into, and the allocator asserts rather than guessing.
144    split::critical(&mut func);
145    let allocation = rucc_regalloc::run(&mut func, &machine.env);
146
147    // After allocation, because the largest area in most frames is the spill slots and nothing
148    // knows how many of those there are until the allocator has finished running out of registers.
149    let frame = Frame::of(&func, &allocation, &stack);
150    finish(&mut func, &allocation, &frame, machine.conv, machine.insts, names);
151
152    // Last, because everything before this finds the blocks a function returns from by looking
153    // for the ones that go nowhere, and after this a block that falls through goes nowhere too.
154    layout::blocks(&mut func, machine.branch, names);
155    Ok(func)
156}
157
158#[cfg(test)]
159mod tests {
160    use rucc_ir::{Builder, Flags as IrFlags, Func, Opcode, Signature, Type};
161    use rucc_target::x86_64::{REGS, SYSV, WIN64};
162
163    use super::*;
164
165    /// A function of two integers, and the block to fill.
166    fn blank(params: &[Type]) -> (Interner, Func, ir::Block, Vec<ir::Value>) {
167        let mut names = Interner::new();
168        let mut func = Func::new(names.intern("f"), Signature::new());
169        let block = func.create_block();
170        let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
171        (names, func, block, values)
172    }
173
174    #[test]
175    fn a_function_comes_out_with_no_virtual_register_left_in_it() {
176        let i32 = Type::int(32);
177        let (mut names, mut source, block, args) = blank(&[i32, i32]);
178        let mut build = Builder::new(&mut source, block);
179        let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
180        build.ret(&[sum]);
181
182        let machine = Machine::x86_64(&SYSV);
183        let out = compile(&source, &mut names, &machine, Flags::default())
184            .expect("every instruction has a rule");
185
186        // `int f(int a, int b) { return a + b; }` end to end. A leaf that spills nothing needs no
187        // frame at all, so there is no prologue to see. The moves in the middle are all copies
188        // between registers that could have been the same register, which is what a coalescer
189        // would take out and there is not one yet, see issue 255.
190        assert_eq!(
191            mir::print_func(&out, &names, &REGS),
192            "mfunc @f {\n\
193             block0:\n    \
194             $rdi($rdi) = x64.arg_val_32\n    \
195             $rax = x64.mov_rr_64 $rdi\n    \
196             $rsi($rsi) = x64.arg_val_32\n    \
197             $rcx = x64.mov_rr_64 $rsi\n    \
198             $rdx = x64.mov_rr_64 $rax\n    \
199             $rdx(reuse 1) = x64.add_rr_32 $rax, $rcx\n    \
200             $rax = x64.mov_rr_64 $rdx\n    \
201             x64.ret_val_32 $rax($rax)\n    \
202             x64.ret\n\
203             }\n"
204        );
205    }
206
207    #[test]
208    fn a_function_that_calls_takes_a_frame_and_gives_it_back() {
209        let i32 = Type::int(32);
210        let (mut names, mut source, block, args) = blank(&[i32]);
211        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
212        let callee = names.intern("g");
213        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
214        let got = source[call].first_result.expect("an integer comes back");
215        let mut build = Builder::new(&mut source, block);
216        let sum = build.binary(Opcode::Add, got, args[0], IrFlags::default());
217        build.ret(&[sum]);
218
219        let machine = Machine::x86_64(&SYSV);
220        let out = compile(&source, &mut names, &machine, Flags::default())
221            .expect("every instruction has a rule");
222
223        // `int f(int a) { return g(a) + a; }`. Not a leaf, so the stack pointer moves and the
224        // register the value that outlives the call went to is one the prologue saves.
225        let text = mir::print_func(&out, &names, &REGS);
226        assert!(text.contains("x64.push_64 $rbx"), "{text}");
227        assert!(text.contains("$rbx = x64.pop_64"), "{text}");
228        assert!(text.contains("x64.call $rdi($rdi), @g"), "{text}");
229        assert!(!text.contains('%'), "{text}");
230    }
231
232    #[test]
233    fn the_other_convention_is_the_same_function_somewhere_else() {
234        let i32 = Type::int(32);
235        let (mut names, mut source, block, args) = blank(&[i32, i32]);
236        let mut build = Builder::new(&mut source, block);
237        let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
238        build.ret(&[sum]);
239
240        let machine = Machine::x86_64(&WIN64);
241        let out = compile(&source, &mut names, &machine, Flags::default())
242            .expect("every instruction has a rule");
243
244        // The arguments arrive in `rcx` and `rdx` here rather than in `rdi` and `rsi`, which is
245        // the whole of what changed, and it changed because the convention was asked.
246        let text = mir::print_func(&out, &names, &REGS);
247        assert!(text.contains("$rcx($rcx) = x64.arg_val_32"), "{text}");
248        assert!(text.contains("$rdx($rdx) = x64.arg_val_32"), "{text}");
249        assert!(!text.contains("$rdi"), "{text}");
250    }
251
252    #[test]
253    fn a_function_with_a_branch_in_it_goes_through_every_pass() {
254        let i32 = Type::int(32);
255        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
256        let then = source.create_block();
257        let join = source.create_block();
258        let got = source.append_param(join, i32);
259        let mut build = Builder::new(&mut source, entry);
260        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
261        build.br_if(cond, then, &[], join, &[args[1]]);
262        Builder::new(&mut source, then).jump(join, &[args[0]]);
263        Builder::new(&mut source, join).ret(&[got]);
264
265        let machine = Machine::x86_64(&SYSV);
266        let out = compile(&source, &mut names, &machine, Flags::default())
267            .expect("every instruction has a rule");
268
269        // The else arm is a critical edge carrying a value, so a block that nothing lowered is in
270        // there, which is the pass between lowering and allocation doing its job. Without it the
271        // allocator would have asserted rather than compiled this.
272        assert_eq!(out.block_count(), 4);
273
274        // `int f(int a, int b) { return a < b ? a : b; }` end to end, and the last pass is what
275        // this pins. The branch became a test and one jump, and it is the jump taken when the
276        // condition failed, because the arm the condition is true for is the block laid out next
277        // and a block falls into the block laid out next. The other arm is the empty block the
278        // edge splitting left, which is where the move the edge carries ended up, and it falls
279        // into the join as well. What is left is one jump in the whole function.
280        let text = mir::print_func(&out, &names, &REGS);
281        assert_eq!(
282            text,
283            "mfunc @f {\n\
284             block0:\n    \
285             $rdi($rdi) = x64.arg_val_32\n    \
286             $rax = x64.mov_rr_64 $rdi\n    \
287             $rsi($rsi) = x64.arg_val_32\n    \
288             $rcx = x64.mov_rr_64 $rsi\n    \
289             $rdx = x64.cmp_set_l_32 $rax, $rcx\n    \
290             x64.test_rr_8 $rdx\n    \
291             x64.jcc_e block2, block1\n\
292             \nblock1:\n    \
293             $rdx = x64.mov_rr_64 $rax\n    \
294             x64.jmp block3\n\
295             \nblock2:\n    \
296             $rdx = x64.mov_rr_64 $rcx, block3\n\
297             \nblock3:\n    \
298             $rax = x64.mov_rr_64 $rdx\n    \
299             x64.ret_val_32 $rax($rax)\n    \
300             x64.ret\n\
301             }\n"
302        );
303    }
304
305    /// A loop that swaps its two values round every time it goes, which is `gcd`, and which is
306    /// the smallest program that caught two ways of losing a value. Both were found by running
307    /// what came out rather than by reading it, and both are pinned here rather than only where
308    /// they were fixed, because what is wrong with either of them is only visible in the whole
309    /// function.
310    #[test]
311    fn a_loop_that_carries_its_values_round_keeps_all_of_them() {
312        let i32 = Type::int(32);
313        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
314        let head = source.create_block();
315        let body = source.create_block();
316        let exit = source.create_block();
317        let left = source.append_param(head, i32);
318        let right = source.append_param(head, i32);
319        Builder::new(&mut source, entry).jump(head, &[args[0], args[1]]);
320        let mut build = Builder::new(&mut source, head);
321        let zero = build.iconst(i32, 0);
322        let more = build.icmp(rucc_ir::IntPred::Ne, right, zero);
323        build.br_if(more, body, &[], exit, &[left]);
324        let mut build = Builder::new(&mut source, body);
325        let rest = build.binary(Opcode::SRem, left, right, IrFlags::default());
326        build.jump(head, &[right, rest]);
327        let result = source.append_param(exit, i32);
328        Builder::new(&mut source, exit).ret(&[result]);
329
330        let machine = Machine::x86_64(&SYSV);
331        let out = compile(&source, &mut names, &machine, Flags::default())
332            .expect("every instruction has a rule");
333
334        // `int gcd(int a, int b) { while (b) { int t = a % b; a = b; b = t; } return a; }`. Two
335        // things in here were wrong and each of them returned three from a program that gcc
336        // returns forty two from.
337        //
338        // The first is in the entry block. The move the edge into the loop asks for writes `rsi`,
339        // and the second argument has to be taken out of `rsi` before it does. An edit at the end
340        // of a block used to go in front of the last instruction, on the reasoning that the last
341        // instruction is the branch, and the block's jump is not an instruction until the layout
342        // has run, so it went in front of the `arg_val` whose own move had not been made yet.
343        //
344        // The second is in the loop body. A division writes both a quotient and a remainder, and
345        // only the remainder is wanted here, so the quotient is a value nothing reads. It used to
346        // be given the same register as the remainder, because a value written early was live at
347        // one point and that point is in front of where the remainder is written. The copy that
348        // takes the quotient nowhere then landed on top of the remainder.
349        assert_eq!(
350            mir::print_func(&out, &names, &REGS),
351            "mfunc @f {\n\
352             block0:\n    \
353             $rdi($rdi) = x64.arg_val_32\n    \
354             $rax = x64.mov_rr_64 $rdi\n    \
355             $rsi($rsi) = x64.arg_val_32\n    \
356             $rcx = x64.mov_rr_64 $rsi\n    \
357             $rsi = x64.mov_rr_64 $rcx\n    \
358             $rcx = x64.mov_rr_64 $rax, block1\n\
359             \nblock1:\n    \
360             $rax = x64.mov_ri_32 0\n    \
361             $rax = x64.cmp_set_ne_32 $rsi, $rax\n    \
362             x64.test_rr_8 $rax\n    \
363             x64.jcc_e block3, block2\n\
364             \nblock2:\n    \
365             $rax = x64.mov_rr_64 $rcx\n    \
366             $rdx($rdx), early $rax($rax) = x64.idiv_rem_32 $rax($rax), $rsi\n    \
367             $rcx = x64.mov_rr_64 $rdx\n    \
368             $rdi = x64.mov_rr_64 $rax\n    \
369             $r10 = x64.mov_rr_64 $rsi\n    \
370             $rsi = x64.mov_rr_64 $rcx\n    \
371             $rcx = x64.mov_rr_64 $r10\n    \
372             x64.jmp block1\n\
373             \nblock3:\n    \
374             $rax = x64.mov_rr_64 $rcx\n    \
375             x64.ret_val_32 $rax($rax)\n    \
376             x64.ret\n\
377             }\n"
378        );
379    }
380
381    /// `spec/10-backend.md` section 10.1 says `--emit=mir-final` round-trips, and a function with
382    /// a branch in it is the one where that is worth checking: after the layout has run, where a
383    /// jump goes is nowhere in the instruction, so the text has to carry it on the block and the
384    /// parser has to put it back on the block it came off.
385    #[test]
386    fn a_function_that_has_been_laid_out_reads_back_as_the_same_function() {
387        let i32 = Type::int(32);
388        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
389        let then = source.create_block();
390        let join = source.create_block();
391        let got = source.append_param(join, i32);
392        let mut build = Builder::new(&mut source, entry);
393        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
394        build.br_if(cond, then, &[], join, &[args[1]]);
395        Builder::new(&mut source, then).jump(join, &[args[0]]);
396        Builder::new(&mut source, join).ret(&[got]);
397
398        let machine = Machine::x86_64(&SYSV);
399        let out = compile(&source, &mut names, &machine, Flags::default())
400            .expect("every instruction has a rule");
401
402        let text = mir::print_func(&out, &names, &REGS);
403        let read = rucc_mir::parse(&text, &mut names, &REGS).expect("what the printer wrote");
404        assert_eq!(mir::print(&read, &names, &REGS), text);
405    }
406
407    #[test]
408    fn a_function_this_cannot_lower_is_reported_rather_than_compiled() {
409        let f64 = Type::float(rucc_ir::Float::F64);
410        let (mut names, mut source, block, args) = blank(&[f64]);
411        Builder::new(&mut source, block).ret(&[args[0]]);
412
413        let machine = Machine::x86_64(&SYSV);
414        let failed = compile(&source, &mut names, &machine, Flags::default())
415            .expect_err("a double arrives in a vector register");
416        assert_eq!(failed.to_string(), "parameter 0 is in a vector register");
417    }
418
419    #[test]
420    fn the_flags_reach_the_frame() {
421        let i32 = Type::int(32);
422        let (mut names, mut source, block, args) = blank(&[i32]);
423        Builder::new(&mut source, block).ret(&[args[0]]);
424
425        let machine = Machine::x86_64(&SYSV);
426        let flags = Flags { frame_pointer: true, red_zone: true };
427        let out =
428            compile(&source, &mut names, &machine, flags).expect("every instruction has a rule");
429
430        // A function that keeps a frame pointer keeps it whether it needed one or not, which is
431        // what `-fno-omit-frame-pointer` is for and is the only thing this test is about.
432        let text = mir::print_func(&out, &names, &REGS);
433        assert!(text.contains("x64.push_64 $rbp"), "{text}");
434        assert!(text.contains("$rbp = x64.mov_rr_64 $rsp"), "{text}");
435    }
436
437    #[test]
438    fn a_target_says_which_machine_it_is_and_which_convention_it_uses() {
439        let triple = |text: &str| text.parse::<rucc_target::Triple>().expect("a triple");
440        let info = TargetInfo::new(triple("x86_64-unknown-linux-gnu"));
441        let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
442        assert!(std::ptr::eq(machine.conv, &SYSV));
443
444        let info = TargetInfo::new(triple("x86_64-pc-windows-msvc"));
445        let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
446        assert!(std::ptr::eq(machine.conv, &WIN64));
447
448        // Not a target this crate has a backend for, and saying so is the whole point: a caller
449        // that got a machine here would compile x86-64 instructions for an AArch64 program.
450        let info = TargetInfo::new(triple("aarch64-unknown-linux-gnu"));
451        assert!(Machine::for_target(&info).is_none());
452    }
453}