rucc_codegen/select/x86_64.rs
1//! The x86-64 lowering table.
2//!
3//! Everything below the module comment is generated from `rules/x86-64.rules` by `rucc-rules`
4//! when this crate is built, and none of it is in the repository. The rule file is the only
5//! place the rules are written, which is what makes the table that is matched with and the
6//! table `rucc-verify` proves things about the same table.
7//!
8//! To read the rules, read the rule file. To read the automaton they compile into, build the
9//! crate and read `x86-64.rs` under the build directory, which is a file worth looking at once
10//! for the shape of it and never again.
11
12// A guard is emitted as the comparison the rule writes, so a rule saying a shift count is at
13// least zero and less than the width comes out as two comparisons rather than as a range. That
14// is deliberate: the generated line and the rule it came from should read the same, and the
15// suggestion to write it another way is advice for somebody editing code, which nobody here is.
16#![allow(clippy::manual_range_contains)]
17
18include!(concat!(env!("OUT_DIR"), "/x86-64.rs"));
19
20/// What the lowering asks of x86-64.
21pub static SELECTOR: super::Selector = super::Selector {
22 table: &TABLE,
23 shapes: &rucc_target::x86_64::MACHINE,
24 address: rucc_target::x86_64::address,
25 frame: &rucc_target::x86_64::FRAME,
26 branch: &rucc_target::x86_64::BRANCH,
27 gpr: rucc_target::x86_64::GPR,
28 fence: "mfence",
29 trap: "ud2",
30 abi: &crate::abi::X86_64,
31 scratch: &crate::pipeline::SCRATCH,
32 symbols: &super::Symbols {
33 near: super::Reach::Mode("lea_64"),
34 far: super::Reach::Mode("mov_rm_64"),
35 // The relocation a thread-local variable's slot takes is only legal on a `mov` with a REX
36 // prefix, so the width here is part of the requirement rather than a choice.
37 thread: super::Reach::Mode("mov_rm_64"),
38 pointer: super::Pointer::Segment("mov_rm_64", rucc_target::Segment::Fs),
39 },
40 jumps: &super::Jumps {
41 near: "lea_64",
42 cell: "movsxd_rm_32_64",
43 add: "add_rr_64",
44 two_address: true,
45 },
46};
47
48#[cfg(test)]
49mod tests {
50 use rucc_target::x86_64;
51
52 use super::TABLE;
53 use crate::select::Piece;
54
55 /// The prefix a rule file puts in front of a machine term, which is how it says which target
56 /// the term belongs to. It is not part of the opcode.
57 const PREFIX: &str = "x64.";
58
59 /// The two address constructors, which are not instructions. An addressing mode is an
60 /// argument to `lea` and to every memory operand after it, so it is written as a term in the
61 /// rule file and built by the selector into the instruction that takes it.
62 const AMODES: &[&str] =
63 &["amode_base_index_scale", "amode_index_scale", "amode_base", "amode_base_offset"];
64
65 /// Every head this table can write, in and under the replacements.
66 fn heads() -> Vec<&'static str> {
67 let mut found: Vec<&'static str> = TABLE
68 .rules
69 .iter()
70 .flat_map(|rule| rule.replacement.iter())
71 .filter_map(|piece| match piece {
72 Piece::App { head, .. } => Some(*head),
73 _ => None,
74 })
75 .collect();
76 found.sort_unstable();
77 found.dedup();
78 found
79 }
80
81 #[test]
82 fn every_instruction_the_table_writes_is_described() {
83 for head in heads() {
84 if AMODES.contains(&head) {
85 continue;
86 }
87 let opcode = head.strip_prefix(PREFIX).unwrap_or_else(|| {
88 panic!("{head} is neither an x86-64 term nor an addressing mode")
89 });
90 assert!(
91 x86_64::form(opcode).is_some(),
92 "{head} is selected by a rule and `rucc_target::x86_64` does not say what it \
93 does with its operands"
94 );
95 }
96 }
97
98 /// The order the operands of a store are written in, which is the IR's and not a choice this
99 /// file makes.
100 ///
101 /// A pattern is matched against an instruction's operand list by position, so a rule that
102 /// names the address where the IR holds the value is a rule that stores to the value and
103 /// writes the address into memory. Nothing in a proof would catch it, because a proof is
104 /// about the rule file agreeing with itself, and both halves would be wrong in the same way.
105 /// `rucc_ir::Builder::store` takes the value first and the machine instruction takes it last,
106 /// which is why the two halves of one of these rules read in opposite orders.
107 #[test]
108 fn a_store_is_written_with_the_value_first_because_that_is_where_the_ir_keeps_it() {
109 let mut seen = 0;
110 for rule in TABLE.rules {
111 let Some(rest) = rule.pattern.strip_prefix("(store.") else { continue };
112 let (width, operands) = rest.split_once(' ').expect("a store takes operands");
113 assert!(
114 operands.starts_with(&format!("(value.{width} ")),
115 "line {}: {} binds something other than the value it is storing first",
116 rule.line,
117 rule.pattern
118 );
119 assert!(
120 operands.contains("(value.i64 "),
121 "line {}: {} reaches no address",
122 rule.line,
123 rule.pattern
124 );
125 seen += 1;
126 }
127 assert_eq!(seen, 16, "the store rules moved and this test did not follow them");
128 }
129
130 /// Every comparison can be made against a constant as well as against a register.
131 ///
132 /// Four comparisons in five in the corpus are against a constant, and without a rule for one
133 /// the constant is loaded into a register first, which is an instruction and a register the
134 /// machine never needed. A missing width or a missing condition would not fail anything else:
135 /// the register rule still matches, the output is still correct, and the only sign is code
136 /// that is one instruction longer in a place nobody is looking. So the two lists are counted
137 /// against each other here.
138 ///
139 /// What this cannot check is that the condition on the immediate rule is the right one, since
140 /// both halves of a wrong pair would be a consistent pair. That is what the `spec` clause is
141 /// for, and `rucc-verify` is what reads it.
142 #[test]
143 fn a_comparison_against_a_constant_is_written_for_every_one_against_a_register() {
144 let mut against_register = Vec::new();
145 let mut against_constant = Vec::new();
146 for rule in TABLE.rules {
147 let Some(rest) = rule.pattern.strip_prefix("(icmp_") else { continue };
148 let (condition, operands) = rest.split_once(".i1 ").expect("a comparison takes two");
149 let width = operands
150 .strip_prefix("(value.")
151 .and_then(|rest| rest.split_once(' '))
152 .map(|(width, _)| width)
153 .expect("a comparison reads a value first");
154 let named = format!("{condition}.{width}");
155 if operands.contains("(iconst.") {
156 // The constant is the second operand and never the first, because a comparison is
157 // not symmetric and the same condition on the other side means the opposite.
158 assert!(
159 !operands.starts_with("(iconst."),
160 "line {}: {} compares a constant against a value",
161 rule.line,
162 rule.pattern
163 );
164 against_constant.push(named);
165 } else {
166 against_register.push(named);
167 }
168 }
169 against_register.sort_unstable();
170 against_constant.sort_unstable();
171 assert_eq!(against_register, against_constant);
172 assert_eq!(against_register.len(), 40, "ten conditions at four widths");
173 }
174
175 /// The instructions the calling convention writes rather than a rule.
176 ///
177 /// Three kinds of them. Naming the register an argument arrived in, where an argument is
178 /// depends on its position in the signature and on the classification of every argument before
179 /// it, and a rule pattern sees one term and has no way to say any of that, so `crate::abi`
180 /// builds these from the convention instead. Calling a name is the same the other way round:
181 /// what its operands are is whatever the signature made them, and a call through an address is
182 /// the same instruction with one operand more.
183 ///
184 /// The second half of a value that comes back in two registers is the third. A return of one
185 /// value is a rule, because where that value goes depends on nothing but the value, which is
186 /// exactly what a rule can say. A return of two is not, because which register the second half
187 /// is in depends on the first half: the two register files are counted separately, so a
188 /// `double` and a `long` both come back at place zero and two `long`s do not.
189 const CONVENTION: &[&str] = &[
190 "arg_val_8",
191 "arg_val_16",
192 "arg_val_32",
193 "arg_val_64",
194 "arg_val_f16",
195 "arg_val_f32",
196 "arg_val_f64",
197 "arg_val_f128",
198 "ret_val2_8",
199 "ret_val2_16",
200 "ret_val2_32",
201 "ret_val2_64",
202 "ret_val2_f16",
203 "ret_val2_f32",
204 "ret_val2_f64",
205 "ret_val2_f128",
206 "call",
207 "call_reg",
208 ];
209
210 /// The instructions the block layout writes rather than a rule.
211 ///
212 /// A rule sees one branch and the layout is about the order of every block in the function, so
213 /// which arm falls through is not something any pattern could say. That answer is what decides
214 /// whether the jump goes to the arm the condition is true for or the other one, and whether
215 /// there is a second jump after it, so all of these are written where the answer is.
216 ///
217 /// The comparisons are here for a second reason on top of that one. A branch on a comparison
218 /// is a comparison and a jump on the flags it set, and the flags are not a value: no pattern
219 /// could bind one and no `spec` clause could say anything about one. So the pair is put
220 /// together by the layout, out of a comparison a rule did select and the branch behind it,
221 /// which is the same argument `rucc_target::x86_64::Form::CmpSet` is one form rather than two
222 /// under.
223 /// The instructions the size directed peephole writes rather than a rule.
224 ///
225 /// [`crate::shorten`] turns a comparison of a register against zero into a test of the register
226 /// against itself, which asks the machine the same thing in one byte less, and an addition of
227 /// one into the instruction that adds one and says so in its opcode, which is another byte less.
228 /// No rule could select either. Whether the first says the same thing depends on the constant
229 /// the comparison carries and a pattern binds a value rather than reads a number out of one, and
230 /// whether the second does depends on what reads the carry behind it, which is not something a
231 /// pattern sees at all. The eight bit test is not here because the layout writes that one as
232 /// well and it is on the list below.
233 const PEEPHOLE: &[&str] = &[
234 "test_rr_16",
235 "test_rr_32",
236 "test_rr_64",
237 "inc_r_8",
238 "inc_r_16",
239 "inc_r_32",
240 "inc_r_64",
241 "dec_r_8",
242 "dec_r_16",
243 "dec_r_32",
244 "dec_r_64",
245 ];
246
247 const LAYOUT: &[&str] = &[
248 "test_rr_8",
249 "cmp_rr_8",
250 "cmp_rr_16",
251 "cmp_rr_32",
252 "cmp_rr_64",
253 "cmp_ri_8",
254 "cmp_ri_16",
255 "cmp_ri_32",
256 "cmp_ri_64",
257 "cmp_rm_8",
258 "cmp_rm_16",
259 "cmp_rm_32",
260 "cmp_rm_64",
261 "cmp_mi_8",
262 "cmp_mi_16",
263 "cmp_mi_32",
264 "cmp_mi_64",
265 "jcc_e",
266 "jcc_ne",
267 "jcc_l",
268 "jcc_le",
269 "jcc_g",
270 "jcc_ge",
271 "jcc_b",
272 "jcc_be",
273 "jcc_a",
274 "jcc_ae",
275 "jmp",
276 ];
277
278 /// The instructions the compare pass writes rather than a rule.
279 ///
280 /// The other half of the argument the comparisons above are here under. A rule selects a
281 /// comparison that keeps its answer in a byte, because that is the shape a value has. What is
282 /// left of one when the machine has already made the comparison is the byte with no comparison
283 /// in front of it, and there is no pattern for that: the term it would compute is the same term
284 /// the full comparison computes, and what makes the short one right is the instruction three
285 /// places back rather than anything about the value. So `crate::compare` writes them by name,
286 /// in place of a comparison it found was already made.
287 const COMPARE: &[&str] = &[
288 "set_e", "set_ne", "set_l", "set_le", "set_g", "set_ge", "set_b", "set_be", "set_a",
289 "set_ae",
290 ];
291
292 /// The instruction a computed `goto` is written as rather than a rule.
293 ///
294 /// The one branch `crate::lower` writes by name, and the one the block layout does not write
295 /// either. What it reads is the address, which a pattern could have bound, so it is not
296 /// exempt for the reason the branches above are. What no pattern can say is the rest of it:
297 /// how many arms the block has, which is every label of the function the program took the
298 /// address of, and a rule says what an instruction reads rather than where a block goes.
299 const LABELS: &[&str] = &["jmp_reg"];
300
301 /// The load a jump table is read with, which `crate::lower` writes by name next to the jump
302 /// above. The address it reads is a table of this function rather than a value in the IR,
303 /// and no IR instruction loads from a place that is not a value, so there is nothing a rule
304 /// could match it from.
305 const CELL: &[&str] = &["movsxd_rm_32_64"];
306
307 /// The instruction the memory model writes rather than a rule.
308 ///
309 /// A barrier computes nothing, so there is no equality for the solver to discharge and no
310 /// pattern for a rule to be written as. What makes it the right answer is what the machine
311 /// promises about the order two other instructions become visible in, which is a claim about
312 /// the program around it rather than about any value. `crate::lower` writes it by name, at the
313 /// strongest ordering and nowhere else, and `crate::expand` says why the strongest is the only
314 /// one that costs anything here.
315 const BARRIER: &[&str] = &["mfence"];
316
317 /// The instruction a program stops on, which `crate::lower` writes rather than a rule.
318 ///
319 /// The first half of the barrier's reason and not the second. It computes nothing, so there is
320 /// no equality for the solver and no pattern for a rule. What makes it right is not a claim
321 /// about the order anything becomes visible in either: it is what the operating system does
322 /// with the fault, which is a fact about neither the values nor the program around it.
323 const STOP: &[&str] = &["ud2"];
324
325 /// The instructions that are a hint rather than a computation.
326 ///
327 /// The same shape of exemption the barrier gets and for a reason one step further out. A
328 /// barrier computes nothing and still has to be where it is, so there is at least a claim about
329 /// the program around it. A prefetch does not even have that: a machine that drops the whole
330 /// instruction runs the program correctly, because the only thing it can change is how long the
331 /// program takes.
332 ///
333 /// So there is no equality for the solver and no pattern for a rule, and which of the four a
334 /// program gets is decided by a number in the builtin's own arguments rather than by anything
335 /// about the value being prefetched. `crate::lower` writes them by name, out of the hint the IR
336 /// carries beside the instruction.
337 const HINT: &[&str] = &["prefetch_nta", "prefetch_t0", "prefetch_t1", "prefetch_t2"];
338
339 /// The instructions nothing but an `asm` statement asks for.
340 ///
341 /// One step further out again. A prefetch is a hint and is still something the compiler decides
342 /// to write, out of a builtin the program called. These are instructions the program wrote down
343 /// itself, by name, in a template, and nothing else in the language reaches them: there is no
344 /// builtin for either, no rule could match a term that produces one, and `crate::lower` writes
345 /// them only because [`rucc_target::x86_64::read`] found the name in a template and said which
346 /// opcode that is.
347 ///
348 /// `pause` is the hint a spin lock writes between two tries at the lock. `cpuid` is how a
349 /// program asks the processor what it can do, which there is no other way to ask, so every
350 /// program that takes a faster path on some machines than on others has one of these in it.
351 ///
352 /// The alignment is the third, and it is on this list rather than one of its own because it
353 /// meets the claim below outright: an instruction is exempt for this reason exactly when there
354 /// is nothing about it for a rule to name, and an opcode with no operands and no addressing mode
355 /// has nothing. It is not an instruction at all, which is more than the test asks and is the
356 /// reason no rule could have been written for it however the rule language grew.
357 ///
358 /// A byte out of a template is the fourth and is there for the same reason as the alignment,
359 /// one step further still: it is not an instruction, and what it holds is a byte the program
360 /// wrote out itself because its assembler was older than the instruction it wanted. There is
361 /// nothing for a rule to have said about a number a program handed the processor directly.
362 ///
363 /// A template kept as text is the fifth, and is further again: it is not even one instruction,
364 /// it is whatever the program wrote that could not be read as instructions.
365 const TEMPLATE: &[&str] = &["cpuid", "pause", "align", "byte", "template"];
366
367 /// The rotates and the test against a constant, which a template writes and nothing else does.
368 ///
369 /// A rotate is a term the IR could have, and does not yet: C spells one as two shifts and an or,
370 /// and nothing puts those back together. A test against a constant is an and whose answer is
371 /// thrown away, and the layout writes a comparison for that rather than this. A store of a
372 /// constant goes through a register when the compiler writes it. So what reaches one of these
373 /// is a program that wrote the name, which is what tcc's byte swap, its copy of `memcpy` and
374 /// its test of `"m"` operands do.
375 const TEMPLATED: &[&str] = &[
376 "rol_ri_8",
377 "rol_ri_16",
378 "rol_ri_32",
379 "rol_ri_64",
380 "rol_rcl_8",
381 "rol_rcl_16",
382 "rol_rcl_32",
383 "rol_rcl_64",
384 "ror_ri_8",
385 "ror_ri_16",
386 "ror_ri_32",
387 "ror_ri_64",
388 "ror_rcl_8",
389 "ror_rcl_16",
390 "ror_rcl_32",
391 "ror_rcl_64",
392 "test_ri_8",
393 "test_ri_16",
394 "test_ri_32",
395 "test_ri_64",
396 "mov_mi_8",
397 "mov_mi_16",
398 "mov_mi_32",
399 "mov_mi_64",
400 ];
401
402 /// The instructions a template asks for that are right because of the line above them.
403 ///
404 /// These are exempt for the reason the ten bytes in [`COMPARE`] are, one step further out. A
405 /// rule selects a conditional move with its comparison in front of it, because that pair is the
406 /// shape a select has. The move on its own computes the same term and what makes it right is the
407 /// comparison somewhere behind it rather than anything about its own operands, so no pattern
408 /// could say what it means. The compare pass does not write one either, because it replaces a
409 /// comparison it found was already made and there is no earlier move here to replace. What
410 /// writes one is a program that put the comparison on one line of a template and the move on the
411 /// next, which is what zstd does to keep a bounds check from becoming a branch, and
412 /// [`crate::choice`] after the layout, out of a select a rule did write and the comparison its
413 /// byte came from.
414 ///
415 /// So these have operands a rule could have named, unlike everything in [`TEMPLATE`], and they
416 /// are still not instructions a rule could have been written for.
417 ///
418 /// The jumps on the sign, the overflow and the parity are here for the same reason. The layout
419 /// writes the other ten behind a comparison it chose, and nothing chooses one of these: a C
420 /// condition never asks about one bit on its own, so the only line above one is a line in a
421 /// template, which is what a loop in tcc's tests that counts down with `dec` and stops on `js`
422 /// is.
423 /// The add with carry and the subtract with borrow, which read a bit off the instruction in
424 /// front of them.
425 ///
426 /// Exempt one step further out again than [`CONDITIONAL`]. A conditional move reads the
427 /// condition state and leaves it alone, so what is missing from a rule that named one is the
428 /// comparison. These read it and write it both, and what is missing is worse than a comparison:
429 /// the bit they read is the carry out of an addition, and an addition in the IR is an addition
430 /// of a width with no carry out at all, so there is no term a rule could match that the bit is
431 /// a part of. A program gets one by writing both halves itself in a template, which is what
432 /// `add_ssaaaa` and `sub_ddmmss` in libgmp's `longlong.h` are. The form against a constant is
433 /// here for the same reason and is the same instruction with a zero where the second source is,
434 /// which `add_sssaaaa` writes for the top word of a number three words wide.
435 ///
436 /// What keeps the two halves together once they are two instructions in a block is not here. It
437 /// is `rucc_target::FlagInsts`, which the scheduler reads for exactly this, and the test below
438 /// checks the entry is there rather than trusting that somebody remembered.
439 const CARRY: &[&str] = &[
440 "adc_rr_8",
441 "adc_rr_16",
442 "adc_rr_32",
443 "adc_rr_64",
444 "sbb_rr_8",
445 "sbb_rr_16",
446 "sbb_rr_32",
447 "sbb_rr_64",
448 "adc_ri_8",
449 "adc_ri_16",
450 "adc_ri_32",
451 "adc_ri_64",
452 "sbb_ri_8",
453 "sbb_ri_16",
454 "sbb_ri_32",
455 "sbb_ri_64",
456 ];
457
458 const CONDITIONAL: &[&str] = &[
459 "cmov_e_16",
460 "cmov_e_32",
461 "cmov_e_64",
462 "cmov_ne_16",
463 "cmov_ne_32",
464 "cmov_ne_64",
465 "cmov_l_16",
466 "cmov_l_32",
467 "cmov_l_64",
468 "cmov_le_16",
469 "cmov_le_32",
470 "cmov_le_64",
471 "cmov_g_16",
472 "cmov_g_32",
473 "cmov_g_64",
474 "cmov_ge_16",
475 "cmov_ge_32",
476 "cmov_ge_64",
477 "cmov_b_16",
478 "cmov_b_32",
479 "cmov_b_64",
480 "cmov_be_16",
481 "cmov_be_32",
482 "cmov_be_64",
483 "cmov_a_16",
484 "cmov_a_32",
485 "cmov_a_64",
486 "cmov_ae_16",
487 "cmov_ae_32",
488 "cmov_ae_64",
489 "jcc_s",
490 "jcc_ns",
491 "jcc_o",
492 "jcc_no",
493 "jcc_p",
494 "jcc_np",
495 ];
496
497 /// The instructions that look for a set bit, which a template asks for and nothing else does.
498 ///
499 /// These have a source and a destination a rule could have named, the way the conditional moves
500 /// above do, and the reason no rule names them is a different one again. It is not that their
501 /// meaning comes from the line in front of them: each of these says on its own exactly what it
502 /// computes. It is that [`crate::expand`] already answers the question they answer, out of
503 /// arithmetic every machine has, and it does that because what these do when the source is zero
504 /// is four different things on four families of processor. A rule that selected one would be a
505 /// rule whose answer depends on which machine ran it.
506 ///
507 /// So the only thing that reaches one is a program that wrote the name in a template, which is
508 /// what the libraries that were counting bits before there was a builtin for it all do.
509 /// `crate::lower` writes them for the reason it writes the three in [`TEMPLATE`], and they are
510 /// not on that list because they are not bare: a rule could have named these operands and the
511 /// claim that list makes would be false of them.
512 const SEARCH: &[&str] = &[
513 "bsf_16", "bsf_32", "bsf_64", "bsr_16", "bsr_32", "bsr_64", "lzcnt_32", "lzcnt_64",
514 "tzcnt_32", "tzcnt_64",
515 ];
516
517 /// The instruction that turns a register round, which a template asks for and nothing else does.
518 ///
519 /// The list above, one step simpler. A search is unselected because what it does with a source
520 /// of zero is not the same on every processor, so a rule that chose one would depend on what ran
521 /// it. A byte reversal has no such case: it means exactly one thing everywhere. What keeps it
522 /// off the rule set is a choice made once, in [`crate::expand`], which builds a reversal out of
523 /// shifts and masks so that the answer is the same on every target this compiler has rather than
524 /// good on the one that happens to have the instruction. tamnd/rucc#310 is where that trade is
525 /// written down, and the day a target grows its own reversal is the day to reopen it.
526 ///
527 /// So the only thing that reaches one is a program that wrote the name in a template, which is
528 /// what libgmp does in `gmp-impl.h` to put a limb the other way round.
529 ///
530 /// The third is the same thing at a width `bswap` does not reach. Turning a sixteen bit number
531 /// round is exchanging its two bytes with each other, and this machine says that by naming the
532 /// high byte of a register, which only the first four registers have. femtolisp writes one in
533 /// `llt/utils.h`, which is how a C library older than `__builtin_bswap16` said it, and that
534 /// header is the one every other file of the library includes.
535 const SWAP: &[&str] = &["bswap_32", "bswap_64", "xchg_high_16"];
536
537 /// The jump out of the function a template may end with, which a template asks for and nothing
538 /// else could.
539 ///
540 /// Unselected for a reason none of the lists above give, and the plainest reason of the lot:
541 /// there is no term in the IR for it to be the answer to. A tail jump is not a computation and
542 /// it is not a branch between this function's blocks either, it is the function ending
543 /// somewhere other than at its own `ret`, and the only thing that says a function ends that way
544 /// is a program writing `jmp` at the end of a template in a function that is `naked`. See
545 /// [`rucc_target::x86_64::Step::Away`].
546 const AWAY: &[&str] = &["jmp_away"];
547
548 /// The instructions that change an object where it lives, which a template asks for and
549 /// nothing else does.
550 ///
551 /// Each of these is a load, one operation and a store in one line. The rules select the three
552 /// on their own and never the one that is all of them, because what a rule sees is a value in a
553 /// register and the store is a separate term further on. What asks for one is a program that
554 /// gave an `asm` operand the constraint `m` and then named it in an instruction, which is how a
555 /// C library sets a bit in a `sigset_t` and how tcc's `tests/tcctest.c` counts a static local up.
556 const MEMORY: &[&str] = &[
557 "neg_m_8",
558 "neg_m_16",
559 "neg_m_32",
560 "neg_m_64",
561 "not_m_8",
562 "not_m_16",
563 "not_m_32",
564 "not_m_64",
565 "inc_m_8",
566 "inc_m_16",
567 "inc_m_32",
568 "inc_m_64",
569 "dec_m_8",
570 "dec_m_16",
571 "dec_m_32",
572 "dec_m_64",
573 "bts_mr_16",
574 "bts_mr_32",
575 "bts_mr_64",
576 "btr_mr_16",
577 "btr_mr_32",
578 "btr_mr_64",
579 "btc_mr_16",
580 "btc_mr_32",
581 "btc_mr_64",
582 "bts_mi_16",
583 "bts_mi_32",
584 "bts_mi_64",
585 "btr_mi_16",
586 "btr_mi_32",
587 "btr_mi_64",
588 "btc_mi_16",
589 "btc_mi_32",
590 "btc_mi_64",
591 ];
592
593 /// The multiply that keeps both halves of its product and the division that reads both halves
594 /// of its dividend, which a template asks for and nothing else does.
595 ///
596 /// A third reason again, and the plainest of the three. A search is unselected because its
597 /// answer depends on the processor and a reversal because a choice was made to build one out of
598 /// arithmetic. This one is unselected because there is nothing in the IR to select it from: a
599 /// multiply in C takes two values of a type and produces a value of that type, so the term a
600 /// rule would match on is the narrow product, and the wide product is not a term at all. A rule
601 /// that fired on the narrow one and wrote this would be writing an instruction that computes
602 /// twice as much as was asked for and leaves the rest in a register nobody asked about.
603 ///
604 /// So the only thing that reaches one is a program that wrote the name in a template, which is
605 /// what `umul_ppmm` in libgmp's `longlong.h` does, and what every library that is building
606 /// arithmetic out of limbs does somewhere.
607 ///
608 /// The division is the same claim upside down and is on this list because the reason is the same
609 /// one. A division in C divides a number by a number of its own width, so the term a rule would
610 /// match is the narrow one, and this compiler already has two opcodes for that: each of them
611 /// fills the high half of the dividend itself and then throws one of the two answers away. A
612 /// dividend the program filled both halves of is not a term the IR has, and `udiv_qrnnd` beside
613 /// the multiply in the same header is how long division a limb at a time is written.
614 const WIDE: &[&str] = &[
615 "mul_wide_16",
616 "mul_wide_32",
617 "mul_wide_64",
618 "imul_wide_16",
619 "imul_wide_32",
620 "imul_wide_64",
621 "div_wide_16",
622 "div_wide_32",
623 "div_wide_64",
624 "idiv_wide_16",
625 "idiv_wide_32",
626 "idiv_wide_64",
627 ];
628
629 /// The string instructions, which a template writes and nothing else does.
630 ///
631 /// Exempt for the reason `cpuid` is in [`TEMPLATE`]: every register one of them reaches is one
632 /// the instruction names for itself, so there is nothing about one for a rule to name. A copy
633 /// or a fill the compiler writes is a loop it can schedule or a call to the library, and never
634 /// one of these.
635 const STRING: &[&str] = &[
636 "movs_8",
637 "movs_16",
638 "movs_32",
639 "movs_64",
640 "rep_movs_8",
641 "rep_movs_16",
642 "rep_movs_32",
643 "rep_movs_64",
644 "stos_8",
645 "stos_16",
646 "stos_32",
647 "stos_64",
648 "rep_stos_8",
649 "rep_stos_16",
650 "rep_stos_32",
651 "rep_stos_64",
652 "lods_8",
653 "lods_16",
654 "lods_32",
655 "lods_64",
656 "scas_8",
657 "scas_16",
658 "scas_32",
659 "scas_64",
660 "repe_scas_8",
661 "repe_scas_16",
662 "repe_scas_32",
663 "repe_scas_64",
664 "repne_scas_8",
665 "repne_scas_16",
666 "repne_scas_32",
667 "repne_scas_64",
668 "cmps_8",
669 "cmps_16",
670 "cmps_32",
671 "cmps_64",
672 "repe_cmps_8",
673 "repe_cmps_16",
674 "repe_cmps_32",
675 "repe_cmps_64",
676 "repne_cmps_8",
677 "repne_cmps_16",
678 "repne_cmps_32",
679 "repne_cmps_64",
680 ];
681
682 /// The instructions that produce two values, which is one more than a rule can name.
683 ///
684 /// A rule replaces a term with a term, and a term is the value one instruction computes. A
685 /// compare and exchange computes two: what it found at the address, and whether what it found
686 /// was what the program expected. There is no way to write the second one down in the rule
687 /// language, and inventing one would be inventing a language for a single instruction.
688 ///
689 /// So `crate::lower` writes it by name, the way it writes the barrier by name, and for a reason
690 /// that is about the rule language rather than about the machine. What the solver would have
691 /// been asked to prove about it is the easy half in any case: the arithmetic is a comparison
692 /// and a select, and what is hard is that the whole of it happens at once, which is the same
693 /// claim about the program around it that a barrier makes.
694 const ATOMIC: &[&str] = &["cmpxchg_8", "cmpxchg_16", "cmpxchg_32", "cmpxchg_64"];
695
696 /// The instructions whose operation is in the payload rather than in the head.
697 ///
698 /// A different exemption from the one above, on instructions that produce one value each and so
699 /// could be named by a rule if the rule had anything to match on. The head a pattern matches is
700 /// an opcode and a type, and every read modify write in the IR is the one opcode `atomic_rmw`.
701 /// Which of the thirteen operations it performs is carried beside the instruction rather than in
702 /// its name, so a pattern written for the exchange would match the add and the nand as well, and
703 /// the rule language has no way to look at what a rule matched to tell them apart.
704 ///
705 /// Giving each operation its own opcode is the other way out and is a worse trade: it is
706 /// thirteen opcodes at four widths where the IR wants one, and every pass that treats a read
707 /// modify write as one thing would then have a list of fifty two.
708 ///
709 /// So `crate::lower` writes these by name too. Three operations here, out of the thirteen: the
710 /// bitwise ones need a loop around a compare and exchange, which is control flow and so is built
711 /// before selection rather than during it, and they are the rest of `tamnd/rucc#311`.
712 const PAYLOAD: &[&str] =
713 &["xchg_8", "xchg_16", "xchg_32", "xchg_64", "xadd_8", "xadd_16", "xadd_32", "xadd_64"];
714
715 /// The instructions a frame writes rather than a rule.
716 ///
717 /// A prologue, an epilogue, a copy, a spill and a reload are not in the program. They are what
718 /// the allocator's answer costs, so they are written after it, by `crate::finish` reading
719 /// `x86_64::FRAME`. Six of the names that describes are already reachable from a rule, since a
720 /// prologue taking its frame is a subtraction and a spill is a store, and those are not here:
721 /// this is only the ones nothing else can reach.
722 const FRAME: &[&str] = &[
723 "push_64",
724 "pop_64",
725 "ret",
726 "mov_rr_64",
727 "movaps_rr",
728 // The touch a probing prologue puts on each page as it reaches it, the landing pad a
729 // prologue opens with, and the byte that does nothing which one reserves room with. All
730 // three are written by a frame and none on a command line that did not ask for it.
731 "or_mi_8",
732 "endbr64",
733 "nop",
734 ];
735
736 /// The instructions that reach the x87 stack, which are selected but not from here.
737 ///
738 /// A third kind of exemption, and the same reason all the way down the list.
739 ///
740 /// Every one of these is written by `crate::lower`, as part of a group rather than on its own.
741 /// What one of them leaves behind and the next picks up is the top of the x87 stack, which is
742 /// not a register anything allocates from and not a value a pattern could bind, so a rule
743 /// could neither match the middle of a group nor name what its replacement produced. And an
744 /// add here reads two addresses and writes a third, where one machine IR instruction carries
745 /// one addressing mode, so the group cannot be folded into a single opcode the way
746 /// `ucomisd_set_e` folds a comparison and a `setcc` either.
747 ///
748 /// So these are exempt for the reason `FRAME` is exempt rather than for the reason the list
749 /// below is, and they will stay exempt. Two of them are not reached by anything yet all the
750 /// same: `fsub_p` and `fdiv_p` are the other direction of the subtraction and the division,
751 /// which a code generator that pushed its operands the other way round would need and this one
752 /// does not. `fabs` is a third, since C spells that as a call to a library function.
753 const X87: &[&str] = &[
754 "fld_t",
755 "fstp_t",
756 "fld_s",
757 "fld_l",
758 "fild_l",
759 "fild_ll",
760 "fstp_s",
761 "fstp_l",
762 "fistp_l",
763 "fistp_ll",
764 "fnstcw",
765 "fldcw",
766 "fadd_p",
767 "fsub_p",
768 "fsubr_p",
769 "fmul_p",
770 "fdiv_p",
771 "fdivr_p",
772 "fchs",
773 "fabs",
774 "fucomip_set_a",
775 "fucomip_set_ae",
776 "fucomip_set_b",
777 "fucomip_set_be",
778 "fucomip_set_e",
779 "fucomip_set_ne",
780 "fucomip_set_p",
781 "fucomip_set_np",
782 "fucomip_set_e_and_np",
783 "fucomip_set_ne_or_p",
784 ];
785
786 /// The instructions no rule selects yet, because the rules that selected them were taken out.
787 ///
788 /// A different kind of exemption from the three above. Those say an instruction is written
789 /// somewhere a rule cannot reach and always will be. These say nobody reaches one at all right
790 /// now, and name the work that puts the rules back.
791 ///
792 /// The rules went out under `tamnd/rucc#368`. C promotes the operands of an arithmetic
793 /// operator to `int`, so a byte add and a two byte compare are things no C program asks the
794 /// back end for, and the rules at those widths sat proved and never selected over the whole
795 /// torture corpus at every optimization level. The width narrowing pass in `tamnd/rucc#375` is
796 /// what asks for them, and the rules come back with it.
797 ///
798 /// The descriptions stayed. A description says what an x86-64 instruction is, how long it is
799 /// and how it encodes, and that is true whether or not anything selects it. Taking them out
800 /// would be deleting a correct account of the machine to make a list shorter, and putting them
801 /// back is then a second thing to get right rather than a line of a rule file.
802 const NARROW: &[&str] = &[
803 // Three of the two address forms against an immediate. The `narrow` pass does write the
804 // shape, since `char c = a | 1;` narrows to a byte `or` against a byte constant, and no
805 // rule selects these yet: the constant goes into a register and the register with
806 // register rule takes it. Their `add`, `sub` and `and` siblings do have rules and are
807 // reached by the bitfield lowering, so this is six rules missing rather than a shape
808 // nothing writes.
809 "or_ri_8",
810 "or_ri_16",
811 "xor_ri_8",
812 "xor_ri_16",
813 "imul_ri_8",
814 "imul_ri_16",
815 // The shifts by a value, whose count is in `cl` whatever the width being shifted is. The
816 // same refusal for the same kind of reason: a count of twenty is a defined shift to zero
817 // at four bytes and is poison at one, so only a count that is a constant below the narrow
818 // width narrows, and that one selects the immediate forms which do have rules.
819 "shl_rcl_8",
820 "shl_rcl_16",
821 "shr_rcl_8",
822 "shr_rcl_16",
823 "sar_rcl_8",
824 "sar_rcl_16",
825 ];
826
827 /// The arithmetic that reaches memory, which [`crate::combine`] writes: the forms that read a
828 /// source out of it and the forms that leave the answer in it.
829 ///
830 /// A function rather than a list, for the reason the compare pass's exemption is taken from the
831 /// flag description rather than typed out: the pass already writes down which instructions it
832 /// can produce, and a second copy of that here would be a second opinion about one pass.
833 ///
834 /// No rule selects one of these because a rule matches a term and one of these is two terms, a
835 /// load and an arithmetic operation, put together, or three where the answer goes back to
836 /// memory. Whether they may be put together depends on what is written between them and on
837 /// whether anything else wants what the load read, and neither is a fact about any of the
838 /// terms. That is the whole reason the pass exists and the module documentation there says it
839 /// at length.
840 fn combine() -> Vec<&'static str> {
841 let loads = crate::combine::FOLDS.iter().map(|fold| fold.into);
842 // And the instruction a load on the other side comes to, which for most rows is the one
843 // above and for a comparison is the condition the other way round.
844 let swapped = crate::combine::FOLDS.iter().filter_map(|fold| fold.swapped);
845 let stores = crate::combine::UPDATES.iter().map(|update| update.into);
846 let constants = crate::combine::BUMPS.iter().map(|bump| bump.into);
847 // And the load that widens on the way in, which only a load that a widening reads becomes.
848 let widened = crate::combine::WIDENINGS.iter().map(|fold| fold.into);
849 loads.chain(swapped).chain(stores).chain(constants).chain(widened).collect()
850 }
851
852 #[test]
853 fn every_instruction_exempt_from_a_rule_is_one_a_frame_really_writes() {
854 // The same claim as the one about the convention, so that this list cannot grow an opcode
855 // that no frame asks for. In the order `x86_64::FRAME` names them, the copies after the
856 // return because there is one set of them per class the allocator may spill.
857 let frame = &x86_64::FRAME;
858 let mut written = vec![frame.push, frame.pop, frame.ret];
859 for class in frame.classes {
860 written.extend([class.mov, class.load, class.store]);
861 }
862 // And the touch a probing prologue puts on a page, which the target names as an option
863 // because a target with no instruction that writes an address without changing it takes
864 // every frame in one subtraction and has nothing to exempt.
865 written.extend(frame.probe.map(|probe| probe.inst));
866 // And the landing pad and the byte that does nothing, which are options for the same
867 // reason.
868 written.extend(frame.landing);
869 written.extend(frame.pad);
870 // What is left after the ones a rule already reaches, which are the loads and the stores of
871 // both register files, since those are the same instructions a program's own reads and
872 // writes of memory are. The vector pair joined them with the rules for a quad float, and a
873 // spill of one is now the same instruction as a program reading a `_Float128` variable.
874 written.retain(|opcode| !heads().contains(&format!("{PREFIX}{opcode}").as_str()));
875 assert_eq!(written, FRAME);
876 }
877
878 #[test]
879 fn every_instruction_exempt_from_a_rule_is_one_the_convention_really_writes() {
880 // An exemption list that nothing checks is a hole, since an opcode dropped into it stops
881 // being covered by either direction of the pinning. These are the ones `crate::abi` can
882 // name, at the four integer widths and the four float formats it has names for an
883 // argument in, and no others.
884 let strip = |head: &'static str| head.strip_prefix(PREFIX).expect("an x86-64 term");
885 let named = |ty| strip(crate::abi::head_of(ty).expect("every width the pseudos cover"));
886 // The second half of a pair at place one, which is the place a rule cannot name. The first
887 // half at place zero is `ret_val_*` and is reached by a rule, so it is not on this list.
888 let second = |ty| strip(crate::abi::ret_of(ty, 1).expect("every width the pseudos cover"));
889 let widths = || {
890 [8, 16, 32, 64].into_iter().map(rucc_ir::Type::int).chain(
891 [
892 rucc_ir::Float::F16,
893 rucc_ir::Float::F32,
894 rucc_ir::Float::F64,
895 rucc_ir::Float::F128,
896 ]
897 .map(rucc_ir::Type::float),
898 )
899 };
900 let written: Vec<&str> = widths()
901 .map(named)
902 .chain(widths().map(second))
903 .chain([strip(crate::abi::CALL), strip(crate::abi::CALL_REG)])
904 .collect();
905 assert_eq!(written, CONVENTION);
906 }
907
908 /// The same claim about the block layout's list, which is longer than it looks.
909 ///
910 /// A name here that the layout does not write is an opcode exempted from needing a rule and
911 /// reached by nothing, and a name the layout writes that is not here is a failing test in
912 /// `every_described_instruction_is_reachable_from_a_rule` with a misleading message. Both are
913 /// avoided by taking the list from `rucc_target::x86_64::BRANCH` rather than believing it.
914 #[test]
915 fn every_instruction_exempt_from_a_rule_is_one_the_block_layout_really_writes() {
916 let branch = &x86_64::BRANCH;
917 // Eighty entries name sixteen instructions between them, so this is a set rather than a
918 // list and both sides are sorted before they are held against each other. What the order
919 // of the list itself is for is reading it.
920 let mut written: Vec<&str> = vec![branch.test, branch.jump];
921 written.extend(branch.fused.iter().map(|fusion| fusion.cmp));
922 written.extend(branch.fused.iter().flat_map(|fusion| [fusion.if_true, fusion.if_false]));
923 written.sort_unstable();
924 written.dedup();
925 let mut exempt = LAYOUT.to_vec();
926 exempt.sort_unstable();
927 assert_eq!(written, exempt);
928 }
929
930 /// The same claim about the compare pass. What it writes is what the flag description says is
931 /// left of a comparison, so the exemption is taken from that rather than typed out twice, and
932 /// an entry added there without a rule to go with it shows up here rather than in a build that
933 /// fails somewhere else.
934 #[test]
935 fn every_instruction_exempt_from_a_rule_is_one_the_compare_pass_really_writes() {
936 let mut written: Vec<&str> =
937 x86_64::FLAGS.compares.iter().filter_map(|entry| entry.kept).collect();
938 written.sort_unstable();
939 written.dedup();
940 let mut exempt = COMPARE.to_vec();
941 exempt.sort_unstable();
942 assert_eq!(written, exempt);
943 }
944
945 /// And the same claim about the one the lowering writes, held against the name the target gave
946 /// it rather than against the spelling written above.
947 #[test]
948 fn the_instruction_a_computed_goto_is_exempt_for_is_the_one_the_target_names() {
949 assert_eq!(LABELS, [x86_64::BRANCH.indirect]);
950 }
951
952 /// The rows of the constant table that take nothing yet are exactly the narrow ones waiting on
953 /// the width narrowing, so the day `NARROW` shrinks is the day this says so.
954 ///
955 /// `crate::combine::BUMPS` has a row per instruction this machine has, which is the whole five
956 /// operations at the whole four widths. Four of those instructions arrive out of a rule that is
957 /// not written yet, so four of the rows sit there taking nothing. That is a fact worth holding
958 /// rather than a thing to notice again later.
959 #[test]
960 fn the_constant_runs_that_take_nothing_are_the_ones_no_rule_selects_yet() {
961 let written = heads();
962 let mut waiting = Vec::new();
963 for bump in crate::combine::BUMPS {
964 if !written.contains(&format!("{PREFIX}{}", bump.from).as_str()) {
965 waiting.push(bump.from);
966 }
967 }
968 assert_eq!(waiting, ["or_ri_8", "or_ri_16", "xor_ri_8", "xor_ri_16"]);
969 for from in waiting {
970 assert!(NARROW.contains(&from), "{from} is unselected and is not on the list");
971 }
972 }
973
974 #[test]
975 fn every_described_instruction_is_reachable_from_a_rule() {
976 let written = heads();
977 let combine = combine();
978 for &(opcode, _) in x86_64::INSTS {
979 if combine.contains(&opcode) {
980 continue;
981 }
982 if CONVENTION.contains(&opcode) || LAYOUT.contains(&opcode) || FRAME.contains(&opcode) {
983 continue;
984 }
985 if PEEPHOLE.contains(&opcode) {
986 continue;
987 }
988 if NARROW.contains(&opcode) || BARRIER.contains(&opcode) || X87.contains(&opcode) {
989 continue;
990 }
991 if ATOMIC.contains(&opcode) || PAYLOAD.contains(&opcode) || HINT.contains(&opcode) {
992 continue;
993 }
994 if CONDITIONAL.contains(&opcode) {
995 continue;
996 }
997 if CARRY.contains(&opcode) {
998 continue;
999 }
1000 if COMPARE.contains(&opcode) || TEMPLATE.contains(&opcode) {
1001 continue;
1002 }
1003 if SEARCH.contains(&opcode) || SWAP.contains(&opcode) || WIDE.contains(&opcode) {
1004 continue;
1005 }
1006 if AWAY.contains(&opcode) || MEMORY.contains(&opcode) || STRING.contains(&opcode) {
1007 continue;
1008 }
1009 if TEMPLATED.contains(&opcode) {
1010 continue;
1011 }
1012 if LABELS.contains(&opcode) || STOP.contains(&opcode) || CELL.contains(&opcode) {
1013 continue;
1014 }
1015 let head = format!("{PREFIX}{opcode}");
1016 assert!(
1017 written.contains(&head.as_str()),
1018 "{opcode} is described and no rule in {} selects it",
1019 TABLE.source
1020 );
1021 }
1022 }
1023
1024 /// The same claim about the peephole's list, which is a claim about the target's description
1025 /// rather than about this crate: every name on it is one the target really has, and every one
1026 /// of them is a shorter spelling the description names, which is what says the peephole is
1027 /// where it comes from. A name on the list that the peephole could never write would be an
1028 /// instruction nothing writes at all, and this test is what stops that sitting there unnoticed.
1029 #[test]
1030 fn every_instruction_exempt_from_a_rule_is_one_the_peephole_really_writes() {
1031 let tests = x86_64::SHORT.testing.iter().map(|entry| entry.into);
1032 let steps = x86_64::SHORT.stepping.iter().map(|entry| entry.into);
1033 let shorter: Vec<&str> = tests.chain(steps).collect();
1034 for &opcode in PEEPHOLE {
1035 assert!(
1036 x86_64::form(opcode).is_some(),
1037 "{opcode} is not an instruction this describes"
1038 );
1039 assert!(shorter.contains(&opcode), "{opcode} is not one the peephole writes");
1040 }
1041 }
1042
1043 /// The same claim about the barrier as the ones above make about the convention and the frame:
1044 /// the list holds instructions this target really describes, and holds only the ones that have
1045 /// no operands, since an instruction with an operand is one a rule could have been written for.
1046 #[test]
1047 fn every_instruction_exempt_from_a_rule_is_one_the_memory_model_really_writes() {
1048 for &opcode in BARRIER {
1049 let form = x86_64::form(opcode).expect("an instruction this target describes");
1050 assert!(form.operands().is_empty(), "{opcode} has operands, so a rule could name it");
1051 }
1052 }
1053
1054 /// The same claim about the instruction a program stops on, which is the barrier's shape
1055 /// exactly: no operands, because an instruction with one is an instruction a rule could have
1056 /// been written for, and no addressing mode either, because it is given nothing at all.
1057 #[test]
1058 fn the_instruction_exempt_from_a_rule_because_it_stops_the_program_is_bare() {
1059 for &opcode in STOP {
1060 let form = x86_64::form(opcode).expect("an instruction this target describes");
1061 assert!(form.operands().is_empty(), "{opcode} has operands, so a rule could name it");
1062 assert!(!form.takes_mem(), "{opcode} is given an address and stopping needs none");
1063 }
1064 }
1065
1066 /// The same claim about the hints, with the one difference between them written down. A hint is
1067 /// given an address and nothing else, so it has no operands for the reason a barrier has none
1068 /// and it does carry an addressing mode, which is what a rule would have had to match on.
1069 #[test]
1070 fn every_instruction_exempt_from_a_rule_because_it_is_a_hint_is_given_only_an_address() {
1071 for &opcode in HINT {
1072 let form = x86_64::form(opcode).expect("an instruction this target describes");
1073 assert!(form.operands().is_empty(), "{opcode} has operands, so a rule could name it");
1074 assert!(form.takes_mem(), "{opcode} is a hint about an address and is given none");
1075 }
1076 }
1077
1078 /// The same claim about the template list. An instruction is exempt for this reason exactly
1079 /// when there is nothing about it for a rule to name, and there are two ways to have nothing.
1080 /// No operands and no address, which is the hint. Or every operand fixed to one register by the
1081 /// description, which is the question put to the processor: a rule names the operands of a term
1082 /// and binds them to the values underneath it, and an operand that can be nothing but `rax` is
1083 /// not a place a value goes. Either way the whole of the claim holds, which is that there was
1084 /// nowhere else for the instruction to come from.
1085 #[test]
1086 fn every_instruction_exempt_from_a_rule_because_only_a_template_asks_for_it_is_bare() {
1087 for &opcode in TEMPLATE {
1088 let form = x86_64::form(opcode).expect("an instruction this target describes");
1089 let fixed = form
1090 .operands()
1091 .iter()
1092 .all(|desc| matches!(desc.constraint, rucc_target::Constraint::Fixed(_)));
1093 assert!(fixed, "{opcode} has an operand a rule could name");
1094 assert!(!form.takes_mem(), "{opcode} is given an address, so a rule could name it");
1095 }
1096 }
1097
1098 /// The same claim about the bit searches, read off the description that put them there and read
1099 /// both ways round. An instruction is exempt for this reason exactly when the machine describes
1100 /// it as a search, so the list cannot grow an opcode that is something else, and a search this
1101 /// target grows later cannot be left off the list and quietly go unselected with nobody saying
1102 /// why. Nothing in the rule set selects one, which is the other half of the reason and is what
1103 /// the check above would have caught in any case.
1104 #[test]
1105 fn every_instruction_exempt_from_a_rule_because_only_a_template_searches_for_a_bit_is_one() {
1106 let written = heads();
1107 for &opcode in SEARCH {
1108 let form = x86_64::form(opcode).expect("an instruction this target describes");
1109 assert_eq!(form, x86_64::Form::Search, "{opcode} is not a search");
1110 assert!(
1111 !written.contains(&format!("{PREFIX}{opcode}").as_str()),
1112 "a rule in {} selects {opcode}, which only a template asks for",
1113 TABLE.source
1114 );
1115 }
1116 for &(opcode, form) in x86_64::INSTS {
1117 if form == x86_64::Form::Search {
1118 assert!(SEARCH.contains(&opcode), "{opcode} is a search and is not on the list");
1119 }
1120 }
1121 }
1122
1123 /// The same claim about the byte reversal, read both ways round the way the searches are, and
1124 /// with the one thing that is different about it checked as well: this is the instruction of its
1125 /// shape that leaves the condition state alone, which is the whole reason it has a form rather
1126 /// than being a unary operation, so a description that stopped saying that would stop being the
1127 /// reason this list exists.
1128 #[test]
1129 fn every_instruction_exempt_from_a_rule_because_only_a_template_turns_a_register_round_is_one()
1130 {
1131 let written = heads();
1132 for &opcode in SWAP {
1133 let form = x86_64::form(opcode).expect("an instruction this target describes");
1134 // Two forms and one job. The wide reversals are one shape and the sixteen bit one is
1135 // another, because the narrow one is an exchange between the halves of a register and
1136 // has to say which register, so what they share is the answer they compute rather than
1137 // the operands they compute it from.
1138 assert!(
1139 matches!(form, x86_64::Form::Swap | x86_64::Form::SwapHalves),
1140 "{opcode} is not a byte reversal"
1141 );
1142 assert!(
1143 !(x86_64::FLAGS.writes)(opcode),
1144 "{opcode} writes the condition state, so it is a unary operation after all"
1145 );
1146 assert!(
1147 !written.contains(&format!("{PREFIX}{opcode}").as_str()),
1148 "a rule in {} selects {opcode}, which only a template asks for",
1149 TABLE.source
1150 );
1151 }
1152 for &(opcode, form) in x86_64::INSTS {
1153 if matches!(form, x86_64::Form::Swap | x86_64::Form::SwapHalves) {
1154 assert!(SWAP.contains(&opcode), "{opcode} is a reversal and is not on the list");
1155 }
1156 }
1157 }
1158
1159 /// The same claim about the two that work on a pair of registers, read both ways round and with
1160 /// the thing that puts them out of reach of a rule checked rather than asserted in prose: each
1161 /// writes two registers, and a rule replaces a term with a term, so there is no way to say the
1162 /// second answer in the rule language at all. That is the same bar the compare and exchange is
1163 /// exempt at, and this list is separate from that one because the reason it is nobody's to select
1164 /// is different: an atomic is written by name where it is needed, and nothing in this compiler
1165 /// needs one of these.
1166 #[test]
1167 fn every_instruction_exempt_from_a_rule_because_only_a_template_wants_both_halves_writes_two() {
1168 let written = heads();
1169 let both = [x86_64::Form::MulWide, x86_64::Form::DivWide];
1170 for &opcode in WIDE {
1171 let form = x86_64::form(opcode).expect("an instruction this target describes");
1172 assert!(both.contains(&form), "{opcode} works on one register rather than on a pair");
1173 let defs = form.operands().iter().filter(|desc| desc.role.is_def()).count();
1174 assert_eq!(defs, 2, "{opcode} writes {defs} registers and a pair takes two");
1175 assert!(
1176 !written.contains(&format!("{PREFIX}{opcode}").as_str()),
1177 "a rule in {} selects {opcode}, which only a template asks for",
1178 TABLE.source
1179 );
1180 }
1181 for &(opcode, form) in x86_64::INSTS {
1182 if both.contains(&form) {
1183 assert!(WIDE.contains(&opcode), "{opcode} works on a pair and is not on the list");
1184 }
1185 }
1186 }
1187
1188 /// The same claim about the carry pair, and the one thing that has to be true of them that is
1189 /// not true of anything else on any of these lists. An instruction here reads the condition
1190 /// state and writes it, which is what makes it half of a pair and not a rewrite of its own, and
1191 /// the scheduler will only keep it behind the instruction that set the bit if the target says
1192 /// it reads one.
1193 #[test]
1194 fn every_instruction_exempt_from_a_rule_because_it_reads_a_carry_says_it_reads_the_state() {
1195 let written = heads();
1196 for &opcode in CARRY {
1197 let form = x86_64::form(opcode).expect("an instruction this target describes");
1198 let pair = matches!(form, x86_64::Form::AluCarry | x86_64::Form::AluCarryI);
1199 assert!(pair, "{opcode} is not one of the pair");
1200 assert_eq!(
1201 x86_64::FLAGS.reads(opcode),
1202 Some(rucc_target::Reads::Carry),
1203 "{opcode} does not say it reads the carry, so the scheduler may move it"
1204 );
1205 assert!(
1206 (x86_64::FLAGS.writes)(opcode),
1207 "{opcode} is said to leave the condition state alone"
1208 );
1209 assert!(
1210 !written.contains(&format!("{PREFIX}{opcode}").as_str()),
1211 "a rule in {} selects {opcode}, which only a template asks for",
1212 TABLE.source
1213 );
1214 }
1215 for &(opcode, form) in x86_64::INSTS {
1216 if matches!(form, x86_64::Form::AluCarry | x86_64::Form::AluCarryI) {
1217 assert!(CARRY.contains(&opcode), "{opcode} reads a carry and is not on the list");
1218 }
1219 }
1220 }
1221
1222 /// The same claim about the conditional moves, read off the flag description the way the compare
1223 /// pass's list is taken from it rather than typed out twice. An instruction is exempt for this
1224 /// reason exactly when it reads the condition state and leaves it as it found it, which is what
1225 /// says the instruction in front of it is where its meaning comes from. One that wrote the state
1226 /// as well would be one a pattern could match on its own.
1227 #[test]
1228 fn every_instruction_exempt_from_a_rule_because_a_comparison_gives_it_its_meaning_reads_one() {
1229 for &opcode in CONDITIONAL {
1230 x86_64::form(opcode).expect("an instruction this target describes");
1231 assert!(
1232 x86_64::FLAGS.reads(opcode).is_some(),
1233 "{opcode} reads no comparison, so a rule could name it"
1234 );
1235 assert!(
1236 !(x86_64::FLAGS.writes)(opcode),
1237 "{opcode} writes the condition state, so a rule could name it"
1238 );
1239 }
1240 }
1241
1242 /// The same claim about the atomic list, read off the thing that put the entry there: an
1243 /// instruction is exempt for this reason exactly when it writes more than one value, and an
1244 /// instruction that writes one is one a rule could have been written for.
1245 #[test]
1246 fn every_instruction_exempt_from_a_rule_is_one_that_writes_more_than_one_value() {
1247 let written = heads();
1248 for &opcode in ATOMIC {
1249 let form = x86_64::form(opcode).expect("an instruction this target describes");
1250 let writes = form.operands().iter().filter(|desc| desc.role.is_def()).count();
1251 assert!(writes > 1, "{opcode} writes one value, so a rule could name it");
1252 assert!(
1253 !written.contains(&format!("{PREFIX}{opcode}").as_str()),
1254 "a rule in {} selects {opcode}, which `crate::lower` also writes by hand",
1255 TABLE.source
1256 );
1257 }
1258 }
1259
1260 /// The same claim about the payload list, read off the thing that puts an entry there.
1261 ///
1262 /// Two halves. Each of these writes one value, which is what says the reason above is not the
1263 /// reason here, so a list that grew to cover an instruction the atomic list should have had
1264 /// fails. And there really is more than one operation behind the one IR opcode, which is the
1265 /// whole of why a pattern cannot name any of them, and is a fact about the IR that would stop
1266 /// being true if the operations were ever given opcodes of their own.
1267 #[test]
1268 fn every_instruction_exempt_because_its_operation_is_beside_it_writes_one_value() {
1269 assert!(
1270 rucc_ir::RmwOp::all().count() > 1,
1271 "one operation per opcode would be a head a rule could match"
1272 );
1273 let written = heads();
1274 for &opcode in PAYLOAD {
1275 let form = x86_64::form(opcode).expect("an instruction this target describes");
1276 let writes = form.operands().iter().filter(|desc| desc.role.is_def()).count();
1277 assert_eq!(writes, 1, "{opcode} writes more than one value, so it is the other list's");
1278 assert!(
1279 !written.contains(&format!("{PREFIX}{opcode}").as_str()),
1280 "a rule in {} selects {opcode}, which `crate::lower` also writes by hand",
1281 TABLE.source
1282 );
1283 }
1284 }
1285
1286 /// The staleness rule every list in this project is kept under, on the one list here whose
1287 /// entries are meant to leave. A rule that starts selecting one of these is `tamnd/rucc#375`
1288 /// arriving, and the entry goes with it. An entry naming an instruction nothing describes is a
1289 /// misspelling, and it would sit here exempting nothing.
1290 #[test]
1291 fn an_instruction_a_rule_now_selects_is_off_the_list_of_the_ones_left_for_later() {
1292 let written = heads();
1293 for &opcode in NARROW {
1294 let head = format!("{PREFIX}{opcode}");
1295 assert!(
1296 !written.contains(&head.as_str()),
1297 "a rule in {} selects {opcode} now, so it is not waiting on tamnd/rucc#375",
1298 TABLE.source
1299 );
1300 assert!(
1301 x86_64::INSTS.iter().any(|&(described, _)| described == opcode),
1302 "{opcode} is not an instruction anything describes"
1303 );
1304 }
1305 }
1306
1307 /// The same staleness rule on the x87 pair, and one thing more that is particular to them.
1308 ///
1309 /// They are a pair. An instruction that pushes onto the x87 stack and nothing that pops off it
1310 /// again would leave the stack one deeper than the function found it, which is not a mistake
1311 /// the allocator or the block layout could catch, since neither of them knows the stack is
1312 /// there. So the two arrive together and leave together, and that is what this says.
1313 #[test]
1314 fn the_x87_stack_is_reached_by_a_pair_and_by_nothing_else() {
1315 let written = heads();
1316 for &opcode in X87 {
1317 assert!(
1318 x86_64::INSTS.iter().any(|&(described, _)| described == opcode),
1319 "{opcode} is not an instruction anything describes"
1320 );
1321 assert!(
1322 !written.contains(&format!("{PREFIX}{opcode}").as_str()),
1323 "a rule in {} selects {opcode}, which `crate::lower` also writes by hand",
1324 TABLE.source
1325 );
1326 }
1327 // One way onto the stack per format a value can be read from, one way off it per format a
1328 // value can be written to, the control word pair that is neither, and the arithmetic. The
1329 // count is here as well as in the target description because this list is what says none
1330 // of them is reachable, and a name that arrived here without its partner would be a format
1331 // this target can convert in one direction and not the other.
1332 assert_eq!(X87.len(), 30, "twelve that move a value and eighteen that work on one");
1333 }
1334}