Skip to main content

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#[cfg(test)]
21mod tests {
22    use rucc_target::x86_64;
23
24    use super::TABLE;
25    use crate::select::Piece;
26
27    /// The prefix a rule file puts in front of a machine term, which is how it says which target
28    /// the term belongs to. It is not part of the opcode.
29    const PREFIX: &str = "x64.";
30
31    /// The two address constructors, which are not instructions. An addressing mode is an
32    /// argument to `lea` and to every memory operand after it, so it is written as a term in the
33    /// rule file and built by the selector into the instruction that takes it.
34    const AMODES: &[&str] =
35        &["amode_base_index_scale", "amode_index_scale", "amode_base", "amode_base_offset"];
36
37    /// Every head this table can write, in and under the replacements.
38    fn heads() -> Vec<&'static str> {
39        let mut found: Vec<&'static str> = TABLE
40            .rules
41            .iter()
42            .flat_map(|rule| rule.replacement.iter())
43            .filter_map(|piece| match piece {
44                Piece::App { head, .. } => Some(*head),
45                _ => None,
46            })
47            .collect();
48        found.sort_unstable();
49        found.dedup();
50        found
51    }
52
53    #[test]
54    fn every_instruction_the_table_writes_is_described() {
55        for head in heads() {
56            if AMODES.contains(&head) {
57                continue;
58            }
59            let opcode = head.strip_prefix(PREFIX).unwrap_or_else(|| {
60                panic!("{head} is neither an x86-64 term nor an addressing mode")
61            });
62            assert!(
63                x86_64::form(opcode).is_some(),
64                "{head} is selected by a rule and `rucc_target::x86_64` does not say what it \
65                 does with its operands"
66            );
67        }
68    }
69
70    /// The order the operands of a store are written in, which is the IR's and not a choice this
71    /// file makes.
72    ///
73    /// A pattern is matched against an instruction's operand list by position, so a rule that
74    /// names the address where the IR holds the value is a rule that stores to the value and
75    /// writes the address into memory. Nothing in a proof would catch it, because a proof is
76    /// about the rule file agreeing with itself, and both halves would be wrong in the same way.
77    /// `rucc_ir::Builder::store` takes the value first and the machine instruction takes it last,
78    /// which is why the two halves of one of these rules read in opposite orders.
79    #[test]
80    fn a_store_is_written_with_the_value_first_because_that_is_where_the_ir_keeps_it() {
81        let mut seen = 0;
82        for rule in TABLE.rules {
83            let Some(rest) = rule.pattern.strip_prefix("(store.") else { continue };
84            let (width, operands) = rest.split_once(' ').expect("a store takes operands");
85            assert!(
86                operands.starts_with(&format!("(value.{width} ")),
87                "line {}: {} binds something other than the value it is storing first",
88                rule.line,
89                rule.pattern
90            );
91            assert!(
92                operands.contains("(value.i64 "),
93                "line {}: {} reaches no address",
94                rule.line,
95                rule.pattern
96            );
97            seen += 1;
98        }
99        assert_eq!(seen, 12, "the store rules moved and this test did not follow them");
100    }
101
102    /// The instructions the calling convention writes rather than a rule.
103    ///
104    /// Three kinds of them. Naming the register an argument arrived in, where an argument is
105    /// depends on its position in the signature and on the classification of every argument before
106    /// it, and a rule pattern sees one term and has no way to say any of that, so `crate::abi`
107    /// builds these from the convention instead. Calling a name is the same the other way round:
108    /// what its operands are is whatever the signature made them, and a call through an address is
109    /// the same instruction with one operand more.
110    ///
111    /// The second half of a value that comes back in two registers is the third. A return of one
112    /// value is a rule, because where that value goes depends on nothing but the value, which is
113    /// exactly what a rule can say. A return of two is not, because which register the second half
114    /// is in depends on the first half: the two register files are counted separately, so a
115    /// `double` and a `long` both come back at place zero and two `long`s do not.
116    const CONVENTION: &[&str] = &[
117        "arg_val_8",
118        "arg_val_16",
119        "arg_val_32",
120        "arg_val_64",
121        "arg_val_f32",
122        "arg_val_f64",
123        "ret_val2_8",
124        "ret_val2_16",
125        "ret_val2_32",
126        "ret_val2_64",
127        "ret_val2_f32",
128        "ret_val2_f64",
129        "call",
130        "call_reg",
131    ];
132
133    /// The instructions the block layout writes rather than a rule.
134    ///
135    /// A rule sees one branch and the layout is about the order of every block in the function, so
136    /// which arm falls through is not something any pattern could say. That answer is what decides
137    /// whether the jump goes to the arm the condition is true for or the other one, and whether
138    /// there is a second jump after it, so all four of these are written where the answer is.
139    const LAYOUT: &[&str] = &["test_rr_8", "jcc_e", "jcc_ne", "jmp"];
140
141    /// The instruction the memory model writes rather than a rule.
142    ///
143    /// A barrier computes nothing, so there is no equality for the solver to discharge and no
144    /// pattern for a rule to be written as. What makes it the right answer is what the machine
145    /// promises about the order two other instructions become visible in, which is a claim about
146    /// the program around it rather than about any value. `crate::lower` writes it by name, at the
147    /// strongest ordering and nowhere else, and `crate::expand` says why the strongest is the only
148    /// one that costs anything here.
149    const BARRIER: &[&str] = &["mfence"];
150
151    /// The instructions a frame writes rather than a rule.
152    ///
153    /// A prologue, an epilogue, a copy, a spill and a reload are not in the program. They are what
154    /// the allocator's answer costs, so they are written after it, by `crate::finish` reading
155    /// `x86_64::FRAME`. Six of the names that describes are already reachable from a rule, since a
156    /// prologue taking its frame is a subtraction and a spill is a store, and those are not here:
157    /// this is only the ones nothing else can reach.
158    const FRAME: &[&str] =
159        &["push_64", "pop_64", "ret", "mov_rr_64", "movaps_rr", "movaps_rm", "movaps_mr"];
160
161    /// The two instructions that reach the x87 stack, which no rule selects yet.
162    ///
163    /// A third kind of exemption, and one that will not last. `fldt` and `fstpt` are the only way
164    /// an eighty bit float gets to the only unit that can do arithmetic on it and back again, and
165    /// there is no arithmetic yet: `tamnd/rucc#540` has this as its third box and the conversions
166    /// and the arithmetic as its fourth and fifth. So this is a description of the machine that
167    /// arrived before the rules that use it, which the list below is also full of.
168    ///
169    /// Whether either of them ever becomes reachable from a rule is the open part. Neither
170    /// computes anything on its own, because what one leaves behind and the other picks up is the
171    /// top of the stack and that is not a value a rule can name, which is the same reason the
172    /// comparisons here are one opcode and not two. The likely answer is that they stay written by
173    /// the code generator, the way a frame's instructions are, and this list says the same about
174    /// them either way: nothing reaches them today.
175    const X87: &[&str] = &["fld_t", "fstp_t"];
176
177    /// The instructions no rule selects yet, because the rules that selected them were taken out.
178    ///
179    /// A different kind of exemption from the three above. Those say an instruction is written
180    /// somewhere a rule cannot reach and always will be. These say nobody reaches one at all right
181    /// now, and name the work that puts the rules back.
182    ///
183    /// The rules went out under `tamnd/rucc#368`. C promotes the operands of an arithmetic
184    /// operator to `int`, so a byte add and a two byte compare are things no C program asks the
185    /// back end for, and the rules at those widths sat proved and never selected over the whole
186    /// torture corpus at every optimization level. The width narrowing pass in `tamnd/rucc#375` is
187    /// what asks for them, and the rules come back with it.
188    ///
189    /// The descriptions stayed. A description says what an x86-64 instruction is, how long it is
190    /// and how it encodes, and that is true whether or not anything selects it. Taking them out
191    /// would be deleting a correct account of the machine to make a list shorter, and putting them
192    /// back is then a second thing to get right rather than a line of a rule file.
193    const NARROW: &[&str] = &[
194        // Three of the two address forms against an immediate. The `narrow` pass does write the
195        // shape, since `char c = a | 1;` narrows to a byte `or` against a byte constant, and no
196        // rule selects these yet: the constant goes into a register and the register with
197        // register rule takes it. Their `add`, `sub` and `and` siblings do have rules and are
198        // reached by the bitfield lowering, so this is six rules missing rather than a shape
199        // nothing writes.
200        "or_ri_8",
201        "or_ri_16",
202        "xor_ri_8",
203        "xor_ri_16",
204        "imul_ri_8",
205        "imul_ri_16",
206        // The divides, which are four instructions per width because the quotient and the
207        // remainder come out of one division in two different registers. `narrow` refuses these
208        // on purpose: the most negative byte over minus one is a defined hundred and twenty eight
209        // at four bytes and is the overflow that raises at one, so narrowing a division wants a
210        // range that rules the pair out and there is no range analysis yet.
211        "idiv_quo_8",
212        "idiv_quo_16",
213        "idiv_rem_8",
214        "idiv_rem_16",
215        "div_quo_8",
216        "div_quo_16",
217        "div_rem_8",
218        "div_rem_16",
219        // The shifts by a value, whose count is in `cl` whatever the width being shifted is. The
220        // same refusal for the same kind of reason: a count of twenty is a defined shift to zero
221        // at four bytes and is poison at one, so only a count that is a constant below the narrow
222        // width narrows, and that one selects the immediate forms which do have rules.
223        "shl_rcl_8",
224        "shl_rcl_16",
225        "shr_rcl_8",
226        "shr_rcl_16",
227        "sar_rcl_8",
228        "sar_rcl_16",
229        // A one bit value widened to a byte or to two bytes. The four byte and eight byte forms
230        // are what a `_Bool` read turns into, and these two want the one shape `narrow` does not
231        // have: a truncation of an extension, where the extension came from something narrower
232        // than the truncation goes to, which is what `char c = a < b;` is.
233        "bit_to_8",
234        "bit_to_16",
235    ];
236
237    #[test]
238    fn every_instruction_exempt_from_a_rule_is_one_a_frame_really_writes() {
239        // The same claim as the one about the convention, so that this list cannot grow an opcode
240        // that no frame asks for. In the order `x86_64::FRAME` names them, the moves last because
241        // there is one set of them per class the allocator may spill.
242        let frame = &x86_64::FRAME;
243        let mut written = vec![frame.push, frame.pop, frame.ret];
244        for class in frame.classes {
245            written.extend([class.mov, class.load, class.store]);
246        }
247        // What is left after the ones a rule already reaches, which are the loads and the stores
248        // of a general purpose register, since those are the same instructions a program's own
249        // reads and writes of memory are.
250        written.retain(|opcode| !heads().contains(&format!("{PREFIX}{opcode}").as_str()));
251        assert_eq!(written, FRAME);
252    }
253
254    #[test]
255    fn every_instruction_exempt_from_a_rule_is_one_the_convention_really_writes() {
256        // An exemption list that nothing checks is a hole, since an opcode dropped into it stops
257        // being covered by either direction of the pinning. These are the ones `crate::abi` can
258        // name, at the four integer widths and the two float formats it has names for an
259        // argument in, and no others.
260        let strip = |head: &'static str| head.strip_prefix(PREFIX).expect("an x86-64 term");
261        let named = |ty| strip(crate::abi::head_of(ty).expect("every width the pseudos cover"));
262        // The second half of a pair at place one, which is the place a rule cannot name. The first
263        // half at place zero is `ret_val_*` and is reached by a rule, so it is not on this list.
264        let second = |ty| strip(crate::abi::ret_of(ty, 1).expect("every width the pseudos cover"));
265        let widths = || {
266            [8, 16, 32, 64]
267                .into_iter()
268                .map(rucc_ir::Type::int)
269                .chain([rucc_ir::Float::F32, rucc_ir::Float::F64].map(rucc_ir::Type::float))
270        };
271        let written: Vec<&str> = widths()
272            .map(named)
273            .chain(widths().map(second))
274            .chain([strip(crate::abi::CALL), strip(crate::abi::CALL_REG)])
275            .collect();
276        assert_eq!(written, CONVENTION);
277    }
278
279    #[test]
280    fn every_described_instruction_is_reachable_from_a_rule() {
281        let written = heads();
282        for &(opcode, _) in x86_64::INSTS {
283            if CONVENTION.contains(&opcode) || LAYOUT.contains(&opcode) || FRAME.contains(&opcode) {
284                continue;
285            }
286            if NARROW.contains(&opcode) || BARRIER.contains(&opcode) || X87.contains(&opcode) {
287                continue;
288            }
289            let head = format!("{PREFIX}{opcode}");
290            assert!(
291                written.contains(&head.as_str()),
292                "{opcode} is described and no rule in {} selects it",
293                TABLE.source
294            );
295        }
296    }
297
298    /// The same claim about the barrier as the ones above make about the convention and the frame:
299    /// the list holds instructions this target really describes, and holds only the ones that have
300    /// no operands, since an instruction with an operand is one a rule could have been written for.
301    #[test]
302    fn every_instruction_exempt_from_a_rule_is_one_the_memory_model_really_writes() {
303        for &opcode in BARRIER {
304            let form = x86_64::form(opcode).expect("an instruction this target describes");
305            assert!(form.operands().is_empty(), "{opcode} has operands, so a rule could name it");
306        }
307    }
308
309    /// The staleness rule every list in this project is kept under, on the one list here whose
310    /// entries are meant to leave. A rule that starts selecting one of these is `tamnd/rucc#375`
311    /// arriving, and the entry goes with it. An entry naming an instruction nothing describes is a
312    /// misspelling, and it would sit here exempting nothing.
313    #[test]
314    fn an_instruction_a_rule_now_selects_is_off_the_list_of_the_ones_left_for_later() {
315        let written = heads();
316        for &opcode in NARROW {
317            let head = format!("{PREFIX}{opcode}");
318            assert!(
319                !written.contains(&head.as_str()),
320                "a rule in {} selects {opcode} now, so it is not waiting on tamnd/rucc#375",
321                TABLE.source
322            );
323            assert!(
324                x86_64::INSTS.iter().any(|&(described, _)| described == opcode),
325                "{opcode} is not an instruction anything describes"
326            );
327        }
328    }
329
330    /// The same staleness rule on the x87 pair, and one thing more that is particular to them.
331    ///
332    /// They are a pair. An instruction that pushes onto the x87 stack and nothing that pops off it
333    /// again would leave the stack one deeper than the function found it, which is not a mistake
334    /// the allocator or the block layout could catch, since neither of them knows the stack is
335    /// there. So the two arrive together and leave together, and that is what this says.
336    #[test]
337    fn the_x87_stack_is_reached_by_a_pair_and_by_nothing_else() {
338        let written = heads();
339        for &opcode in X87 {
340            assert!(
341                x86_64::INSTS.iter().any(|&(described, _)| described == opcode),
342                "{opcode} is not an instruction anything describes"
343            );
344            assert!(
345                !written.contains(&format!("{PREFIX}{opcode}").as_str()),
346                "a rule in {} selects {opcode} now, so the note on tamnd/rucc#540 is stale",
347                TABLE.source
348            );
349        }
350        assert_eq!(X87, ["fld_t", "fstp_t"], "one way onto the x87 stack and one way off it");
351    }
352}