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