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