Skip to main content

rucc_codegen/
pipeline.rs

1//! One IR function to one machine function, which is every pass in this crate in order.
2//!
3//! Design: `spec/10-backend.md` section 10.1, which is where the order comes from.
4//!
5//! Each pass here is written and tested on its own and each is useful on its own, but there is
6//! exactly one order they run in and until now that order lived in the tests. A caller outside
7//! this crate would have had to know that splitting critical edges comes after lowering and
8//! before allocation, that the frame is worked out after allocation because the spill slots are
9//! the largest thing in it, and that the prologue is written after the frame. None of that is a
10//! decision a driver should be making, so it is written down once, here.
11//!
12//! # What comes out
13//!
14//! A function whose every register is physical, whose every offset into the frame is a constant,
15//! and whose blocks are in the order they run in with the jumps that order needs. That is the
16//! point at which a function is one an encoder could read, and there is nothing left in it that
17//! is not an instruction of the machine it was compiled for.
18//!
19//! # What is still missing from the middle
20//!
21//! The optimizing path, all of it. What runs here is `spec/10-backend.md` section 10.3's fast
22//! path: one rule per term, a linear scan, and a block order from the shape of the CFG rather
23//! than from block frequency. No scheduling, and the redundant moves a coalescer would take out
24//! are still in the output.
25
26use rucc_base::Interner;
27use rucc_ir as ir;
28use rucc_mir as mir;
29use rucc_regalloc::assign::Env;
30use rucc_target::{
31    BitInsts, BranchInsts, CallRegs, FlagInsts, FrameInsts, MachineInsts, PhysReg, RegFile,
32    TargetInfo, x86_64,
33};
34use rucc_tuple::Arch;
35
36use crate::bits;
37use crate::compare;
38use crate::copies;
39use crate::coverage::Fired;
40use crate::elsewhere::Elsewhere;
41use crate::expand;
42use crate::finish::{Convention, Padding, Probing, Protect, Tracing, finish};
43use crate::fold;
44use crate::frame::{self, Frame, Layout};
45use crate::layout;
46use crate::lower::{self, Unsupported};
47use crate::pressure::{Cost, Pressure};
48use crate::quad;
49use crate::retry;
50use crate::slots::{self, Slots};
51use crate::split;
52use crate::switch;
53use crate::varargs;
54use crate::weights;
55use crate::wide;
56use crate::widths;
57
58/// Everything about a machine that compiling a function for it needs.
59///
60/// The fields are different kinds of fact and they come from different places: where the
61/// convention puts things, what registers the machine has, which instructions build a frame,
62/// which instructions a branch becomes, and which registers the allocator may hand out. The last
63/// one is not a target fact on its own, because holding a register back as scratch is a decision
64/// about the allocator rather than about the machine, which is why it is built here rather than
65/// in [`rucc_target`].
66#[derive(Debug)]
67pub struct Machine {
68    /// Where the convention this function is compiled for puts things.
69    pub conv: &'static CallRegs,
70    /// The registers the machine has, which is what says how wide a spill slot of a class is.
71    pub file: RegFile,
72    /// The instructions that take a frame and give it back.
73    pub insts: &'static FrameInsts,
74    /// The instructions a branch becomes once the blocks are in an order.
75    pub branch: &'static BranchInsts,
76    /// How much of a register each of the machine's instructions reads and writes.
77    pub bits: &'static BitInsts,
78    /// What each of the machine's instructions leaves in the condition state.
79    pub flags: &'static FlagInsts,
80    /// What shape each of the machine's instructions is, which is what a pass proposing a new one
81    /// has its proposal held against.
82    pub shapes: &'static MachineInsts,
83    /// What the allocator may hand out, and what it holds back.
84    pub env: Env,
85}
86
87/// The scratch registers held back from the allocator on x86-64.
88///
89/// Two, because a move on an edge may have to break a cycle and a spilled value has to be read
90/// into something, and those can want a register at the same instruction. Two is also what the
91/// instruction wanting most wants, which is one that reads two spilled values and writes a third,
92/// and `rewrite` says why the answer goes back into a register an operand arrived in rather than
93/// asking for a third.
94///
95/// It is not two because two was enough to start with and nobody looked again. There is no third
96/// to hold back. A scratch register has to be one the convention passes nothing in, since the
97/// rewriter puts moves in wherever it likes, and one the callee does not owe back, since the
98/// rewriter runs after the prologue has been decided and cannot ask for a register to be saved.
99/// On SysV that is `r10` and `r11` and nothing else, so if the rewriter ever does want a third the
100/// answer is not to take one here.
101const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
102
103/// How many of each class are held back.
104const SCRATCH_COUNT: usize = SCRATCH.len();
105
106impl Machine {
107    /// The x86-64 machine under that convention.
108    ///
109    /// Both files are offered. A value the selector produces is in one or the other, which is
110    /// decided by its type: an integer and an address are general purpose and a `float` or a
111    /// `double` is in a vector register, and the allocator is given each file separately because
112    /// no move goes between them.
113    #[must_use]
114    pub fn x86_64(conv: &'static CallRegs) -> Self {
115        let order: Vec<PhysReg> =
116            conv.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
117        // The vector file wants its own two, for the same two jobs, and they have to be two the
118        // convention does not preserve: a scratch register is written by a move the rewriter puts
119        // in, which is after the prologue has already been decided, so one the callee owes back
120        // would be one nothing saved. That rules out the upper ten on Windows and nothing at all
121        // on SysV, and taking the last two that are left lands on `xmm14` and `xmm15` there and on
122        // `xmm4` and `xmm5` on Windows, neither of which any argument travels in.
123        let free: Vec<PhysReg> =
124            conv.sse_order.iter().copied().filter(|&reg| !conv.preserves_sse(reg)).collect();
125        let at = free.len().saturating_sub(SCRATCH_COUNT);
126        let sse_scratch: Vec<PhysReg> = free[at..].to_vec();
127        let sse_order: Vec<PhysReg> =
128            conv.sse_order.iter().copied().filter(|reg| !sse_scratch.contains(reg)).collect();
129        Self {
130            conv,
131            file: x86_64::REGS,
132            insts: &x86_64::FRAME,
133            branch: &x86_64::BRANCH,
134            bits: &x86_64::BITS,
135            flags: &x86_64::FLAGS,
136            shapes: &x86_64::MACHINE,
137            env: Env::new().with(x86_64::GPR, &order, &SCRATCH).with(
138                x86_64::XMM,
139                &sse_order,
140                &sse_scratch,
141            ),
142        }
143    }
144
145    /// The machine a target describes, or `None` when no backend in this crate covers it.
146    ///
147    /// [`TargetInfo`] already carries the convention, because the front end needs it to lay a
148    /// `va_list` out, so the only thing this decides is which architecture's frame instructions
149    /// and register file go with it. AArch64 and RISC-V are `None` until M6 fills them in, and a
150    /// caller that gets one reports a target it cannot compile for rather than compiling wrongly.
151    #[must_use]
152    pub fn for_target(target: &TargetInfo) -> Option<Self> {
153        let conv = target.call_regs?;
154        match target.tuple.arch() {
155            Arch::X86_64 => Some(Self::x86_64(conv)),
156            _ => None,
157        }
158    }
159}
160
161/// Whether every function calls a profiler on the way in, and where that call goes.
162///
163/// What `-pg` asks for, with `-mfentry` and `-mno-fentry` choosing between the last two. The choice
164/// has already been made against the target by the time this is built, which is why there is no
165/// answer here for a command line that named neither.
166#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
167pub enum Profile {
168    /// It does not, which is what nearly every command line asks for.
169    #[default]
170    No,
171    /// In front of the prologue, which is the hook a tracer can replace while the program runs.
172    Early,
173    /// Once the frame is taken, which is the hook that reads the frame pointer.
174    Late,
175}
176
177/// How much room every function opens with for something to be written over it later.
178///
179/// What `-fpatchable-function-entry=` asks for, as the two halves a prologue deals in rather than
180/// as the total and the part the flag is written in. The room can be on either side of the
181/// function's own label and the two sides are not the same thing: what is after the label is inside
182/// the function, which is what a patcher redirecting a call into it wants, and what is in front of
183/// it is outside, which is where a patcher that needs a whole instruction it can reach from the
184/// first one puts it.
185#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
186pub struct Room {
187    /// How many bytes go after the function's own label.
188    pub after: u32,
189    /// How many go in front of it.
190    pub before: u32,
191}
192
193impl Room {
194    /// Whether any room at all was asked for, which is what decides whether a function gets one.
195    ///
196    /// `=0` is a command line that asked for none, and gcc takes it and writes nothing, so the
197    /// question is about the numbers rather than about whether the flag was written.
198    #[must_use]
199    pub const fn any(self) -> bool {
200        self.after > 0 || self.before > 0
201    }
202}
203
204/// What the command line says about a frame, as opposed to what the machine says.
205#[derive(Debug, Clone, Copy, PartialEq, Eq)]
206pub struct Flags {
207    /// Whether every function keeps a frame pointer, which `-fno-omit-frame-pointer` asks for.
208    pub frame_pointer: bool,
209    /// Whether the red zone may be used, which `-mno-red-zone` and every kernel turns off.
210    pub red_zone: bool,
211    /// Whether a frame is taken a page at a time, which `-fstack-clash-protection` asks for.
212    pub stack_clash: bool,
213    /// Whether every address an indirect branch may arrive at opens with a landing pad, which
214    /// `-fcf-protection=branch` asks for. That is every function, and every label of a function
215    /// whose address the program took.
216    pub landing: bool,
217    /// Whether every function calls a profiler on the way in, which `-pg` asks for.
218    pub profile: Profile,
219    /// How much room every function opens with for a patcher, which
220    /// `-fpatchable-function-entry=` asks for. See [`Room`].
221    pub patch: Room,
222    /// Whether the blocks are put in the order the weights say rather than in the order the
223    /// shape of the graph says, which `-freorder-blocks` asks for and every level above `-O0`
224    /// turns on. See [`crate::layout`].
225    pub reorder: bool,
226    /// Whether two things in the frame that are never both wanted may be the same bytes, which
227    /// `-fstack-reuse=none` turns off. See [`crate::slots`].
228    pub reuse: bool,
229}
230
231impl Default for Flags {
232    /// No frame pointer, the red zone allowed, the frame taken in one subtraction, no landing pad,
233    /// no profiling, no room for a patcher, the blocks in the order the graph's shape gives and
234    /// nothing in the frame sharing with anything, which is what a convention that has a red zone
235    /// says at `-O0` when nobody on the command line has said otherwise.
236    fn default() -> Self {
237        Self {
238            frame_pointer: false,
239            red_zone: true,
240            stack_clash: false,
241            landing: false,
242            profile: Profile::No,
243            patch: Room::default(),
244            reorder: false,
245            reuse: false,
246        }
247    }
248}
249
250/// Compiles one function, from the IR the middle end produced to machine instructions.
251///
252/// The function is taken by reference that can be written through, because the first pass is an
253/// IR to IR rewrite: a construct whose lowering is a new shape of control flow cannot be a rule,
254/// since a rule replaces a term with a term and has nowhere to put a block. So the IR that reaches
255/// selection is not quite the IR the middle end produced, and this is the only place that is true.
256/// `--emit=ir` prints before any of this runs.
257///
258/// `elsewhere` is the one thing here that is a fact about the module rather than about the
259/// function, and it is passed in rather than looked up because this only ever sees the one
260/// function. What it decides is how the address of a name is come by, which is the difference
261/// between an address this file can measure to and one only the linker knows.
262///
263/// # Errors
264///
265/// The first thing in it this cannot lower, which is what [`lower::func`] reports, and one thing
266/// after it that is about the shape of the function rather than about an instruction, which is a
267/// frame that grows while it runs in a function whose flags say no frame may. Everything else after
268/// lowering works on machine instructions that exist, so it either runs or it is a bug in this
269/// crate.
270pub fn compile(
271    source: &mut ir::Func,
272    names: &mut Interner,
273    machine: &Machine,
274    elsewhere: &Elsewhere,
275    flags: Flags,
276) -> Result<mir::Func, Unsupported> {
277    compile_recording(
278        source,
279        names,
280        machine,
281        elsewhere,
282        flags,
283        &mut Fired::new(),
284        &mut Pressure::new(),
285    )
286}
287
288/// The same compilation, with what it did along the way recorded.
289///
290/// Two functions rather than one that takes options, because a caller that does not want the
291/// numbers should not have to say so. What `fired` is for is `-Zrule-coverage`, which is how the
292/// harness in `tamnd/rucc-compat` turns coverage of the rule set into a number over a corpus. What
293/// `pressure` is for is `-Zregister-pressure`, which is how much of the frame the allocator had to
294/// use and is the metric `spec/safe-memory/13-performance.md` section 13.1 asks for.
295///
296/// Both are added to rather than replaced, so a caller can pass the same pair for every function of
297/// a module and every module of a command line and get the answer for all of them.
298///
299/// # Errors
300///
301/// The same as [`compile`]. A function that was refused contributes nothing to either, since a
302/// function that did not compile is not evidence about what a rule set or a frame would have done.
303pub fn compile_recording(
304    source: &mut ir::Func,
305    names: &mut Interner,
306    machine: &Machine,
307    elsewhere: &Elsewhere,
308    flags: Flags,
309    fired: &mut Fired,
310    pressure: &mut Pressure,
311) -> Result<mir::Func, Unsupported> {
312    switch::switches(source);
313    // Beside the switches rather than down with the rest of the rewriting, because both of them
314    // make blocks and nothing in `expand` may. Before the orderings as well, since the head of the
315    // loop it builds reads with an `atomic_load` and the pass below is what turns that into the
316    // plain load this machine does anyway.
317    retry::loops(source);
318    // Before the width legalisation and everything after it, because what an ordered access
319    // becomes here is a plain one and every pass below is written about a plain one by name.
320    expand::orderings(source, machine.conv.word);
321    // Above the splitting rather than below it, because an overflow check is the one instruction
322    // whose result is two things and the splitting has no answer for that, while the arithmetic it
323    // becomes here is adds, multiplies and comparisons the splitting knows already. Nothing is lost
324    // by running it this early: the widths it is written for are the widths the machine has, and
325    // the legalisation below never touches one of these anyway, so a check at a width neither pass
326    // is written for is refused by name either way round.
327    expand::overflows(source);
328    // Ahead of the width legalisation and not part of it, because the two go in opposite
329    // directions: an integer of forty bits becomes one of sixty four down there, and one of a
330    // hundred and twenty eight becomes two of sixty four here. Doing this first means a function
331    // holding both is one the pass below still works on, since by the time it runs the only widths
332    // left are ones it has an answer for.
333    wide::halves(source, names, machine.conv);
334    // Before everything, because every pass after it is written about widths the machine has and
335    // an integer of forty bits is not one of them.
336    widths::integers(source);
337    expand::bytes(source);
338    expand::counts(source);
339    // Above the float rewriting rather than part of it, because the two are written about different
340    // machines: every rewrite down there ends at an instruction this one has, and every operation up
341    // here ends at a call because this machine has no instruction at the format at all. Running
342    // first means the pass below never sees a quad, so its rules about what it will not touch above
343    // sixty four bits are about the eighty bit format and nothing else.
344    quad::calls(source, names);
345    expand::floats(source);
346    expand::bulk(source, names, machine.conv.word);
347    expand::rounds(source, machine.conv.stack_align);
348    varargs::lists(source, machine.conv);
349    let lowered = lower::func(source, names, machine.conv, elsewhere)?;
350    fired.merge(&lowered.fired);
351    let lower::Lowered { mut func, mut stack, blocks, .. } = lowered;
352    // Straight after selection, because this is the last moment the machine blocks and the IR
353    // blocks still stand one for one, and the pass that reads the numbers is the very last one
354    // there is. See `crate::weights`.
355    if flags.reorder {
356        weights::carry(source, &blocks, &mut func);
357    }
358    // Two things a frame that grows while it runs cannot be asked for at the same time, both of
359    // them refusals rather than wrong code.
360    if let Some(inst) = stack.grown_at {
361        // What `-fstack-clash-protection` buys is that no frame ever steps over a guard page
362        // without touching it, and a frame that grows while it runs steps by however much the
363        // declaration asked for. The prologue's own pages are touched below, and the ones a
364        // variable length array takes are not, so a function with both is refused rather than
365        // compiled to something that keeps the flag's name and not its promise.
366        if flags.stack_clash {
367            return Err(Unsupported::Dynamic { inst, growing: lower::Growing::Probed });
368        }
369        // The lowering refuses a variable length array that asks for more alignment than a call
370        // leaves the stack pointer on. A fixed local asking for it in the same function is the same
371        // refusal arrived at from the other side: the prologue would force the alignment, and
372        // forcing it and moving the stack pointer afterwards are two frames that each want the one
373        // register that still reaches the rest of the frame. See `Growing` in [`crate::frame`].
374        if stack.locals.iter().any(|local| local.align > machine.conv.stack_align) {
375            return Err(Unsupported::Dynamic { inst, growing: lower::Growing::Aligned });
376        }
377    }
378
379    // Before the fold below, which is the order section 37.6 puts the two in. A widening this takes
380    // out is one whose readers are sent to its source, and one of those readers may be an address
381    // computation, so asking which bits are read first means the fold sees the addresses as they
382    // will be rather than as they were.
383    bits::dead(&mut func, machine.bits, machine.shapes, names);
384
385    // After selection, because the address instruction and the one that reads it are both machine
386    // instructions only once selection has written them, and before allocation, because what makes
387    // the pair safe to put together is that a virtual register is written once. The addresses into
388    // the frame and into the caller's argument area go through it like anything else, and the two
389    // lists `finish` reads are rewritten as they do, so an address that ends up inside its reader
390    // is still an address the frame layout knows to write an offset into.
391    let mut pending = fold::Pending {
392        addresses: &mut stack.addresses,
393        arguments: &mut stack.arguments,
394        dynamic: &mut stack.dynamic,
395    };
396    fold::addresses(&mut func, machine.insts, machine.shapes, names, &mut pending);
397
398    // Whether this function carries a canary is the front end's answer, because what
399    // `-fstack-protector` asks about is the kind of local a function has and the types are gone by
400    // here. What the machine does about it is this crate's answer, and a target with nowhere to
401    // keep the word a canary is copied from does nothing, which is what the driver refuses a
402    // command line over before any of this runs.
403    let protect = source.attrs.set.contains(ir::AttrSet::STACK_PROTECT);
404    let guard = protect.then_some(machine.conv.guard.as_ref()).flatten();
405    // Nothing at all on a target with no hook to call, which is the same answer the protector gives
406    // on a target with nowhere to keep its word, and the driver refuses the command line over it
407    // before any of this runs.
408    let profile = match machine.conv.trace {
409        Some(_) => flags.profile,
410        None => Profile::No,
411    };
412    let base = stack.layout(Layout::new(machine.conv, machine.file));
413    let layout = Layout {
414        // The later hook reads the frame pointer to find out who called this function, so a
415        // function that calls it is given one whether or not anything else asked. A function that
416        // asked where its own frame is has the same claim on one, and for a plainer reason: the
417        // register is the answer.
418        frame_pointer: flags.frame_pointer || profile == Profile::Late || stack.walks_frames,
419        red_zone: flags.red_zone,
420        protect: guard.is_some(),
421        // A protected function calls the one that does not come back, on the arm where the check
422        // failed, so it is not a leaf however few calls the program wrote in it. That is what
423        // takes the red zone away from it and what makes its frame leave the stack pointer where
424        // a call needs it. The later hook is a call in the same position and costs the same.
425        //
426        // The earlier one is not, and this is the one place the difference shows. It runs before
427        // the prologue has written anything, so the bytes below the stack pointer it uses are ones
428        // this function has not put anything in yet, and a leaf that keeps its locals down there
429        // stays a leaf. gcc leaves it alone too.
430        leaf: base.leaf && guard.is_none() && profile != Profile::Late,
431        ..base
432    };
433
434    // Before allocation as well, and asked here rather than where it is used because what it asks
435    // is whether anything but the branch reads the byte a comparison wrote. A virtual register is
436    // written once and a physical one is not, so after allocation that question no longer has an
437    // answer.
438    let fusable = layout::fusable(&func, machine.branch, names);
439
440    // In front of the splitting below, because what it does is take the values off the edges out of
441    // a computed `goto` and the splitting has no answer for one of those: the block they leave ends
442    // in a jump already, so neither end of the edge is somewhere a move can go.
443    split::indirect(&mut func, machine.branch, machine.insts, names);
444
445    // And after it, because what it puts a pad at is the block an address names and the pass above
446    // is what settles which block that is. The pad the prologue opens with is written much later,
447    // with the rest of the prologue, since the address it answers for is the function's own.
448    //
449    // Nothing at all on a target with nothing that marks an address as one an indirect branch may
450    // arrive at, which is the same answer the stack protector gives on a target with nowhere to
451    // keep its word, and the driver refuses the command line over it before any of this runs.
452    let landing = flags.landing.then_some(machine.insts.landing).flatten();
453    split::pads(&mut func, machine.insts, landing, names);
454
455    // Before allocation, because an edge that carries values into a block arrived at more than
456    // one way, out of a block that leaves more than one way, has nowhere to put the moves those
457    // values turn into, and the allocator asserts rather than guessing.
458    split::critical(&mut func);
459
460    // Before allocation, because how far the address of a local gets is a question about values and
461    // a value is written once only until the allocator's rewrite has been through. What is done
462    // with the answer waits until afterwards, since the liveness it is read against is the
463    // allocator's. See [`crate::slots`].
464    let reach = flags
465        .reuse
466        .then(|| slots::reach(&func, &stack.addresses, stack.locals.len(), machine.insts, names));
467
468    let called = names.resolve(func.name).to_owned();
469    let allocation = rucc_regalloc::run(&mut func, &machine.env, &called);
470    pressure.record(&called, Cost::of(&allocation));
471
472    // After allocation, because the largest area in most frames is the spill slots and nothing
473    // knows how many of those there are until the allocator has finished running out of registers,
474    // and because a spill slot cannot be shared with a local until it is known there is one.
475    let share = reach.map(|reach| {
476        let widths = frame::widths(&layout, &allocation);
477        Slots::share(&func, &reach, &allocation, &stack.locals, &widths)
478    });
479    let layout = Layout { share: share.as_ref(), ..layout };
480    let frame = Frame::of(&func, &allocation, &layout);
481    let scratch = machine.env.scratch(machine.conv.int_class);
482    let protect = guard.map(|guard| Protect {
483        guard,
484        branch: machine.branch,
485        scratch: [scratch[0], scratch[1]],
486    });
487    // A target with no instruction that touches a page without changing it does nothing about the
488    // flag, which is the same answer the protector gives on a target with nowhere to keep its word.
489    // Every target this crate has a back end for has one.
490    let probe = flags
491        .stack_clash
492        .then_some(machine.insts.probe.as_ref())
493        .flatten()
494        .map(|probe| Probing { probe, branch: machine.branch, scratch: [scratch[0], scratch[1]] });
495    let trace = machine.conv.trace.and_then(|trace| match profile {
496        Profile::No => None,
497        Profile::Early => Some(Tracing { name: trace.early, early: true }),
498        Profile::Late => Some(Tracing { name: trace.late, early: false }),
499    });
500    // And once more for the room a patcher was promised, which is a run of the shortest
501    // instruction that does nothing and so needs the target to have one. Nothing is written on a
502    // target that does not, rather than a run of something longer: the flag counts bytes, and a
503    // patcher writing over the room starts at its front and wants every byte in it to be a place
504    // it could have started at.
505    let pad = flags.patch.any().then_some(machine.insts.pad).flatten().map(|name| Padding {
506        name,
507        before: flags.patch.before,
508        after: flags.patch.after,
509    });
510    let convention = Convention {
511        protect,
512        probe,
513        landing,
514        trace,
515        pad,
516        ..Convention::new(machine.conv, machine.insts)
517    };
518    let moves = finish(&mut func, &allocation, &frame, &stack, convention, names);
519
520    // After the moves are written, because a spill and the reload of it are written by different
521    // decisions of the allocator and what stands between the two is settled by the function they
522    // both went into. Before the layout, because the layout is where the instruction sequence
523    // stops being something a pass may edit.
524    copies::clean(&mut func, &moves, machine.shapes, machine.insts, machine.conv, names);
525
526    // Last, because everything before this finds the blocks a function returns from by looking
527    // for the ones that go nowhere, and after this a block that falls through goes nowhere too.
528    layout::blocks(&mut func, machine.branch, names, &fusable, flags.reorder);
529
530    // After the layout rather than before it, which is the whole of what makes it safe. What a
531    // comparison leaves for the instruction behind it to read is not a register and nothing may
532    // come between the two, and the layout is the other pass that writes such a pair. Running
533    // here means there is nothing left that could put an instruction in the middle of one.
534    compare::redundant(&mut func, machine.flags, machine.shapes, names);
535    Ok(func)
536}
537
538#[cfg(test)]
539mod tests {
540    use rucc_ir::{Builder, Flags as IrFlags, Func, Opcode, Restrict, Signature, Type};
541    use rucc_target::x86_64::{REGS, SYSV, WIN64};
542
543    use super::*;
544
545    /// A function of two integers, and the block to fill.
546    fn blank(params: &[Type]) -> (Interner, Func, ir::Block, Vec<ir::Value>) {
547        let mut names = Interner::new();
548        let mut func = Func::new(names.intern("f"), Signature::new());
549        let block = func.create_block();
550        let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
551        (names, func, block, values)
552    }
553
554    #[test]
555    fn a_function_comes_out_with_no_virtual_register_left_in_it() {
556        let i32 = Type::int(32);
557        let (mut names, mut source, block, args) = blank(&[i32, i32]);
558        let mut build = Builder::new(&mut source, block);
559        let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
560        build.ret(&[sum]);
561
562        let machine = Machine::x86_64(&SYSV);
563        let out =
564            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
565                .expect("every instruction has a rule");
566
567        // `int f(int a, int b) { return a + b; }` end to end. A leaf that spills nothing needs no
568        // frame at all, so there is no prologue to see. The one move left is the one the machine's
569        // addition needs, since the sum is written into the register the left operand was read
570        // from and the return wants it in `rax`.
571        assert_eq!(
572            mir::print_func(&out, &names, &REGS),
573            "mfunc @f {\n\
574             block0:\n    \
575             $rdi($rdi) = x64.arg_val_32\n    \
576             $rsi($rsi) = x64.arg_val_32\n    \
577             $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n    \
578             $rax = x64.mov_rr_64 $rdi\n    \
579             x64.ret_val_32 $rax($rax)\n    \
580             x64.ret\n\
581             }\n"
582        );
583    }
584
585    /// What `-Zrule-coverage` is built out of: the rules a compilation fired, recorded as it went.
586    /// The second function adds to the first rather than replacing it, which is what makes one of
587    /// these files the answer for a whole command line rather than for whichever function was last.
588    #[test]
589    fn which_rules_lowered_a_function_is_something_the_compilation_can_be_asked_for() {
590        let i32 = Type::int(32);
591        let (mut names, mut source, block, args) = blank(&[i32, i32]);
592        let mut build = Builder::new(&mut source, block);
593        let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
594        build.ret(&[sum]);
595
596        let machine = Machine::x86_64(&SYSV);
597        let mut fired = Fired::new();
598        compile_recording(
599            &mut source,
600            &mut names,
601            &machine,
602            &Elsewhere::default(),
603            Flags::default(),
604            &mut fired,
605            &mut Pressure::new(),
606        )
607        .expect("every instruction has a rule");
608        let one = fired.count();
609        assert!(one > 0, "an add and a return went through the table and nothing was recorded");
610
611        let listing = fired.listing(&crate::select::x86_64::TABLE);
612        assert_eq!(listing.lines().filter(|line| line.starts_with("fired ")).count(), one);
613        assert!(
614            listing.contains(&format!("{one} of ")),
615            "{}",
616            listing.lines().next().unwrap_or("")
617        );
618
619        // The same rules again plus the ones a subtraction needs, into the same record.
620        let (mut names, mut source, block, args) = blank(&[i32, i32]);
621        let mut build = Builder::new(&mut source, block);
622        let difference = build.binary(Opcode::Sub, args[0], args[1], IrFlags::default());
623        build.ret(&[difference]);
624        compile_recording(
625            &mut source,
626            &mut names,
627            &machine,
628            &Elsewhere::default(),
629            Flags::default(),
630            &mut fired,
631            &mut Pressure::new(),
632        )
633        .expect("every instruction has a rule");
634        assert!(fired.count() > one, "a subtraction is not an addition");
635    }
636
637    #[test]
638    fn a_function_that_calls_takes_a_frame_and_gives_it_back() {
639        let i32 = Type::int(32);
640        let (mut names, mut source, block, args) = blank(&[i32]);
641        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
642        let callee = names.intern("g");
643        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
644        let got = source[call].first_result.expect("an integer comes back");
645        let mut build = Builder::new(&mut source, block);
646        let sum = build.binary(Opcode::Add, got, args[0], IrFlags::default());
647        build.ret(&[sum]);
648
649        let machine = Machine::x86_64(&SYSV);
650        let out =
651            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
652                .expect("every instruction has a rule");
653
654        // `int f(int a) { return g(a) + a; }`. Not a leaf, so the stack pointer moves and the
655        // register the value that outlives the call went to is one the prologue saves.
656        let text = mir::print_func(&out, &names, &REGS);
657        assert!(text.contains("x64.push_64 $rbx"), "{text}");
658        assert!(text.contains("$rbx = x64.pop_64"), "{text}");
659        assert!(text.contains("x64.call $rdi($rdi), @g"), "{text}");
660        assert!(!text.contains('%'), "{text}");
661    }
662
663    #[test]
664    fn the_other_convention_is_the_same_function_somewhere_else() {
665        let i32 = Type::int(32);
666        let (mut names, mut source, block, args) = blank(&[i32, i32]);
667        let mut build = Builder::new(&mut source, block);
668        let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
669        build.ret(&[sum]);
670
671        let machine = Machine::x86_64(&WIN64);
672        let out =
673            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
674                .expect("every instruction has a rule");
675
676        // The arguments arrive in `rcx` and `rdx` here rather than in `rdi` and `rsi`, which is
677        // the whole of what changed, and it changed because the convention was asked.
678        let text = mir::print_func(&out, &names, &REGS);
679        assert!(text.contains("$rcx($rcx) = x64.arg_val_32"), "{text}");
680        assert!(text.contains("$rdx($rdx) = x64.arg_val_32"), "{text}");
681        assert!(!text.contains("$rdi"), "{text}");
682    }
683
684    #[test]
685    fn a_function_with_a_branch_in_it_goes_through_every_pass() {
686        let i32 = Type::int(32);
687        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
688        let then = source.create_block();
689        let join = source.create_block();
690        let got = source.append_param(join, i32);
691        let mut build = Builder::new(&mut source, entry);
692        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
693        build.br_if(cond, then, &[], join, &[args[1]]);
694        Builder::new(&mut source, then).jump(join, &[args[0]]);
695        Builder::new(&mut source, join).ret(&[got]);
696
697        let machine = Machine::x86_64(&SYSV);
698        let out =
699            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
700                .expect("every instruction has a rule");
701
702        // The else arm is a critical edge carrying a value, so a block that nothing lowered is in
703        // there, which is the pass between lowering and allocation doing its job. Without it the
704        // allocator would have asserted rather than compiled this.
705        assert_eq!(out.block_count(), 4);
706
707        // `int f(int a, int b) { return a < b ? a : b; }` end to end, and the last pass is what
708        // this pins. The branch became a test and one jump, and it is the jump taken when the
709        // condition failed, because the arm the condition is true for is the block laid out next
710        // and a block falls into the block laid out next. The other arm is the empty block the
711        // edge splitting left, which is where the move the edge carries ended up, and it falls
712        // into the join as well. What is left is one jump in the whole function. Both arms write
713        // the join's parameter straight into `rax`, because the return at the bottom insists on
714        // that register and the moves the edges carry are free to name it.
715        let text = mir::print_func(&out, &names, &REGS);
716        assert_eq!(
717            text,
718            "mfunc @f {\n\
719             block0:\n    \
720             $rdi($rdi) = x64.arg_val_32\n    \
721             $rsi($rsi) = x64.arg_val_32\n    \
722             x64.cmp_rr_32 $rdi, $rsi\n    \
723             x64.jcc_ge block2, block1\n\
724             \nblock1:\n    \
725             $rax = x64.mov_rr_64 $rdi\n    \
726             x64.jmp block3\n\
727             \nblock2:\n    \
728             $rax = x64.mov_rr_64 $rsi, block3\n\
729             \nblock3:\n    \
730             x64.ret_val_32 $rax($rax)\n    \
731             x64.ret\n\
732             }\n"
733        );
734    }
735
736    /// A loop that swaps its two values round every time it goes, which is `gcd`, and which is
737    /// the smallest program that caught two ways of losing a value. Both were found by running
738    /// what came out rather than by reading it, and both are pinned here rather than only where
739    /// they were fixed, because what is wrong with either of them is only visible in the whole
740    /// function.
741    #[test]
742    fn a_loop_that_carries_its_values_round_keeps_all_of_them() {
743        let i32 = Type::int(32);
744        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
745        let head = source.create_block();
746        let body = source.create_block();
747        let exit = source.create_block();
748        let left = source.append_param(head, i32);
749        let right = source.append_param(head, i32);
750        Builder::new(&mut source, entry).jump(head, &[args[0], args[1]]);
751        let mut build = Builder::new(&mut source, head);
752        let zero = build.iconst(i32, 0);
753        let more = build.icmp(rucc_ir::IntPred::Ne, right, zero);
754        build.br_if(more, body, &[], exit, &[left]);
755        let mut build = Builder::new(&mut source, body);
756        let rest = build.binary(Opcode::SRem, left, right, IrFlags::default());
757        build.jump(head, &[right, rest]);
758        let result = source.append_param(exit, i32);
759        Builder::new(&mut source, exit).ret(&[result]);
760
761        let machine = Machine::x86_64(&SYSV);
762        let out =
763            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
764                .expect("every instruction has a rule");
765
766        // `int gcd(int a, int b) { while (b) { int t = a % b; a = b; b = t; } return a; }`. Two
767        // things in here were wrong and each of them returned three from a program that gcc
768        // returns forty two from.
769        //
770        // The first is in the entry block. The move the edge into the loop asks for writes `rsi`,
771        // and the second argument has to be taken out of `rsi` before it does. An edit at the end
772        // of a block used to go in front of the last instruction, on the reasoning that the last
773        // instruction is the branch, and the block's jump is not an instruction until the layout
774        // has run, so it went in front of the `arg_val` whose own move had not been made yet.
775        //
776        // The second is in the loop body. A division writes both a quotient and a remainder, and
777        // only the remainder is wanted here, so the quotient is a value nothing reads. It used to
778        // be given the same register as the remainder, because a value written early was live at
779        // one point and that point is in front of where the remainder is written. The copy that
780        // takes the quotient nowhere then landed on top of the remainder.
781        assert_eq!(
782            mir::print_func(&out, &names, &REGS),
783            "mfunc @f {\n\
784             block0:\n    \
785             $rdi($rdi) = x64.arg_val_32\n    \
786             $rsi($rsi) = x64.arg_val_32\n    \
787             $rcx = x64.mov_rr_64 $rdi, block1\n\
788             \nblock1:\n    \
789             x64.cmp_ri_32 $rsi, 0\n    \
790             x64.jcc_e block3, block2\n\
791             \nblock2:\n    \
792             $rax = x64.mov_rr_64 $rcx\n    \
793             $rdx($rdx), early $rax($rax) = x64.idiv_rem_32 $rax($rax), $rsi\n    \
794             $rdi = x64.mov_rr_64 $rax\n    \
795             $rcx = x64.mov_rr_64 $rsi\n    \
796             $rsi = x64.mov_rr_64 $rdx\n    \
797             x64.jmp block1\n\
798             \nblock3:\n    \
799             $rax = x64.mov_rr_64 $rcx\n    \
800             x64.ret_val_32 $rax($rax)\n    \
801             x64.ret\n\
802             }\n"
803        );
804    }
805
806    /// `spec/10-backend.md` section 10.1 says `--emit=mir-final` round-trips, and a function with
807    /// a branch in it is the one where that is worth checking: after the layout has run, where a
808    /// jump goes is nowhere in the instruction, so the text has to carry it on the block and the
809    /// parser has to put it back on the block it came off.
810    #[test]
811    fn a_function_that_has_been_laid_out_reads_back_as_the_same_function() {
812        let i32 = Type::int(32);
813        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
814        let then = source.create_block();
815        let join = source.create_block();
816        let got = source.append_param(join, i32);
817        let mut build = Builder::new(&mut source, entry);
818        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
819        build.br_if(cond, then, &[], join, &[args[1]]);
820        Builder::new(&mut source, then).jump(join, &[args[0]]);
821        Builder::new(&mut source, join).ret(&[got]);
822
823        let machine = Machine::x86_64(&SYSV);
824        let out =
825            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
826                .expect("every instruction has a rule");
827
828        let text = mir::print_func(&out, &names, &REGS);
829        let read = rucc_mir::parse(&text, &mut names, &REGS).expect("what the printer wrote");
830        assert_eq!(mir::print(&read, &names, &REGS), text);
831    }
832
833    #[test]
834    fn a_function_this_cannot_lower_is_reported_rather_than_compiled() {
835        let f80 = Type::float(rucc_ir::Float::F80);
836        let (mut names, mut source, block, args) = blank(&[f80, Type::int(64)]);
837        Builder::new(&mut source, block).ret(&args);
838
839        // One of these comes back on the x87 stack and a pair comes back in a pair of registers,
840        // and there is no pair with that stack in it. So this is refused rather than lowered, and
841        // it is the convention that refuses it rather than anything about the instructions.
842        let machine = Machine::x86_64(&SYSV);
843        let failed =
844            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
845                .expect_err("a long double cannot come back beside another value");
846        assert_eq!(failed.to_string(), "what this function gives back is on the x87 stack");
847    }
848
849    /// A `long double` in and a `long double` out, which is the whole of what the convention says
850    /// about the type and is two different answers rather than one.
851    ///
852    /// It arrives in the caller's argument area, so what the parameter is is the address of the
853    /// bytes and the function reads them where they are. It goes back on the x87 stack, so the
854    /// return is an `fld` and nothing else, and the value is still on that stack when the function
855    /// returns, which is the one time anything here leaves it that way.
856    ///
857    /// The addresses are gone from the instruction listing, which is [`crate::fold`]: an argument's
858    /// address is a `lea` off the stack pointer and the `fld` that reads it has room for that
859    /// address itself, so the offset the frame layout works out is written into the `fld`.
860    #[test]
861    fn a_long_double_arrives_in_memory_and_goes_back_on_the_x87_stack() {
862        let f80 = Type::float(rucc_ir::Float::F80);
863        let (mut names, mut source, block, args) = blank(&[f80, f80]);
864        let mut build = Builder::new(&mut source, block);
865        let sum = build.binary(Opcode::FAdd, args[0], args[1], IrFlags::default());
866        build.ret(&[sum]);
867
868        let machine = Machine::x86_64(&SYSV);
869        let out =
870            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
871                .expect("every instruction has a rule");
872
873        let text = mir::print_func(&out, &names, &REGS);
874        // The two parameters, sixteen bytes apart, read out of the caller's frame rather than out
875        // of a register, and the answer left on the stack by the last instruction in the function.
876        assert!(text.contains("x64.fld_t [$rsp + 32]"), "{text}");
877        assert!(text.contains("x64.fld_t [$rsp + 48]"), "{text}");
878        assert!(!text.contains("x64.lea_64"), "an address every reader took is gone: {text}");
879        assert!(!text.contains("x64.ret_val"), "nothing comes back in a register: {text}");
880        // What comes after the `fld` is the epilogue, which gives the frame back and touches
881        // nothing in the unit, so the value is where the caller looks for it when the `ret` runs.
882        let end: Vec<&str> = text.lines().rev().skip(1).take(3).map(str::trim).collect();
883        assert_eq!(end, ["x64.ret", "$rsp = x64.add_ri_64 $rsp, 24", "x64.fld_t [$rsp]"], "{text}");
884    }
885
886    /// The whole of the second register class, end to end: two floats arrive in vector registers,
887    /// the arithmetic happens in one, and the answer goes back in the register the convention
888    /// names. Nothing here touches the general purpose file, which is the point.
889    #[test]
890    fn a_float_is_added_in_the_register_file_it_arrives_in() {
891        let f32 = Type::float(rucc_ir::Float::F32);
892        let (mut names, mut source, block, args) = blank(&[f32, f32]);
893        let mut build = Builder::new(&mut source, block);
894        let sum = build.binary(Opcode::FAdd, args[0], args[1], ir::Flags::default());
895        build.ret(&[sum]);
896
897        let machine = Machine::x86_64(&SYSV);
898        let out =
899            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
900                .expect("every instruction has a rule");
901
902        let text = mir::print_func(&out, &names, &REGS);
903        assert!(text.contains("x64.addss_rr"), "{text}");
904        assert!(text.contains("$xmm0"), "{text}");
905        assert!(!text.contains("$rax"), "{text}");
906    }
907
908    /// A float moved between a register and memory, which is the instruction that decides which
909    /// file the value is in and is a different one from the `mov` that moves the same four bytes.
910    #[test]
911    fn a_float_read_from_memory_and_written_back_uses_the_scalar_moves() {
912        let f64 = Type::float(rucc_ir::Float::F64);
913        let (mut names, mut source, block, args) = blank(&[Type::PTR, f64]);
914        let mut build = Builder::new(&mut source, block);
915        let info = rucc_ir::MemInfo {
916            size: 8,
917            align: 8,
918            order: rucc_ir::MemOrder::NotAtomic,
919            tbaa: None,
920            owns: 0,
921            restrict: Restrict::NONE,
922        };
923        let read = build.load(f64, args[0], info, ir::Flags::default());
924        let sum = build.binary(Opcode::FAdd, read, args[1], ir::Flags::default());
925        build.store(sum, args[0], info, ir::Flags::default());
926        build.ret(&[sum]);
927
928        let machine = Machine::x86_64(&SYSV);
929        let out =
930            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
931                .expect("every instruction has a rule");
932
933        let text = mir::print_func(&out, &names, &REGS);
934        assert!(text.contains("x64.movsd_rm"), "{text}");
935        assert!(text.contains("x64.movsd_mr"), "{text}");
936        // Not the aligned whole register move, which is what a spill uses and is the one
937        // instruction here that would read and write more than the program asked for.
938        assert!(!text.contains("x64.movaps_rm"), "{text}");
939        assert!(!text.contains("x64.movaps_mr"), "{text}");
940    }
941
942    /// The same journey at the format the machine only moves, which is the whole of what it can do
943    /// with one: in from memory, back out to memory, in and out of a register, and back to the
944    /// caller.
945    ///
946    /// No arithmetic, because there is no instruction for any and every one of them is a call to
947    /// the runtime. What this says is that the value gets where a call would need it to be.
948    #[test]
949    fn a_quad_float_read_from_memory_and_written_back_uses_the_whole_register_move() {
950        let quad = Type::float(rucc_ir::Float::F128);
951        let (mut names, mut source, block, args) = blank(&[Type::PTR, quad]);
952        let mut build = Builder::new(&mut source, block);
953        let info = rucc_ir::MemInfo {
954            size: 16,
955            align: 16,
956            order: rucc_ir::MemOrder::NotAtomic,
957            tbaa: None,
958            owns: 0,
959            restrict: Restrict::NONE,
960        };
961        let read = build.load(quad, args[0], info, ir::Flags::default());
962        build.store(args[1], args[0], info, ir::Flags::default());
963        build.ret(&[read]);
964
965        let machine = Machine::x86_64(&SYSV);
966        let out =
967            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
968                .expect("every instruction has a rule");
969
970        let text = mir::print_func(&out, &names, &REGS);
971        assert!(text.contains("x64.movaps_rm"), "{text}");
972        assert!(text.contains("x64.movaps_mr"), "{text}");
973        assert!(text.contains("x64.arg_val_f128"), "{text}");
974        assert!(text.contains("x64.ret_val_f128"), "{text}");
975        // In the vector file and not the general purpose one, which is where the two eightbytes
976        // of this value would have gone if it had been classified as a pair of integers.
977        assert!(text.contains("$xmm0"), "{text}");
978        assert!(!text.contains("gpr($rax)"), "{text}");
979    }
980
981    /// Both conversions between an unsigned word and a `long double`, all the way to instructions.
982    ///
983    /// What the rewrite writes and what the x87 group in [`crate::lower`] has are two lists put
984    /// together in two different files, and this is where they meet. The rewrite is free to write
985    /// any instruction it likes at any width, and at this width almost none of them can be
986    /// lowered, so a correction written the way the narrower ones are written would pass its own
987    /// tests next door and fail here.
988    #[test]
989    fn an_unsigned_word_and_a_long_double_convert_into_each_other() {
990        let f80 = Type::float(rucc_ir::Float::F80);
991        let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
992        let mut build = Builder::new(&mut source, block);
993        let info = rucc_ir::MemInfo {
994            size: 16,
995            align: 16,
996            order: rucc_ir::MemOrder::NotAtomic,
997            tbaa: None,
998            owns: 0,
999            restrict: Restrict::NONE,
1000        };
1001        let wide = build.unary(Opcode::UIToFP, args[1], f80);
1002        build.store(wide, args[0], info, ir::Flags::default());
1003        let read = build.load(f80, args[0], info, ir::Flags::default());
1004        let back = build.unary(Opcode::FPToUI, read, Type::int(64));
1005        build.ret(&[back]);
1006
1007        let machine = Machine::x86_64(&SYSV);
1008        let out =
1009            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1010                .expect("every instruction has a rule");
1011
1012        let text = mir::print_func(&out, &names, &REGS);
1013        // The signed conversions in both directions, the constants that correct them, and the
1014        // multiply that takes a correction or leaves it. Nothing here reaches a wide register.
1015        assert!(text.contains("x64.fild_ll"), "the integer goes in as a signed one: {text}");
1016        assert!(text.contains("x64.fistp_ll"), "and comes back out as one: {text}");
1017        assert!(text.contains("x64.fmul_p"), "the correction is taken or not: {text}");
1018        assert!(text.contains("x64.fadd_p"), "and applied one way: {text}");
1019        assert!(text.contains("x64.fsubr_p"), "and the other: {text}");
1020        assert!(!text.contains("xmm"), "no part of this is in a vector register: {text}");
1021    }
1022
1023    /// A value carried from one register file to the other, which is what a conversion is. The
1024    /// instruction reads one file and writes the other, and the allocator has to know that: a
1025    /// conversion whose operands were both said to be in one file would put the answer in a
1026    /// register the next instruction cannot reach.
1027    #[test]
1028    fn a_conversion_carries_the_value_into_the_other_register_file() {
1029        let f64 = Type::float(rucc_ir::Float::F64);
1030        let (mut names, mut source, block, args) = blank(&[f64]);
1031        let mut build = Builder::new(&mut source, block);
1032        let whole = build.unary(Opcode::FPToSI, args[0], Type::int(32));
1033        let back = build.unary(Opcode::SIToFP, whole, f64);
1034        build.ret(&[back]);
1035
1036        let machine = Machine::x86_64(&SYSV);
1037        let out =
1038            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1039                .expect("every instruction has a rule");
1040
1041        // The conversion that cuts towards zero rather than the one that rounds, which is what C
1042        // means by the cast, and the argument and the answer in the register the convention names.
1043        let text = mir::print_func(&out, &names, &REGS);
1044        assert!(text.contains("x64.cvttsd2si_32"), "{text}");
1045        assert!(text.contains("x64.cvtsi2sd_32"), "{text}");
1046        assert!(text.contains("$xmm0"), "{text}");
1047    }
1048
1049    /// The other way of putting a float and a number together, which keeps every bit rather than
1050    /// the value and is what a program reading the bits of a `double` asks for.
1051    #[test]
1052    fn a_bitcast_between_the_files_is_the_move_that_changes_no_bit() {
1053        let f64 = Type::float(rucc_ir::Float::F64);
1054        let (mut names, mut source, block, args) = blank(&[f64]);
1055        let mut build = Builder::new(&mut source, block);
1056        let bits = build.unary(Opcode::Bitcast, args[0], Type::int(64));
1057        build.ret(&[bits]);
1058
1059        let machine = Machine::x86_64(&SYSV);
1060        let out =
1061            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1062                .expect("every instruction has a rule");
1063
1064        let text = mir::print_func(&out, &names, &REGS);
1065        assert!(text.contains("x64.movq_from_xmm"), "{text}");
1066        assert!(!text.contains("cvt"), "{text}");
1067    }
1068
1069    /// A comparison whose answer the machine has a condition for, which is most of them.
1070    #[test]
1071    fn a_float_comparison_is_the_compare_and_the_byte_a_condition_sets() {
1072        let f64 = Type::float(rucc_ir::Float::F64);
1073        let (mut names, mut source, block, args) = blank(&[f64, f64]);
1074        let mut build = Builder::new(&mut source, block);
1075        let less = build.fcmp(rucc_ir::FloatPred::Olt, args[0], args[1], ir::Flags::default());
1076        let wide = build.unary(Opcode::ZExt, less, Type::int(32));
1077        build.ret(&[wide]);
1078
1079        let machine = Machine::x86_64(&SYSV);
1080        let out =
1081            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1082                .expect("every instruction has a rule");
1083
1084        // Less than is greater than with the operands the other way round, and the machine has no
1085        // condition for the first, so the rule that fires is the one that swaps them.
1086        let text = mir::print_func(&out, &names, &REGS);
1087        assert!(text.contains("x64.ucomisd_set_a"), "{text}");
1088    }
1089
1090    /// The two comparisons that are not one condition. An ordered equality is the flag that means
1091    /// equal or unordered and the flag that says it was ordered, so the instruction writes a
1092    /// second byte and reads it back, and what this is about is that the second byte gets a
1093    /// register of its own rather than the one the answer is in.
1094    #[test]
1095    fn an_equality_between_floats_gets_a_register_for_the_byte_it_needs_twice() {
1096        let f64 = Type::float(rucc_ir::Float::F64);
1097        let (mut names, mut source, block, args) = blank(&[f64, f64]);
1098        let mut build = Builder::new(&mut source, block);
1099        let same = build.fcmp(rucc_ir::FloatPred::Oeq, args[0], args[1], ir::Flags::default());
1100        let wide = build.unary(Opcode::ZExt, same, Type::int(32));
1101        build.ret(&[wide]);
1102
1103        let machine = Machine::x86_64(&SYSV);
1104        let out =
1105            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1106                .expect("every instruction has a rule");
1107
1108        let text = mir::print_func(&out, &names, &REGS);
1109        let line = text
1110            .lines()
1111            .find(|line| line.contains("x64.ucomisd_set_e_and_np"))
1112            .expect("the rule for an ordered equality fired");
1113        let written: Vec<&str> = line
1114            .split_once('=')
1115            .expect("the instruction writes something")
1116            .0
1117            .split(',')
1118            .map(str::trim)
1119            .collect();
1120        assert_eq!(written.len(), 2, "{line}");
1121        assert_ne!(written[0], written[1], "{line}");
1122    }
1123
1124    /// A float literal, which is the last float thing a C program writes that had no lowering.
1125    /// The rewrite that puts it in reach is in `expand`, and what this is about is that the two
1126    /// halves meet: the constant is spelled in a general purpose register and moved across.
1127    #[test]
1128    fn a_float_constant_is_the_bits_in_a_register_and_the_move_that_carries_them_over() {
1129        let f64 = Type::float(rucc_ir::Float::F64);
1130        let (mut names, mut source, block, _) = blank(&[]);
1131        let mut build = Builder::new(&mut source, block);
1132        let half = build.fconst(f64, 0x3fe0_0000_0000_0000);
1133        build.ret(&[half]);
1134
1135        let machine = Machine::x86_64(&SYSV);
1136        let out =
1137            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1138                .expect("every instruction has a rule");
1139
1140        let text = mir::print_func(&out, &names, &REGS);
1141        assert!(text.contains("x64.mov_ri_64"), "{text}");
1142        assert!(text.contains("x64.movq_to_xmm"), "{text}");
1143    }
1144
1145    /// A negation, which is the sign bit flipped and nothing else touched, so what the machine
1146    /// does is an exclusive or in a general purpose register rather than any float instruction.
1147    #[test]
1148    fn a_negation_is_the_sign_bit_flipped_and_no_float_instruction_at_all() {
1149        let f64 = Type::float(rucc_ir::Float::F64);
1150        let (mut names, mut source, block, args) = blank(&[f64]);
1151        let mut build = Builder::new(&mut source, block);
1152        let less = build.unary(Opcode::FNeg, args[0], f64);
1153        build.ret(&[less]);
1154
1155        let machine = Machine::x86_64(&SYSV);
1156        let out =
1157            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1158                .expect("every instruction has a rule");
1159
1160        let text = mir::print_func(&out, &names, &REGS);
1161        assert!(text.contains("x64.xor_rr_64"), "{text}");
1162        assert!(!text.contains("sub"), "a negation is not a subtraction: {text}");
1163    }
1164
1165    #[test]
1166    fn the_flags_reach_the_frame() {
1167        let i32 = Type::int(32);
1168        let (mut names, mut source, block, args) = blank(&[i32]);
1169        Builder::new(&mut source, block).ret(&[args[0]]);
1170
1171        let machine = Machine::x86_64(&SYSV);
1172        let flags = Flags { frame_pointer: true, profile: Profile::No, ..Flags::default() };
1173        let out = compile(&mut source, &mut names, &machine, &Elsewhere::default(), flags)
1174            .expect("every instruction has a rule");
1175
1176        // A function that keeps a frame pointer keeps it whether it needed one or not, which is
1177        // what `-fno-omit-frame-pointer` is for and is the only thing this test is about.
1178        let text = mir::print_func(&out, &names, &REGS);
1179        assert!(text.contains("x64.push_64 $rbp"), "{text}");
1180        assert!(text.contains("$rbp = x64.mov_rr_64 $rsp"), "{text}");
1181    }
1182
1183    #[test]
1184    fn a_target_says_which_machine_it_is_and_which_convention_it_uses() {
1185        let triple = |text: &str| text.parse::<rucc_target::Triple>().expect("a triple");
1186        let info = TargetInfo::new(triple("x86_64-unknown-linux-gnu"));
1187        let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
1188        assert!(std::ptr::eq(machine.conv, &SYSV));
1189
1190        let info = TargetInfo::new(triple("x86_64-pc-windows-msvc"));
1191        let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
1192        assert!(std::ptr::eq(machine.conv, &WIN64));
1193
1194        // Not a target this crate has a backend for, and saying so is the whole point: a caller
1195        // that got a machine here would compile x86-64 instructions for an AArch64 program.
1196        let info = TargetInfo::new(triple("aarch64-unknown-linux-gnu"));
1197        assert!(Machine::for_target(&info).is_none());
1198    }
1199}