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 /// How a Windows thread finds its copy of a thread-local variable, where this machine has
95 /// been taught. See [`Indexed`].
96 pub indexed: Option<Indexed>,
97}
98
99/// The instructions a thread-local variable is reached with on Windows.
100///
101/// Every thread keeps an array of pointers, one for each image's copy of its `.tls` section. The
102/// thread block holds the array, the image's `_tls_index` says which slot is its own, and the
103/// variable is as far into the copy as it is into the section.
104///
105/// ```text
106/// movl _tls_index(%rip), %idx
107/// movq %gs:88, %arr
108/// movq (%arr,%idx,8), %blk
109/// leaq x@SECREL32(%blk), %x
110/// ```
111#[derive(Debug)]
112pub struct Indexed {
113 /// A 32-bit load, zero extended, which reads `_tls_index`.
114 pub index: &'static str,
115 /// A load of a whole word, which reads the array out of the thread block and the block out of
116 /// the array.
117 pub load: &'static str,
118 /// The segment the thread block is in, and how far into it the array is.
119 pub segment: Segment,
120 /// The same.
121 pub at: i32,
122 /// The instruction that adds an offset to a register, which takes the variable's offset in its
123 /// section as its displacement.
124 pub add: &'static str,
125}
126
127/// Where the thread pointer is read from.
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub enum Pointer {
130 /// A load at zero in a segment, since the word at the front of the block is its own address.
131 /// That is x86-64, whose `%fs` is not a register a program can read.
132 Segment(&'static str, Segment),
133 /// An instruction that reads a system register, which is AArch64's `mrs` of `tpidr_el0`.
134 Own(&'static str),
135}
136
137/// One instruction that puts the address of a symbol in a register, and where it carries the
138/// symbol.
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub enum Reach {
141 /// In its addressing mode, which is how x86-64 does both: a `lea` or a `mov` relative to the
142 /// instruction pointer.
143 Mode(&'static str),
144 /// As the instruction's own symbol with no addressing mode at all, which is how AArch64 does
145 /// both: an `adrp` for the page and a second instruction for the rest, written as one opcode.
146 Own(&'static str),
147}
148
149impl Selector {
150 /// What a rule file and the machine IR put in front of this machine's opcodes.
151 #[must_use]
152 pub fn prefix(&self) -> &'static str {
153 self.shapes.prefix
154 }
155
156 /// The operands the opcode of that name has, the name written without the prefix.
157 #[must_use]
158 pub fn operands(&self, name: &str) -> Option<&'static [OperandDesc]> {
159 (self.shapes.operands)(name)
160 }
161}
162
163#[cfg(test)]
164mod tests {
165 use super::x86_64::TABLE;
166 use super::{Piece, Subject};
167
168 /// A term, in the only shape a test needs: a flat arena, because that is the shape the IR
169 /// has and answering the questions out of one is what the selector will be doing.
170 #[derive(Debug)]
171 enum Node {
172 Int(i128),
173 App(String, Vec<usize>),
174 }
175
176 #[derive(Debug, Default)]
177 struct Terms {
178 nodes: Vec<Node>,
179 }
180
181 impl Terms {
182 fn constant(&mut self, value: i128) -> usize {
183 self.nodes.push(Node::Int(value));
184 self.nodes.len() - 1
185 }
186
187 fn app(&mut self, head: &str, args: &[usize]) -> usize {
188 self.nodes.push(Node::App(head.to_owned(), args.to_vec()));
189 self.nodes.len() - 1
190 }
191
192 /// A register operand, which is a term with a head the rules write and nothing under it.
193 fn value(&mut self, width: u32, name: &str) -> usize {
194 let inner = self.app(name, &[]);
195 self.app(&format!("value.i{width}"), &[inner])
196 }
197 }
198
199 impl Subject for Terms {
200 type Node = usize;
201
202 fn head(&self, node: usize) -> Option<(&str, usize)> {
203 match &self.nodes[node] {
204 Node::App(head, args) => Some((head.as_str(), args.len())),
205 Node::Int(_) => None,
206 }
207 }
208
209 fn arg(&self, node: usize, index: usize) -> usize {
210 match &self.nodes[node] {
211 Node::App(_, args) => args[index],
212 Node::Int(_) => unreachable!("a constant has no arguments"),
213 }
214 }
215
216 fn int(&self, node: usize) -> Option<i128> {
217 match self.nodes[node] {
218 Node::Int(value) => Some(value),
219 Node::App(..) => None,
220 }
221 }
222
223 // An index into the arena is the identity of a term here, so two places are the same
224 // thing when they point at the same entry.
225 fn same(&self, a: usize, b: usize) -> bool {
226 a == b
227 }
228 }
229
230 /// What the head of the rule that fired selects, which is the answer every one of these
231 /// tests is really about.
232 fn selects(terms: &Terms, term: usize) -> Option<&'static str> {
233 let found = TABLE.find(terms, term)?;
234 TABLE.rule(&found).head()
235 }
236
237 /// No pattern is reached by reading past the ones in front of it.
238 ///
239 /// `spec/optimizer/36-lowering-and-isel.md` section 36.5 asks for the decision to be on the
240 /// shape of the term, and the root of this table is where that is worth anything: every
241 /// instruction the selector looks at arrives there, and a hundred and sixty seven different
242 /// heads are written on it. Sorted, that is eight comparisons and the walk finds the branch.
243 /// In the order the rules happen to be written it would be a hundred and sixty seven, every
244 /// time, and worst for the terms no rule covers, which are the ones the selector has to see
245 /// the most of.
246 ///
247 /// What is asserted is the property the search needs, which is that every node is in order.
248 /// A node that is not is not a slower table, it is a wrong one, because a binary search over
249 /// an unsorted list finds nothing and the rule silently stops firing.
250 #[test]
251 fn no_rule_is_reached_by_reading_past_the_rules_in_front_of_it() {
252 let root = TABLE.nodes.first().expect("the table has a root");
253 assert!(root.heads.len() > 100, "the root is the node this is about");
254 for (at, node) in TABLE.nodes.iter().enumerate() {
255 assert!(node.heads.is_sorted(), "node {at} is not in an order a search can use");
256 assert!(node.ints.is_sorted(), "node {at} is not in an order a search can use");
257 }
258 }
259
260 #[test]
261 fn the_table_holds_every_rule_the_file_writes() {
262 let text = include_str!("../rules/x86-64.rules");
263 let written = text.lines().filter(|line| line.starts_with("(rule ")).count();
264 assert_eq!(TABLE.rules.len(), written, "the table and the rule file disagree");
265 assert_eq!(TABLE.source, "rules/x86-64.rules");
266 }
267
268 #[test]
269 fn an_addition_of_two_registers_is_the_register_form() {
270 let mut terms = Terms::default();
271 let x = terms.value(64, "v0");
272 let y = terms.value(64, "v1");
273 let add = terms.app("add.i64", &[x, y]);
274 assert_eq!(selects(&terms, add), Some("x64.add_rr_64"));
275 }
276
277 /// The bindings are the operands in the order the pattern names them, and the replacement
278 /// says which of them goes where. This is the whole of what the selector will read.
279 ///
280 /// What a name is bound to is what the pattern put it under, so `(value.i32 x)` binds the
281 /// register and not the term saying it is one. That is the difference between the operand of
282 /// the instruction this becomes and a wrapper that exists to say how wide it is.
283 #[test]
284 fn a_match_gives_back_the_operands_the_pattern_named() {
285 let mut terms = Terms::default();
286 let first = terms.app("v0", &[]);
287 let second = terms.app("v1", &[]);
288 let x = terms.app("value.i32", &[first]);
289 let y = terms.app("value.i32", &[second]);
290 let sub = terms.app("sub.i32", &[x, y]);
291 let found = TABLE.find(&terms, sub).expect("a rule fires");
292 let rule = TABLE.rule(&found);
293 assert_eq!(rule.pattern, "(sub.i32 (value.i32 x) (value.i32 y))");
294 assert_eq!(found.bindings, vec![first, second]);
295 let names: Vec<&str> = rule
296 .replacement
297 .iter()
298 .filter_map(|piece| match piece {
299 Piece::Var { name, index } => {
300 assert_eq!(found.bindings[*index], if *index == 0 { first } else { second });
301 Some(*name)
302 }
303 _ => None,
304 })
305 .collect();
306 assert_eq!(names, ["x", "y"]);
307 }
308
309 /// An immediate the instruction has room for takes the immediate form. The rule for it is
310 /// guarded, so this is also the test that a guard which holds does not stop a rule firing.
311 #[test]
312 fn an_addition_of_an_immediate_that_fits_is_the_immediate_form() {
313 let mut terms = Terms::default();
314 let x = terms.value(64, "v0");
315 let k = terms.constant(4);
316 let k = terms.app("iconst.i64", &[k]);
317 let add = terms.app("add.i64", &[x, k]);
318 assert_eq!(selects(&terms, add), Some("x64.add_ri_64"));
319 }
320
321 /// An immediate too wide for the encoding is what the guard is there to refuse. Nothing else
322 /// matches such a term, and that is the right answer: the constant has to be put in a
323 /// register first, which is a decision for the selector and not for the table.
324 #[test]
325 fn an_addition_of_an_immediate_too_wide_for_the_form_matches_nothing() {
326 let mut terms = Terms::default();
327 let x = terms.value(64, "v0");
328 let k = terms.constant(1 << 40);
329 let k = terms.app("iconst.i64", &[k]);
330 let add = terms.app("add.i64", &[x, k]);
331 assert_eq!(selects(&terms, add), None);
332 }
333
334 /// The other shape of guard, which is a shift count the width allows.
335 #[test]
336 fn a_shift_by_a_count_the_width_allows_is_the_immediate_form() {
337 let mut terms = Terms::default();
338 let x = terms.value(64, "v0");
339 let k = terms.constant(3);
340 let k = terms.app("iconst.i64", &[k]);
341 let shl = terms.app("shl.i64", &[x, k]);
342 assert_eq!(selects(&terms, shl), Some("x64.shl_ri_64"));
343 }
344
345 #[test]
346 fn a_shift_by_a_count_the_width_does_not_allow_matches_nothing() {
347 let mut terms = Terms::default();
348 let x = terms.value(64, "v0");
349 let k = terms.constant(64);
350 let k = terms.app("iconst.i64", &[k]);
351 let shl = terms.app("shl.i64", &[x, k]);
352 assert_eq!(selects(&terms, shl), None);
353 }
354
355 /// One bit reaches the byte instructions, which is the whole of how the machine holds a truth
356 /// value. The widening is the interesting one: it is `movzbl` under a name of its own, so the
357 /// rule that fires here is not the rule a byte would have found.
358 #[test]
359 fn a_truth_value_is_lowered_to_the_byte_instructions_that_keep_it_one() {
360 let mut terms = Terms::default();
361 let x = terms.value(1, "v0");
362 let y = terms.value(1, "v1");
363 let xor = terms.app("xor.i1", &[x, y]);
364 assert_eq!(selects(&terms, xor), Some("x64.xor_rr_8"));
365
366 let x = terms.value(1, "v2");
367 let wide = terms.app("zext.i1.i32", &[x]);
368 assert_eq!(selects(&terms, wide), Some("x64.bit_to_32"));
369
370 let x = terms.value(8, "v3");
371 let byte = terms.app("zext.i8.i32", &[x]);
372 assert_eq!(selects(&terms, byte), Some("x64.movzx_8_32"));
373 }
374
375 /// The half of a truth value that is an object rather than a value in a register. A `_Bool`
376 /// in memory is a byte holding a zero or a one, so a load widens on the way in and a store
377 /// writes the byte, and both are named apart from the byte pair for the reason the widening
378 /// is named apart from the byte widening. The narrowing is the mask, and it is the one of
379 /// these that nothing in C asks for directly: a bit field one bit wide whose type is a
380 /// `_Bool` is what writes it.
381 #[test]
382 fn a_truth_value_in_memory_is_the_byte_it_lives_in() {
383 let mut terms = Terms::default();
384 let address = terms.value(64, "v0");
385 let read = terms.app("load.i1", &[address]);
386 assert_eq!(selects(&terms, read), Some("x64.mov_rm_bit"));
387
388 let value = terms.value(1, "v1");
389 let address = terms.value(64, "v2");
390 let write = terms.app("store.i1", &[value, address]);
391 assert_eq!(selects(&terms, write), Some("x64.mov_mr_bit"));
392
393 let value = terms.value(1, "v3");
394 let back = terms.app("ret.i1", &[value]);
395 assert_eq!(selects(&terms, back), Some("x64.ret_val_8"));
396
397 let x = terms.value(32, "v4");
398 let bit = terms.app("trunc.i32.i1", &[x]);
399 assert_eq!(selects(&terms, bit), Some("x64.bit_of_32"));
400 }
401
402 /// The divisions at one byte and at two, which the `narrow` pass writes for a division of two
403 /// zero extensions and, signed, for a division of two sign extensions the ranges clear.
404 #[test]
405 fn a_narrow_division_is_the_narrow_divide() {
406 let mut terms = Terms::default();
407 for width in [8, 16] {
408 let x = terms.value(width, "v0");
409 let y = terms.value(width, "v1");
410 for (op, head) in [
411 ("udiv", "div_quo"),
412 ("urem", "div_rem"),
413 ("sdiv", "idiv_quo"),
414 ("srem", "idiv_rem"),
415 ] {
416 let term = terms.app(&format!("{op}.i{width}"), &[x, y]);
417 let want = format!("x64.{head}_{width}");
418 assert_eq!(selects(&terms, term), Some(want.as_str()));
419 }
420 }
421 }
422
423 /// A term the rule set says nothing about is nothing rather than a wrong answer, which is
424 /// what the completeness check in `spec/10-backend.md` will be for.
425 #[test]
426 fn a_term_no_rule_covers_finds_no_rule() {
427 let mut terms = Terms::default();
428 let x = terms.value(64, "v0");
429 let y = terms.value(64, "v1");
430 let odd = terms.app("no.such.opcode", &[x, y]);
431 assert_eq!(selects(&terms, odd), None);
432 }
433
434 /// Every instruction a selector names outside its rules is one its machine describes, since
435 /// the lowering writes those without asking a rule and nothing else would catch a name that is
436 /// not there.
437 #[test]
438 fn a_selector_names_only_instructions_its_machine_has() {
439 for selector in [&super::x86_64::SELECTOR, &super::aarch64::SELECTOR] {
440 let named = [
441 selector.fence,
442 selector.trap,
443 selector.frame.lea,
444 selector.frame.grow,
445 selector.frame.imm,
446 selector.branch.indirect,
447 ];
448 for name in named {
449 assert!(
450 selector.operands(name).is_some(),
451 "{}{name} is not an instruction of its machine",
452 selector.prefix()
453 );
454 }
455 // And the rules it is handed are the ones written for the same machine.
456 for rule in selector.table.rules {
457 let Some(Piece::App { head, .. }) = rule.replacement.first() else { continue };
458 assert!(head.starts_with(selector.prefix()), "{head} in {}", selector.table.source);
459 }
460 }
461 }
462
463 /// An address constructor is read the same way on both machines, and the one the AArch64 rules
464 /// cannot write is not one it answers for.
465 #[test]
466 fn both_machines_read_an_address_the_same_way() {
467 let (x86, a64) = (&super::x86_64::SELECTOR, &super::aarch64::SELECTOR);
468 for name in ["amode_base", "amode_base_offset"] {
469 assert_eq!((x86.address)(name), (a64.address)(name));
470 assert!((a64.address)(name).is_some());
471 }
472 assert!((x86.address)("amode_base_index_scale").is_some());
473 assert_eq!((a64.address)("amode_base_index_scale"), None);
474 assert_eq!((a64.address)("add_rr_64"), None);
475 }
476}