Skip to main content

rucc_regalloc/
lib.rs

1//! Both register allocators and the allocation checker.
2//!
3//! Design: `spec/10-backend.md`. Layer rank 11, see `spec/18-package-layout.md`.
4//!
5//! # Status
6//!
7//! Liveness is here, which is the question both allocators ask first: [`order`] lays a function
8//! out in the line the encoder will emit it in, and [`live`] says where in that line each value
9//! is wanted. So is [`moves`], which puts the moves an edge turns into in an order they can be
10//! made in one at a time. The single pass allocator's decision is in [`assign`]: where every value
11//! of a function goes, in one linear scan, which is what `-O0` asks for. The rewrite that makes
12//! that decision true in the function is in [`rewrite`], and [`run`] is the two of them together,
13//! which is the whole of the `-O0` allocator. [`check`] reads an assignment back and says whether
14//! it is one the machine can run, which [`run`] asserts on in debug and CI builds and which the
15//! backtracking allocator in M4 will be held to the same way. [`trace`] asks the other half of the
16//! question, which is whether the rewrite wrote that decision down without losing a value on the
17//! way: it follows every value from the instruction that wrote it to the instructions that read
18//! it, through the moves, and [`run`] asserts on it in the same builds.
19//!
20//! Every crate in the workspace is published, and publishing implies a promise. This one is
21//! tier 3: its Rust API is explicitly unstable and will change without a major version bump.
22//! Depend on the `rucc` binary's behaviour, not on this.
23
24#![doc(html_root_url = "https://docs.rs/rucc-regalloc/0.10.38")]
25
26pub mod assign;
27pub mod check;
28pub mod live;
29pub mod moves;
30pub mod order;
31pub mod rewrite;
32pub mod trace;
33
34/// What allocating a function produced.
35///
36/// The moves are handed back rather than written into the function because a move is an
37/// instruction and an instruction belongs to a target, which `spec/10-backend.md` section 10.8
38/// says this crate holds nothing of. The consumer turns each one into whatever its target moves a
39/// register with.
40#[derive(Debug, Clone)]
41pub struct Allocation {
42    /// Where every value of the function went, which is what the frame layout reads.
43    pub assignment: assign::Assignment,
44    /// The moves the places do not already make true, in the order they have to be made in.
45    pub edits: Vec<rewrite::Edit>,
46}
47
48/// Allocates registers for a function the way `-O0` asks for, rewriting it as it goes.
49///
50/// This is the shape `spec/10-backend.md` section 10.4 gives an allocator: a function and the
51/// registers it may use in, an assignment and the moves that make it true out. The backtracking
52/// allocator will answer the same question the same way.
53///
54/// # Panics
55///
56/// Panics on a function the caller was told not to hand it, which is one with a critical edge,
57/// one whose entry block has parameters, or one wanting more scratch registers at an instruction
58/// than the environment holds back. See [`rewrite::rewrite`].
59///
60/// In a debug build it also panics on an assignment [`check`] finds a problem with, which is a bug
61/// in this crate rather than anything the caller did. `spec/10-backend.md` section 10.4 asks for
62/// that check in debug and CI builds, and it runs before the rewrite because the assignment is the
63/// decision and the rewrite only writes it down.
64///
65/// A debug build panics on a rewrite [`trace`] finds a value missing from as well. That one runs
66/// afterwards, since a transcription can only be read once it has been made, and it is the check
67/// `spec/optimizer/39-register-allocation.md` section 39.6 asks for.
68///
69/// `called` is what to call the function in that message. It is passed in rather than read off the
70/// function because the name there is a symbol and resolving one wants the interner, which this
71/// crate has no reason to be handed otherwise. Without it the message is a pair of register numbers
72/// and nothing that says where, and finding the function it was about in a file the size of the
73/// SQLite amalgamation means bisecting by hand.
74pub fn run(func: &mut rucc_mir::Func, env: &assign::Env, called: &str) -> Allocation {
75    let order = order::Order::of(func);
76    let live = live::Live::of(func, &order);
77    let assignment = assign::assign(func, &order, &live, env);
78    if cfg!(debug_assertions) {
79        let problems = check::check(func, &order, &live, &assignment);
80        assert!(problems.is_empty(), "in '{called}': {}", check::report(&problems));
81    }
82    // What the rewrite is about to lose, taken while it is still there. Only in a build that is
83    // going to read it, since the snapshot is a copy of every operand list in the function.
84    let shape = cfg!(debug_assertions).then(|| trace::shape(func));
85    let edits = rewrite::rewrite(func, &assignment, env);
86    if let Some(shape) = shape {
87        let faults = trace::trace(func, &shape, &assignment, &edits);
88        assert!(faults.is_empty(), "in '{called}': {}", trace::report(&faults));
89    }
90    Allocation { assignment, edits }
91}
92
93/// The milestone in `spec/17-milestones.md` that fills this crate in.
94pub const MILESTONE: &str = "M3";
95
96#[cfg(test)]
97mod tests {
98    use rucc_base::Interner;
99    use rucc_mir::{Func, Opcode};
100    use rucc_target::x86_64::{GPR, SYSV};
101
102    use super::*;
103
104    #[test]
105    fn milestone_is_recorded() {
106        assert!(MILESTONE.starts_with('M'));
107    }
108
109    #[test]
110    fn allocating_a_function_places_every_value_and_hands_back_the_moves_it_needs() {
111        let mut names = Interner::new();
112        let mut func = Func::new(names.intern("f"));
113        let opcode = Opcode::new(names.intern("x64.nop"));
114        let block = func.create_block();
115        let first = func.new_vreg(GPR);
116        let second = func.new_vreg(GPR);
117        let third = func.new_vreg(GPR);
118        func.build(block, opcode).def(first, GPR).finish();
119        func.build(block, opcode).def(second, GPR).finish();
120        func.build(block, opcode).def(third, GPR).finish();
121        func.build(block, opcode).uses(first, GPR).uses(second, GPR).uses(third, GPR).finish();
122
123        // Two registers to hand out and three values that are all wanted at once, so one of them
124        // goes to the stack and the instruction that reads it gets a reload. This is also where
125        // the checker runs, since a debug build asserts on what it says.
126        let env = assign::Env::new().with(GPR, &SYSV.int_order[..2], &SYSV.int_order[2..5]);
127        let allocation = run(&mut func, &env, "test");
128
129        assert_eq!(allocation.assignment.spilled(), 1);
130        assert_eq!(allocation.edits.len(), 2);
131    }
132}