Skip to main content

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