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 instructions no rule selects yet, because the rules that selected them were taken out.
162    ///
163    /// A different kind of exemption from the three above. Those say an instruction is written
164    /// somewhere a rule cannot reach and always will be. These say nobody reaches one at all right
165    /// now, and name the work that puts the rules back.
166    ///
167    /// The rules went out under `tamnd/rucc#368`. C promotes the operands of an arithmetic
168    /// operator to `int`, so a byte add and a two byte compare are things no C program asks the
169    /// back end for, and the rules at those widths sat proved and never selected over the whole
170    /// torture corpus at every optimization level. The width narrowing pass in `tamnd/rucc#375` is
171    /// what asks for them, and the rules come back with it.
172    ///
173    /// The descriptions stayed. A description says what an x86-64 instruction is, how long it is
174    /// and how it encodes, and that is true whether or not anything selects it. Taking them out
175    /// would be deleting a correct account of the machine to make a list shorter, and putting them
176    /// back is then a second thing to get right rather than a line of a rule file.
177    const NARROW: &[&str] = &[
178        // Three of the two address forms against an immediate. The `narrow` pass does write the
179        // shape, since `char c = a | 1;` narrows to a byte `or` against a byte constant, and no
180        // rule selects these yet: the constant goes into a register and the register with
181        // register rule takes it. Their `add`, `sub` and `and` siblings do have rules and are
182        // reached by the bitfield lowering, so this is six rules missing rather than a shape
183        // nothing writes.
184        "or_ri_8",
185        "or_ri_16",
186        "xor_ri_8",
187        "xor_ri_16",
188        "imul_ri_8",
189        "imul_ri_16",
190        // The divides, which are four instructions per width because the quotient and the
191        // remainder come out of one division in two different registers. `narrow` refuses these
192        // on purpose: the most negative byte over minus one is a defined hundred and twenty eight
193        // at four bytes and is the overflow that raises at one, so narrowing a division wants a
194        // range that rules the pair out and there is no range analysis yet.
195        "idiv_quo_8",
196        "idiv_quo_16",
197        "idiv_rem_8",
198        "idiv_rem_16",
199        "div_quo_8",
200        "div_quo_16",
201        "div_rem_8",
202        "div_rem_16",
203        // The shifts by a value, whose count is in `cl` whatever the width being shifted is. The
204        // same refusal for the same kind of reason: a count of twenty is a defined shift to zero
205        // at four bytes and is poison at one, so only a count that is a constant below the narrow
206        // width narrows, and that one selects the immediate forms which do have rules.
207        "shl_rcl_8",
208        "shl_rcl_16",
209        "shr_rcl_8",
210        "shr_rcl_16",
211        "sar_rcl_8",
212        "sar_rcl_16",
213        // A one bit value widened to a byte or to two bytes. The four byte and eight byte forms
214        // are what a `_Bool` read turns into, and these two want the one shape `narrow` does not
215        // have: a truncation of an extension, where the extension came from something narrower
216        // than the truncation goes to, which is what `char c = a < b;` is.
217        "bit_to_8",
218        "bit_to_16",
219    ];
220
221    #[test]
222    fn every_instruction_exempt_from_a_rule_is_one_a_frame_really_writes() {
223        // The same claim as the one about the convention, so that this list cannot grow an opcode
224        // that no frame asks for. In the order `x86_64::FRAME` names them, the moves last because
225        // there is one set of them per class the allocator may spill.
226        let frame = &x86_64::FRAME;
227        let mut written = vec![frame.push, frame.pop, frame.ret];
228        for class in frame.classes {
229            written.extend([class.mov, class.load, class.store]);
230        }
231        // What is left after the ones a rule already reaches, which are the loads and the stores
232        // of a general purpose register, since those are the same instructions a program's own
233        // reads and writes of memory are.
234        written.retain(|opcode| !heads().contains(&format!("{PREFIX}{opcode}").as_str()));
235        assert_eq!(written, FRAME);
236    }
237
238    #[test]
239    fn every_instruction_exempt_from_a_rule_is_one_the_convention_really_writes() {
240        // An exemption list that nothing checks is a hole, since an opcode dropped into it stops
241        // being covered by either direction of the pinning. These are the ones `crate::abi` can
242        // name, at the four integer widths and the two float formats it has names for an
243        // argument in, and no others.
244        let strip = |head: &'static str| head.strip_prefix(PREFIX).expect("an x86-64 term");
245        let named = |ty| strip(crate::abi::head_of(ty).expect("every width the pseudos cover"));
246        // The second half of a pair at place one, which is the place a rule cannot name. The first
247        // half at place zero is `ret_val_*` and is reached by a rule, so it is not on this list.
248        let second = |ty| strip(crate::abi::ret_of(ty, 1).expect("every width the pseudos cover"));
249        let widths = || {
250            [8, 16, 32, 64]
251                .into_iter()
252                .map(rucc_ir::Type::int)
253                .chain([rucc_ir::Float::F32, rucc_ir::Float::F64].map(rucc_ir::Type::float))
254        };
255        let written: Vec<&str> = widths()
256            .map(named)
257            .chain(widths().map(second))
258            .chain([strip(crate::abi::CALL), strip(crate::abi::CALL_REG)])
259            .collect();
260        assert_eq!(written, CONVENTION);
261    }
262
263    #[test]
264    fn every_described_instruction_is_reachable_from_a_rule() {
265        let written = heads();
266        for &(opcode, _) in x86_64::INSTS {
267            if CONVENTION.contains(&opcode) || LAYOUT.contains(&opcode) || FRAME.contains(&opcode) {
268                continue;
269            }
270            if NARROW.contains(&opcode) || BARRIER.contains(&opcode) {
271                continue;
272            }
273            let head = format!("{PREFIX}{opcode}");
274            assert!(
275                written.contains(&head.as_str()),
276                "{opcode} is described and no rule in {} selects it",
277                TABLE.source
278            );
279        }
280    }
281
282    /// The same claim about the barrier as the ones above make about the convention and the frame:
283    /// the list holds instructions this target really describes, and holds only the ones that have
284    /// no operands, since an instruction with an operand is one a rule could have been written for.
285    #[test]
286    fn every_instruction_exempt_from_a_rule_is_one_the_memory_model_really_writes() {
287        for &opcode in BARRIER {
288            let form = x86_64::form(opcode).expect("an instruction this target describes");
289            assert!(form.operands().is_empty(), "{opcode} has operands, so a rule could name it");
290        }
291    }
292
293    /// The staleness rule every list in this project is kept under, on the one list here whose
294    /// entries are meant to leave. A rule that starts selecting one of these is `tamnd/rucc#375`
295    /// arriving, and the entry goes with it. An entry naming an instruction nothing describes is a
296    /// misspelling, and it would sit here exempting nothing.
297    #[test]
298    fn an_instruction_a_rule_now_selects_is_off_the_list_of_the_ones_left_for_later() {
299        let written = heads();
300        for &opcode in NARROW {
301            let head = format!("{PREFIX}{opcode}");
302            assert!(
303                !written.contains(&head.as_str()),
304                "a rule in {} selects {opcode} now, so it is not waiting on tamnd/rucc#375",
305                TABLE.source
306            );
307            assert!(
308                x86_64::INSTS.iter().any(|&(described, _)| described == opcode),
309                "{opcode} is not an instruction anything describes"
310            );
311        }
312    }
313}