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