rucc_codegen/frame.rs
1//! The frame: what a function's stack looks like while it runs.
2//!
3//! Design: `spec/10-backend.md` section 10.7.
4//!
5//! This is worked out after register allocation and not before, because the largest area in most
6//! frames is the spill slots and nothing knows how many of those there are until the allocator has
7//! finished running out of registers. It is worked out from the rewritten function rather than
8//! from the assignment alone, because the rewrite is what decides which scratch registers a reload
9//! uses, and a scratch register a call preserves is one the prologue has to save.
10//!
11//! # What is in one
12//!
13//! Section 10.7 lists the areas and this is the order they are in, from the stack pointer upward,
14//! which is the order of increasing address on every machine here.
15//!
16//! ```text
17//! incoming stack arguments the caller wrote these and they are above everything
18//! return address the call instruction pushed it, on a machine that does
19//! saved frame pointer when the function keeps one
20//! saved general purpose regs pushed, one word each
21//! saved vector registers stored rather than pushed, since no machine here pushes one
22//! stack protector canary when the function has one, above everything a local reaches
23//! locals what an alloca becomes, widest alignment first
24//! spill slots one for every value the allocator ran out of registers for
25//! outgoing argument area at the bottom, because a call reads its stack arguments from
26//! the stack pointer upward
27//! ```
28//!
29//! Every offset reported here is from the stack pointer as it stands in the body of the function,
30//! which is after the prologue and before the epilogue. That is the one base register always
31//! available. A frame pointer is a second way to reach the same bytes and the prologue is what
32//! knows the distance between the two, so nothing here reports an offset from it. There are two
33//! exceptions and [`Frame::incoming`] is one of them, because the bytes it reports are the caller's
34//! rather than this function's, which is the one part of the picture a realigned frame loses sight
35//! of. It says which register it counted from. The other is a frame that grows, which is the next
36//! section and where the stack pointer stops being a base register at all.
37//!
38//! # Where the alignment comes from
39//!
40//! A call has to leave the stack pointer on a multiple of the convention's alignment, so a
41//! function's own frame is what puts it back: the call that reached this function pushed a return
42//! address and left the stack pointer one word off, and the prologue's pushes either fix that or
43//! make it worse depending on how many there are. The size the prologue subtracts is therefore not
44//! the size of the areas. It is whatever brings the stack pointer back to a multiple of the
45//! alignment given the pushes in front of it, which is the arithmetic in [`Frame::of`].
46//!
47//! # The red zone
48//!
49//! A leaf function may use the bytes below the stack pointer without moving it, which is what
50//! `red_zone` on a convention says and what makes a small leaf function's prologue and epilogue
51//! empty. Then the offsets are negative, which is why they are signed, and the areas are in the
52//! same order as ever, below the line rather than above it. Anything that calls, or is too big for
53//! the zone, or wants more alignment than the stack pointer has for free, moves the stack pointer.
54//!
55//! # Realignment
56//!
57//! A local wanting more alignment than a call leaves the stack pointer with cannot be placed by
58//! arithmetic, because nothing in the frame knows what the caller's stack pointer was a multiple
59//! of. The prologue has to force it, and forcing it destroys the only record of where the caller's
60//! stack was, so a realigned frame needs a frame pointer and the distance from the body's stack
61//! pointer to the incoming arguments stops being a constant. [`Frame::realign`] is where that is
62//! reported and it is why [`Frame::incoming`] answers from the frame pointer in such a frame and
63//! from the stack pointer in every other one.
64//!
65//! # Growing
66//!
67//! A variable length array is bytes the function takes off the stack pointer where the declaration
68//! stands, so in a function that has one the stack pointer is in a different place in the middle of
69//! the body than it was at the top of it. Every other offset in the frame was a distance from the
70//! stack pointer, and a distance from a register that moves is not a distance, so in a frame like
71//! this they are all distances from the frame pointer instead. That is what [`Layout::grows`] says
72//! and [`Frame::grows`] reports, and it is why such a frame keeps a frame pointer whatever the
73//! flags asked for, the same way a realigned one does and for a version of the same reason.
74//!
75//! Three other things follow from it. The red zone is gone, because the zone is the bytes below the
76//! stack pointer and the first thing an array like this does is move the stack pointer down over
77//! them. The frame asks for the convention's alignment even when nothing in it wanted that much, so
78//! that the stack pointer is on a multiple of it when the body starts and stays on one as each
79//! array rounds its own size up. And the bytes the array hands out start above the outgoing
80//! argument area rather than at the stack pointer, because that area stays at the bottom of the
81//! frame wherever the bottom has moved to, which is what [`Frame::below`] is for.
82//!
83//! An array asking for more alignment than that is not a realignment of the frame, and nothing
84//! here has to know about it. [`crate::expand::rounds`] asks for the alignment in extra bytes and
85//! hands out an address inside them, so the stack pointer moves by a multiple of the convention's
86//! alignment as it always did and the frame is an ordinary growing one.
87//!
88//! Realigning and growing together is the one combination that is not here. After the prologue has
89//! forced an alignment the distance from the frame pointer to the body's stack pointer is already
90//! not a constant, so there is no register left for the rest of the frame to be counted from, and
91//! what fixes that is a second pointer held for the purpose. The lowering refuses that pair rather
92//! than this guessing at it.
93//!
94//! # Late
95//!
96//! Where in the prologue the frame pointer is established is the platform's answer rather than this
97//! file's, and [`rucc_target::CallRegs::late_frame_pointer`] is where the reason for it is written
98//! down. On Windows it goes up after the frame has been taken rather than before, because the
99//! unwind record there cannot describe the other order, and that moves it: it holds a copy of the
100//! body's stack pointer rather than the address of the caller's copy of itself.
101//!
102//! Which is the easier of the two to lay out rather than the harder. Every offset here is from the
103//! body's stack pointer already, so in a frame like this the frame pointer holds exactly what those
104//! offsets are counted from, and a frame that grows needs no adjustment at all where the other
105//! order needs the whole frame and every push taken off. [`Frame::late`] is what says which it is.
106//!
107//! A realigned frame takes the late order too, the way clang lays one out for Windows. The early
108//! order forces the alignment after the pushes and before the frame, which leaves the pushes at a
109//! distance from the body's stack pointer that is not a constant, and the record has nothing to
110//! count them from. So the prologue does everything the record describes first, the pushes, the
111//! frame, the pointer and the vector saves, and only then rounds the stack pointer down. The record
112//! counts from the frame pointer and never sees the rounding. The body counts from the rounded
113//! stack pointer, and the epilogue puts the stack pointer back from the frame pointer before it
114//! does anything else. The vector saves go at the top of such a frame rather than the bottom,
115//! since the body's view of the frame moves down by up to the alignment and must not reach them.
116//! This was `tamnd/rucc#1422`.
117
118use rucc_mir::{Constraint, Func};
119use rucc_regalloc::Allocation;
120use rucc_regalloc::assign::Place;
121use rucc_target::{CallRegs, PhysReg, RegClass, RegFile};
122
123use crate::slots::{Cell, Slots};
124
125/// One register the prologue puts away in the frame, and where in the frame it goes.
126///
127/// A pushed register does not need one of these, because where it goes is wherever the stack
128/// pointer had reached, and the epilogue pops them back in the opposite order without having to
129/// know. A register that is stored rather than pushed does need one.
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub struct Save {
132 /// The register.
133 pub reg: PhysReg,
134 /// Where it goes, from the stack pointer in the body of the function.
135 pub at: i32,
136}
137
138/// Where the arguments the caller passed on the stack are, and which register reaches them.
139///
140/// Two fields rather than one number because a realigned frame has no constant distance from its
141/// stack pointer to the caller's. Forcing the alignment threw that distance away, and the frame
142/// pointer is what still reaches the caller's stack afterwards, which is why a realigned frame is
143/// made to keep one. So there is always an answer, and which register it is counted from is part of
144/// it rather than something the reader is left to work out.
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub struct Incoming {
147 /// How far above that register the first argument passed on the stack is.
148 pub at: i32,
149 /// Whether the register is the frame pointer rather than the stack pointer.
150 pub through_frame_pointer: bool,
151}
152
153impl Incoming {
154 /// That far above the stack pointer as it stands in the body of the function, which is where
155 /// every other offset in a frame is from.
156 #[must_use]
157 pub fn from_stack(at: i32) -> Self {
158 Self { at, through_frame_pointer: false }
159 }
160
161 /// That far above the frame pointer, which is the only way a realigned frame reaches back.
162 #[must_use]
163 pub fn from_frame(at: i32) -> Self {
164 Self { at, through_frame_pointer: true }
165 }
166}
167
168/// A piece of memory the function needs for its own use, which is what an `alloca` becomes.
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub struct Local {
171 /// How many bytes of it there are.
172 pub size: u32,
173 /// What its address has to be a multiple of.
174 pub align: u32,
175}
176
177/// Everything about a function's frame that does not come out of its allocation.
178#[derive(Debug, Clone, Copy)]
179pub struct Layout<'a> {
180 /// Where the convention this function is compiled for puts things.
181 pub conv: &'a CallRegs,
182 /// The registers the target has, which is what says how wide a spill slot of a class is.
183 pub file: RegFile,
184 /// The memory the function asked for itself, in the order it wants it reported back.
185 pub locals: &'a [Local],
186 /// How many bytes the widest call in the function needs for arguments it passes on the stack.
187 pub outgoing: u32,
188 /// Whether the function calls nothing, which is what the alignment and the red zone turn on.
189 pub leaf: bool,
190 /// Whether the function keeps a frame pointer, which `-fno-omit-frame-pointer` asks for and
191 /// which a realigned or a dynamically grown frame requires whatever the flags say.
192 pub frame_pointer: bool,
193 /// Whether the function moves the stack pointer while it runs, which is what a variable length
194 /// array does and what the rest of the frame then has to be reached around.
195 ///
196 /// See `Growing` in the module documentation. A frame like this keeps a frame pointer, takes
197 /// its bytes rather than living in the red zone, and reports every offset in its body from the
198 /// frame pointer, because the stack pointer stops being somewhere a constant reaches from.
199 pub grows: bool,
200 /// Whether the red zone may be used at all, which `-mno-red-zone` and every kernel turns off.
201 pub red_zone: bool,
202 /// Whether the frame holds a stack protector's canary, which `-fstack-protector` and the
203 /// function's own attribute decide between them.
204 ///
205 /// A protected frame is never a leaf, whatever the function called, because the check at the
206 /// end of it calls when it fails. The caller sets `leaf` accordingly rather than this working
207 /// it out, so that there is one place a frame learns whether it owes an aligned stack pointer.
208 pub protect: bool,
209 /// Whether the function is written without a prologue or an epilogue, which
210 /// `__attribute__((naked))` asks for.
211 ///
212 /// A frame like this is empty and nothing is written around the body. No register is put away,
213 /// because the program said it would do that itself and the first thing one of these usually
214 /// does is read something the saving would have moved. No bytes are taken, because taking them
215 /// is the prologue's job and there is no prologue, which is why a naked function that wants any
216 /// is refused rather than given a frame nothing sets up. See [`Frame::of`].
217 pub naked: bool,
218 /// Whether the prologue puts the general purpose registers it saves on the stack two at a time,
219 /// which is what a machine with a pair instruction does and what [`crate::pipeline`] sets from
220 /// the target's `FrameInsts::pair`.
221 ///
222 /// On AArch64 a push moves the stack pointer sixteen bytes to keep it aligned, so a register
223 /// pushed alone wastes eight of them. Two in one `stp` fill the sixteen, which is how every
224 /// compiler for the machine saves `x19` to `x28`, and a count that is odd leaves the last one
225 /// alone.
226 pub pairs: bool,
227 /// Which locals and spill slots share their bytes with which, or `None` for a frame where
228 /// every one of them gets a run of its own.
229 ///
230 /// Worked out in [`crate::slots`], because what may share is a question about liveness and this
231 /// file is about arithmetic. `None` is the layout there was before that pass existed and is
232 /// what `-fstack-reuse=none` asks for.
233 pub share: Option<&'a Slots>,
234}
235
236impl<'a> Layout<'a> {
237 /// A layout for a function with nothing in it but what its allocation says: a leaf with no
238 /// locals and no calls, which is what every function is until the pieces that produce those
239 /// exist.
240 #[must_use]
241 pub fn new(conv: &'a CallRegs, file: RegFile) -> Self {
242 Self {
243 conv,
244 file,
245 locals: &[],
246 outgoing: 0,
247 leaf: true,
248 frame_pointer: false,
249 grows: false,
250 red_zone: true,
251 protect: false,
252 naked: false,
253 pairs: false,
254 share: None,
255 }
256 }
257}
258
259/// What a function's stack looks like while it runs.
260#[derive(Debug, Clone, PartialEq, Eq)]
261pub struct Frame {
262 saved_int: Vec<PhysReg>,
263 saved_sse: Vec<Save>,
264 slots: Vec<i32>,
265 locals: Vec<i32>,
266 canary: Option<i32>,
267 outgoing: u32,
268 below: u32,
269 size: u32,
270 realign: Option<u32>,
271 incoming: Incoming,
272 frame_pointer: bool,
273 late: bool,
274 grows: bool,
275 naked: bool,
276 pairs: bool,
277 usage: u32,
278}
279
280impl Frame {
281 /// Works out the frame of a function the allocator has finished with.
282 ///
283 /// # Panics
284 ///
285 /// Panics on a frame of two gigabytes or more, which is a stack no machine here gives a
286 /// thread, and on a local whose alignment is not a power of two.
287 #[must_use]
288 pub fn of(func: &Func, allocation: &Allocation, layout: &Layout<'_>) -> Self {
289 let conv = layout.conv;
290 let word = conv.word;
291 // How far one push moves the stack pointer, which is the word on x86-64 and the whole
292 // alignment on AArch64. A machine where it is the whole alignment is one whose stack
293 // pointer is never allowed off it, and so a leaf there owes itself an aligned frame even
294 // though it owes nobody else one.
295 let push = conv.push;
296 let aligned = push % conv.stack_align == 0;
297 let (saved_int, vectors) = saved(func, allocation, layout);
298
299 // The vector registers are saved in the frame rather than pushed, because no machine here
300 // has an instruction that pushes one. Each takes the part of it a call keeps, which on
301 // AArch64 is the bottom eight bytes, and the whole register everywhere else.
302 let vector = conv.sse_kept.map_or_else(|| width(layout, conv.sse_class), u32::from);
303 let mut top = 0;
304 let mut align = word;
305 let mut saved_sse = Vec::with_capacity(vectors.len());
306 if !vectors.is_empty() {
307 align = align.max(vector);
308 }
309
310 // A frame that grows hands out the bytes above the outgoing area, and what makes that
311 // address usable for anything is the stack pointer being on a multiple of the convention's
312 // alignment when the body starts. Asking for that much here is what buys it: the area below
313 // is padded to `align` and the frame is rounded to land the stack pointer back on it.
314 if layout.grows {
315 align = align.max(conv.stack_align);
316 }
317
318 // One list rather than two, because a local and a spill slot that are never both wanted can
319 // be the same bytes and neither of them can share with something on the other list if the
320 // two lists are placed one after the other. See [`crate::slots`]. A layout that was handed
321 // no plan gets the one where nothing shares anything, which is the frame there was before
322 // that pass existed.
323 let apart;
324 let plan = match layout.share {
325 Some(plan) => plan,
326 None => {
327 apart = Slots::apart(layout.locals, &widths(layout, allocation));
328 &apart
329 }
330 };
331 // Normally they go at the bottom. In a frame that realigns with the pointer established
332 // late they go at the top instead, because the prologue stores them before it forces the
333 // alignment and the body counts from the stack pointer after it, which is anywhere up to
334 // the alignment lower. With the saves above everything the body reaches, the two never
335 // meet whichever way the rounding went. See `Late` above.
336 let wanted = plan.cells().iter().map(|cell| cell.align).max().unwrap_or(0);
337 let last = conv.late_frame_pointer && align.max(wanted) > conv.stack_align;
338 if !last {
339 for ® in &vectors {
340 saved_sse.push(Save { reg, at: offset(top) });
341 top += vector;
342 }
343 }
344
345 let mut cells = Vec::with_capacity(plan.cells().len());
346 let mut order: Vec<usize> = (0..plan.cells().len()).collect();
347 // Widest alignment first, so that placing each one straight after the last never leaves a
348 // hole bigger than the alignment the next one asked for. Within one alignment, the cells
349 // that are a whole number of it go before the ones that are not, because a cell that ends
350 // part way through leaves a hole in front of the next cell that asked for the same
351 // alignment and none at all in front of a narrower one. A cell shared by a wide thing and
352 // a strict one is exactly how a size that is not a multiple of its own alignment arises,
353 // so without this a frame could come out larger for sharing than it was for not.
354 order.sort_by_key(|&cell| {
355 let Cell { size, align } = plan.cells()[cell];
356 (std::cmp::Reverse(align), size % align != 0)
357 });
358 cells.resize(plan.cells().len(), 0);
359 for cell in order {
360 let Cell { size, align: want } = plan.cells()[cell];
361 assert!(
362 want.is_power_of_two(),
363 "a local aligned to something that is not a power of 2"
364 );
365 align = align.max(want);
366 top = top.next_multiple_of(want);
367 cells[cell] = offset(top);
368 top += size;
369 }
370
371 // Read back out to the two lists the rest of the compiler asks its questions in. A cell
372 // several things share gives all of them the same offset, which is the whole point of it.
373 let placed = |cell: Option<usize>| cells[cell.expect("a plan covering every slot")];
374 let mut locals: Vec<i32> =
375 (0..layout.locals.len()).map(|local| placed(plan.local(local))).collect();
376 let mut slots: Vec<i32> = (0..allocation.assignment.slots().len())
377 .map(|slot| placed(plan.slot(u32::try_from(slot).expect("a frame"))))
378 .collect();
379
380 // Above everything the function can reach through a local, which is the whole point of it.
381 // A write that runs off the end of an array in this frame passes the canary before it
382 // reaches the saved registers and the return address, so the check at the end of the
383 // function sees a word that changed rather than a return that has already been taken.
384 let mut canary = None;
385 if layout.protect {
386 top = top.next_multiple_of(word);
387 canary = Some(offset(top));
388 top += word;
389 }
390 if last {
391 top = top.next_multiple_of(vector);
392 for ® in &vectors {
393 saved_sse.push(Save { reg, at: offset(top) });
394 top += vector;
395 }
396 }
397
398 // A call reads its stack arguments from the stack pointer upward, so the outgoing area is
399 // at the bottom of the frame and its size is what shifts everything else.
400 let outgoing = if layout.leaf { 0 } else { layout.outgoing.max(conv.shadow) };
401 // Everything above it was placed as though it were not there, so moving it up by the size
402 // of the area is what would break its alignment. The area is padded to the widest
403 // alignment anything above it asked for, which costs at most that many bytes once and
404 // costs nothing at all in the usual frame, where the area is a multiple of it already.
405 // What the padding must not do is move the area itself: the callee reads its arguments
406 // from the stack pointer, so the bottom of the area is the stack pointer whatever is
407 // above it.
408 let shifted = outgoing.next_multiple_of(align);
409 let body = (top + shifted).next_multiple_of(word);
410
411 let realign = (align > conv.stack_align).then_some(align);
412 // Refused by [`crate::pipeline`] before anything gets here, because the two of them together
413 // want one register twice. See `Growing` above.
414 assert!(
415 !(layout.grows && realign.is_some()),
416 "a frame that grows and forces its alignment needs a second base register"
417 );
418 // Two frames keep one whatever the flags asked for, and each of them for its own version of
419 // the same reason: the prologue is about to leave the stack pointer somewhere no constant
420 // reaches the rest of the frame from, and the frame pointer is the register that still
421 // does. Forcing an alignment is one of the two and growing while the function runs is the
422 // other.
423 //
424 // A function that calls something on a machine whose call leaves the return address in a
425 // register is a third. The call writes over that register, so the prologue has to put it
426 // away, and it goes with the frame pointer as the one frame record the machine's unwinders
427 // and `__builtin_frame_address` expect to find.
428 let frame_pointer = layout.frame_pointer
429 || realign.is_some()
430 || layout.grows
431 || (!layout.leaf && conv.link.is_some());
432 // Where in the prologue the pointer is established, which is the platform's answer. See
433 // `Late` above.
434 let late = conv.late_frame_pointer;
435
436 // Where the stack pointer sits once the prologue has finished pushing: one return address
437 // short of aligned when the function starts, and one push further off for every push. The
438 // frame pointer is a push like any other here, which is why this is asked after the frames
439 // that keep one without being asked to have said so.
440 let pushed = u32::from(frame_pointer) + groups(saved_int.len(), layout.pairs);
441 let entry = wrap(conv.stack_align, conv.return_address);
442 let after = (entry + wrap(conv.stack_align, push * pushed)) % conv.stack_align;
443
444 // A frame that grows cannot be one of the free ones. The red zone is the bytes below the
445 // stack pointer, and the first thing a variable length array does is move the stack pointer
446 // down over them, so what was in the zone would be handed out twice.
447 let free = layout.leaf
448 && layout.red_zone
449 && realign.is_none()
450 && !layout.grows
451 && align <= word
452 && body <= conv.red_zone;
453 let size = match realign {
454 _ if free => 0,
455 // Once the prologue has forced the alignment, keeping the frame a multiple of it keeps
456 // everything in the frame aligned too. A late pointer forces it after the frame is
457 // taken, so the frame itself only has to land where any other frame does.
458 Some(to) if !late => body.next_multiple_of(to),
459 // A leaf owes nobody an aligned stack pointer, so it takes exactly what it uses.
460 None if layout.leaf && align <= word && !aligned => body,
461 // The smallest frame that lands the stack pointer back on a multiple of the alignment
462 // given where the pushes left it.
463 _ => body + (after + conv.stack_align - body % conv.stack_align) % conv.stack_align,
464 };
465
466 // With the stack pointer left where it was, the areas are the same areas in the same order
467 // and they are below it rather than above it.
468 //
469 // A frame that grows is counted from the frame pointer instead, which is the same areas in
470 // the same order with one more constant taken off: the prologue pushed the registers and
471 // then took the frame, so the body's stack pointer is that far below where the frame
472 // pointer was set. That distance is what a variable length array destroys and the frame
473 // pointer is what is left, which is why a growing frame keeps one.
474 //
475 // Unless the pointer is established late, where there is nothing to take off: the prologue
476 // points it at the stack pointer once the frame is whole, so the two hold the same address
477 // when the body starts and every distance from one is a distance from the other.
478 let mut shift = if free { -offset(body) } else { offset(shifted) };
479 if layout.grows && !late {
480 shift -= offset(size + push * groups(saved_int.len(), layout.pairs));
481 }
482 for at in slots
483 .iter_mut()
484 .chain(locals.iter_mut())
485 .chain(canary.iter_mut())
486 .chain(saved_sse.iter_mut().map(|save| &mut save.at))
487 {
488 *at += shift;
489 }
490
491 // What `-fstack-usage` reports, worked out here because this is the one place every term
492 // of it is in hand. See [`Frame::usage`] for what the number is. Every push comes before
493 // the prologue forces an alignment, so the pushes are what gets rounded up.
494 let pushes = conv.return_address + push * pushed;
495 let usage = realign.map_or(pushes, |to| pushes.next_multiple_of(to)) + size;
496
497 Self {
498 saved_int,
499 saved_sse,
500 slots,
501 locals,
502 canary,
503 outgoing,
504 below: shifted,
505 size,
506 realign,
507 incoming: match () {
508 // A pointer established late holds what the body's stack pointer holds, so the
509 // caller's stack is the whole frame and every push above it, which is the same
510 // number a frame with no pointer counts from the stack pointer.
511 () if late && (layout.grows || realign.is_some()) => {
512 Incoming::from_frame(offset(size + push * pushed + conv.return_address))
513 }
514 // The prologue saves the frame pointer before it does anything else and points it
515 // at where it saved it, so the caller's stack is one push for that and one return
516 // address above it, whatever the prologue did to the stack pointer afterwards.
517 () if realign.is_some() || layout.grows => {
518 Incoming::from_frame(offset(push + conv.return_address))
519 }
520 () => Incoming::from_stack(offset(size + push * pushed + conv.return_address)),
521 },
522 frame_pointer,
523 late,
524 grows: layout.grows,
525 naked: layout.naked,
526 pairs: layout.pairs,
527 usage,
528 }
529 }
530
531 /// The general purpose registers the prologue pushes, in the order it pushes them.
532 ///
533 /// The frame pointer is not among them even when the convention calls it a saved register,
534 /// because a function that keeps one saves it as part of setting it up.
535 #[must_use]
536 pub fn saved_int(&self) -> &[PhysReg] {
537 &self.saved_int
538 }
539
540 /// The same registers as the pushes that put them on the stack, one or two to a push, in the
541 /// order the prologue makes them. See [`Layout::pairs`].
542 pub fn pushed_int(&self) -> std::slice::Chunks<'_, PhysReg> {
543 self.saved_int.chunks(if self.pairs { 2 } else { 1 })
544 }
545
546 /// The vector registers the prologue stores into the frame, and where each of them goes.
547 #[must_use]
548 pub fn saved_sse(&self) -> &[Save] {
549 &self.saved_sse
550 }
551
552 /// Where a spill slot is, from the stack pointer in the body of the function.
553 #[must_use]
554 pub fn slot(&self, slot: u32) -> Option<i32> {
555 self.slots.get(usize::try_from(slot).ok()?).copied()
556 }
557
558 /// Where a local is, from the stack pointer in the body of the function.
559 #[must_use]
560 pub fn local(&self, local: usize) -> Option<i32> {
561 self.locals.get(local).copied()
562 }
563
564 /// Where a local is, from the call frame address, which is what a debugger counts from.
565 ///
566 /// The call frame address is the stack pointer the caller held when it made the call, and
567 /// [`Frame::incoming`] is already the distance up to it, since the first argument passed on the
568 /// stack sits there. So the answer is one subtraction, and it is a negative number, because the
569 /// frame is below the address the call was made from.
570 ///
571 /// `None` in a frame whose alignment the prologue had to force, where there is no answer to
572 /// give. Rounding the stack pointer down throws away however far it was from where the caller
573 /// left it, so the distance from the body's stack pointer up to the call frame address is not a
574 /// constant in such a function, and the two numbers subtracted here are counted from different
575 /// registers on top of that. What the locals of such a function want is a location counted from
576 /// the frame pointer, which is a different expression from the one a frame base gives.
577 ///
578 /// `None` as well for a local this frame never placed.
579 #[must_use]
580 pub fn from_frame_base(&self, local: usize) -> Option<i32> {
581 if self.realign.is_some() {
582 return None;
583 }
584 Some(self.local(local)? - self.incoming.at)
585 }
586
587 /// Where a spill slot is, from the call frame address, which is what a debugger counts from.
588 ///
589 /// The same subtraction [`Frame::from_frame_base`] makes and `None` in the same function, for
590 /// the same reasons. It is the other half of the same question: a local the program named is
591 /// either in the part of the frame the front end asked for or in the part the allocator ran
592 /// out of registers into, and a debugger wants both counted from the same place.
593 #[must_use]
594 pub fn slot_from_frame_base(&self, slot: u32) -> Option<i32> {
595 if self.realign.is_some() {
596 return None;
597 }
598 Some(self.slot(slot)? - self.incoming.at)
599 }
600
601 /// Where the stack protector's canary is, from the stack pointer in the body of the function,
602 /// or `None` in a frame that has none.
603 #[must_use]
604 pub fn canary(&self) -> Option<i32> {
605 self.canary
606 }
607
608 /// How many bytes the prologue takes off the stack pointer, which is nothing for a function
609 /// small enough and quiet enough to live in the red zone.
610 #[must_use]
611 pub fn size(&self) -> u32 {
612 self.size
613 }
614
615 /// How many bytes at the bottom of the frame belong to the arguments of calls this function
616 /// makes, which is where the shadow space goes on Windows.
617 #[must_use]
618 pub fn outgoing(&self) -> u32 {
619 self.outgoing
620 }
621
622 /// How many bytes at the bottom of the frame nothing else may be placed in, which is that area
623 /// padded to the alignment everything above it asked for.
624 ///
625 /// What a variable length array has to step over. It takes its bytes off the stack pointer,
626 /// which leaves them at the bottom of the frame where the next call is going to write its
627 /// arguments, so the address it hands out is this far above the stack pointer rather than the
628 /// stack pointer itself.
629 #[must_use]
630 pub fn below(&self) -> u32 {
631 self.below
632 }
633
634 /// Whether the function moves the stack pointer while it runs.
635 ///
636 /// Every offset in the body of such a frame is from the frame pointer rather than from the
637 /// stack pointer, because a variable length array leaves the stack pointer somewhere no
638 /// constant reaches the rest of the frame from. See `Growing` in the module documentation.
639 #[must_use]
640 pub fn grows(&self) -> bool {
641 self.grows
642 }
643
644 /// What the prologue has to force the stack pointer to be a multiple of, when a local wants
645 /// more alignment than a call leaves it with.
646 #[must_use]
647 pub fn realign(&self) -> Option<u32> {
648 self.realign
649 }
650
651 /// Where the first argument the caller passed on the stack is, and which register reaches it.
652 ///
653 /// The only offset here that is not always from the stack pointer. A realigned frame counts
654 /// from the frame pointer instead, because forcing the alignment threw away however far the
655 /// caller's stack pointer was from where the prologue wanted it, and the frame pointer is what
656 /// reaches the caller's stack afterwards.
657 #[must_use]
658 pub fn incoming(&self) -> Incoming {
659 self.incoming
660 }
661
662 /// Whether the function keeps a frame pointer.
663 #[must_use]
664 pub fn frame_pointer(&self) -> bool {
665 self.frame_pointer
666 }
667
668 /// Whether nothing at all is to be written around the body, which `__attribute__((naked))`
669 /// asks for. See [`Layout::naked`].
670 ///
671 /// Such a frame is empty, since [`crate::pipeline`] refuses a naked function that wanted any
672 /// bytes rather than handing it a frame no prologue sets up. What is left for this to say is
673 /// that the prologue and the epilogue are not to be written, and the epilogue is the point:
674 /// the `ret` at the end of a function is written there, and a naked function ends where its
675 /// own text ends.
676 #[must_use]
677 pub fn naked(&self) -> bool {
678 self.naked
679 }
680
681 /// Whether the prologue points the frame pointer at the frame after taking it rather than
682 /// before, which is [`rucc_target::CallRegs::late_frame_pointer`]. See `Late` in the module
683 /// documentation.
684 #[must_use]
685 pub fn late(&self) -> bool {
686 self.late
687 }
688
689 /// How many bytes of stack the function uses, not counting what a variable length array or an
690 /// `alloca` takes while it runs, which is the number `-fstack-usage` reports.
691 ///
692 /// Counted the way gcc counts its own frames, so that the two compilers' reports can be
693 /// compared function by function: the distance from the stack pointer the caller held just
694 /// before its call instruction down to where the prologue leaves the stack pointer. That is
695 /// the return address when the call pushes one, every register the prologue pushes, the frame
696 /// pointer among them, and the size the prologue subtracts, which already holds the saved
697 /// vector registers, the locals, the spill slots, the canary and the outgoing argument area.
698 /// Bytes a leaf keeps in the red zone are not counted, and gcc does not count them either.
699 ///
700 /// A frame whose alignment the prologue forces has the pushes rounded up to that alignment
701 /// before the rest is added, which is gcc's rule for the same frame. It is exact when the
702 /// caller's stack pointer happened to be aligned that far already, and otherwise it is off by
703 /// less than the alignment in one direction or the other, since how much the rounding throws
704 /// away depends on where the caller's stack pointer was.
705 ///
706 /// The two numbers agree on what they count and not always on the bytes: a function whose
707 /// locals rucc keeps in fewer or more slots than gcc does comes out smaller or larger by that
708 /// much. A frame that [`Frame::grows`] is reported as `dynamic` beside this, the same as gcc.
709 #[must_use]
710 pub fn usage(&self) -> u32 {
711 self.usage
712 }
713}
714
715/// The registers a call preserves that this function writes anyway, so the prologue has to put
716/// them back.
717///
718/// The rewritten function is what is read here rather than the assignment, because a spilled value
719/// is reloaded into a scratch register that no assignment mentions, and a scratch register the
720/// convention preserves is one this has to find.
721///
722/// Nothing at all in a naked function, which is the whole of what the attribute asks for. Such a
723/// function names `%rbx` and `%rbp` in its own text and means the registers rather than places to
724/// keep something, and putting them away in front of it would be the compiler answering a question
725/// the program did not ask. See [`Layout::naked`].
726fn saved(
727 func: &Func,
728 allocation: &Allocation,
729 layout: &Layout<'_>,
730) -> (Vec<PhysReg>, Vec<PhysReg>) {
731 if layout.naked {
732 return (Vec::new(), Vec::new());
733 }
734 let mut used: Vec<(RegClass, PhysReg)> = Vec::new();
735 let mut note = |class: RegClass, at: PhysReg| {
736 if !used.contains(&(class, at)) {
737 used.push((class, at));
738 }
739 };
740 for block in func.blocks() {
741 for inst in func.insts(block) {
742 for operand in &func[func[inst].operands] {
743 // Not the top of a register a call writes, which is nothing the caller counts on
744 // and nothing this function owes anybody. See [`Constraint::Above`].
745 if matches!(operand.constraint, Constraint::Above(_)) {
746 continue;
747 }
748 if let Some(at) = operand.reg.phys() {
749 note(operand.class, at);
750 }
751 }
752 }
753 }
754 for edit in &allocation.edits {
755 for place in [edit.mov.from, edit.mov.to] {
756 if let Place::Reg(at) = place {
757 note(edit.class, at);
758 }
759 }
760 }
761
762 let conv = layout.conv;
763 let wanted = |class: RegClass, at: PhysReg| used.contains(&(class, at));
764 // In the convention's order rather than the order the function happened to reach for them, so
765 // that two functions saving the same registers get the same prologue.
766 let saved_int = conv
767 .int_saved
768 .iter()
769 .copied()
770 .filter(|&at| wanted(conv.int_class, at))
771 .filter(|&at| !(layout.frame_pointer && at == conv.frame_pointer))
772 .collect();
773 let saved_sse =
774 conv.sse_saved.iter().copied().filter(|&at| wanted(conv.sse_class, at)).collect();
775 (saved_int, saved_sse)
776}
777
778/// How many bytes a value of a class takes on the stack.
779///
780/// A power of two at least a word wide, because a slot is addressed and an address that is not a
781/// multiple of the size of the thing at it is a fault on some machines and slow on the rest. An
782/// eighty bit `long double` takes sixteen bytes for that reason, which is what every compiler
783/// does with one.
784fn width(layout: &Layout<'_>, class: RegClass) -> u32 {
785 let bits = layout.file.class(class).map_or(0, |info| info.bits);
786 bits.div_ceil(8).max(layout.conv.word).next_power_of_two()
787}
788
789/// How many bytes each of an allocation's spill slots takes on the stack.
790///
791/// The same question the width of one register class is, asked of a whole allocation at once, and
792/// public because [`crate::slots`] needs it to say how big a cell holding a spilled value has to
793/// be, which it has to know before there is a frame to ask.
794#[must_use]
795pub fn widths(layout: &Layout<'_>, allocation: &Allocation) -> Vec<u32> {
796 allocation.assignment.slots().iter().map(|&class| width(layout, class)).collect()
797}
798
799/// How many pushes put that many general purpose registers on the stack.
800fn groups(saved: usize, pairs: bool) -> u32 {
801 let pushes = if pairs { saved.div_ceil(2) } else { saved };
802 u32::try_from(pushes).expect("a frame")
803}
804
805/// How far past a multiple of an alignment a number is, counted the other way: what has to be
806/// added to it to reach the next one.
807fn wrap(align: u32, value: u32) -> u32 {
808 (align - value % align) % align
809}
810
811/// A distance in a frame, as the signed number every offset out of here is.
812fn offset(bytes: u32) -> i32 {
813 i32::try_from(bytes).expect("a frame under two gigabytes")
814}
815
816#[cfg(test)]
817mod tests {
818 use rucc_base::Interner;
819 use rucc_mir::{Opcode, Operand, Reg};
820 use rucc_regalloc::assign::Env;
821 use rucc_target::x86_64::{GPR, RBP, REGS, SYSV, WIN64, XMM};
822
823 use super::*;
824
825 /// An environment offering that many of the convention's registers, with everything after
826 /// them held back as scratch.
827 fn env(conv: &CallRegs, count: usize) -> Env {
828 Env::new().with(GPR, &conv.int_order[..count], &conv.int_order[count..])
829 }
830
831 /// A function of that many values, every one of them written before any is read, allocated
832 /// with that many registers to hand out.
833 ///
834 /// Every value is live at the first read, so a count below the number of values is what puts
835 /// the function under enough pressure to spill, and each read wants one value so a reload
836 /// never needs more than one scratch register.
837 fn pressure(conv: &CallRegs, values: usize, count: usize) -> (Func, Allocation) {
838 let mut names = Interner::new();
839 let mut func = Func::new(names.intern("f"));
840 let opcode = Opcode::new(names.intern("x64.nop"));
841 let block = func.create_block();
842 let regs: Vec<Reg> = (0..values).map(|_| func.new_vreg(GPR)).collect();
843 for ® in ®s {
844 func.build(block, opcode).def(reg, GPR).finish();
845 }
846 for ® in ®s {
847 func.build(block, opcode).uses(reg, GPR).finish();
848 }
849 let allocation = rucc_regalloc::run(&mut func, &env(conv, count), "test", true);
850 (func, allocation)
851 }
852
853 /// What a list of registers is called, which is what an assertion reads.
854 fn named(regs: &[PhysReg]) -> Vec<&'static str> {
855 regs.iter().map(|®| REGS.name(GPR, reg).expect("a register")).collect()
856 }
857
858 #[test]
859 fn a_function_that_needs_nothing_of_the_stack_has_no_frame_at_all() {
860 let (func, allocation) = pressure(&SYSV, 2, 4);
861 let frame = Frame::of(&func, &allocation, &Layout::new(&SYSV, REGS));
862
863 assert_eq!(frame.size(), 0);
864 assert_eq!(named(frame.saved_int()), Vec::<&str>::new());
865 assert_eq!(frame.slot(0), None);
866 // Nothing between the stack pointer and the return address the call pushed.
867 assert_eq!(frame.incoming(), Incoming::from_stack(8));
868 }
869
870 #[test]
871 fn a_small_leaf_function_puts_its_spills_in_the_red_zone_and_moves_nothing() {
872 let (func, allocation) = pressure(&SYSV, 4, 2);
873 let frame = Frame::of(&func, &allocation, &Layout::new(&SYSV, REGS));
874
875 // Two registers for four values that are all live at once, so two are on the stack, and a
876 // leaf function small enough is entitled to the bytes below the stack pointer.
877 assert_eq!(frame.size(), 0);
878 assert_eq!((frame.slot(0), frame.slot(1)), (Some(-16), Some(-8)));
879 assert_eq!(frame.slot(2), None);
880 assert_eq!(frame.incoming(), Incoming::from_stack(8));
881 }
882
883 #[test]
884 fn a_leaf_function_told_it_has_no_red_zone_takes_the_bytes_instead() {
885 let (func, allocation) = pressure(&SYSV, 4, 2);
886 let base = Layout::new(&SYSV, REGS);
887 let frame = Frame::of(&func, &allocation, &Layout { red_zone: false, ..base });
888
889 assert_eq!(frame.size(), 16);
890 assert_eq!((frame.slot(0), frame.slot(1)), (Some(0), Some(8)));
891 assert_eq!(frame.incoming(), Incoming::from_stack(24));
892 }
893
894 #[test]
895 fn a_frame_too_big_for_the_red_zone_takes_the_bytes_whatever_else_is_true() {
896 let (func, allocation) = pressure(&SYSV, 40, 2);
897 let frame = Frame::of(&func, &allocation, &Layout::new(&SYSV, REGS));
898
899 // Thirty eight values on the stack is three hundred and four bytes, and the red zone is a
900 // hundred and twenty eight.
901 assert_eq!(frame.size(), 304);
902 assert_eq!(frame.slot(0), Some(0));
903 assert_eq!(frame.slot(37), Some(296));
904 }
905
906 #[test]
907 fn a_function_that_calls_something_leaves_the_stack_pointer_where_a_call_wants_it() {
908 let (func, allocation) = pressure(&SYSV, 4, 2);
909 let base = Layout::new(&SYSV, REGS);
910 let frame = Frame::of(&func, &allocation, &Layout { leaf: false, ..base });
911
912 // Sixteen bytes of spills, and the call that reached this function left the stack pointer
913 // eight bytes off, so the frame is eight bytes wider than the spills need and every call
914 // this function makes is correctly aligned.
915 assert_eq!(frame.size(), 24);
916 assert_eq!((frame.slot(0), frame.slot(1)), (Some(0), Some(8)));
917 assert_eq!(frame.incoming(), Incoming::from_stack(32));
918 }
919
920 #[test]
921 fn a_push_is_counted_in_the_alignment_the_frame_has_to_produce() {
922 let (func, allocation) = pressure(&SYSV, 12, 12);
923 let base = Layout::new(&SYSV, REGS);
924 let frame = Frame::of(&func, &allocation, &Layout { leaf: false, ..base });
925
926 // Twelve values reach into the preserved end of the allocation order, so three registers
927 // are pushed, and three pushes plus the return address is a multiple of sixteen already.
928 // The frame is empty and stays empty rather than being padded for the sake of it.
929 assert_eq!(named(frame.saved_int()), ["rbx", "r12", "r13"]);
930 assert_eq!(frame.size(), 0);
931 assert_eq!(frame.incoming(), Incoming::from_stack(32));
932 }
933
934 #[test]
935 fn the_registers_a_call_leaves_alone_are_saved_in_the_order_the_convention_lists_them() {
936 let (func, allocation) = pressure(&SYSV, 13, 13);
937 let frame = Frame::of(&func, &allocation, &Layout::new(&SYSV, REGS));
938
939 // Four of them now, in the convention's order rather than the order the allocator handed
940 // them out in, so that two functions saving the same registers get the same prologue.
941 assert_eq!(named(frame.saved_int()), ["rbx", "r12", "r13", "r14"]);
942 }
943
944 #[test]
945 fn a_function_that_keeps_a_frame_pointer_does_not_save_it_twice() {
946 let mut names = Interner::new();
947 let mut func = Func::new(names.intern("f"));
948 let opcode = Opcode::new(names.intern("x64.nop"));
949 let block = func.create_block();
950 // An instruction that names the frame pointer register outright, which is what a lowering
951 // rule for something that has to use it produces.
952 func.build(block, opcode).operand(Operand::write(Reg::physical(RBP), GPR)).finish();
953 let allocation = rucc_regalloc::run(&mut func, &env(&SYSV, 4), "test", true);
954 let base = Layout::new(&SYSV, REGS);
955
956 let kept = Frame::of(&func, &allocation, &Layout { frame_pointer: true, ..base });
957 let dropped = Frame::of(&func, &allocation, &base);
958
959 // `rbp` is a register SysV preserves, so a function that leaves it alone saves it in the
960 // ordinary way, and a function that keeps a frame pointer in it saves it as part of
961 // setting the frame pointer up instead.
962 assert_eq!(named(dropped.saved_int()), ["rbp"]);
963 assert_eq!(named(kept.saved_int()), Vec::<&str>::new());
964 assert!(kept.frame_pointer());
965 }
966
967 #[test]
968 fn locals_are_placed_widest_alignment_first_and_reported_in_the_order_they_arrived() {
969 let (func, allocation) = pressure(&SYSV, 2, 4);
970 let locals = [
971 Local { size: 1, align: 1 },
972 Local { size: 16, align: 16 },
973 Local { size: 8, align: 8 },
974 ];
975 let base = Layout::new(&SYSV, REGS);
976 let frame = Frame::of(&func, &allocation, &Layout { locals: &locals, ..base });
977
978 // The sixteen byte one is placed first, so nothing is padded to reach it, and the one
979 // byte one goes last where the padding after it costs nothing.
980 assert_eq!((frame.local(1), frame.local(2), frame.local(0)), (Some(0), Some(16), Some(24)));
981 assert_eq!(frame.local(3), None);
982 // A local wanting sixteen byte alignment is more than the stack pointer has for free, so
983 // the frame is taken rather than the red zone used, and it is padded to keep the local
984 // where it was put.
985 assert_eq!(frame.size(), 40);
986 assert_eq!(frame.realign(), None);
987 }
988
989 #[test]
990 fn a_local_is_counted_from_the_call_frame_address_wherever_the_frame_was_put() {
991 let (func, allocation) = pressure(&SYSV, 2, 4);
992 let base = Layout::new(&SYSV, REGS);
993
994 let locals = [
995 Local { size: 1, align: 1 },
996 Local { size: 16, align: 16 },
997 Local { size: 8, align: 8 },
998 ];
999 let taken = Frame::of(&func, &allocation, &Layout { locals: &locals, ..base });
1000
1001 // The frame is forty bytes and the return address is eight more, so the call frame address
1002 // is forty eight above the stack pointer and every local is that much less than wherever
1003 // the layout put it. The one byte one is nearest, at the top of the frame.
1004 assert_eq!(taken.incoming(), Incoming::from_stack(48));
1005 assert_eq!(taken.from_frame_base(1), Some(-48));
1006 assert_eq!(taken.from_frame_base(2), Some(-32));
1007 assert_eq!(taken.from_frame_base(0), Some(-24));
1008 assert_eq!(taken.from_frame_base(3), None);
1009
1010 // And a leaf small enough to live in the red zone takes no frame at all, so its stack
1011 // pointer is still one return address below the call frame address and its local is below
1012 // that. The same subtraction answers both, which is the point of doing it this way.
1013 let one = [Local { size: 8, align: 8 }];
1014 let free = Frame::of(&func, &allocation, &Layout { locals: &one, ..base });
1015
1016 assert_eq!(free.size(), 0);
1017 assert_eq!(free.incoming(), Incoming::from_stack(8));
1018 assert_eq!(free.from_frame_base(0), Some(-16));
1019 }
1020
1021 #[test]
1022 fn a_realigned_frame_is_no_constant_distance_from_the_call_frame_address() {
1023 let (func, allocation) = pressure(&SYSV, 2, 4);
1024 let locals = [Local { size: 64, align: 32 }];
1025 let base = Layout::new(&SYSV, REGS);
1026 let frame = Frame::of(&func, &allocation, &Layout { locals: &locals, ..base });
1027
1028 // The prologue rounds the stack pointer down to a multiple of thirty two, which throws
1029 // away however far the caller left it from there, so how far the local is below the call
1030 // frame address is a different number every time the function is called.
1031 assert_eq!(frame.realign(), Some(32));
1032 assert_eq!(frame.local(0), Some(0));
1033 assert_eq!(frame.from_frame_base(0), None);
1034 }
1035
1036 #[test]
1037 fn a_local_wanting_more_alignment_than_a_call_gives_makes_the_prologue_force_it() {
1038 let (func, allocation) = pressure(&SYSV, 2, 4);
1039 let locals = [Local { size: 64, align: 32 }];
1040 let base = Layout::new(&SYSV, REGS);
1041 let frame = Frame::of(&func, &allocation, &Layout { locals: &locals, ..base });
1042
1043 assert_eq!(frame.realign(), Some(32));
1044 assert_eq!(frame.local(0), Some(0));
1045 assert_eq!(frame.size(), 64);
1046 // Forcing the alignment throws away how far the caller's stack pointer was from where the
1047 // prologue wanted it, so a frame pointer is needed and the caller's stack is reached
1048 // through it instead: one word for the saved frame pointer and one for the return address.
1049 assert!(frame.frame_pointer());
1050 assert_eq!(frame.incoming(), Incoming::from_frame(16));
1051 }
1052
1053 #[test]
1054 fn the_canary_is_above_every_byte_a_local_or_a_spill_reaches() {
1055 let (func, allocation) = pressure(&SYSV, 4, 2);
1056 let locals = [Local { size: 16, align: 16 }, Local { size: 8, align: 8 }];
1057 let base = Layout::new(&SYSV, REGS);
1058 let there = Layout { leaf: false, locals: &locals, protect: true, ..base };
1059 let frame = Frame::of(&func, &allocation, &there);
1060
1061 // Two spill slots at the bottom, then the two locals, then the canary above all four. That
1062 // order is the whole mechanism: a write that runs off the end of either local passes the
1063 // canary before it reaches the saved registers and the return address.
1064 let canary = frame.canary().expect("a protected frame has a slot");
1065 for below in [frame.slot(0), frame.slot(1), frame.local(0), frame.local(1)] {
1066 assert!(below.expect("a slot that was asked for") < canary);
1067 }
1068 assert_eq!(canary, 40);
1069 // Forty eight bytes of areas, and then the eight that put the stack pointer back where a
1070 // call wants it, because the arm the check fails on makes one.
1071 assert_eq!(frame.size(), 56);
1072 assert_eq!((frame.size() + SYSV.return_address) % SYSV.stack_align, 0);
1073 }
1074
1075 #[test]
1076 fn a_frame_with_no_protector_has_no_slot_for_a_canary() {
1077 let (func, allocation) = pressure(&SYSV, 2, 4);
1078 let frame = Frame::of(&func, &allocation, &Layout::new(&SYSV, REGS));
1079
1080 assert_eq!(frame.canary(), None);
1081 }
1082
1083 #[test]
1084 fn a_call_reads_its_stack_arguments_from_the_bottom_of_the_frame() {
1085 let (func, allocation) = pressure(&SYSV, 4, 2);
1086 let base = Layout::new(&SYSV, REGS);
1087 let frame = Frame::of(&func, &allocation, &Layout { leaf: false, outgoing: 24, ..base });
1088
1089 // The outgoing area is at the stack pointer, because that is where the callee will look
1090 // for it, and the spills sit above it.
1091 assert_eq!(frame.outgoing(), 24);
1092 assert_eq!((frame.slot(0), frame.slot(1)), (Some(24), Some(32)));
1093 assert_eq!(frame.size(), 40);
1094 }
1095
1096 /// Moving everything up by the size of the outgoing area is what would break its alignment,
1097 /// so the area is padded to the widest alignment anything above it wanted. The area itself
1098 /// still starts at the stack pointer, because that is the one thing about it that is not this
1099 /// frame's to choose.
1100 #[test]
1101 fn what_is_above_the_outgoing_area_keeps_the_alignment_it_asked_for() {
1102 let (func, allocation) = pressure(&SYSV, 2, 4);
1103 let locals = [Local { size: 16, align: 16 }];
1104 let base = Layout::new(&SYSV, REGS);
1105 let there = Layout { leaf: false, outgoing: 8, locals: &locals, ..base };
1106 let frame = Frame::of(&func, &allocation, &there);
1107
1108 assert_eq!(frame.outgoing(), 8);
1109 assert_eq!(frame.local(0), Some(16));
1110 assert_eq!(frame.size(), 40);
1111 // A call leaves the stack pointer one return address short of aligned and nothing was
1112 // pushed on top of that, so the frame is what puts it back and the local lands aligned.
1113 assert_eq!((frame.size() + SYSV.return_address) % SYSV.stack_align, 0);
1114 }
1115
1116 #[test]
1117 fn a_windows_call_gets_the_thirty_two_bytes_below_it_even_when_it_passes_nothing() {
1118 let (func, allocation) = pressure(&WIN64, 2, 4);
1119 let base = Layout::new(&WIN64, REGS);
1120 let frame = Frame::of(&func, &allocation, &Layout { leaf: false, ..base });
1121
1122 // Windows has no red zone and every caller reserves thirty two bytes below the call for
1123 // the callee to spill its register arguments into.
1124 assert_eq!(frame.outgoing(), 32);
1125 assert_eq!(frame.size(), 40);
1126 assert_eq!(frame.incoming(), Incoming::from_stack(48));
1127 }
1128
1129 #[test]
1130 fn a_windows_frame_pointer_is_established_after_the_frame_rather_than_before_it() {
1131 let (func, allocation) = pressure(&WIN64, 4, 2);
1132 let base = Layout::new(&WIN64, REGS);
1133 let kept = Frame::of(&func, &allocation, &Layout { frame_pointer: true, ..base });
1134 let dropped = Frame::of(&func, &allocation, &base);
1135
1136 // The unwind record that platform reads cannot describe the other order, so the prologue
1137 // pushes, takes the frame and only then points the pointer at it. What that buys is that
1138 // the pointer holds what the stack pointer holds, so a frame with one and a frame without
1139 // one are the same frame with the same numbers in it.
1140 assert!(kept.frame_pointer());
1141 assert!(kept.late());
1142 assert!(!dropped.frame_pointer());
1143 assert_eq!(kept.size(), dropped.size());
1144 assert_eq!((kept.slot(0), kept.slot(1)), (dropped.slot(0), dropped.slot(1)));
1145 assert_eq!(kept.incoming(), Incoming::from_stack(dropped.incoming().at + 8));
1146 }
1147
1148 #[test]
1149 fn a_windows_frame_that_grows_keeps_the_numbers_it_had_and_changes_the_register() {
1150 let (func, allocation) = pressure(&WIN64, 4, 2);
1151 let base = Layout::new(&WIN64, REGS);
1152 let there = Layout { leaf: false, frame_pointer: true, ..base };
1153 let still = Frame::of(&func, &allocation, &there);
1154 let grown = Frame::of(&func, &allocation, &Layout { grows: true, ..there });
1155
1156 // A frame that grows keeps a pointer whatever the flags asked for, and on this platform
1157 // that pointer is established late, which means it is a copy of the stack pointer as the
1158 // body finds it. So every distance the frame had already worked out from the stack pointer
1159 // is the same distance from the pointer, and growing changes which register the offsets are
1160 // counted from and nothing else. That is the whole of why this frame needs no adjustment.
1161 assert!(grown.grows());
1162 assert!(grown.late());
1163 assert_eq!(grown.size(), still.size());
1164 assert_eq!(grown.outgoing(), still.outgoing());
1165 assert_eq!((grown.slot(0), grown.slot(1)), (still.slot(0), still.slot(1)));
1166 assert_eq!(grown.incoming(), Incoming::from_frame(still.incoming().at));
1167 }
1168
1169 #[test]
1170 fn a_realigned_frame_on_windows_takes_the_late_order_and_rounds_after_it() {
1171 let (func, allocation) = pressure(&WIN64, 2, 4);
1172 let locals = [Local { size: 64, align: 32 }];
1173 let base = Layout::new(&WIN64, REGS);
1174 let frame = Frame::of(&func, &allocation, &Layout { locals: &locals, ..base });
1175
1176 // The pointer goes up after the frame as it does in any other frame here, and the rounding
1177 // comes after that, so the record describes the frame and never sees the rounding. The
1178 // caller's stack is the whole frame above the pointer, the pushes and the return address,
1179 // since the pointer holds where the stack pointer was before it was rounded.
1180 assert_eq!(frame.realign(), Some(32));
1181 assert!(frame.frame_pointer());
1182 assert!(frame.late());
1183 let pushes = 8 * (1 + u32::try_from(frame.saved_int().len()).unwrap()) + 8;
1184 assert_eq!(frame.incoming(), Incoming::from_frame(offset(frame.size() + pushes)));
1185 assert_eq!((frame.size() + pushes) % 16, 0);
1186 assert!(frame.local(0).unwrap() % 32 == 0);
1187 }
1188
1189 #[test]
1190 fn a_slot_is_as_wide_as_the_widest_thing_of_its_class() {
1191 let base = Layout::new(&SYSV, REGS);
1192
1193 assert_eq!(width(&base, GPR), 8);
1194 assert_eq!(width(&base, XMM), 16);
1195 // A long double is eighty bits and takes sixteen bytes, because an address has to be a
1196 // multiple of the size of what is at it.
1197 assert_eq!(width(&base, REGS.class_named("x87").expect("a class")), 16);
1198 }
1199}