Skip to main content

rucc_codegen/select/
aarch64.rs

1//! The AArch64 lowering table.
2//!
3//! Everything below the module comment is generated from `rules/aarch64.rules` by `rucc-rules`
4//! when this crate is built, the same way the x86-64 table is, and `crate::pipeline::Machine`
5//! hands it to the lowering for any target whose architecture is AArch64.
6
7// The guards are emitted as the comparisons the rules write, for the reason the x86-64 table gives.
8#![allow(clippy::manual_range_contains)]
9
10include!(concat!(env!("OUT_DIR"), "/aarch64.rs"));
11
12/// What the lowering asks of AArch64.
13pub static SELECTOR: super::Selector = super::Selector {
14    table: &TABLE,
15    shapes: &rucc_target::aarch64::MACHINE,
16    address: rucc_target::aarch64::address,
17    frame: &rucc_target::aarch64::FRAME,
18    branch: &rucc_target::aarch64::BRANCH,
19    gpr: rucc_target::aarch64::GPR,
20    fence: "fence",
21    trap: "trap",
22    abi: &crate::abi::aarch64::INSTS,
23    scratch: &crate::pipeline::AARCH64_SCRATCH,
24    symbols: &super::Symbols {
25        near: super::Reach::Own("addr_64"),
26        far: super::Reach::Own("got_64"),
27        thread: super::Reach::Own("gottprel_64"),
28        pointer: super::Pointer::Own("thread_64"),
29        indexed: None,
30    },
31    jumps: &super::Jumps {
32        near: "adr_64",
33        cell: "ldrs_32_64",
34        add: "add_rr_64",
35        two_address: false,
36    },
37};
38
39#[cfg(test)]
40mod tests {
41    use rucc_target::aarch64;
42
43    use super::TABLE;
44    use crate::select::{Piece, Subject};
45
46    /// The prefix the rule file puts in front of a machine term.
47    const PREFIX: &str = "a64.";
48
49    /// The address constructors, which are terms in the rule file and not instructions.
50    const AMODES: &[&str] = &["amode_base", "amode_base_offset"];
51
52    /// A term as a flat arena, which is the shape the x86-64 tests use and the shape the IR has.
53    #[derive(Debug)]
54    enum Node {
55        Int(i128),
56        App(String, Vec<usize>),
57    }
58
59    #[derive(Debug, Default)]
60    struct Terms {
61        nodes: Vec<Node>,
62    }
63
64    impl Terms {
65        fn constant(&mut self, head: &str, value: i128) -> usize {
66            self.nodes.push(Node::Int(value));
67            let at = self.nodes.len() - 1;
68            self.app(head, &[at])
69        }
70
71        fn app(&mut self, head: &str, args: &[usize]) -> usize {
72            self.nodes.push(Node::App(head.to_owned(), args.to_vec()));
73            self.nodes.len() - 1
74        }
75
76        fn value(&mut self, width: &str, name: &str) -> usize {
77            let inner = self.app(name, &[]);
78            self.app(&format!("value.{width}"), &[inner])
79        }
80    }
81
82    impl Subject for Terms {
83        type Node = usize;
84
85        fn head(&self, node: usize) -> Option<(&str, usize)> {
86            match &self.nodes[node] {
87                Node::App(head, args) => Some((head.as_str(), args.len())),
88                Node::Int(_) => None,
89            }
90        }
91
92        fn arg(&self, node: usize, index: usize) -> usize {
93            match &self.nodes[node] {
94                Node::App(_, args) => args[index],
95                Node::Int(_) => unreachable!("a constant has no arguments"),
96            }
97        }
98
99        fn int(&self, node: usize) -> Option<i128> {
100            match self.nodes[node] {
101                Node::Int(value) => Some(value),
102                Node::App(..) => None,
103            }
104        }
105
106        fn same(&self, a: usize, b: usize) -> bool {
107            a == b
108        }
109    }
110
111    fn selects(terms: &Terms, term: usize) -> Option<&'static str> {
112        let found = TABLE.find(terms, term)?;
113        TABLE.rule(&found).head()
114    }
115
116    #[test]
117    fn the_table_holds_every_rule_the_file_writes() {
118        let text = include_str!("../../rules/aarch64.rules");
119        let written = text.lines().filter(|line| line.starts_with("(rule ")).count();
120        assert_eq!(TABLE.rules.len(), written, "the table and the rule file disagree");
121        assert_eq!(TABLE.source, "rules/aarch64.rules");
122    }
123
124    #[test]
125    fn every_instruction_the_table_writes_is_described() {
126        for rule in TABLE.rules {
127            for piece in rule.replacement {
128                let Piece::App { head, .. } = piece else { continue };
129                if AMODES.contains(head) {
130                    continue;
131                }
132                let opcode = head.strip_prefix(PREFIX).unwrap_or_else(|| {
133                    panic!("line {}: {head} is neither an AArch64 term nor an address", rule.line)
134                });
135                assert!(
136                    aarch64::form(opcode).is_some(),
137                    "line {}: {head} is selected and `rucc_target::aarch64` does not describe it",
138                    rule.line
139                );
140            }
141        }
142    }
143
144    /// The narrow widths take the thirty two bit instruction for the operations whose low bits do
145    /// not depend on the high ones, and nothing else reaches them.
146    #[test]
147    fn narrow_arithmetic_is_the_thirty_two_bit_instruction() {
148        let mut terms = Terms::default();
149        for width in ["i8", "i16", "i32"] {
150            let x = terms.value(width, "v0");
151            let y = terms.value(width, "v1");
152            let add = terms.app(&format!("add.{width}"), &[x, y]);
153            assert_eq!(selects(&terms, add), Some("a64.add_rr_32"));
154            let mul = terms.app(&format!("mul.{width}"), &[x, y]);
155            assert_eq!(selects(&terms, mul), Some("a64.mul_rr_32"));
156        }
157        let x = terms.value("i8", "v0");
158        let y = terms.value("i8", "v1");
159        let shift = terms.app("lshr.i8", &[x, y]);
160        assert_eq!(selects(&terms, shift), None);
161        let x = terms.value("i64", "v2");
162        let y = terms.value("i64", "v3");
163        let add = terms.app("add.i64", &[x, y]);
164        assert_eq!(selects(&terms, add), Some("a64.add_rr_64"));
165    }
166
167    /// A narrow right shift by a constant is the instruction that widens first, since the bits
168    /// above a byte or a half in its register are not known.
169    #[test]
170    fn a_narrow_right_shift_by_a_constant_is_the_instruction_that_widens_first() {
171        let mut terms = Terms::default();
172        for (width, bits) in [("i8", 7), ("i16", 15)] {
173            let x = terms.value(width, "v0");
174            let k = terms.constant(&format!("iconst.{width}"), 3);
175            let right = terms.app(&format!("lshr.{width}"), &[x, k]);
176            assert_eq!(selects(&terms, right), Some(&*format!("a64.lsr_ri_{}", &width[1..])));
177            let right = terms.app(&format!("ashr.{width}"), &[x, k]);
178            assert_eq!(selects(&terms, right), Some(&*format!("a64.asr_ri_{}", &width[1..])));
179            let far = terms.constant(&format!("iconst.{width}"), bits + 1);
180            let right = terms.app(&format!("lshr.{width}"), &[x, far]);
181            assert_eq!(selects(&terms, right), None);
182        }
183    }
184
185    /// A constant is one `mov` when it or its complement fits in sixteen bits, or when every
186    /// sixteen bit piece but one is zero or every one but one is all ones. Anything else is built a
187    /// piece at a time, and the outermost instruction says how many pieces: one `movk` under two
188    /// to the thirty two, two when the top piece is zero, and three otherwise.
189    #[test]
190    fn a_constant_is_one_mov_only_when_one_mov_can_build_it() {
191        let mut terms = Terms::default();
192        let wanted = [
193            (0, "a64.mov_ri_64"),
194            (65535, "a64.mov_ri_64"),
195            (-65536, "a64.mov_ri_64"),
196            (65536, "a64.mov_ri_64"),
197            (0x1_0000_0000, "a64.mov_ri_64"),
198            (0x4008_0000_0000_0000, "a64.mov_ri_64"),
199            (-0x1234_0000_0001, "a64.mov_ri_64"),
200            (-0x1_0001, "a64.mov_ri_64"),
201            (0x1_0001, "a64.movk_ri_16_64"),
202            (0xffff_ffff, "a64.movk_ri_16_64"),
203            (0x1_2345_6789, "a64.movk_ri_32_64"),
204            (0x1_0000_0001, "a64.movk_ri_32_64"),
205            (-0x1_0002, "a64.movk_ri_48_64"),
206            (0x1_0000_0000_0001, "a64.movk_ri_48_64"),
207        ];
208        for (value, want) in wanted {
209            let k = terms.constant("iconst.i64", value);
210            assert_eq!(selects(&terms, k), Some(want), "{value}");
211        }
212        let wanted = [
213            (0x1234_5678, "a64.movk_ri_16_32"),
214            (0x4040_0000, "a64.mov_ri_32"),
215            (0x1234_ffff, "a64.mov_ri_32"),
216            (i128::from(i32::MIN), "a64.mov_ri_32"),
217        ];
218        for (value, want) in wanted {
219            let k = terms.constant("iconst.i32", value);
220            assert_eq!(selects(&terms, k), Some(want), "{value}");
221        }
222    }
223
224    /// Every widening and narrowing the IR has between its integer types has a rule.
225    #[test]
226    fn every_widening_and_narrowing_has_an_instruction() {
227        let mut terms = Terms::default();
228        let wanted = [
229            ("sext", "i8", "i16", "a64.sxtb_16"),
230            ("zext", "i8", "i16", "a64.uxtb_16"),
231            ("zext", "i8", "i64", "a64.uxtb_64"),
232            ("zext", "i16", "i64", "a64.uxth_64"),
233            ("zext", "i1", "i8", "a64.bit_to_8"),
234            ("zext", "i1", "i64", "a64.bit_to_64"),
235            ("trunc", "i64", "i32", "a64.low_32"),
236            ("trunc", "i32", "i16", "a64.low_16"),
237            ("trunc", "i16", "i8", "a64.low_8"),
238            ("trunc", "i8", "i1", "a64.bit_of_32"),
239            ("trunc", "i64", "i1", "a64.bit_of_64"),
240        ];
241        for (op, from, to, want) in wanted {
242            let x = terms.value(from, "v0");
243            let term = terms.app(&format!("{op}.{from}.{to}"), &[x]);
244            assert_eq!(selects(&terms, term), Some(want), "{op}.{from}.{to}");
245        }
246    }
247
248    #[test]
249    fn an_immediate_is_taken_when_twelve_bits_hold_it() {
250        let mut terms = Terms::default();
251        let x = terms.value("i32", "v0");
252        let k = terms.constant("iconst.i32", 4095);
253        let add = terms.app("add.i32", &[x, k]);
254        assert_eq!(selects(&terms, add), Some("a64.add_ri_32"));
255        let k = terms.constant("iconst.i32", 4096);
256        let add = terms.app("add.i32", &[x, k]);
257        assert_eq!(selects(&terms, add), None);
258    }
259
260    /// The IR's unsigned predicates are under the architecture's names for them.
261    #[test]
262    fn an_unsigned_comparison_is_the_condition_the_architecture_names() {
263        let mut terms = Terms::default();
264        let x = terms.value("i64", "v0");
265        let y = terms.value("i64", "v1");
266        for (ir, cc) in [("ult", "lo"), ("ule", "ls"), ("ugt", "hi"), ("uge", "hs")] {
267            let term = terms.app(&format!("icmp_{ir}.i1"), &[x, y]);
268            let want = format!("a64.cmp_set_{cc}_64");
269            assert_eq!(selects(&terms, term), Some(want.as_str()));
270        }
271    }
272
273    /// Every comparison against a register has one against a constant, for the reason the x86-64
274    /// table counts them.
275    #[test]
276    fn a_comparison_against_a_constant_is_written_for_every_one_against_a_register() {
277        let mut against_register = Vec::new();
278        let mut against_constant = Vec::new();
279        let mut narrow = 0;
280        for rule in TABLE.rules {
281            let Some(rest) = rule.pattern.strip_prefix("(icmp_") else { continue };
282            let (condition, operands) = rest.split_once(".i1 ").expect("a comparison takes two");
283            let width = operands
284                .strip_prefix("(value.")
285                .and_then(|rest| rest.split_once(' '))
286                .map(|(width, _)| width)
287                .expect("a comparison reads a value first");
288            // The narrow widths compare two registers, each widened first, and have no form
289            // against a constant.
290            if matches!(width, "i8" | "i16") {
291                narrow += 1;
292                continue;
293            }
294            let named = format!("{condition}.{width}");
295            if operands.contains("(iconst.") {
296                against_constant.push(named);
297            } else {
298                against_register.push(named);
299            }
300        }
301        against_register.sort_unstable();
302        against_constant.sort_unstable();
303        assert_eq!(against_register, against_constant);
304        assert_eq!(against_register.len(), 20, "ten conditions at two widths");
305        assert_eq!(narrow, 20, "ten conditions at the two narrow widths");
306    }
307
308    /// The value comes first in a store, which is where the IR keeps it.
309    #[test]
310    fn a_store_is_written_with_the_value_first() {
311        let mut seen = 0;
312        for rule in TABLE.rules {
313            let Some(rest) = rule.pattern.strip_prefix("(store.") else { continue };
314            let (width, operands) = rest.split_once(' ').expect("a store takes operands");
315            assert!(
316                operands.starts_with(&format!("(value.{width} ")),
317                "line {}: {} binds something other than the value first",
318                rule.line,
319                rule.pattern
320            );
321            seen += 1;
322        }
323        assert_eq!(seen, 16, "the store rules moved and this test did not follow them");
324    }
325
326    /// An offset the unscaled form holds goes into the address, and one it does not leaves the
327    /// addition where it is.
328    #[test]
329    fn a_small_offset_is_part_of_the_address() {
330        let mut terms = Terms::default();
331        let a = terms.value("i64", "v0");
332        let k = terms.constant("iconst.i64", -8);
333        let at = terms.app("add.i64", &[a, k]);
334        let load = terms.app("load.i32", &[at]);
335        let found = TABLE.find(&terms, load).expect("a rule fires");
336        assert_eq!(TABLE.rule(&found).head(), Some("a64.ldr_32"));
337        assert!(
338            TABLE
339                .rule(&found)
340                .replacement
341                .iter()
342                .any(|piece| matches!(piece, Piece::App { head: "amode_base_offset", .. }))
343        );
344        let k = terms.constant("iconst.i64", 256);
345        let at = terms.app("add.i64", &[a, k]);
346        let load = terms.app("load.i32", &[at]);
347        assert_eq!(selects(&terms, load), None);
348    }
349}