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