Skip to main content

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//! The loads that read the arguments the caller passed on the stack are waiting on the same number
25//! and on one more. Those bytes are the caller's rather than this function's, and a frame that had
26//! to force its own alignment cannot say how far away the caller's stack pointer was, so it reaches
27//! back through the frame pointer instead. Which register a load reads through is therefore settled
28//! here too, and it is the only base register in a finished function that was not settled by
29//! whoever wrote the instruction.
30//!
31//! After this the function is one an encoder can read: every register is physical, every offset
32//! into the frame is a constant, and the stack pointer is where the convention says it should be
33//! at every instruction that could look.
34//!
35//! # Why the moves go in first
36//!
37//! Every offset the frame reports is from the stack pointer as it stands in the body of the
38//! function. A spill written before the prologue exists would be written in front of the
39//! instruction it belongs to and behind nothing, which is where the prologue then goes, so the
40//! prologue ends up in front of it and the offsets stay true. Writing them the other way round
41//! would put the first reload above the instruction that takes the frame, and it would read from
42//! an address that is one frame out.
43//!
44//! # Where a return is
45//!
46//! A block that goes nowhere is a block the function leaves from. Mostly that is a return, and
47//! the other kind is a block ending in `unreachable`, which is a point the front end says control
48//! does not arrive at and which the lowering writes no instruction for. Both want the same thing
49//! here. A return wants the epilogue because that is what a return is once the frame is known,
50//! and an unreachable block wants it because the alternative is a function whose last instruction
51//! falls into whatever the assembler put after it, which is worse than an epilogue nothing runs.
52//! So the epilogue goes at the end of every block with an empty successor list, and there may be
53//! several, because nothing here insists a function has one exit.
54//!
55//! # What is target-specific here
56//!
57//! The names, and only the names. Which instruction pushes a register and which one moves the
58//! stack pointer is [`rucc_target::FrameInsts`], which the target says and this reads, so what
59//! is written below is the shape of a prologue rather than any particular machine's. That is
60//! `spec/10-backend.md` section 10.8 as it applies to the one pass that would otherwise be full
61//! of `x64.` by hand.
62
63use std::collections::HashMap;
64
65use rucc_base::Interner;
66use rucc_mir::{Block, BlockCall, CfiOp, Func, Inst, Mem, Opcode, Operand, Patch, Reg};
67use rucc_regalloc::Allocation;
68use rucc_regalloc::assign::Place;
69use rucc_regalloc::rewrite::{At, Edit};
70use rucc_target::{BranchInsts, CallRegs, FrameInsts, Guard, PhysReg, Probe, RegClass};
71
72use crate::frame::Frame;
73use crate::lower::Stack;
74
75/// What the stack protector's check needs beyond the frame, in a function that has one.
76///
77/// Three things that come from three places, which is why they arrive together rather than being
78/// looked up here. Where the word the canary is copied from lives is a fact about the runtime the
79/// code is linked against. What a branch on a register is is a fact about the machine. And the two
80/// registers are neither: they are the ones the allocator was told to hold back, which is a
81/// decision about the allocator, and they are free at a return for exactly that reason.
82#[derive(Debug, Clone, Copy)]
83pub struct Protect<'a> {
84    /// Where the word the canary is a copy of lives, and what to call when the copy has changed.
85    pub guard: &'a Guard,
86    /// What a branch on a register is, which is what the check ends its block with.
87    pub branch: &'a BranchInsts,
88    /// The two registers the check may use, which are two the allocator never handed out.
89    pub scratch: [PhysReg; 2],
90}
91
92/// What a prologue that takes its frame a page at a time needs beyond the frame.
93///
94/// What `-fstack-clash-protection` asks for, and the same three kinds of thing [`Protect`] is:
95/// one fact about the platform, one about the machine, and two registers that are neither. See
96/// [`rucc_target::Probe`] for what the sequence is defending against.
97#[derive(Debug, Clone, Copy)]
98pub struct Probing<'a> {
99    /// What touches a page and how far apart the pages are.
100    pub probe: &'a Probe,
101    /// What a branch on a register is, which is what the loop under a large frame ends with.
102    pub branch: &'a BranchInsts,
103    /// The two registers the sequence may use, which are two the allocator never handed out.
104    pub scratch: [PhysReg; 2],
105}
106
107/// What a profiler's hook at the top of a function is, in a function that has one.
108///
109/// What `-pg` asks for. See [`rucc_target::Trace`] for why there are two of these and what each of
110/// them lets the hook see. Only the name survives to here, because by this point the flag has been
111/// read against the target and a prologue that has the name has everything it needs.
112#[derive(Debug, Clone, Copy)]
113pub struct Tracing {
114    /// What is called, which is a routine the runtime provides and not one the program wrote.
115    pub name: &'static str,
116    /// Whether the call goes in front of the prologue rather than once the frame is taken.
117    pub early: bool,
118}
119
120/// The room at the top of a function for something to be written over later, in a function that
121/// was promised any.
122///
123/// What `-fpatchable-function-entry=` asks for. The room is a run of the shortest instruction the
124/// machine has that does nothing, and what makes it worth reserving is that it is never run for
125/// long: a tracer or a live patcher writes a jump or a call over it once the program is up, and
126/// what it needs from the compiler is a known address and a known number of bytes.
127///
128/// Two counts because the room can be on either side of the function's own label. Only the half
129/// after it is written here, since the stream starts at the label and there is nowhere in it to put
130/// the other half; the half in front is carried through so that whatever lays the function down can
131/// lay that many bytes ahead of the symbol.
132#[derive(Debug, Clone, Copy)]
133pub struct Padding {
134    /// What the instruction that does nothing is called on this target.
135    pub name: &'static str,
136    /// How many of them go in front of the function's own label.
137    pub before: u32,
138    /// How many go after it.
139    pub after: u32,
140}
141
142/// What the convention this function is compiled for says a frame is.
143///
144/// Seven answers to the one question, which is why they travel together: where it puts things,
145/// which instructions build one, whether this function's carries a protector, whether it is taken a
146/// page at a time, whether the function opens with a landing pad, whether it calls a profiler on
147/// the way in, and how much room it opens with for a patcher. The last five are the only ones about
148/// this function rather than about every function on the target, and they are here because what
149/// they need is the other two and nothing else.
150#[derive(Debug, Clone, Copy)]
151pub struct Convention<'a> {
152    /// Where the convention puts things.
153    pub regs: &'a CallRegs,
154    /// The instructions a prologue, an epilogue, a spill and a reload are made of on it.
155    pub insts: &'a FrameInsts,
156    /// What this function's stack protector needs, or `None` in a function with none.
157    pub protect: Option<Protect<'a>>,
158    /// What this function's probing prologue needs, or `None` when the frame is taken in one
159    /// subtraction, which is what a command line that did not ask asks for.
160    pub probe: Option<Probing<'a>>,
161    /// What says an indirect branch may arrive at the top of this function, or `None` when the
162    /// command line did not ask for one and on a target that has no such instruction.
163    ///
164    /// See [`rucc_target::FrameInsts::landing`]. A name rather than a flag because the flag has
165    /// already been read against the target by the time this is built, and because a prologue that
166    /// has the name has everything it needs.
167    pub landing: Option<&'static str>,
168    /// What this function's call to a profiler is, or `None` in one that makes none, which is every
169    /// function on a command line that did not ask.
170    pub trace: Option<Tracing>,
171    /// What room this function opens with for a patcher, or `None` in one that was promised none,
172    /// which is every function on a command line that did not ask.
173    pub pad: Option<Padding>,
174}
175
176impl<'a> Convention<'a> {
177    /// That convention, for a function with no stack protector, no probing, no landing pad, no
178    /// call to a profiler and no room for a patcher, which is most of them.
179    #[must_use]
180    pub fn new(regs: &'a CallRegs, insts: &'a FrameInsts) -> Self {
181        Self { regs, insts, protect: None, probe: None, landing: None, trace: None, pad: None }
182    }
183}
184
185/// Writes the moves, the prologue and the epilogue into a function the allocator has finished
186/// with.
187///
188/// # Panics
189///
190/// Panics on a function with no blocks in it, on a frame whose slots or locals the allocation and
191/// the lowering do not match, and on a move of a class the target did not say how to move. All of
192/// them are the caller handing it a frame and a function that were not worked out from each other.
193pub fn finish(
194    func: &mut Func,
195    allocation: &Allocation,
196    frame: &Frame,
197    stack: &Stack,
198    convention: Convention<'_>,
199    names: &mut Interner,
200) {
201    let Convention { regs: conv, insts, protect, probe, landing, trace, pad } = convention;
202    let entry = func.entry().expect("a function with a block in it");
203    let returns: Vec<Block> = func.blocks().filter(|&block| func[block].succs.is_empty()).collect();
204
205    // Before anything is written, because these are instructions the lowering already put in the
206    // function and every one of them is somewhere the prologue is about to go in front of, which
207    // is what makes an offset from the stack pointer the right thing to write into them. In a
208    // frame that grows it is an offset from the frame pointer instead, so the base register is
209    // rewritten the way an incoming argument's is, and for a version of the same reason.
210    //
211    // Added rather than assigned. The instruction named here is the `lea` the lowering wrote, or
212    // whatever [`crate::fold`] folded that `lea` into, and a reader that took it brought a
213    // displacement of its own: the address of a local is where the object starts and reading a
214    // field of it is some way past that. Assigning would throw the field offset away and read the
215    // front of the object every time.
216    for &(inst, local) in &stack.addresses {
217        let at = frame.local(local).expect("a local the frame was worked out from");
218        let mem = func[inst].mem.expect("the address of a local is an address");
219        func[mem].disp += at;
220        if frame.grows() {
221            rebase(func, inst, conv.frame_pointer);
222        }
223    }
224
225    // The bytes a variable length array takes are already off the stack pointer by the time one of
226    // these runs, so what is left to write is how far above the new stack pointer the array starts,
227    // which is however much of the bottom of the frame belongs to the arguments of a call. That
228    // area stays at the bottom wherever the bottom has moved to. Added rather than assigned for the
229    // reason the loop above is: one of these folds into its readers like any other address, and a
230    // reader that took it brought a displacement of its own.
231    for &inst in &stack.dynamic {
232        let mem = func[inst].mem.expect("the address of a growable local is an address");
233        func[mem].disp += offset(frame.below());
234    }
235
236    // The same, one area further up, and through the frame pointer when that is what reaches it.
237    // These are in the entry block ahead of everything, so the prologue still goes in front of
238    // them, which is what makes both registers hold what these offsets are counted from.
239    let incoming = frame.incoming();
240    for &(inst, up) in &stack.arguments {
241        let mem = func[inst].mem.expect("an argument read out of memory is read from an address");
242        func[mem].disp += incoming.at + offset(up);
243        if incoming.through_frame_pointer {
244            rebase(func, inst, conv.frame_pointer);
245        }
246    }
247
248    // Every offset the frame reports is from this one register, which is the stack pointer in an
249    // ordinary frame and the frame pointer in one that moves the stack pointer while it runs.
250    let base = if frame.grows() { conv.frame_pointer } else { conv.stack_pointer };
251    let mut writer = Writer { func, conv, insts, names, base, ahead: None };
252
253    let mut cursors: HashMap<At, Inst> = HashMap::new();
254    for edit in &allocation.edits {
255        let inst = writer.mov(edit, frame);
256        writer.put(&mut cursors, edit.at, inst);
257    }
258
259    let prologue = writer.prologue(frame, protect, probe, landing, trace, pad);
260    for &inst in prologue.iter().rev() {
261        writer.func.prepend_inst(entry, inst);
262    }
263    for block in returns {
264        // The check goes in front of the epilogue and takes the return with it. What is left in
265        // the block the function used to return from is the check, and the block the epilogue then
266        // goes in is the arm the canary was unchanged on.
267        let block = match protect {
268            Some(protect) => writer.check(block, frame, protect),
269            None => block,
270        };
271        let epilogue = writer.epilogue(frame);
272        for inst in epilogue {
273            writer.func.append_inst(block, inst);
274        }
275    }
276
277    // Last of everything, because the blocks a probing prologue made have to come in front of the
278    // block the function used to begin with and the ones the protector's check makes are made
279    // after that. Nothing has been laid out yet: `crate::layout` runs after this and puts every
280    // block in its own order, and all this decides is which block the function is entered at.
281    if let Some(ahead) = writer.ahead {
282        let rest: Vec<Block> =
283            writer.func.blocks().filter(|block| !ahead.contains(block)).collect();
284        let order: Vec<Block> = ahead.into_iter().chain(rest).collect();
285        writer.func.set_block_order(&order);
286    }
287}
288
289/// How many pages a probing prologue touches one after another before it writes a loop instead.
290///
291/// Three, which is what gcc unrolls to. The loop is four instructions however many pages it walks
292/// and a page written out is two, so three is the last size at which the straight line is no
293/// longer than the loop, and the straight line has no branch in it and needs no register.
294const UNROLLED: u32 = 3;
295
296/// One function having its frame written into it.
297/// Points an address the lowering left counted from the stack pointer at another register.
298///
299/// The base register is an operand of the instruction and the addressing mode holds where in the
300/// operand vector it is, so the register is changed there and not in the mode.
301fn rebase(func: &mut Func, inst: Inst, to: PhysReg) {
302    let mem = func[inst].mem.expect("an address");
303    let at = func[mem].base.expect("an address the lowering wrote a base register into");
304    let operands = func[inst].operands;
305    func[operands][usize::from(at)].reg = Reg::physical(to);
306}
307
308struct Writer<'a> {
309    func: &'a mut Func,
310    conv: &'a CallRegs,
311    insts: &'a FrameInsts,
312    names: &'a mut Interner,
313    /// Which register every offset into the frame is counted from, which is the stack pointer
314    /// unless the function moves it while it runs. See `Growing` in [`crate::frame`].
315    base: PhysReg,
316    /// The blocks a probing prologue made, which go in front of the one the function began with.
317    ///
318    /// Empty in every function whose frame is taken in one subtraction, which is every function
319    /// on a command line that did not ask for the stack to be touched a page at a time and most
320    /// of them on one that did. See [`Writer::pages`].
321    ahead: Option<[Block; 2]>,
322}
323
324impl Writer<'_> {
325    /// The instructions the prologue is, in the order they run.
326    ///
327    /// The order is the one the epilogue undoes and it is not free. The frame pointer is saved
328    /// before anything else, so that it points at a fixed place whatever else happens. The
329    /// registers are pushed before the alignment is forced, so that the epilogue can find them
330    /// again from the frame pointer, since after the alignment is forced nothing else can. And the
331    /// vector registers are stored last, because until the frame has been taken there is nowhere
332    /// to store them.
333    ///
334    /// The landing pad is in front of all of it, because the address it makes reachable is the
335    /// address of the function and the address of the function is where the first instruction is.
336    /// It has to be written here rather than after the fact, since a probing prologue moves the
337    /// instructions written so far into a block of its own and the pad has to move with them.
338    ///
339    /// The room a patcher was promised goes after the pad, because a patcher wants somewhere it can
340    /// write a call that happens before anything else, and the pad is the one instruction that has
341    /// to come first for a reason of its own.
342    ///
343    /// A profiler's hook goes next, or at the end when it is the kind that reads the frame pointer.
344    /// The early one is in front of everything the frame does for a reason of its own: what makes
345    /// it worth replacing while the program runs is that the stack at that instruction is exactly
346    /// what a call leaves, and a prologue that had already run would have changed it.
347    fn prologue(
348        &mut self,
349        frame: &Frame,
350        protect: Option<Protect<'_>>,
351        probe: Option<Probing<'_>>,
352        landing: Option<&'static str>,
353        trace: Option<Tracing>,
354        pad: Option<Padding>,
355    ) -> Vec<Inst> {
356        let sp = self.conv.stack_pointer;
357        let fp = self.conv.frame_pointer;
358        let int = self.conv.int_class;
359        let sse = self.conv.sse_class;
360        let word = offset(self.conv.word);
361        let mut out = Vec::new();
362        // What the prologue wrote before it had described anything, which is what decides whether
363        // there is a rule to remember at the end of it. Neither of these moves a register or takes
364        // a frame, so a function whose whole prologue is one of them has no rows and must not be
365        // given a pair of them that cancel out.
366        let mut quiet = Vec::new();
367        if let Some(name) = landing {
368            let opcode = self.opcode(name);
369            let inst = self.func.build_loose(opcode).finish();
370            out.push(inst);
371            quiet.push(inst);
372        }
373        // After the pad and in front of everything else, which is where gcc puts it. The pad is the
374        // function's first instruction because the address an indirect branch may arrive at is the
375        // address of the function, and the room comes next because what gets written over it is a
376        // call and the point of that call is that it happens before the function has done anything.
377        //
378        // Nothing is described for any of it. A byte that does nothing does not move the stack
379        // pointer, and what a patcher writes over it later is its own problem rather than this
380        // function's: the rules here say what this function did, and it did nothing.
381        if let Some(pad) = pad {
382            let opcode = self.opcode(pad.name);
383            let mut first = None;
384            for _ in 0..pad.after {
385                let inst = self.func.build_loose(opcode).finish();
386                out.push(inst);
387                quiet.push(inst);
388                first.get_or_insert(inst);
389            }
390            self.func.patch = Some(Patch { before: pad.before, pad: opcode, after: first });
391        }
392        // Nothing is described for it and nothing needs to be: the call pushes a return address and
393        // the hook pops it, so the frame is the same on both sides, and the hook preserves every
394        // register because it is written in assembly for exactly this. That is also why the
395        // allocator, which ran before any of this, never saw the call and did not have to.
396        if let Some(trace) = trace.filter(|trace| trace.early) {
397            let inst = self.hook(trace);
398            out.push(inst);
399            quiet.push(inst);
400        }
401        // How far the stack pointer is below the canonical frame address, and whether the address
402        // is still counted from the stack pointer at all. It starts at the return address the
403        // call itself pushed, which is the rule the CIE already states, so the first row here is
404        // the first thing this function does on top of that.
405        let mut below = offset(self.conv.return_address);
406        let mut from_sp = true;
407        if frame.frame_pointer() {
408            let inst = self.push(fp);
409            out.push(inst);
410            below += word;
411            self.row(inst, CfiOp::DefCfaOffset(below));
412            self.saved(inst, int, fp, -below);
413            let mov = self.opcode(self.insts.moves(int).expect("a move").mov);
414            let inst = self.two(mov, fp, sp);
415            out.push(inst);
416            let number = self.dwarf(int, fp);
417            self.row(inst, CfiOp::DefCfaRegister(number));
418            from_sp = false;
419        }
420        for &reg in frame.saved_int() {
421            let inst = self.push(reg);
422            out.push(inst);
423            below += word;
424            if from_sp {
425                self.row(inst, CfiOp::DefCfaOffset(below));
426            }
427            self.saved(inst, int, reg, -below);
428        }
429        if let Some(to) = frame.realign() {
430            // Nothing is written for this and nothing can be. After it the stack pointer is a
431            // rounded-down version of where it was rather than a fixed distance from it, which is
432            // exactly what a rule cannot say. It is also why a frame that realigns is a frame
433            // with a frame pointer: by here the address is already counted from that instead.
434            assert!(!from_sp, "a frame that forces its own alignment has a frame pointer");
435            let and = self.opcode(self.insts.align);
436            out.push(self.arith(and, -i64::from(to)));
437        }
438        if frame.size() > 0 {
439            self.take(&mut out, frame.size(), &mut below, from_sp, probe);
440        }
441        for save in frame.saved_sse() {
442            let inst = self.store(sse, save.reg, save.at);
443            out.push(inst);
444            // Where it went is an offset from whichever register the frame counts from, and the
445            // address is a constant above that register, so the two make one constant. In an
446            // ordinary frame that register is the stack pointer and the constant is `below`. In one
447            // that grows it is the frame pointer, which the address has been counted from since the
448            // prologue pointed it at where it saved the caller's copy, so the constant is the two
449            // words above it and nothing the prologue did afterwards changes it. A realigned frame
450            // has no such constant at all and the rule is left out rather than guessed; the one
451            // convention that realigns and the one that preserves a vector register are not the
452            // same convention, so nothing reaches any of this today.
453            if frame.realign().is_none() {
454                let above =
455                    if frame.grows() { word + offset(self.conv.return_address) } else { below };
456                self.saved(inst, sse, save.reg, save.at - above);
457            }
458        }
459        // Before the canary and after the frame, which is where gcc puts it. The hook reads the
460        // frame pointer to find out who called this function, so it has to run once there is one,
461        // and it is a call, so it has to run before anything the function is keeping in the frame
462        // could be read back.
463        if let Some(trace) = trace.filter(|trace| !trace.early) {
464            let inst = self.hook(trace);
465            out.push(inst);
466        }
467        // Last of everything, because it writes into the frame and there is no frame to write into
468        // until the stack pointer has moved. Nothing is described for either instruction: they
469        // write a slot rather than save a register, and no unwinder wants to put a canary back.
470        if let Some(protect) = protect {
471            let at = frame.canary().expect("a protected function has a slot for its canary");
472            let [into, _] = protect.scratch;
473            out.push(self.read_guard(into, protect.guard));
474            out.push(self.store(self.conv.int_class, into, at));
475        }
476        // The rules the body runs under, kept so that each epilogue can put them back rather than
477        // leaving the next block reading whatever the last one ended on. See `epilogue`.
478        //
479        // Nothing is kept in a function whose whole prologue is the pieces that describe nothing.
480        // See `quiet` above.
481        if let Some(&last) = out.last() {
482            if !quiet.contains(&last) {
483                self.row(last, CfiOp::RememberState);
484            }
485        }
486        out
487    }
488
489    /// The call to a profiler's hook.
490    ///
491    /// No arguments and no result. Which function is being entered is not passed, because the hook
492    /// reads its own return address to find out, and that is the whole reason the call is written
493    /// rather than something cheaper.
494    fn hook(&mut self, trace: Tracing) -> Inst {
495        let call = self.opcode(self.insts.call);
496        let symbol = self.names.intern(trace.name);
497        self.func.build_loose(call).symbol(symbol).finish()
498    }
499
500    /// Takes the frame, which is one subtraction unless the command line asked for the stack to be
501    /// touched a page at a time.
502    ///
503    /// `below` is how far the canonical frame address is above the stack pointer, and it comes
504    /// back as what it is once the frame has been taken.
505    fn take(
506        &mut self,
507        out: &mut Vec<Inst>,
508        size: u32,
509        below: &mut i32,
510        from_sp: bool,
511        probe: Option<Probing<'_>>,
512    ) {
513        let Some(probing) = probe.filter(|probing| size > probing.probe.interval) else {
514            let inst = self.sub(size);
515            out.push(inst);
516            *below += offset(size);
517            if from_sp {
518                self.row(inst, CfiOp::DefCfaOffset(*below));
519            }
520            return;
521        };
522        // Every step but the last is a whole page and is followed by a touch, and the last is
523        // whatever is left over, which is between one byte and one whole page. So the stack
524        // pointer never moves further than a page without something being written where it landed,
525        // and the unmapped page an operating system leaves below a stack cannot be stepped over.
526        //
527        // That is why the count is worked out from one less than the size. A frame that is an
528        // exact number of pages gets one fewer touch than it has pages, and the step left over is
529        // a whole page, which is a step that lands on the next page boundary rather than past it.
530        // gcc touches that last page as well, so this is one instruction shorter on a frame whose
531        // size is a multiple of the page and the same everywhere else.
532        let interval = probing.probe.interval;
533        let pages = (size - 1) / interval;
534        let rest = size - pages * interval;
535        let mut walked = false;
536        if pages <= UNROLLED {
537            for _ in 0..pages {
538                let inst = self.sub(interval);
539                out.push(inst);
540                *below += offset(interval);
541                if from_sp {
542                    self.row(inst, CfiOp::DefCfaOffset(*below));
543                }
544                let touch = self.touch(probing.probe);
545                out.push(touch);
546            }
547        } else {
548            self.pages(out, pages, below, from_sp, probing);
549            walked = from_sp;
550        }
551        let inst = self.sub(rest);
552        out.push(inst);
553        *below += offset(rest);
554        if from_sp {
555            // A loop leaves the address counted from the register the stack pointer was compared
556            // against, since that is the one thing in it that holds still. This is where it goes
557            // back to being counted from the stack pointer, and it is written behind this
558            // instruction rather than behind the branch because a row is written behind an
559            // instruction and the branch is not one that survives [`crate::layout`].
560            let op = if walked {
561                let number = self.dwarf(self.conv.int_class, self.conv.stack_pointer);
562                CfiOp::DefCfa { reg: number, offset: *below }
563            } else {
564                CfiOp::DefCfaOffset(*below)
565            };
566            self.row(inst, op);
567        }
568    }
569
570    /// The loop that takes a frame too large for the touches to be written one after another.
571    ///
572    /// Three blocks, and the first two are new and go in front of the one the function began with:
573    ///
574    /// ```text
575    ///   what the function is entered at   everything the prologue did before this, and then the
576    ///                                     address the stack pointer is walking down to
577    ///   the loop                          one page, the touch, and the question of whether the
578    ///                                     stack pointer has got there yet
579    ///   what the function began with      the rest of the prologue, and then the body
580    /// ```
581    ///
582    /// The instructions the prologue has written so far move into the first of them, because a
583    /// block is entered at the top and they have to run before the loop does. Nothing is laid out
584    /// here: which block comes first in memory is [`crate::layout`]'s answer, and all this decides
585    /// is which one the function is entered at.
586    fn pages(
587        &mut self,
588        out: &mut Vec<Inst>,
589        pages: u32,
590        below: &mut i32,
591        from_sp: bool,
592        probing: Probing<'_>,
593    ) {
594        let class = self.conv.int_class;
595        let sp = self.conv.stack_pointer;
596        let all = offset(pages * probing.probe.interval);
597        let [limit, byte] = probing.scratch;
598
599        let head = self.func.create_block();
600        for &inst in out.iter() {
601            self.func.append_inst(head, inst);
602        }
603        out.clear();
604        // Where the stack pointer is walking down to, worked out before it starts moving. A loop
605        // that counted down instead would need somewhere to keep the count, and this is somewhere
606        // to keep it that the comparison can read without arithmetic.
607        let lea = self.opcode(self.insts.lea);
608        let inst = self.address(lea, limit, sp, -all);
609        self.func.append_inst(head, inst);
610        if from_sp {
611            // The address is counted from that register for as long as the loop runs, and it has
612            // to be: the stack pointer moves once an iteration, so no fixed distance from it is
613            // true twice, and this register was written so that one distance is.
614            let number = self.dwarf(class, limit);
615            self.row(inst, CfiOp::DefCfa { reg: number, offset: *below + all });
616        }
617
618        let body = self.func.create_block();
619        *self.func.succs_mut(head) = vec![BlockCall::to(body)];
620        let inst = self.sub(probing.probe.interval);
621        self.func.append_inst(body, inst);
622        let touch = self.touch(probing.probe);
623        self.func.append_inst(body, touch);
624        let differ = self.opcode(self.insts.differ);
625        let inst = self
626            .func
627            .build_loose(differ)
628            .def(Reg::physical(byte), class)
629            .uses(Reg::physical(sp), class)
630            .uses(Reg::physical(limit), class)
631            .finish();
632        self.func.append_inst(body, inst);
633        let cond = Opcode::new(
634            self.names.intern(&format!("{}{}", probing.branch.prefix, probing.branch.cond)),
635        );
636        let inst = self.func.build_loose(cond).uses(Reg::physical(byte), class).finish();
637        self.func.append_inst(body, inst);
638        // The first arm is the one taken when the condition held, and the condition is that the
639        // stack pointer and the address it is walking down to still differ, so the first arm is
640        // another page.
641        let began = self.func.entry().expect("a function with a block in it");
642        *self.func.succs_mut(body) = vec![BlockCall::to(body), BlockCall::to(began)];
643        *below += all;
644        self.ahead = Some([head, body]);
645    }
646
647    /// Writes the page the stack pointer is on without changing what is there.
648    fn touch(&mut self, probe: &Probe) -> Inst {
649        let opcode = self.opcode(probe.inst);
650        let base = Operand::read(Reg::physical(self.conv.stack_pointer), self.conv.int_class);
651        self.func.build_loose(opcode).imm(0).mem(Mem::at(base)).finish()
652    }
653
654    /// Takes that many bytes off the stack pointer.
655    fn sub(&mut self, bytes: u32) -> Inst {
656        let sub = self.opcode(self.insts.sub);
657        self.arith(sub, i64::from(bytes))
658    }
659
660    /// The stack protector's check, written at the end of a block the function returns from.
661    ///
662    /// Gives back the block the epilogue goes in, which is a new one: the check has to be the last
663    /// thing the old block does, and what follows it is one of two arms rather than the return.
664    ///
665    /// ```text
666    ///   block that returned      reload the slot, read the word again, compare, branch
667    ///   the arm it changed on    call the function that does not come back, and nothing after
668    ///   the arm it did not       the epilogue, which the caller writes into what this gives back
669    /// ```
670    ///
671    /// The two registers are the ones the allocator was told to hold back, so nothing here has to
672    /// ask what is live: a scratch register holds nothing at the end of a block, because the only
673    /// thing that writes one is a move the rewriter put in and every one of those is read by the
674    /// instruction it was put in front of.
675    fn check(&mut self, block: Block, frame: &Frame, protect: Protect<'_>) -> Block {
676        let class = self.conv.int_class;
677        let at = frame.canary().expect("a protected function has a slot for its canary");
678        let [ours, theirs] = protect.scratch;
679
680        let inst = self.load(class, ours, at);
681        self.func.append_inst(block, inst);
682        let inst = self.read_guard(theirs, protect.guard);
683        self.func.append_inst(block, inst);
684        let differ = self.opcode(self.insts.differ);
685        let inst = self
686            .func
687            .build_loose(differ)
688            .def(Reg::physical(theirs), class)
689            .uses(Reg::physical(ours), class)
690            .uses(Reg::physical(theirs), class)
691            .finish();
692        self.func.append_inst(block, inst);
693
694        let failed = self.func.create_block();
695        let ok = self.func.create_block();
696        let cond = Opcode::new(
697            self.names.intern(&format!("{}{}", protect.branch.prefix, protect.branch.cond)),
698        );
699        let inst = self.func.build_loose(cond).uses(Reg::physical(theirs), class).finish();
700        self.func.append_inst(block, inst);
701        // The first arm is the one taken when the condition held, and the condition is that the
702        // two words differ, so the first arm is the one the canary was overwritten on.
703        *self.func.succs_mut(block) = vec![BlockCall::to(failed), BlockCall::to(ok)];
704
705        let call = self.opcode(self.insts.call);
706        let symbol = self.names.intern(protect.guard.fail);
707        self.func.build(failed, call).symbol(symbol).finish();
708        ok
709    }
710
711    /// Reads the word the canary is a copy of into a register.
712    ///
713    /// The address is a constant and names no register at all, because where the block a thread
714    /// has to itself begins is something only the machine knows and the segment register is what
715    /// holds it.
716    fn read_guard(&mut self, into: PhysReg, guard: &Guard) -> Inst {
717        let class = self.conv.int_class;
718        let load = self.opcode(self.insts.moves(class).expect("a class to load").load);
719        self.func
720            .build_loose(load)
721            .def(Reg::physical(into), class)
722            .mem(Mem::in_segment(guard.segment, guard.at))
723            .finish()
724    }
725
726    /// The instructions the epilogue is, in the order they run.
727    ///
728    /// The vector registers are read back while the stack pointer is still where the body left it,
729    /// because that is what their offsets are from. Then the stack pointer goes back to the last
730    /// register the prologue pushed, which is arithmetic when the prologue knew how far it had
731    /// moved and a read of the frame pointer when it did not.
732    fn epilogue(&mut self, frame: &Frame) -> Vec<Inst> {
733        let sp = self.conv.stack_pointer;
734        let fp = self.conv.frame_pointer;
735        let int = self.conv.int_class;
736        let sse = self.conv.sse_class;
737        let word = self.conv.word;
738        let described = !self.func.cfi.is_empty();
739        let mut out = Vec::new();
740        // Where the body left things, which is where every epilogue starts from.
741        let mut below = offset(self.conv.return_address)
742            + offset(word) * self.pushes(frame)
743            + offset(frame.size());
744        let from_sp = !frame.frame_pointer();
745        for save in frame.saved_sse() {
746            let inst = self.load(sse, save.reg, save.at);
747            out.push(inst);
748            if frame.realign().is_none() {
749                self.restored(inst, sse, save.reg);
750            }
751        }
752        let pushed = u32::try_from(frame.saved_int().len()).expect("a frame");
753        if frame.frame_pointer() {
754            // No row for either of these. The address is counted from the frame pointer here and
755            // this is what moves the stack pointer rather than the frame pointer, so the rule that
756            // was true before it is still true after it.
757            if pushed == 0 {
758                let mov = self.opcode(self.insts.moves(int).expect("a move").mov);
759                out.push(self.two(mov, sp, fp));
760            } else {
761                let lea = self.opcode(self.insts.lea);
762                let back = -offset(word * pushed);
763                out.push(self.address(lea, sp, fp, back));
764            }
765        } else if frame.size() > 0 {
766            let add = self.opcode(self.insts.add);
767            let inst = self.arith(add, i64::from(frame.size()));
768            out.push(inst);
769            below -= offset(frame.size());
770            self.row(inst, CfiOp::DefCfaOffset(below));
771        }
772        for &reg in frame.saved_int().iter().rev() {
773            let inst = self.pop(reg);
774            out.push(inst);
775            self.restored(inst, int, reg);
776            below -= offset(word);
777            if from_sp {
778                self.row(inst, CfiOp::DefCfaOffset(below));
779            }
780        }
781        if frame.frame_pointer() {
782            let inst = self.pop(fp);
783            out.push(inst);
784            self.restored(inst, int, fp);
785            // The frame pointer holds the caller's value again, so the address goes back to being
786            // counted from the stack pointer, which by now is at the return address.
787            let number = self.dwarf(int, sp);
788            self.row(inst, CfiOp::DefCfa { reg: number, offset: offset(self.conv.return_address) });
789        }
790        let ret = self.opcode(self.insts.ret);
791        let inst = self.func.build_loose(ret).finish();
792        out.push(inst);
793        // These take effect at the address just past the return, which is where the next block
794        // begins, and the next block is body again. Popping the body's rules and pushing them
795        // straight back leaves the stack one deep however many blocks the function returns from,
796        // which is what makes one remembering in the prologue enough for all of them.
797        if described {
798            self.row(inst, CfiOp::RestoreState);
799            self.row(inst, CfiOp::RememberState);
800        }
801        out
802    }
803
804    /// How many general purpose registers the prologue put on the stack, the frame pointer
805    /// included.
806    fn pushes(&self, frame: &Frame) -> i32 {
807        let saved = i32::try_from(frame.saved_int().len()).expect("a frame");
808        saved + i32::from(frame.frame_pointer())
809    }
810
811    /// One row of the unwind table, taking effect after that instruction.
812    fn row(&mut self, inst: Inst, op: CfiOp) {
813        self.func.cfi.push((inst, op));
814    }
815
816    /// A row saying the caller's copy of that register is that far from the canonical frame
817    /// address, which is below it and so is negative.
818    fn saved(&mut self, inst: Inst, class: RegClass, reg: PhysReg, from_cfa: i32) {
819        let number = self.dwarf(class, reg);
820        self.row(inst, CfiOp::Offset { reg: number, offset: from_cfa });
821    }
822
823    /// A row saying that register holds what the caller left in it again.
824    fn restored(&mut self, inst: Inst, class: RegClass, reg: PhysReg) {
825        let number = self.dwarf(class, reg);
826        self.row(inst, CfiOp::Restore(number));
827    }
828
829    /// What an unwind table calls that register.
830    fn dwarf(&self, class: RegClass, reg: PhysReg) -> u16 {
831        self.conv.dwarf(class, reg).expect("a register a frame saves is one the table can name")
832    }
833
834    /// One edit as the instruction that makes it true.
835    fn mov(&mut self, edit: &Edit, frame: &Frame) -> Inst {
836        let moves = self.insts.moves(edit.class).expect("a class the target says how to move");
837        match (edit.mov.to, edit.mov.from) {
838            (Place::Reg(to), Place::Reg(from)) => {
839                let mov = self.opcode(moves.mov);
840                self.func
841                    .build_loose(mov)
842                    .def(Reg::physical(to), edit.class)
843                    .uses(Reg::physical(from), edit.class)
844                    .finish()
845            }
846            (Place::Reg(to), Place::Slot(slot)) => {
847                let at = self.slot(frame, slot);
848                self.load(edit.class, to, at)
849            }
850            (Place::Slot(slot), Place::Reg(from)) => {
851                let at = self.slot(frame, slot);
852                self.store(edit.class, from, at)
853            }
854            // The allocator expands this into two moves through a register of its own, because a
855            // machine that could do it in one is not a machine any of this is written for.
856            (Place::Slot(_), Place::Slot(_)) => {
857                unreachable!("a move from one stack slot straight into another")
858            }
859        }
860    }
861
862    /// Puts an instruction where an edit says it goes, after whatever earlier edits went there.
863    ///
864    /// The edits at one place are in the order they have to be made in, so each one goes behind
865    /// the last, and the first of them is what the place itself means.
866    fn put(&mut self, cursors: &mut HashMap<At, Inst>, at: At, inst: Inst) {
867        if let Some(cursor) = cursors.get_mut(&at) {
868            self.func.insert_after(*cursor, inst);
869            *cursor = inst;
870            return;
871        }
872        match at {
873            At::Before(before) => self.func.insert_before(before, inst),
874            At::After(after) => self.func.insert_after(after, inst),
875            At::StartOf(block) => self.func.prepend_inst(block, inst),
876            // Behind everything in the block. A block the allocator puts an edge's moves at the
877            // end of is one with a single edge out of it, and an edge like that is not an
878            // instruction here: [`crate::layout`] writes the jump it becomes after this has run.
879            // So the last instruction is an ordinary one, which may still be waiting on moves of
880            // its own that have to be made before the edge's are.
881            At::EndOf(block) => self.func.append_inst(block, inst),
882        }
883        cursors.insert(at, inst);
884    }
885
886    /// Where a spill slot is, from the stack pointer in the body of the function.
887    fn slot(&self, frame: &Frame, slot: u32) -> i32 {
888        frame.slot(slot).expect("a slot the frame was worked out from")
889    }
890
891    /// Reads a register out of the frame.
892    fn load(&mut self, class: RegClass, reg: PhysReg, at: i32) -> Inst {
893        let load = self.opcode(self.insts.moves(class).expect("a class to load").load);
894        let base = Operand::read(Reg::physical(self.base), self.conv.int_class);
895        self.func
896            .build_loose(load)
897            .def(Reg::physical(reg), class)
898            .mem(Mem::at(base).plus(at))
899            .finish()
900    }
901
902    /// Writes a register into the frame.
903    fn store(&mut self, class: RegClass, reg: PhysReg, at: i32) -> Inst {
904        let store = self.opcode(self.insts.moves(class).expect("a class to store").store);
905        let base = Operand::read(Reg::physical(self.base), self.conv.int_class);
906        self.func
907            .build_loose(store)
908            .uses(Reg::physical(reg), class)
909            .mem(Mem::at(base).plus(at))
910            .finish()
911    }
912
913    /// Puts a general purpose register on the stack.
914    fn push(&mut self, reg: PhysReg) -> Inst {
915        let push = self.opcode(self.insts.push);
916        self.func.build_loose(push).uses(Reg::physical(reg), self.conv.int_class).finish()
917    }
918
919    /// Takes a general purpose register back off the stack.
920    fn pop(&mut self, reg: PhysReg) -> Inst {
921        let pop = self.opcode(self.insts.pop);
922        self.func.build_loose(pop).def(Reg::physical(reg), self.conv.int_class).finish()
923    }
924
925    /// One general purpose register written with another.
926    fn two(&mut self, opcode: Opcode, to: PhysReg, from: PhysReg) -> Inst {
927        let class = self.conv.int_class;
928        self.func
929            .build_loose(opcode)
930            .def(Reg::physical(to), class)
931            .uses(Reg::physical(from), class)
932            .finish()
933    }
934
935    /// Two-address arithmetic on the stack pointer, which reads it and writes it back.
936    fn arith(&mut self, opcode: Opcode, value: i64) -> Inst {
937        let class = self.conv.int_class;
938        let sp = Reg::physical(self.conv.stack_pointer);
939        self.func.build_loose(opcode).def(sp, class).uses(sp, class).imm(value).finish()
940    }
941
942    /// One register written with an address rather than with what is at it.
943    fn address(&mut self, opcode: Opcode, to: PhysReg, base: PhysReg, disp: i32) -> Inst {
944        let class = self.conv.int_class;
945        let base = Operand::read(Reg::physical(base), class);
946        self.func
947            .build_loose(opcode)
948            .def(Reg::physical(to), class)
949            .mem(Mem::at(base).plus(disp))
950            .finish()
951    }
952
953    /// The opcode of that name, in the machine IR's spelling, which is the target's prefix and
954    /// then the name the target gave.
955    fn opcode(&mut self, name: &str) -> Opcode {
956        Opcode::new(self.names.intern(&format!("{}{name}", self.insts.prefix)))
957    }
958}
959
960/// A distance in a frame, as the signed number every offset is.
961fn offset(bytes: u32) -> i32 {
962    i32::try_from(bytes).expect("a frame under two gigabytes")
963}
964
965#[cfg(test)]
966mod tests {
967    use rucc_base::Interner;
968    use rucc_mir::{BlockCall, print_func};
969    use rucc_regalloc::assign::Env;
970    use rucc_target::x86_64::{BRANCH, FRAME, GPR, PROBE, R10, R11, REGS, SYSV, WIN64, XMM, xmm};
971
972    use super::*;
973    use crate::frame::{Layout, Local};
974
975    /// An environment offering that many of the convention's registers, with everything after
976    /// them held back as scratch.
977    fn env(conv: &CallRegs, count: usize) -> Env {
978        Env::new().with(GPR, &conv.int_order[..count], &conv.int_order[count..])
979    }
980
981    /// A function of that many values, every one written before any is read, allocated with that
982    /// many registers to hand out. The same shape the frame layout's own tests are written
983    /// against, so that a frame here is one that has already been checked there.
984    fn pressure(conv: &CallRegs, values: usize, count: usize) -> (Func, Allocation, Interner) {
985        let mut names = Interner::new();
986        let mut func = Func::new(names.intern("f"));
987        let opcode = Opcode::new(names.intern("x64.nop"));
988        let block = func.create_block();
989        let regs: Vec<Reg> = (0..values).map(|_| func.new_vreg(GPR)).collect();
990        for &reg in &regs {
991            func.build(block, opcode).def(reg, GPR).finish();
992        }
993        for &reg in &regs {
994            func.build(block, opcode).uses(reg, GPR).finish();
995        }
996        let allocation = rucc_regalloc::run(&mut func, &env(conv, count), "test");
997        (func, allocation, names)
998    }
999
1000    /// The function with its frame written into it, as the lines a dump would show.
1001    fn written(
1002        func: &mut Func,
1003        allocation: &Allocation,
1004        layout: &Layout<'_>,
1005        names: &mut Interner,
1006    ) -> Vec<String> {
1007        with_protector(func, allocation, layout, None, names)
1008    }
1009
1010    /// The same, for a function the caller has decided is protected or is not.
1011    fn with_protector(
1012        func: &mut Func,
1013        allocation: &Allocation,
1014        layout: &Layout<'_>,
1015        protect: Option<Protect<'_>>,
1016        names: &mut Interner,
1017    ) -> Vec<String> {
1018        let convention = Convention { protect, ..Convention::new(layout.conv, &FRAME) };
1019        under(func, allocation, layout, convention, names)
1020    }
1021
1022    /// The same, for a function whose frame the caller has decided is taken a page at a time.
1023    fn with_probing(
1024        func: &mut Func,
1025        allocation: &Allocation,
1026        layout: &Layout<'_>,
1027        probe: Option<Probing<'_>>,
1028        names: &mut Interner,
1029    ) -> Vec<String> {
1030        let convention = Convention { probe, ..Convention::new(layout.conv, &FRAME) };
1031        under(func, allocation, layout, convention, names)
1032    }
1033
1034    /// The function with its frame written into it under that convention.
1035    fn under(
1036        func: &mut Func,
1037        allocation: &Allocation,
1038        layout: &Layout<'_>,
1039        convention: Convention<'_>,
1040        names: &mut Interner,
1041    ) -> Vec<String> {
1042        let frame = Frame::of(func, allocation, layout);
1043        finish(func, allocation, &frame, &Stack::default(), convention, names);
1044        print_func(func, names, &REGS)
1045            .lines()
1046            .filter(|line| !line.is_empty())
1047            .map(|line| line.trim().to_string())
1048            .collect()
1049    }
1050
1051    /// Just the lines the frame put in, which is every line that is not the function it was
1052    /// given and not the shape of the dump around it.
1053    fn added(lines: &[String]) -> Vec<&str> {
1054        lines
1055            .iter()
1056            .map(String::as_str)
1057            .filter(|line| !line.contains("x64.nop"))
1058            .filter(|line| !line.starts_with("mfunc") && !line.starts_with("block") && *line != "}")
1059            .collect()
1060    }
1061
1062    #[test]
1063    fn a_function_that_needs_no_frame_is_given_a_return_and_nothing_else() {
1064        let (mut func, allocation, mut names) = pressure(&SYSV, 2, 4);
1065        let lines = written(&mut func, &allocation, &Layout::new(&SYSV, REGS), &mut names);
1066
1067        // Two values and four registers, so nothing is spilled, nothing is saved and the stack
1068        // pointer never moves. A prologue of nothing is the right prologue for that.
1069        assert_eq!(added(&lines), ["x64.ret"]);
1070    }
1071
1072    #[test]
1073    fn a_spill_is_a_store_and_a_reload_is_a_load() {
1074        let (mut func, allocation, mut names) = pressure(&SYSV, 4, 2);
1075        let lines = written(&mut func, &allocation, &Layout::new(&SYSV, REGS), &mut names);
1076
1077        // Two registers for four values, so two of them go to the stack. The store goes behind the
1078        // instruction that wrote the value and the load in front of the one that wants it, both at
1079        // the offsets the frame gave, which are below the stack pointer because a small leaf
1080        // function is entitled to the red zone.
1081        assert_eq!(
1082            lines,
1083            [
1084                "mfunc @f {",
1085                "block0:",
1086                "$rax = x64.nop",
1087                "$rcx = x64.nop",
1088                "$rdx = x64.nop",
1089                "x64.mov_mr_64 $rdx, [$rsp - 16]",
1090                "$rdx = x64.nop",
1091                "x64.mov_mr_64 $rdx, [$rsp - 8]",
1092                "x64.nop $rax",
1093                "x64.nop $rcx",
1094                "$rdx = x64.mov_rm_64 [$rsp - 16]",
1095                "x64.nop $rdx",
1096                "$rdx = x64.mov_rm_64 [$rsp - 8]",
1097                "x64.nop $rdx",
1098                "x64.ret",
1099                "}",
1100            ]
1101        );
1102    }
1103
1104    #[test]
1105    fn the_frame_the_prologue_takes_is_the_frame_the_epilogue_gives_back() {
1106        let (mut func, allocation, mut names) = pressure(&SYSV, 4, 2);
1107        let base = Layout::new(&SYSV, REGS);
1108        let layout = Layout { red_zone: false, ..base };
1109        let lines = written(&mut func, &allocation, &layout, &mut names);
1110
1111        // The same function told it may not use the red zone takes sixteen bytes instead, and
1112        // every offset moves above the stack pointer to match.
1113        assert_eq!(
1114            added(&lines),
1115            [
1116                "$rsp = x64.sub_ri_64 $rsp, 16",
1117                "x64.mov_mr_64 $rdx, [$rsp]",
1118                "x64.mov_mr_64 $rdx, [$rsp + 8]",
1119                "$rdx = x64.mov_rm_64 [$rsp]",
1120                "$rdx = x64.mov_rm_64 [$rsp + 8]",
1121                "$rsp = x64.add_ri_64 $rsp, 16",
1122                "x64.ret",
1123            ]
1124        );
1125    }
1126
1127    #[test]
1128    fn the_registers_the_prologue_pushes_come_back_in_the_opposite_order() {
1129        let (mut func, allocation, mut names) = pressure(&SYSV, 13, 13);
1130        let lines = written(&mut func, &allocation, &Layout::new(&SYSV, REGS), &mut names);
1131
1132        // Four registers a call leaves alone, pushed in the convention's order and popped in the
1133        // other one, which is the only order that gets each of them its own value back.
1134        assert_eq!(
1135            added(&lines),
1136            [
1137                "x64.push_64 $rbx",
1138                "x64.push_64 $r12",
1139                "x64.push_64 $r13",
1140                "x64.push_64 $r14",
1141                "$r14 = x64.pop_64",
1142                "$r13 = x64.pop_64",
1143                "$r12 = x64.pop_64",
1144                "$rbx = x64.pop_64",
1145                "x64.ret",
1146            ]
1147        );
1148    }
1149
1150    #[test]
1151    fn a_function_that_keeps_a_frame_pointer_sets_it_up_and_leaves_by_it() {
1152        let (mut func, allocation, mut names) = pressure(&SYSV, 4, 2);
1153        let base = Layout::new(&SYSV, REGS);
1154        let layout = Layout { frame_pointer: true, red_zone: false, ..base };
1155        let lines = written(&mut func, &allocation, &layout, &mut names);
1156
1157        // The frame pointer is saved before anything else and points at where it was saved, so the
1158        // epilogue reaches the stack pointer through it rather than by counting the frame back.
1159        assert_eq!(
1160            added(&lines),
1161            [
1162                "x64.push_64 $rbp",
1163                "$rbp = x64.mov_rr_64 $rsp",
1164                "$rsp = x64.sub_ri_64 $rsp, 16",
1165                "x64.mov_mr_64 $rdx, [$rsp]",
1166                "x64.mov_mr_64 $rdx, [$rsp + 8]",
1167                "$rdx = x64.mov_rm_64 [$rsp]",
1168                "$rdx = x64.mov_rm_64 [$rsp + 8]",
1169                "$rsp = x64.mov_rr_64 $rbp",
1170                "$rbp = x64.pop_64",
1171                "x64.ret",
1172            ]
1173        );
1174    }
1175
1176    #[test]
1177    fn a_realigned_frame_forces_the_alignment_after_it_has_pushed_what_it_saves() {
1178        let (mut func, allocation, mut names) = pressure(&SYSV, 13, 13);
1179        let locals = [Local { size: 64, align: 32 }];
1180        let base = Layout::new(&SYSV, REGS);
1181        let layout = Layout { locals: &locals, ..base };
1182        let lines = written(&mut func, &allocation, &layout, &mut names);
1183
1184        // Forcing the alignment throws away how far the stack pointer had moved, so the registers
1185        // are pushed before it happens and the epilogue counts back from the frame pointer to find
1186        // them. The frame pointer is required here whatever the flags said.
1187        assert_eq!(
1188            added(&lines),
1189            [
1190                "x64.push_64 $rbp",
1191                "$rbp = x64.mov_rr_64 $rsp",
1192                "x64.push_64 $rbx",
1193                "x64.push_64 $r12",
1194                "x64.push_64 $r13",
1195                "x64.push_64 $r14",
1196                "$rsp = x64.and_ri_64 $rsp, -32",
1197                "$rsp = x64.sub_ri_64 $rsp, 64",
1198                "$rsp = x64.lea_64 [$rbp - 32]",
1199                "$r14 = x64.pop_64",
1200                "$r13 = x64.pop_64",
1201                "$r12 = x64.pop_64",
1202                "$rbx = x64.pop_64",
1203                "$rbp = x64.pop_64",
1204                "x64.ret",
1205            ]
1206        );
1207    }
1208
1209    #[test]
1210    fn every_block_the_function_returns_from_gets_an_epilogue() {
1211        let mut names = Interner::new();
1212        let mut func = Func::new(names.intern("f"));
1213        let opcode = Opcode::new(names.intern("x64.nop"));
1214        let head = func.create_block();
1215        let left = func.create_block();
1216        let right = func.create_block();
1217        func.build(head, opcode).finish();
1218        *func.succs_mut(head) = vec![BlockCall::to(left), BlockCall::to(right)];
1219        func.build(left, opcode).finish();
1220        func.build(right, opcode).finish();
1221        let allocation = rucc_regalloc::run(&mut func, &env(&SYSV, 4), "test");
1222        let base = Layout::new(&SYSV, REGS);
1223        let layout = Layout { leaf: false, ..base };
1224        let lines = written(&mut func, &allocation, &layout, &mut names);
1225
1226        // Both ways out get the frame given back, and the block that goes somewhere gets nothing,
1227        // because a block with an edge out of it is not a block anything returns from.
1228        assert_eq!(
1229            lines,
1230            [
1231                "mfunc @f {",
1232                "block0:",
1233                "$rsp = x64.sub_ri_64 $rsp, 8",
1234                "x64.nop block1, block2",
1235                "block1:",
1236                "x64.nop",
1237                "$rsp = x64.add_ri_64 $rsp, 8",
1238                "x64.ret",
1239                "block2:",
1240                "x64.nop",
1241                "$rsp = x64.add_ri_64 $rsp, 8",
1242                "x64.ret",
1243                "}",
1244            ]
1245        );
1246    }
1247
1248    #[test]
1249    fn a_protected_function_writes_the_canary_last_and_checks_it_before_it_returns() {
1250        let (mut func, allocation, mut names) = pressure(&SYSV, 4, 2);
1251        let base = Layout::new(&SYSV, REGS);
1252        let layout = Layout { leaf: false, protect: true, ..base };
1253        let guard = SYSV.guard.as_ref().expect("this convention has somewhere to keep the word");
1254        // The two the real pipeline holds back, which are held back in the environment above too:
1255        // it hands out the first two of the convention's order and keeps everything after them.
1256        let protect = Protect { guard, branch: &BRANCH, scratch: [R10, R11] };
1257        let lines = with_protector(&mut func, &allocation, &layout, Some(protect), &mut names);
1258
1259        // The read of the word and the store into the slot come after the stack pointer has moved,
1260        // because there is no slot to store into until it has. The check is the last thing the
1261        // block that returned does and the epilogue is on the arm the canary was unchanged on, so
1262        // a function whose canary changed never gives its frame back and never returns.
1263        assert_eq!(
1264            added(&lines),
1265            [
1266                "$rsp = x64.sub_ri_64 $rsp, 24",
1267                "$r10 = x64.mov_rm_64 [fs:40]",
1268                "x64.mov_mr_64 $r10, [$rsp + 16]",
1269                "x64.mov_mr_64 $rdx, [$rsp]",
1270                "x64.mov_mr_64 $rdx, [$rsp + 8]",
1271                "$rdx = x64.mov_rm_64 [$rsp]",
1272                "$rdx = x64.mov_rm_64 [$rsp + 8]",
1273                "$r10 = x64.mov_rm_64 [$rsp + 16]",
1274                "$r11 = x64.mov_rm_64 [fs:40]",
1275                "$r11 = x64.cmp_set_ne_64 $r10, $r11",
1276                "x64.br_cond_8 $r11, block1, block2",
1277                "x64.call @__stack_chk_fail",
1278                "$rsp = x64.add_ri_64 $rsp, 24",
1279                "x64.ret",
1280            ]
1281        );
1282    }
1283
1284    #[test]
1285    fn a_frame_that_fits_in_one_page_is_taken_in_one_subtraction_even_when_pages_are_touched() {
1286        let (mut func, allocation, mut names) = pressure(&SYSV, 2, 4);
1287        let locals = [Local { size: 4088, align: 16 }];
1288        let base = Layout::new(&SYSV, REGS);
1289        let layout = Layout { leaf: false, locals: &locals, ..base };
1290        let probing = Probing { probe: &PROBE, branch: &BRANCH, scratch: [R10, R11] };
1291        let lines = with_probing(&mut func, &allocation, &layout, Some(probing), &mut names);
1292
1293        // A frame of one page cannot step over the page below it, because the far end of it is the
1294        // near end of that page and anything written there is written to a page that is there. So
1295        // the flag costs such a function nothing, which is most functions.
1296        assert_eq!(
1297            added(&lines),
1298            ["$rsp = x64.sub_ri_64 $rsp, 4088", "$rsp = x64.add_ri_64 $rsp, 4088", "x64.ret",]
1299        );
1300    }
1301
1302    #[test]
1303    fn a_probing_prologue_touches_every_page_of_a_frame_a_few_pages_deep() {
1304        let (mut func, allocation, mut names) = pressure(&SYSV, 2, 4);
1305        let locals = [Local { size: 9000, align: 16 }];
1306        let base = Layout::new(&SYSV, REGS);
1307        let layout = Layout { leaf: false, locals: &locals, ..base };
1308        let probing = Probing { probe: &PROBE, branch: &BRANCH, scratch: [R10, R11] };
1309        let lines = with_probing(&mut func, &allocation, &layout, Some(probing), &mut names);
1310
1311        // A page of the stack pointer's own, then the touch that says the page is there, and only
1312        // then the next one, which is the whole of the defence: nothing here ever moves the stack
1313        // pointer further than one page without writing where it landed. The last subtraction is
1314        // the remainder and is smaller than a page, so it needs no touch of its own, and it exists
1315        // in every frame because the count of pages is taken off one less than the size.
1316        assert_eq!(
1317            added(&lines),
1318            [
1319                "$rsp = x64.sub_ri_64 $rsp, 4096",
1320                "x64.or_mi_8 [$rsp], 0",
1321                "$rsp = x64.sub_ri_64 $rsp, 4096",
1322                "x64.or_mi_8 [$rsp], 0",
1323                "$rsp = x64.sub_ri_64 $rsp, 808",
1324                "$rsp = x64.add_ri_64 $rsp, 9000",
1325                "x64.ret",
1326            ]
1327        );
1328    }
1329
1330    #[test]
1331    fn a_probing_prologue_deeper_than_that_walks_the_pages_in_a_loop() {
1332        let (mut func, allocation, mut names) = pressure(&SYSV, 2, 4);
1333        let locals = [Local { size: 100_000, align: 16 }];
1334        let base = Layout::new(&SYSV, REGS);
1335        let layout = Layout { leaf: false, locals: &locals, ..base };
1336        let probing = Probing { probe: &PROBE, branch: &BRANCH, scratch: [R10, R11] };
1337        let lines = with_probing(&mut func, &allocation, &layout, Some(probing), &mut names);
1338
1339        // Twenty-four pages, which is more than a straight line is worth, so the prologue works out
1340        // where it is going first and then walks there. The whole listing rather than the added
1341        // lines, because what matters as much as the instructions is that the two blocks the walk
1342        // is made of come in front of the block the function began with: the body the allocator
1343        // filled is block2 here and it was block0 before this ran.
1344        assert_eq!(
1345            lines,
1346            [
1347                "mfunc @f {",
1348                "block0:",
1349                "$r10 = x64.lea_64 [$rsp - 98304], block1",
1350                "block1:",
1351                "$rsp = x64.sub_ri_64 $rsp, 4096",
1352                "x64.or_mi_8 [$rsp], 0",
1353                "$r11 = x64.cmp_set_ne_64 $rsp, $r10",
1354                "x64.br_cond_8 $r11, block1, block2",
1355                "block2:",
1356                "$rsp = x64.sub_ri_64 $rsp, 1704",
1357                "$rax = x64.nop",
1358                "$rcx = x64.nop",
1359                "x64.nop $rax",
1360                "x64.nop $rcx",
1361                "$rsp = x64.add_ri_64 $rsp, 100008",
1362                "x64.ret",
1363                "}",
1364            ]
1365        );
1366    }
1367
1368    #[test]
1369    fn a_vector_register_a_windows_call_preserves_is_stored_and_read_back() {
1370        let mut names = Interner::new();
1371        let mut func = Func::new(names.intern("f"));
1372        let opcode = Opcode::new(names.intern("x64.nop"));
1373        let block = func.create_block();
1374        // An instruction that writes one of the vector registers Windows preserves, which is what
1375        // a rule for something that has to use it produces.
1376        func.build(block, opcode).operand(Operand::write(Reg::physical(xmm(6)), XMM)).finish();
1377        let allocation = rucc_regalloc::run(&mut func, &env(&WIN64, 4), "test");
1378        let lines = written(&mut func, &allocation, &Layout::new(&WIN64, REGS), &mut names);
1379
1380        // No machine here pushes a vector register, so it is stored into the frame rather than
1381        // pushed, and the frame has to be taken before there is anywhere to put it.
1382        assert_eq!(
1383            added(&lines),
1384            [
1385                "$rsp = x64.sub_ri_64 $rsp, 24",
1386                "x64.movaps_mr $xmm6, [$rsp]",
1387                "$xmm6 = x64.movaps_rm [$rsp]",
1388                "$rsp = x64.add_ri_64 $rsp, 24",
1389                "x64.ret",
1390            ]
1391        );
1392    }
1393}