Skip to main content

rucc_abi/
describe.rs

1//! The language an ABI is described in.
2//!
3//! Design: `spec/cross-compile/06-abis.md` section 6.7.
4//!
5//! # The argument, restated
6//!
7//! `spec/cross-compile/06-abis.md` section 6.1 lists fifteen psABIs and the compiler has four of them today,
8//! hand written, at about a thousand lines. Fifteen at that rate is six to ten thousand lines of
9//! the most bug prone code in a compiler, and `spec/cross-compile/02-the-goal.md` claim 3 says the per target
10//! line count outside the target crate and the rule set has to be zero.
11//!
12//! # Where the line is drawn, and why here
13//!
14//! The tempting version of this idea is to make everything data, and it does not work. The SysV
15//! eightbyte merge is a real algorithm with a real fixed point, the homogeneous aggregate scan
16//! walks a list and compares members, and writing either as a table produces an interpreter that
17//! is longer than the four functions it replaced and slower than all of them.
18//!
19//! So the split is between mechanism and policy. The mechanisms are code, in [`crate::classify`],
20//! and there are four of them across the five ABIs described here: cut into eightbytes and merge,
21//! look for a homogeneous run of floating point members, look for a one or two member aggregate
22//! with a floating point member in it, and check the size against a list. The policies are data,
23//! and a policy is which mechanisms an ABI applies, in what order, with what limits, and what
24//! happens when the registers a mechanism wanted are not there.
25//!
26//! That split is what makes the count work. The fifth ABI reuses a mechanism and costs a
27//! description. The eleventh probably does too. A new mechanism is a real cost and it is paid
28//! once per idea rather than once per target, and there are far fewer ideas than targets.
29//!
30//! # The performance objection
31//!
32//! Section 6.7 raises it against itself: a compile time decision becoming a run time table walk,
33//! on the hot path. Two answers. The classifier runs once per call site and once per function
34//! signature rather than once per instruction, so the exposure is bounded, and the descriptions
35//! are `const` data reached through a `&'static`, so the branch predictor sees the same rule list
36//! for every call in a translation unit.
37//!
38//! Bounded is a prediction rather than a measurement, and the measurement is `spec/cross-compile/02-the-goal.md`
39//! claim 2's benchmark at the migration point. The fallback if it fails is written down in
40//! section 6.7: the descriptions stay as the source of truth for the tests and the documentation
41//! and the classifiers go back to being hand written, which loses claim 3 and keeps claim 2.
42//! Claim 2 outranks claim 3.
43
44use crate::shape::Format;
45
46/// One psABI, completely.
47///
48/// Everything an ABI decides about how a value travels is in here. What is deliberately not in
49/// here is in [`AbiDescription::stack_args`]'s note: prologue emission, register allocation
50/// constraints and unwind emission are per architecture code with per ABI parameters, and
51/// section 6.7 is explicit that turning those into tables costs more than the duplication.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub struct AbiDescription {
54    /// What the ABI is called, which is the name that goes in a diagnostic and in the report.
55    pub name: &'static str,
56    /// The registers a call starts with, and how a scalar spends them.
57    pub banks: Banks,
58    /// How a scalar spends registers, which differs between ABIs more than it looks like it
59    /// should.
60    pub scalars: Scalars,
61    /// The rules for a return value, tried in order.
62    pub returns: &'static [Rule],
63    /// The rules for an argument, tried in order.
64    pub arguments: &'static [Rule],
65    /// Where the address of a return value that comes back in memory travels.
66    pub return_pointer: ReturnPointer,
67    /// What a variadic argument does differently.
68    pub variadic: Variadic,
69    /// How arguments that did not get a register sit in the argument area.
70    ///
71    /// Nothing in this crate reads it. It is here because it is a fact about the ABI and section
72    /// 6.7 wants the description to be the source of truth for the whole ABI rather than for the
73    /// half of it that happens to be classification, and because the backend that does read it
74    /// should be reading it from the same place the tests are generated from.
75    pub stack_args: StackArgs,
76}
77
78impl AbiDescription {
79    /// Whether a scalar of this size travels as the address of a copy the caller made.
80    ///
81    /// The size rule of the one ABI that does this is written over the size of the object and says
82    /// nothing about what is in it, which is why this takes a number rather than a [`Scalar`]: a
83    /// pass writing a call to a runtime routine has a width in hand and no C type behind it, and the
84    /// answer is the same for both askers because there is only the one rule.
85    ///
86    /// [`Scalar`]: crate::shape::Scalar
87    #[must_use]
88    pub const fn scalar_is_by_reference(&self, size: u64) -> bool {
89        self.scalars.wide_is_by_reference && !matches!(size, 1 | 2 | 4 | 8)
90    }
91
92    /// The format an integer of this size comes back in, where the ABI brings one back whole in a
93    /// vector register rather than through the address the caller passed.
94    ///
95    /// The companion to [`AbiDescription::scalar_is_by_reference`] and asked by the same kind of
96    /// caller for the same reason, a pass writing a call to a runtime routine with a width in hand
97    /// and no C type behind it. It is a separate question rather than the same one answered the
98    /// other way because the two disagree on the one ABI that says yes to either: Windows x64
99    /// passes a sixteen byte integer as an address and brings one back in xmm0, so `__fixtfti`
100    /// there takes an address and answers in a vector register.
101    ///
102    /// [`None`] where the size is one a register holds, since then nothing about it is wide, and
103    /// [`None`] on every ABI that does not do this.
104    #[must_use]
105    pub const fn wide_integer_returns_in(&self, size: u64) -> Option<Format> {
106        match self.scalars.wide_integer_returns_in {
107            Some(format) if self.scalar_is_by_reference(size) => Some(format),
108            _ => None,
109        }
110    }
111}
112
113/// The registers a call starts with.
114#[derive(Debug, Clone, Copy, PartialEq, Eq)]
115pub struct Banks {
116    /// General purpose argument registers.
117    pub integer: u32,
118    /// Floating point argument registers.
119    pub float: u32,
120    /// Whether the two banks share argument positions.
121    ///
122    /// True on Windows x64, where rcx, rdx, r8 and r9 and xmm0 to xmm3 are the same four
123    /// positions, so a call taking an `int` and then a `double` uses rcx and xmm1 and never
124    /// xmm0. When this is set the floating point bank is not counted separately and every spend
125    /// comes out of the integer one, which is why [`Banks::float`] is zero on such a target.
126    pub shared: bool,
127    /// The width of a general purpose register in bytes, which is how wide one integer slot is.
128    pub integer_width: u64,
129    /// The widest floating point value a vector register holds, in bytes.
130    ///
131    /// Eight on RISC-V LP64D, where a sixteen byte `long double` therefore travels in integer
132    /// registers, and sixteen on AAPCS64, where it does not. This is the field that makes the
133    /// difference between those two ABIs' otherwise identical treatment of a wide float.
134    pub float_width: u64,
135}
136
137/// How a scalar spends registers.
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub struct Scalars {
140    /// A floating point value in this format travels in the argument area and spends nothing.
141    ///
142    /// `Some(Format::X87Extended)` on SysV AMD64, where a `long double` argument is on the stack
143    /// and there is no register file it could have gone in. `None` everywhere else.
144    pub in_memory: Option<Format>,
145    /// Whether an integer wider than one register takes every register it needs or none of them.
146    ///
147    /// True on SysV AMD64, where an `__int128` takes two consecutive general purpose registers,
148    /// and taking one of them would spend a register on half a value and deny it to an argument
149    /// after it that could have used the whole thing.
150    pub wide_integer_is_all_or_nothing: bool,
151    /// Whether a scalar of a size no register holds travels as the address of a copy the caller
152    /// made, the way an aggregate of that size does.
153    ///
154    /// True on Windows x64, whose one rule is about the size of the object and not about what is
155    /// inside it: anything that is not one, two, four or eight bytes is an address, and a
156    /// `long double`, a `_Float128` and an `__int128` are all sixteen bytes there. False on the
157    /// other four, where a wide scalar has registers to travel in or a place in the argument area
158    /// of its own, which is what [`Scalars::in_memory`] says for the one that puts it there.
159    pub wide_is_by_reference: bool,
160    /// The format a wide integer comes back in, where the ABI brings one back in a vector
161    /// register rather than through the address the caller passed.
162    ///
163    /// `Some(Format::Quad)` on Windows x64, and for an integer only: gcc returns an `__int128`
164    /// in xmm0 there, which is its own answer to a convention that has no 128-bit integer in it,
165    /// and brings the two floating point types of the same size back through the address like
166    /// everything else that size. `None` everywhere else, including on the ABIs where a wide
167    /// integer is not by reference to begin with.
168    pub wide_integer_returns_in: Option<Format>,
169}
170
171/// Where the address of a return value that comes back in memory travels.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub enum ReturnPointer {
174    /// A hidden first argument, which spends an argument register.
175    ///
176    /// SysV AMD64, Windows x64 and RISC-V. This is why the return value is classified before the
177    /// arguments: on these three, a function returning a large structure has one argument
178    /// register fewer than the same function returning `int`, and classifying the arguments
179    /// first gives the wrong answer for the last one of them.
180    FirstArgument,
181    /// A register outside the argument bank, which spends nothing.
182    ///
183    /// AAPCS64's x8. A function returning a large structure still has all eight argument
184    /// registers for what it was called with.
185    Dedicated,
186}
187
188/// What a variadic argument does differently.
189#[derive(Debug, Clone, Copy, PartialEq, Eq)]
190pub enum Variadic {
191    /// Nothing. A variadic argument is classified the same way a fixed one is.
192    SameAsFixed,
193    /// Every variadic argument is in the argument area, whatever registers are left.
194    ///
195    /// Darwin arm64, and the divergence that makes it a separate ABI rather than AAPCS64 with
196    /// notes, per `spec/cross-compile/06-abis.md` section 6.3. It is also the reason a variadic call there is
197    /// ABI-incompatible with a non-variadic one, so calling an unprototyped function works until
198    /// the day it does not.
199    AlwaysMemory,
200    /// A floating point argument travels in both its vector register and the corresponding
201    /// general purpose one.
202    ///
203    /// Windows x64, because the callee of a variadic function does not know which bank to read.
204    BothBanks,
205}
206
207/// How arguments that did not get a register sit in the argument area.
208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
209pub enum StackArgs {
210    /// Each argument occupies a whole number of registers' worth of the argument area, so a
211    /// `char` takes eight bytes. Every ELF ABI here.
212    RegisterSized,
213    /// Each argument occupies its natural size and alignment, so a `char` takes one byte.
214    ///
215    /// Darwin arm64. Getting this wrong produces functions whose ninth argument onward is
216    /// garbage, on Darwin only, which is `spec/cross-compile/06-abis.md` section 6.3's first row.
217    Packed,
218}
219
220/// One rule: what an aggregate has to look like, how it travels if it does, and what happens
221/// when the registers it wanted are not there.
222///
223/// The rules are tried in order and the first one whose test matches wins, so a rule list reads
224/// the way the psABI document it came from is written: the special cases first, the general size
225/// rule after them, and the catch-all last.
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub struct Rule {
228    /// What the aggregate has to look like.
229    pub when: Test,
230    /// How it travels if it does.
231    pub then: Travel,
232    /// What happens if the registers it wanted are not there.
233    pub short: Short,
234}
235
236impl Rule {
237    /// A rule that cannot run short of registers, which is every rule whose result does not
238    /// depend on how many are left.
239    #[must_use]
240    pub const fn new(when: Test, then: Travel) -> Self {
241        Self { when, then, short: Short::Unchanged }
242    }
243
244    /// The same rule, with what happens when the registers are gone.
245    #[must_use]
246    pub const fn short(self, short: Short) -> Self {
247        Self { short, ..self }
248    }
249}
250
251/// What an aggregate has to look like for a rule to apply.
252///
253/// Four of these look inside the aggregate and the rest read its size. The four are the
254/// mechanisms of this crate, and the claim in section 6.7 is that the number of them grows much
255/// more slowly than the number of ABIs.
256#[derive(Debug, Clone, Copy, PartialEq, Eq)]
257pub enum Test {
258    /// Anything, which is what the last rule in a list is.
259    Anything,
260    /// An aggregate of no size, which is a GNU empty struct and travels nowhere.
261    Empty,
262    /// A size that is exactly one of these.
263    ///
264    /// Windows x64's rule, and the sharpest one on the list: anything not exactly one, two, four
265    /// or eight bytes travels as an address, so a three byte structure and a three hundred byte
266    /// structure are passed the same way. Also s390x's, with the same list.
267    SizeOneOf(&'static [u64]),
268    /// A size at most this many bytes.
269    SizeAtMost(u64),
270    /// A homogeneous floating point aggregate of at most this many members.
271    ///
272    /// AAPCS64's HFA, and the same idea with a different limit on AAPCS32 hard float and on
273    /// ELFv2. Homogeneous means every scalar in it is the same floating point type once arrays
274    /// and nested records are flattened, and that they fill the aggregate with no padding left
275    /// over. The second half is what rules out `struct { float a; char pad[8]; }` and anything a
276    /// zero width bit-field has stretched.
277    Homogeneous {
278        /// The most members it can have and still travel in vector registers.
279        limit: usize,
280    },
281    /// One or two members with at least one floating point member between them, each fitting one
282    /// register.
283    ///
284    /// The RISC-V rule, and LoongArch's. `struct { double re, im; }` is two floating point
285    /// registers and `struct { double value; int tag; }` is one of each, which no other ABI on
286    /// the list does. A member wider than a floating point register is not a floating point
287    /// member for this purpose, which is what makes a `long double` here behave like an integer
288    /// pair.
289    FloatPair,
290    /// Every scalar is an x87 `long double`, and there is one of them, or two if it is a
291    /// `_Complex`.
292    ///
293    /// The SysV return path, where a `long double` comes back in st(0) and a `_Complex long
294    /// double` in st(0) and st(1). A record holding two of them is the same thirty two bytes and
295    /// comes back in memory, which is the only thing [`crate::Shape::complex`] is for.
296    X87Stack,
297    /// The SysV eightbyte classification succeeds, and no eightbyte came out x87.
298    ///
299    /// The intricate one. The aggregate is cut into eight byte chunks, each chunk gets a class
300    /// from merging the classes of every scalar reaching into it, and any chunk that comes out
301    /// MEMORY takes the whole argument to memory with it. The cases that catch people are all in
302    /// the merge: an eightbyte holding an `int` and a `float` together is INTEGER, so the float
303    /// travels in a general purpose register, and a member away from its natural alignment sends
304    /// the whole thing to memory.
305    Eightbytes {
306        /// The largest aggregate that can be classified at all, sixteen bytes on SysV.
307        ///
308        /// It is a consequence of the eight eightbyte limit rather than an independent rule: an
309        /// aggregate over two eightbytes travels in registers only when every eightbyte after
310        /// the first is SSEUP. A vector produces a run of those, and a `_Float128` produces one,
311        /// and sixteen bytes of `_Float128` is inside this limit rather than over it.
312        limit: u64,
313    },
314}
315
316/// How a value travels when a rule's test matched.
317#[derive(Debug, Clone, Copy, PartialEq, Eq)]
318pub enum Travel {
319    /// Nothing travels.
320    Ignore,
321    /// In the slots the test found, which is only meaningful after a test that finds some.
322    AsFound,
323    /// As a run of integer registers covering the object, one per register width, the last one
324    /// holding only what is left.
325    AsIntegers,
326    /// As one integer register of the object's exact size, whatever is in it.
327    ///
328    /// Windows x64, where a `struct { float x, y; }` arrives in rcx rather than in xmm0.
329    AsOneInteger,
330    /// As the address of a copy.
331    ByReference,
332    /// As the object's own bytes in the argument area.
333    InMemory,
334}
335
336/// What happens when the registers a rule wanted are not there.
337///
338/// This is the part of a psABI that is easiest to get wrong and hardest to notice, because every
339/// test anybody writes by hand passes few enough arguments that it never comes up. The ninth
340/// argument of a call is not classified the way the first one is on three of the five ABIs here.
341#[derive(Debug, Clone, Copy, PartialEq, Eq)]
342pub enum Short {
343    /// Running out changes nothing. The value goes in the argument area in the same form it
344    /// would have had in a register, and the spend saturates.
345    ///
346    /// Every scalar, and every aggregate on Windows x64, where an argument past the fourth
347    /// travels the way the first one does.
348    Unchanged,
349    /// The argument goes in the argument area, and the registers that are left stay available
350    /// for the arguments after it.
351    ///
352    /// SysV AMD64. An aggregate that did not fit does not stop a later scalar from getting a
353    /// register, which is the opposite of what AAPCS64 does with the same situation.
354    Memory,
355    /// The argument goes in the argument area, and every remaining register of that bank goes
356    /// with it.
357    ///
358    /// AAPCS64 and RISC-V. The draining is the surprising half: once one aggregate has been put
359    /// on the stack for want of registers, a later argument that would have fitted goes on the
360    /// stack too, because the ABI will not leave a hole in the register sequence.
361    MemoryAndDrain,
362    /// The rule does not apply after all, and the rules after it are tried.
363    ///
364    /// The RISC-V floating point pair, which is a bonus rather than a requirement: an aggregate
365    /// the rule reached but the registers did not is classified by the ordinary size rules and
366    /// still travels in registers if those find any.
367    TryNextRule,
368}
369
370#[cfg(test)]
371mod tests {
372    use crate::abis::{AAPCS64, SYSV_AMD64, WIN64};
373    use crate::shape::Format;
374
375    /// The two questions about a wide scalar are asked separately because the one ABI that says
376    /// yes to either gives different answers to them.
377    #[test]
378    fn windows_passes_a_wide_scalar_as_an_address_and_brings_an_integer_back_in_a_register() {
379        assert!(WIN64.scalar_is_by_reference(16));
380        assert_eq!(WIN64.wide_integer_returns_in(16), Some(Format::Quad));
381    }
382
383    /// A size a register holds is not wide, whatever the ABI says about the ones that are.
384    #[test]
385    fn a_size_a_register_holds_is_neither() {
386        for size in [1, 2, 4, 8] {
387            assert!(!WIN64.scalar_is_by_reference(size), "{size} bytes fits a register");
388            assert_eq!(WIN64.wide_integer_returns_in(size), None, "{size} bytes fits a register");
389        }
390    }
391
392    /// Everywhere else a wide scalar has registers to travel in, so neither question applies.
393    #[test]
394    fn the_conventions_with_registers_for_one_say_no_to_both() {
395        for abi in [&SYSV_AMD64, &AAPCS64] {
396            assert!(!abi.scalar_is_by_reference(16), "{}", abi.name);
397            assert_eq!(abi.wide_integer_returns_in(16), None, "{}", abi.name);
398        }
399    }
400}