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