rucc_codegen/select.rs
1//! Matching a target's lowering rules against a term.
2//!
3//! Design: `spec/10-backend.md` section 10.2. The rules themselves are in `rules/`, one file per
4//! target, and the automaton they compile into is generated by `rucc-rules` when this crate is
5//! built.
6//!
7//! The walk over that automaton is [`rucc_base::rules`], because `rucc-opt` matches IR against a
8//! table of rewrite rules with the same walk and neither crate can see the other. What is here
9//! is which targets there are and the tests that the x86-64 table lowers what it should. The
10//! AArch64 table has its own tests beside it.
11//!
12//! The names are re-exported rather than reached for through `rucc_base`, because the generated
13//! file refers to them through `super` and that is the whole of the contract between the two.
14
15pub mod aarch64;
16pub mod x86_64;
17
18pub use rucc_base::rules::{Guard, Match, Node, Piece, Rule, Subject, Table};
19use rucc_target::{
20 Address, BranchInsts, FrameInsts, MachineInsts, OperandDesc, PhysReg, RegClass, Segment,
21};
22
23/// What `crate::lower` has to know about the machine it selects instructions for.
24///
25/// The lowering is one walk over the IR whichever machine it is for, and everything in it that
26/// differs between two machines is a question this answers: which table the rules compiled into,
27/// what each opcode's operands are, what an address constructor's arguments mean, and the handful
28/// of instructions the walk writes itself rather than getting from a rule. A walk that reaches
29/// for a machine's module by name is a walk for that machine only, which is what this is here to
30/// stop.
31///
32/// The frame and branch instructions are the same tables `crate::pipeline::Machine` hands the
33/// passes after this one. They are in here as well so that the lowering is handed one thing,
34/// rather than a machine and the convention and the rules separately.
35#[derive(Debug)]
36pub struct Selector {
37 /// The rules, compiled.
38 pub table: &'static Table,
39 /// The shape of each opcode, and the prefix a rule file puts in front of one.
40 pub shapes: &'static MachineInsts,
41 /// What an address constructor in a replacement stands for, or `None` for a name that is not
42 /// one of this machine's.
43 pub address: fn(&str) -> Option<Address>,
44 /// The instructions that take a frame and give it back, of which the walk writes the address
45 /// of a local and the move between two registers itself.
46 pub frame: &'static FrameInsts,
47 /// The instructions a branch becomes, of which the walk writes the indirect jump itself.
48 pub branch: &'static BranchInsts,
49 /// The class an address is in.
50 pub gpr: RegClass,
51 /// The instruction a full fence is, without the prefix.
52 pub fence: &'static str,
53 /// The instruction a program that must stop here stops with, without the prefix.
54 pub trap: &'static str,
55 /// The instructions the calling convention is written with.
56 pub abi: &'static crate::abi::Insts,
57 /// The address registers held back from the allocator for the rewriter's reloads, which are
58 /// the ones the walk must not keep anything in across more than one instruction.
59 pub scratch: &'static [PhysReg],
60 /// How the walk comes by the address of a symbol, which is its own business rather than a
61 /// rule's because whether it goes through the global offset table is a fact about the link and
62 /// not about the instruction.
63 pub symbols: &'static Symbols,
64 /// The instructions a jump through a table is built from, and the address of a label.
65 pub jumps: &'static Jumps,
66}
67
68/// The instructions a place in this function is reached with: the address of a block or a jump
69/// table, and the read of one cell of a table and the add that turns it back into an address.
70#[derive(Debug)]
71pub struct Jumps {
72 /// The address of a block or a table, which is carried in the addressing mode.
73 pub near: &'static str,
74 /// A load of a 32-bit cell, sign extended to the width of an address.
75 pub cell: &'static str,
76 /// The add of two addresses.
77 pub add: &'static str,
78 /// Whether the add writes its first operand, the way it does on x86-64.
79 pub two_address: bool,
80}
81
82/// The two ways the address of a symbol is come by.
83#[derive(Debug)]
84pub struct Symbols {
85 /// A symbol this image defines, whose address is a fixed distance from the code.
86 pub near: Reach,
87 /// A symbol another image may define, whose address is read out of the global offset table.
88 pub far: Reach,
89 /// How far a thread-local variable is from the thread pointer, which is read out of the global
90 /// offset table too, from a slot the link fills in with that distance.
91 pub thread: Reach,
92 /// The thread pointer itself.
93 pub pointer: Pointer,
94}
95
96/// Where the thread pointer is read from.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum Pointer {
99 /// A load at zero in a segment, since the word at the front of the block is its own address.
100 /// That is x86-64, whose `%fs` is not a register a program can read.
101 Segment(&'static str, Segment),
102 /// An instruction that reads a system register, which is AArch64's `mrs` of `tpidr_el0`.
103 Own(&'static str),
104}
105
106/// One instruction that puts the address of a symbol in a register, and where it carries the
107/// symbol.
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub enum Reach {
110 /// In its addressing mode, which is how x86-64 does both: a `lea` or a `mov` relative to the
111 /// instruction pointer.
112 Mode(&'static str),
113 /// As the instruction's own symbol with no addressing mode at all, which is how AArch64 does
114 /// both: an `adrp` for the page and a second instruction for the rest, written as one opcode.
115 Own(&'static str),
116}
117
118impl Selector {
119 /// What a rule file and the machine IR put in front of this machine's opcodes.
120 #[must_use]
121 pub fn prefix(&self) -> &'static str {
122 self.shapes.prefix
123 }
124
125 /// The operands the opcode of that name has, the name written without the prefix.
126 #[must_use]
127 pub fn operands(&self, name: &str) -> Option<&'static [OperandDesc]> {
128 (self.shapes.operands)(name)
129 }
130}
131
132#[cfg(test)]
133mod tests {
134 use super::x86_64::TABLE;
135 use super::{Piece, Subject};
136
137 /// A term, in the only shape a test needs: a flat arena, because that is the shape the IR
138 /// has and answering the questions out of one is what the selector will be doing.
139 #[derive(Debug)]
140 enum Node {
141 Int(i128),
142 App(String, Vec<usize>),
143 }
144
145 #[derive(Debug, Default)]
146 struct Terms {
147 nodes: Vec<Node>,
148 }
149
150 impl Terms {
151 fn constant(&mut self, value: i128) -> usize {
152 self.nodes.push(Node::Int(value));
153 self.nodes.len() - 1
154 }
155
156 fn app(&mut self, head: &str, args: &[usize]) -> usize {
157 self.nodes.push(Node::App(head.to_owned(), args.to_vec()));
158 self.nodes.len() - 1
159 }
160
161 /// A register operand, which is a term with a head the rules write and nothing under it.
162 fn value(&mut self, width: u32, name: &str) -> usize {
163 let inner = self.app(name, &[]);
164 self.app(&format!("value.i{width}"), &[inner])
165 }
166 }
167
168 impl Subject for Terms {
169 type Node = usize;
170
171 fn head(&self, node: usize) -> Option<(&str, usize)> {
172 match &self.nodes[node] {
173 Node::App(head, args) => Some((head.as_str(), args.len())),
174 Node::Int(_) => None,
175 }
176 }
177
178 fn arg(&self, node: usize, index: usize) -> usize {
179 match &self.nodes[node] {
180 Node::App(_, args) => args[index],
181 Node::Int(_) => unreachable!("a constant has no arguments"),
182 }
183 }
184
185 fn int(&self, node: usize) -> Option<i128> {
186 match self.nodes[node] {
187 Node::Int(value) => Some(value),
188 Node::App(..) => None,
189 }
190 }
191
192 // An index into the arena is the identity of a term here, so two places are the same
193 // thing when they point at the same entry.
194 fn same(&self, a: usize, b: usize) -> bool {
195 a == b
196 }
197 }
198
199 /// What the head of the rule that fired selects, which is the answer every one of these
200 /// tests is really about.
201 fn selects(terms: &Terms, term: usize) -> Option<&'static str> {
202 let found = TABLE.find(terms, term)?;
203 TABLE.rule(&found).head()
204 }
205
206 /// No pattern is reached by reading past the ones in front of it.
207 ///
208 /// `spec/optimizer/36-lowering-and-isel.md` section 36.5 asks for the decision to be on the
209 /// shape of the term, and the root of this table is where that is worth anything: every
210 /// instruction the selector looks at arrives there, and a hundred and sixty seven different
211 /// heads are written on it. Sorted, that is eight comparisons and the walk finds the branch.
212 /// In the order the rules happen to be written it would be a hundred and sixty seven, every
213 /// time, and worst for the terms no rule covers, which are the ones the selector has to see
214 /// the most of.
215 ///
216 /// What is asserted is the property the search needs, which is that every node is in order.
217 /// A node that is not is not a slower table, it is a wrong one, because a binary search over
218 /// an unsorted list finds nothing and the rule silently stops firing.
219 #[test]
220 fn no_rule_is_reached_by_reading_past_the_rules_in_front_of_it() {
221 let root = TABLE.nodes.first().expect("the table has a root");
222 assert!(root.heads.len() > 100, "the root is the node this is about");
223 for (at, node) in TABLE.nodes.iter().enumerate() {
224 assert!(node.heads.is_sorted(), "node {at} is not in an order a search can use");
225 assert!(node.ints.is_sorted(), "node {at} is not in an order a search can use");
226 }
227 }
228
229 #[test]
230 fn the_table_holds_every_rule_the_file_writes() {
231 let text = include_str!("../rules/x86-64.rules");
232 let written = text.lines().filter(|line| line.starts_with("(rule ")).count();
233 assert_eq!(TABLE.rules.len(), written, "the table and the rule file disagree");
234 assert_eq!(TABLE.source, "rules/x86-64.rules");
235 }
236
237 #[test]
238 fn an_addition_of_two_registers_is_the_register_form() {
239 let mut terms = Terms::default();
240 let x = terms.value(64, "v0");
241 let y = terms.value(64, "v1");
242 let add = terms.app("add.i64", &[x, y]);
243 assert_eq!(selects(&terms, add), Some("x64.add_rr_64"));
244 }
245
246 /// The bindings are the operands in the order the pattern names them, and the replacement
247 /// says which of them goes where. This is the whole of what the selector will read.
248 ///
249 /// What a name is bound to is what the pattern put it under, so `(value.i32 x)` binds the
250 /// register and not the term saying it is one. That is the difference between the operand of
251 /// the instruction this becomes and a wrapper that exists to say how wide it is.
252 #[test]
253 fn a_match_gives_back_the_operands_the_pattern_named() {
254 let mut terms = Terms::default();
255 let first = terms.app("v0", &[]);
256 let second = terms.app("v1", &[]);
257 let x = terms.app("value.i32", &[first]);
258 let y = terms.app("value.i32", &[second]);
259 let sub = terms.app("sub.i32", &[x, y]);
260 let found = TABLE.find(&terms, sub).expect("a rule fires");
261 let rule = TABLE.rule(&found);
262 assert_eq!(rule.pattern, "(sub.i32 (value.i32 x) (value.i32 y))");
263 assert_eq!(found.bindings, vec![first, second]);
264 let names: Vec<&str> = rule
265 .replacement
266 .iter()
267 .filter_map(|piece| match piece {
268 Piece::Var { name, index } => {
269 assert_eq!(found.bindings[*index], if *index == 0 { first } else { second });
270 Some(*name)
271 }
272 _ => None,
273 })
274 .collect();
275 assert_eq!(names, ["x", "y"]);
276 }
277
278 /// An immediate the instruction has room for takes the immediate form. The rule for it is
279 /// guarded, so this is also the test that a guard which holds does not stop a rule firing.
280 #[test]
281 fn an_addition_of_an_immediate_that_fits_is_the_immediate_form() {
282 let mut terms = Terms::default();
283 let x = terms.value(64, "v0");
284 let k = terms.constant(4);
285 let k = terms.app("iconst.i64", &[k]);
286 let add = terms.app("add.i64", &[x, k]);
287 assert_eq!(selects(&terms, add), Some("x64.add_ri_64"));
288 }
289
290 /// An immediate too wide for the encoding is what the guard is there to refuse. Nothing else
291 /// matches such a term, and that is the right answer: the constant has to be put in a
292 /// register first, which is a decision for the selector and not for the table.
293 #[test]
294 fn an_addition_of_an_immediate_too_wide_for_the_form_matches_nothing() {
295 let mut terms = Terms::default();
296 let x = terms.value(64, "v0");
297 let k = terms.constant(1 << 40);
298 let k = terms.app("iconst.i64", &[k]);
299 let add = terms.app("add.i64", &[x, k]);
300 assert_eq!(selects(&terms, add), None);
301 }
302
303 /// The other shape of guard, which is a shift count the width allows.
304 #[test]
305 fn a_shift_by_a_count_the_width_allows_is_the_immediate_form() {
306 let mut terms = Terms::default();
307 let x = terms.value(64, "v0");
308 let k = terms.constant(3);
309 let k = terms.app("iconst.i64", &[k]);
310 let shl = terms.app("shl.i64", &[x, k]);
311 assert_eq!(selects(&terms, shl), Some("x64.shl_ri_64"));
312 }
313
314 #[test]
315 fn a_shift_by_a_count_the_width_does_not_allow_matches_nothing() {
316 let mut terms = Terms::default();
317 let x = terms.value(64, "v0");
318 let k = terms.constant(64);
319 let k = terms.app("iconst.i64", &[k]);
320 let shl = terms.app("shl.i64", &[x, k]);
321 assert_eq!(selects(&terms, shl), None);
322 }
323
324 /// One bit reaches the byte instructions, which is the whole of how the machine holds a truth
325 /// value. The widening is the interesting one: it is `movzbl` under a name of its own, so the
326 /// rule that fires here is not the rule a byte would have found.
327 #[test]
328 fn a_truth_value_is_lowered_to_the_byte_instructions_that_keep_it_one() {
329 let mut terms = Terms::default();
330 let x = terms.value(1, "v0");
331 let y = terms.value(1, "v1");
332 let xor = terms.app("xor.i1", &[x, y]);
333 assert_eq!(selects(&terms, xor), Some("x64.xor_rr_8"));
334
335 let x = terms.value(1, "v2");
336 let wide = terms.app("zext.i1.i32", &[x]);
337 assert_eq!(selects(&terms, wide), Some("x64.bit_to_32"));
338
339 let x = terms.value(8, "v3");
340 let byte = terms.app("zext.i8.i32", &[x]);
341 assert_eq!(selects(&terms, byte), Some("x64.movzx_8_32"));
342 }
343
344 /// The half of a truth value that is an object rather than a value in a register. A `_Bool`
345 /// in memory is a byte holding a zero or a one, so a load widens on the way in and a store
346 /// writes the byte, and both are named apart from the byte pair for the reason the widening
347 /// is named apart from the byte widening. The narrowing is the mask, and it is the one of
348 /// these that nothing in C asks for directly: a bit field one bit wide whose type is a
349 /// `_Bool` is what writes it.
350 #[test]
351 fn a_truth_value_in_memory_is_the_byte_it_lives_in() {
352 let mut terms = Terms::default();
353 let address = terms.value(64, "v0");
354 let read = terms.app("load.i1", &[address]);
355 assert_eq!(selects(&terms, read), Some("x64.mov_rm_bit"));
356
357 let value = terms.value(1, "v1");
358 let address = terms.value(64, "v2");
359 let write = terms.app("store.i1", &[value, address]);
360 assert_eq!(selects(&terms, write), Some("x64.mov_mr_bit"));
361
362 let value = terms.value(1, "v3");
363 let back = terms.app("ret.i1", &[value]);
364 assert_eq!(selects(&terms, back), Some("x64.ret_val_8"));
365
366 let x = terms.value(32, "v4");
367 let bit = terms.app("trunc.i32.i1", &[x]);
368 assert_eq!(selects(&terms, bit), Some("x64.bit_of_32"));
369 }
370
371 /// The divisions at one byte and at two, which the `narrow` pass writes for a division of two
372 /// zero extensions and, signed, for a division of two sign extensions the ranges clear.
373 #[test]
374 fn a_narrow_division_is_the_narrow_divide() {
375 let mut terms = Terms::default();
376 for width in [8, 16] {
377 let x = terms.value(width, "v0");
378 let y = terms.value(width, "v1");
379 for (op, head) in [
380 ("udiv", "div_quo"),
381 ("urem", "div_rem"),
382 ("sdiv", "idiv_quo"),
383 ("srem", "idiv_rem"),
384 ] {
385 let term = terms.app(&format!("{op}.i{width}"), &[x, y]);
386 let want = format!("x64.{head}_{width}");
387 assert_eq!(selects(&terms, term), Some(want.as_str()));
388 }
389 }
390 }
391
392 /// A term the rule set says nothing about is nothing rather than a wrong answer, which is
393 /// what the completeness check in `spec/10-backend.md` will be for.
394 #[test]
395 fn a_term_no_rule_covers_finds_no_rule() {
396 let mut terms = Terms::default();
397 let x = terms.value(64, "v0");
398 let y = terms.value(64, "v1");
399 let odd = terms.app("no.such.opcode", &[x, y]);
400 assert_eq!(selects(&terms, odd), None);
401 }
402
403 /// Every instruction a selector names outside its rules is one its machine describes, since
404 /// the lowering writes those without asking a rule and nothing else would catch a name that is
405 /// not there.
406 #[test]
407 fn a_selector_names_only_instructions_its_machine_has() {
408 for selector in [&super::x86_64::SELECTOR, &super::aarch64::SELECTOR] {
409 let named = [
410 selector.fence,
411 selector.trap,
412 selector.frame.lea,
413 selector.frame.grow,
414 selector.frame.imm,
415 selector.branch.indirect,
416 ];
417 for name in named {
418 assert!(
419 selector.operands(name).is_some(),
420 "{}{name} is not an instruction of its machine",
421 selector.prefix()
422 );
423 }
424 // And the rules it is handed are the ones written for the same machine.
425 for rule in selector.table.rules {
426 let Some(Piece::App { head, .. }) = rule.replacement.first() else { continue };
427 assert!(head.starts_with(selector.prefix()), "{head} in {}", selector.table.source);
428 }
429 }
430 }
431
432 /// An address constructor is read the same way on both machines, and the one the AArch64 rules
433 /// cannot write is not one it answers for.
434 #[test]
435 fn both_machines_read_an_address_the_same_way() {
436 let (x86, a64) = (&super::x86_64::SELECTOR, &super::aarch64::SELECTOR);
437 for name in ["amode_base", "amode_base_offset"] {
438 assert_eq!((x86.address)(name), (a64.address)(name));
439 assert!((a64.address)(name).is_some());
440 }
441 assert!((x86.address)("amode_base_index_scale").is_some());
442 assert_eq!((a64.address)("amode_base_index_scale"), None);
443 assert_eq!((a64.address)("add_rr_64"), None);
444 }
445}