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//! What is not the document's is what goes in the upper half of a vector slot, and the answer here
41//! is nothing at all. A slot is sixteen bytes wide because the register is, and the low eight are
42//! the whole of what any reader of a list looks at, since the widest thing `va_arg` names in this
43//! compiler is a `double`. So the spill writes eight bytes per vector register rather than sixteen
44//! and leaves the eight above them holding whatever the frame held. A reader that wanted all sixteen
45//! would be reading 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
74use rucc_ir::{
75    Block, Builder, Extra, Flags, Func, Imm, Inst, InstData, IntPred, MemInfo, MemOrder, Opcode,
76    Type, Value,
77};
78use rucc_target::{CallRegs, Slot};
79
80/// Where the count of general purpose register bytes already walked is.
81pub const GP_OFFSET: i64 = 0;
82/// Where the count of vector register bytes already walked is.
83pub const FP_OFFSET: i64 = 4;
84/// Where the pointer to the next argument in the caller's memory is.
85pub const OVERFLOW: i64 = 8;
86/// Where the pointer to the bottom of the register save area is.
87pub const SAVE_AREA: i64 = 16;
88/// How many bytes one `va_list` is, which is what a `va_copy` moves.
89pub const SIZE: u64 = 24;
90/// How wide the slot one vector register is saved in is, which is how wide the register is whatever
91/// this actually writes into it.
92pub const VECTOR_SLOT: u32 = 16;
93
94/// How big a callee's register save area is and where its two halves are.
95///
96/// Worked out from the convention rather than written down, so that a convention with a different
97/// number of argument registers gets an area the right size for it without anything here changing.
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub struct Area {
100    /// How many bytes of it the general purpose registers take, which is also where the vector half
101    /// begins, since the general purpose half is first and starts at nothing.
102    pub floats_at: u32,
103    /// How many bytes the whole of it is.
104    pub size: u32,
105    /// How many registers of each file it holds, general purpose first.
106    counts: (u32, u32),
107    /// How far apart two general purpose slots are, which is a word.
108    word: u32,
109}
110
111impl Area {
112    /// The save area a variadic callee under that convention needs.
113    #[must_use]
114    pub fn of(conv: &CallRegs) -> Self {
115        let ints = u32::try_from(conv.int_args.len()).unwrap_or(0);
116        let floats = u32::try_from(conv.sse_args.len()).unwrap_or(0);
117        let floats_at = conv.word * ints;
118        Self {
119            floats_at,
120            size: floats_at + VECTOR_SLOT * floats,
121            counts: (ints, floats),
122            word: conv.word,
123        }
124    }
125
126    /// How far apart two of a file's slots are.
127    #[must_use]
128    pub fn stride(self, float: bool) -> u32 {
129        if float { VECTOR_SLOT } else { self.word }
130    }
131
132    /// Where a file's first slot is, which is what `va_start` writes into that file's field when
133    /// the signature named no argument that file carried.
134    #[must_use]
135    pub fn starts_at(self, float: bool) -> u32 {
136        if float { self.floats_at } else { 0 }
137    }
138
139    /// Where a file's slots end, which is where the vector half begins for the general purpose
140    /// file and the end of the whole area for the vector one.
141    ///
142    /// This is what an object taking more than one register of a file is measured against: the
143    /// psABI asks whether the offset is at or below the end less a slot for each register the
144    /// object wants, and one register of it is the same question [`Area::last`] asks.
145    #[must_use]
146    pub fn ends_at(self, float: bool) -> u32 {
147        if float { self.size } else { self.floats_at }
148    }
149
150    /// How many registers of a file the area holds.
151    #[must_use]
152    fn holds(self, float: bool) -> u32 {
153        if float { self.counts.1 } else { self.counts.0 }
154    }
155
156    /// The offset of a file's last slot, which is the threshold `va_arg` compares against.
157    ///
158    /// The last slot's own offset and not the end of the area, because an offset equal to the end
159    /// is one slot past the last argument while an offset a slot below the end is the last argument
160    /// itself. An empty file has no such offset and nothing here has one.
161    #[must_use]
162    pub fn last(self, float: bool) -> Option<u32> {
163        let last = self.holds(float).checked_sub(1)?;
164        Some(self.starts_at(float) + self.stride(float) * last)
165    }
166}
167
168/// Rewrites every `va_arg`, `va_copy` and `va_end` in the function, and leaves `va_start` alone.
169///
170/// Those three are the ones made only of reads and writes of a list some pointer already reaches,
171/// so none of them needs to know anything about the frame and all three can be done here.
172/// `va_start` is the one that does need the frame, and [`crate::lower`] has it.
173///
174/// A convention whose list is not the four field one is left alone entirely, and a function using
175/// one is then refused further down with the message about a rule that does not exist. Windows is
176/// the one such convention here: its list is a plain pointer, its callee spills its four register
177/// arguments into the shadow space the caller already reserved rather than into an area of its own,
178/// and none of the three rewrites below is right for any of that.
179pub fn lists(func: &mut Func, conv: &CallRegs) {
180    if conv.shared_positions {
181        return;
182    }
183    let area = Area::of(conv);
184    let found: Vec<Inst> =
185        func.blocks().flat_map(|block| func.insts(block).collect::<Vec<_>>()).collect();
186    for inst in found {
187        match func[inst].opcode {
188            Opcode::VaArg => next(func, inst, area),
189            Opcode::VaObject => object(func, inst, area),
190            Opcode::VaCopy => copy(func, inst),
191            // Nothing at all, which is what the psABI says it is. The instruction was still worth
192            // emitting, because it says the list stops being read here, and here is where that
193            // stops being worth saying.
194            Opcode::VaEnd => func.remove_inst(inst),
195            _ => {}
196        }
197    }
198}
199
200/// One `va_arg`, as the branch on whether the argument it wants is still in the save area.
201///
202/// The block the instruction was in is cut in two at the instruction. What was above it stays where
203/// it is and gets the compare and the branch, what was below it moves into a new block that takes
204/// the address as a parameter, and the `va_arg` itself becomes the load at the top of that block.
205/// Turning it into the load rather than replacing it keeps the value the rest of the function reads
206/// the value it already read, so nothing has to be substituted anywhere, and the two paths meet at a
207/// block parameter because the IR has no variables for them to meet at.
208fn next(func: &mut Func, inst: Inst, area: Area) {
209    let Some(result) = func[inst].first_result else { return };
210    let Some(&list) = func[func[inst].args].first() else { return };
211    let ty = func[result].ty;
212    let Some(block) = func.block_of(inst) else { return };
213    let span = func.span(inst);
214    // A scalar of a width a register holds, which is every type the algorithm below is right about.
215    // A `long double` is on the x87 stack, and an `__int128` takes two slots with an alignment rule
216    // of its own. Both of those are a second algorithm rather than a wider reading of this one, so
217    // both are left alone here and refused by name further down.
218    if !ty.is_scalar() || ty.bits() > 64 || !(ty.is_int() || ty.is_float() || ty.is_ptr()) {
219        return;
220    }
221    let float = ty.is_float();
222    let Some(last) = area.last(float) else { return };
223    let field = if float { FP_OFFSET } else { GP_OFFSET };
224
225    // Everything below the instruction, taken out before anything is built, because the builder
226    // appends to a block and this block has to end at the branch.
227    let rest: Vec<Inst> = func.insts(block).skip_while(|&at| at != inst).skip(1).collect();
228    let taken = func.create_block();
229    let overflowed = func.create_block();
230    let join = func.create_block();
231    let addr = func.append_param(join, Type::PTR);
232    func.remove_inst(inst);
233    for &at in &rest {
234        func.remove_inst(at);
235    }
236
237    // The question, in the block the `va_arg` used to be in. Unsigned, because an offset into the
238    // save area counts bytes and is never negative, and because what the field holds once the
239    // register arguments have all been walked is a number past the end rather than a small one.
240    let mut build = Builder::new(func, block).at(span);
241    let counter = offset(&mut build, list, field);
242    let walked = build.load(Type::int(32), counter, info(4, 4), Flags::default());
243    let end = build.iconst(Type::int(32), i128::from(last));
244    let inside = build.icmp(IntPred::Ule, walked, end);
245    build.br_if(inside, taken, &[], overflowed, &[]);
246
247    // The register path: the argument is in the save area at the offset the field holds, and the
248    // field steps on by one slot of its file.
249    let mut build = Builder::new(func, taken).at(span);
250    let base = offset(&mut build, list, SAVE_AREA);
251    let save = build.load(Type::PTR, base, info(8, 8), Flags::default());
252    let wide = build.unary(Opcode::ZExt, walked, Type::int(64));
253    let found = added(&mut build, save, wide);
254    let stride = build.iconst(Type::int(32), i128::from(area.stride(float)));
255    let stepped = build.binary(Opcode::Add, walked, stride, Flags::default());
256    let counter = offset(&mut build, list, field);
257    build.store(stepped, counter, info(4, 4), Flags::default());
258    build.jump(join, &[found]);
259
260    // The memory path: the argument is where the caller left it, and the pointer steps on by a
261    // word, because the caller's argument area is a run of whole words whatever is in them.
262    let mut build = Builder::new(func, overflowed).at(span);
263    let pointer = offset(&mut build, list, OVERFLOW);
264    let here = build.load(Type::PTR, pointer, info(8, 8), Flags::default());
265    let word = build.iconst(Type::int(64), i128::from(area.word));
266    let onward = added(&mut build, here, word);
267    build.store(onward, pointer, info(8, 8), Flags::default());
268    build.jump(join, &[here]);
269
270    // And the load the program actually wrote, over the address the two paths agreed on, with
271    // everything that used to follow it behind it in the order it was written.
272    let bytes = ty.bits() / 8;
273    let mem = func.add_mem(info(u64::from(bytes), bytes));
274    let args = func.push_values(&[addr]);
275    let data = &mut func[inst];
276    data.opcode = Opcode::Load;
277    data.args = args;
278    data.extra = Extra::Mem(mem);
279    data.flags = data.flags.intersection(Flags::legal_on(Opcode::Load));
280    func.append_inst(join, inst);
281    for at in rest {
282        func.append_inst(join, at);
283    }
284}
285
286/// One `va_object`, as the address the object can be read from.
287///
288/// Two shapes, and the slots on the instruction are what say which. An object with none is one the
289/// classification sent to the caller's argument area, which is what everything over two eightbytes
290/// is whatever its members are. There is no question to ask about that one: the overflow pointer
291/// says where it is and steps on past it, and no block is needed.
292///
293/// An object with slots arrived in registers, and that is the branch [`next`] builds for a scalar
294/// with the object's own two differences: the room has to be there for every one of its slots at
295/// once, and what is answered is a buffer the slots were copied into rather than an address in the
296/// save area, because two eightbytes of one object are not next to each other in there.
297///
298/// The address is answered rather than a copy of the object, which is what the instruction is for
299/// and what gcc does with the same argument. An object in the caller's memory is already somewhere
300/// addressable, and the copy the C standard describes is the assignment the caller of `va_arg`
301/// wrote, which the front end has already built around this.
302fn object(func: &mut Func, inst: Inst, area: Area) {
303    let Extra::VaObject(at) = func[inst].extra else { return };
304    let object = func[at];
305    let MemInfo { size, align, .. } = func[object.mem];
306    let slots: Vec<Slot> = func[object.slots].to_vec();
307    let Some(&list) = func[func[inst].args].first() else { return };
308    let Some(block) = func.block_of(inst) else { return };
309    if func[inst].first_result.is_none() || !fits(&slots, area) {
310        return;
311    }
312    let span = func.span(inst);
313
314    // The buffer the register form copies into, made before anything else, because an alloca of
315    // a fixed size belongs in the entry block and the walk below is built where the instruction
316    // is. It is as big as the slots reach rather than as big as the object, which is more for an
317    // object whose last eightbyte is a part of one: five bytes travel in a whole register and
318    // come out of the area as a whole register, so the buffer has eight bytes for them to land
319    // in and the three past the object are never read.
320    let reach = slots.iter().map(|&slot| slot.offset() + width(slot)).max().unwrap_or(0);
321    let room = buffer(func, inst, reach.max(size), align);
322
323    // Everything below the instruction, taken out before anything is built, because a builder
324    // appends to a block and the register form ends this one at a branch.
325    let rest: Vec<Inst> = func.insts(block).skip_while(|&at| at != inst).skip(1).collect();
326    func.remove_inst(inst);
327    for &at in &rest {
328        func.remove_inst(at);
329    }
330
331    let (ends, address) = match room {
332        Some(room) if !slots.is_empty() => {
333            registers(func, block, inst, Read { list, area, slots: &slots, size, align, room })
334        }
335        _ => {
336            let mut build = Builder::new(func, block).at(span);
337            (block, overflow(&mut build, list, area, size, align))
338        }
339    };
340
341    // And the instruction itself is that address, so that everything reading it goes on reading
342    // the value it already read and nothing has to be substituted anywhere.
343    let args = func.push_values(&[address]);
344    let data = &mut func[inst];
345    data.opcode = Opcode::IntToPtr;
346    data.args = args;
347    data.extra = Extra::None;
348    data.flags = data.flags.intersection(Flags::legal_on(Opcode::IntToPtr));
349    func.append_inst(ends, inst);
350    for at in rest {
351        func.append_inst(ends, at);
352    }
353}
354
355/// One object read off one list, which is what both halves of the walk are about.
356#[derive(Clone, Copy)]
357struct Read<'a> {
358    /// The list it is read from.
359    list: Value,
360    /// The save area of the function doing the reading.
361    area: Area,
362    /// Which register each of the object's eightbytes arrived in, and empty for an object that
363    /// arrived in the caller's memory.
364    slots: &'a [Slot],
365    /// How many bytes the object is.
366    size: u64,
367    /// What it is aligned to.
368    align: u32,
369    /// The buffer of the function's own the register form copies the object into.
370    room: Value,
371}
372
373/// Whether the classification is one this knows how to read out of the save area.
374///
375/// A slot wider than a register or more of them than the area holds is a classification from some
376/// other machine or from a rule this has not been taught. Turning it down here leaves the
377/// instruction alone, and an instruction left alone is refused by name further down, which is a
378/// message about `va_arg` rather than whatever a half built walk would do at run time.
379fn fits(slots: &[Slot], area: Area) -> bool {
380    let mut counts = [0, 0];
381    for &slot in slots {
382        if width(slot) > u64::from(area.word) {
383            return false;
384        }
385        counts[usize::from(is_float(slot))] += 1;
386    }
387    counts[0] <= area.holds(false) && counts[1] <= area.holds(true)
388}
389
390/// The register form: the room in the save area is asked about once per file, and the object is
391/// copied out of the area into a buffer when it is there and read from the caller's memory when it
392/// is not.
393///
394/// The question is asked once per file the object takes a register of, and both have to say yes,
395/// because the psABI puts the whole object in the caller's memory when there is not room in the
396/// area for all of it. A file the object takes nothing of has room by definition and is not asked
397/// about, which is every object of one class and is most of them.
398///
399/// Gives back the block the walk ends in and the address, as an integer, that the two paths agreed
400/// on.
401fn registers(func: &mut Func, block: Block, inst: Inst, read: Read<'_>) -> (Block, Value) {
402    let span = func.span(inst);
403    let area = read.area;
404    let counts = [taken_of(read.slots, false), taken_of(read.slots, true)];
405    let saved = func.create_block();
406    let overflowed = func.create_block();
407    let join = func.create_block();
408    let address = func.append_param(join, Type::int(64));
409
410    // The questions, each in its own block, because two of them are two branches and the second
411    // is only asked when the first said yes.
412    let asked: Vec<bool> =
413        [false, true].into_iter().filter(|&float| counts[usize::from(float)] > 0).collect();
414    let mut at = block;
415    for (index, &float) in asked.iter().enumerate() {
416        let next = if index + 1 == asked.len() { saved } else { func.create_block() };
417        // The psABI's own threshold: the end of the file's half of the area, less a slot for each
418        // register the object wants, so that an offset at it leaves room for all of them.
419        let room =
420            area.ends_at(float).saturating_sub(area.stride(float) * counts[usize::from(float)]);
421        let mut build = Builder::new(func, at).at(span);
422        let counter = offset(&mut build, read.list, field_of(float));
423        let walked = build.load(Type::int(32), counter, info(4, 4), Flags::default());
424        let end = build.iconst(Type::int(32), i128::from(room));
425        let inside = build.icmp(IntPred::Ule, walked, end);
426        build.br_if(inside, next, &[], overflowed, &[]);
427        at = next;
428    }
429
430    let mut build = Builder::new(func, saved).at(span);
431    let found = copied(&mut build, read, counts);
432    build.jump(join, &[found]);
433
434    let mut build = Builder::new(func, overflowed).at(span);
435    let here = overflow(&mut build, read.list, area, read.size, read.align);
436    build.jump(join, &[here]);
437
438    (join, address)
439}
440
441/// The object copied out of the save area into the buffer, as the address of the buffer.
442///
443/// A buffer and not an address in the area because the eightbytes of one object are not next to
444/// each other in there: two integer eightbytes are eight bytes apart and two vector ones are
445/// sixteen, and an object of one of each has them in different halves of the area entirely. So
446/// there is nowhere in the area the object is, and the one place it can be made to be is somewhere
447/// else.
448fn copied(build: &mut Builder<'_>, read: Read<'_>, counts: [u32; 2]) -> Value {
449    let area = read.area;
450    let base = offset(build, read.list, SAVE_AREA);
451    let save = build.load(Type::PTR, base, info(8, 8), Flags::default());
452
453    // Where each file's next slot is, which is the one thing the offsets in the list say, and the
454    // counter itself, which is what steps on by every slot the object took of that file.
455    let mut walked = [None, None];
456    let mut nexts = [None, None];
457    for float in [false, true] {
458        let file = usize::from(float);
459        if counts[file] == 0 {
460            continue;
461        }
462        let counter = offset(build, read.list, field_of(float));
463        let read = build.load(Type::int(32), counter, info(4, 4), Flags::default());
464        let wide = build.unary(Opcode::ZExt, read, Type::int(64));
465        walked[file] = Some(read);
466        nexts[file] = Some(added(build, save, wide));
467    }
468
469    let mut seen = [0, 0];
470    for &slot in read.slots {
471        let float = is_float(slot);
472        let file = usize::from(float);
473        let Some(from) = nexts[file] else { continue };
474        let step = i64::from(area.stride(float) * seen[file]);
475        seen[file] += 1;
476        // As an integer of the slot's width whatever the file it came from, because what this is
477        // is a copy of the object's bytes and nothing here reads them as anything.
478        let bytes = width(slot);
479        let ty = Type::int(u32::try_from(bytes).unwrap_or(1) * 8);
480        let at = offset(build, from, step);
481        let value =
482            build.load(ty, at, info(bytes, area.stride(float).min(area.word)), Flags::default());
483        let into = offset(build, read.room, i64::try_from(slot.offset()).unwrap_or(0));
484        let holds = info(bytes, part(read.align, slot.offset()));
485        build.store(value, into, holds, Flags::default());
486    }
487
488    // And the counters step on by every slot the object took, since the whole of it came out of
489    // the area and the argument behind it starts past all of it.
490    for float in [false, true] {
491        let file = usize::from(float);
492        let Some(counter) = walked[file] else { continue };
493        let by = build.iconst(Type::int(32), i128::from(area.stride(float) * counts[file]));
494        let stepped = build.binary(Opcode::Add, counter, by, Flags::default());
495        let at = offset(build, read.list, field_of(float));
496        build.store(stepped, at, info(4, 4), Flags::default());
497    }
498    build.unary(Opcode::PtrToInt, read.room, Type::int(64))
499}
500
501/// A buffer at the front of the entry block, which is where an alloca of a fixed size belongs.
502///
503/// Not where the walk is, because a walk inside a loop would then be an alloca inside a loop,
504/// which is a frame that grows every time round. One buffer per `va_arg` of an object, made once
505/// and written every time the object is read, which is what the front end would have written if
506/// the temporary had a name.
507fn buffer(func: &mut Func, inst: Inst, size: u64, align: u32) -> Option<Value> {
508    let entry = func.entry()?;
509    let span = func.span(inst);
510    let mem = func.add_mem(info(size, align.max(1)));
511    let data = InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) };
512    let made = func.create_inst(data, &[Type::PTR], span);
513    let first = func.insts(entry).next();
514    match first {
515        Some(first) => func.insert_before(made, first),
516        None => func.append_inst(entry, made),
517    }
518    func[made].first_result
519}
520
521/// Where the argument the caller left in memory is, with the overflow pointer stepped on past it,
522/// as an integer address.
523///
524/// The pointer is rounded up first for an object that wants more alignment than a word. The
525/// argument area is a run of words, so anything asking for eight or less is where it is already,
526/// and anything asking for more was put at the next multiple of what it asked for by whoever
527/// passed it.
528fn overflow(build: &mut Builder<'_>, list: Value, area: Area, size: u64, align: u32) -> Value {
529    let word = u64::from(area.word);
530    let wide = Type::int(64);
531    let pointer = offset(build, list, OVERFLOW);
532    let here = build.load(Type::PTR, pointer, info(word, area.word), Flags::default());
533
534    // As an integer, because rounding up is an add and a mask and neither is a thing to do to a
535    // pointer. Both casts are free: the two are the same bits on this machine and nothing is
536    // written for either.
537    let mut at = build.unary(Opcode::PtrToInt, here, wide);
538    if u64::from(align) > word {
539        // Up to the next multiple of a power of two, which is the round up every alignment is.
540        // The mask is the negative of the alignment because that is what the complement of one
541        // less than it comes to, and writing it that way keeps it inside a signed sixty four bit
542        // constant.
543        let bump = build.iconst(wide, i128::from(align) - 1);
544        at = build.binary(Opcode::Add, at, bump, Flags::default());
545        let mask = build.iconst(wide, -i128::from(align));
546        at = build.binary(Opcode::And, at, mask, Flags::default());
547    }
548
549    // Past it, rounded up to a whole number of words, because the argument area holds words and
550    // the argument behind this one starts at one of them.
551    let by = build.iconst(wide, i128::from(size.next_multiple_of(word)));
552    let onward = build.binary(Opcode::Add, at, by, Flags::default());
553    let onward = build.unary(Opcode::IntToPtr, onward, Type::PTR);
554    build.store(onward, pointer, info(word, area.word), Flags::default());
555    at
556}
557
558/// Which of the two counters a file's slots are walked with.
559fn field_of(float: bool) -> i64 {
560    if float { FP_OFFSET } else { GP_OFFSET }
561}
562
563/// Whether a slot is one of the vector file's.
564fn is_float(slot: Slot) -> bool {
565    matches!(slot, Slot::Float { .. })
566}
567
568/// How many registers of a file an object takes.
569fn taken_of(slots: &[Slot], float: bool) -> u32 {
570    u32::try_from(slots.iter().filter(|&&slot| is_float(slot) == float).count()).unwrap_or(0)
571}
572
573/// How many bytes one slot moves, which is its own width rounded up to one the machine has a load
574/// for.
575fn width(slot: Slot) -> u64 {
576    match slot {
577        Slot::Integer { size, .. } => u64::from(size.next_power_of_two().clamp(1, 8)),
578        Slot::Float { format, .. } => u64::from(format.width()).div_ceil(8),
579    }
580}
581
582/// What a part of an object at that offset is aligned to, which is what the object is aligned to
583/// for the part at the front of it and how far into the object the part sits for every other.
584fn part(align: u32, offset: u64) -> u32 {
585    let align = align.max(1);
586    if offset == 0 {
587        return align;
588    }
589    u32::try_from(1_u64 << offset.trailing_zeros()).unwrap_or(align).min(align)
590}
591
592/// One `va_copy`, as the fields of one list moved into another.
593///
594/// A list is those fields and holds nothing anywhere else, so copying it is copying them, and three
595/// words move as three words rather than as a call to `memcpy`, which is a name this compiler
596/// cannot emit yet and would be the wrong answer for three words in any case.
597///
598/// Every read is built before any write, so that a list copied onto itself, which is legal and
599/// useless, moves what it held rather than what it has just been given.
600fn copy(func: &mut Func, inst: Inst) {
601    let [into, from] = func[func[inst].args] else { return };
602    let mut moved = Vec::new();
603    for word in 0..SIZE / 8 {
604        let step = i64::try_from(word * 8).unwrap_or(0);
605        let there = field(func, inst, from, step);
606        let mem = func.add_mem(info(8, 8));
607        let args = func.push_values(&[there]);
608        let data = InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Load) };
609        moved.push((ahead(func, inst, data, Type::int(64)), step));
610    }
611    for (read, step) in moved {
612        let here = field(func, inst, into, step);
613        let mem = func.add_mem(info(8, 8));
614        let args = func.push_values(&[read, here]);
615        let data = InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Store) };
616        let span = func.span(inst);
617        let made = func.create_inst(data, &[], span);
618        func.insert_before(made, inst);
619    }
620    func.remove_inst(inst);
621}
622
623/// The address of a field of a list, written in front of an instruction, or the list itself for the
624/// field at the front of it.
625fn field(func: &mut Func, inst: Inst, list: Value, at: i64) -> Value {
626    if at == 0 {
627        return list;
628    }
629    let extra = Extra::Imm(func.add_imm(Imm::int(i128::from(at), Type::int(64))));
630    let step =
631        ahead(func, inst, InstData { extra, ..InstData::new(Opcode::IConst) }, Type::int(64));
632    let args = func.push_values(&[list, step]);
633    ahead(func, inst, InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR)
634}
635
636/// Puts an instruction in front of another one and gives back the value it produces.
637fn ahead(func: &mut Func, inst: Inst, data: InstData, ty: Type) -> Value {
638    let span = func.span(inst);
639    let made = func.create_inst(data, &[ty], span);
640    func.insert_before(made, inst);
641    func[made].first_result.expect("an instruction created with one result has one")
642}
643
644/// The address of a field of a list in a block being filled, or the list itself for the field at
645/// the front of it.
646fn offset(build: &mut Builder<'_>, list: Value, at: i64) -> Value {
647    if at == 0 {
648        return list;
649    }
650    let step = build.iconst(Type::int(64), i128::from(at));
651    added(build, list, step)
652}
653
654/// A pointer with an integer added to it.
655fn added(build: &mut Builder<'_>, pointer: Value, by: Value) -> Value {
656    let args = build.func().push_values(&[pointer, by]);
657    build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR)
658}
659
660/// An ordinary read or write of that many bytes, aligned that far.
661///
662/// Every access this pass makes is to a field of a list or to an argument, and none of them is
663/// atomic or has anything to say about aliasing.
664fn info(size: u64, align: u32) -> MemInfo {
665    MemInfo { size, align, order: MemOrder::NotAtomic, tbaa: None }
666}
667
668#[cfg(test)]
669mod tests {
670    use rucc_base::Interner;
671    use rucc_base::float::Format;
672    use rucc_ir::{Builder, Extra, Func, InstData, Module, Opcode, Signature, Type, VaInfo};
673    use rucc_target::x86_64::{SYSV, WIN64};
674    use rucc_target::{Arch, Env, Os, Slot, TargetInfo, Triple};
675
676    use super::{Area, FP_OFFSET, GP_OFFSET, OVERFLOW, SAVE_AREA, SIZE, VECTOR_SLOT, lists};
677
678    fn target() -> TargetInfo {
679        TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu))
680    }
681
682    /// `T f(va_list *ap) { return va_arg(*ap, T); }`, or the same shape over whichever of the
683    /// family is asked for, with the list arriving as the pointer it has decayed to by the time
684    /// anything reads it.
685    fn built(opcode: Opcode, ty: Type, lists: usize) -> (Interner, Func) {
686        let mut names = Interner::new();
687        let params = vec![Type::PTR; lists];
688        let mut signature = Signature::new().with_params(&params);
689        if !ty.is_void() {
690            signature = signature.with_returns(&[ty]);
691        }
692        let mut func = Func::new(names.intern("f"), signature);
693        let entry = func.create_block();
694        let args: Vec<_> = params.iter().map(|&ty| func.append_param(entry, ty)).collect();
695
696        let mut build = Builder::new(&mut func, entry);
697        let list = build.func().push_values(&args);
698        if ty.is_void() {
699            build.inst(InstData { args: list, ..InstData::new(opcode) }, &[]);
700            build.ret(&[]);
701        } else {
702            let got = build.value(InstData { args: list, ..InstData::new(opcode) }, ty);
703            build.ret(&[got]);
704        }
705        (names, func)
706    }
707
708    fn printed(func: &Func, names: &mut Interner) -> String {
709        let module = Module::new(names.intern("va.c"), &target());
710        rucc_ir::print_func(&module, func, names)
711    }
712
713    fn valid(func: &Func, names: &mut Interner) {
714        let module = Module::new(names.intern("va.c"), &target());
715        rucc_ir::verify_func(&module, func, names).expect("the rewrite builds valid IR");
716    }
717
718    /// The numbers in this test are the psABI's own, written out rather than computed, because the
719    /// whole point of the layout is that it is the document's and not a convenient one. A version
720    /// of [`Area`] that worked them out differently would agree with itself and disagree with the C
721    /// library, and this is what would notice.
722    #[test]
723    fn the_save_area_is_the_one_the_document_describes() {
724        let area = Area::of(&SYSV);
725        assert_eq!(area.floats_at, 48, "six general purpose registers of eight bytes");
726        assert_eq!(area.size, 176, "and eight vector ones of sixteen");
727        assert_eq!(area.stride(false), 8);
728        assert_eq!(area.stride(true), VECTOR_SLOT);
729        assert_eq!(area.starts_at(false), 0);
730        assert_eq!(area.starts_at(true), 48);
731        // The last slot's own offset and not the end of the area, which is what `va_arg` compares
732        // against: an offset equal to the end is one slot past the last argument.
733        assert_eq!(area.last(false), Some(40));
734        assert_eq!(area.last(true), Some(160));
735    }
736
737    /// And the four fields, for the same reason.
738    #[test]
739    fn a_list_is_the_four_fields_the_document_describes() {
740        assert_eq!((GP_OFFSET, FP_OFFSET, OVERFLOW, SAVE_AREA), (0, 4, 8, 16));
741        assert_eq!(SIZE, 24);
742    }
743
744    #[test]
745    fn a_va_arg_becomes_the_branch_on_whether_the_argument_is_still_in_the_save_area() {
746        let (mut names, mut func) = built(Opcode::VaArg, Type::int(32), 1);
747        let before = func.blocks().count();
748        lists(&mut func, &SYSV);
749        assert_eq!(func.blocks().count(), before + 3, "one for each path and one they meet at");
750
751        let text = printed(&func, &mut names);
752        assert!(!text.contains("va_arg"), "the va_arg is gone: {text}");
753        assert!(text.contains("icmp ule"), "the threshold is a comparison: {text}");
754        assert!(text.contains("br_if"), "and it is branched on: {text}");
755        valid(&func, &mut names);
756    }
757
758    /// Which field it walks is the whole of the difference between the two files, and getting it
759    /// backwards is a program that reads its integers out of the vector half.
760    #[test]
761    fn which_half_of_the_area_is_walked_is_the_type_s_answer() {
762        for (ty, last, stride) in
763            [(Type::int(64), 40, 8), (Type::float(rucc_ir::Float::F64), 160, 16)]
764        {
765            let (mut names, mut func) = built(Opcode::VaArg, ty, 1);
766            lists(&mut func, &SYSV);
767            let text = printed(&func, &mut names);
768            assert!(text.contains(&format!("iconst.i32 {last}")), "{ty:?} stops at {last}: {text}");
769            assert!(text.contains(&format!("iconst.i32 {stride}")), "and steps by it: {text}");
770        }
771    }
772
773    /// The value the rest of the function reads has to stay the value it already read, since the
774    /// rewrite substitutes nothing anywhere. It stays it by the `va_arg` becoming the load rather
775    /// than being replaced by one, so the instruction is the same instruction under a new opcode
776    /// and in a new block.
777    #[test]
778    fn what_reads_the_argument_reads_the_same_value_it_did_before() {
779        let (mut names, mut func) = built(Opcode::VaArg, Type::int(32), 1);
780        let entry = func.entry().expect("an entry block");
781        let inst = func.insts(entry).next().expect("the va_arg is first");
782        let read = func[inst].first_result.expect("it produces the argument");
783
784        lists(&mut func, &SYSV);
785        assert_eq!(func[inst].opcode, Opcode::Load, "the same instruction, lowered");
786        assert_eq!(func[inst].first_result, Some(read), "producing the same value");
787        assert_ne!(func.block_of(inst), Some(entry), "in the block the two paths meet at");
788        valid(&func, &mut names);
789    }
790
791    #[test]
792    fn a_va_end_is_nothing_at_all() {
793        let (mut names, mut func) = built(Opcode::VaEnd, Type::VOID, 1);
794        lists(&mut func, &SYSV);
795        let text = printed(&func, &mut names);
796        assert!(!text.contains("va_end"), "{text}");
797        assert_eq!(func.blocks().count(), 1, "and needs no block: {text}");
798        valid(&func, &mut names);
799    }
800
801    /// Three words and no branch, because a list is three words and holds nothing anywhere else.
802    #[test]
803    fn a_va_copy_is_the_list_moved_a_word_at_a_time() {
804        let (mut names, mut func) = built(Opcode::VaCopy, Type::VOID, 2);
805        lists(&mut func, &SYSV);
806        let text = printed(&func, &mut names);
807        assert!(!text.contains("va_copy"), "{text}");
808        assert_eq!(text.matches("load.i64").count(), 3, "{text}");
809        assert_eq!(text.matches("store").count(), 3, "{text}");
810        assert_eq!(func.blocks().count(), 1, "and needs no block: {text}");
811        valid(&func, &mut names);
812    }
813
814    /// Every read before every write, so that `va_copy(ap, ap)` moves what the list held rather
815    /// than what it has just been given. Useless and legal, which is exactly the combination that
816    /// gets written once and never tested anywhere else.
817    #[test]
818    fn a_list_copied_onto_itself_moves_what_it_held() {
819        let (mut names, mut func) = built(Opcode::VaCopy, Type::VOID, 1);
820        // One parameter, so both operands of the copy are the same list. The builder above pushes
821        // as many operands as there are parameters, so the second is added here.
822        let entry = func.entry().expect("an entry block");
823        let inst = func.insts(entry).next().expect("the copy is first");
824        let list = func[func[inst].args][0];
825        let args = func.push_values(&[list, list]);
826        func[inst].args = args;
827
828        lists(&mut func, &SYSV);
829        let text = printed(&func, &mut names);
830        let first = text.find("store").expect("a write");
831        let last = text.rfind("load.i64").expect("a read");
832        assert!(last < first, "every read is above every write: {text}");
833        valid(&func, &mut names);
834    }
835
836    /// `struct s f(va_list *ap) { return va_arg(*ap, struct s); }`, where the structure is that
837    /// many bytes wanting that much alignment and arrived in those registers. The object form of
838    /// the instruction rather than the value one, because an aggregate is not a value and answers
839    /// where it is instead.
840    ///
841    /// No slots is the object the classification sent to the caller's argument area, which is what
842    /// everything over two eightbytes is.
843    fn object(size: u64, align: u32, slots: &[Slot]) -> (Interner, Func) {
844        let mut names = Interner::new();
845        let signature = Signature::new().with_params(&[Type::PTR]).with_returns(&[Type::PTR]);
846        let mut func = Func::new(names.intern("f"), signature);
847        let entry = func.create_block();
848        let list = func.append_param(entry, Type::PTR);
849        let mem = func.add_mem(super::info(size, align));
850        let slots = func.push_slots(slots);
851        let at = func.add_va_object(VaInfo { mem, slots });
852        let mut build = Builder::new(&mut func, entry);
853        let args = build.func().push_values(&[list]);
854        let data = InstData { args, extra: Extra::VaObject(at), ..InstData::new(Opcode::VaObject) };
855        let got = build.value(data, Type::PTR);
856        build.ret(&[got]);
857        (names, func)
858    }
859
860    /// One eightbyte of an object in the general purpose file, at that offset.
861    fn gpr(offset: u64, size: u32) -> Slot {
862        Slot::Integer { offset, size }
863    }
864
865    /// One in the vector file, holding a `double`, which is what a whole eightbyte of floating
866    /// point data is read as whichever way the members divide it up.
867    fn sse(offset: u64) -> Slot {
868        Slot::Float { offset, format: Format::Double }
869    }
870
871    /// Over two eightbytes is class MEMORY whatever the members are, so there is one place it can
872    /// be and no question to ask about which.
873    #[test]
874    fn an_object_too_big_for_the_registers_is_read_out_of_the_caller_s_memory() {
875        let (mut names, mut func) = object(24, 8, &[]);
876        lists(&mut func, &SYSV);
877        let text = printed(&func, &mut names);
878        assert!(!text.contains("va_object"), "{text}");
879        assert_eq!(func.blocks().count(), 1, "no branch, so no new block: {text}");
880        assert!(text.contains("iconst.i64 8"), "the overflow field is at eight: {text}");
881        assert!(text.contains("iconst.i64 24"), "and the pointer steps past the object: {text}");
882        assert!(!text.contains("gp_offset"), "{text}");
883        valid(&func, &mut names);
884    }
885
886    /// The size the pointer steps on by is the size rounded up to a word, because the argument
887    /// area holds words and the argument behind this one starts at one of them.
888    #[test]
889    fn a_size_that_is_not_a_whole_number_of_words_steps_on_by_the_next_one() {
890        let (mut names, mut func) = object(28, 4, &[]);
891        lists(&mut func, &SYSV);
892        let text = printed(&func, &mut names);
893        assert!(text.contains("iconst.i64 32"), "twenty eight bytes step on by thirty two: {text}");
894        valid(&func, &mut names);
895    }
896
897    /// An object wanting more than a word is at the next multiple of what it wants, and one
898    /// wanting a word or less is where the pointer already is, since the area is a run of words.
899    #[test]
900    fn an_object_wanting_more_alignment_than_a_word_is_rounded_up_to_it() {
901        let (mut names, mut func) = object(32, 16, &[]);
902        lists(&mut func, &SYSV);
903        let text = printed(&func, &mut names);
904        assert!(text.contains("iconst.i64 15"), "up to the next sixteen: {text}");
905        assert!(text.contains("iconst.i64 -16"), "and down to a multiple of it: {text}");
906        assert!(text.contains(" = and "), "which is an add and a mask: {text}");
907        valid(&func, &mut names);
908
909        let (mut names, mut func) = object(24, 8, &[]);
910        lists(&mut func, &SYSV);
911        assert!(!printed(&func, &mut names).contains(" = and "), "a word wants no rounding");
912    }
913
914    /// An object that arrived in registers is in the save area, and reading it is the branch a
915    /// scalar asks with the object's own threshold: two eightbytes want two slots, so an offset
916    /// that leaves room for one is not room enough.
917    #[test]
918    fn an_object_that_arrived_in_registers_is_copied_out_of_the_save_area() {
919        let (mut names, mut func) = object(16, 8, &[gpr(0, 8), gpr(8, 8)]);
920        let before = func.blocks().count();
921        lists(&mut func, &SYSV);
922        assert_eq!(func.blocks().count(), before + 3, "one for each path and one they meet at");
923
924        let text = printed(&func, &mut names);
925        assert!(!text.contains("va_object"), "{text}");
926        assert!(text.contains("iconst.i32 32"), "forty eight less two slots: {text}");
927        assert!(text.contains("icmp ule"), "which is the threshold: {text}");
928        assert!(text.contains("alloca, size 16"), "the object lands in a buffer: {text}");
929        assert!(text.contains("iconst.i32 16"), "and the counter steps by both slots: {text}");
930        valid(&func, &mut names);
931    }
932
933    /// An object of one eightbyte of each file has to have room in both halves of the area, and
934    /// the psABI puts the whole of it in the caller's memory when either of them is out. So there
935    /// are two questions, and the second is only asked when the first said yes.
936    #[test]
937    fn an_object_in_both_files_asks_about_both_of_them() {
938        let (mut names, mut func) = object(16, 8, &[gpr(0, 8), sse(8)]);
939        lists(&mut func, &SYSV);
940        let text = printed(&func, &mut names);
941        assert_eq!(text.matches("br_if").count(), 2, "one question per file: {text}");
942        assert!(text.contains("iconst.i32 40"), "forty eight less one slot: {text}");
943        assert!(text.contains("iconst.i32 160"), "and a hundred and seventy six less one: {text}");
944        assert!(text.contains("iconst.i32 8"), "each counter steps by its own slot: {text}");
945        valid(&func, &mut names);
946    }
947
948    /// An object whose last eightbyte is a part of one still comes out of the area as a whole
949    /// register, so the buffer has room for the whole register and the bytes past the object are
950    /// never read.
951    #[test]
952    fn the_buffer_is_as_big_as_the_registers_reach() {
953        let (mut names, mut func) = object(5, 1, &[gpr(0, 5)]);
954        lists(&mut func, &SYSV);
955        let text = printed(&func, &mut names);
956        assert!(text.contains("alloca, size 8"), "five bytes travel in a whole register: {text}");
957        valid(&func, &mut names);
958    }
959
960    /// A classification this cannot read out of the area is left alone, which is what makes the
961    /// function refused by name further down rather than compiled into half a walk.
962    #[test]
963    fn a_classification_that_does_not_fit_the_area_is_left_alone() {
964        let wide = [Slot::Float { offset: 0, format: Format::Quad }];
965        let (mut names, mut func) = object(16, 16, &wide);
966        let before = printed(&func, &mut names);
967        lists(&mut func, &SYSV);
968        assert_eq!(printed(&func, &mut names), before);
969    }
970
971    /// What reads the object goes on reading the value it already read, the same way it does for a
972    /// value, and for the same reason: the instruction becomes the address rather than being
973    /// replaced by one, so nothing has to be substituted anywhere.
974    #[test]
975    fn what_reads_the_object_reads_the_same_value_it_did_before() {
976        for slots in [&[][..], &[gpr(0, 8), gpr(8, 8)][..]] {
977            let (mut names, mut func) = object(if slots.is_empty() { 24 } else { 16 }, 8, slots);
978            let entry = func.entry().expect("an entry block");
979            let inst = func.insts(entry).next().expect("the va_object is first");
980            let read = func[inst].first_result.expect("it answers an address");
981
982            lists(&mut func, &SYSV);
983            assert_eq!(func[inst].opcode, Opcode::IntToPtr, "the same instruction, lowered");
984            assert_eq!(func[inst].first_result, Some(read), "producing the same value");
985            valid(&func, &mut names);
986        }
987    }
988
989    /// Windows has a list of a different shape and an algorithm to match, and none of the rewrites
990    /// here is right for any of it. Leaving it alone is what makes the function refused by name
991    /// further down rather than compiled into a walk over an area that was never filled in.
992    #[test]
993    fn a_convention_whose_list_is_not_this_one_is_left_alone() {
994        let (mut names, mut func) = built(Opcode::VaArg, Type::int(32), 1);
995        let before = printed(&func, &mut names);
996        lists(&mut func, &WIN64);
997        assert_eq!(printed(&func, &mut names), before);
998    }
999
1000    /// A width the algorithm is not right about is left alone for the same reason, and the two
1001    /// here are the ones a program actually writes: a `long double` is on a register file this has
1002    /// nothing to say about, and an `__int128` takes two slots under an alignment rule of its own.
1003    #[test]
1004    fn a_type_that_does_not_travel_in_one_slot_is_left_alone() {
1005        for ty in [Type::float(rucc_ir::Float::F80), Type::int(128)] {
1006            let (mut names, mut func) = built(Opcode::VaArg, ty, 1);
1007            let before = printed(&func, &mut names);
1008            lists(&mut func, &SYSV);
1009            assert_eq!(printed(&func, &mut names), before, "{ty:?}");
1010        }
1011    }
1012
1013    /// Nothing else is touched, which matters because this runs over every function whether or not
1014    /// one reads a variable argument.
1015    #[test]
1016    fn a_function_with_no_list_in_it_is_left_exactly_as_it_was() {
1017        let mut names = Interner::new();
1018        let int = Type::int(32);
1019        let mut func =
1020            Func::new(names.intern("f"), Signature::new().with_params(&[int]).with_returns(&[int]));
1021        let entry = func.create_block();
1022        let x = func.append_param(entry, int);
1023        Builder::new(&mut func, entry).ret(&[x]);
1024
1025        let before = printed(&func, &mut names);
1026        lists(&mut func, &SYSV);
1027        assert_eq!(printed(&func, &mut names), before);
1028    }
1029}