rucc_codegen/finish.rs
1//! The prologue, the epilogue, and the moves the allocator asked for.
2//!
3//! Design: `spec/10-backend.md` sections 10.4 and 10.7.
4//!
5//! [`crate::frame`] works out what a function's stack looks like and writes nothing. This is what
6//! writes it. Three things are still missing from a function the allocator has finished with, and
7//! all three of them are instructions no lowering rule chose:
8//!
9//! ```text
10//! the prologue takes the frame the layout worked out, and puts away the registers a call
11//! leaves alone that this function writes anyway
12//! the moves every spill, every reload and every copy the allocator handed back as an
13//! edit, in the place it said and in the order it said
14//! the epilogue gives the frame back and puts the registers back, at the end of every block
15//! the function returns from
16//! ```
17//!
18//! There is a fourth thing and it is not an instruction but a number. The lowering wrote an
19//! instruction for every `alloca` that computes the address of the memory it asked for, and could
20//! not write how far into the frame that memory is, because when it ran there was no frame. So
21//! the displacement of each of those is filled in here, out of the same [`Frame`] everything else
22//! here reads, and off the same stack pointer every other offset in it is from.
23//!
24//! There is a fifth thing on a command line that asked for the stack to be touched a page at a
25//! time, and it is the only one of them that is written into the middle of a block rather than at
26//! one end of the function. A variable length array moves the stack pointer by a number that is not
27//! known until the declaration runs, so walking it a page at a time is a loop written around the one
28//! instruction the lowering left, and that turns the block the declaration was in into four.
29//!
30//! The loads that read the arguments the caller passed on the stack are waiting on the same number
31//! and on one more. Those bytes are the caller's rather than this function's, and a frame that had
32//! to force its own alignment cannot say how far away the caller's stack pointer was, so it reaches
33//! back through the frame pointer instead. Which register a load reads through is therefore settled
34//! here too, and it is the only base register in a finished function that was not settled by
35//! whoever wrote the instruction.
36//!
37//! After this the function is one an encoder can read: every register is physical, every offset
38//! into the frame is a constant, and the stack pointer is where the convention says it should be
39//! at every instruction that could look.
40//!
41//! # Why the moves go in first
42//!
43//! Every offset the frame reports is from the stack pointer as it stands in the body of the
44//! function. A spill written before the prologue exists would be written in front of the
45//! instruction it belongs to and behind nothing, which is where the prologue then goes, so the
46//! prologue ends up in front of it and the offsets stay true. Writing them the other way round
47//! would put the first reload above the instruction that takes the frame, and it would read from
48//! an address that is one frame out.
49//!
50//! # Where a return is
51//!
52//! A block that goes nowhere is a block the function leaves from. Mostly that is a return, and
53//! the other kind is a block ending in `unreachable`, which is a point the front end says control
54//! does not arrive at and which the lowering writes no instruction for. Both want the same thing
55//! here. A return wants the epilogue because that is what a return is once the frame is known,
56//! and an unreachable block wants it because the alternative is a function whose last instruction
57//! falls into whatever the assembler put after it, which is worse than an epilogue nothing runs.
58//! So the epilogue goes at the end of every block with an empty successor list, and there may be
59//! several, because nothing here insists a function has one exit.
60//!
61//! # What is target-specific here
62//!
63//! The names, and only the names. Which instruction pushes a register and which one moves the
64//! stack pointer is [`rucc_target::FrameInsts`], which the target says and this reads, so what
65//! is written below is the shape of a prologue rather than any particular machine's. That is
66//! `spec/10-backend.md` section 10.8 as it applies to the one pass that would otherwise be full
67//! of `x64.` by hand.
68
69use std::collections::HashMap;
70
71use rucc_base::Interner;
72use rucc_diag::Span;
73use rucc_mir::{Block, BlockCall, CfiOp, Func, Inst, Mem, Opcode, Operand, Patch, Reg};
74use rucc_regalloc::Allocation;
75use rucc_regalloc::assign::Place;
76use rucc_regalloc::rewrite::{At, Edit};
77use rucc_target::{BranchInsts, CallRegs, Chkstk, FrameInsts, Guard, PhysReg, Probe, RegClass};
78
79use crate::frame::Frame;
80use crate::lower::Stack;
81
82/// What the stack protector's check needs beyond the frame, in a function that has one.
83///
84/// Three things that come from three places, which is why they arrive together rather than being
85/// looked up here. Where the word the canary is copied from lives is a fact about the runtime the
86/// code is linked against. What a branch on a register is is a fact about the machine. And the two
87/// registers are neither: they are the ones the allocator was told to hold back, which is a
88/// decision about the allocator, and they are free at a return for exactly that reason.
89#[derive(Debug, Clone, Copy)]
90pub struct Protect<'a> {
91 /// Where the word the canary is a copy of lives, and what to call when the copy has changed.
92 pub guard: &'a Guard,
93 /// What a branch on a register is, which is what the check ends its block with.
94 pub branch: &'a BranchInsts,
95 /// The two registers the check may use, which are two the allocator never handed out.
96 pub scratch: [PhysReg; 2],
97}
98
99/// What a function that takes its stack a page at a time needs beyond the frame.
100///
101/// What `-fstack-clash-protection` asks for, and the same three kinds of thing [`Protect`] is:
102/// one fact about the platform, one about the machine, and two registers that are neither. See
103/// [`rucc_target::Probe`] for what the sequence is defending against.
104///
105/// Read in two places, because a function has two ways of moving its stack pointer and the flag is
106/// about both of them. The prologue takes the frame the layout worked out, and a variable length
107/// array takes however many bytes its declaration asked for while the function runs. The same three
108/// things answer both.
109#[derive(Debug, Clone, Copy)]
110pub struct Probing<'a> {
111 /// What touches a page and how far apart the pages are.
112 pub probe: &'a Probe,
113 /// What a branch on a register is, which is what the loop under a large frame ends with.
114 pub branch: &'a BranchInsts,
115 /// The two registers the sequence may use, which are two the allocator never handed out.
116 pub scratch: [PhysReg; 2],
117}
118
119/// What a profiler's hook at the top of a function is, in a function that has one.
120///
121/// What `-pg` asks for. See [`rucc_target::Trace`] for why there are two of these and what each of
122/// them lets the hook see. Only the name survives to here, because by this point the flag has been
123/// read against the target and a prologue that has the name has everything it needs.
124#[derive(Debug, Clone, Copy)]
125pub struct Tracing {
126 /// What is called, which is a routine the runtime provides and not one the program wrote.
127 pub name: &'static str,
128 /// Whether the call goes in front of the prologue rather than once the frame is taken.
129 pub early: bool,
130}
131
132/// The room at the top of a function for something to be written over later, in a function that
133/// was promised any.
134///
135/// What `-fpatchable-function-entry=` asks for. The room is a run of the shortest instruction the
136/// machine has that does nothing, and what makes it worth reserving is that it is never run for
137/// long: a tracer or a live patcher writes a jump or a call over it once the program is up, and
138/// what it needs from the compiler is a known address and a known number of bytes.
139///
140/// Two counts because the room can be on either side of the function's own label. Only the half
141/// after it is written here, since the stream starts at the label and there is nowhere in it to put
142/// the other half; the half in front is carried through so that whatever lays the function down can
143/// lay that many bytes ahead of the symbol.
144#[derive(Debug, Clone, Copy)]
145pub struct Padding {
146 /// What the instruction that does nothing is called on this target.
147 pub name: &'static str,
148 /// How many of them go in front of the function's own label.
149 pub before: u32,
150 /// How many go after it.
151 pub after: u32,
152}
153
154/// What the convention this function is compiled for says a frame is.
155///
156/// Seven answers to the one question, which is why they travel together: where it puts things,
157/// which instructions build one, whether this function's carries a protector, whether it is taken a
158/// page at a time, whether the function opens with a landing pad, whether it calls a profiler on
159/// the way in, and how much room it opens with for a patcher. The last five are the only ones about
160/// this function rather than about every function on the target, and they are here because what
161/// they need is the other two and nothing else.
162#[derive(Debug, Clone, Copy)]
163pub struct Convention<'a> {
164 /// Where the convention puts things.
165 pub regs: &'a CallRegs,
166 /// The instructions a prologue, an epilogue, a spill and a reload are made of on it.
167 pub insts: &'a FrameInsts,
168 /// What this function's stack protector needs, or `None` in a function with none.
169 pub protect: Option<Protect<'a>>,
170 /// What this function's probing prologue needs, or `None` when the frame is taken in one
171 /// subtraction, which is what a command line that did not ask asks for.
172 pub probe: Option<Probing<'a>>,
173 /// What says an indirect branch may arrive at the top of this function, or `None` when the
174 /// command line did not ask for one and on a target that has no such instruction.
175 ///
176 /// See [`rucc_target::FrameInsts::landing`]. A name rather than a flag because the flag has
177 /// already been read against the target by the time this is built, and because a prologue that
178 /// has the name has everything it needs.
179 pub landing: Option<&'static str>,
180 /// What this function's call to a profiler is, or `None` in one that makes none, which is every
181 /// function on a command line that did not ask.
182 pub trace: Option<Tracing>,
183 /// What room this function opens with for a patcher, or `None` in one that was promised none,
184 /// which is every function on a command line that did not ask.
185 pub pad: Option<Padding>,
186}
187
188impl<'a> Convention<'a> {
189 /// That convention, for a function with no stack protector, no probing, no landing pad, no
190 /// call to a profiler and no room for a patcher, which is most of them.
191 #[must_use]
192 pub fn new(regs: &'a CallRegs, insts: &'a FrameInsts) -> Self {
193 Self { regs, insts, protect: None, probe: None, landing: None, trace: None, pad: None }
194 }
195}
196
197/// Which instruction each of the allocator's moves became.
198///
199/// A spill and a copy are both a `mov` once they are written, and so is an instruction the lowering
200/// wrote that happens to move the same register to the same address. Telling them apart afterwards
201/// by looking at them is guesswork, and a pass that guesses wrong about a store to a volatile
202/// variable deletes a read the program insisted on. So what the allocator asked for is recorded as
203/// it is written, and a later pass that is only allowed to touch the allocator's own moves has the
204/// list rather than a heuristic. See [`crate::copies`], which is the one pass that reads this.
205#[derive(Debug, Default)]
206pub struct Moves(HashMap<Inst, Edit>);
207
208impl Moves {
209 /// What the allocator asked for at this instruction, or `None` at an instruction that is not
210 /// one of its moves.
211 #[must_use]
212 pub fn at(&self, inst: Inst) -> Option<Edit> {
213 self.0.get(&inst).copied()
214 }
215
216 /// Records that this instruction is what that move came to.
217 pub fn record(&mut self, inst: Inst, edit: Edit) {
218 self.0.insert(inst, edit);
219 }
220}
221
222/// Writes the moves, the prologue and the epilogue into a function the allocator has finished
223/// with.
224///
225/// Hands back which instruction each of the allocator's moves became, for the one pass that is
226/// allowed to take one of them out again.
227///
228/// # Panics
229///
230/// Panics on a function with no blocks in it, on a frame whose slots or locals the allocation and
231/// the lowering do not match, and on a move of a class the target did not say how to move. All of
232/// them are the caller handing it a frame and a function that were not worked out from each other.
233pub fn finish(
234 func: &mut Func,
235 allocation: &Allocation,
236 frame: &Frame,
237 stack: &Stack,
238 convention: Convention<'_>,
239 names: &mut Interner,
240) -> Moves {
241 let Convention { regs: conv, insts, protect, probe, landing, trace, pad } = convention;
242 let entry = func.entry().expect("a function with a block in it");
243
244 // Before anything is written, because these are instructions the lowering already put in the
245 // function and every one of them is somewhere the prologue is about to go in front of, which
246 // is what makes an offset from the stack pointer the right thing to write into them. In a
247 // frame that grows it is an offset from the frame pointer instead, so the base register is
248 // rewritten the way an incoming argument's is, and for a version of the same reason.
249 //
250 // Added rather than assigned. The instruction named here is the `lea` the lowering wrote, or
251 // whatever [`crate::fold`] folded that `lea` into, and a reader that took it brought a
252 // displacement of its own: the address of a local is where the object starts and reading a
253 // field of it is some way past that. Assigning would throw the field offset away and read the
254 // front of the object every time.
255 for &(inst, local) in &stack.addresses {
256 let at = frame.local(local).expect("a local the frame was worked out from");
257 let mem = func[inst].mem.expect("the address of a local is an address");
258 func[mem].disp += at;
259 if frame.grows() {
260 rebase(func, inst, conv.frame_pointer);
261 }
262 }
263
264 // The bytes a variable length array takes are already off the stack pointer by the time one of
265 // these runs, so what is left to write is how far above the new stack pointer the array starts,
266 // which is however much of the bottom of the frame belongs to the arguments of a call. That
267 // area stays at the bottom wherever the bottom has moved to. Added rather than assigned for the
268 // reason the loop above is: one of these folds into its readers like any other address, and a
269 // reader that took it brought a displacement of its own.
270 for &inst in &stack.dynamic {
271 let mem = func[inst].mem.expect("the address of a growable local is an address");
272 func[mem].disp += offset(frame.below());
273 }
274
275 // The same, one area further up, and through the frame pointer when that is what reaches it.
276 // These are in the entry block ahead of everything, so the prologue still goes in front of
277 // them, which is what makes both registers hold what these offsets are counted from.
278 let incoming = frame.incoming();
279 for &(inst, up) in &stack.arguments {
280 let mem = func[inst].mem.expect("an argument read out of memory is read from an address");
281 func[mem].disp += incoming.at + offset(up);
282 if incoming.through_frame_pointer {
283 rebase(func, inst, conv.frame_pointer);
284 }
285 }
286
287 // Every offset the frame reports is from this one register, which is the stack pointer in an
288 // ordinary frame and the frame pointer in one that moves the stack pointer while it runs.
289 let base = if frame.grows() { conv.frame_pointer } else { conv.stack_pointer };
290 let mut writer = Writer { func, conv, insts, names, base, ahead: None };
291
292 let mut cursors: HashMap<At, Inst> = HashMap::new();
293 let mut moves = Moves::default();
294 for edit in &allocation.edits {
295 let inst = writer.mov(edit, frame);
296 writer.put(&mut cursors, edit.at, inst);
297 moves.record(inst, *edit);
298 }
299
300 // Before the epilogues, because this is what turns one block into four and the last of the four
301 // is the one the function goes on to return from. A block that went nowhere before a variable
302 // length array was walked in the middle of it is not the block that goes nowhere afterwards, and
303 // an epilogue written into the wrong one of them gives the frame back before the body has run.
304 if let Some(probing) = probe {
305 for &took in &stack.grown {
306 writer.walk(took, probing);
307 }
308 }
309
310 let prologue = writer.prologue(frame, protect, probe, landing, trace, pad);
311 for &inst in prologue.iter().rev() {
312 writer.func.prepend_inst(entry, inst);
313 }
314 let returns: Vec<Block> =
315 writer.func.blocks().filter(|&block| writer.func[block].succs.is_empty()).collect();
316 for block in returns {
317 // The check goes in front of the epilogue and takes the return with it. What is left in
318 // the block the function used to return from is the check, and the block the epilogue then
319 // goes in is the arm the canary was unchanged on.
320 let block = match protect {
321 Some(protect) => writer.check(block, frame, protect),
322 None => block,
323 };
324 let epilogue = writer.epilogue(frame);
325 for inst in epilogue {
326 writer.func.append_inst(block, inst);
327 }
328 }
329
330 // Last of everything, because the blocks a probing prologue made have to come in front of the
331 // block the function used to begin with and the ones the protector's check makes are made
332 // after that. Nothing has been laid out yet: `crate::layout` runs after this and puts every
333 // block in its own order, and all this decides is which block the function is entered at.
334 if let Some(ahead) = writer.ahead {
335 let rest: Vec<Block> =
336 writer.func.blocks().filter(|block| !ahead.contains(block)).collect();
337 let order: Vec<Block> = ahead.into_iter().chain(rest).collect();
338 writer.func.set_block_order(&order);
339 }
340 moves
341}
342
343/// How many pages a probing prologue touches one after another before it writes a loop instead.
344///
345/// Three, which is what gcc unrolls to. The loop is four instructions however many pages it walks
346/// and a page written out is two, so three is the last size at which the straight line is no
347/// longer than the loop, and the straight line has no branch in it and needs no register.
348const UNROLLED: u32 = 3;
349
350/// One function having its frame written into it.
351/// Points an address the lowering left counted from the stack pointer at another register.
352///
353/// The base register is an operand of the instruction and the addressing mode holds where in the
354/// operand vector it is, so the register is changed there and not in the mode.
355fn rebase(func: &mut Func, inst: Inst, to: PhysReg) {
356 let mem = func[inst].mem.expect("an address");
357 let at = func[mem].base.expect("an address the lowering wrote a base register into");
358 let operands = func[inst].operands;
359 func[operands][usize::from(at)].reg = Reg::physical(to);
360}
361
362struct Writer<'a> {
363 func: &'a mut Func,
364 conv: &'a CallRegs,
365 insts: &'a FrameInsts,
366 names: &'a mut Interner,
367 /// Which register every offset into the frame is counted from, which is the stack pointer
368 /// unless the function moves it while it runs. See `Growing` in [`crate::frame`].
369 base: PhysReg,
370 /// The blocks a probing prologue made, which go in front of the one the function began with.
371 ///
372 /// Empty in every function whose frame is taken in one subtraction, which is every function
373 /// on a command line that did not ask for the stack to be touched a page at a time and most
374 /// of them on one that did. See [`Writer::pages`].
375 ahead: Option<[Block; 2]>,
376}
377
378impl Writer<'_> {
379 /// The instructions the prologue is, in the order they run.
380 ///
381 /// The order is the one the epilogue undoes and it is not free. The frame pointer is saved
382 /// before anything else, so that it points at a fixed place whatever else happens. The
383 /// registers are pushed before the alignment is forced, so that the epilogue can find them
384 /// again from the frame pointer, since after the alignment is forced nothing else can. And the
385 /// vector registers are stored last, because until the frame has been taken there is nowhere
386 /// to store them.
387 ///
388 /// Where the pointer is pointed at the frame is the one part of that order the platform gets a
389 /// say in. Windows wants it after the frame has been taken rather than before, because the
390 /// unwind record it reads has no way to describe the other order, so on that target the move
391 /// goes between the frame and the vector stores instead. See `Late` in [`crate::frame`].
392 ///
393 /// The landing pad is in front of all of it, because the address it makes reachable is the
394 /// address of the function and the address of the function is where the first instruction is.
395 /// It has to be written here rather than after the fact, since a probing prologue moves the
396 /// instructions written so far into a block of its own and the pad has to move with them.
397 ///
398 /// The room a patcher was promised goes after the pad, because a patcher wants somewhere it can
399 /// write a call that happens before anything else, and the pad is the one instruction that has
400 /// to come first for a reason of its own.
401 ///
402 /// A profiler's hook goes next, or at the end when it is the kind that reads the frame pointer.
403 /// The early one is in front of everything the frame does for a reason of its own: what makes
404 /// it worth replacing while the program runs is that the stack at that instruction is exactly
405 /// what a call leaves, and a prologue that had already run would have changed it.
406 fn prologue(
407 &mut self,
408 frame: &Frame,
409 protect: Option<Protect<'_>>,
410 probe: Option<Probing<'_>>,
411 landing: Option<&'static str>,
412 trace: Option<Tracing>,
413 pad: Option<Padding>,
414 ) -> Vec<Inst> {
415 let sp = self.conv.stack_pointer;
416 let fp = self.conv.frame_pointer;
417 let int = self.conv.int_class;
418 let sse = self.conv.sse_class;
419 let word = offset(self.conv.word);
420 let mut out = Vec::new();
421 // What the prologue wrote before it had described anything, which is what decides whether
422 // there is a rule to remember at the end of it. Neither of these moves a register or takes
423 // a frame, so a function whose whole prologue is one of them has no rows and must not be
424 // given a pair of them that cancel out.
425 let mut quiet = Vec::new();
426 if let Some(name) = landing {
427 let opcode = self.opcode(name);
428 let inst = self.func.build_loose(opcode).finish();
429 out.push(inst);
430 quiet.push(inst);
431 }
432 // After the pad and in front of everything else, which is where gcc puts it. The pad is the
433 // function's first instruction because the address an indirect branch may arrive at is the
434 // address of the function, and the room comes next because what gets written over it is a
435 // call and the point of that call is that it happens before the function has done anything.
436 //
437 // Nothing is described for any of it. A byte that does nothing does not move the stack
438 // pointer, and what a patcher writes over it later is its own problem rather than this
439 // function's: the rules here say what this function did, and it did nothing.
440 if let Some(pad) = pad {
441 let opcode = self.opcode(pad.name);
442 let mut first = None;
443 for _ in 0..pad.after {
444 let inst = self.func.build_loose(opcode).finish();
445 out.push(inst);
446 quiet.push(inst);
447 first.get_or_insert(inst);
448 }
449 self.func.patch = Some(Patch { before: pad.before, pad: opcode, after: first });
450 }
451 // Nothing is described for it and nothing needs to be: the call pushes a return address and
452 // the hook pops it, so the frame is the same on both sides, and the hook preserves every
453 // register because it is written in assembly for exactly this. That is also why the
454 // allocator, which ran before any of this, never saw the call and did not have to.
455 if let Some(trace) = trace.filter(|trace| trace.early) {
456 let inst = self.hook(trace);
457 out.push(inst);
458 quiet.push(inst);
459 }
460 // How far the stack pointer is below the canonical frame address, and whether the address
461 // is still counted from the stack pointer at all. It starts at the return address the
462 // call itself pushed, which is the rule the CIE already states, so the first row here is
463 // the first thing this function does on top of that.
464 let mut below = offset(self.conv.return_address);
465 let mut from_sp = true;
466 if frame.frame_pointer() {
467 let inst = self.push(fp);
468 out.push(inst);
469 below += word;
470 self.row(inst, CfiOp::DefCfaOffset(below));
471 self.saved(inst, int, fp, -below);
472 // Straight away unless the platform wants it after the frame, where the same two
473 // instructions go at the bottom of this function instead. See `Late` in
474 // [`crate::frame`].
475 if !frame.late() {
476 let mov = self.opcode(self.insts.moves(int).expect("a move").mov);
477 let inst = self.two(mov, fp, sp);
478 out.push(inst);
479 let number = self.dwarf(int, fp);
480 self.row(inst, CfiOp::DefCfaRegister(number));
481 from_sp = false;
482 }
483 }
484 for ® in frame.saved_int() {
485 let inst = self.push(reg);
486 out.push(inst);
487 below += word;
488 if from_sp {
489 self.row(inst, CfiOp::DefCfaOffset(below));
490 }
491 self.saved(inst, int, reg, -below);
492 }
493 if let Some(to) = frame.realign() {
494 // Nothing is written for this and nothing can be. After it the stack pointer is a
495 // rounded-down version of where it was rather than a fixed distance from it, which is
496 // exactly what a rule cannot say. It is also why a frame that realigns is a frame
497 // with a frame pointer: by here the address is already counted from that instead.
498 assert!(!from_sp, "a frame that forces its own alignment has a frame pointer");
499 let and = self.opcode(self.insts.align);
500 out.push(self.arith(and, -i64::from(to)));
501 }
502 if frame.size() > 0 {
503 self.take(&mut out, frame.size(), &mut below, from_sp, probe);
504 }
505 // The other half of the pair above, for the platform whose record counts everything from
506 // where the stack pointer ends the prologue. Here it is that register the pointer is a copy
507 // of, so what the row says is the whole distance rather than that nothing has changed, and
508 // the frame is described before it rather than after, which is the whole of what the record
509 // could not say about the early order.
510 if frame.late() && frame.frame_pointer() {
511 let mov = self.opcode(self.insts.moves(int).expect("a move").mov);
512 let inst = self.two(mov, fp, sp);
513 out.push(inst);
514 let number = self.dwarf(int, fp);
515 self.row(inst, CfiOp::DefCfa { reg: number, offset: below });
516 }
517 for save in frame.saved_sse() {
518 let inst = self.store(sse, save.reg, save.at);
519 out.push(inst);
520 // Where it went is an offset from whichever register the frame counts from, and the
521 // address is a constant above that register, so the two make one constant. In an
522 // ordinary frame that register is the stack pointer and the constant is `below`. In one
523 // that grows it is the frame pointer, which the address has been counted from since the
524 // prologue pointed it at where it saved the caller's copy, so the constant is the two
525 // words above it and nothing the prologue did afterwards changes it. Unless the pointer
526 // went up late, where it holds what the stack pointer holds and the constant is `below`
527 // again, which is why the question is about both. A realigned frame has no such constant
528 // at all and the rule is left out rather than guessed. On SysV that costs nothing, since
529 // it preserves no vector register for a prologue to save. On Windows it would be a save
530 // with no row, and what stops that reaching an object file is that a realigned frame
531 // there keeps the early order and is refused whole by the unwind writer, which is
532 // `tamnd/rucc#1422`.
533 if frame.realign().is_none() {
534 let above = if frame.grows() && !frame.late() {
535 word + offset(self.conv.return_address)
536 } else {
537 below
538 };
539 self.saved(inst, sse, save.reg, save.at - above);
540 }
541 }
542 // Before the canary and after the frame, which is where gcc puts it. The hook reads the
543 // frame pointer to find out who called this function, so it has to run once there is one,
544 // and it is a call, so it has to run before anything the function is keeping in the frame
545 // could be read back.
546 if let Some(trace) = trace.filter(|trace| !trace.early) {
547 let inst = self.hook(trace);
548 out.push(inst);
549 }
550 // Last of everything, because it writes into the frame and there is no frame to write into
551 // until the stack pointer has moved. Nothing is described for either instruction: they
552 // write a slot rather than save a register, and no unwinder wants to put a canary back.
553 if let Some(protect) = protect {
554 let at = frame.canary().expect("a protected function has a slot for its canary");
555 let [into, _] = protect.scratch;
556 out.push(self.read_guard(into, protect.guard));
557 out.push(self.store(self.conv.int_class, into, at));
558 }
559 // The rules the body runs under, kept so that each epilogue can put them back rather than
560 // leaving the next block reading whatever the last one ended on. See `epilogue`.
561 //
562 // Nothing is kept in a function whose whole prologue is the pieces that describe nothing.
563 // See `quiet` above.
564 if let Some(&last) = out.last() {
565 if !quiet.contains(&last) {
566 self.row(last, CfiOp::RememberState);
567 }
568 }
569 out
570 }
571
572 /// The call to a profiler's hook.
573 ///
574 /// No arguments and no result. Which function is being entered is not passed, because the hook
575 /// reads its own return address to find out, and that is the whole reason the call is written
576 /// rather than something cheaper.
577 fn hook(&mut self, trace: Tracing) -> Inst {
578 let call = self.opcode(self.insts.call);
579 let symbol = self.names.intern(trace.name);
580 self.func.build_loose(call).symbol(symbol).finish()
581 }
582
583 /// Takes the frame, which is one subtraction unless the command line asked for the stack to be
584 /// touched a page at a time.
585 ///
586 /// `below` is how far the canonical frame address is above the stack pointer, and it comes
587 /// back as what it is once the frame has been taken.
588 fn take(
589 &mut self,
590 out: &mut Vec<Inst>,
591 size: u32,
592 below: &mut i32,
593 from_sp: bool,
594 probe: Option<Probing<'_>>,
595 ) {
596 // In front of everything else, because a platform with a routine for this has it for every
597 // frame rather than for the ones a flag was passed about, and because the routine does the
598 // whole of what the walk below would have done. See [`rucc_target::Chkstk`].
599 let page = self.insts.probe.map_or(u32::MAX, |probe| probe.interval);
600 if let Some(chkstk) = self.conv.chkstk.filter(|_| size > page) {
601 let inst = self.reach(out, chkstk, size);
602 *below += offset(size);
603 if from_sp {
604 self.row(inst, CfiOp::DefCfaOffset(*below));
605 }
606 return;
607 }
608 let Some(probing) = probe.filter(|probing| size > probing.probe.interval) else {
609 let inst = self.sub(size);
610 out.push(inst);
611 *below += offset(size);
612 if from_sp {
613 self.row(inst, CfiOp::DefCfaOffset(*below));
614 }
615 return;
616 };
617 // Every step but the last is a whole page and is followed by a touch, and the last is
618 // whatever is left over, which is between one byte and one whole page. So the stack
619 // pointer never moves further than a page without something being written where it landed,
620 // and the unmapped page an operating system leaves below a stack cannot be stepped over.
621 //
622 // That is why the count is worked out from one less than the size. A frame that is an
623 // exact number of pages gets one fewer touch than it has pages, and the step left over is
624 // a whole page, which is a step that lands on the next page boundary rather than past it.
625 // gcc touches that last page as well, so this is one instruction shorter on a frame whose
626 // size is a multiple of the page and the same everywhere else.
627 let interval = probing.probe.interval;
628 let pages = (size - 1) / interval;
629 let rest = size - pages * interval;
630 let mut walked = false;
631 if pages <= UNROLLED {
632 for _ in 0..pages {
633 let inst = self.sub(interval);
634 out.push(inst);
635 *below += offset(interval);
636 if from_sp {
637 self.row(inst, CfiOp::DefCfaOffset(*below));
638 }
639 let touch = self.touch(probing.probe);
640 out.push(touch);
641 }
642 } else {
643 self.pages(out, pages, below, from_sp, probing);
644 walked = from_sp;
645 }
646 let inst = self.sub(rest);
647 out.push(inst);
648 *below += offset(rest);
649 if from_sp {
650 // A loop leaves the address counted from the register the stack pointer was compared
651 // against, since that is the one thing in it that holds still. This is where it goes
652 // back to being counted from the stack pointer, and it is written behind this
653 // instruction rather than behind the branch because a row is written behind an
654 // instruction and the branch is not one that survives [`crate::layout`].
655 let op = if walked {
656 let number = self.dwarf(self.conv.int_class, self.conv.stack_pointer);
657 CfiOp::DefCfa { reg: number, offset: *below }
658 } else {
659 CfiOp::DefCfaOffset(*below)
660 };
661 self.row(inst, op);
662 }
663 }
664
665 /// Reaches the pages of a frame by calling the routine this platform has for it, and then takes
666 /// the frame.
667 ///
668 /// Three instructions, and the third is the one that moves anything:
669 ///
670 /// ```text
671 /// the size into a register which register is the platform's answer rather than ours
672 /// the call touches every page from here down to that many bytes below
673 /// the subtraction takes the frame, of the register the size is still in
674 /// ```
675 ///
676 /// The routine comes back having moved nothing, which is what makes the third instruction
677 /// necessary and is also what makes it a subtraction of a register rather than of the constant
678 /// written again. Writing the constant twice would be the same number of bytes of code and one
679 /// more place for the two to disagree.
680 ///
681 /// Nothing is described to the unwinder for the first two. The call pushes a return address and
682 /// the routine pops it, so the frame is the same on both sides of it, which is the same argument
683 /// the profiler's hook makes a few lines above. The row goes behind the subtraction, where the
684 /// stack pointer has actually moved.
685 ///
686 /// No register here has to be asked about. The size goes in one the convention passes no
687 /// argument in, which is what lets the platform name it at all, and the routine destroys two
688 /// that are exactly the two the allocator was told to hold back. A prologue is also the one
689 /// place in a function where the only live values are the ones that arrived in the convention's
690 /// own registers.
691 fn reach(&mut self, out: &mut Vec<Inst>, chkstk: Chkstk, size: u32) -> Inst {
692 let class = self.conv.int_class;
693 let sp = Reg::physical(self.conv.stack_pointer);
694 let count = Reg::physical(chkstk.size);
695
696 let imm = self.opcode(self.insts.imm);
697 let inst = self.func.build_loose(imm).def(count, class).imm(i64::from(size)).finish();
698 out.push(inst);
699 let call = self.opcode(self.insts.call);
700 let symbol = self.names.intern(chkstk.name);
701 let inst = self.func.build_loose(call).symbol(symbol).finish();
702 out.push(inst);
703 let grow = self.opcode(self.insts.grow);
704 let inst =
705 self.func.build_loose(grow).def(sp, class).uses(sp, class).uses(count, class).finish();
706 out.push(inst);
707 inst
708 }
709
710 /// The loop that takes a frame too large for the touches to be written one after another.
711 ///
712 /// Three blocks, and the first two are new and go in front of the one the function began with:
713 ///
714 /// ```text
715 /// what the function is entered at everything the prologue did before this, and then the
716 /// address the stack pointer is walking down to
717 /// the loop one page, the touch, and the question of whether the
718 /// stack pointer has got there yet
719 /// what the function began with the rest of the prologue, and then the body
720 /// ```
721 ///
722 /// The instructions the prologue has written so far move into the first of them, because a
723 /// block is entered at the top and they have to run before the loop does. Nothing is laid out
724 /// here: which block comes first in memory is [`crate::layout`]'s answer, and all this decides
725 /// is which one the function is entered at.
726 fn pages(
727 &mut self,
728 out: &mut Vec<Inst>,
729 pages: u32,
730 below: &mut i32,
731 from_sp: bool,
732 probing: Probing<'_>,
733 ) {
734 let class = self.conv.int_class;
735 let sp = self.conv.stack_pointer;
736 let all = offset(pages * probing.probe.interval);
737 let [limit, byte] = probing.scratch;
738
739 let head = self.func.create_block();
740 for &inst in out.iter() {
741 self.func.append_inst(head, inst);
742 }
743 out.clear();
744 // Where the stack pointer is walking down to, worked out before it starts moving. A loop
745 // that counted down instead would need somewhere to keep the count, and this is somewhere
746 // to keep it that the comparison can read without arithmetic.
747 let lea = self.opcode(self.insts.lea);
748 let inst = self.address(lea, limit, sp, -all);
749 self.func.append_inst(head, inst);
750 if from_sp {
751 // The address is counted from that register for as long as the loop runs, and it has
752 // to be: the stack pointer moves once an iteration, so no fixed distance from it is
753 // true twice, and this register was written so that one distance is.
754 let number = self.dwarf(class, limit);
755 self.row(inst, CfiOp::DefCfa { reg: number, offset: *below + all });
756 }
757
758 let body = self.func.create_block();
759 *self.func.succs_mut(head) = vec![BlockCall::to(body)];
760 let inst = self.sub(probing.probe.interval);
761 self.func.append_inst(body, inst);
762 let touch = self.touch(probing.probe);
763 self.func.append_inst(body, touch);
764 let differ = self.opcode(self.insts.differ);
765 let inst = self
766 .func
767 .build_loose(differ)
768 .def(Reg::physical(byte), class)
769 .uses(Reg::physical(sp), class)
770 .uses(Reg::physical(limit), class)
771 .finish();
772 self.func.append_inst(body, inst);
773 let cond = Opcode::new(
774 self.names.intern(&format!("{}{}", probing.branch.prefix, probing.branch.cond)),
775 );
776 let inst = self.func.build_loose(cond).uses(Reg::physical(byte), class).finish();
777 self.func.append_inst(body, inst);
778 // The first arm is the one taken when the condition held, and the condition is that the
779 // stack pointer and the address it is walking down to still differ, so the first arm is
780 // another page.
781 let began = self.func.entry().expect("a function with a block in it");
782 *self.func.succs_mut(body) = vec![BlockCall::to(body), BlockCall::to(began)];
783 *below += all;
784 self.ahead = Some([head, body]);
785 }
786
787 /// Walks the pages a variable length array takes, at the declaration that takes them.
788 ///
789 /// The prologue's own pages are counted when it is written, so it can step down to an address
790 /// it worked out in advance and stop when it gets there. A declaration in the body cannot: how
791 /// many bytes it asked for arrives in a register, so where it is going is arithmetic rather than
792 /// a constant, and how many pages that is is a number nothing has. What is written instead is a
793 /// loop that steps a page and asks whether it has arrived yet, which is the same walk with the
794 /// count taken out of it.
795 ///
796 /// The one instruction the lowering wrote becomes four blocks:
797 ///
798 /// ```text
799 /// what the block was everything it did before the declaration, and then where the
800 /// stack pointer is going, worked out before it starts moving
801 /// the step one page, and whether the stack pointer is still above there
802 /// the page it stepped onto the touch, and round again
803 /// the rest of the block the stack pointer put where it was going, and then the body
804 /// ```
805 ///
806 /// The touch is behind the question rather than in front of it, so the only page ever written
807 /// is one the array reaches. The last step down is a whole page whatever is left, which puts the
808 /// stack pointer at or past the end of the array, and the block that follows puts it back on the
809 /// end. Nothing is touched there and nothing has to be: that is a move of less than a page from
810 /// a page this loop has already been to, which is the whole of what a guard page asks.
811 ///
812 /// Nothing is described to the unwinder for any of it. A function with a variable length array
813 /// in it keeps a frame pointer, because its own stack pointer is not a fixed distance from
814 /// anything, and by here the frame is already counted from that register rather than from the
815 /// stack pointer. So the rule that was true before the walk is still true after it.
816 fn walk(&mut self, took: Inst, probing: Probing<'_>) {
817 let class = self.conv.int_class;
818 let sp = self.conv.stack_pointer;
819 let span = self.func.span(took);
820 let block = self.func.block_of(took).expect("an instruction the lowering put in a block");
821
822 // Which register the bytes arrived in, and which two the walk may use. The bytes may be in
823 // one of the two, because a reload the rewriter wrote is written into one of them, and a
824 // value that arrived that way is read by the one instruction it was written in front of and
825 // is dead after it. So the limit goes in whichever of the pair the bytes are not in, and the
826 // other one is free from the moment the limit has been worked out.
827 let operands = self.func[took].operands;
828 let bytes = self.func[operands][2].reg.phys().expect("a register the allocator settled");
829 let [first, second] = probing.scratch;
830 let (limit, flag) = if bytes == first { (second, first) } else { (first, second) };
831
832 let tail: Vec<Inst> = {
833 let mut rest = self.func.insts(block).skip_while(|&inst| inst != took);
834 rest.next();
835 rest.collect()
836 };
837 let step = self.func.create_block();
838 let onto = self.func.create_block();
839 let done = self.func.create_block();
840
841 let mov = self.opcode(self.insts.moves(class).expect("a class the target can move").mov);
842 let inst = self.two(mov, sp, limit);
843 self.func.append_inst(done, inst);
844 for inst in tail {
845 self.func.remove_inst(inst);
846 self.func.append_inst(done, inst);
847 }
848 let succs = std::mem::take(self.func.succs_mut(block));
849 *self.func.succs_mut(done) = succs;
850
851 // The subtraction the lowering wrote is what the loop is instead of, so it goes. What is
852 // left in the block it was in is where the stack pointer is walking down to.
853 self.func.remove_inst(took);
854 let inst = self.two(mov, limit, sp);
855 self.func.append_inst(block, inst);
856 let grow = self.opcode(self.insts.grow);
857 let inst = self
858 .func
859 .build_loose(grow)
860 .at(span)
861 .def(Reg::physical(limit), class)
862 .uses(Reg::physical(limit), class)
863 .uses(Reg::physical(bytes), class)
864 .finish();
865 self.func.append_inst(block, inst);
866 *self.func.succs_mut(block) = vec![BlockCall::to(step)];
867
868 let inst = self.sub(probing.probe.interval);
869 self.func.append_inst(step, inst);
870 let above = self.opcode(self.insts.above);
871 let inst = self
872 .func
873 .build_loose(above)
874 .def(Reg::physical(flag), class)
875 .uses(Reg::physical(sp), class)
876 .uses(Reg::physical(limit), class)
877 .finish();
878 self.func.append_inst(step, inst);
879 let cond = Opcode::new(
880 self.names.intern(&format!("{}{}", probing.branch.prefix, probing.branch.cond)),
881 );
882 let inst = self.func.build_loose(cond).uses(Reg::physical(flag), class).finish();
883 self.func.append_inst(step, inst);
884 // The first arm is the one taken when the condition held, and the condition is that the
885 // stack pointer is still above where the array ends, so the first arm is the page it has
886 // just stepped onto being written and another time round.
887 *self.func.succs_mut(step) = vec![BlockCall::to(onto), BlockCall::to(done)];
888
889 let touch = self.touch(probing.probe);
890 self.func.append_inst(onto, touch);
891 *self.func.succs_mut(onto) = vec![BlockCall::to(step)];
892 }
893
894 /// Writes the page the stack pointer is on without changing what is there.
895 fn touch(&mut self, probe: &Probe) -> Inst {
896 let opcode = self.opcode(probe.inst);
897 let base = Operand::read(Reg::physical(self.conv.stack_pointer), self.conv.int_class);
898 self.func.build_loose(opcode).imm(0).mem(Mem::at(base)).finish()
899 }
900
901 /// Takes that many bytes off the stack pointer.
902 fn sub(&mut self, bytes: u32) -> Inst {
903 let sub = self.opcode(self.insts.sub);
904 self.arith(sub, i64::from(bytes))
905 }
906
907 /// The stack protector's check, written at the end of a block the function returns from.
908 ///
909 /// Gives back the block the epilogue goes in, which is a new one: the check has to be the last
910 /// thing the old block does, and what follows it is one of two arms rather than the return.
911 ///
912 /// ```text
913 /// block that returned reload the slot, read the word again, compare, branch
914 /// the arm it changed on call the function that does not come back, and nothing after
915 /// the arm it did not the epilogue, which the caller writes into what this gives back
916 /// ```
917 ///
918 /// The two registers are the ones the allocator was told to hold back, so nothing here has to
919 /// ask what is live: a scratch register holds nothing at the end of a block, because the only
920 /// thing that writes one is a move the rewriter put in and every one of those is read by the
921 /// instruction it was put in front of.
922 fn check(&mut self, block: Block, frame: &Frame, protect: Protect<'_>) -> Block {
923 let class = self.conv.int_class;
924 let at = frame.canary().expect("a protected function has a slot for its canary");
925 let [ours, theirs] = protect.scratch;
926
927 let inst = self.load(class, ours, at);
928 self.func.append_inst(block, inst);
929 let inst = self.read_guard(theirs, protect.guard);
930 self.func.append_inst(block, inst);
931 let differ = self.opcode(self.insts.differ);
932 let inst = self
933 .func
934 .build_loose(differ)
935 .def(Reg::physical(theirs), class)
936 .uses(Reg::physical(ours), class)
937 .uses(Reg::physical(theirs), class)
938 .finish();
939 self.func.append_inst(block, inst);
940
941 let failed = self.func.create_block();
942 let ok = self.func.create_block();
943 let cond = Opcode::new(
944 self.names.intern(&format!("{}{}", protect.branch.prefix, protect.branch.cond)),
945 );
946 let inst = self.func.build_loose(cond).uses(Reg::physical(theirs), class).finish();
947 self.func.append_inst(block, inst);
948 // The first arm is the one taken when the condition held, and the condition is that the
949 // two words differ, so the first arm is the one the canary was overwritten on.
950 *self.func.succs_mut(block) = vec![BlockCall::to(failed), BlockCall::to(ok)];
951
952 let call = self.opcode(self.insts.call);
953 let symbol = self.names.intern(protect.guard.fail);
954 self.func.build(failed, call).symbol(symbol).finish();
955 ok
956 }
957
958 /// Reads the word the canary is a copy of into a register.
959 ///
960 /// The address is a constant and names no register at all, because where the block a thread
961 /// has to itself begins is something only the machine knows and the segment register is what
962 /// holds it.
963 fn read_guard(&mut self, into: PhysReg, guard: &Guard) -> Inst {
964 let class = self.conv.int_class;
965 let load = self.opcode(self.insts.moves(class).expect("a class to load").load);
966 self.func
967 .build_loose(load)
968 .def(Reg::physical(into), class)
969 .mem(Mem::in_segment(guard.segment, guard.at))
970 .finish()
971 }
972
973 /// The instructions the epilogue is, in the order they run.
974 ///
975 /// The vector registers are read back while the stack pointer is still where the body left it,
976 /// because that is what their offsets are from. Then the stack pointer goes back to the last
977 /// register the prologue pushed, which is arithmetic when the prologue knew how far it had
978 /// moved and a read of the frame pointer when it did not.
979 fn epilogue(&mut self, frame: &Frame) -> Vec<Inst> {
980 let sp = self.conv.stack_pointer;
981 let fp = self.conv.frame_pointer;
982 let int = self.conv.int_class;
983 let sse = self.conv.sse_class;
984 let word = self.conv.word;
985 let described = !self.func.cfi.is_empty();
986 let mut out = Vec::new();
987 // Where the body left things, which is where every epilogue starts from.
988 let mut below = offset(self.conv.return_address)
989 + offset(word) * self.pushes(frame)
990 + offset(frame.size());
991 let from_sp = !frame.frame_pointer();
992 for save in frame.saved_sse() {
993 let inst = self.load(sse, save.reg, save.at);
994 out.push(inst);
995 if frame.realign().is_none() {
996 self.restored(inst, sse, save.reg);
997 }
998 }
999 let pushed = u32::try_from(frame.saved_int().len()).expect("a frame");
1000 if frame.frame_pointer() {
1001 // No row for either of these. The address is counted from the frame pointer here and
1002 // this is what moves the stack pointer rather than the frame pointer, so the rule that
1003 // was true before it is still true after it.
1004 //
1005 // Where the pointer is decides how far back this has to go. The early order left it one
1006 // word above the first push, so the pops start that many words below it. The late one
1007 // left it where the body's stack pointer was, so they start the whole frame above it,
1008 // and in both cases the distance is a constant even in a frame that grew while it ran,
1009 // which is why this is written rather than an addition to the stack pointer.
1010 let back = if frame.late() { offset(frame.size()) } else { -offset(word * pushed) };
1011 if back == 0 {
1012 let mov = self.opcode(self.insts.moves(int).expect("a move").mov);
1013 out.push(self.two(mov, sp, fp));
1014 } else {
1015 let lea = self.opcode(self.insts.lea);
1016 out.push(self.address(lea, sp, fp, back));
1017 }
1018 } else if frame.size() > 0 {
1019 let add = self.opcode(self.insts.add);
1020 let inst = self.arith(add, i64::from(frame.size()));
1021 out.push(inst);
1022 below -= offset(frame.size());
1023 self.row(inst, CfiOp::DefCfaOffset(below));
1024 }
1025 for ® in frame.saved_int().iter().rev() {
1026 let inst = self.pop(reg);
1027 out.push(inst);
1028 self.restored(inst, int, reg);
1029 below -= offset(word);
1030 if from_sp {
1031 self.row(inst, CfiOp::DefCfaOffset(below));
1032 }
1033 }
1034 if frame.frame_pointer() {
1035 let inst = self.pop(fp);
1036 out.push(inst);
1037 self.restored(inst, int, fp);
1038 // The frame pointer holds the caller's value again, so the address goes back to being
1039 // counted from the stack pointer, which by now is at the return address.
1040 let number = self.dwarf(int, sp);
1041 self.row(inst, CfiOp::DefCfa { reg: number, offset: offset(self.conv.return_address) });
1042 }
1043 let ret = self.opcode(self.insts.ret);
1044 let inst = self.func.build_loose(ret).finish();
1045 out.push(inst);
1046 // These take effect at the address just past the return, which is where the next block
1047 // begins, and the next block is body again. Popping the body's rules and pushing them
1048 // straight back leaves the stack one deep however many blocks the function returns from,
1049 // which is what makes one remembering in the prologue enough for all of them.
1050 if described {
1051 self.row(inst, CfiOp::RestoreState);
1052 self.row(inst, CfiOp::RememberState);
1053 }
1054 // And where all of it came from, which is the closing brace. Nothing here has a span of its
1055 // own: an epilogue is the frame going back the way it came and no expression in the source
1056 // asked for any of it, so without this the bytes are covered by whatever the last statement
1057 // of the body was. That is the hole the prologue used to have, at the other end, and gcc
1058 // fills it the same way it fills the other one, with the brace. A function whose body this
1059 // does not know is left alone and keeps covering those bytes with the last row before them.
1060 let closing = ending(self.func.declared);
1061 if !closing.is_dummy() {
1062 for &inst in &out {
1063 self.func.set_span(inst, closing);
1064 }
1065 }
1066 out
1067 }
1068
1069 /// How many general purpose registers the prologue put on the stack, the frame pointer
1070 /// included.
1071 fn pushes(&self, frame: &Frame) -> i32 {
1072 let saved = i32::try_from(frame.saved_int().len()).expect("a frame");
1073 saved + i32::from(frame.frame_pointer())
1074 }
1075
1076 /// One row of the unwind table, taking effect after that instruction.
1077 fn row(&mut self, inst: Inst, op: CfiOp) {
1078 self.func.cfi.push((inst, op));
1079 }
1080
1081 /// A row saying the caller's copy of that register is that far from the canonical frame
1082 /// address, which is below it and so is negative.
1083 fn saved(&mut self, inst: Inst, class: RegClass, reg: PhysReg, from_cfa: i32) {
1084 let number = self.dwarf(class, reg);
1085 self.row(inst, CfiOp::Offset { reg: number, offset: from_cfa });
1086 }
1087
1088 /// A row saying that register holds what the caller left in it again.
1089 fn restored(&mut self, inst: Inst, class: RegClass, reg: PhysReg) {
1090 let number = self.dwarf(class, reg);
1091 self.row(inst, CfiOp::Restore(number));
1092 }
1093
1094 /// What an unwind table calls that register.
1095 fn dwarf(&self, class: RegClass, reg: PhysReg) -> u16 {
1096 self.conv.dwarf(class, reg).expect("a register a frame saves is one the table can name")
1097 }
1098
1099 /// One edit as the instruction that makes it true.
1100 fn mov(&mut self, edit: &Edit, frame: &Frame) -> Inst {
1101 let moves = self.insts.moves(edit.class).expect("a class the target says how to move");
1102 match (edit.mov.to, edit.mov.from) {
1103 (Place::Reg(to), Place::Reg(from)) => {
1104 let mov = self.opcode(moves.mov);
1105 self.func
1106 .build_loose(mov)
1107 .def(Reg::physical(to), edit.class)
1108 .uses(Reg::physical(from), edit.class)
1109 .finish()
1110 }
1111 (Place::Reg(to), Place::Slot(slot)) => {
1112 let at = self.slot(frame, slot);
1113 self.load(edit.class, to, at)
1114 }
1115 (Place::Slot(slot), Place::Reg(from)) => {
1116 let at = self.slot(frame, slot);
1117 self.store(edit.class, from, at)
1118 }
1119 // The allocator expands this into two moves through a register of its own, because a
1120 // machine that could do it in one is not a machine any of this is written for.
1121 (Place::Slot(_), Place::Slot(_)) => {
1122 unreachable!("a move from one stack slot straight into another")
1123 }
1124 }
1125 }
1126
1127 /// Puts an instruction where an edit says it goes, after whatever earlier edits went there.
1128 ///
1129 /// The edits at one place are in the order they have to be made in, so each one goes behind
1130 /// the last, and the first of them is what the place itself means.
1131 fn put(&mut self, cursors: &mut HashMap<At, Inst>, at: At, inst: Inst) {
1132 if let Some(cursor) = cursors.get_mut(&at) {
1133 self.func.insert_after(*cursor, inst);
1134 *cursor = inst;
1135 return;
1136 }
1137 match at {
1138 At::Before(before) => self.func.insert_before(before, inst),
1139 At::After(after) => self.func.insert_after(after, inst),
1140 At::StartOf(block) => self.func.prepend_inst(block, inst),
1141 // Behind everything in the block. A block the allocator puts an edge's moves at the
1142 // end of is one with a single edge out of it, and an edge like that is not an
1143 // instruction here: [`crate::layout`] writes the jump it becomes after this has run.
1144 // So the last instruction is an ordinary one, which may still be waiting on moves of
1145 // its own that have to be made before the edge's are.
1146 At::EndOf(block) => self.func.append_inst(block, inst),
1147 }
1148 cursors.insert(at, inst);
1149 }
1150
1151 /// Where a spill slot is, from the stack pointer in the body of the function.
1152 fn slot(&self, frame: &Frame, slot: u32) -> i32 {
1153 frame.slot(slot).expect("a slot the frame was worked out from")
1154 }
1155
1156 /// Reads a register out of the frame.
1157 fn load(&mut self, class: RegClass, reg: PhysReg, at: i32) -> Inst {
1158 let load = self.opcode(self.insts.moves(class).expect("a class to load").load);
1159 let base = Operand::read(Reg::physical(self.base), self.conv.int_class);
1160 self.func
1161 .build_loose(load)
1162 .def(Reg::physical(reg), class)
1163 .mem(Mem::at(base).plus(at))
1164 .finish()
1165 }
1166
1167 /// Writes a register into the frame.
1168 fn store(&mut self, class: RegClass, reg: PhysReg, at: i32) -> Inst {
1169 let store = self.opcode(self.insts.moves(class).expect("a class to store").store);
1170 let base = Operand::read(Reg::physical(self.base), self.conv.int_class);
1171 self.func
1172 .build_loose(store)
1173 .uses(Reg::physical(reg), class)
1174 .mem(Mem::at(base).plus(at))
1175 .finish()
1176 }
1177
1178 /// Puts a general purpose register on the stack.
1179 fn push(&mut self, reg: PhysReg) -> Inst {
1180 let push = self.opcode(self.insts.push);
1181 self.func.build_loose(push).uses(Reg::physical(reg), self.conv.int_class).finish()
1182 }
1183
1184 /// Takes a general purpose register back off the stack.
1185 fn pop(&mut self, reg: PhysReg) -> Inst {
1186 let pop = self.opcode(self.insts.pop);
1187 self.func.build_loose(pop).def(Reg::physical(reg), self.conv.int_class).finish()
1188 }
1189
1190 /// One general purpose register written with another.
1191 fn two(&mut self, opcode: Opcode, to: PhysReg, from: PhysReg) -> Inst {
1192 let class = self.conv.int_class;
1193 self.func
1194 .build_loose(opcode)
1195 .def(Reg::physical(to), class)
1196 .uses(Reg::physical(from), class)
1197 .finish()
1198 }
1199
1200 /// Two-address arithmetic on the stack pointer, which reads it and writes it back.
1201 fn arith(&mut self, opcode: Opcode, value: i64) -> Inst {
1202 let class = self.conv.int_class;
1203 let sp = Reg::physical(self.conv.stack_pointer);
1204 self.func.build_loose(opcode).def(sp, class).uses(sp, class).imm(value).finish()
1205 }
1206
1207 /// One register written with an address rather than with what is at it.
1208 fn address(&mut self, opcode: Opcode, to: PhysReg, base: PhysReg, disp: i32) -> Inst {
1209 let class = self.conv.int_class;
1210 let base = Operand::read(Reg::physical(base), class);
1211 self.func
1212 .build_loose(opcode)
1213 .def(Reg::physical(to), class)
1214 .mem(Mem::at(base).plus(disp))
1215 .finish()
1216 }
1217
1218 /// The opcode of that name, in the machine IR's spelling, which is the target's prefix and
1219 /// then the name the target gave.
1220 fn opcode(&mut self, name: &str) -> Opcode {
1221 Opcode::new(self.names.intern(&format!("{}{name}", self.insts.prefix)))
1222 }
1223}
1224
1225/// A distance in a frame, as the signed number every offset is.
1226fn offset(bytes: u32) -> i32 {
1227 i32::try_from(bytes).expect("a frame under two gigabytes")
1228}
1229
1230/// The last character of a span, which for the span of a function body is its closing brace.
1231///
1232/// A span runs from the first byte to one past the last, so the brace is the byte before the end
1233/// rather than the end. [`Span::DUMMY`] for a function that came from no C source, which is what
1234/// the tests and the IR parser build, and for the empty span that cannot have a last character.
1235fn ending(body: Span) -> Span {
1236 if body.is_dummy() || body.hi <= body.lo {
1237 return Span::DUMMY;
1238 }
1239 Span::new(body.hi - 1, body.hi)
1240}
1241
1242#[cfg(test)]
1243mod tests {
1244 use rucc_base::Interner;
1245 use rucc_mir::{BlockCall, print_func};
1246 use rucc_regalloc::assign::Env;
1247 use rucc_target::x86_64::{
1248 BRANCH, FRAME, GPR, PROBE, R10, R11, RAX, REGS, SYSV, WIN64, XMM, xmm,
1249 };
1250
1251 use super::*;
1252 use crate::frame::{Layout, Local};
1253
1254 /// The closing brace of a body is the last character of its span and not the end of it, since a
1255 /// span runs to one past what it covers. A function that came from no source has no brace and
1256 /// asks for no row, which is what keeps the epilogue of one the IR parser built covered by the
1257 /// row before it rather than by a position in a file that is not there.
1258 #[test]
1259 fn the_end_of_a_body_is_its_closing_brace_and_not_one_past_it() {
1260 assert_eq!(ending(Span::new(10, 40)), Span::new(39, 40));
1261 assert_eq!(ending(Span::DUMMY), Span::DUMMY);
1262 assert_eq!(ending(Span::new(7, 7)), Span::DUMMY);
1263 }
1264
1265 /// An environment offering that many of the convention's registers, with everything after
1266 /// them held back as scratch.
1267 fn env(conv: &CallRegs, count: usize) -> Env {
1268 Env::new().with(GPR, &conv.int_order[..count], &conv.int_order[count..])
1269 }
1270
1271 /// A function of that many values, every one written before any is read, allocated with that
1272 /// many registers to hand out. The same shape the frame layout's own tests are written
1273 /// against, so that a frame here is one that has already been checked there.
1274 fn pressure(conv: &CallRegs, values: usize, count: usize) -> (Func, Allocation, Interner) {
1275 let mut names = Interner::new();
1276 let mut func = Func::new(names.intern("f"));
1277 let opcode = Opcode::new(names.intern("x64.nop"));
1278 let block = func.create_block();
1279 let regs: Vec<Reg> = (0..values).map(|_| func.new_vreg(GPR)).collect();
1280 for ® in ®s {
1281 func.build(block, opcode).def(reg, GPR).finish();
1282 }
1283 for ® in ®s {
1284 func.build(block, opcode).uses(reg, GPR).finish();
1285 }
1286 let allocation = rucc_regalloc::run(&mut func, &env(conv, count), "test", true);
1287 (func, allocation, names)
1288 }
1289
1290 /// The function with its frame written into it, as the lines a dump would show.
1291 fn written(
1292 func: &mut Func,
1293 allocation: &Allocation,
1294 layout: &Layout<'_>,
1295 names: &mut Interner,
1296 ) -> Vec<String> {
1297 with_protector(func, allocation, layout, None, names)
1298 }
1299
1300 /// The same, for a function the caller has decided is protected or is not.
1301 fn with_protector(
1302 func: &mut Func,
1303 allocation: &Allocation,
1304 layout: &Layout<'_>,
1305 protect: Option<Protect<'_>>,
1306 names: &mut Interner,
1307 ) -> Vec<String> {
1308 let convention = Convention { protect, ..Convention::new(layout.conv, &FRAME) };
1309 under(func, allocation, layout, &Stack::default(), convention, names)
1310 }
1311
1312 /// The same, for a function whose frame the caller has decided is taken a page at a time.
1313 fn with_probing(
1314 func: &mut Func,
1315 allocation: &Allocation,
1316 layout: &Layout<'_>,
1317 probe: Option<Probing<'_>>,
1318 names: &mut Interner,
1319 ) -> Vec<String> {
1320 let convention = Convention { probe, ..Convention::new(layout.conv, &FRAME) };
1321 under(func, allocation, layout, &Stack::default(), convention, names)
1322 }
1323
1324 /// A function whose one block takes a run of bytes off the stack pointer, which is what the
1325 /// lowering writes for a variable length array, with the count already in the register given.
1326 fn growing(count: PhysReg) -> (Func, Allocation, Interner, Stack) {
1327 let mut names = Interner::new();
1328 let mut func = Func::new(names.intern("f"));
1329 let block = func.create_block();
1330 let sp = Reg::physical(SYSV.stack_pointer);
1331 let grow = Opcode::new(names.intern("x64.sub_rr_64"));
1332 let took = func
1333 .build(block, grow)
1334 .def(sp, GPR)
1335 .uses(sp, GPR)
1336 .uses(Reg::physical(count), GPR)
1337 .finish();
1338 let nop = Opcode::new(names.intern("x64.nop"));
1339 func.build(block, nop).finish();
1340 let allocation = rucc_regalloc::run(&mut func, &env(&SYSV, 4), "test", true);
1341 (func, allocation, names, Stack { grown: vec![took], ..Stack::default() })
1342 }
1343
1344 /// The function with its frame written into it under that convention.
1345 fn under(
1346 func: &mut Func,
1347 allocation: &Allocation,
1348 layout: &Layout<'_>,
1349 stack: &Stack,
1350 convention: Convention<'_>,
1351 names: &mut Interner,
1352 ) -> Vec<String> {
1353 let frame = Frame::of(func, allocation, layout);
1354 finish(func, allocation, &frame, stack, convention, names);
1355 print_func(func, names, ®S)
1356 .lines()
1357 .filter(|line| !line.is_empty())
1358 .map(|line| line.trim().to_string())
1359 .collect()
1360 }
1361
1362 /// Just the lines the frame put in, which is every line that is not the function it was
1363 /// given and not the shape of the dump around it.
1364 fn added(lines: &[String]) -> Vec<&str> {
1365 lines
1366 .iter()
1367 .map(String::as_str)
1368 .filter(|line| !line.contains("x64.nop"))
1369 .filter(|line| !line.starts_with("mfunc") && !line.starts_with("block") && *line != "}")
1370 .collect()
1371 }
1372
1373 #[test]
1374 fn a_function_that_needs_no_frame_is_given_a_return_and_nothing_else() {
1375 let (mut func, allocation, mut names) = pressure(&SYSV, 2, 4);
1376 let lines = written(&mut func, &allocation, &Layout::new(&SYSV, REGS), &mut names);
1377
1378 // Two values and four registers, so nothing is spilled, nothing is saved and the stack
1379 // pointer never moves. A prologue of nothing is the right prologue for that.
1380 assert_eq!(added(&lines), ["x64.ret"]);
1381 }
1382
1383 /// The bytes that give a frame back are filed under the closing brace, which is where a
1384 /// debugger says a function ends and which nothing in an epilogue could say for itself.
1385 #[test]
1386 fn an_epilogue_is_filed_under_the_closing_brace_of_the_body() {
1387 let (mut func, allocation, mut names) = pressure(&SYSV, 4, 2);
1388 func.declared = Span::new(100, 140);
1389 let base = Layout::new(&SYSV, REGS);
1390 let layout = Layout { red_zone: false, ..base };
1391 written(&mut func, &allocation, &layout, &mut names);
1392
1393 // Everything from the first instruction of the epilogue to the return, and nothing above
1394 // it: the body's own instructions keep the spans they arrived with, which here is none.
1395 let ends: Vec<Span> = func
1396 .blocks()
1397 .flat_map(|block| func.insts(block).collect::<Vec<_>>())
1398 .map(|inst| func.span(inst))
1399 .filter(|span| !span.is_dummy())
1400 .collect();
1401 assert!(!ends.is_empty(), "an epilogue was written");
1402 assert!(ends.iter().all(|&span| span == Span::new(139, 140)), "{ends:?}");
1403 }
1404
1405 #[test]
1406 fn a_spill_is_a_store_and_a_reload_is_a_load() {
1407 let (mut func, allocation, mut names) = pressure(&SYSV, 4, 2);
1408 let lines = written(&mut func, &allocation, &Layout::new(&SYSV, REGS), &mut names);
1409
1410 // Two registers for four values, so two of them go to the stack. The store goes behind the
1411 // instruction that wrote the value and the load in front of the one that wants it, both at
1412 // the offsets the frame gave, which are below the stack pointer because a small leaf
1413 // function is entitled to the red zone.
1414 assert_eq!(
1415 lines,
1416 [
1417 "mfunc @f {",
1418 "block0:",
1419 "$rax = x64.nop",
1420 "$rcx = x64.nop",
1421 "$rdx = x64.nop",
1422 "x64.mov_mr_64 $rdx, [$rsp - 16]",
1423 "$rdx = x64.nop",
1424 "x64.mov_mr_64 $rdx, [$rsp - 8]",
1425 "x64.nop $rax",
1426 "x64.nop $rcx",
1427 "$rdx = x64.mov_rm_64 [$rsp - 16]",
1428 "x64.nop $rdx",
1429 "$rdx = x64.mov_rm_64 [$rsp - 8]",
1430 "x64.nop $rdx",
1431 "x64.ret",
1432 "}",
1433 ]
1434 );
1435 }
1436
1437 #[test]
1438 fn the_frame_the_prologue_takes_is_the_frame_the_epilogue_gives_back() {
1439 let (mut func, allocation, mut names) = pressure(&SYSV, 4, 2);
1440 let base = Layout::new(&SYSV, REGS);
1441 let layout = Layout { red_zone: false, ..base };
1442 let lines = written(&mut func, &allocation, &layout, &mut names);
1443
1444 // The same function told it may not use the red zone takes sixteen bytes instead, and
1445 // every offset moves above the stack pointer to match.
1446 assert_eq!(
1447 added(&lines),
1448 [
1449 "$rsp = x64.sub_ri_64 $rsp, 16",
1450 "x64.mov_mr_64 $rdx, [$rsp]",
1451 "x64.mov_mr_64 $rdx, [$rsp + 8]",
1452 "$rdx = x64.mov_rm_64 [$rsp]",
1453 "$rdx = x64.mov_rm_64 [$rsp + 8]",
1454 "$rsp = x64.add_ri_64 $rsp, 16",
1455 "x64.ret",
1456 ]
1457 );
1458 }
1459
1460 #[test]
1461 fn the_registers_the_prologue_pushes_come_back_in_the_opposite_order() {
1462 let (mut func, allocation, mut names) = pressure(&SYSV, 13, 13);
1463 let lines = written(&mut func, &allocation, &Layout::new(&SYSV, REGS), &mut names);
1464
1465 // Four registers a call leaves alone, pushed in the convention's order and popped in the
1466 // other one, which is the only order that gets each of them its own value back.
1467 assert_eq!(
1468 added(&lines),
1469 [
1470 "x64.push_64 $rbx",
1471 "x64.push_64 $r12",
1472 "x64.push_64 $r13",
1473 "x64.push_64 $r14",
1474 "$r14 = x64.pop_64",
1475 "$r13 = x64.pop_64",
1476 "$r12 = x64.pop_64",
1477 "$rbx = x64.pop_64",
1478 "x64.ret",
1479 ]
1480 );
1481 }
1482
1483 #[test]
1484 fn a_function_that_keeps_a_frame_pointer_sets_it_up_and_leaves_by_it() {
1485 let (mut func, allocation, mut names) = pressure(&SYSV, 4, 2);
1486 let base = Layout::new(&SYSV, REGS);
1487 let layout = Layout { frame_pointer: true, red_zone: false, ..base };
1488 let lines = written(&mut func, &allocation, &layout, &mut names);
1489
1490 // The frame pointer is saved before anything else and points at where it was saved, so the
1491 // epilogue reaches the stack pointer through it rather than by counting the frame back.
1492 assert_eq!(
1493 added(&lines),
1494 [
1495 "x64.push_64 $rbp",
1496 "$rbp = x64.mov_rr_64 $rsp",
1497 "$rsp = x64.sub_ri_64 $rsp, 16",
1498 "x64.mov_mr_64 $rdx, [$rsp]",
1499 "x64.mov_mr_64 $rdx, [$rsp + 8]",
1500 "$rdx = x64.mov_rm_64 [$rsp]",
1501 "$rdx = x64.mov_rm_64 [$rsp + 8]",
1502 "$rsp = x64.mov_rr_64 $rbp",
1503 "$rbp = x64.pop_64",
1504 "x64.ret",
1505 ]
1506 );
1507 }
1508
1509 #[test]
1510 fn a_realigned_frame_forces_the_alignment_after_it_has_pushed_what_it_saves() {
1511 let (mut func, allocation, mut names) = pressure(&SYSV, 13, 13);
1512 let locals = [Local { size: 64, align: 32 }];
1513 let base = Layout::new(&SYSV, REGS);
1514 let layout = Layout { locals: &locals, ..base };
1515 let lines = written(&mut func, &allocation, &layout, &mut names);
1516
1517 // Forcing the alignment throws away how far the stack pointer had moved, so the registers
1518 // are pushed before it happens and the epilogue counts back from the frame pointer to find
1519 // them. The frame pointer is required here whatever the flags said.
1520 assert_eq!(
1521 added(&lines),
1522 [
1523 "x64.push_64 $rbp",
1524 "$rbp = x64.mov_rr_64 $rsp",
1525 "x64.push_64 $rbx",
1526 "x64.push_64 $r12",
1527 "x64.push_64 $r13",
1528 "x64.push_64 $r14",
1529 "$rsp = x64.and_ri_64 $rsp, -32",
1530 "$rsp = x64.sub_ri_64 $rsp, 64",
1531 "$rsp = x64.lea_64 [$rbp - 32]",
1532 "$r14 = x64.pop_64",
1533 "$r13 = x64.pop_64",
1534 "$r12 = x64.pop_64",
1535 "$rbx = x64.pop_64",
1536 "$rbp = x64.pop_64",
1537 "x64.ret",
1538 ]
1539 );
1540 }
1541
1542 #[test]
1543 fn every_block_the_function_returns_from_gets_an_epilogue() {
1544 let mut names = Interner::new();
1545 let mut func = Func::new(names.intern("f"));
1546 let opcode = Opcode::new(names.intern("x64.nop"));
1547 let head = func.create_block();
1548 let left = func.create_block();
1549 let right = func.create_block();
1550 func.build(head, opcode).finish();
1551 *func.succs_mut(head) = vec![BlockCall::to(left), BlockCall::to(right)];
1552 func.build(left, opcode).finish();
1553 func.build(right, opcode).finish();
1554 let allocation = rucc_regalloc::run(&mut func, &env(&SYSV, 4), "test", true);
1555 let base = Layout::new(&SYSV, REGS);
1556 let layout = Layout { leaf: false, ..base };
1557 let lines = written(&mut func, &allocation, &layout, &mut names);
1558
1559 // Both ways out get the frame given back, and the block that goes somewhere gets nothing,
1560 // because a block with an edge out of it is not a block anything returns from.
1561 assert_eq!(
1562 lines,
1563 [
1564 "mfunc @f {",
1565 "block0:",
1566 "$rsp = x64.sub_ri_64 $rsp, 8",
1567 "x64.nop block1, block2",
1568 "block1:",
1569 "x64.nop",
1570 "$rsp = x64.add_ri_64 $rsp, 8",
1571 "x64.ret",
1572 "block2:",
1573 "x64.nop",
1574 "$rsp = x64.add_ri_64 $rsp, 8",
1575 "x64.ret",
1576 "}",
1577 ]
1578 );
1579 }
1580
1581 #[test]
1582 fn a_protected_function_writes_the_canary_last_and_checks_it_before_it_returns() {
1583 let (mut func, allocation, mut names) = pressure(&SYSV, 4, 2);
1584 let base = Layout::new(&SYSV, REGS);
1585 let layout = Layout { leaf: false, protect: true, ..base };
1586 let guard = SYSV.guard.as_ref().expect("this convention has somewhere to keep the word");
1587 // The two the real pipeline holds back, which are held back in the environment above too:
1588 // it hands out the first two of the convention's order and keeps everything after them.
1589 let protect = Protect { guard, branch: &BRANCH, scratch: [R10, R11] };
1590 let lines = with_protector(&mut func, &allocation, &layout, Some(protect), &mut names);
1591
1592 // The read of the word and the store into the slot come after the stack pointer has moved,
1593 // because there is no slot to store into until it has. The check is the last thing the
1594 // block that returned does and the epilogue is on the arm the canary was unchanged on, so
1595 // a function whose canary changed never gives its frame back and never returns.
1596 assert_eq!(
1597 added(&lines),
1598 [
1599 "$rsp = x64.sub_ri_64 $rsp, 24",
1600 "$r10 = x64.mov_rm_64 [fs:40]",
1601 "x64.mov_mr_64 $r10, [$rsp + 16]",
1602 "x64.mov_mr_64 $rdx, [$rsp]",
1603 "x64.mov_mr_64 $rdx, [$rsp + 8]",
1604 "$rdx = x64.mov_rm_64 [$rsp]",
1605 "$rdx = x64.mov_rm_64 [$rsp + 8]",
1606 "$r10 = x64.mov_rm_64 [$rsp + 16]",
1607 "$r11 = x64.mov_rm_64 [fs:40]",
1608 "$r11 = x64.cmp_set_ne_64 $r10, $r11",
1609 "x64.br_cond_8 $r11, block1, block2",
1610 "x64.call @__stack_chk_fail",
1611 "$rsp = x64.add_ri_64 $rsp, 24",
1612 "x64.ret",
1613 ]
1614 );
1615 }
1616
1617 #[test]
1618 fn a_frame_that_fits_in_one_page_is_taken_in_one_subtraction_even_when_pages_are_touched() {
1619 let (mut func, allocation, mut names) = pressure(&SYSV, 2, 4);
1620 let locals = [Local { size: 4088, align: 16 }];
1621 let base = Layout::new(&SYSV, REGS);
1622 let layout = Layout { leaf: false, locals: &locals, ..base };
1623 let probing = Probing { probe: &PROBE, branch: &BRANCH, scratch: [R10, R11] };
1624 let lines = with_probing(&mut func, &allocation, &layout, Some(probing), &mut names);
1625
1626 // A frame of one page cannot step over the page below it, because the far end of it is the
1627 // near end of that page and anything written there is written to a page that is there. So
1628 // the flag costs such a function nothing, which is most functions.
1629 assert_eq!(
1630 added(&lines),
1631 ["$rsp = x64.sub_ri_64 $rsp, 4088", "$rsp = x64.add_ri_64 $rsp, 4088", "x64.ret",]
1632 );
1633 }
1634
1635 #[test]
1636 fn a_probing_prologue_touches_every_page_of_a_frame_a_few_pages_deep() {
1637 let (mut func, allocation, mut names) = pressure(&SYSV, 2, 4);
1638 let locals = [Local { size: 9000, align: 16 }];
1639 let base = Layout::new(&SYSV, REGS);
1640 let layout = Layout { leaf: false, locals: &locals, ..base };
1641 let probing = Probing { probe: &PROBE, branch: &BRANCH, scratch: [R10, R11] };
1642 let lines = with_probing(&mut func, &allocation, &layout, Some(probing), &mut names);
1643
1644 // A page of the stack pointer's own, then the touch that says the page is there, and only
1645 // then the next one, which is the whole of the defence: nothing here ever moves the stack
1646 // pointer further than one page without writing where it landed. The last subtraction is
1647 // the remainder and is smaller than a page, so it needs no touch of its own, and it exists
1648 // in every frame because the count of pages is taken off one less than the size.
1649 assert_eq!(
1650 added(&lines),
1651 [
1652 "$rsp = x64.sub_ri_64 $rsp, 4096",
1653 "x64.or_mi_8 [$rsp], 0",
1654 "$rsp = x64.sub_ri_64 $rsp, 4096",
1655 "x64.or_mi_8 [$rsp], 0",
1656 "$rsp = x64.sub_ri_64 $rsp, 808",
1657 "$rsp = x64.add_ri_64 $rsp, 9000",
1658 "x64.ret",
1659 ]
1660 );
1661 }
1662
1663 #[test]
1664 fn a_variable_length_array_walks_its_pages_where_the_declaration_stands() {
1665 let (mut func, allocation, mut names, stack) = growing(RAX);
1666 let base = Layout::new(&SYSV, REGS);
1667 let layout = Layout { leaf: false, grows: true, ..base };
1668 let probing = Probing { probe: &PROBE, branch: &BRANCH, scratch: [R10, R11] };
1669 let convention = Convention { probe: Some(probing), ..Convention::new(&SYSV, &FRAME) };
1670 let lines = under(&mut func, &allocation, &layout, &stack, convention, &mut names);
1671
1672 // The whole listing, because what the walk is cannot be read off the instructions alone.
1673 // The one subtraction the lowering wrote is gone and four blocks stand where its block was:
1674 // where the stack pointer is going, the step, the page the step landed on, and the rest of
1675 // what the block was doing with the stack pointer put back where it was going.
1676 assert_eq!(
1677 lines,
1678 [
1679 "mfunc @f {",
1680 "block0:",
1681 "x64.push_64 $rbp",
1682 "$rbp = x64.mov_rr_64 $rsp",
1683 "$r10 = x64.mov_rr_64 $rsp",
1684 "$r10 = x64.sub_rr_64 $r10, $rax, block1",
1685 "block1:",
1686 "$rsp = x64.sub_ri_64 $rsp, 4096",
1687 "$r11 = x64.cmp_set_a_64 $rsp, $r10",
1688 "x64.br_cond_8 $r11, block2, block3",
1689 "block2:",
1690 "x64.or_mi_8 [$rsp], 0, block1",
1691 "block3:",
1692 "$rsp = x64.mov_rr_64 $r10",
1693 "x64.nop",
1694 "$rsp = x64.mov_rr_64 $rbp",
1695 "$rbp = x64.pop_64",
1696 "x64.ret",
1697 "}",
1698 ]
1699 );
1700 }
1701
1702 #[test]
1703 fn the_walk_keeps_the_register_the_count_arrived_in() {
1704 let (mut func, allocation, mut names, stack) = growing(R10);
1705 let base = Layout::new(&SYSV, REGS);
1706 let layout = Layout { leaf: false, grows: true, ..base };
1707 let probing = Probing { probe: &PROBE, branch: &BRANCH, scratch: [R10, R11] };
1708 let convention = Convention { probe: Some(probing), ..Convention::new(&SYSV, &FRAME) };
1709 let lines = under(&mut func, &allocation, &layout, &stack, convention, &mut names);
1710
1711 // The count is in the first of the two registers the walk was given, which is where a
1712 // reload the rewriter wrote would have put it, so the limit goes in the other one and the
1713 // comparison writes the first one back only once the count has been read for the last time.
1714 let added = added(&lines);
1715 assert!(added.contains(&"$r11 = x64.mov_rr_64 $rsp"), "{added:?}");
1716 assert!(added.contains(&"$r11 = x64.sub_rr_64 $r11, $r10, block1"), "{added:?}");
1717 assert!(added.contains(&"$r10 = x64.cmp_set_a_64 $rsp, $r11"), "{added:?}");
1718 }
1719
1720 #[test]
1721 fn a_variable_length_array_takes_its_bytes_in_one_subtraction_when_nothing_asked() {
1722 let (mut func, allocation, mut names, stack) = growing(RAX);
1723 let base = Layout::new(&SYSV, REGS);
1724 let layout = Layout { leaf: false, grows: true, ..base };
1725 let convention = Convention::new(&SYSV, &FRAME);
1726 let lines = under(&mut func, &allocation, &layout, &stack, convention, &mut names);
1727
1728 // The instruction the lowering wrote, where it wrote it, and one block still.
1729 assert!(lines.contains(&"$rsp = x64.sub_rr_64 $rsp, $rax".to_owned()), "{lines:?}");
1730 assert_eq!(lines.iter().filter(|line| line.starts_with("block")).count(), 1, "{lines:?}");
1731 }
1732
1733 #[test]
1734 fn a_probing_prologue_deeper_than_that_walks_the_pages_in_a_loop() {
1735 let (mut func, allocation, mut names) = pressure(&SYSV, 2, 4);
1736 let locals = [Local { size: 100_000, align: 16 }];
1737 let base = Layout::new(&SYSV, REGS);
1738 let layout = Layout { leaf: false, locals: &locals, ..base };
1739 let probing = Probing { probe: &PROBE, branch: &BRANCH, scratch: [R10, R11] };
1740 let lines = with_probing(&mut func, &allocation, &layout, Some(probing), &mut names);
1741
1742 // Twenty-four pages, which is more than a straight line is worth, so the prologue works out
1743 // where it is going first and then walks there. The whole listing rather than the added
1744 // lines, because what matters as much as the instructions is that the two blocks the walk
1745 // is made of come in front of the block the function began with: the body the allocator
1746 // filled is block2 here and it was block0 before this ran.
1747 assert_eq!(
1748 lines,
1749 [
1750 "mfunc @f {",
1751 "block0:",
1752 "$r10 = x64.lea_64 [$rsp - 98304], block1",
1753 "block1:",
1754 "$rsp = x64.sub_ri_64 $rsp, 4096",
1755 "x64.or_mi_8 [$rsp], 0",
1756 "$r11 = x64.cmp_set_ne_64 $rsp, $r10",
1757 "x64.br_cond_8 $r11, block1, block2",
1758 "block2:",
1759 "$rsp = x64.sub_ri_64 $rsp, 1704",
1760 "$rax = x64.nop",
1761 "$rcx = x64.nop",
1762 "x64.nop $rax",
1763 "x64.nop $rcx",
1764 "$rsp = x64.add_ri_64 $rsp, 100008",
1765 "x64.ret",
1766 "}",
1767 ]
1768 );
1769 }
1770
1771 #[test]
1772 fn a_large_frame_on_a_platform_with_a_routine_for_its_pages_calls_the_routine() {
1773 let (mut func, allocation, mut names) = pressure(&WIN64, 2, 4);
1774 let locals = [Local { size: 100_000, align: 16 }];
1775 let base = Layout::new(&WIN64, REGS);
1776 let layout = Layout { leaf: false, locals: &locals, ..base };
1777 let lines = written(&mut func, &allocation, &layout, &mut names);
1778
1779 // Nothing asked for this on the command line, which is the point: Windows commits a stack
1780 // by having the pages touched in order, so a frame this size has to reach them whatever the
1781 // flags said. The size goes in the register the platform names, the routine touches every
1782 // page down to there, and the frame is taken afterwards, because the routine comes back
1783 // having moved nothing. What the epilogue gives back is what the register was given, which
1784 // is the one thing worth tying together here.
1785 let added = added(&lines);
1786 assert_eq!(added.len(), 5, "{added:?}");
1787 let size = added[0].strip_prefix("$rax = x64.mov_ri_64 ").expect("a size in a register");
1788 assert_eq!(added[1], "x64.call @__chkstk");
1789 assert_eq!(added[2], "$rsp = x64.sub_rr_64 $rsp, $rax");
1790 assert_eq!(added[3], format!("$rsp = x64.add_ri_64 $rsp, {size}"));
1791 assert_eq!(added[4], "x64.ret");
1792 }
1793
1794 #[test]
1795 fn a_frame_of_one_page_calls_nothing_on_that_platform_either() {
1796 let (mut func, allocation, mut names) = pressure(&WIN64, 2, 4);
1797 let locals = [Local { size: 4000, align: 16 }];
1798 let base = Layout::new(&WIN64, REGS);
1799 let layout = Layout { leaf: false, locals: &locals, ..base };
1800 let lines = written(&mut func, &allocation, &layout, &mut names);
1801
1802 // The same reason a frame of one page is taken in one subtraction under the flag. The far
1803 // end of such a frame is inside the page below the stack pointer, and touching that page is
1804 // what the function does on its way to using the frame at all, so there is nothing for a
1805 // routine to do and a call to it would be a call in every function that declares an array.
1806 let added = added(&lines);
1807 assert!(added.iter().all(|line| !line.contains("chkstk")), "{added:?}");
1808 assert_eq!(added.len(), 3, "{added:?}");
1809 }
1810
1811 #[test]
1812 fn a_windows_prologue_points_its_frame_pointer_at_the_frame_once_the_frame_is_whole() {
1813 let (mut func, allocation, mut names) = pressure(&WIN64, 4, 2);
1814 let base = Layout::new(&WIN64, REGS);
1815 let layout = Layout { frame_pointer: true, ..base };
1816 let lines = written(&mut func, &allocation, &layout, &mut names);
1817
1818 // The other order, which is what every other platform here writes, has no unwind record on
1819 // this one: the record counts its slots from where the stack pointer ends the prologue and
1820 // gets there by taking a constant off the frame pointer, so a register pushed after the
1821 // pointer was established sits below the place the record counts from. Pushing first and
1822 // pointing last is the order that has a record, and it leaves the pointer holding a copy of
1823 // the stack pointer, so the spills stay where they were and the epilogue counts the frame
1824 // back off the pointer rather than moving the pointer into the stack pointer.
1825 assert_eq!(
1826 added(&lines),
1827 [
1828 "x64.push_64 $rbp",
1829 "$rsp = x64.sub_ri_64 $rsp, 16",
1830 "$rbp = x64.mov_rr_64 $rsp",
1831 "x64.mov_mr_64 $rdx, [$rsp]",
1832 "x64.mov_mr_64 $rdx, [$rsp + 8]",
1833 "$rdx = x64.mov_rm_64 [$rsp]",
1834 "$rdx = x64.mov_rm_64 [$rsp + 8]",
1835 "$rsp = x64.lea_64 [$rbp + 16]",
1836 "$rbp = x64.pop_64",
1837 "x64.ret",
1838 ]
1839 );
1840 }
1841
1842 #[test]
1843 fn a_windows_prologue_that_saves_registers_too_pushes_all_of_them_before_the_frame() {
1844 let (mut func, allocation, mut names) = pressure(&WIN64, 9, 8);
1845 let base = Layout::new(&WIN64, REGS);
1846 let layout = Layout { leaf: false, frame_pointer: true, ..base };
1847 let lines = written(&mut func, &allocation, &layout, &mut names);
1848
1849 // The shape that made the order necessary. All three pushes are above the frame, so every
1850 // one of them has a row the record can write, and the pointer is the last thing the
1851 // prologue does. Forty eight bytes is the thirty two every Windows caller reserves below a
1852 // call, eight for the one value that did not fit in a register, and eight that put the
1853 // stack pointer back where a call wants it given three pushes and the return address.
1854 assert_eq!(
1855 added(&lines),
1856 [
1857 "x64.push_64 $rbp",
1858 "x64.push_64 $rbx",
1859 "x64.push_64 $rsi",
1860 "$rsp = x64.sub_ri_64 $rsp, 48",
1861 "$rbp = x64.mov_rr_64 $rsp",
1862 "x64.mov_mr_64 $rsi, [$rsp + 32]",
1863 "$rsi = x64.mov_rm_64 [$rsp + 32]",
1864 "$rsp = x64.lea_64 [$rbp + 48]",
1865 "$rsi = x64.pop_64",
1866 "$rbx = x64.pop_64",
1867 "$rbp = x64.pop_64",
1868 "x64.ret",
1869 ]
1870 );
1871 }
1872
1873 #[test]
1874 fn a_vector_register_a_windows_call_preserves_is_stored_and_read_back() {
1875 let mut names = Interner::new();
1876 let mut func = Func::new(names.intern("f"));
1877 let opcode = Opcode::new(names.intern("x64.nop"));
1878 let block = func.create_block();
1879 // An instruction that writes one of the vector registers Windows preserves, which is what
1880 // a rule for something that has to use it produces.
1881 func.build(block, opcode).operand(Operand::write(Reg::physical(xmm(6)), XMM)).finish();
1882 let allocation = rucc_regalloc::run(&mut func, &env(&WIN64, 4), "test", true);
1883 let lines = written(&mut func, &allocation, &Layout::new(&WIN64, REGS), &mut names);
1884
1885 // No machine here pushes a vector register, so it is stored into the frame rather than
1886 // pushed, and the frame has to be taken before there is anywhere to put it.
1887 assert_eq!(
1888 added(&lines),
1889 [
1890 "$rsp = x64.sub_ri_64 $rsp, 24",
1891 "x64.movaps_mr $xmm6, [$rsp]",
1892 "$xmm6 = x64.movaps_rm [$rsp]",
1893 "$rsp = x64.add_ri_64 $rsp, 24",
1894 "x64.ret",
1895 ]
1896 );
1897 }
1898}