Skip to main content

rucc_codegen/
varargs.rs

1//! What a function does to read the arguments its own signature does not name.
2//!
3//! Design: `spec/12-abi-and-runtime.md`, which is where the layout below comes from.
4//!
5//! A variadic callee has a problem an ordinary one does not. Six of its arguments arrived in
6//! general purpose registers and eight more in vector ones, and it cannot know which of those hold
7//! anything, because what it was passed is a thing only the caller knew. Registers are also not
8//! addressable, and `va_arg` walks arguments one after another at run time, which is walking
9//! addresses. So the convention says the callee spills all fourteen of them into a block of its own
10//! frame on the way in, and from then on every argument it was passed is somewhere in memory: the
11//! ones that came in registers are in that block, and the ones that did not are in the caller's
12//! argument area where they were left.
13//!
14//! That block is the register save area, and a `va_list` is four fields saying how far into the
15//! arguments the walk has got:
16//!
17//! ```text
18//! offset  0  gp_offset          bytes into the save area of the next argument from a gpr
19//! offset  4  fp_offset          bytes into the save area of the next argument from an xmm
20//! offset  8  overflow_arg_area  the next argument that came in the caller's memory
21//! offset 16  reg_save_area      the bottom of the save area
22//! ```
23//!
24//! `va_start` fills all four in. The two offsets do not start at zero: the arguments the signature
25//! does name took registers too, and they took the first ones, so each offset starts past them.
26//! `va_arg` is then one question asked at run time, which is whether the offset for its file has run
27//! off the end of the save area. If it has not, the argument is in the save area and the offset
28//! steps on by a slot. If it has, the argument is in the caller's memory and the overflow pointer
29//! steps on by a word instead.
30//!
31//! # Why the layout is exactly the psABI's and not a convenient one
32//!
33//! Nothing outside the function can see the save area, so its shape looks like a private decision.
34//! It is not one, because a `va_list` is a thing a program hands to another function, and the
35//! function it usually hands it to is `vfprintf` in the C library, which somebody else compiled and
36//! which walks the list by the rules in the psABI document. So the offsets are the document's
37//! offsets, the area is the document's one hundred and seventy six bytes, and the eight bytes
38//! between two general purpose slots and the sixteen between two vector ones are the document's too.
39//!
40//! The upper half of a vector slot is the document's too, and what is in it is the top of a
41//! `_Float128`. A slot is sixteen bytes wide because the register is, and a quad is the one type
42//! here that fills one, so the spill writes all sixteen bytes of every vector register and a
43//! `va_arg` of a quad reads all sixteen back. gcc writes the same sixteen with the same instruction,
44//! which is what makes a list built here readable by a walk somebody else compiled. Anything wider
45//! than a register would be a vector type, which is issue #200 and is not a thing yet.
46//!
47//! # What is here and what is next door
48//!
49//! `va_arg` becomes a compare and a branch, and this is where, because a rewrite that needs new
50//! blocks has to happen before selection for the reason [`crate::expand`] gives. Everything it needs
51//! is in the list it was handed, so it needs nothing from the frame and can run here.
52//!
53//! An aggregate read off a list is the same instruction under another name, because an aggregate is
54//! not a value and there is nothing for one result to be, so that one answers where the object is
55//! instead. Over two eightbytes it is class MEMORY whatever its members are, which means it is in
56//! the caller's argument area and there is no question to ask about which half of the walk it is
57//! in: the overflow pointer says where it is and steps on past it. Sixteen bytes and under arrived
58//! in registers, and then the question is the one a scalar asks, with two differences. The object
59//! takes a register of each file for each of its eightbytes, so the room in the save area has to be
60//! there for all of them at once and the offsets step on by all of them at once. And the halves of
61//! it in the save area are not next to each other, so the answer cannot be an address in the area:
62//! the eightbytes are copied out into a buffer of the function's own and the answer is that.
63//!
64//! Which file each eightbyte came from is the classification, which is an answer about a C type and
65//! not one the size and the alignment give. It arrives on the instruction, worked out by the front
66//! end, which is the last thing to hold a type. An object with no slots on it is one the
67//! classification sent to the argument area, and that is what tells the two halves below apart.
68//!
69//! `va_start` is the other way round. Three of the four fields it writes are distances into a frame
70//! that does not exist yet, so it stays an instruction as far as [`crate::lower`], which builds it
71//! out of the frame the way it builds an `alloca`. The spill that fills the save area is written
72//! there for the same reason.
73//!
74//! # The other kind of list
75//!
76//! Windows has none of that. Its convention counts the two register files as one run of positions,
77//! so an argument's position says which register of either file it is in and the two walks above
78//! are one walk. It also gives every argument exactly one eight byte slot whatever it is: anything
79//! that is not one, two, four or eight bytes travels as the address of a copy the caller owns, and
80//! a float beyond the ones the signature names travels in the general purpose register at its
81//! position as well as in the vector one, because a callee with no prototype has no way to know
82//! which file to look in.
83//!
84//! What that comes to is that every argument a variadic callee was passed is already one contiguous
85//! run of words in the caller's argument area, since the first four of them are homed in the thirty
86//! two bytes of shadow space the caller reserved above the return address and the rest follow.
87//! There is nothing to gather and nowhere to gather it to. So a `va_list` is a `char *` pointing at
88//! the next of those words, `va_start` is one `lea` and one store, and `va_arg` is a load and an
89//! eight byte step with no compare, no branch and no second file. The register save area of the
90//! four field list is, on this convention, the caller's shadow space, and the callee's prologue
91//! writes its leftover argument registers into it rather than into a block of its own.
92//!
93//! An argument that travelled by reference costs one more load and that is the whole of the
94//! difference: the slot holds the address of the copy rather than the copy. Which arguments those
95//! are is a question about the size and nothing else, so the classification the front end put on a
96//! `va_object` is not read here at all.
97
98use rucc_base::float::Format;
99use rucc_ir::{
100    Block, Builder, Extra, Flags, Float, Func, Imm, Inst, InstData, IntPred, MemInfo, MemOrder,
101    Opcode, Restrict, Type, Value,
102};
103use rucc_target::{CallRegs, Slot};
104
105/// Where the count of general purpose register bytes already walked is.
106pub const GP_OFFSET: i64 = 0;
107/// Where the count of vector register bytes already walked is.
108pub const FP_OFFSET: i64 = 4;
109/// Where the pointer to the next argument in the caller's memory is.
110pub const OVERFLOW: i64 = 8;
111/// Where the pointer to the bottom of the register save area is.
112pub const SAVE_AREA: i64 = 16;
113/// How many bytes the four field `va_list` is, which is what a `va_copy` of one moves.
114pub const SIZE: u64 = 24;
115/// How wide the slot one vector register is saved in is, which is how wide the register is whatever
116/// this actually writes into it.
117pub const VECTOR_SLOT: u32 = 16;
118
119/// How big a callee's register save area is and where its two halves are.
120///
121/// Worked out from the convention rather than written down, so that a convention with a different
122/// number of argument registers gets an area the right size for it without anything here changing.
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub struct Area {
125    /// How many bytes of it the general purpose registers take, which is also where the vector half
126    /// begins, since the general purpose half is first and starts at nothing.
127    pub floats_at: u32,
128    /// How many bytes the whole of it is.
129    pub size: u32,
130    /// How many registers of each file it holds, general purpose first.
131    counts: (u32, u32),
132    /// How far apart two general purpose slots are, which is a word.
133    word: u32,
134}
135
136impl Area {
137    /// The save area a variadic callee under that convention needs.
138    ///
139    /// Two shapes, and what tells them apart is the convention's own answer about how it counts
140    /// argument positions. One that counts the two files apart spills all of both into a block of
141    /// the callee's own frame, which is the psABI's register save area and is what the four field
142    /// list walks. One that counts them as one run homes each register argument in the word of the
143    /// caller's argument area that belongs to its position, and that run of words is the area. The
144    /// vector file has nothing in it there: a float beyond the ones the signature names travels in
145    /// the general purpose register at its position as well, so the copy a walk reads is that one.
146    #[must_use]
147    pub fn of(conv: &CallRegs) -> Self {
148        let ints = u32::try_from(conv.int_args.len()).unwrap_or(0);
149        let floats = u32::try_from(conv.sse_args.len()).unwrap_or(0);
150        if conv.shared_positions {
151            let size = conv.word * ints;
152            return Self { floats_at: size, size, counts: (ints, 0), word: conv.word };
153        }
154        let floats_at = conv.word * ints;
155        Self {
156            floats_at,
157            size: floats_at + VECTOR_SLOT * floats,
158            counts: (ints, floats),
159            word: conv.word,
160        }
161    }
162
163    /// How far apart two of a file's slots are.
164    #[must_use]
165    pub fn stride(self, float: bool) -> u32 {
166        if float { VECTOR_SLOT } else { self.word }
167    }
168
169    /// Where a file's first slot is, which is what `va_start` writes into that file's field when
170    /// the signature named no argument that file carried.
171    #[must_use]
172    pub fn starts_at(self, float: bool) -> u32 {
173        if float { self.floats_at } else { 0 }
174    }
175
176    /// Where a file's slots end, which is where the vector half begins for the general purpose
177    /// file and the end of the whole area for the vector one.
178    ///
179    /// This is what an object taking more than one register of a file is measured against: the
180    /// psABI asks whether the offset is at or below the end less a slot for each register the
181    /// object wants, and one register of it is the same question [`Area::last`] asks.
182    #[must_use]
183    pub fn ends_at(self, float: bool) -> u32 {
184        if float { self.size } else { self.floats_at }
185    }
186
187    /// How many registers of a file the area holds.
188    #[must_use]
189    pub fn holds(self, float: bool) -> u32 {
190        if float { self.counts.1 } else { self.counts.0 }
191    }
192
193    /// The offset of a file's last slot, which is the threshold `va_arg` compares against.
194    ///
195    /// The last slot's own offset and not the end of the area, because an offset equal to the end
196    /// is one slot past the last argument while an offset a slot below the end is the last argument
197    /// itself. An empty file has no such offset and nothing here has one.
198    #[must_use]
199    pub fn last(self, float: bool) -> Option<u32> {
200        let last = self.holds(float).checked_sub(1)?;
201        Some(self.starts_at(float) + self.stride(float) * last)
202    }
203}
204
205/// Rewrites every `va_arg`, `va_copy` and `va_end` in the function, and leaves `va_start` alone.
206///
207/// Those three are the ones made only of reads and writes of a list some pointer already reaches,
208/// so none of them needs to know anything about the frame and all three can be done here.
209/// `va_start` is the one that does need the frame, and [`crate::lower`] has it.
210///
211/// A convention whose list is a plain pointer gets the walk the module doc's last section
212/// describes instead, which is the same three rewrites over a list of one field.
213pub fn lists(func: &mut Func, conv: &CallRegs) {
214    let area = Area::of(conv);
215    let word = u64::from(conv.word);
216    let found: Vec<Inst> =
217        func.blocks().flat_map(|block| func.insts(block).collect::<Vec<_>>()).collect();
218    for inst in found {
219        match (func[inst].opcode, conv.shared_positions) {
220            (Opcode::VaArg, false) => next(func, inst, area),
221            (Opcode::VaArg, true) => value(func, inst, word),
222            (Opcode::VaObject, false) => object(func, inst, area),
223            (Opcode::VaObject, true) => held(func, inst, word),
224            (Opcode::VaCopy, shared) => copy(func, inst, if shared { word } else { SIZE }),
225            // Nothing at all, which is what the psABI says it is. The instruction was still worth
226            // emitting, because it says the list stops being read here, and here is where that
227            // stops being worth saying.
228            (Opcode::VaEnd, _) => func.remove_inst(inst),
229            _ => {}
230        }
231    }
232}
233
234/// One `va_arg`, as the branch on whether the argument it wants is still in the save area.
235///
236/// The block the instruction was in is cut in two at the instruction. What was above it stays where
237/// it is and gets the compare and the branch, what was below it moves into a new block that takes
238/// the address as a parameter, and the `va_arg` itself becomes the load at the top of that block.
239/// Turning it into the load rather than replacing it keeps the value the rest of the function reads
240/// the value it already read, so nothing has to be substituted anywhere, and the two paths meet at a
241/// block parameter because the IR has no variables for them to meet at.
242fn next(func: &mut Func, inst: Inst, area: Area) {
243    let Some(result) = func[inst].first_result else { return };
244    let Some(&list) = func[func[inst].args].first() else { return };
245    let ty = func[result].ty;
246    let Some(block) = func.block_of(inst) else { return };
247    let span = func.span(inst);
248    // A `long double` is class X87, which is a class with no register in the save area, so it is
249    // always in the caller's argument area and there is no question to ask about it. That is this
250    // walk with the register half deleted, which is little enough to be written out separately
251    // rather than folded in as a special case of a branch that is never taken.
252    if ty.is_float() && ty.bits() == 80 {
253        x87(func, inst, area);
254        return;
255    }
256    // A `_Float128` is the one value wider than a general purpose register that a single register
257    // still holds. It is class SSE followed by SSEUP, which name one vector register between them,
258    // so it walks the vector half the way a `double` does and takes the whole of a slot instead of
259    // the low half of one. Where it stops being a wider `double` is the caller's argument area,
260    // which gives it two words aligned to two rather than the one word every value the machine
261    // computes in gets.
262    let quad = ty.is_float() && ty.bits() == 128;
263    // A scalar of a width a register holds, which is every type the algorithm below is right about.
264    // An `__int128` takes two slots with an alignment rule of its own, which is a second algorithm
265    // rather than a wider reading of this one, so it is left alone here and refused by name further
266    // down.
267    if !quad
268        && (!ty.is_scalar() || ty.bits() > 64 || !(ty.is_int() || ty.is_float() || ty.is_ptr()))
269    {
270        return;
271    }
272    let float = ty.is_float();
273    let Some(last) = area.last(float) else { return };
274    let field = if float { FP_OFFSET } else { GP_OFFSET };
275
276    // Everything below the instruction, taken out before anything is built, because the builder
277    // appends to a block and this block has to end at the branch.
278    let rest: Vec<Inst> = func.insts(block).skip_while(|&at| at != inst).skip(1).collect();
279    let taken = func.create_block();
280    let overflowed = func.create_block();
281    let join = func.create_block();
282    let addr = func.append_param(join, Type::PTR);
283    func.remove_inst(inst);
284    for &at in &rest {
285        func.remove_inst(at);
286    }
287
288    // The question, in the block the `va_arg` used to be in. Unsigned, because an offset into the
289    // save area counts bytes and is never negative, and because what the field holds once the
290    // register arguments have all been walked is a number past the end rather than a small one.
291    let mut build = Builder::new(func, block).at(span);
292    let counter = offset(&mut build, list, field);
293    let walked = build.load(Type::int(32), counter, info(4, 4), Flags::default());
294    let end = build.iconst(Type::int(32), i128::from(last));
295    let inside = build.icmp(IntPred::Ule, walked, end);
296    build.br_if(inside, taken, &[], overflowed, &[]);
297
298    // The register path: the argument is in the save area at the offset the field holds, and the
299    // field steps on by one slot of its file.
300    let mut build = Builder::new(func, taken).at(span);
301    let base = offset(&mut build, list, SAVE_AREA);
302    let save = build.load(Type::PTR, base, info(8, 8), Flags::default());
303    let wide = build.unary(Opcode::ZExt, walked, Type::int(64));
304    let found = added(&mut build, save, wide);
305    let stride = build.iconst(Type::int(32), i128::from(area.stride(float)));
306    let stepped = build.binary(Opcode::Add, walked, stride, Flags::default());
307    let counter = offset(&mut build, list, field);
308    build.store(stepped, counter, info(4, 4), Flags::default());
309    build.jump(join, &[found]);
310
311    // The memory path: the argument is where the caller left it, and the pointer steps on past it.
312    // By a word for everything the machine computes in, because the caller's argument area is a run
313    // of whole words whatever is in them, and by two words rounded up to two for a quad, which is
314    // the slot the class gets from a function that names it as well as from one that does not.
315    let mut build = Builder::new(func, overflowed).at(span);
316    let (slot, want) = if quad {
317        (u64::from(VECTOR_SLOT), VECTOR_SLOT)
318    } else {
319        (u64::from(area.word), area.word)
320    };
321    let at = overflow(&mut build, list, area, slot, want);
322    let here = build.unary(Opcode::IntToPtr, at, Type::PTR);
323    build.jump(join, &[here]);
324
325    // And the load the program actually wrote, over the address the two paths agreed on, with
326    // everything that used to follow it behind it in the order it was written.
327    let bytes = ty.bits() / 8;
328    let mem = func.add_mem(info(u64::from(bytes), bytes));
329    let args = func.push_values(&[addr]);
330    let data = &mut func[inst];
331    data.opcode = Opcode::Load;
332    data.args = args;
333    data.extra = Extra::Mem(mem);
334    data.flags = data.flags.intersection(Flags::legal_on(Opcode::Load));
335    func.append_inst(join, inst);
336    for at in rest {
337        func.append_inst(join, at);
338    }
339}
340
341/// One `va_arg` of a `long double`, which is the memory half of the walk and nothing else.
342///
343/// The psABI gives a `long double` class X87 and there is no x87 register among the ones a variadic
344/// callee spills, so a `long double` passed to one is in the caller's argument area whatever else
345/// the call passed and however few arguments came before it. Nothing is asked, no block is made,
346/// and the overflow pointer is rounded up, read and stepped on.
347///
348/// Sixteen bytes and sixteen byte alignment are the psABI's numbers for the class rather than the
349/// type's own: the value is ten bytes of x87 and the argument slot it sits in is padded out to two
350/// words, which is why the load below is ten bytes wide and the step is sixteen.
351fn x87(func: &mut Func, inst: Inst, area: Area) {
352    /// What one of these takes in the argument area.
353    const SLOT: u64 = 16;
354    /// What the argument area aligns one to.
355    const ALIGN: u32 = 16;
356
357    let Some(result) = func[inst].first_result else { return };
358    let Some(&list) = func[func[inst].args].first() else { return };
359    let Some(block) = func.block_of(inst) else { return };
360    let bytes = func[result].ty.bits() / 8;
361    let span = func.span(inst);
362
363    // Everything below the instruction, taken out before anything is built, for the reason the
364    // branching walk takes it out: a builder appends to a block, and the instruction has to end up
365    // behind what is built and in front of what followed it.
366    let rest: Vec<Inst> = func.insts(block).skip_while(|&at| at != inst).skip(1).collect();
367    func.remove_inst(inst);
368    for &at in &rest {
369        func.remove_inst(at);
370    }
371
372    let mut build = Builder::new(func, block).at(span);
373    let at = overflow(&mut build, list, area, SLOT, ALIGN);
374    let addr = build.unary(Opcode::IntToPtr, at, Type::PTR);
375
376    let mem = func.add_mem(info(u64::from(bytes), ALIGN));
377    let args = func.push_values(&[addr]);
378    let data = &mut func[inst];
379    data.opcode = Opcode::Load;
380    data.args = args;
381    data.extra = Extra::Mem(mem);
382    data.flags = data.flags.intersection(Flags::legal_on(Opcode::Load));
383    func.append_inst(block, inst);
384    for at in rest {
385        func.append_inst(block, at);
386    }
387}
388
389/// One `va_object`, as the address the object can be read from.
390///
391/// Two shapes, and the slots on the instruction are what say which. An object with none is one the
392/// classification sent to the caller's argument area, which is what everything over two eightbytes
393/// is whatever its members are. There is no question to ask about that one: the overflow pointer
394/// says where it is and steps on past it, and no block is needed.
395///
396/// An object with slots arrived in registers, and that is the branch [`next`] builds for a scalar
397/// with the object's own two differences: the room has to be there for every one of its slots at
398/// once, and what is answered is a buffer the slots were copied into rather than an address in the
399/// save area, because two eightbytes of one object are not next to each other in there.
400///
401/// The address is answered rather than a copy of the object, which is what the instruction is for
402/// and what gcc does with the same argument. An object in the caller's memory is already somewhere
403/// addressable, and the copy the C standard describes is the assignment the caller of `va_arg`
404/// wrote, which the front end has already built around this.
405fn object(func: &mut Func, inst: Inst, area: Area) {
406    let Extra::VaObject(at) = func[inst].extra else { return };
407    let object = func[at];
408    let MemInfo { size, align, .. } = func[object.mem];
409    let slots: Vec<Slot> = func[object.slots].to_vec();
410    let Some(&list) = func[func[inst].args].first() else { return };
411    let Some(block) = func.block_of(inst) else { return };
412    if func[inst].first_result.is_none() || !fits(&slots, area) {
413        return;
414    }
415    let span = func.span(inst);
416
417    // The buffer the register form copies into, made before anything else, because an alloca of
418    // a fixed size belongs in the entry block and the walk below is built where the instruction
419    // is. It is as big as the slots reach rather than as big as the object, which is more for an
420    // object whose last eightbyte is a part of one: five bytes travel in a whole register and
421    // come out of the area as a whole register, so the buffer has eight bytes for them to land
422    // in and the three past the object are never read.
423    // It is also aligned to whatever the widest slot has to be stored at rather than to whatever
424    // the object asked for, which is the same number for every object a C program can write and is
425    // not the same statement. A slot holding a whole vector register moves as a `movaps`, and a
426    // `movaps` faults on an address that is not a multiple of sixteen, so the buffer says sixteen
427    // because the copy needs it and not because the type happened to ask.
428    let reach = slots.iter().map(|&slot| slot.offset() + width(slot)).max().unwrap_or(0);
429    let wants = slots
430        .iter()
431        .map(|&slot| slot_align(area, is_float(slot), width(slot)))
432        .max()
433        .unwrap_or(1)
434        .max(align);
435    let room = buffer(func, inst, reach.max(size), wants);
436
437    // Everything below the instruction, taken out before anything is built, because a builder
438    // appends to a block and the register form ends this one at a branch.
439    let rest: Vec<Inst> = func.insts(block).skip_while(|&at| at != inst).skip(1).collect();
440    func.remove_inst(inst);
441    for &at in &rest {
442        func.remove_inst(at);
443    }
444
445    let (ends, address) = match room {
446        Some(room) if !slots.is_empty() => {
447            let read = Read { list, area, slots: &slots, size, align, room, wants };
448            registers(func, block, inst, read)
449        }
450        _ => {
451            let mut build = Builder::new(func, block).at(span);
452            (block, overflow(&mut build, list, area, size, align))
453        }
454    };
455
456    // And the instruction itself is that address, so that everything reading it goes on reading
457    // the value it already read and nothing has to be substituted anywhere.
458    let args = func.push_values(&[address]);
459    let data = &mut func[inst];
460    data.opcode = Opcode::IntToPtr;
461    data.args = args;
462    data.extra = Extra::None;
463    data.flags = data.flags.intersection(Flags::legal_on(Opcode::IntToPtr));
464    func.append_inst(ends, inst);
465    for at in rest {
466        func.append_inst(ends, at);
467    }
468}
469
470/// One object read off one list, which is what both halves of the walk are about.
471#[derive(Clone, Copy)]
472struct Read<'a> {
473    /// The list it is read from.
474    list: Value,
475    /// The save area of the function doing the reading.
476    area: Area,
477    /// Which register each of the object's eightbytes arrived in, and empty for an object that
478    /// arrived in the caller's memory.
479    slots: &'a [Slot],
480    /// How many bytes the object is.
481    size: u64,
482    /// What it is aligned to, which is what the caller's argument area put it at.
483    align: u32,
484    /// The buffer of the function's own the register form copies the object into.
485    room: Value,
486    /// What that buffer is aligned to, which is the object's alignment or what the widest slot
487    /// needs, whichever is the larger.
488    wants: u32,
489}
490
491/// Whether the classification is one this knows how to read out of the save area.
492///
493/// A slot wider than a register or more of them than the area holds is a classification from some
494/// other machine or from a rule this has not been taught. Turning it down here leaves the
495/// instruction alone, and an instruction left alone is refused by name further down, which is a
496/// message about `va_arg` rather than whatever a half built walk would do at run time.
497fn fits(slots: &[Slot], area: Area) -> bool {
498    let mut counts = [0, 0];
499    for &slot in slots {
500        let float = is_float(slot);
501        if !in_a_register(slot) || width(slot) > u64::from(area.stride(float)) {
502            return false;
503        }
504        counts[usize::from(float)] += 1;
505    }
506    counts[0] <= area.holds(false) && counts[1] <= area.holds(true)
507}
508
509/// Whether a slot is one of the registers a variadic callee spills.
510///
511/// The width does not say on its own. A `long double` is ten bytes and would sit inside a vector
512/// slot with room to spare, and it is class X87, which has no register among the fourteen, so a
513/// classification carrying one is a classification this walk cannot read. The formats a vector
514/// register does hold are named rather than the ones it does not, so a format added later is one
515/// this leaves alone until somebody says where it travels.
516fn in_a_register(slot: Slot) -> bool {
517    match slot {
518        Slot::Integer { .. } => true,
519        Slot::Float { format, .. } => matches!(
520            format,
521            Format::Half | Format::BFloat16 | Format::Single | Format::Double | Format::Quad
522        ),
523    }
524}
525
526/// The register form: the room in the save area is asked about once per file, and the object is
527/// copied out of the area into a buffer when it is there and read from the caller's memory when it
528/// is not.
529///
530/// The question is asked once per file the object takes a register of, and both have to say yes,
531/// because the psABI puts the whole object in the caller's memory when there is not room in the
532/// area for all of it. A file the object takes nothing of has room by definition and is not asked
533/// about, which is every object of one class and is most of them.
534///
535/// Gives back the block the walk ends in and the address, as an integer, that the two paths agreed
536/// on.
537fn registers(func: &mut Func, block: Block, inst: Inst, read: Read<'_>) -> (Block, Value) {
538    let span = func.span(inst);
539    let area = read.area;
540    let counts = [taken_of(read.slots, false), taken_of(read.slots, true)];
541    let saved = func.create_block();
542    let overflowed = func.create_block();
543    let join = func.create_block();
544    let address = func.append_param(join, Type::int(64));
545
546    // The questions, each in its own block, because two of them are two branches and the second
547    // is only asked when the first said yes.
548    let asked: Vec<bool> =
549        [false, true].into_iter().filter(|&float| counts[usize::from(float)] > 0).collect();
550    let mut at = block;
551    for (index, &float) in asked.iter().enumerate() {
552        let next = if index + 1 == asked.len() { saved } else { func.create_block() };
553        // The psABI's own threshold: the end of the file's half of the area, less a slot for each
554        // register the object wants, so that an offset at it leaves room for all of them.
555        let room =
556            area.ends_at(float).saturating_sub(area.stride(float) * counts[usize::from(float)]);
557        let mut build = Builder::new(func, at).at(span);
558        let counter = offset(&mut build, read.list, field_of(float));
559        let walked = build.load(Type::int(32), counter, info(4, 4), Flags::default());
560        let end = build.iconst(Type::int(32), i128::from(room));
561        let inside = build.icmp(IntPred::Ule, walked, end);
562        build.br_if(inside, next, &[], overflowed, &[]);
563        at = next;
564    }
565
566    let mut build = Builder::new(func, saved).at(span);
567    let found = copied(&mut build, read, counts);
568    build.jump(join, &[found]);
569
570    let mut build = Builder::new(func, overflowed).at(span);
571    let here = overflow(&mut build, read.list, area, read.size, read.align);
572    build.jump(join, &[here]);
573
574    (join, address)
575}
576
577/// The object copied out of the save area into the buffer, as the address of the buffer.
578///
579/// A buffer and not an address in the area because the eightbytes of one object are not next to
580/// each other in there: two integer eightbytes are eight bytes apart and two vector ones are
581/// sixteen, and an object of one of each has them in different halves of the area entirely. So
582/// there is nowhere in the area the object is, and the one place it can be made to be is somewhere
583/// else.
584fn copied(build: &mut Builder<'_>, read: Read<'_>, counts: [u32; 2]) -> Value {
585    let area = read.area;
586    let base = offset(build, read.list, SAVE_AREA);
587    let save = build.load(Type::PTR, base, info(8, 8), Flags::default());
588
589    // Where each file's next slot is, which is the one thing the offsets in the list say, and the
590    // counter itself, which is what steps on by every slot the object took of that file.
591    let mut walked = [None, None];
592    let mut nexts = [None, None];
593    for float in [false, true] {
594        let file = usize::from(float);
595        if counts[file] == 0 {
596            continue;
597        }
598        let counter = offset(build, read.list, field_of(float));
599        let read = build.load(Type::int(32), counter, info(4, 4), Flags::default());
600        let wide = build.unary(Opcode::ZExt, read, Type::int(64));
601        walked[file] = Some(read);
602        nexts[file] = Some(added(build, save, wide));
603    }
604
605    let mut seen = [0, 0];
606    for &slot in read.slots {
607        let float = is_float(slot);
608        let file = usize::from(float);
609        let Some(from) = nexts[file] else { continue };
610        let step = i64::from(area.stride(float) * seen[file]);
611        seen[file] += 1;
612        let bytes = width(slot);
613        let ty = moved_as(area, float, bytes);
614        let aligned = slot_align(area, float, bytes);
615        let at = offset(build, from, step);
616        let value = build.load(ty, at, info(bytes, aligned), Flags::default());
617        let into = offset(build, read.room, i64::try_from(slot.offset()).unwrap_or(0));
618        let holds = info(bytes, part(read.wants, slot.offset()));
619        build.store(value, into, holds, Flags::default());
620    }
621
622    // And the counters step on by every slot the object took, since the whole of it came out of
623    // the area and the argument behind it starts past all of it.
624    for float in [false, true] {
625        let file = usize::from(float);
626        let Some(counter) = walked[file] else { continue };
627        let by = build.iconst(Type::int(32), i128::from(area.stride(float) * counts[file]));
628        let stepped = build.binary(Opcode::Add, counter, by, Flags::default());
629        let at = offset(build, read.list, field_of(float));
630        build.store(stepped, at, info(4, 4), Flags::default());
631    }
632    build.unary(Opcode::PtrToInt, read.room, Type::int(64))
633}
634
635/// A buffer at the front of the entry block, which is where an alloca of a fixed size belongs.
636///
637/// Not where the walk is, because a walk inside a loop would then be an alloca inside a loop,
638/// which is a frame that grows every time round. One buffer per `va_arg` of an object, made once
639/// and written every time the object is read, which is what the front end would have written if
640/// the temporary had a name.
641fn buffer(func: &mut Func, inst: Inst, size: u64, align: u32) -> Option<Value> {
642    let entry = func.entry()?;
643    let span = func.span(inst);
644    let mem = func.add_mem(info(size, align.max(1)));
645    let data = InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) };
646    let made = func.create_inst(data, &[Type::PTR], span);
647    let first = func.insts(entry).next();
648    match first {
649        Some(first) => func.insert_before(made, first),
650        None => func.append_inst(entry, made),
651    }
652    func[made].first_result
653}
654
655/// Where the argument the caller left in memory is, with the overflow pointer stepped on past it,
656/// as an integer address.
657///
658/// The pointer is rounded up first for an object that wants more alignment than a word. The
659/// argument area is a run of words, so anything asking for eight or less is where it is already,
660/// and anything asking for more was put at the next multiple of what it asked for by whoever
661/// passed it.
662fn overflow(build: &mut Builder<'_>, list: Value, area: Area, size: u64, align: u32) -> Value {
663    let word = u64::from(area.word);
664    let wide = Type::int(64);
665    let pointer = offset(build, list, OVERFLOW);
666    let here = build.load(Type::PTR, pointer, info(word, area.word), Flags::default());
667
668    // As an integer, because rounding up is an add and a mask and neither is a thing to do to a
669    // pointer. Both casts are free: the two are the same bits on this machine and nothing is
670    // written for either.
671    let mut at = build.unary(Opcode::PtrToInt, here, wide);
672    if u64::from(align) > word {
673        // Up to the next multiple of a power of two, which is the round up every alignment is.
674        // The mask is the negative of the alignment because that is what the complement of one
675        // less than it comes to, and writing it that way keeps it inside a signed sixty four bit
676        // constant.
677        let bump = build.iconst(wide, i128::from(align) - 1);
678        at = build.binary(Opcode::Add, at, bump, Flags::default());
679        let mask = build.iconst(wide, -i128::from(align));
680        at = build.binary(Opcode::And, at, mask, Flags::default());
681    }
682
683    // Past it, rounded up to a whole number of words, because the argument area holds words and
684    // the argument behind this one starts at one of them.
685    let by = build.iconst(wide, i128::from(size.next_multiple_of(word)));
686    let onward = build.binary(Opcode::Add, at, by, Flags::default());
687    let onward = build.unary(Opcode::IntToPtr, onward, Type::PTR);
688    build.store(onward, pointer, info(word, area.word), Flags::default());
689    at
690}
691
692/// Which of the two counters a file's slots are walked with.
693fn field_of(float: bool) -> i64 {
694    if float { FP_OFFSET } else { GP_OFFSET }
695}
696
697/// Whether a slot is one of the vector file's.
698fn is_float(slot: Slot) -> bool {
699    matches!(slot, Slot::Float { .. })
700}
701
702/// How many registers of a file an object takes.
703fn taken_of(slots: &[Slot], float: bool) -> u32 {
704    u32::try_from(slots.iter().filter(|&&slot| is_float(slot) == float).count()).unwrap_or(0)
705}
706
707/// What one slot's bytes are moved as.
708///
709/// An integer of the slot's width whatever file it came from, because what this is is a copy of the
710/// object's bytes and nothing here reads them as anything. A slot the whole width of a vector
711/// register is the exception and has to be: there is no integer that wide on this machine, and the
712/// file the bytes are already in is the one that moves all sixteen of them at once.
713fn moved_as(area: Area, float: bool, bytes: u64) -> Type {
714    if float && bytes > u64::from(area.word) {
715        return Type::float(Float::F128);
716    }
717    Type::int(u32::try_from(bytes).unwrap_or(1) * 8)
718}
719
720/// What the address of a slot in the save area is known to be aligned to.
721///
722/// The area begins on a vector slot boundary and every slot in it is a whole number of its file's
723/// strides along from there, so a value as wide as its file's stride sits at a multiple of the
724/// stride and everything narrower sits at a multiple of a word. The wide case is the one that has
725/// to be right, since what moves a whole vector register is a `movaps` and a `movaps` faults on an
726/// address that is not a multiple of sixteen rather than being slow about it.
727fn slot_align(area: Area, float: bool, bytes: u64) -> u32 {
728    if bytes > u64::from(area.word) { area.stride(float) } else { area.word }
729}
730
731/// How many bytes one slot moves, which is its own width rounded up to one the machine has a load
732/// for.
733fn width(slot: Slot) -> u64 {
734    match slot {
735        Slot::Integer { size, .. } => u64::from(size.next_power_of_two().clamp(1, 8)),
736        Slot::Float { format, .. } => u64::from(format.width()).div_ceil(8),
737    }
738}
739
740/// What a part of an object at that offset is aligned to, which is what the object is aligned to
741/// for the part at the front of it and how far into the object the part sits for every other.
742fn part(align: u32, offset: u64) -> u32 {
743    let align = align.max(1);
744    if offset == 0 {
745        return align;
746    }
747    u32::try_from(1_u64 << offset.trailing_zeros()).unwrap_or(align).min(align)
748}
749
750/// Whether an argument of that size travelled as the address of a copy rather than as itself.
751///
752/// The platform's rule stated as a size and nothing else: an argument that is not one, two, four or
753/// eight bytes is passed as a pointer to a copy the caller made, whatever the argument is made of.
754/// A three byte structure is one and so is a sixteen byte float, and no classification is asked
755/// about either, which is why the slots the front end put on a `va_object` go unread on this side.
756fn by_reference(size: u64) -> bool {
757    !matches!(size, 1 | 2 | 4 | 8)
758}
759
760/// The slot the walk is at, with the list stepped on past it, written in front of an instruction.
761///
762/// One word whatever is in the slot, because this convention gives every argument exactly one and
763/// pays for the ones that do not fit by passing their address instead. So there is nothing to round
764/// up, nothing to ask and nothing to branch on.
765fn slot(func: &mut Func, inst: Inst, list: Value, word: u64) -> Value {
766    let here = read(func, inst, list, Type::PTR, word);
767    let step = field(func, inst, here, i64::try_from(word).unwrap_or(0));
768    let mem = func.add_mem(info(word, u32::try_from(word).unwrap_or(1)));
769    let args = func.push_values(&[step, list]);
770    let data = InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Store) };
771    let span = func.span(inst);
772    let made = func.create_inst(data, &[], span);
773    func.insert_before(made, inst);
774    here
775}
776
777/// A load written in front of an instruction, at the alignment its own width gives it.
778fn read(func: &mut Func, inst: Inst, from: Value, ty: Type, size: u64) -> Value {
779    let mem = func.add_mem(info(size, u32::try_from(size).unwrap_or(1)));
780    let args = func.push_values(&[from]);
781    let data = InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Load) };
782    ahead(func, inst, data, ty)
783}
784
785/// How many bytes of a scalar the one field walk moves, or nothing for a type it is not right
786/// about.
787///
788/// A pointer has no width of its own here and is as wide as the convention's word, which is the one
789/// question this has to ask the target rather than the type.
790///
791/// Anything wider than a general purpose register is left alone, which is a `long double`, a
792/// `_Float128` and an `__int128`. The convention travels all three as the address of a copy, and
793/// reading one back that way would be reading through an address nobody wrote: a wide scalar is
794/// passed as itself here today whether or not the signature names it, which is tamnd/rucc#1331 and
795/// is wrong for a named argument first. So they stay as they are and are refused by name further
796/// down, which is where the four field walk leaves the last of them too.
797fn travels(ty: Type, word: u64) -> Option<u64> {
798    if !ty.is_scalar() || !(ty.is_int() || ty.is_float() || ty.is_ptr()) {
799        return None;
800    }
801    if ty.is_ptr() {
802        return Some(word);
803    }
804    (ty.bits() <= 64).then(|| u64::from(ty.bits().div_ceil(8)))
805}
806
807/// One `va_arg` on a convention whose list is a plain pointer, as the load at the slot the walk is
808/// at.
809///
810/// The instruction becomes that load rather than being replaced by one, for the reason the
811/// branching walk gives: the value the rest of the function reads stays the value it already read,
812/// so nothing has to be substituted anywhere. Everything the load needs is written in front of it,
813/// and since nothing here branches the instruction does not move and the block is not cut.
814///
815/// Every scalar [`travels`] answers for is one the convention passes whole, so the slot holds the
816/// value and not an address, and the load is the whole of it. The object walk below is where the
817/// other case is.
818fn value(func: &mut Func, inst: Inst, word: u64) {
819    let Some(result) = func[inst].first_result else { return };
820    let Some(&list) = func[func[inst].args].first() else { return };
821    let ty = func[result].ty;
822    let Some(bytes) = travels(ty, word) else { return };
823
824    let from = slot(func, inst, list, word);
825    let mem = func.add_mem(info(bytes, u32::try_from(bytes).unwrap_or(1)));
826    let args = func.push_values(&[from]);
827    let data = &mut func[inst];
828    data.opcode = Opcode::Load;
829    data.args = args;
830    data.extra = Extra::Mem(mem);
831    data.flags = data.flags.intersection(Flags::legal_on(Opcode::Load));
832}
833
834/// One `va_object` on the same convention, as the address the object can be read from.
835///
836/// The slot itself for an object of a width the convention passes whole, and what the slot holds
837/// for every other one, which is the address of the copy the caller made. That is the same question
838/// [`by_reference`] answers for a scalar and it is asked of the size alone, so an object of three
839/// bytes and an object of a hundred take the two different paths for the one reason.
840///
841/// The address is answered rather than a copy of the object, which is what the instruction is for:
842/// the object is already somewhere addressable either way, and the copy the C standard describes is
843/// the assignment the caller of `va_arg` wrote.
844fn held(func: &mut Func, inst: Inst, word: u64) {
845    let Extra::VaObject(at) = func[inst].extra else { return };
846    let MemInfo { size, .. } = func[func[at].mem];
847    let Some(&list) = func[func[inst].args].first() else { return };
848    if func[inst].first_result.is_none() {
849        return;
850    }
851
852    let here = slot(func, inst, list, word);
853    let from = if by_reference(size) { read(func, inst, here, Type::PTR, word) } else { here };
854    // Through an integer and back, which is what the branching walk's answer is too and is free
855    // either way: the two are the same bits on this machine and nothing is written for the pair.
856    let args = func.push_values(&[from]);
857    let data = InstData { args, ..InstData::new(Opcode::PtrToInt) };
858    let address = ahead(func, inst, data, Type::int(64));
859    let args = func.push_values(&[address]);
860    let data = &mut func[inst];
861    data.opcode = Opcode::IntToPtr;
862    data.args = args;
863    data.extra = Extra::None;
864    data.flags = data.flags.intersection(Flags::legal_on(Opcode::IntToPtr));
865}
866
867/// One `va_copy`, as the fields of one list moved into another.
868///
869/// A list is those fields and holds nothing anywhere else, so copying it is copying them, and a
870/// handful of words move as a handful of words rather than as a call to `memcpy`, which is a name
871/// this compiler cannot emit yet and would be the wrong answer for three words in any case. How
872/// many words there are is the convention's answer: three for the four field list, since the two
873/// offsets share one, and one for the list that is a pointer.
874///
875/// Every read is built before any write, so that a list copied onto itself, which is legal and
876/// useless, moves what it held rather than what it has just been given.
877fn copy(func: &mut Func, inst: Inst, bytes: u64) {
878    let [into, from] = func[func[inst].args] else { return };
879    let mut moved = Vec::new();
880    for word in 0..bytes / 8 {
881        let step = i64::try_from(word * 8).unwrap_or(0);
882        let there = field(func, inst, from, step);
883        let mem = func.add_mem(info(8, 8));
884        let args = func.push_values(&[there]);
885        let data = InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Load) };
886        moved.push((ahead(func, inst, data, Type::int(64)), step));
887    }
888    for (read, step) in moved {
889        let here = field(func, inst, into, step);
890        let mem = func.add_mem(info(8, 8));
891        let args = func.push_values(&[read, here]);
892        let data = InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Store) };
893        let span = func.span(inst);
894        let made = func.create_inst(data, &[], span);
895        func.insert_before(made, inst);
896    }
897    func.remove_inst(inst);
898}
899
900/// The address that far past a pointer, written in front of an instruction, or the pointer itself
901/// for no distance at all.
902///
903/// A field of a list for the walk that has four of them, and the slot behind this one for the walk
904/// whose list is a pointer.
905fn field(func: &mut Func, inst: Inst, list: Value, at: i64) -> Value {
906    if at == 0 {
907        return list;
908    }
909    let extra = Extra::Imm(func.add_imm(Imm::int(i128::from(at), Type::int(64))));
910    let step =
911        ahead(func, inst, InstData { extra, ..InstData::new(Opcode::IConst) }, Type::int(64));
912    let args = func.push_values(&[list, step]);
913    ahead(func, inst, InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR)
914}
915
916/// Puts an instruction in front of another one and gives back the value it produces.
917fn ahead(func: &mut Func, inst: Inst, data: InstData, ty: Type) -> Value {
918    let span = func.span(inst);
919    let made = func.create_inst(data, &[ty], span);
920    func.insert_before(made, inst);
921    func[made].first_result.expect("an instruction created with one result has one")
922}
923
924/// The address of a field of a list in a block being filled, or the list itself for the field at
925/// the front of it.
926fn offset(build: &mut Builder<'_>, list: Value, at: i64) -> Value {
927    if at == 0 {
928        return list;
929    }
930    let step = build.iconst(Type::int(64), i128::from(at));
931    added(build, list, step)
932}
933
934/// A pointer with an integer added to it.
935fn added(build: &mut Builder<'_>, pointer: Value, by: Value) -> Value {
936    let args = build.func().push_values(&[pointer, by]);
937    build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR)
938}
939
940/// An ordinary read or write of that many bytes, aligned that far.
941///
942/// Every access this pass makes is to a field of a list or to an argument, and none of them is
943/// atomic or has anything to say about aliasing.
944fn info(size: u64, align: u32) -> MemInfo {
945    MemInfo {
946        size,
947        align,
948        order: MemOrder::NotAtomic,
949        tbaa: None,
950        owns: 0,
951        restrict: Restrict::NONE,
952    }
953}
954
955#[cfg(test)]
956mod tests {
957    use rucc_base::Interner;
958    use rucc_base::float::Format;
959    use rucc_ir::{Builder, Extra, Func, InstData, Module, Opcode, Signature, Type, VaInfo};
960    use rucc_target::x86_64::{SYSV, WIN64};
961    use rucc_target::{Arch, Env, Os, Slot, TargetInfo, Triple};
962
963    use super::{Area, FP_OFFSET, GP_OFFSET, OVERFLOW, SAVE_AREA, SIZE, VECTOR_SLOT, lists};
964
965    fn target() -> TargetInfo {
966        TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu))
967    }
968
969    /// `T f(va_list *ap) { return va_arg(*ap, T); }`, or the same shape over whichever of the
970    /// family is asked for, with the list arriving as the pointer it has decayed to by the time
971    /// anything reads it.
972    fn built(opcode: Opcode, ty: Type, lists: usize) -> (Interner, Func) {
973        let mut names = Interner::new();
974        let params = vec![Type::PTR; lists];
975        let mut signature = Signature::new().with_params(&params);
976        if !ty.is_void() {
977            signature = signature.with_returns(&[ty]);
978        }
979        let mut func = Func::new(names.intern("f"), signature);
980        let entry = func.create_block();
981        let args: Vec<_> = params.iter().map(|&ty| func.append_param(entry, ty)).collect();
982
983        let mut build = Builder::new(&mut func, entry);
984        let list = build.func().push_values(&args);
985        if ty.is_void() {
986            build.inst(InstData { args: list, ..InstData::new(opcode) }, &[]);
987            build.ret(&[]);
988        } else {
989            let got = build.value(InstData { args: list, ..InstData::new(opcode) }, ty);
990            build.ret(&[got]);
991        }
992        (names, func)
993    }
994
995    fn printed(func: &Func, names: &mut Interner) -> String {
996        let module = Module::new(names.intern("va.c"), &target());
997        rucc_ir::print_func(&module, func, names)
998    }
999
1000    fn valid(func: &Func, names: &mut Interner) {
1001        let module = Module::new(names.intern("va.c"), &target());
1002        rucc_ir::verify_func(&module, func, names).expect("the rewrite builds valid IR");
1003    }
1004
1005    /// The numbers in this test are the psABI's own, written out rather than computed, because the
1006    /// whole point of the layout is that it is the document's and not a convenient one. A version
1007    /// of [`Area`] that worked them out differently would agree with itself and disagree with the C
1008    /// library, and this is what would notice.
1009    #[test]
1010    fn the_save_area_is_the_one_the_document_describes() {
1011        let area = Area::of(&SYSV);
1012        assert_eq!(area.floats_at, 48, "six general purpose registers of eight bytes");
1013        assert_eq!(area.size, 176, "and eight vector ones of sixteen");
1014        assert_eq!(area.stride(false), 8);
1015        assert_eq!(area.stride(true), VECTOR_SLOT);
1016        assert_eq!(area.starts_at(false), 0);
1017        assert_eq!(area.starts_at(true), 48);
1018        // The last slot's own offset and not the end of the area, which is what `va_arg` compares
1019        // against: an offset equal to the end is one slot past the last argument.
1020        assert_eq!(area.last(false), Some(40));
1021        assert_eq!(area.last(true), Some(160));
1022    }
1023
1024    /// And the four fields, for the same reason.
1025    #[test]
1026    fn a_list_is_the_four_fields_the_document_describes() {
1027        assert_eq!((GP_OFFSET, FP_OFFSET, OVERFLOW, SAVE_AREA), (0, 4, 8, 16));
1028        assert_eq!(SIZE, 24);
1029    }
1030
1031    #[test]
1032    fn a_va_arg_becomes_the_branch_on_whether_the_argument_is_still_in_the_save_area() {
1033        let (mut names, mut func) = built(Opcode::VaArg, Type::int(32), 1);
1034        let before = func.blocks().count();
1035        lists(&mut func, &SYSV);
1036        assert_eq!(func.blocks().count(), before + 3, "one for each path and one they meet at");
1037
1038        let text = printed(&func, &mut names);
1039        assert!(!text.contains("va_arg"), "the va_arg is gone: {text}");
1040        assert!(text.contains("icmp ule"), "the threshold is a comparison: {text}");
1041        assert!(text.contains("br_if"), "and it is branched on: {text}");
1042        valid(&func, &mut names);
1043    }
1044
1045    /// Which field it walks is the whole of the difference between the two files, and getting it
1046    /// backwards is a program that reads its integers out of the vector half.
1047    #[test]
1048    fn which_half_of_the_area_is_walked_is_the_type_s_answer() {
1049        for (ty, last, stride) in
1050            [(Type::int(64), 40, 8), (Type::float(rucc_ir::Float::F64), 160, 16)]
1051        {
1052            let (mut names, mut func) = built(Opcode::VaArg, ty, 1);
1053            lists(&mut func, &SYSV);
1054            let text = printed(&func, &mut names);
1055            assert!(text.contains(&format!("iconst.i32 {last}")), "{ty:?} stops at {last}: {text}");
1056            assert!(text.contains(&format!("iconst.i32 {stride}")), "and steps by it: {text}");
1057        }
1058    }
1059
1060    /// The value the rest of the function reads has to stay the value it already read, since the
1061    /// rewrite substitutes nothing anywhere. It stays it by the `va_arg` becoming the load rather
1062    /// than being replaced by one, so the instruction is the same instruction under a new opcode
1063    /// and in a new block.
1064    #[test]
1065    fn what_reads_the_argument_reads_the_same_value_it_did_before() {
1066        let (mut names, mut func) = built(Opcode::VaArg, Type::int(32), 1);
1067        let entry = func.entry().expect("an entry block");
1068        let inst = func.insts(entry).next().expect("the va_arg is first");
1069        let read = func[inst].first_result.expect("it produces the argument");
1070
1071        lists(&mut func, &SYSV);
1072        assert_eq!(func[inst].opcode, Opcode::Load, "the same instruction, lowered");
1073        assert_eq!(func[inst].first_result, Some(read), "producing the same value");
1074        assert_ne!(func.block_of(inst), Some(entry), "in the block the two paths meet at");
1075        valid(&func, &mut names);
1076    }
1077
1078    #[test]
1079    fn a_va_end_is_nothing_at_all() {
1080        let (mut names, mut func) = built(Opcode::VaEnd, Type::VOID, 1);
1081        lists(&mut func, &SYSV);
1082        let text = printed(&func, &mut names);
1083        assert!(!text.contains("va_end"), "{text}");
1084        assert_eq!(func.blocks().count(), 1, "and needs no block: {text}");
1085        valid(&func, &mut names);
1086    }
1087
1088    /// Three words and no branch, because a list is three words and holds nothing anywhere else.
1089    #[test]
1090    fn a_va_copy_is_the_list_moved_a_word_at_a_time() {
1091        let (mut names, mut func) = built(Opcode::VaCopy, Type::VOID, 2);
1092        lists(&mut func, &SYSV);
1093        let text = printed(&func, &mut names);
1094        assert!(!text.contains("va_copy"), "{text}");
1095        assert_eq!(text.matches("load.i64").count(), 3, "{text}");
1096        assert_eq!(text.matches("store").count(), 3, "{text}");
1097        assert_eq!(func.blocks().count(), 1, "and needs no block: {text}");
1098        valid(&func, &mut names);
1099    }
1100
1101    /// Every read before every write, so that `va_copy(ap, ap)` moves what the list held rather
1102    /// than what it has just been given. Useless and legal, which is exactly the combination that
1103    /// gets written once and never tested anywhere else.
1104    #[test]
1105    fn a_list_copied_onto_itself_moves_what_it_held() {
1106        let (mut names, mut func) = built(Opcode::VaCopy, Type::VOID, 1);
1107        // One parameter, so both operands of the copy are the same list. The builder above pushes
1108        // as many operands as there are parameters, so the second is added here.
1109        let entry = func.entry().expect("an entry block");
1110        let inst = func.insts(entry).next().expect("the copy is first");
1111        let list = func[func[inst].args][0];
1112        let args = func.push_values(&[list, list]);
1113        func[inst].args = args;
1114
1115        lists(&mut func, &SYSV);
1116        let text = printed(&func, &mut names);
1117        let first = text.find("store").expect("a write");
1118        let last = text.rfind("load.i64").expect("a read");
1119        assert!(last < first, "every read is above every write: {text}");
1120        valid(&func, &mut names);
1121    }
1122
1123    /// `struct s f(va_list *ap) { return va_arg(*ap, struct s); }`, where the structure is that
1124    /// many bytes wanting that much alignment and arrived in those registers. The object form of
1125    /// the instruction rather than the value one, because an aggregate is not a value and answers
1126    /// where it is instead.
1127    ///
1128    /// No slots is the object the classification sent to the caller's argument area, which is what
1129    /// everything over two eightbytes is.
1130    fn object(size: u64, align: u32, slots: &[Slot]) -> (Interner, Func) {
1131        let mut names = Interner::new();
1132        let signature = Signature::new().with_params(&[Type::PTR]).with_returns(&[Type::PTR]);
1133        let mut func = Func::new(names.intern("f"), signature);
1134        let entry = func.create_block();
1135        let list = func.append_param(entry, Type::PTR);
1136        let mem = func.add_mem(super::info(size, align));
1137        let slots = func.push_slots(slots);
1138        let at = func.add_va_object(VaInfo { mem, slots });
1139        let mut build = Builder::new(&mut func, entry);
1140        let args = build.func().push_values(&[list]);
1141        let data = InstData { args, extra: Extra::VaObject(at), ..InstData::new(Opcode::VaObject) };
1142        let got = build.value(data, Type::PTR);
1143        build.ret(&[got]);
1144        (names, func)
1145    }
1146
1147    /// One eightbyte of an object in the general purpose file, at that offset.
1148    fn gpr(offset: u64, size: u32) -> Slot {
1149        Slot::Integer { offset, size }
1150    }
1151
1152    /// One in the vector file, holding a `double`, which is what a whole eightbyte of floating
1153    /// point data is read as whichever way the members divide it up.
1154    fn sse(offset: u64) -> Slot {
1155        Slot::Float { offset, format: Format::Double }
1156    }
1157
1158    /// Over two eightbytes is class MEMORY whatever the members are, so there is one place it can
1159    /// be and no question to ask about which.
1160    #[test]
1161    fn an_object_too_big_for_the_registers_is_read_out_of_the_caller_s_memory() {
1162        let (mut names, mut func) = object(24, 8, &[]);
1163        lists(&mut func, &SYSV);
1164        let text = printed(&func, &mut names);
1165        assert!(!text.contains("va_object"), "{text}");
1166        assert_eq!(func.blocks().count(), 1, "no branch, so no new block: {text}");
1167        assert!(text.contains("iconst.i64 8"), "the overflow field is at eight: {text}");
1168        assert!(text.contains("iconst.i64 24"), "and the pointer steps past the object: {text}");
1169        assert!(!text.contains("gp_offset"), "{text}");
1170        valid(&func, &mut names);
1171    }
1172
1173    /// The size the pointer steps on by is the size rounded up to a word, because the argument
1174    /// area holds words and the argument behind this one starts at one of them.
1175    #[test]
1176    fn a_size_that_is_not_a_whole_number_of_words_steps_on_by_the_next_one() {
1177        let (mut names, mut func) = object(28, 4, &[]);
1178        lists(&mut func, &SYSV);
1179        let text = printed(&func, &mut names);
1180        assert!(text.contains("iconst.i64 32"), "twenty eight bytes step on by thirty two: {text}");
1181        valid(&func, &mut names);
1182    }
1183
1184    /// An object wanting more than a word is at the next multiple of what it wants, and one
1185    /// wanting a word or less is where the pointer already is, since the area is a run of words.
1186    #[test]
1187    fn an_object_wanting_more_alignment_than_a_word_is_rounded_up_to_it() {
1188        let (mut names, mut func) = object(32, 16, &[]);
1189        lists(&mut func, &SYSV);
1190        let text = printed(&func, &mut names);
1191        assert!(text.contains("iconst.i64 15"), "up to the next sixteen: {text}");
1192        assert!(text.contains("iconst.i64 -16"), "and down to a multiple of it: {text}");
1193        assert!(text.contains(" = and "), "which is an add and a mask: {text}");
1194        valid(&func, &mut names);
1195
1196        let (mut names, mut func) = object(24, 8, &[]);
1197        lists(&mut func, &SYSV);
1198        assert!(!printed(&func, &mut names).contains(" = and "), "a word wants no rounding");
1199    }
1200
1201    /// An object that arrived in registers is in the save area, and reading it is the branch a
1202    /// scalar asks with the object's own threshold: two eightbytes want two slots, so an offset
1203    /// that leaves room for one is not room enough.
1204    #[test]
1205    fn an_object_that_arrived_in_registers_is_copied_out_of_the_save_area() {
1206        let (mut names, mut func) = object(16, 8, &[gpr(0, 8), gpr(8, 8)]);
1207        let before = func.blocks().count();
1208        lists(&mut func, &SYSV);
1209        assert_eq!(func.blocks().count(), before + 3, "one for each path and one they meet at");
1210
1211        let text = printed(&func, &mut names);
1212        assert!(!text.contains("va_object"), "{text}");
1213        assert!(text.contains("iconst.i32 32"), "forty eight less two slots: {text}");
1214        assert!(text.contains("icmp ule"), "which is the threshold: {text}");
1215        assert!(text.contains("alloca, size 16"), "the object lands in a buffer: {text}");
1216        assert!(text.contains("iconst.i32 16"), "and the counter steps by both slots: {text}");
1217        valid(&func, &mut names);
1218    }
1219
1220    /// An object of one eightbyte of each file has to have room in both halves of the area, and
1221    /// the psABI puts the whole of it in the caller's memory when either of them is out. So there
1222    /// are two questions, and the second is only asked when the first said yes.
1223    #[test]
1224    fn an_object_in_both_files_asks_about_both_of_them() {
1225        let (mut names, mut func) = object(16, 8, &[gpr(0, 8), sse(8)]);
1226        lists(&mut func, &SYSV);
1227        let text = printed(&func, &mut names);
1228        assert_eq!(text.matches("br_if").count(), 2, "one question per file: {text}");
1229        assert!(text.contains("iconst.i32 40"), "forty eight less one slot: {text}");
1230        assert!(text.contains("iconst.i32 160"), "and a hundred and seventy six less one: {text}");
1231        assert!(text.contains("iconst.i32 8"), "each counter steps by its own slot: {text}");
1232        valid(&func, &mut names);
1233    }
1234
1235    /// An object whose last eightbyte is a part of one still comes out of the area as a whole
1236    /// register, so the buffer has room for the whole register and the bytes past the object are
1237    /// never read.
1238    #[test]
1239    fn the_buffer_is_as_big_as_the_registers_reach() {
1240        let (mut names, mut func) = object(5, 1, &[gpr(0, 5)]);
1241        lists(&mut func, &SYSV);
1242        let text = printed(&func, &mut names);
1243        assert!(text.contains("alloca, size 8"), "five bytes travel in a whole register: {text}");
1244        valid(&func, &mut names);
1245    }
1246
1247    /// A classification this cannot read out of the area is left alone, which is what makes the
1248    /// function refused by name further down rather than compiled into half a walk.
1249    ///
1250    /// Class X87 is the one to ask about, because the width alone would say yes: ten bytes sit
1251    /// inside a vector slot with room to spare, and there is no x87 register among the fourteen a
1252    /// variadic callee spills, so there is nothing in the area for this to read.
1253    #[test]
1254    fn a_classification_that_does_not_fit_the_area_is_left_alone() {
1255        let x87 = [Slot::Float { offset: 0, format: Format::X87Extended }];
1256        let (mut names, mut func) = object(16, 16, &x87);
1257        let before = printed(&func, &mut names);
1258        lists(&mut func, &SYSV);
1259        assert_eq!(printed(&func, &mut names), before);
1260    }
1261
1262    /// A `_Float128` walks the vector half with a slot of the whole register.
1263    ///
1264    /// One register and not two, which is the same answer the classification gives a quad passed to
1265    /// a function that names it: the offset stops at the last slot rather than the last but one,
1266    /// and it steps on by sixteen. What is read is sixteen bytes of float, which is a `movaps`
1267    /// further down and is the instruction gcc reads the same slot with.
1268    #[test]
1269    fn a_quad_takes_a_whole_vector_slot_of_the_save_area() {
1270        let (mut names, mut func) = built(Opcode::VaArg, Type::float(rucc_ir::Float::F128), 1);
1271        lists(&mut func, &SYSV);
1272        valid(&func, &mut names);
1273        let text = printed(&func, &mut names);
1274        assert!(!text.contains("va_arg"), "the va_arg is gone: {text}");
1275        assert!(text.contains("iconst.i32 160"), "a hundred and seventy six less one slot: {text}");
1276        assert!(text.contains("iconst.i32 16"), "and the counter steps by a whole one: {text}");
1277        assert!(text.contains("load.f128"), "read as the sixteen bytes it is: {text}");
1278    }
1279
1280    /// And the argument area gives it two words aligned to two, which is where it stops being a
1281    /// wider `double`. Every other value the machine computes in is where the pointer already is
1282    /// and steps it on by a word.
1283    #[test]
1284    fn a_quad_the_registers_ran_out_before_is_rounded_up_to_sixteen() {
1285        let (mut names, mut func) = built(Opcode::VaArg, Type::float(rucc_ir::Float::F128), 1);
1286        lists(&mut func, &SYSV);
1287        let text = printed(&func, &mut names);
1288        assert!(text.contains("iconst.i64 15"), "up to the next sixteen: {text}");
1289        assert!(text.contains("iconst.i64 -16"), "and down to a multiple of it: {text}");
1290        assert!(text.contains(" = and "), "which is an add and a mask: {text}");
1291
1292        let (mut names, mut func) = built(Opcode::VaArg, Type::float(rucc_ir::Float::F64), 1);
1293        lists(&mut func, &SYSV);
1294        let text = printed(&func, &mut names);
1295        assert!(!text.contains(" = and "), "a double is where the pointer already is: {text}");
1296        assert!(text.contains("iconst.i64 8"), "and steps it on by a word: {text}");
1297    }
1298
1299    /// An object holding a quad is one slot of the vector file, so the question is a single one
1300    /// and the copy moves all sixteen bytes at once.
1301    ///
1302    /// The buffer it lands in is sixteen byte aligned, which is what the store needs rather than
1303    /// what the object asked for, although for this object the two are the same number.
1304    #[test]
1305    fn an_object_holding_a_quad_is_copied_out_as_one_whole_register() {
1306        let quad = [Slot::Float { offset: 0, format: Format::Quad }];
1307        let (mut names, mut func) = object(16, 16, &quad);
1308        lists(&mut func, &SYSV);
1309        valid(&func, &mut names);
1310        let text = printed(&func, &mut names);
1311        assert!(!text.contains("va_object"), "{text}");
1312        assert_eq!(text.matches("br_if").count(), 1, "one file, so one question: {text}");
1313        assert!(text.contains("iconst.i32 160"), "a hundred and seventy six less one slot: {text}");
1314        assert!(text.contains("load.f128"), "moved as the register it is in: {text}");
1315        assert!(text.contains("alloca, size 16, align 16"), "a buffer a movaps accepts: {text}");
1316    }
1317
1318    /// What reads the object goes on reading the value it already read, the same way it does for a
1319    /// value, and for the same reason: the instruction becomes the address rather than being
1320    /// replaced by one, so nothing has to be substituted anywhere.
1321    #[test]
1322    fn what_reads_the_object_reads_the_same_value_it_did_before() {
1323        for slots in [&[][..], &[gpr(0, 8), gpr(8, 8)][..]] {
1324            let (mut names, mut func) = object(if slots.is_empty() { 24 } else { 16 }, 8, slots);
1325            let entry = func.entry().expect("an entry block");
1326            let inst = func.insts(entry).next().expect("the va_object is first");
1327            let read = func[inst].first_result.expect("it answers an address");
1328
1329            lists(&mut func, &SYSV);
1330            assert_eq!(func[inst].opcode, Opcode::IntToPtr, "the same instruction, lowered");
1331            assert_eq!(func[inst].first_result, Some(read), "producing the same value");
1332            valid(&func, &mut names);
1333        }
1334    }
1335
1336    /// Windows describes a list as one pointer, and its walk is that pointer stepped on, so there is
1337    /// nothing to compare and nowhere else to look: the argument is at the pointer, the pointer
1338    /// moves on by a word, and all of it is straight line.
1339    #[test]
1340    fn a_windows_va_arg_is_the_word_at_the_pointer_and_a_step() {
1341        let (mut names, mut func) = built(Opcode::VaArg, Type::int(32), 1);
1342        lists(&mut func, &WIN64);
1343        valid(&func, &mut names);
1344        let text = printed(&func, &mut names);
1345        assert!(!text.contains("va_arg"), "the va_arg is gone: {text}");
1346        assert!(!text.contains("br_if"), "and nothing was asked: {text}");
1347        assert_eq!(func.blocks().count(), 1, "so no block was made: {text}");
1348        assert!(text.contains("iconst.i64 8"), "the step is one word: {text}");
1349        assert_eq!(text.matches("= load").count(), 2, "the list and the argument: {text}");
1350        assert_eq!(text.matches("store").count(), 1, "and the list is written back: {text}");
1351    }
1352
1353    /// A pointer is as wide as the convention says a word is, since a type carries no width for
1354    /// one. Reading it as no bytes at all would be every string a `printf` was handed.
1355    #[test]
1356    fn a_windows_pointer_argument_is_the_whole_word() {
1357        let (mut names, mut func) = built(Opcode::VaArg, Type::PTR, 1);
1358        lists(&mut func, &WIN64);
1359        valid(&func, &mut names);
1360        let text = printed(&func, &mut names);
1361        assert_eq!(text.matches("= load").count(), 2, "the list and the argument: {text}");
1362        assert_eq!(text.matches("size 8").count(), 3, "and all three are words: {text}");
1363    }
1364
1365    /// The size is the whole of what says where a Windows argument is, so an object of eight bytes
1366    /// is in the slot and the answer is the slot's own address, and one of twenty four is elsewhere
1367    /// and the answer is what the slot holds. Neither of them asks about the classification.
1368    #[test]
1369    fn a_windows_object_is_in_the_slot_or_behind_it_according_to_its_size() {
1370        for (size, loads) in [(8, 1), (24, 2)] {
1371            let (mut names, mut func) = object(size, 8, &[]);
1372            lists(&mut func, &WIN64);
1373            valid(&func, &mut names);
1374            let text = printed(&func, &mut names);
1375            assert!(!text.contains("va_object"), "{text}");
1376            assert_eq!(func.blocks().count(), 1, "no branch, so no new block: {text}");
1377            assert_eq!(text.matches("= load").count(), loads, "{size} bytes: {text}");
1378            assert!(!text.contains("iconst.i64 24"), "the step is a word either way: {text}");
1379        }
1380    }
1381
1382    /// A list that is one pointer is copied by moving one pointer, and a copy moving three words
1383    /// would read two the caller never wrote and write them somewhere it does not own.
1384    #[test]
1385    fn a_windows_va_copy_moves_the_one_word_a_list_is() {
1386        let (mut names, mut func) = built(Opcode::VaCopy, Type::VOID, 2);
1387        lists(&mut func, &WIN64);
1388        valid(&func, &mut names);
1389        let text = printed(&func, &mut names);
1390        assert!(!text.contains("va_copy"), "{text}");
1391        assert_eq!(text.matches("load.i64").count(), 1, "{text}");
1392        assert_eq!(text.matches("store").count(), 1, "{text}");
1393    }
1394
1395    /// A scalar wider than a general purpose register is left alone, because the convention travels
1396    /// one as the address of a copy and nothing here writes that address yet, which is
1397    /// tamnd/rucc#1331. Reading the slot as the value would be reading the low eight bytes of a
1398    /// `long double`, and reading it as an address would be following a float.
1399    #[test]
1400    fn a_wide_scalar_is_left_alone_on_windows() {
1401        let wide =
1402            [Type::int(128), Type::float(rucc_ir::Float::F80), Type::float(rucc_ir::Float::F128)];
1403        for ty in wide {
1404            let (mut names, mut func) = built(Opcode::VaArg, ty, 1);
1405            let before = printed(&func, &mut names);
1406            lists(&mut func, &WIN64);
1407            assert_eq!(printed(&func, &mut names), before, "{ty:?}");
1408        }
1409    }
1410
1411    /// A width the algorithm is not right about is left alone for the same reason. An `__int128`
1412    /// takes two slots under an alignment rule of its own, which is a second algorithm and not a
1413    /// wider reading of this one, so it stays exactly as it was and is refused by name later.
1414    #[test]
1415    fn a_type_that_does_not_travel_in_one_slot_is_left_alone() {
1416        let ty = Type::int(128);
1417        let (mut names, mut func) = built(Opcode::VaArg, ty, 1);
1418        let before = printed(&func, &mut names);
1419        lists(&mut func, &SYSV);
1420        assert_eq!(printed(&func, &mut names), before, "{ty:?}");
1421    }
1422
1423    /// A `long double` is class X87, and the class has no register among the fourteen a variadic
1424    /// callee spills, so one is in the caller's argument area whether or not anything came before
1425    /// it. What that means for the rewrite is that the question `va_arg` usually asks has a known
1426    /// answer, so there is no compare, no branch and no join: one block, the overflow pointer
1427    /// rounded up to sixteen and stepped on by sixteen, and the load.
1428    #[test]
1429    fn a_long_double_is_read_straight_out_of_the_callers_argument_area() {
1430        let (mut names, mut func) = built(Opcode::VaArg, Type::float(rucc_ir::Float::F80), 1);
1431        lists(&mut func, &SYSV);
1432        valid(&func, &mut names);
1433        let text = printed(&func, &mut names);
1434        assert!(!text.contains("va_arg"), "the va_arg is gone: {text}");
1435        assert!(!text.contains("br_if"), "and nothing was asked: {text}");
1436        assert_eq!(func.blocks().count(), 1, "so no block was made: {text}");
1437        // The two numbers the psABI gives the class, in the rounding up and in the step.
1438        assert!(text.contains(" 15"), "rounded up to sixteen: {text}");
1439        assert!(text.contains(" 16"), "and stepped on by sixteen: {text}");
1440    }
1441
1442    /// Nothing else is touched, which matters because this runs over every function whether or not
1443    /// one reads a variable argument.
1444    #[test]
1445    fn a_function_with_no_list_in_it_is_left_exactly_as_it_was() {
1446        let mut names = Interner::new();
1447        let int = Type::int(32);
1448        let mut func =
1449            Func::new(names.intern("f"), Signature::new().with_params(&[int]).with_returns(&[int]));
1450        let entry = func.create_block();
1451        let x = func.append_param(entry, int);
1452        Builder::new(&mut func, entry).ret(&[x]);
1453
1454        let before = printed(&func, &mut names);
1455        lists(&mut func, &SYSV);
1456        assert_eq!(printed(&func, &mut names), before);
1457    }
1458}