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