1#![allow(clippy::manual_range_contains)]
9
10include!(concat!(env!("OUT_DIR"), "/aarch64.rs"));
11
12pub 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 },
30 jumps: &super::Jumps {
31 near: "adr_64",
32 cell: "ldrs_32_64",
33 add: "add_rr_64",
34 two_address: false,
35 },
36};
37
38#[cfg(test)]
39mod tests {
40 use rucc_target::aarch64;
41
42 use super::TABLE;
43 use crate::select::{Piece, Subject};
44
45 const PREFIX: &str = "a64.";
47
48 const AMODES: &[&str] = &["amode_base", "amode_base_offset"];
50
51 #[derive(Debug)]
53 enum Node {
54 Int(i128),
55 App(String, Vec<usize>),
56 }
57
58 #[derive(Debug, Default)]
59 struct Terms {
60 nodes: Vec<Node>,
61 }
62
63 impl Terms {
64 fn constant(&mut self, head: &str, value: i128) -> usize {
65 self.nodes.push(Node::Int(value));
66 let at = self.nodes.len() - 1;
67 self.app(head, &[at])
68 }
69
70 fn app(&mut self, head: &str, args: &[usize]) -> usize {
71 self.nodes.push(Node::App(head.to_owned(), args.to_vec()));
72 self.nodes.len() - 1
73 }
74
75 fn value(&mut self, width: &str, name: &str) -> usize {
76 let inner = self.app(name, &[]);
77 self.app(&format!("value.{width}"), &[inner])
78 }
79 }
80
81 impl Subject for Terms {
82 type Node = usize;
83
84 fn head(&self, node: usize) -> Option<(&str, usize)> {
85 match &self.nodes[node] {
86 Node::App(head, args) => Some((head.as_str(), args.len())),
87 Node::Int(_) => None,
88 }
89 }
90
91 fn arg(&self, node: usize, index: usize) -> usize {
92 match &self.nodes[node] {
93 Node::App(_, args) => args[index],
94 Node::Int(_) => unreachable!("a constant has no arguments"),
95 }
96 }
97
98 fn int(&self, node: usize) -> Option<i128> {
99 match self.nodes[node] {
100 Node::Int(value) => Some(value),
101 Node::App(..) => None,
102 }
103 }
104
105 fn same(&self, a: usize, b: usize) -> bool {
106 a == b
107 }
108 }
109
110 fn selects(terms: &Terms, term: usize) -> Option<&'static str> {
111 let found = TABLE.find(terms, term)?;
112 TABLE.rule(&found).head()
113 }
114
115 #[test]
116 fn the_table_holds_every_rule_the_file_writes() {
117 let text = include_str!("../../rules/aarch64.rules");
118 let written = text.lines().filter(|line| line.starts_with("(rule ")).count();
119 assert_eq!(TABLE.rules.len(), written, "the table and the rule file disagree");
120 assert_eq!(TABLE.source, "rules/aarch64.rules");
121 }
122
123 #[test]
124 fn every_instruction_the_table_writes_is_described() {
125 for rule in TABLE.rules {
126 for piece in rule.replacement {
127 let Piece::App { head, .. } = piece else { continue };
128 if AMODES.contains(head) {
129 continue;
130 }
131 let opcode = head.strip_prefix(PREFIX).unwrap_or_else(|| {
132 panic!("line {}: {head} is neither an AArch64 term nor an address", rule.line)
133 });
134 assert!(
135 aarch64::form(opcode).is_some(),
136 "line {}: {head} is selected and `rucc_target::aarch64` does not describe it",
137 rule.line
138 );
139 }
140 }
141 }
142
143 #[test]
146 fn narrow_arithmetic_is_the_thirty_two_bit_instruction() {
147 let mut terms = Terms::default();
148 for width in ["i8", "i16", "i32"] {
149 let x = terms.value(width, "v0");
150 let y = terms.value(width, "v1");
151 let add = terms.app(&format!("add.{width}"), &[x, y]);
152 assert_eq!(selects(&terms, add), Some("a64.add_rr_32"));
153 let mul = terms.app(&format!("mul.{width}"), &[x, y]);
154 assert_eq!(selects(&terms, mul), Some("a64.mul_rr_32"));
155 }
156 let x = terms.value("i8", "v0");
157 let y = terms.value("i8", "v1");
158 let shift = terms.app("lshr.i8", &[x, y]);
159 assert_eq!(selects(&terms, shift), None);
160 let x = terms.value("i64", "v2");
161 let y = terms.value("i64", "v3");
162 let add = terms.app("add.i64", &[x, y]);
163 assert_eq!(selects(&terms, add), Some("a64.add_rr_64"));
164 }
165
166 #[test]
169 fn a_narrow_right_shift_by_a_constant_is_the_instruction_that_widens_first() {
170 let mut terms = Terms::default();
171 for (width, bits) in [("i8", 7), ("i16", 15)] {
172 let x = terms.value(width, "v0");
173 let k = terms.constant(&format!("iconst.{width}"), 3);
174 let right = terms.app(&format!("lshr.{width}"), &[x, k]);
175 assert_eq!(selects(&terms, right), Some(&*format!("a64.lsr_ri_{}", &width[1..])));
176 let right = terms.app(&format!("ashr.{width}"), &[x, k]);
177 assert_eq!(selects(&terms, right), Some(&*format!("a64.asr_ri_{}", &width[1..])));
178 let far = terms.constant(&format!("iconst.{width}"), bits + 1);
179 let right = terms.app(&format!("lshr.{width}"), &[x, far]);
180 assert_eq!(selects(&terms, right), None);
181 }
182 }
183
184 #[test]
189 fn a_constant_is_one_mov_only_when_one_mov_can_build_it() {
190 let mut terms = Terms::default();
191 let wanted = [
192 (0, "a64.mov_ri_64"),
193 (65535, "a64.mov_ri_64"),
194 (-65536, "a64.mov_ri_64"),
195 (65536, "a64.mov_ri_64"),
196 (0x1_0000_0000, "a64.mov_ri_64"),
197 (0x4008_0000_0000_0000, "a64.mov_ri_64"),
198 (-0x1234_0000_0001, "a64.mov_ri_64"),
199 (-0x1_0001, "a64.mov_ri_64"),
200 (0x1_0001, "a64.movk_ri_16_64"),
201 (0xffff_ffff, "a64.movk_ri_16_64"),
202 (0x1_2345_6789, "a64.movk_ri_32_64"),
203 (0x1_0000_0001, "a64.movk_ri_32_64"),
204 (-0x1_0002, "a64.movk_ri_48_64"),
205 (0x1_0000_0000_0001, "a64.movk_ri_48_64"),
206 ];
207 for (value, want) in wanted {
208 let k = terms.constant("iconst.i64", value);
209 assert_eq!(selects(&terms, k), Some(want), "{value}");
210 }
211 let wanted = [
212 (0x1234_5678, "a64.movk_ri_16_32"),
213 (0x4040_0000, "a64.mov_ri_32"),
214 (0x1234_ffff, "a64.mov_ri_32"),
215 (i128::from(i32::MIN), "a64.mov_ri_32"),
216 ];
217 for (value, want) in wanted {
218 let k = terms.constant("iconst.i32", value);
219 assert_eq!(selects(&terms, k), Some(want), "{value}");
220 }
221 }
222
223 #[test]
225 fn every_widening_and_narrowing_has_an_instruction() {
226 let mut terms = Terms::default();
227 let wanted = [
228 ("sext", "i8", "i16", "a64.sxtb_16"),
229 ("zext", "i8", "i16", "a64.uxtb_16"),
230 ("zext", "i8", "i64", "a64.uxtb_64"),
231 ("zext", "i16", "i64", "a64.uxth_64"),
232 ("zext", "i1", "i8", "a64.bit_to_8"),
233 ("zext", "i1", "i64", "a64.bit_to_64"),
234 ("trunc", "i64", "i32", "a64.low_32"),
235 ("trunc", "i32", "i16", "a64.low_16"),
236 ("trunc", "i16", "i8", "a64.low_8"),
237 ("trunc", "i8", "i1", "a64.bit_of_32"),
238 ("trunc", "i64", "i1", "a64.bit_of_64"),
239 ];
240 for (op, from, to, want) in wanted {
241 let x = terms.value(from, "v0");
242 let term = terms.app(&format!("{op}.{from}.{to}"), &[x]);
243 assert_eq!(selects(&terms, term), Some(want), "{op}.{from}.{to}");
244 }
245 }
246
247 #[test]
248 fn an_immediate_is_taken_when_twelve_bits_hold_it() {
249 let mut terms = Terms::default();
250 let x = terms.value("i32", "v0");
251 let k = terms.constant("iconst.i32", 4095);
252 let add = terms.app("add.i32", &[x, k]);
253 assert_eq!(selects(&terms, add), Some("a64.add_ri_32"));
254 let k = terms.constant("iconst.i32", 4096);
255 let add = terms.app("add.i32", &[x, k]);
256 assert_eq!(selects(&terms, add), None);
257 }
258
259 #[test]
261 fn an_unsigned_comparison_is_the_condition_the_architecture_names() {
262 let mut terms = Terms::default();
263 let x = terms.value("i64", "v0");
264 let y = terms.value("i64", "v1");
265 for (ir, cc) in [("ult", "lo"), ("ule", "ls"), ("ugt", "hi"), ("uge", "hs")] {
266 let term = terms.app(&format!("icmp_{ir}.i1"), &[x, y]);
267 let want = format!("a64.cmp_set_{cc}_64");
268 assert_eq!(selects(&terms, term), Some(want.as_str()));
269 }
270 }
271
272 #[test]
275 fn a_comparison_against_a_constant_is_written_for_every_one_against_a_register() {
276 let mut against_register = Vec::new();
277 let mut against_constant = Vec::new();
278 let mut narrow = 0;
279 for rule in TABLE.rules {
280 let Some(rest) = rule.pattern.strip_prefix("(icmp_") else { continue };
281 let (condition, operands) = rest.split_once(".i1 ").expect("a comparison takes two");
282 let width = operands
283 .strip_prefix("(value.")
284 .and_then(|rest| rest.split_once(' '))
285 .map(|(width, _)| width)
286 .expect("a comparison reads a value first");
287 if matches!(width, "i8" | "i16") {
290 narrow += 1;
291 continue;
292 }
293 let named = format!("{condition}.{width}");
294 if operands.contains("(iconst.") {
295 against_constant.push(named);
296 } else {
297 against_register.push(named);
298 }
299 }
300 against_register.sort_unstable();
301 against_constant.sort_unstable();
302 assert_eq!(against_register, against_constant);
303 assert_eq!(against_register.len(), 20, "ten conditions at two widths");
304 assert_eq!(narrow, 20, "ten conditions at the two narrow widths");
305 }
306
307 #[test]
309 fn a_store_is_written_with_the_value_first() {
310 let mut seen = 0;
311 for rule in TABLE.rules {
312 let Some(rest) = rule.pattern.strip_prefix("(store.") else { continue };
313 let (width, operands) = rest.split_once(' ').expect("a store takes operands");
314 assert!(
315 operands.starts_with(&format!("(value.{width} ")),
316 "line {}: {} binds something other than the value first",
317 rule.line,
318 rule.pattern
319 );
320 seen += 1;
321 }
322 assert_eq!(seen, 16, "the store rules moved and this test did not follow them");
323 }
324
325 #[test]
328 fn a_small_offset_is_part_of_the_address() {
329 let mut terms = Terms::default();
330 let a = terms.value("i64", "v0");
331 let k = terms.constant("iconst.i64", -8);
332 let at = terms.app("add.i64", &[a, k]);
333 let load = terms.app("load.i32", &[at]);
334 let found = TABLE.find(&terms, load).expect("a rule fires");
335 assert_eq!(TABLE.rule(&found).head(), Some("a64.ldr_32"));
336 assert!(
337 TABLE
338 .rule(&found)
339 .replacement
340 .iter()
341 .any(|piece| matches!(piece, Piece::App { head: "amode_base_offset", .. }))
342 );
343 let k = terms.constant("iconst.i64", 256);
344 let at = terms.app("add.i64", &[a, k]);
345 let load = terms.app("load.i32", &[at]);
346 assert_eq!(selects(&terms, load), None);
347 }
348}