Skip to main content

rucc_codegen/
lower.rs

1//! The selector: an IR function becomes a machine IR function.
2//!
3//! Design: `spec/10-backend.md` sections 10.2 and 10.3.
4//!
5//! What the matcher in [`crate::select`] does is answer one question about one term. What this
6//! does is ask it: walk a function, decide which terms are worth asking about, and build machine
7//! instructions out of what comes back. Nothing here decides what an IR term lowers to. That is
8//! in `rules/x86-64.rules` and it is proved before it is used, which is the whole point of the
9//! arrangement and the reason this file is short.
10//!
11//! # What it does with an instruction
12//!
13//! It tries the ways the instruction can be shown to the matcher, in order, and takes the first
14//! that a rule fires on. [`crate::term`] is what a way of showing one is, and the order is the
15//! most specific first: an operand that is a constant is offered as a constant before it is
16//! offered as a register, and an operand computed by an instruction of its own is offered as
17//! that instruction before it is offered as a register. A rule that wants an immediate too wide
18//! for the machine has a guard that turns it down, and the search carries on to the way of
19//! showing it that puts the constant in a register, which is the right answer and is one nobody
20//! had to write down.
21//!
22//! A constant is not lowered where it is written. It is materialized where a register for it is
23//! first wanted, which is what keeps a constant that every use folded into an immediate from
24//! leaving a dead instruction behind, and it also gives the value the shortest live range it
25//! could have. The instruction that materializes it comes from the rule set like everything else.
26//!
27//! # What it does not do yet
28//!
29//! Everything is in the general purpose registers, because every rule in the set is about an
30//! integer, so a call that passes a `double` and a function that returns one are both reported
31//! rather than lowered. So is an argument that travels on the stack, on either side of a call,
32//! and so is a call through an address rather than to a name.
33//!
34//! # A call
35//!
36//! Not a rule, because a rule pattern sees one term and what a call's operands are is whatever
37//! the signature made them. [`crate::abi`] builds one instead, out of the same description of the
38//! convention the arguments come from: the values it passes are reads constrained to the
39//! registers the convention places them in, what comes back is a write constrained to the
40//! register it comes back in, and every other register the callee is free to destroy is a write
41//! of that register and nothing else, which is all the allocator needs to keep a value out of it.
42//!
43//! What that costs the frame is an argument area, and nothing after selection could work out how
44//! big, so the size of the widest call is given back with the function. A function that makes no
45//! call at all is a leaf, and a leaf is the function that may use the red zone.
46//!
47//! # Where a block goes
48//!
49//! On the block, which is what machine IR does with an edge and is why the branches need no more
50//! rule language than the arithmetic did. A rule never names a block, so an unconditional jump
51//! has no rule at all and a conditional branch has one that is about its condition and nothing
52//! else. The arms are copied across after the block is filled, arguments and all, because an
53//! argument that is a constant is materialized where a register for it is first wanted and the
54//! end of the block is where an edge wants it.
55//!
56//! What this leaves behind is a function whose blocks are in the order the IR held them and whose
57//! branches are still branches on a register. Turning one into a `test` and a `jcc` is the block
58//! layout's, since which of the two arms falls through is the layout's answer, and [`crate::split`]
59//! has to run before allocation so that every edge carrying a value has somewhere to put it.
60//!
61//! A store and a return are the two things here that write no register. A store is emitted like
62//! everything else and the only difference is that there is no result to put anywhere, so the
63//! operands the target describes are all reads. A return is the same, and what it is for is its
64//! one operand: the target constrains it to the register the caller reads the value out of, and
65//! the allocator is what gets it there. The instruction that leaves is not chosen here at all,
66//! because the epilogue has to give the frame back first and [`crate::finish`] writes that after
67//! allocation, so a return of nothing is lowered to nothing.
68//!
69//! The entry block is the one block whose parameters are not block parameters here. They are the
70//! function's arguments, they are already somewhere when it starts, and [`crate::abi`] is what
71//! says where. An argument that arrives on the stack is reported rather than read, because where
72//! the stack put it is a distance into a frame and no frame exists until after allocation.
73//!
74//! Blocks are walked in the order the function holds them and a value is expected to be defined
75//! before it is used, which is true of the IR this is given because every pass before it keeps
76//! definitions ahead of uses.
77
78use std::fmt;
79
80use rucc_base::Interner;
81use rucc_diag::Span;
82use rucc_ir::{
83    Abi, Block, Def, Extra, FloatPred, Func, Inst, Linkage, MemOrder, Opcode, Param, Type, Value,
84};
85use rucc_mir as mir;
86use rucc_target::x86_64;
87use rucc_target::{CallRegs, Constraint, RegClass};
88
89use crate::abi::{self, Missing, Refused};
90use crate::coverage::Fired;
91use crate::frame::{Layout, Local};
92use crate::select::{Match, Piece, Rule, Table};
93use crate::term::{MAX_ARGS, PLAIN, Plan, Shown, Term, Terms};
94use crate::varargs;
95
96/// The prefix a rule file puts in front of a machine term, which says which target it belongs
97/// to and is not part of the opcode.
98pub(crate) const PREFIX: &str = "x64.";
99
100/// How wide an address is on this target, which is the width a cast between a pointer and an
101/// integer has to be at for the cast to be nothing.
102const ADDRESS_BITS: u32 = 64;
103
104/// How many bytes a `long double` takes in memory, and what it is aligned to, which are the same
105/// number and are both more than the ten bytes that mean anything.
106///
107/// The psABI's answer rather than a choice here. `sizeof (long double)` is sixteen on this
108/// machine, so an array of them is laid out this way whatever a slot holding one does, and a slot
109/// that agreed with the array is one fewer thing to get wrong.
110const X87_BYTES: u32 = 16;
111
112/// How many values the x87 stack holds at once.
113///
114/// Eight, which is the machine's number rather than a choice here, and it matters in one place:
115/// the parameters of a block are copied through the stack so that they all move at once, and a
116/// block with more of them than this has nowhere to put the ninth.
117const X87_DEPTH: usize = 8;
118
119/// How many bytes a value passes through on its way between a register and the x87 stack.
120///
121/// Eight, because the widest thing that crosses is a `double` or a sixty four bit integer, and
122/// nothing crosses at eighty bits: a value that wide is already in the frame and the stack reaches
123/// it where it is.
124const X87_CROSSING: u32 = 8;
125
126/// Where the rounding field of the x87 control word is and what it has to be set to for the unit
127/// to cut towards zero, which is the one rounding C asks for that the unit does not do by default.
128///
129/// Both bits on is truncate. The field is ORed into the word that was already there rather than
130/// written over it, so the precision control and the exception masks somebody else set stay set.
131const X87_TRUNCATE: i64 = 0x0c00;
132
133/// Whether a type is the one this machine has no register for.
134///
135/// Only the eighty bit float is, and that is a fact about x86-64 rather than about floats: every
136/// other scalar the front end produces is in a general purpose register or a vector one, and this
137/// one is on the x87 stack while it is being worked on and in memory the rest of the time. So it
138/// has no place in [`Lowering::class_of`] and no name in [`crate::term`], and every instruction
139/// that touches one is written out by hand in this file.
140fn on_x87(ty: Type) -> bool {
141    ty.is_scalar() && ty.is_float() && ty.bits() == 80
142}
143
144/// Why a function could not be lowered.
145///
146/// One reason and then nothing. A function with no rule for something in it is a function this
147/// cannot finish, and the second thing it could not lower is not news.
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub enum Unsupported {
150    /// An instruction no rule fires on.
151    Inst {
152        /// The instruction that stopped it.
153        inst: Inst,
154        /// What the rule file would call it, or nothing if the rule language has no name for it
155        /// at all, which is what an instruction at a width nothing is written about looks like.
156        term: Option<&'static str>,
157        /// The opcode, which is what gets named when the rule language has no word for it.
158        ///
159        /// An opcode the rule language has no word for is exactly the opcode no rule lowers, so
160        /// without this the message would be empty in every case where somebody needs it.
161        opcode: Opcode,
162        /// What it produces, or nothing for an instruction that is only an effect.
163        ty: Option<Type>,
164    },
165    /// A parameter that does not arrive somewhere this can bring it in from.
166    ///
167    /// Not an instruction, which is why it is a separate arm: it is a fact about the signature
168    /// and there is nothing in the body of the function to point at.
169    Argument {
170        /// Its position in the signature.
171        index: usize,
172        /// What is wrong with where it arrives.
173        missing: Missing,
174    },
175    /// A call that passes or gives back a value this cannot put where the convention wants it.
176    Call {
177        /// The call.
178        inst: Inst,
179        /// Which value, and what is wrong with where it travels.
180        refused: Refused,
181    },
182    /// A `return` this cannot put where the convention wants it.
183    ///
184    /// A separate arm from [`Unsupported::Inst`] because it is not an instruction no rule fires
185    /// on. A return of more than one value is built from the convention rather than matched, the
186    /// same way a call is, so what goes wrong with one is what goes wrong with a call and not the
187    /// absence of a rule.
188    Returned {
189        /// The `return`.
190        inst: Inst,
191        /// What is wrong with where one of the values travels.
192        missing: Missing,
193    },
194    /// A stack slot whose size is not known until the function runs, which is what a variable
195    /// length array is.
196    ///
197    /// Not an instruction no rule covers. Growing the stack where the declaration stands is
198    /// arithmetic on the stack pointer, and everything else in the frame then has to be reached
199    /// through a frame pointer instead, and neither of those is a term a rule could be written
200    /// about or a thing the frame here knows how to lay out.
201    Dynamic {
202        /// The `alloca`.
203        inst: Inst,
204    },
205    /// More parameters of a type that travels on the x87 stack than the stack is deep.
206    ///
207    /// Not an instruction either, for the reason a function's parameter is not one: it is a fact
208    /// about the block and there is nothing in the block to point at. What crosses an edge for one
209    /// of these is the address of where the value is, and the block copies the bytes into a slot
210    /// of its own, all of them through the stack at once so that a block carrying two of them
211    /// swapped is copied in an order that is right. Eight is as many as the stack holds, and a
212    /// ninth would have to be copied before or after the rest, which is the order that could be
213    /// wrong.
214    Phi {
215        /// Which block it arrives at.
216        block: Block,
217        /// How many of them arrive there, which is the whole of what is wrong.
218        count: usize,
219        /// What they are.
220        ty: Type,
221    },
222}
223
224impl Unsupported {
225    /// The instruction it is about, or nothing for the one arm that is about a signature.
226    ///
227    /// What a caller wants this for is the span. The function knows where every instruction in
228    /// it came from, so a caller holding both can point a message at the line somebody wrote
229    /// rather than at the file as a whole, and nothing here has to carry a span of its own.
230    pub fn inst(&self) -> Option<Inst> {
231        match *self {
232            Unsupported::Inst { inst, .. }
233            | Unsupported::Call { inst, .. }
234            | Unsupported::Returned { inst, .. }
235            | Unsupported::Dynamic { inst, .. } => Some(inst),
236            Unsupported::Argument { .. } | Unsupported::Phi { .. } => None,
237        }
238    }
239}
240
241impl fmt::Display for Unsupported {
242    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243        match *self {
244            Unsupported::Inst { term: Some(term), .. } => write!(f, "no rule lowers `{term}`"),
245            Unsupported::Inst { term: None, opcode, ty: Some(ty), .. } => {
246                write!(f, "no rule lowers a `{opcode}` producing a `{ty}`")
247            }
248            Unsupported::Inst { term: None, opcode, ty: None, .. } => {
249                write!(f, "no rule lowers a `{opcode}`")
250            }
251            Unsupported::Argument { index, missing } => {
252                write!(f, "parameter {index} {}", missing.why())
253            }
254            Unsupported::Call { refused: Refused { argument: Some(index), missing }, .. } => {
255                write!(f, "argument {index} of this call {}", missing.why())
256            }
257            Unsupported::Call { refused: Refused { argument: None, missing }, .. } => {
258                write!(f, "what this call gives back {}", missing.why())
259            }
260            Unsupported::Returned { missing, .. } => {
261                write!(f, "what this function gives back {}", missing.why())
262            }
263            Unsupported::Dynamic { .. } => {
264                f.write_str("nothing here grows the stack for a variable length array")
265            }
266            Unsupported::Phi { block, count, ty } => {
267                let block = block.index();
268                write!(
269                    f,
270                    "block{block} takes {count} parameters of type `{ty}` and only {X87_DEPTH} can cross an edge at once"
271                )
272            }
273        }
274    }
275}
276
277impl std::error::Error for Unsupported {}
278
279/// A lowered function, and what the frame needs that the machine IR does not hold.
280#[derive(Debug)]
281pub struct Lowered {
282    /// The function, in machine instructions.
283    pub func: mir::Func,
284    /// What it wants its stack to look like, which is separate from the function so that the two
285    /// can be read and written at the same time.
286    pub stack: Stack,
287    /// Which rules of the table lowered it, which is what `-Zrule-coverage` asks for and what
288    /// `crate::coverage` writes down.
289    pub fired: Fired,
290}
291
292/// What a function's stack has to hold, as far as selection is able to say.
293///
294/// All of it is answered here because selection is where a call is built and where an `alloca`
295/// is read, and nothing after it could tell what either of them needed.
296#[derive(Debug, Default)]
297pub struct Stack {
298    /// How many bytes the widest call in the function needs below the stack pointer for the
299    /// arguments it passes there, or `None` for a function that makes no call at all.
300    ///
301    /// `None` is a leaf, which is the function that may use the red zone and the one whose stack
302    /// pointer does not have to be left aligned for anybody.
303    pub calls: Option<u32>,
304    /// The memory the function asked for itself, one entry for every `alloca` in it, in the order
305    /// the walk reached them.
306    pub locals: Vec<Local>,
307    /// Which instruction computes the address of which of those locals.
308    ///
309    /// An address in the frame is a distance from the stack pointer, and there is no frame until
310    /// after allocation, so the instruction is written here with nothing in its displacement and
311    /// [`crate::finish`] writes the number in once [`crate::frame::Frame`] knows it.
312    pub addresses: Vec<(mir::Inst, usize)>,
313    /// Which instruction reads which of the arguments the caller passed on the stack, as how far up
314    /// the caller's argument area it reads.
315    ///
316    /// Waiting on [`crate::finish`] for the same reason the addresses above are, and on one thing
317    /// more: where the caller's argument area is from inside this function depends on whether the
318    /// prologue had to force the stack pointer's alignment, so which register the load reads
319    /// through is not settled here either.
320    pub arguments: Vec<(mir::Inst, u32)>,
321}
322
323impl Stack {
324    /// The layout given, with the three fields only the lowering knows the answer to filled in.
325    ///
326    /// Everything else in a layout comes from the flags the function is compiled under or from the
327    /// allocation, so this takes one and returns it rather than building one.
328    #[must_use]
329    pub fn layout<'a>(&'a self, base: Layout<'a>) -> Layout<'a> {
330        Layout {
331            leaf: self.calls.is_none(),
332            outgoing: self.calls.unwrap_or(0),
333            locals: &self.locals,
334            ..base
335        }
336    }
337}
338
339/// The x86-64 machine IR for that function.
340///
341/// # Errors
342///
343/// The first instruction no rule fires on, which today is anything at a width the rule set is not
344/// written at, a parameter that does not arrive in a register this can read, or a call that
345/// passes something this cannot put where the convention wants it.
346pub fn func(
347    source: &Func,
348    names: &mut Interner,
349    conv: &'static CallRegs,
350) -> Result<Lowered, Unsupported> {
351    Lowering::new(source, names, conv).run()
352}
353
354/// One function being lowered.
355struct Lowering<'a> {
356    source: &'a Func,
357    names: &'a mut Interner,
358    out: mir::Func,
359    /// The machine register each IR value is in, once it has one.
360    regs: Vec<Option<mir::Reg>>,
361    /// For a constant that has been written into a register, the block it was written into,
362    /// which is the only block that register is any good in.
363    written: Vec<Option<mir::Block>>,
364    /// How many times each IR value is read, which is what says whether an instruction may be
365    /// folded into the one that reads it.
366    uses: Vec<u32>,
367    /// The block being filled.
368    at: Option<mir::Block>,
369    /// The machine IR block each IR block became.
370    blocks: Vec<Option<mir::Block>>,
371    /// The class an address is in, which is the general purpose one and is not a question: every
372    /// register an addressing mode names holds part of an address, and there is no machine here
373    /// that computes an address anywhere but in this file. Which class a *value* is in is
374    /// [`Lowering::class_of`], and it is a question, because a float is in the other one.
375    gpr: RegClass,
376    /// Where the convention this function is compiled for puts things, which is read for the
377    /// arguments and for the calls.
378    conv: &'static CallRegs,
379    /// What the function wants its stack to look like, filled in as the walk finds out.
380    stack: Stack,
381    /// What a `va_start` in this function has to write, or nothing for a function that takes no
382    /// arguments its signature does not name.
383    ///
384    /// Worked out once, when the entry block binds the parameters, because every number in it is
385    /// about where those parameters left the walk over the argument registers and there is nowhere
386    /// else that knows.
387    varargs: Option<Varargs>,
388    /// Which of the function's stack objects each eighty bit value lives in, once it has asked
389    /// for one.
390    ///
391    /// One slot per value and it is never given back, which is what makes an eighty bit value
392    /// behave like every other one: it is written once and read wherever it is read, and no two
393    /// of them share a slot the way two of them would share a register. What is in a register is
394    /// the address, and that is worked out again at every use rather than kept, so nothing here
395    /// holds a general purpose register open across a whole function.
396    slots: Vec<Option<usize>>,
397    /// The eight bytes a value passes through between a register and the x87 stack, once
398    /// something has wanted them.
399    ///
400    /// One for the whole function, because every group that uses it is a handful of instructions
401    /// with nothing in between: the bytes are written, read straight back and never looked at
402    /// again, so a second slot would be a second slot holding the same nothing.
403    crossing: Option<usize>,
404    /// The four bytes the control word is saved in and the changed copy written to, once
405    /// something has wanted them.
406    ///
407    /// One for the whole function for the reason above, and four rather than two because it is
408    /// two words: the one the unit had and the one with the rounding field turned to truncate.
409    control: Option<usize>,
410    /// Which rules have fired so far.
411    fired: Fired,
412}
413
414/// What a `va_start` in a variadic function writes into the list it is given.
415///
416/// Three of the four are settled here and the fourth is not a number at all yet: where the save
417/// area is and where the caller's argument area is are both distances into a frame that does not
418/// exist until after allocation, so both are `lea` instructions [`crate::finish`] fills in.
419#[derive(Debug, Clone, Copy, PartialEq, Eq)]
420struct Varargs {
421    /// Which of the function's stack objects is the register save area.
422    save: usize,
423    /// How far up the caller's argument area the first argument the signature does not name is,
424    /// which is the whole of that area the named ones did not take.
425    incoming: u32,
426    /// What `gp_offset` starts at, which is past the general purpose registers the named arguments
427    /// took.
428    integers: u32,
429    /// What `fp_offset` starts at, which is past the vector ones.
430    floats: u32,
431}
432
433/// How far a function's name reaches, narrowed from the linkage the IR gave it.
434///
435/// The IR has five and an object file says three, and the two the linker cannot tell apart are
436/// the two weak ones: which of them a symbol had is a fact the optimizer reads and the linker has
437/// no way to record. A function is never `Common`, since that is what a tentative definition of an
438/// object is and there is no tentative definition of a function, and it is written here rather
439/// than left out so that a linkage added later has to come past this.
440const fn binding(linkage: Linkage) -> mir::Binding {
441    match linkage {
442        Linkage::Internal => mir::Binding::Local,
443        Linkage::Weak | Linkage::LinkOnce => mir::Binding::Weak,
444        Linkage::External | Linkage::Common => mir::Binding::Global,
445    }
446}
447
448impl<'a> Lowering<'a> {
449    fn new(source: &'a Func, names: &'a mut Interner, conv: &'static CallRegs) -> Self {
450        let counts = source.counts();
451        let name = source.name;
452        let mut uses = vec![0; counts.values];
453        for block in source.blocks() {
454            for inst in source.insts(block) {
455                for &arg in &source[source[inst].args] {
456                    uses[arg.index()] += 1;
457                }
458                for call in source.successors(inst) {
459                    for &arg in &source[call.args] {
460                        uses[arg.index()] += 1;
461                    }
462                }
463            }
464        }
465        let mut out = mir::Func::new(name);
466        out.align = source.align;
467        out.binding = binding(source.linkage);
468        Self {
469            source,
470            names,
471            out,
472            regs: vec![None; counts.values],
473            written: vec![None; counts.values],
474            blocks: vec![None; counts.blocks],
475            uses,
476            at: None,
477            gpr: x86_64::GPR,
478            conv,
479            stack: Stack::default(),
480            varargs: None,
481            slots: vec![None; counts.values],
482            crossing: None,
483            control: None,
484            fired: Fired::new(),
485        }
486    }
487
488    fn run(mut self) -> Result<Lowered, Unsupported> {
489        // Every block before any of them is filled, because a block that jumps forward has to
490        // name the block it jumps to and a machine IR block is named by a handle rather than by
491        // the IR block it came from.
492        for block in self.source.blocks() {
493            let out = self.out.create_block();
494            self.blocks[block.index()] = Some(out);
495        }
496        for block in self.source.blocks() {
497            self.block(block)?;
498        }
499        Ok(Lowered { func: self.out, stack: self.stack, fired: self.fired })
500    }
501
502    /// One block: its parameters, then every instruction in it that is not folded into another.
503    fn block(&mut self, block: Block) -> Result<(), Unsupported> {
504        let out = self.out_block(block);
505        self.at = Some(out);
506        if self.source.entry() == Some(block) {
507            self.arrive(block, out)?;
508        } else {
509            let mut arriving = Vec::new();
510            for &param in &self.source[block].params {
511                // A value with no register to arrive in, which the class would not say, since
512                // `class_of` puts one of these in the general purpose file on purpose and what it
513                // means by that is that nothing there can hold it. What crosses the edge for one
514                // of those is the address of where the value already is, so the parameter is a
515                // pointer here and the bytes it points at are copied below.
516                let ty = self.source[param].ty;
517                let reg = self.out.append_param(out, self.class_of(ty));
518                self.regs[param.index()] = Some(reg);
519                if on_x87(ty) {
520                    arriving.push((param, reg));
521                }
522            }
523            self.settle(block, &arriving)?;
524        }
525
526        // What each instruction matched, and which instructions were folded into another. The
527        // instruction that is folded comes before the one that folds it, so the decision has to
528        // be made for the whole block before any of it is written, and it is made backwards: an
529        // instruction that has been folded into a later one does not get to fold anything into
530        // itself, because the rule that took it only reached one level down.
531        let insts: Vec<Inst> = self.source.insts(block).collect();
532        let mut found: Vec<Option<Match<Term>>> = (0..insts.len()).map(|_| None).collect();
533        let mut folded: Vec<Inst> = Vec::new();
534        for (index, &inst) in insts.iter().enumerate().rev() {
535            if folded.contains(&inst) {
536                continue;
537            }
538            if let Some((plan, matched)) = self.select(inst) {
539                folded.extend(self.folds(inst, plan));
540                found[index] = Some(matched);
541            }
542        }
543
544        for (&inst, matched) in insts.iter().zip(found) {
545            if folded.contains(&inst) || self.writes_nothing(inst) {
546                continue;
547            }
548            // A call is built from the convention rather than matched, which is why it is the one
549            // opcode looked at by name here. Through an address it is a different instruction and
550            // the same convention, so the two arrive at the same place and differ in one line of
551            // it.
552            match self.source[inst].opcode {
553                Opcode::Call | Opcode::CallIndirect => {
554                    self.called(inst)?;
555                    continue;
556                }
557                // Built from the frame rather than matched, for the same shape of reason a call
558                // is built from the convention: what a rule replaces a term with is instructions,
559                // and what an `alloca` needs first is bytes, which the rule language has no way
560                // to ask for.
561                Opcode::Alloca => {
562                    self.reserve(inst)?;
563                    continue;
564                }
565                // The address of a name, built here for the same reason an `alloca` is: what a
566                // rule replaces a term with is instructions over values, and the operand of this
567                // one is a symbol, which is a thing the rule language has no way to bind and the
568                // solver has no way to say anything about. There is nothing in `lea sym(%rip)` a
569                // proof over bitvectors could discharge, because what makes it the right answer
570                // is the relocation and what the linker does with it.
571                Opcode::GlobalAddr => {
572                    self.address_of(inst)?;
573                    continue;
574                }
575                // Built from the frame for the reason an `alloca` is, and from the convention for
576                // the reason a call is: three of the four fields it writes are distances that do
577                // not exist until the frame does, and the fourth is where the walk over the
578                // argument registers stopped. A function that is not variadic has no such walk to
579                // report, so it has nothing here and is refused below, which is the right answer
580                // for a `va_start` in one.
581                Opcode::VaStart if self.varargs.is_some() => {
582                    self.va_start(inst)?;
583                    continue;
584                }
585                // A return of more than one value, which is a structure small enough to come
586                // back in a pair of registers. Built from the convention for the reason a call
587                // is: which register each half goes in depends on the halves in front of it,
588                // because the two register files are walked separately, and a pattern over a term
589                // cannot see them. A return of one value is a term with a name and a rule, and it
590                // stays one.
591                //
592                // A return of none in a function whose answer went through memory is here too,
593                // and for a different reason: what it gives back is not written in the IR at all.
594                // The convention says the address the caller handed over comes back, and only the
595                // signature says this function was handed one.
596                //
597                // And a return of one eighty bit value, for a third reason: what a rule would
598                // write is an instruction leaving the value in a register, and this one is left on
599                // the x87 stack instead. A rule could not name that stack any more than any other
600                // rule about this type could.
601                Opcode::Return
602                    if self.source[self.source[inst].args].len() > 1
603                        || self.sret().is_some()
604                        || self.gives_back_x87(inst) =>
605                {
606                    self.returned(inst)?;
607                    continue;
608                }
609                // A cast between a pointer and an integer of the same width, which on this
610                // machine is every one the front end writes. No instruction at all, so no rule
611                // could name one.
612                Opcode::PtrToInt | Opcode::IntToPtr => {
613                    self.rename(inst)?;
614                    continue;
615                }
616                // A barrier, which is one instruction or none depending on the ordering. Written
617                // by name because there is nothing about it a rule could be proved against, the
618                // way there is nothing to prove about the address of a symbol.
619                Opcode::Fence => {
620                    self.barrier(inst)?;
621                    continue;
622                }
623                // Anything at all with an eighty bit float in it, which is the one arm here
624                // chosen by a type rather than by an opcode, because what makes these different
625                // is not what they do but where the value is. A `long double` has no register,
626                // so it has no name in `crate::term` and no rule could bind one: every one of
627                // these is a group of instructions over a frame slot, written out below.
628                //
629                // Last of the arms, so that a call and a return with one of these in them reach
630                // the convention first and are refused by it, which is the truer answer: what is
631                // wrong there is where the value has to travel and not that nothing can compute
632                // it.
633                _ if self.touches_x87(inst) => {
634                    self.x87(inst)?;
635                    continue;
636                }
637                _ => {}
638            }
639            let matched = matched.ok_or_else(|| self.unsupported(inst))?;
640            self.emit(inst, &matched)?;
641            // After it is built rather than when it matched, so that what is recorded is the rules
642            // this function was lowered by and not the rules something was tried with.
643            self.fired.mark(matched.rule);
644        }
645        self.edges(block, out)
646    }
647
648    /// One call, which is built from the convention rather than matched against the table for the
649    /// same reason the arguments of the function itself are.
650    ///
651    /// The arguments are read before the call is built, which is what materializes a constant
652    /// argument into a register, since no call passes an immediate.
653    ///
654    /// A call to a name and a call through an address are both here, and what tells them apart is
655    /// the opcode rather than whether a callee was recorded, which is the same thing the verifier
656    /// reads. Through an address the first operand is the address and the arguments are the ones
657    /// behind it, and everything after that is the same: where each argument goes, where the value
658    /// comes back and which registers are gone across it are the convention's answers and the
659    /// convention does not ask what is being called.
660    fn called(&mut self, inst: Inst) -> Result<(), Unsupported> {
661        let data = &self.source[inst];
662        let Extra::Call(info) = data.extra else { return Err(self.unsupported(inst)) };
663        let info = self.source[info];
664        let indirect = data.opcode == Opcode::CallIndirect;
665
666        let values: Vec<Value> = self.source[data.args].to_vec();
667        let callee = if indirect {
668            let &address = values.first().ok_or_else(|| self.unsupported(inst))?;
669            abi::Callee::Through(self.reg_of(address)?)
670        } else {
671            abi::Callee::Named(info.callee.ok_or_else(|| self.unsupported(inst))?)
672        };
673
674        // What the ABI asks of each argument, read out before any of them is, because reading one
675        // borrows the function this is a table in. The ones the signature names are the signature's
676        // answer and the ones behind them are the call's, which is where a structure passed to a
677        // variadic callee by value says that its bytes travel: there is no parameter to say it on.
678        let signature = &self.source[info.signature];
679        let variadic = signature.variadic;
680        let named: Vec<Abi> = signature.params.iter().map(|param| param.abi).collect();
681        let beyond: Vec<Abi> = self.source[info.varargs].to_vec();
682        // Every value that comes back and not only the first. A structure small enough to travel
683        // in registers comes back in up to two of them, and which register each half is in is the
684        // convention's answer, which is why the whole list goes to the same place the arguments do
685        // rather than to a rule.
686        let returns: Vec<Type> = signature.return_types().collect();
687
688        let mut args = Vec::with_capacity(values.len());
689        for (index, value) in values.into_iter().skip(usize::from(indirect)).enumerate() {
690            let abi = named.get(index).or_else(|| beyond.get(index - named.len()));
691            let abi = abi.copied().unwrap_or_default();
692            let ty = self.source[value].ty;
693            // What travels for an eighty bit value is its bytes, so what the call is handed is
694            // where they are rather than a register they are in, and there is no register they
695            // could be in. Everything else about it is a sixteen byte object passed by value and
696            // is built by the same code.
697            let reg =
698                if abi::on_the_stack(ty) { self.x87_slot(value) } else { self.reg_of(value)? };
699            args.push(abi::Passing { ty, reg, abi });
700        }
701        let block = self.at.expect("a block is being filled");
702        let what = abi::Calling { callee, args: &args, returns: &returns, variadic };
703        let made = abi::call(&mut self.out, block, &what, self.conv, self.names)
704            .map_err(|refused| Unsupported::Call { inst, refused })?;
705        let calls = &mut self.stack.calls;
706        *calls = Some(calls.unwrap_or(0).max(made.outgoing));
707        // An eighty bit value came back on the x87 stack, and the one thing that has to happen
708        // before anything else touches that stack is taking it off. So the `fstp` goes here, in
709        // front of everything the block does next, and after it the value is in its slot and is
710        // read the way every other one is.
711        let results: Vec<Value> = self.source[inst].results().collect();
712        if let [result] = results[..] {
713            if abi::on_the_stack(self.source[result].ty) {
714                let span = self.source.span(inst);
715                let into = self.x87_slot(result);
716                let into = self.through(into);
717                self.x87_at("fstp_t", span, into);
718                return Ok(());
719            }
720        }
721        for (result, &reg) in results.into_iter().zip(&made.results) {
722            self.regs[result.index()] = Some(reg);
723        }
724        Ok(())
725    }
726
727    /// The pointer a function returning through memory was handed, or nothing in a function that
728    /// was not.
729    ///
730    /// It is the first parameter and the signature is what says so, since in the IR it is an
731    /// ordinary pointer and reads like one everywhere in the body. A function with a signature
732    /// like that and no entry block has nothing to give back and no body to give it back from.
733    fn sret(&self) -> Option<Value> {
734        let first = self.source.signature().params.first()?;
735        if !matches!(first.abi, Abi::Sret { .. }) {
736            return None;
737        }
738        self.source[self.source.entry()?].params.first().copied()
739    }
740
741    /// One `return` the convention has to write, as the place each value has to be in by the end.
742    ///
743    /// One pseudo per value, each a read constrained to a return register, which is what a return
744    /// of one value already is and is the whole of what either does. The `ret` itself comes from
745    /// the epilogue for both, long after this, because the frame has to be given back first.
746    ///
747    /// The two register files are counted separately, so a structure of a `double` and a `long`
748    /// leaves the `double` in the first vector register and the `long` in the first integer one
749    /// rather than in the second of either. That is the same walk `rucc_codegen::abi` makes on
750    /// the other side of the call, which is what makes the two ends agree.
751    ///
752    /// A function whose answer went through memory gives back the address it was handed, in front
753    /// of nothing else, because a signature that returns that way returns nothing else. That the
754    /// caller already knows the address is not enough: it is allowed to read the register instead,
755    /// and a caller that does gets whatever the allocator last left there. In a leaf function that
756    /// is usually the right answer by accident, and one call in the body is enough to make it a
757    /// wild pointer, which is why this is written rather than left to luck.
758    ///
759    /// Where everything goes is worked out before anything is written, so a return this cannot
760    /// make leaves no half of one behind.
761    /// Whether what a `return` gives back is the one value that goes back on the x87 stack.
762    fn gives_back_x87(&self, inst: Inst) -> bool {
763        let [value] = self.source[self.source[inst].args] else { return false };
764        abi::on_the_stack(self.source[value].ty)
765    }
766
767    fn returned(&mut self, inst: Inst) -> Result<(), Unsupported> {
768        let values: Vec<Value> = self.source[self.source[inst].args].to_vec();
769        let (mut ints, mut floats) = (0usize, 0usize);
770        let mut parts = Vec::with_capacity(values.len() + 1);
771        // An eighty bit value goes back on the x87 stack, which is where the convention says it is
772        // and is the one place a value is left rather than put in a register. So the whole of the
773        // return is an `fld` of its slot, and the stack it leaves the value on is not empty at the
774        // `ret`, which is the one time in this file that is true and is what the convention asks
775        // for. What comes after is the epilogue, which gives the frame back and touches nothing in
776        // the unit.
777        if let [value] = values[..] {
778            let ty = self.source[value].ty;
779            if abi::on_the_stack(ty) && self.sret().is_none() {
780                let span = self.source.span(inst);
781                let from = self.x87_slot(value);
782                let from = self.through(from);
783                self.x87_at("fld_t", span, from);
784                return Ok(());
785            }
786        }
787        for value in self.sret().into_iter().chain(values) {
788            let ty = self.source[value].ty;
789            let at = if crate::term::float_slot(ty).is_some() { &mut floats } else { &mut ints };
790            // Why it cannot come back, and not only that it cannot. A type that travels nowhere
791            // says so itself, and a type that travels perfectly well ran out of registers.
792            let missing = abi::refuses(ty).unwrap_or(Missing::NoRoom);
793            let name = abi::ret_of(ty, *at).ok_or(Unsupported::Returned { inst, missing })?;
794            *at += 1;
795            // The register is the target's answer and not one worked out here, the same as it is
796            // for a return of one value, so that both halves of a pair and every rule that writes
797            // half of one are reading the same table.
798            let opcode = name.strip_prefix(PREFIX).expect("a machine instruction of this target");
799            let form = x86_64::form(opcode).ok_or_else(|| self.unsupported(inst))?;
800            let [desc] = form.operands() else { return Err(self.unsupported(inst)) };
801            parts.push((self.names.intern(name), self.reg_of(value)?, *desc));
802        }
803
804        let block = self.at.expect("a block is being filled");
805        let span = self.source.span(inst);
806        for (opcode, reg, desc) in parts {
807            let operand = mir::Operand {
808                reg,
809                class: desc.class,
810                role: desc.role,
811                constraint: desc.constraint,
812            };
813            self.out.build(block, mir::Opcode::new(opcode)).at(span).operand(operand).finish();
814        }
815        Ok(())
816    }
817
818    /// One `alloca`: the bytes it asks for go on the list the frame is laid out from, and the
819    /// address of them is one instruction.
820    ///
821    /// The instruction is a `lea` off the stack pointer, which is the one register that reaches
822    /// the frame in every function, and its displacement is left at nothing because there is no
823    /// frame yet. Which instruction is waiting for which local is remembered, and
824    /// [`crate::finish`] fills the numbers in after [`crate::frame::Frame`] has placed them.
825    ///
826    /// There is deliberately no rule for `alloca` and no name for one in [`crate::term`], and
827    /// that is what stops it being folded into something else. An operand shown as the
828    /// instruction that computed it is offered to the matcher by its name, so an `alloca` with no
829    /// name is one no pattern can reach past, and the address it computes is always in a register
830    /// by the time anything reads it.
831    fn reserve(&mut self, inst: Inst) -> Result<(), Unsupported> {
832        let data = &self.source[inst];
833        // A variable length array carries the size it wants as an operand rather than in the
834        // instruction, which is the whole of what tells the two apart here.
835        if !self.source[data.args].is_empty() {
836            return Err(Unsupported::Dynamic { inst });
837        }
838        let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
839        let info = self.source[mem];
840        let size = u32::try_from(info.size).map_err(|_| Unsupported::Dynamic { inst })?;
841        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
842
843        // At least one, because the frame divides by the alignment and an object with no
844        // alignment at all is one the front end had nothing to say about rather than one that may
845        // go anywhere.
846        let index = self.stack.locals.len();
847        self.stack.locals.push(Local { size, align: info.align.max(1) });
848
849        let block = self.at.expect("a block is being filled");
850        let reg = self.new_reg(result);
851        let span = self.source.span(inst);
852        let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
853        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
854        let made =
855            self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
856        self.stack.addresses.push((made, index));
857        Ok(())
858    }
859
860    /// Whether an instruction has an eighty bit float anywhere in it.
861    ///
862    /// Producing one and reading one are the same question here, because what makes one of these
863    /// different from every other instruction is not the operation but where the value is. A
864    /// `long double` is on the x87 stack while it is being worked on and in a frame slot the rest
865    /// of the time, and neither of those is somewhere the operand of a rule could point.
866    fn touches_x87(&self, inst: Inst) -> bool {
867        let data = &self.source[inst];
868        data.results().any(|value| on_x87(self.source[value].ty))
869            || self.source[data.args].iter().any(|&arg| on_x87(self.source[arg].ty))
870    }
871
872    /// Everything that happens to an eighty bit float, as the group of instructions it is.
873    ///
874    /// The first six move one, and every one of those is a load, a store, or a load and a store at
875    /// two different formats, because that is the whole of what this machine converts with: the
876    /// x87 has no instruction that turns one thing on its stack into another, so a widening is
877    /// `fld` of the narrow format and a narrowing is `fstp` of it.
878    ///
879    /// The rest work on one, and they are here rather than in a rule for the same reason the six
880    /// are. An add is a push, a push, the add and a pop, and what passes between those four is the
881    /// top of a stack nothing allocates from, so there is no value in the middle of the group for
882    /// a pattern to bind or a replacement to name. The comparison is the same shape with its last
883    /// two instructions folded into one opcode, which is where the byte it produces comes from.
884    ///
885    /// Every group leaves the stack as empty as it found it, which is what `spec/10-backend.md`
886    /// section 10.8 asks of one and is why nothing in this file has to track a depth: each push
887    /// below is answered by a pop a line or two later, so no two groups can ever be looking at
888    /// the same eight registers.
889    fn x87(&mut self, inst: Inst) -> Result<(), Unsupported> {
890        match self.source[inst].opcode {
891            Opcode::Load => self.x87_load(inst),
892            Opcode::Store => self.x87_store(inst),
893            Opcode::FPExt => self.x87_widen(inst),
894            Opcode::FPTrunc => self.x87_narrow(inst),
895            Opcode::SIToFP => self.x87_from_signed(inst),
896            Opcode::FPToSI => self.x87_to_signed(inst),
897            Opcode::FAdd => self.x87_arith(inst, "fadd_p"),
898            Opcode::FSub => self.x87_arith(inst, "fsub_p"),
899            Opcode::FMul => self.x87_arith(inst, "fmul_p"),
900            Opcode::FDiv => self.x87_arith(inst, "fdiv_p"),
901            Opcode::FNeg => self.x87_flip(inst),
902            Opcode::FCmp => self.x87_compare(inst),
903            Opcode::FConst => self.x87_const(inst),
904            _ => Err(self.unsupported(inst)),
905        }
906    }
907
908    /// The eighty bit parameters of a block, copied out of the addresses an edge handed over and
909    /// into slots of the block's own.
910    ///
911    /// What crosses an edge for a value of this type is an address, because the value is sixteen
912    /// bytes of the frame and no register holds any of it. The block cannot keep that address: a
913    /// second edge into the same block hands over a second one, and a read after the block would
914    /// then be a read of whichever edge was taken rather than of one place. So the block has a
915    /// slot per parameter and the bytes are copied into it here, which is the move on an edge that
916    /// every other type gets from the allocator.
917    ///
918    /// Every load runs before every store and the stores run backwards, so all of the values are
919    /// on the x87 stack at once and nothing reads a slot another one has already written. That
920    /// costs nothing in the ordinary case of one parameter and is what makes the back edge of a
921    /// loop that swaps two of these work. It is also the reason for the limit: the stack is eight
922    /// deep, and a block with more of these than that is refused rather than copied in an order
923    /// that could be wrong.
924    fn settle(&mut self, block: Block, arriving: &[(Value, mir::Reg)]) -> Result<(), Unsupported> {
925        let Some(&(first, _)) = arriving.first() else { return Ok(()) };
926        if arriving.len() > X87_DEPTH {
927            let ty = self.source[first].ty;
928            return Err(Unsupported::Phi { block, count: arriving.len(), ty });
929        }
930        // A block parameter comes from no instruction, so what this points at is the first thing
931        // in the block, which is where a reader looking for the copy would look.
932        let first_inst = self.source.insts(block).next();
933        let span = first_inst.map_or(Span::DUMMY, |it| self.source.span(it));
934        for &(_, reg) in arriving {
935            let from = self.through(reg);
936            self.x87_at("fld_t", span, from);
937        }
938        for &(param, _) in arriving.iter().rev() {
939            let into = self.x87_slot(param);
940            let into = self.through(into);
941            self.x87_at("fstp_t", span, into);
942        }
943        Ok(())
944    }
945
946    /// The frame slot an eighty bit value lives in, as its address in a fresh register.
947    ///
948    /// The slot is the value's for the whole function and is taken the first time somebody asks.
949    /// The address is worked out again every time, which is a `lea` per use and is deliberate: one
950    /// address kept in a register from the definition to the last use would hold a general purpose
951    /// register open across everything in between, and a function with a handful of these in it
952    /// would spend its registers on addresses of things rather than on things.
953    fn x87_slot(&mut self, value: Value) -> mir::Reg {
954        // An argument of the function has a slot already and it is the caller's. The convention
955        // puts the bytes in the argument area and hands over where they are, so the address that
956        // arrived is the answer and no second copy of the value is made. Nothing ever writes to a
957        // value of this type once it exists, so nothing writes to the caller's copy either. A
958        // parameter of any other block is not this: what arrived there is an address a predecessor
959        // chose, [`Lowering::settle`] has already copied the bytes out of it, and the slot those
960        // bytes landed in is the one below.
961        let entry = self.source.entry();
962        if let (Def::Param { block, .. }, Some(reg)) =
963            (self.source[value].def, self.regs[value.index()])
964        {
965            if entry == Some(block) {
966                return reg;
967            }
968        }
969        let index = match self.slots[value.index()] {
970            Some(index) => index,
971            None => {
972                let index = self.stack.locals.len();
973                self.stack.locals.push(Local { size: X87_BYTES, align: X87_BYTES });
974                self.slots[value.index()] = Some(index);
975                index
976            }
977        };
978        let block = self.at.expect("a block is being filled");
979        self.frame_address(block, index)
980    }
981
982    /// The bytes a value crosses between a register and the x87 stack through, as their address
983    /// in a fresh register.
984    fn x87_crossing(&mut self) -> mir::Reg {
985        let index = match self.crossing {
986            Some(index) => index,
987            None => {
988                let index = self.stack.locals.len();
989                self.stack.locals.push(Local { size: X87_CROSSING, align: X87_CROSSING });
990                self.crossing = Some(index);
991                index
992            }
993        };
994        let block = self.at.expect("a block is being filled");
995        self.frame_address(block, index)
996    }
997
998    /// The two control words, as the address of the first of them in a fresh register.
999    fn x87_control(&mut self) -> mir::Reg {
1000        let index = match self.control {
1001            Some(index) => index,
1002            None => {
1003                let index = self.stack.locals.len();
1004                self.stack.locals.push(Local { size: 4, align: 4 });
1005                self.control = Some(index);
1006                index
1007            }
1008        };
1009        let block = self.at.expect("a block is being filled");
1010        self.frame_address(block, index)
1011    }
1012
1013    /// An address held in a register, as the addressing mode that reaches it.
1014    fn through(&self, reg: mir::Reg) -> mir::Mem {
1015        mir::Mem::at(mir::Operand::read(reg, self.gpr))
1016    }
1017
1018    /// One instruction of a group, which names an address and nothing else.
1019    ///
1020    /// Every x87 instruction that moves a value is one of these. What it does to the stack is in
1021    /// the mnemonic rather than in an operand, so there is no register to write down and no
1022    /// register the allocator gets a say in.
1023    fn x87_at(&mut self, name: &str, span: Span, at: mir::Mem) {
1024        let block = self.at.expect("a block is being filled");
1025        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1026        self.out.build(block, opcode).at(span).mem(at).finish();
1027    }
1028
1029    /// One instruction of a group that names nothing at all.
1030    ///
1031    /// The arithmetic is these. Both of an add's operands are already on the stack when it runs
1032    /// and so is where the answer goes, and the stack is not somewhere an instruction says, so
1033    /// `faddp` has an argument in the assembler's syntax and nothing here for the argument to come
1034    /// from. What it works on is which two pushes came before it, which is a fact about the order
1035    /// of the group and is why the group is written in one place.
1036    fn x87_only(&mut self, name: &str, span: Span) {
1037        let block = self.at.expect("a block is being filled");
1038        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1039        self.out.build(block, opcode).at(span).finish();
1040    }
1041
1042    /// A `load` of a `long double`: onto the stack from where it was, and off it into the slot.
1043    ///
1044    /// Two instructions rather than the two general purpose moves the same sixteen bytes would
1045    /// take, because `fld` and `fstp` at this format neither convert nor look: the value goes on
1046    /// in the format it was already in and comes back off in it, so a signalling NaN stays one
1047    /// and nothing is raised. Which is what makes this a copy at all.
1048    fn x87_load(&mut self, inst: Inst) -> Result<(), Unsupported> {
1049        let (args, result) = self.ends(inst)?;
1050        let &address = args.first().ok_or_else(|| self.unsupported(inst))?;
1051        let span = self.source.span(inst);
1052        let from = self.reg_of(address)?;
1053        let from = self.through(from);
1054        let into = self.x87_slot(result);
1055        let into = self.through(into);
1056        self.x87_at("fld_t", span, from);
1057        self.x87_at("fstp_t", span, into);
1058        Ok(())
1059    }
1060
1061    /// A `store` of a `long double`: the same pair the other way round.
1062    fn x87_store(&mut self, inst: Inst) -> Result<(), Unsupported> {
1063        let args = self.source[self.source[inst].args].to_vec();
1064        let [value, address] = args[..] else { return Err(self.unsupported(inst)) };
1065        let span = self.source.span(inst);
1066        let from = self.x87_slot(value);
1067        let from = self.through(from);
1068        let into = self.reg_of(address)?;
1069        let into = self.through(into);
1070        self.x87_at("fld_t", span, from);
1071        self.x87_at("fstp_t", span, into);
1072        Ok(())
1073    }
1074
1075    /// A `float`, a `double` or an integer becoming a `long double`.
1076    ///
1077    /// Through memory, because the x87 reads memory and nothing else: the value is in a register
1078    /// the machine has and the unit has no way to be handed one, so it is written to the crossing
1079    /// bytes and loaded back at the format that widens it. Every one of these is exact. Sixty four
1080    /// bits of significand and fifteen of exponent hold every `float`, every `double` and every
1081    /// sixty four bit integer outright, so none of the four can round and none can raise.
1082    fn x87_across(
1083        &mut self,
1084        inst: Inst,
1085        put: &'static str,
1086        class: RegClass,
1087        get: &'static str,
1088    ) -> Result<(), Unsupported> {
1089        let (args, result) = self.ends(inst)?;
1090        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1091        let span = self.source.span(inst);
1092        let value = self.reg_of(source)?;
1093        let across = self.x87_crossing();
1094        let across = self.through(across);
1095        let into = self.x87_slot(result);
1096        let into = self.through(into);
1097
1098        let block = self.at.expect("a block is being filled");
1099        let store = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{put}")));
1100        self.out.build(block, store).at(span).uses(value, class).mem(across).finish();
1101        self.x87_at(get, span, across);
1102        self.x87_at("fstp_t", span, into);
1103        Ok(())
1104    }
1105
1106    /// A `long double` becoming a `float`, a `double` or an integer.
1107    ///
1108    /// Through memory for the reason above and in the same three instructions backwards. The two
1109    /// that go to a float round to nearest, which is what the control word says unless somebody
1110    /// has changed it and is what C wants. The two that go to an integer do not, which is why they
1111    /// do not come here.
1112    fn x87_back(
1113        &mut self,
1114        inst: Inst,
1115        put: &'static str,
1116        get: &'static str,
1117        class: RegClass,
1118    ) -> Result<(), Unsupported> {
1119        let (args, result) = self.ends(inst)?;
1120        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1121        let span = self.source.span(inst);
1122        let from = self.x87_slot(source);
1123        let from = self.through(from);
1124        let across = self.x87_crossing();
1125        let across = self.through(across);
1126
1127        self.x87_at("fld_t", span, from);
1128        self.x87_at(put, span, across);
1129        let block = self.at.expect("a block is being filled");
1130        let reg = self.new_reg(result);
1131        let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{get}")));
1132        self.out.build(block, load).at(span).def(reg, class).mem(across).finish();
1133        Ok(())
1134    }
1135
1136    /// An `fpext` up to a `long double`, which is the only direction this machine has one in.
1137    fn x87_widen(&mut self, inst: Inst) -> Result<(), Unsupported> {
1138        let sse = self.conv.sse_class;
1139        match self.source[self.narrow(inst)?].ty.bits() {
1140            32 => self.x87_across(inst, "movss_mr", sse, "fld_s"),
1141            64 => self.x87_across(inst, "movsd_mr", sse, "fld_l"),
1142            _ => Err(self.unsupported(inst)),
1143        }
1144    }
1145
1146    /// An `fptrunc` down from a `long double`, which is the other direction of the same.
1147    fn x87_narrow(&mut self, inst: Inst) -> Result<(), Unsupported> {
1148        let sse = self.conv.sse_class;
1149        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
1150        match self.source[result].ty.bits() {
1151            32 => self.x87_back(inst, "fstp_s", "movss_rm", sse),
1152            64 => self.x87_back(inst, "fstp_l", "movsd_rm", sse),
1153            _ => Err(self.unsupported(inst)),
1154        }
1155    }
1156
1157    /// A `sitofp` up to a `long double`.
1158    ///
1159    /// Thirty two bits and sixty four, and nothing narrower, because C widens an integer to `int`
1160    /// before it converts one and the front end writes that widening down. An unsigned integer is
1161    /// not here at all: `fild` reads its operand as signed, so a value above the signed range
1162    /// comes back short by two to the sixty fourth and has to be added back, which is arithmetic
1163    /// rather than a move and waits with the rest of it.
1164    fn x87_from_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
1165        let gpr = self.gpr;
1166        match self.source[self.narrow(inst)?].ty.bits() {
1167            32 => self.x87_across(inst, "mov_mr_32", gpr, "fild_l"),
1168            64 => self.x87_across(inst, "mov_mr_64", gpr, "fild_ll"),
1169            _ => Err(self.unsupported(inst)),
1170        }
1171    }
1172
1173    /// An `fptosi` down from a `long double`, which is the one conversion here with no single
1174    /// instruction behind it.
1175    ///
1176    /// C cuts towards zero and the unit rounds the way its control word says, so the store that
1177    /// takes the value off the stack is wrapped in the control word being saved, changed and put
1178    /// back. Five instructions around the one that does the work, and three more moving the word
1179    /// through a register, because this machine has no way to OR a constant into memory at this
1180    /// width. The unit has a shorter answer in `fisttp`, and `spec/10-backend.md` section 10.8
1181    /// says why it is not used: it is SSE3, the x86-64 baseline is not, and there is nothing here
1182    /// that can gate an instruction on a feature yet.
1183    fn x87_to_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
1184        let (args, result) = self.ends(inst)?;
1185        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1186        let (put, get) = match self.source[result].ty.bits() {
1187            32 => ("fistp_l", "mov_rm_32"),
1188            64 => ("fistp_ll", "mov_rm_64"),
1189            _ => return Err(self.unsupported(inst)),
1190        };
1191        let span = self.source.span(inst);
1192        let gpr = self.gpr;
1193        let from = self.x87_slot(source);
1194        let from = self.through(from);
1195        let across = self.x87_crossing();
1196        let across = self.through(across);
1197        let control = self.x87_control();
1198        let saved = self.through(control).plus(0);
1199        let cut = self.through(control).plus(2);
1200
1201        // The word the unit has now, into the first of the two slots and into a register, with the
1202        // rounding field turned to truncate on the way to the second.
1203        self.x87_at("fnstcw", span, saved);
1204        let block = self.at.expect("a block is being filled");
1205        let was = self.out.new_vreg(gpr);
1206        let read = mir::Opcode::new(self.names.intern("x64.mov_rm_16"));
1207        self.out.build(block, read).at(span).def(was, gpr).mem(saved).finish();
1208        let now = self.out.new_vreg(gpr);
1209        let set = mir::Opcode::new(self.names.intern("x64.or_ri_16"));
1210        // Two address, which is written out here rather than taken from the two shorthands
1211        // because the shorthands leave an operand unconstrained: this machine ORs into the
1212        // register it read, so the two have to be the same one and only the constraint says so.
1213        self.out
1214            .build(block, set)
1215            .at(span)
1216            .operand(mir::Operand::write(now, gpr).with(Constraint::Reuse(1)))
1217            .operand(mir::Operand::read(was, gpr))
1218            .imm(X87_TRUNCATE)
1219            .finish();
1220        let write = mir::Opcode::new(self.names.intern("x64.mov_mr_16"));
1221        self.out.build(block, write).at(span).uses(now, gpr).mem(cut).finish();
1222
1223        // The conversion itself, under the changed word, and then the word the unit had put back
1224        // before anything else runs.
1225        self.x87_at("fldcw", span, cut);
1226        self.x87_at("fld_t", span, from);
1227        self.x87_at(put, span, across);
1228        self.x87_at("fldcw", span, saved);
1229
1230        let block = self.at.expect("a block is being filled");
1231        let reg = self.new_reg(result);
1232        let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{get}")));
1233        self.out.build(block, load).at(span).def(reg, gpr).mem(across).finish();
1234        Ok(())
1235    }
1236
1237    /// A constant of this type, as the bits of it written into its slot.
1238    ///
1239    /// No x87 instruction at all, which is the surprise here. A slot holding an eighty bit value is
1240    /// the value, so a constant is ten bytes put where the value lives, and the unit never has to
1241    /// see it: whatever reads it will `fld` it out of the slot the way it reads any other one.
1242    ///
1243    /// Ten bytes in two goes, because the machine stores eight at a time and there is no store of
1244    /// an immediate to memory, so each half is put in a register first. The six bytes above the ten
1245    /// are left alone, since nothing reads them: they are the padding that makes the type sixteen
1246    /// wide and they are unspecified in the psABI rather than zero.
1247    ///
1248    /// The other way is a constant pool, an `fldt` of a symbol, and a relocation, which is what a
1249    /// compiler with somewhere to put a literal does. This back end has nowhere to put one yet, and
1250    /// four instructions in the frame is what that costs until it does.
1251    fn x87_const(&mut self, inst: Inst) -> Result<(), Unsupported> {
1252        let Extra::Imm(imm) = self.source[inst].extra else { return Err(self.unsupported(inst)) };
1253        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
1254        let bits = self.source[imm].bits();
1255        let span = self.source.span(inst);
1256        let gpr = self.gpr;
1257        let slot = self.x87_slot(result);
1258        let low = self.through(slot).plus(0);
1259        let high = self.through(slot).plus(8);
1260
1261        let block = self.at.expect("a block is being filled");
1262        for (bytes, at, into) in
1263            [(bits as u64 as i64, low, "64"), (((bits >> 64) & 0xffff) as i64, high, "16")]
1264        {
1265            let held = self.out.new_vreg(gpr);
1266            let put = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_ri_{into}")));
1267            self.out.build(block, put).at(span).def(held, gpr).imm(bytes).finish();
1268            let store = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_mr_{into}")));
1269            self.out.build(block, store).at(span).uses(held, gpr).mem(at).finish();
1270        }
1271        Ok(())
1272    }
1273
1274    /// One arithmetic instruction on two eighty bit values, as the four it takes.
1275    ///
1276    /// The left operand is pushed first and the right one on top of it, so the left ends up
1277    /// underneath and the instruction computes the top against the one below in that order, which
1278    /// is what a subtraction and a division need and is why neither `fsubrp` nor `fdivrp` appears
1279    /// anywhere in this file. The reversed forms exist for a code generator that decided its push
1280    /// order the other way round, and this one does not.
1281    ///
1282    /// The answer is left where the deeper of the two was and the shallower is gone, which is what
1283    /// the `p` on the mnemonic means, so one push has already been paid back by the time the
1284    /// `fstp` runs and the stack is level again after it.
1285    ///
1286    /// Nothing here is folded and nothing is reused. Two values that are the same value get two
1287    /// pushes of the same slot, and an operand that was just computed is read back out of the slot
1288    /// it was written to rather than left on the stack, which costs a store and a load per
1289    /// instruction in an expression. Keeping a partial result on the stack across the next
1290    /// instruction's operands means knowing how deep the stack is at every point in the block, and
1291    /// that is a different thing from writing a group.
1292    fn x87_arith(&mut self, inst: Inst, with: &'static str) -> Result<(), Unsupported> {
1293        let (args, result) = self.ends(inst)?;
1294        let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
1295        let span = self.source.span(inst);
1296        let left = self.x87_slot(left);
1297        let left = self.through(left);
1298        let right = self.x87_slot(right);
1299        let right = self.through(right);
1300        let into = self.x87_slot(result);
1301        let into = self.through(into);
1302        self.x87_at("fld_t", span, left);
1303        self.x87_at("fld_t", span, right);
1304        self.x87_only(with, span);
1305        self.x87_at("fstp_t", span, into);
1306        Ok(())
1307    }
1308
1309    /// A negation, which is a push, the sign bit turned over and a pop.
1310    ///
1311    /// `fchs` does not read the value as a number, so this is right for a zero, for an infinity
1312    /// and for a NaN, and it raises nothing on any of them. Which is what C asks of a negation and
1313    /// is not what subtracting from zero would give: `0.0L - x` is a different answer at a
1314    /// negative zero and a signalling one at a NaN.
1315    fn x87_flip(&mut self, inst: Inst) -> Result<(), Unsupported> {
1316        let (args, result) = self.ends(inst)?;
1317        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1318        let span = self.source.span(inst);
1319        let from = self.x87_slot(source);
1320        let from = self.through(from);
1321        let into = self.x87_slot(result);
1322        let into = self.through(into);
1323        self.x87_at("fld_t", span, from);
1324        self.x87_only("fchs", span);
1325        self.x87_at("fstp_t", span, into);
1326        Ok(())
1327    }
1328
1329    /// A comparison of two eighty bit values, as the two pushes and the one opcode that reads them.
1330    ///
1331    /// The right operand is pushed first and the left one on top of it, which is the other way
1332    /// round from the arithmetic and is because `fucomip` asks about the top against what is under
1333    /// it: the comparison this machine can do is the top's, so the value the predicate is about
1334    /// has to be the top. The pop that gets the loser off the stack and the byte that reads the
1335    /// flags are both inside the opcode, since what passes between those and the comparison is the
1336    /// flags and the flags are not something anything here can name.
1337    ///
1338    /// Which of the ten opcodes, and which way round, is the same table the vector comparisons
1339    /// match against in `rules/x86-64.rules`, and it has to stay the same table: a predicate that
1340    /// picked a different condition here than there would be a `long double` comparison that
1341    /// disagreed with the `double` comparison of the same two numbers, which is the one thing a
1342    /// wider format is not allowed to do.
1343    ///
1344    /// The always false and the always true are refused rather than folded into a constant,
1345    /// because a comparison this machine never has to do is one the optimizer should have removed
1346    /// and an instruction here that quietly agreed with it would hide that it did not.
1347    fn x87_compare(&mut self, inst: Inst) -> Result<(), Unsupported> {
1348        let Extra::FloatPred(pred) = self.source[inst].extra else {
1349            return Err(self.unsupported(inst));
1350        };
1351        let (args, result) = self.ends(inst)?;
1352        let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
1353        // Two of the fourteen need a second byte and an instruction to put the two together,
1354        // because they are two conditions at once: an ordered equal is equal and not unordered,
1355        // and an unordered not equal is either. The opcode carries all of that and says here only
1356        // that it writes somewhere else as well.
1357        let (name, reversed, both) = match pred {
1358            FloatPred::Ogt => ("fucomip_set_a", false, false),
1359            FloatPred::Oge => ("fucomip_set_ae", false, false),
1360            FloatPred::Olt => ("fucomip_set_a", true, false),
1361            FloatPred::Ole => ("fucomip_set_ae", true, false),
1362            FloatPred::One => ("fucomip_set_ne", false, false),
1363            FloatPred::Ord => ("fucomip_set_np", false, false),
1364            FloatPred::Uno => ("fucomip_set_p", false, false),
1365            FloatPred::Ueq => ("fucomip_set_e", false, false),
1366            FloatPred::Ult => ("fucomip_set_b", false, false),
1367            FloatPred::Ule => ("fucomip_set_be", false, false),
1368            FloatPred::Ugt => ("fucomip_set_b", true, false),
1369            FloatPred::Uge => ("fucomip_set_be", true, false),
1370            FloatPred::Oeq => ("fucomip_set_e_and_np", false, true),
1371            FloatPred::Une => ("fucomip_set_ne_or_p", false, true),
1372            FloatPred::False | FloatPred::True => return Err(self.unsupported(inst)),
1373        };
1374        let (top, under) = if reversed { (right, left) } else { (left, right) };
1375
1376        let span = self.source.span(inst);
1377        let gpr = self.gpr;
1378        let under = self.x87_slot(under);
1379        let under = self.through(under);
1380        let top = self.x87_slot(top);
1381        let top = self.through(top);
1382        self.x87_at("fld_t", span, under);
1383        self.x87_at("fld_t", span, top);
1384
1385        let block = self.at.expect("a block is being filled");
1386        let reg = self.new_reg(result);
1387        // Taken before the instruction is started rather than inside it, since both come from the
1388        // same function being built and only one thing at a time may be adding to it.
1389        let spare = both.then(|| self.out.new_vreg(gpr));
1390        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1391        let mut build = self.out.build(block, opcode).at(span).def(reg, gpr);
1392        if let Some(spare) = spare {
1393            build = build.def(spare, gpr);
1394        }
1395        build.finish();
1396        Ok(())
1397    }
1398
1399    /// The operands and the one result of an instruction that has exactly one.
1400    fn ends(&self, inst: Inst) -> Result<(&'a [Value], Value), Unsupported> {
1401        let data = &self.source[inst];
1402        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1403        Ok((&self.source[data.args], result))
1404    }
1405
1406    /// The operand of a conversion, which is the end of it that is not the `long double`.
1407    fn narrow(&self, inst: Inst) -> Result<Value, Unsupported> {
1408        let args = &self.source[self.source[inst].args];
1409        args.first().copied().ok_or_else(|| self.unsupported(inst))
1410    }
1411
1412    /// One `va_start`, as the four fields of the list it was handed.
1413    ///
1414    /// Two of them are numbers this already knows, and each costs an instruction to put in a
1415    /// register before it can be stored, because the machine here has no store of an immediate to
1416    /// memory. The other two are addresses in the frame, and each is a `lea` [`crate::finish`]
1417    /// finishes: the save area is one of the function's own stack objects, and the caller's
1418    /// argument area is where the parameters that had no register came from, which is the same
1419    /// place and the same fixup a parameter past the sixth already uses.
1420    ///
1421    /// What is written is exactly the four fields [`crate::varargs`] describes, in the order they
1422    /// are laid out, so that reading this beside that table is the whole of the check.
1423    fn va_start(&mut self, inst: Inst) -> Result<(), Unsupported> {
1424        let Some(&list) = self.source[self.source[inst].args].first() else {
1425            return Err(self.unsupported(inst));
1426        };
1427        let started = self.varargs.ok_or_else(|| self.unsupported(inst))?;
1428        let list = self.reg_of(list)?;
1429        let block = self.at.expect("a block is being filled");
1430        let span = self.source.span(inst);
1431
1432        for (at, count) in
1433            [(varargs::GP_OFFSET, started.integers), (varargs::FP_OFFSET, started.floats)]
1434        {
1435            let held = self.out.new_vreg(self.gpr);
1436            let load = mir::Opcode::new(self.names.intern("x64.mov_ri_32"));
1437            self.out.build(block, load).at(span).def(held, self.gpr).imm(i64::from(count)).finish();
1438
1439            let store = mir::Opcode::new(self.names.intern("x64.mov_mr_32"));
1440            let mem = self.field(list, at);
1441            self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
1442        }
1443
1444        // The first argument the signature did not name, which is as far up the caller's argument
1445        // area as the ones it did name reached. Nothing here knows where that area is, so the
1446        // distance is recorded the way a parameter read out of it is and finished with it.
1447        let overflow = self.out.new_vreg(self.gpr);
1448        let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
1449        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
1450        let made = self
1451            .out
1452            .build(block, lea)
1453            .at(span)
1454            .def(overflow, self.gpr)
1455            .mem(mir::Mem::at(sp))
1456            .finish();
1457        self.stack.arguments.push((made, started.incoming));
1458
1459        let save = self.frame_address(block, started.save);
1460        for (at, held) in [(varargs::OVERFLOW, overflow), (varargs::SAVE_AREA, save)] {
1461            let store = mir::Opcode::new(self.names.intern("x64.mov_mr_64"));
1462            let mem = self.field(list, at);
1463            self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
1464        }
1465        Ok(())
1466    }
1467
1468    /// One field of a list, as the addressing mode that reaches it.
1469    fn field(&self, list: mir::Reg, at: i64) -> mir::Mem {
1470        let base = mir::Operand::read(list, self.gpr);
1471        mir::Mem::at(base).plus(i32::try_from(at).expect("a field of a list is a small offset"))
1472    }
1473
1474    /// The address of a name: one `lea` off the instruction pointer, with the name on it.
1475    ///
1476    /// The same instruction an `alloca` gets and for a related reason. An address that is not in
1477    /// the program is a `lea` of an addressing mode that names no register, and the mode carries
1478    /// the symbol so that [`rucc_asm`] can write it relative to `%rip` and leave the relocation
1479    /// for the assembler. Both halves of that already existed: the printer writes `sym(%rip)` and
1480    /// the encoder emits the relocation, because a call to a name the file does not define needed
1481    /// them first.
1482    ///
1483    /// There is deliberately no name for this in [`crate::term`], which is what stops the address
1484    /// being folded into the instruction that reads it. Folding it is the right thing to do and
1485    /// is what turns a load of a global from two instructions into one, but it is a separate
1486    /// question about addressing modes and issue #282 is it. Until then the address is in a
1487    /// register before anything uses it, which is correct and one instruction longer.
1488    ///
1489    /// What this does not do is give the name anything to refer to. A module carries its globals
1490    /// and nothing writes them out, so a file that defines the variable it reads compiles to a
1491    /// reference the linker cannot resolve. Issue #293 is the other half.
1492    fn address_of(&mut self, inst: Inst) -> Result<(), Unsupported> {
1493        let data = &self.source[inst];
1494        let Extra::Symbol(symbol) = data.extra else { return Err(self.unsupported(inst)) };
1495        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1496
1497        let block = self.at.expect("a block is being filled");
1498        let reg = self.new_reg(result);
1499        let span = self.source.span(inst);
1500        let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
1501        self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::of(symbol)).finish();
1502        Ok(())
1503    }
1504
1505    /// A conversion that converts nothing: the result is the operand under another type.
1506    ///
1507    /// `ptrtoint` and `inttoptr` at one width are the whole of this. An address on this machine is
1508    /// an integer as wide as the machine addresses, so a cast between the two changes what the
1509    /// type system calls the value and changes nothing about the value, and the register holding
1510    /// it is the register that already held it. The front end never writes either of them at any
1511    /// other width, because it widens or narrows around the cast rather than through it, so the
1512    /// two widths disagreeing here means the IR came from somewhere else and is refused rather
1513    /// than guessed at.
1514    ///
1515    /// Reading the operand first is what materializes it when it is a constant, which is the case
1516    /// that matters: a null pointer is an `inttoptr` of zero, and that zero has to reach a
1517    /// register before anything can call it an address.
1518    fn rename(&mut self, inst: Inst) -> Result<(), Unsupported> {
1519        let data = &self.source[inst];
1520        let [arg] = self.source[data.args] else { return Err(self.unsupported(inst)) };
1521        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1522        if !self.is_address_width(self.source[arg].ty)
1523            || !self.is_address_width(self.source[result].ty)
1524        {
1525            return Err(self.unsupported(inst));
1526        }
1527        let reg = self.reg_of(arg)?;
1528        self.regs[result.index()] = Some(reg);
1529        Ok(())
1530    }
1531
1532    /// One barrier, which on this machine is one instruction at the strongest ordering and no
1533    /// instruction at all at every other one.
1534    ///
1535    /// x86-64 is total store order, so the only reordering the machine does is a store followed by
1536    /// a load of a different address, and the only ordering that forbids that is sequential
1537    /// consistency. An acquire, a release and an acquire release fence are therefore already true
1538    /// of every program running here, and what a program wanted from writing one is that the
1539    /// compiler not move memory accesses across it. The optimizer has finished by the time this
1540    /// runs and nothing below reorders one access past another, so the constraint is already
1541    /// discharged and there is nothing to write.
1542    ///
1543    /// The strongest one is `mfence`, which is what gcc 16.2.0 writes for
1544    /// `__atomic_thread_fence(__ATOMIC_SEQ_CST)` and for `__sync_synchronize`. A locked instruction
1545    /// on the stack is faster on most parts and is what some compilers write instead; it is also a
1546    /// write to memory the program did not ask for, and the plain barrier is the one that says what
1547    /// it means.
1548    ///
1549    /// Written here by name rather than by a rule, for the same reason a `lea` of a symbol is:
1550    /// there is nothing in a barrier that a proof over bitvectors could discharge. It computes
1551    /// nothing, so there is no equality to state, and what makes it the right answer is the memory
1552    /// model, which the rule language cannot talk about.
1553    fn barrier(&mut self, inst: Inst) -> Result<(), Unsupported> {
1554        let Extra::Order(order) = self.source[inst].extra else {
1555            return Err(self.unsupported(inst));
1556        };
1557        if order != MemOrder::SeqCst {
1558            return Ok(());
1559        }
1560        let block = self.at.expect("a block is being filled");
1561        let span = self.source.span(inst);
1562        let fence = mir::Opcode::new(self.names.intern("x64.mfence"));
1563        self.out.build(block, fence).at(span).finish();
1564        Ok(())
1565    }
1566
1567    /// Whether a type is the width an address is, which is what makes a cast to or from one free.
1568    fn is_address_width(&self, ty: Type) -> bool {
1569        ty.is_ptr() || (ty.is_int() && ty.bits() == ADDRESS_BITS)
1570    }
1571
1572    /// Where a block goes, which in machine IR is on the block rather than on its terminator.
1573    ///
1574    /// That is why no rule ever names a block: a branch is selected for what it reads and the
1575    /// edges are copied across here, arguments and all. The arguments are read last, after every
1576    /// instruction of the block is written, because an argument that is a constant is
1577    /// materialized where it is first wanted and the end of the block is where an edge wants it.
1578    ///
1579    /// Which is not quite the end. A block that leaves two ways has the branch as its last
1580    /// instruction, and anything appended after a branch is something the branch has already
1581    /// jumped past, so a constant materialized here would be a register the block below reads and
1582    /// nothing ever writes. The branch is put back on the end when that happened, which is the
1583    /// only reordering anything in this crate does and is why the branch is remembered before a
1584    /// single argument is read.
1585    fn edges(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
1586        let Some(term) = self.source.terminator(block) else { return Ok(()) };
1587        let branch =
1588            if self.source[term].opcode == Opcode::BrIf { self.out.terminator(out) } else { None };
1589
1590        let calls: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
1591        let mut succs = Vec::with_capacity(calls.len());
1592        for call in calls {
1593            let args: Vec<Value> = self.source[call.args].to_vec();
1594            let mut regs = Vec::with_capacity(args.len());
1595            for value in args {
1596                // The address of where the value is rather than the value, for the one type a
1597                // register holds none of. The block on the other side copies the bytes out of it
1598                // into a slot of its own, which is what makes a second edge into the same block
1599                // safe.
1600                let reg = if on_x87(self.source[value].ty) {
1601                    self.x87_slot(value)
1602                } else {
1603                    self.reg_of(value)?
1604                };
1605                regs.push(reg);
1606            }
1607            succs.push(mir::BlockCall { block: self.out_block(call.block), args: regs });
1608        }
1609        if let Some(branch) = branch {
1610            if self.out.terminator(out) != Some(branch) {
1611                self.out.remove_inst(branch);
1612                self.out.append_inst(out, branch);
1613            }
1614        }
1615        *self.out.succs_mut(out) = succs;
1616        Ok(())
1617    }
1618
1619    /// The machine IR block an IR block became.
1620    fn out_block(&self, block: Block) -> mir::Block {
1621        self.blocks[block.index()].expect("every block was created before any was filled")
1622    }
1623
1624    /// The parameters of the entry block, which are the function's arguments.
1625    ///
1626    /// They are not block parameters in the machine IR and they cannot be. A block parameter is
1627    /// given its value by a move on the edge into the block, and there is no edge into an entry
1628    /// block, so what arrives in a function is the convention's to say. [`crate::abi`] is what
1629    /// says it.
1630    ///
1631    /// The ones past the last register arrived in the caller's memory and are read out of it, and
1632    /// the loads that read them come back here so that the frame can finish them the way it
1633    /// finishes an `alloca`.
1634    fn arrive(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
1635        let params = self.source[block].params.clone();
1636        // The type of each is the block's answer and what the ABI asks of it is the signature's,
1637        // and the two lists are the same list: a parameter the classification turned into a
1638        // pointer is a pointer in the block too. A block with more parameters than the signature
1639        // names is not one the front end writes, and each of those is taken as a plain value.
1640        let asked: Vec<Abi> = self.source.signature().params.iter().map(|it| it.abi).collect();
1641        let types: Vec<Param> = params
1642            .iter()
1643            .enumerate()
1644            .map(|(index, &value)| {
1645                let abi = asked.get(index).copied().unwrap_or_default();
1646                Param { ty: self.source[value].ty, abi }
1647            })
1648            .collect();
1649        // A save area for a function that takes arguments its signature does not name, on a
1650        // convention whose list is the four field one. Windows is the other kind and has no area at
1651        // all, so a `va_start` in one is refused rather than built wrong.
1652        let variadic = self.source.signature().variadic && !self.conv.shared_positions;
1653        let area = variadic.then(|| varargs::Area::of(self.conv));
1654        let arrived = abi::entry(&mut self.out, out, &types, self.conv, self.names, area)
1655            .map_err(|(index, missing)| Unsupported::Argument { index, missing })?;
1656        for (&param, reg) in params.iter().zip(&arrived.regs) {
1657            self.regs[param.index()] = Some(*reg);
1658        }
1659        if let Some(area) = area {
1660            self.save_area(out, &arrived, area);
1661        }
1662        self.stack.arguments.extend(arrived.stack);
1663        Ok(())
1664    }
1665
1666    /// The prologue of a variadic function, which is every argument register it was handed written
1667    /// into the frame.
1668    ///
1669    /// Every one the signature did not name, that is. Which of those hold anything is a thing only
1670    /// the caller knew and there is nothing here to ask, so all of them are written, and the ones a
1671    /// named parameter took are not, because `va_start` sets the two offsets past them and nothing
1672    /// ever reads their slots.
1673    ///
1674    /// What that costs is up to fourteen stores in the prologue of a function that may read none of
1675    /// them, and the convention's answer to that is the count of vector registers in `%al`, which
1676    /// lets a callee skip the eight vector stores when the call passed no floats. Skipping them is a
1677    /// branch in a prologue, and a prologue is written long after this by [`crate::finish`], which
1678    /// has no blocks to branch between. So they are all written every time, which is correct and is
1679    /// what `-O0` costs. Issue #323 is the branch.
1680    ///
1681    /// A vector register is written eight bytes at a time and not sixteen, for the reason
1682    /// [`crate::varargs`] gives: the upper half of a slot is not something any reader of a list
1683    /// looks at.
1684    ///
1685    /// The address is computed once into a register rather than written as a displacement off the
1686    /// stack pointer, because a displacement into a frame is not known until after allocation and
1687    /// one `lea` costs less than a fixup list for a dozen stores. It is the same `lea` an `alloca`
1688    /// gets and [`crate::finish`] fills it in the same way.
1689    fn save_area(&mut self, out: mir::Block, arrived: &abi::Arrived, area: varargs::Area) {
1690        let save = self.stack.locals.len();
1691        self.stack.locals.push(Local { size: area.size, align: varargs::VECTOR_SLOT });
1692        self.varargs = Some(Varargs {
1693            save,
1694            incoming: arrived.used,
1695            integers: u32::try_from(arrived.took.0).unwrap_or(0) * area.stride(false),
1696            floats: area.starts_at(true)
1697                + u32::try_from(arrived.took.1).unwrap_or(0) * area.stride(true),
1698        });
1699
1700        let base = self.frame_address(out, save);
1701        for &(reg, class, at) in &arrived.spare {
1702            let name = if class == self.gpr { "x64.mov_mr_64" } else { "x64.movsd_mr" };
1703            let store = mir::Opcode::new(self.names.intern(name));
1704            let up = i32::try_from(at).expect("a register save area under two gigabytes");
1705            let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
1706            self.out.build(out, store).uses(reg, class).mem(mem).finish();
1707        }
1708    }
1709
1710    /// The address of one of the function's stack objects, in a fresh register.
1711    ///
1712    /// Written with nothing in its displacement, because where an object is in a frame is not known
1713    /// until after allocation, and given to [`crate::finish`] to fill in the way an `alloca` is.
1714    fn frame_address(&mut self, out: mir::Block, local: usize) -> mir::Reg {
1715        let reg = self.out.new_vreg(self.gpr);
1716        let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
1717        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
1718        let made = self.out.build(out, lea).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
1719        self.stack.addresses.push((made, local));
1720        reg
1721    }
1722
1723    /// Whether an instruction is one no machine instruction is written for where it stands.
1724    ///
1725    /// Four of them, and none is a lowering decision, which is why none is a rule. A constant is
1726    /// written where a register for it is first wanted rather than where the IR put it, and every
1727    /// reader of one may have folded it into an immediate, in which case nowhere is the right
1728    /// place. A return of nothing has nothing to put anywhere: the epilogue gives the frame back
1729    /// and leaves, and it is appended to every block with no successors long after this has
1730    /// finished, so a return with a value is one instruction here and a return without one is
1731    /// none. Unless the value went back through memory, in which case there is something to put
1732    /// somewhere after all and the IR does not carry it: the address the caller handed over has
1733    /// to be in `rax` on the way out, and [`Lowering::returned`] is what writes that.
1734    ///
1735    /// An unconditional jump is the third, and there is even less of it: the edge is on the
1736    /// block, and whether the block it goes to is the next one and needs no jump at all is the
1737    /// block layout's answer rather than this one's.
1738    ///
1739    /// The fourth is a point control does not arrive at, in both of the forms the IR has for it:
1740    /// the `unreachable` terminator the front end puts at the end of a function whose body can run
1741    /// off the bottom, and the `unreachable_hint` a call to `__builtin_unreachable` becomes. What
1742    /// to write for a place nothing reaches is a question with no wrong answer, and nothing is the
1743    /// smallest one and the one gcc 16.2.0 gives at `-O0`. The terminator leaves the block with no
1744    /// successors, so the epilogue lands at the end of it the way it does on any other block that
1745    /// goes nowhere, and the function cannot fall out of its own last instruction into whatever
1746    /// the assembler puts next.
1747    fn writes_nothing(&self, inst: Inst) -> bool {
1748        let data = &self.source[inst];
1749        match data.opcode {
1750            Opcode::IConst | Opcode::Jump | Opcode::Unreachable | Opcode::UnreachableHint => true,
1751            Opcode::Return => self.source[data.args].is_empty() && self.sret().is_none(),
1752            _ => false,
1753        }
1754    }
1755
1756    /// The rule that fires on an instruction, and what it bound.
1757    ///
1758    /// The plans are tried in order and the first that matches wins, which is the maximal munch
1759    /// `spec/10-backend.md` asks for: a plan that offers more to the matcher is tried before one
1760    /// that offers less.
1761    fn select(&self, inst: Inst) -> Option<(Plan, Match<Term>)> {
1762        for plan in self.plans(inst) {
1763            let terms = Terms::new(self.source, inst, plan);
1764            if let Some(matched) = TABLE.find(&terms, Term::Root) {
1765                return Some((plan, matched));
1766            }
1767        }
1768        None
1769    }
1770
1771    /// Every way this instruction can be shown to the matcher, most offered first.
1772    fn plans(&self, inst: Inst) -> Vec<Plan> {
1773        let args = &self.source[self.source[inst].args];
1774        let mut plans = vec![PLAIN];
1775        for (index, &arg) in args.iter().enumerate().take(MAX_ARGS) {
1776            let mut ways = Vec::new();
1777            if self.foldable(inst, arg) {
1778                ways.push(Shown::Expand);
1779            }
1780            if Terms::new(self.source, inst, PLAIN).constant(arg).is_some() {
1781                ways.push(Shown::Const);
1782            }
1783            ways.push(Shown::Reg);
1784            plans = plans
1785                .into_iter()
1786                .flat_map(|plan| {
1787                    ways.iter().map(move |&way| {
1788                        let mut next = plan;
1789                        next[index] = way;
1790                        next
1791                    })
1792                })
1793                .collect();
1794        }
1795        plans
1796    }
1797
1798    /// Whether an operand may be shown as the instruction that computed it.
1799    ///
1800    /// It has to be in the same block, because a rule that folds one instruction into another
1801    /// moves the work to where the second one is. It has to be read only by this instruction,
1802    /// because folding it does not delete it for anybody else and doing the work twice is not a
1803    /// saving. And it has to be something rather than a block parameter, and not a constant,
1804    /// which is shown as a constant instead.
1805    fn foldable(&self, into: Inst, value: Value) -> bool {
1806        let Def::Result { inst, .. } = self.source[value].def else { return false };
1807        if self.source[inst].opcode == Opcode::IConst || self.uses[value.index()] != 1 {
1808            return false;
1809        }
1810        self.source.block_of(inst).is_some()
1811            && self.source.block_of(inst) == self.source.block_of(into)
1812    }
1813
1814    /// The instructions a match folded into the one it matched.
1815    ///
1816    /// The plan is what says this, not the bindings: a binding is a register or a number either
1817    /// way, and an operand shown as the instruction that computed it is one no rule could have
1818    /// matched without taking that instruction, because the plan offered the matcher nothing
1819    /// else to call it.
1820    fn folds(&self, inst: Inst, plan: Plan) -> Vec<Inst> {
1821        let args = &self.source[self.source[inst].args];
1822        args.iter()
1823            .take(MAX_ARGS)
1824            .enumerate()
1825            .filter(|&(index, _)| plan[index] == Shown::Expand)
1826            .filter_map(|(_, &arg)| match self.source[arg].def {
1827                Def::Result { inst, .. } => Some(inst),
1828                Def::Param { .. } => None,
1829            })
1830            .collect()
1831    }
1832
1833    /// Build the machine instruction a match calls for.
1834    fn emit(&mut self, inst: Inst, matched: &Match<Term>) -> Result<(), Unsupported> {
1835        let rule: &Rule = TABLE.rule(matched);
1836        let pieces = rule.replacement;
1837        let Some(Piece::App { head, arity }) = pieces.first() else {
1838            return Err(self.unsupported(inst));
1839        };
1840        let opcode = head.strip_prefix(PREFIX).ok_or_else(|| self.unsupported(inst))?;
1841        let form = x86_64::form(opcode).ok_or_else(|| self.unsupported(inst))?;
1842
1843        let mut read = Read::default();
1844        let mut at = 1;
1845        for _ in 0..*arity {
1846            at = self.read(inst, pieces, at, &matched.bindings, &mut read)?;
1847        }
1848
1849        let descs = form.operands();
1850        let writes = descs.iter().take_while(|desc| desc.role.is_def()).count();
1851        if descs.len() - writes != read.regs.len() {
1852            return Err(self.unsupported(inst));
1853        }
1854
1855        // The first thing the instruction writes is what it computes, and any others are
1856        // registers the machine destroys on the way, which are fresh because nothing else is in
1857        // them and nothing reads them. An instruction that writes nothing at all is one whose
1858        // whole purpose is its effect, which is what a store is, and there is no result to put
1859        // anywhere.
1860        let mut regs = Vec::new();
1861        if writes > 0 {
1862            let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
1863            regs.push(self.new_reg(result));
1864            // The rest are the registers the machine destroys on the way, and the class each is in
1865            // is the one the instruction's description gives it rather than a guess, so that an
1866            // instruction that wrecks a register in the other file says so.
1867            regs.extend(descs[1..writes].iter().map(|desc| self.out.new_vreg(desc.class)));
1868        } else if self.source[inst].first_result.is_some() {
1869            // A rule that throws away a value the IR gave a name to would leave every reader of
1870            // that name with nothing to read, so it is a rule this and the target disagree about.
1871            return Err(self.unsupported(inst));
1872        }
1873        regs.extend(read.regs.iter().copied());
1874
1875        let block = self.at.expect("a block is being filled");
1876        let opcode = mir::Opcode::new(self.names.intern(head));
1877        let mut build = self.out.build(block, opcode).at(self.source.span(inst));
1878        for (desc, reg) in descs.iter().zip(regs) {
1879            let operand = mir::Operand {
1880                reg,
1881                class: desc.class,
1882                role: desc.role,
1883                constraint: desc.constraint,
1884            };
1885            build = build.operand(operand);
1886        }
1887        if let Some(mem) = read.mem {
1888            build = build.mem(mem);
1889        }
1890        if let Some(imm) = read.imm {
1891            build = build.imm(imm);
1892        }
1893        build.finish();
1894        Ok(())
1895    }
1896
1897    /// Read one argument of a replacement, which is a register, a number or an address.
1898    ///
1899    /// Gives back the position after it, because a replacement is flat and an address takes
1900    /// arguments of its own.
1901    fn read(
1902        &mut self,
1903        inst: Inst,
1904        pieces: &'static [Piece],
1905        at: usize,
1906        bindings: &[Term],
1907        out: &mut Read,
1908    ) -> Result<usize, Unsupported> {
1909        match pieces.get(at) {
1910            Some(Piece::Int(value)) => {
1911                out.imm = i64::try_from(*value).ok();
1912                Ok(at + 1)
1913            }
1914            Some(Piece::Var { index, .. }) => {
1915                match bindings.get(*index) {
1916                    Some(&Term::Reg(value)) => {
1917                        let reg = self.reg_of(value)?;
1918                        out.regs.push(reg);
1919                    }
1920                    Some(&Term::Num(value)) => out.imm = i64::try_from(value).ok(),
1921                    // A pattern binds a register or a number and nothing else, so this is a
1922                    // rule the matcher and this file disagree about.
1923                    _ => return Err(self.unsupported(inst)),
1924                }
1925                Ok(at + 1)
1926            }
1927            Some(Piece::App { head, arity }) => {
1928                let kind = x86_64::address(head).ok_or_else(|| self.unsupported(inst))?;
1929                let mut inner = Read::default();
1930                let mut next = at + 1;
1931                for _ in 0..*arity {
1932                    next = self.read(inst, pieces, next, bindings, &mut inner)?;
1933                }
1934                let mem = address(kind, &inner, self.gpr).ok_or_else(|| self.unsupported(inst))?;
1935                out.mem = Some(mem);
1936                Ok(next)
1937            }
1938            None => Err(self.unsupported(inst)),
1939        }
1940    }
1941
1942    /// The register a value is in, materializing it if it is a constant that has not been put in
1943    /// one yet.
1944    ///
1945    /// A constant is written where it is wanted rather than where the IR defined it, and where it
1946    /// is wanted is a block that need not be the one the IR defined it in. So the register holding
1947    /// one is only good inside the block it was written into, and a second block that wants the
1948    /// same constant gets its own. Anything else is a register read where nothing wrote it: the
1949    /// IR guarantees a definition dominates its uses, and this moved the definition.
1950    ///
1951    /// Writing the number again is also the right answer and not merely the safe one. It is one
1952    /// instruction that reads nothing, which is cheaper than holding a register live across a
1953    /// branch for it, and it is what a rematerializing allocator would do with the value anyway.
1954    fn reg_of(&mut self, value: Value) -> Result<mir::Reg, Unsupported> {
1955        let constant = match self.source[value].def {
1956            Def::Result { inst, .. } => {
1957                (self.source[inst].opcode == Opcode::IConst).then_some(inst)
1958            }
1959            Def::Param { .. } => None,
1960        };
1961        let here = self.at.expect("a block is being filled");
1962        if let Some(reg) = self.regs[value.index()] {
1963            if constant.is_none() || self.written[value.index()] == Some(here) {
1964                return Ok(reg);
1965            }
1966        }
1967        if let Some(inst) = constant {
1968            // Cleared so that the register the constant is written into is a new one rather than
1969            // the one the block above wrote, which is still being read up there.
1970            self.regs[value.index()] = None;
1971            let matched = self
1972                .select(inst)
1973                .map(|(_, matched)| matched)
1974                .ok_or_else(|| self.unsupported(inst))?;
1975            self.emit(inst, &matched)?;
1976            // The same mark the loop over the instructions makes, and it has to be made here as
1977            // well because this is the only place a constant is ever selected: the loop skips one
1978            // where the IR wrote it, so a rule that lowers a constant fires from nowhere else and
1979            // would be reported as a rule nothing reaches.
1980            self.fired.mark(matched.rule);
1981            self.written[value.index()] = Some(here);
1982            return Ok(self.regs[value.index()].expect("a constant is written into a register"));
1983        }
1984        Ok(self.new_reg(value))
1985    }
1986
1987    /// Which register file a value of that type lives in.
1988    ///
1989    /// The vector one for the two float widths the machine has scalar instructions for, and the
1990    /// general purpose one for everything else. A `long double` is in neither, and it is here
1991    /// rather than in the vector class on purpose: it would be put in a register that cannot hold
1992    /// it, and there is no rule that names one, so the instruction computing it is reported. The
1993    /// wrong class would make that a wrong program instead of a refused one.
1994    fn class_of(&self, ty: Type) -> RegClass {
1995        match crate::term::float_slot(ty) {
1996            Some(_) => self.conv.sse_class,
1997            None => self.gpr,
1998        }
1999    }
2000
2001    /// A fresh register for a value, which is what the instruction computing it writes.
2002    fn new_reg(&mut self, value: Value) -> mir::Reg {
2003        if let Some(reg) = self.regs[value.index()] {
2004            return reg;
2005        }
2006        let reg = self.out.new_vreg(self.class_of(self.source[value].ty));
2007        self.regs[value.index()] = Some(reg);
2008        reg
2009    }
2010
2011    fn unsupported(&self, inst: Inst) -> Unsupported {
2012        let data = &self.source[inst];
2013        Unsupported::Inst {
2014            inst,
2015            term: Terms::new(self.source, inst, PLAIN).name(inst),
2016            opcode: data.opcode,
2017            ty: data.first_result.map(|result| self.source[result].ty),
2018        }
2019    }
2020}
2021
2022/// What the arguments of one replacement came to.
2023#[derive(Debug, Default)]
2024struct Read {
2025    regs: Vec<mir::Reg>,
2026    imm: Option<i64>,
2027    mem: Option<mir::Mem>,
2028}
2029
2030/// The addressing mode an address constructor's arguments make.
2031///
2032/// One arm per constructor rather than a question asked of the kind, because what the arguments
2033/// mean is the whole of what tells the four apart: the same register is a base in one and an
2034/// index in another, and the same constant is a scale in one and a displacement in another.
2035fn address(kind: x86_64::Address, read: &Read, gpr: RegClass) -> Option<mir::Mem> {
2036    let mut regs = read.regs.iter().copied().map(|reg| mir::Operand::read(reg, gpr));
2037    match kind {
2038        x86_64::Address::BaseIndexScale => {
2039            let base = regs.next()?;
2040            let index = regs.next()?;
2041            Some(mir::Mem::at(base).indexed(index, u8::try_from(read.imm?).ok()?))
2042        }
2043        x86_64::Address::IndexScale => Some(mir::Mem {
2044            base: None,
2045            index: Some(regs.next()?),
2046            scale: u8::try_from(read.imm?).ok()?,
2047            disp: 0,
2048            symbol: None,
2049        }),
2050        x86_64::Address::Base => Some(mir::Mem::at(regs.next()?)),
2051        // The rule that writes this has a guard saying the constant fits, so a displacement that
2052        // does not is a rule and a target that disagree rather than a program this cannot compile.
2053        x86_64::Address::BaseOffset => {
2054            Some(mir::Mem { disp: i32::try_from(read.imm?).ok()?, ..mir::Mem::at(regs.next()?) })
2055        }
2056    }
2057}
2058
2059/// The table this selector matches with.
2060///
2061/// One target for now, because one target has a rule file. Which table to use becomes a question
2062/// the moment a second one does, and the answer will be the target the session was given rather
2063/// than a constant here.
2064static TABLE: &Table = &crate::select::x86_64::TABLE;
2065
2066#[cfg(test)]
2067mod tests {
2068    use rucc_ir::{
2069        Builder, CallInfo, Flags, InstData, MemInfo, MemOrder, Restrict, Signature, Type,
2070    };
2071    use rucc_regalloc::assign::Env;
2072    use rucc_target::x86_64::{FRAME, REGS, SYSV};
2073
2074    use super::*;
2075    use crate::finish::finish;
2076    use crate::frame::{Frame, Incoming, Layout};
2077
2078    /// A function of as many 64 bit parameters as the test wants, and the block they are in.
2079    fn blank(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
2080        let mut names = Interner::new();
2081        let mut func = Func::new(names.intern("f"), Signature::new());
2082        let block = func.create_block();
2083        let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
2084        (names, func, block, values)
2085    }
2086
2087    /// An ordinary access: not atomic, and aligned enough that nothing here has an opinion.
2088    /// Neither field reaches selection, which is the point of saying it once here.
2089    fn plain() -> MemInfo {
2090        MemInfo {
2091            size: 0,
2092            align: 1,
2093            order: MemOrder::NotAtomic,
2094            tbaa: None,
2095            restrict: Restrict::NONE,
2096        }
2097    }
2098
2099    /// What the allocator is given: every integer register the convention offers except two, held
2100    /// back so that a move on an edge has somewhere to break a cycle and a spilled value has
2101    /// somewhere to be read into. Which two does not matter, and holding back the last two the
2102    /// convention would reach for leaves every expectation below unchanged.
2103    fn env() -> Env {
2104        const SCRATCH: [rucc_target::PhysReg; 2] = [x86_64::R10, x86_64::R11];
2105        let order: Vec<rucc_target::PhysReg> =
2106            SYSV.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
2107        Env::new().with(x86_64::GPR, &order, &SCRATCH)
2108    }
2109
2110    /// The machine IR text a function lowers to.
2111    fn lower(names: &mut Interner, source: &Func) -> String {
2112        let out = func(source, names, &SYSV).expect("every instruction has a rule");
2113        mir::print_func(&out.func, names, &REGS)
2114    }
2115
2116    #[test]
2117    fn an_addition_of_two_registers_is_one_instruction() {
2118        let i32 = Type::int(32);
2119        let (mut names, mut func, block, args) = blank(&[i32, i32]);
2120        let mut build = Builder::new(&mut func, block);
2121        build.binary(Opcode::Add, args[0], args[1], Flags::default());
2122
2123        assert_eq!(
2124            lower(&mut names, &func),
2125            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
2126             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr(reuse 1) = x64.add_rr_32 %0, %1\n}\n"
2127        );
2128    }
2129
2130    #[test]
2131    fn a_constant_operand_becomes_an_immediate() {
2132        let i32 = Type::int(32);
2133        let (mut names, mut func, block, args) = blank(&[i32]);
2134        let mut build = Builder::new(&mut func, block);
2135        let seven = build.iconst(i32, 7);
2136        build.binary(Opcode::Add, args[0], seven, Flags::default());
2137
2138        // The constant is in the instruction and nothing was written to hold it, which is what
2139        // materializing one where a register for it is wanted buys.
2140        assert_eq!(
2141            lower(&mut names, &func),
2142            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
2143             %1:gpr(reuse 1) = x64.add_ri_32 %0, 7\n}\n"
2144        );
2145    }
2146
2147    #[test]
2148    fn a_constant_too_wide_for_an_immediate_goes_into_a_register() {
2149        let i64 = Type::int(64);
2150        let (mut names, mut func, block, args) = blank(&[i64]);
2151        let mut build = Builder::new(&mut func, block);
2152        let big = build.iconst(i64, i128::from(i32::MAX) + 1);
2153        build.binary(Opcode::Add, args[0], big, Flags::default());
2154
2155        // Nobody wrote this fallback down. The rule that takes an immediate has a guard that
2156        // turns a number this wide down, so it does not fire, and the next way of showing the
2157        // operand puts it in a register.
2158        assert_eq!(
2159            lower(&mut names, &func),
2160            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
2161             %1:gpr = x64.mov_ri_64 2147483648\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n}\n"
2162        );
2163    }
2164
2165    #[test]
2166    fn an_index_calculation_folds_into_an_address() {
2167        let i64 = Type::int(64);
2168        let (mut names, mut func, block, args) = blank(&[i64, i64]);
2169        let mut build = Builder::new(&mut func, block);
2170        let four = build.iconst(i64, 4);
2171        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
2172        build.binary(Opcode::Add, args[0], scaled, Flags::default());
2173
2174        // Three IR instructions and one machine instruction. The multiply is gone because the
2175        // rule that matched reached down and took it.
2176        assert_eq!(
2177            lower(&mut names, &func),
2178            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
2179             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.lea_64 [%0 + %1*4]\n}\n"
2180        );
2181    }
2182
2183    #[test]
2184    fn an_instruction_read_twice_is_not_folded_into_either_reader() {
2185        let i64 = Type::int(64);
2186        let (mut names, mut func, block, args) = blank(&[i64, i64]);
2187        let mut build = Builder::new(&mut func, block);
2188        let four = build.iconst(i64, 4);
2189        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
2190        let first = build.binary(Opcode::Add, args[0], scaled, Flags::default());
2191        build.binary(Opcode::Add, first, scaled, Flags::default());
2192
2193        // Folding it into both would compute it twice, which is not a saving, so it stays where
2194        // it is and both readers read the register it wrote.
2195        let text = lower(&mut names, &func);
2196        assert!(text.contains("x64.lea_64 [%1*4]"), "{text}");
2197        assert_eq!(text.matches("x64.add_rr_64").count(), 2, "{text}");
2198    }
2199
2200    #[test]
2201    fn a_shift_by_a_register_asks_for_it_in_cl() {
2202        let i32 = Type::int(32);
2203        let (mut names, mut func, block, args) = blank(&[i32, i32]);
2204        let mut build = Builder::new(&mut func, block);
2205        build.binary(Opcode::Shl, args[0], args[1], Flags::default());
2206
2207        // The fixed register is not in the rule. It is what the target says the instruction does
2208        // with its operands, and the allocator is what will act on it.
2209        let text = lower(&mut names, &func);
2210        assert!(text.contains("x64.shl_rcl_32 %0, %1($rcx)"), "{text}");
2211    }
2212
2213    #[test]
2214    fn a_division_names_the_registers_and_the_register_it_destroys() {
2215        let i32 = Type::int(32);
2216        let (mut names, mut func, block, args) = blank(&[i32, i32]);
2217        let mut build = Builder::new(&mut func, block);
2218        build.binary(Opcode::SDiv, args[0], args[1], Flags::default());
2219
2220        // Two definitions, because a division writes the remainder whether anybody wanted it or
2221        // not, and the second one is early because it is destroyed before the operands are read.
2222        let text = lower(&mut names, &func);
2223        assert!(
2224            text.contains("%2:gpr($rax), early %3:gpr($rdx) = x64.idiv_quo_32 %0($rax), %1"),
2225            "{text}"
2226        );
2227    }
2228
2229    #[test]
2230    fn a_load_reads_through_the_register_the_address_is_in() {
2231        let i64 = Type::int(64);
2232        let (mut names, mut func, block, args) = blank(&[i64]);
2233        let mut build = Builder::new(&mut func, block);
2234        build.load(Type::int(32), args[0], plain(), Flags::default());
2235
2236        assert_eq!(
2237            lower(&mut names, &func),
2238            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
2239             %1:gpr = x64.mov_rm_32 [%0]\n}\n"
2240        );
2241    }
2242
2243    #[test]
2244    fn a_store_writes_no_register_and_the_value_it_writes_is_the_one_the_ir_gave_it() {
2245        let (mut names, mut func, block, args) = blank(&[Type::int(32), Type::int(64)]);
2246        let mut build = Builder::new(&mut func, block);
2247        build.store(args[0], args[1], plain(), Flags::default());
2248
2249        // The value is the first parameter and the address is the second, and the instruction
2250        // takes them the other way round. Getting that backwards would compile to a store of the
2251        // address into the value, which is a program that runs and does the wrong thing.
2252        assert_eq!(
2253            lower(&mut names, &func),
2254            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
2255             %1:gpr($rsi) = x64.arg_val_64\n    x64.mov_mr_32 %0, [%1]\n}\n"
2256        );
2257    }
2258
2259    #[test]
2260    fn an_address_with_a_constant_added_folds_into_the_access() {
2261        let i64 = Type::int(64);
2262        let (mut names, mut func, block, args) = blank(&[i64]);
2263        let mut build = Builder::new(&mut func, block);
2264        let twelve = build.iconst(i64, 12);
2265        let field = build.binary(Opcode::Add, args[0], twelve, Flags::default());
2266        build.load(Type::int(64), field, plain(), Flags::default());
2267
2268        // Two IR instructions and one machine instruction, which is what every read of a field
2269        // of a structure comes to.
2270        assert_eq!(
2271            lower(&mut names, &func),
2272            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
2273             %1:gpr = x64.mov_rm_64 [%0 + 12]\n}\n"
2274        );
2275    }
2276
2277    #[test]
2278    fn a_displacement_too_wide_to_encode_leaves_the_addition_where_it_is() {
2279        let i64 = Type::int(64);
2280        let (mut names, mut func, block, args) = blank(&[i64]);
2281        let mut build = Builder::new(&mut func, block);
2282        let big = build.iconst(i64, i128::from(i32::MAX) + 1);
2283        let far = build.binary(Opcode::Add, args[0], big, Flags::default());
2284        build.load(Type::int(32), far, plain(), Flags::default());
2285
2286        // A displacement is signed and 32 bits. The rule that folds one has a guard that turns
2287        // this down, so the addition stays and the load reads through what it produced. Nobody
2288        // wrote that fallback: it is the next way of showing the operand.
2289        let text = lower(&mut names, &func);
2290        assert!(text.contains("x64.mov_rm_32 [%2]"), "{text}");
2291        assert!(text.contains("x64.add_rr_64"), "{text}");
2292    }
2293
2294    #[test]
2295    fn a_store_of_a_value_that_was_loaded_is_two_instructions_and_no_arithmetic() {
2296        let i64 = Type::int(64);
2297        let (mut names, mut func, block, args) = blank(&[i64, i64]);
2298        let mut build = Builder::new(&mut func, block);
2299        let got = build.load(Type::int(8), args[0], plain(), Flags::default());
2300        build.store(got, args[1], plain(), Flags::default());
2301
2302        // A load feeding a store is the one place folding would be wrong: an x86-64 `mov` has at
2303        // most one memory operand, and there is no rule that takes two, so the load is left where
2304        // it is and the store reads the register it wrote.
2305        assert_eq!(
2306            lower(&mut names, &func),
2307            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
2308             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.mov_rm_8 [%0]\n    \
2309             x64.mov_mr_8 %2, [%1]\n}\n"
2310        );
2311    }
2312
2313    #[test]
2314    fn an_access_at_a_width_no_rule_is_written_at_is_reported() {
2315        let i64 = Type::int(64);
2316        let (mut names, mut source, block, args) = blank(&[i64]);
2317        let mut build = Builder::new(&mut source, block);
2318        build.load(Type::int(128), args[0], plain(), Flags::default());
2319
2320        // The width is the whole of what is wrong here, so the width is in the message: `load`
2321        // on its own is written about at every other width and would send a reader looking in
2322        // the wrong place.
2323        let failed = func(&source, &mut names, &SYSV).expect_err("nothing loads 128 bits");
2324        assert_eq!(failed.to_string(), "no rule lowers a `load` producing a `i128`");
2325    }
2326
2327    #[test]
2328    fn a_return_asks_for_the_value_in_the_register_the_caller_reads() {
2329        let (mut names, mut func, block, args) = blank(&[Type::int(32)]);
2330        let mut build = Builder::new(&mut func, block);
2331        build.ret(&[args[0]]);
2332
2333        // The register is not in the rule, the same way `cl` is not in the rule for a shift. It
2334        // is what the target says the instruction does with its operand, and the allocator is
2335        // what will act on it. There is no `ret` here, because giving the frame back has to
2336        // happen between this and leaving and the frame is not worked out yet.
2337        assert_eq!(
2338            lower(&mut names, &func),
2339            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
2340             x64.ret_val_32 %0($rax)\n}\n"
2341        );
2342    }
2343
2344    #[test]
2345    fn a_return_of_two_values_asks_for_the_second_register_as_well() {
2346        let i64 = Type::int(64);
2347        let (mut names, mut func, block, args) = blank(&[i64, i64]);
2348        let mut build = Builder::new(&mut func, block);
2349        build.ret(&[args[0], args[1]]);
2350
2351        // `struct { long a, b; } f(long a, long b)`, after the front end has classified it. Both
2352        // halves are integers, so the second is in the second integer return register, and both
2353        // pseudos say so the same way the one for a single value does.
2354        assert_eq!(
2355            lower(&mut names, &func),
2356            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
2357             %1:gpr($rsi) = x64.arg_val_64\n    x64.ret_val_64 %0($rax)\n    \
2358             x64.ret_val2_64 %1($rdx)\n}\n"
2359        );
2360    }
2361
2362    #[test]
2363    fn two_values_back_in_different_files_are_both_the_first_of_their_own() {
2364        let f64 = Type::float(rucc_ir::Float::F64);
2365        let (mut names, mut func, block, args) = blank(&[f64, Type::int(64)]);
2366        let mut build = Builder::new(&mut func, block);
2367        build.ret(&[args[0], args[1]]);
2368
2369        // `struct { double a; long b; } f(double a, long b)`. The two files are counted apart, so
2370        // neither half is the second of anything and the `double` is in `xmm0` rather than in the
2371        // register a second `double` would have been in. Getting this wrong is not a crash: the
2372        // caller reads a register nobody wrote, and this is where that is ruled out.
2373        assert_eq!(
2374            lower(&mut names, &func),
2375            "mfunc @f {\nblock0:\n    %0:xmm($xmm0) = x64.arg_val_f64\n    \
2376             %1:gpr($rdi) = x64.arg_val_64\n    x64.ret_val_f64 %0($xmm0)\n    \
2377             x64.ret_val_64 %1($rax)\n}\n"
2378        );
2379    }
2380
2381    #[test]
2382    fn two_of_the_same_file_back_take_the_first_two_of_it() {
2383        let f64 = Type::float(rucc_ir::Float::F64);
2384        let (mut names, mut func, block, args) = blank(&[f64, f64]);
2385        let mut build = Builder::new(&mut func, block);
2386        build.ret(&[args[0], args[1]]);
2387
2388        // `struct { double x, y; } f(double x, double y)`, which is the vector half of the pair
2389        // above and counts in its own file the same way.
2390        assert_eq!(
2391            lower(&mut names, &func),
2392            "mfunc @f {\nblock0:\n    %0:xmm($xmm0) = x64.arg_val_f64\n    \
2393             %1:xmm($xmm1) = x64.arg_val_f64\n    x64.ret_val_f64 %0($xmm0)\n    \
2394             x64.ret_val2_f64 %1($xmm1)\n}\n"
2395        );
2396    }
2397
2398    /// A function whose answer goes back through memory, with the pointer to the space for it in
2399    /// front of whatever else it takes. Only the signature says it is one.
2400    fn returning_through_memory(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
2401        let mut names = Interner::new();
2402        let sret = Abi::Sret { size: 32, align: 8 };
2403        let mut signature = Signature::new().and_param(Param::with_abi(Type::PTR, sret));
2404        signature.params.extend(params.iter().copied().map(Param::new));
2405        let mut func = Func::new(names.intern("f"), signature);
2406        let block = func.create_block();
2407        let space = func.append_param(block, Type::PTR);
2408        let values = std::iter::once(space)
2409            .chain(params.iter().map(|&ty| func.append_param(block, ty)))
2410            .collect();
2411        (names, func, block, values)
2412    }
2413
2414    #[test]
2415    fn the_space_a_return_through_memory_was_given_goes_back_in_the_first_return_register() {
2416        let (mut names, mut func, block, _) = returning_through_memory(&[]);
2417        Builder::new(&mut func, block).ret(&[]);
2418
2419        // `struct big f(void)`, where `big` is too large to come back in registers. The `return`
2420        // carries nothing, because the value went into the space the caller handed over, and the
2421        // document still says that address comes back in `rax`. Nothing in the IR says it, so the
2422        // convention says it, and the pseudo is the one any other pointer return would use.
2423        assert_eq!(
2424            lower(&mut names, &func),
2425            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
2426             x64.ret_val_64 %0($rax)\n}\n"
2427        );
2428    }
2429
2430    #[test]
2431    fn what_the_function_did_in_between_does_not_take_the_register_off_it() {
2432        let (mut names, mut func, block, args) = returning_through_memory(&[Type::int(32)]);
2433        let mut build = Builder::new(&mut func, block);
2434        build.store(args[1], args[0], plain(), Flags::default());
2435        build.ret(&[]);
2436
2437        // The register is a read at the end and not a move at the start, so it is live across
2438        // everything between the two and the allocator has to keep it somewhere. In a function
2439        // with a call in it that somewhere is a callee saved register, and the address comes back
2440        // into `rax` here rather than whatever the last instruction happened to leave there. That
2441        // is issue #333, and a store is enough to show the value outlives the entry block.
2442        let text = lower(&mut names, &func);
2443        assert!(text.contains("x64.mov_mr_32 %1, [%0]"), "{text}");
2444        assert!(text.ends_with("    x64.ret_val_64 %0($rax)\n}\n"), "{text}");
2445    }
2446
2447    #[test]
2448    fn a_pointer_that_is_only_a_pointer_is_not_given_back() {
2449        let (mut names, mut func, block, args) = blank(&[Type::PTR]);
2450        let mut build = Builder::new(&mut func, block);
2451        build.store(args[0], args[0], plain(), Flags::default());
2452        build.ret(&[]);
2453
2454        // `void f(void **p)`. It takes a pointer first and returns nothing, which is the shape of
2455        // the one above and none of its meaning, and what tells them apart is the signature. A
2456        // `void` function leaves `rax` alone.
2457        assert!(!lower(&mut names, &func).contains("ret_val"));
2458    }
2459
2460    #[test]
2461    fn a_return_of_a_constant_puts_it_in_a_register_first() {
2462        let (mut names, mut func, block, _) = blank(&[]);
2463        let mut build = Builder::new(&mut func, block);
2464        let zero = build.iconst(Type::int(32), 0);
2465        build.ret(&[zero]);
2466
2467        // No rule returns an immediate, so the plan that offers one is turned down and the next
2468        // one materializes it. That is `int main(void) { return 0; }` in full, once the epilogue
2469        // is appended to it.
2470        assert_eq!(
2471            lower(&mut names, &func),
2472            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 0\n    x64.ret_val_32 %0($rax)\n}\n"
2473        );
2474    }
2475
2476    #[test]
2477    fn the_rule_that_writes_a_constant_down_is_recorded_as_a_rule_that_fired() {
2478        let (mut names, mut func, block, _) = blank(&[]);
2479        let mut build = Builder::new(&mut func, block);
2480        let zero = build.iconst(Type::int(32), 0);
2481        build.ret(&[zero]);
2482
2483        // The loop over the instructions passes a constant by, because a constant is written where
2484        // a register for it is first wanted rather than where the IR put it. So the only place a
2485        // rule about one is ever selected is the materialization, and a mark made in the loop
2486        // alone would report every rule about a constant as a rule nothing reaches.
2487        let out = super::func(&func, &mut names, &SYSV).expect("every instruction has a rule");
2488        let rules = &crate::select::x86_64::TABLE.rules;
2489        let fired: Vec<&str> = rules
2490            .iter()
2491            .enumerate()
2492            .filter(|(index, _)| out.fired.has(*index))
2493            .map(|(_, rule)| rule.pattern)
2494            .collect();
2495        assert!(fired.contains(&"(iconst.i32 k)"), "{fired:?}");
2496    }
2497
2498    #[test]
2499    fn a_return_of_nothing_is_no_instruction_at_all() {
2500        let (mut names, mut func, block, _) = blank(&[]);
2501        let mut build = Builder::new(&mut func, block);
2502        build.ret(&[]);
2503
2504        // Every part of leaving a function that returns nothing is the epilogue's, and the
2505        // epilogue goes in after allocation. A block with nothing in it is the right answer here
2506        // rather than a function that could not be lowered.
2507        assert_eq!(lower(&mut names, &func), "mfunc @f {\nblock0:\n}\n");
2508    }
2509
2510    #[test]
2511    fn the_allocator_is_what_moves_the_answer_into_the_return_register() {
2512        let (mut names, mut source, block, _) = blank(&[]);
2513        let mut build = Builder::new(&mut source, block);
2514        let zero = build.iconst(Type::int(32), 0);
2515        build.ret(&[zero]);
2516
2517        let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
2518        let env = env();
2519        let allocation = rucc_regalloc::run(&mut out, &env);
2520        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
2521        finish(&mut out, &allocation, &frame, &Stack::default(), &SYSV, &FRAME, &mut names);
2522
2523        // `int main(void) { return 0; }` end to end. Nothing here asked for `rax`: the rule said
2524        // the value goes back, the target said where, and the allocator is what made it true. The
2525        // epilogue is what leaves, and this function needs no frame, so it is the return alone.
2526        //
2527        // Two instructions and no copy, which is what a hint buys. The return insists on `rax`,
2528        // so `rax` is the register the allocator tries first for the value the return reads, and
2529        // the constant is written straight into it.
2530        assert_eq!(
2531            mir::print_func(&out, &names, &REGS),
2532            "mfunc @f {\nblock0:\n    $rax = x64.mov_ri_32 0\n    \
2533             x64.ret_val_32 $rax($rax)\n    x64.ret\n}\n"
2534        );
2535    }
2536
2537    #[test]
2538    fn a_function_of_two_arguments_is_a_whole_function_now() {
2539        let i32 = Type::int(32);
2540        let (mut names, mut source, block, args) = blank(&[i32, i32]);
2541        let mut build = Builder::new(&mut source, block);
2542        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
2543        build.ret(&[sum]);
2544
2545        let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
2546        let env = env();
2547        let allocation = rucc_regalloc::run(&mut out, &env);
2548        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
2549        finish(&mut out, &allocation, &frame, &Stack::default(), &SYSV, &FRAME, &mut names);
2550
2551        // `int f(int a, int b) { return a + b; }` end to end, and this is the test the argument
2552        // side exists for. Before it there was no way to write one: the allocator refuses a
2553        // function whose entry block takes parameters, because there is no edge into an entry
2554        // block for the moves that give a block parameter its value to go on.
2555        //
2556        // One move, and it is the one the machine's addition needs rather than one the allocator
2557        // owes anybody. Each argument stays in the register it arrived in, because the pseudo
2558        // that defines it insists on that register and the allocator now tries it first, and the
2559        // sum stays in the register the addition wrote it to until the return reads it out. The
2560        // copy in front of a two address instruction is what makes its destination one of the
2561        // registers it reads, and the source operand keeps its own name because the destination
2562        // is what the encoder writes.
2563        assert_eq!(
2564            mir::print_func(&out, &names, &REGS),
2565            "mfunc @f {\nblock0:\n    $rdi($rdi) = x64.arg_val_32\n    \
2566             $rsi($rsi) = x64.arg_val_32\n    \
2567             $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n    $rax = x64.mov_rr_64 $rdi\n    \
2568             x64.ret_val_32 $rax($rax)\n    x64.ret\n}\n"
2569        );
2570    }
2571
2572    #[test]
2573    fn an_argument_with_no_register_left_for_it_is_read_out_of_the_caller_s_stack() {
2574        let i64 = Type::int(64);
2575        let (mut names, mut source, block, args) = blank(&[i64; 7]);
2576        let mut build = Builder::new(&mut source, block);
2577        build.ret(&[args[6]]);
2578
2579        let lowered = func(&source, &mut names, &SYSV).expect("the seventh is read from memory");
2580
2581        // SysV passes six integers in registers and the seventh in the caller's memory, so six of
2582        // these are pseudos that encode to nothing and the seventh is a load that encodes to real
2583        // bytes. Its displacement is nothing here for the reason a local's is: there is no frame
2584        // yet. What the walk hands on is which instruction is waiting, and for how far up the
2585        // caller's argument area, which is the bottom of it because it is the first one there.
2586        assert_eq!(lowered.stack.arguments.len(), 1);
2587        assert_eq!(lowered.stack.arguments[0].1, 0);
2588        let text = mir::print_func(&lowered.func, &names, &REGS);
2589        assert!(text.contains("%6:gpr = x64.mov_rm_64 [$rsp]"), "{text}");
2590        assert_eq!(text.matches("x64.arg_val_64").count(), 6, "{text}");
2591    }
2592
2593    #[test]
2594    fn the_frame_is_what_says_how_far_up_the_caller_s_stack_an_argument_is() {
2595        let i64 = Type::int(64);
2596        let (mut names, mut source, block, args) = blank(&[i64; 8]);
2597        let mut build = Builder::new(&mut source, block);
2598        let sum = build.binary(Opcode::Add, args[6], args[7], Flags::default());
2599        build.ret(&[sum]);
2600
2601        let lowered = func(&source, &mut names, &SYSV).expect("both are read from memory");
2602        let stack = lowered.stack;
2603        let mut out = lowered.func;
2604        let env = env();
2605        let allocation = rucc_regalloc::run(&mut out, &env);
2606        let layout = stack.layout(Layout::new(&SYSV, REGS));
2607        let frame = Frame::of(&out, &allocation, &layout);
2608        finish(&mut out, &allocation, &frame, &stack, &SYSV, &FRAME, &mut names);
2609
2610        // A leaf that takes no frame, so the stack pointer never moves and the only thing between
2611        // it and the caller's arguments is the return address the call pushed. The seventh
2612        // parameter is at the bottom of the caller's argument area and the eighth is one word
2613        // further up, which is the eight bytes between the two offsets.
2614        let text = mir::print_func(&out, &names, &REGS);
2615        assert_eq!(frame.size(), 0);
2616        assert_eq!(frame.incoming(), Incoming::from_stack(8));
2617        assert!(text.contains("x64.mov_rm_64 [$rsp + 8]"), "{text}");
2618        assert!(text.contains("x64.mov_rm_64 [$rsp + 16]"), "{text}");
2619    }
2620
2621    #[test]
2622    fn a_realigned_frame_reaches_the_caller_s_arguments_through_the_frame_pointer() {
2623        let i64 = Type::int(64);
2624        let (mut names, mut source, block, args) = blank(&[i64; 7]);
2625        let wide = slot(&mut source, block, 64, 32);
2626        let mut build = Builder::new(&mut source, block);
2627        build.store(args[6], wide, plain(), Flags::default());
2628        build.ret(&[args[6]]);
2629
2630        let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
2631        let stack = lowered.stack;
2632        let mut out = lowered.func;
2633        let env = env();
2634        let allocation = rucc_regalloc::run(&mut out, &env);
2635        let layout = stack.layout(Layout::new(&SYSV, REGS));
2636        let frame = Frame::of(&out, &allocation, &layout);
2637        finish(&mut out, &allocation, &frame, &stack, &SYSV, &FRAME, &mut names);
2638
2639        // A local wanting thirty two byte alignment makes the prologue force the stack pointer,
2640        // which throws away how far the caller's stack was. So the load the lowering wrote off the
2641        // stack pointer is rewritten to read through the frame pointer, at the one distance that
2642        // survives: the word the prologue pushed the frame pointer into, and the return address
2643        // above it.
2644        let text = mir::print_func(&out, &names, &REGS);
2645        assert_eq!(frame.realign(), Some(32));
2646        assert_eq!(frame.incoming(), Incoming::from_frame(16));
2647        assert!(text.contains("x64.mov_rm_64 [$rbp + 16]"), "{text}");
2648        assert!(!text.contains("x64.mov_rm_64 [$rsp"), "{text}");
2649    }
2650
2651    #[test]
2652    fn a_jump_is_the_edge_and_nothing_else() {
2653        let i32 = Type::int(32);
2654        let (mut names, mut source, entry, args) = blank(&[i32]);
2655        let next = source.create_block();
2656        let got = source.append_param(next, i32);
2657        Builder::new(&mut source, entry).jump(next, &[args[0]]);
2658        Builder::new(&mut source, next).ret(&[got]);
2659
2660        // Two blocks and two instructions, and the jump is neither of them. What it was is the
2661        // arm on the first block, and what the arm carries is the argument it was called with.
2662        assert_eq!(
2663            lower(&mut names, &source),
2664            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32 block1(%0)\n\n\
2665             block1(%1:gpr):\n    x64.ret_val_32 %1($rax)\n}\n"
2666        );
2667    }
2668
2669    /// A constant is written where it is wanted rather than where the IR defined it, and two
2670    /// blocks wanting the same one is two places. Writing it once and reading it in both is a
2671    /// register read where nothing wrote it, unless the block it was written in happens to
2672    /// dominate the other, which nothing here checks and which the second arm of a branch never
2673    /// does. Each block gets its own copy of the number instead.
2674    #[test]
2675    fn a_constant_two_blocks_want_is_written_in_both_of_them() {
2676        let i32 = Type::int(32);
2677        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
2678        let then = source.create_block();
2679        let other = source.create_block();
2680        let join = source.create_block();
2681        let got = source.append_param(join, i32);
2682
2683        let mut build = Builder::new(&mut source, entry);
2684        let seven = build.iconst(i32, 7);
2685        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
2686        build.br_if(cond, then, &[], other, &[]);
2687        // Both arms want the seven in a register, because a block argument is never an immediate,
2688        // and neither arm dominates the other.
2689        Builder::new(&mut source, then).jump(join, &[seven]);
2690        Builder::new(&mut source, other).jump(join, &[seven]);
2691        Builder::new(&mut source, join).ret(&[got]);
2692
2693        let text = lower(&mut names, &source);
2694        assert_eq!(text.matches("x64.mov_ri_32 7").count(), 2, "one seven per block: {text}");
2695    }
2696
2697    /// An argument on an edge out of a block that leaves two ways is read after every instruction
2698    /// of the block is written, and reading one can write an instruction, which would land after
2699    /// the branch that has already jumped past it. The branch goes back on the end.
2700    #[test]
2701    fn a_constant_an_edge_wants_is_written_before_the_branch_and_not_after_it() {
2702        let i32 = Type::int(32);
2703        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
2704        let then = source.create_block();
2705        let join = source.create_block();
2706        let got = source.append_param(join, i32);
2707
2708        let mut build = Builder::new(&mut source, entry);
2709        let nine = build.iconst(i32, 9);
2710        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
2711        build.br_if(cond, then, &[], join, &[nine]);
2712        Builder::new(&mut source, then).jump(join, &[args[0]]);
2713        Builder::new(&mut source, join).ret(&[got]);
2714
2715        let out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
2716        let entry = out.entry().expect("an entry block");
2717        let last = out.terminator(entry).expect("a block that leaves two ways has a branch");
2718        let branch = names.intern("x64.br_cond_8");
2719        assert_eq!(
2720            out[last].opcode,
2721            mir::Opcode::new(branch),
2722            "the branch is last: {}",
2723            mir::print_func(&out, &names, &REGS)
2724        );
2725    }
2726
2727    #[test]
2728    fn a_conditional_branch_is_lowered_to_the_condition_and_nothing_about_where_it_goes() {
2729        let i32 = Type::int(32);
2730        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
2731        let then = source.create_block();
2732        let other = source.create_block();
2733        let mut build = Builder::new(&mut source, entry);
2734        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
2735        build.br_if(cond, then, &[], other, &[]);
2736        Builder::new(&mut source, then).ret(&[args[0]]);
2737        Builder::new(&mut source, other).ret(&[args[1]]);
2738
2739        // The comparison writes a byte and the branch reads it, and neither says a block. Both
2740        // arms are on the entry block, in the order the branch took them, so the arm that runs
2741        // when the condition holds is the first.
2742        assert_eq!(
2743            lower(&mut names, &source),
2744            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
2745             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr = x64.cmp_set_l_32 %0, %1\n    \
2746             x64.br_cond_8 %2, block1, block2\n\n\
2747             block1:\n    x64.ret_val_32 %0($rax)\n\n\
2748             block2:\n    x64.ret_val_32 %1($rax)\n}\n"
2749        );
2750    }
2751
2752    /// A choice between two values, which is one instruction and no blocks at all.
2753    ///
2754    /// The arms come out the other way round from the IR, because a conditional move overwrites its
2755    /// destination and the destination is the arm taken when the condition does not hold. The
2756    /// condition arrives last for the same reason: it is read by the test in front of the move
2757    /// rather than by the move.
2758    #[test]
2759    fn a_select_is_lowered_to_a_test_and_a_conditional_move() {
2760        let i32 = Type::int(32);
2761        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
2762        let mut build = Builder::new(&mut source, entry);
2763        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
2764        let picked = build.select(cond, args[0], args[1]);
2765        build.ret(&[picked]);
2766
2767        assert_eq!(
2768            lower(&mut names, &source),
2769            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
2770             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr = x64.cmp_set_l_32 %0, %1\n    \
2771             %3:gpr(reuse 1) = x64.test_cmov_ne_32 %1, %0, %2\n    \
2772             x64.ret_val_32 %3($rax)\n}\n"
2773        );
2774    }
2775
2776    #[test]
2777    fn a_branch_over_a_block_is_a_whole_function_now() {
2778        let i32 = Type::int(32);
2779        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
2780        let then = source.create_block();
2781        let other = source.create_block();
2782        let join = source.create_block();
2783        let got = source.append_param(join, i32);
2784        let mut build = Builder::new(&mut source, entry);
2785        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
2786        build.br_if(cond, then, &[], other, &[]);
2787        let mut build = Builder::new(&mut source, then);
2788        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
2789        build.jump(join, &[sum]);
2790        Builder::new(&mut source, other).jump(join, &[args[1]]);
2791        Builder::new(&mut source, join).ret(&[got]);
2792
2793        // `int f(int a, int b) { if (a < b) return a + b; else return b; }` end to end, written
2794        // the way a front end writes it: both arms of the branch are blocks of their own and the
2795        // return is the block they meet at. No edge here is critical, because the two arms out of
2796        // the entry carry nothing and the two arms into the join each leave a block that goes
2797        // nowhere else, so each has its own end to put its move at.
2798        let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
2799        assert_eq!(crate::split::critical(&mut out), 0, "no edge here is critical");
2800        let env = env();
2801        let allocation = rucc_regalloc::run(&mut out, &env);
2802        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
2803        finish(&mut out, &allocation, &frame, &Stack::default(), &SYSV, &FRAME, &mut names);
2804
2805        // One epilogue, on the join, which is the one block the function leaves from, and the
2806        // moves that give the join its parameter are at the end of each arm. Every register is
2807        // physical and the branch is still a branch on a register, because turning it into a
2808        // `test` and a `jcc` is the block layout's and there is no block layout yet.
2809        let text = mir::print_func(&out, &names, &REGS);
2810        assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
2811        assert!(text.contains("x64.br_cond_8"), "{text}");
2812        assert!(text.contains("x64.add_rr_32"), "{text}");
2813        assert!(!text.contains('%'), "{text}");
2814    }
2815
2816    #[test]
2817    fn a_critical_edge_is_split_before_the_allocator_ever_sees_it() {
2818        let i32 = Type::int(32);
2819        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
2820        let then = source.create_block();
2821        let join = source.create_block();
2822        let got = source.append_param(join, i32);
2823        let mut build = Builder::new(&mut source, entry);
2824        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
2825        build.br_if(cond, then, &[], join, &[args[1]]);
2826        Builder::new(&mut source, then).jump(join, &[args[0]]);
2827        let mut build = Builder::new(&mut source, join);
2828        let twice = build.binary(Opcode::Add, got, got, Flags::default());
2829        build.ret(&[twice]);
2830
2831        // The else arm is critical: the entry block leaves two ways and the join is arrived at
2832        // two ways, and the arm carries a value. Without splitting it the allocator asserts,
2833        // because the move that gives the join its parameter would have to run at the end of a
2834        // block that also goes to the other arm.
2835        let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
2836        assert_eq!(crate::split::critical(&mut out), 1);
2837        let env = env();
2838        let allocation = rucc_regalloc::run(&mut out, &env);
2839        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
2840        finish(&mut out, &allocation, &frame, &Stack::default(), &SYSV, &FRAME, &mut names);
2841
2842        // The block the split added is where the move went, and it is the whole of that block.
2843        let text = mir::print_func(&out, &names, &REGS);
2844        assert_eq!(out.block_count(), 4, "{text}");
2845        assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
2846    }
2847
2848    #[test]
2849    fn a_call_passes_what_the_convention_says_and_takes_back_what_it_says() {
2850        let i32 = Type::int(32);
2851        let (mut names, mut source, block, args) = blank(&[i32, i32]);
2852        let sig =
2853            source.add_signature(Signature::new().with_params(&[i32, i32]).with_returns(&[i32]));
2854        let callee = names.intern("g");
2855        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0], args[1]]);
2856        let got = source[call].first_result.expect("an integer comes back");
2857        Builder::new(&mut source, block).ret(&[got]);
2858
2859        // `int f(int a, int b) { return g(a, b); }`. The arguments arrived where the call wants
2860        // them, so what the call reads is what arrived, and the whole of the convention is in the
2861        // constraints rather than in a move.
2862        let text = lower(&mut names, &source);
2863        assert!(text.contains("= x64.call %0($rdi), %1($rsi), @g"), "{text}");
2864        assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
2865        // What the call writes is the value that comes back and then every register the callee is
2866        // free to destroy, in both classes, which is the whole of what stops the allocator from
2867        // leaving something in one of them.
2868        assert!(text.contains("%2:gpr($rax), $rcx, $rdx, $r8, $r9, $r10, $r11, $xmm0,"), "{text}");
2869        assert!(text.contains("$xmm15 = x64.call"), "{text}");
2870    }
2871
2872    #[test]
2873    fn what_the_frame_owes_a_call_comes_back_with_the_function() {
2874        let i32 = Type::int(32);
2875        let sig = |source: &mut Func| source.add_signature(Signature::new().with_params(&[i32]));
2876
2877        let (mut names, mut source, block, args) = blank(&[i32]);
2878        let sig = sig(&mut source);
2879        let callee = names.intern("g");
2880        Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
2881        let out = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
2882
2883        // Nothing on the stack, so nothing owed, but not a leaf either: a function that calls
2884        // owes the callee an aligned stack pointer and may not use the red zone.
2885        assert_eq!(out.stack.calls, Some(0));
2886        let layout = out.stack.layout(Layout::new(&SYSV, REGS));
2887        assert!(!layout.leaf);
2888        assert_eq!(layout.outgoing, 0);
2889
2890        // The same call under the other convention owes thirty two bytes for the callee to spill
2891        // its register arguments into, which is a fact about the convention and not about the call.
2892        let out = func(&source, &mut names, &x86_64::WIN64).expect("every instruction has a rule");
2893        assert_eq!(out.stack.calls, Some(32));
2894
2895        // And a function that calls nothing is a leaf, which is what says it may use the red zone.
2896        let (mut names, mut source, block, args) = blank(&[i32]);
2897        Builder::new(&mut source, block).ret(&[args[0]]);
2898        let out = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
2899        assert_eq!(out.stack.calls, None);
2900        assert!(out.stack.layout(Layout::new(&SYSV, REGS)).leaf);
2901    }
2902
2903    #[test]
2904    fn a_value_that_outlives_a_call_is_not_left_where_the_call_destroys_it() {
2905        let i32 = Type::int(32);
2906        let (mut names, mut source, block, args) = blank(&[i32]);
2907        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
2908        let callee = names.intern("g");
2909        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
2910        let got = source[call].first_result.expect("an integer comes back");
2911        let mut build = Builder::new(&mut source, block);
2912        let sum = build.binary(Opcode::Add, got, args[0], Flags::default());
2913        build.ret(&[sum]);
2914
2915        // `int f(int a) { return g(a) + a; }`, which is the smallest program that asks the
2916        // question: `a` is read after the call and `rdi` is a register the call destroys.
2917        let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
2918        let layout = lowered.stack.layout(Layout::new(&SYSV, REGS));
2919        let mut out = lowered.func;
2920        let env = env();
2921        let allocation = rucc_regalloc::run(&mut out, &env);
2922        let frame = Frame::of(&out, &allocation, &layout);
2923        finish(&mut out, &allocation, &frame, &Stack::default(), &SYSV, &FRAME, &mut names);
2924
2925        // It went to a register the callee has to put back, and the prologue and epilogue are what
2926        // put it back, which is the whole bargain the two halves of a convention make.
2927        let text = mir::print_func(&out, &names, &REGS);
2928        assert!(text.contains("$rbx"), "{text}");
2929        assert!(!text.contains('%'), "{text}");
2930        assert_eq!(text.matches("x64.call").count(), 1, "{text}");
2931    }
2932
2933    #[test]
2934    fn a_call_with_more_arguments_than_registers_writes_the_rest_into_the_outgoing_area() {
2935        let i64 = Type::int(64);
2936        let (mut names, mut source, block, args) = blank(&[i64]);
2937        let seven = vec![i64; 7];
2938        let sig = source.add_signature(Signature::new().with_params(&seven));
2939        let callee = names.intern("g");
2940        let passed = vec![args[0]; 7];
2941        Builder::new(&mut source, block).call(callee, sig, &passed);
2942
2943        let lowered = func(&source, &mut names, &SYSV).expect("the seventh goes to memory");
2944        // The bytes the call needs are on the layout the frame is worked out from, so that the
2945        // frame reserves as many as the widest call in the function asked for.
2946        assert_eq!(lowered.stack.calls, Some(8));
2947        let text = mir::print_func(&lowered.func, &names, &REGS);
2948        assert!(text.contains("x64.mov_mr_64 %0, [$rsp]\n"), "{text}");
2949    }
2950
2951    #[test]
2952    fn a_call_this_cannot_make_is_reported_rather_than_made() {
2953        let (mut names, mut source, block, _) = blank(&[]);
2954        let returns = [Type::float(rucc_ir::Float::F80), Type::int(64)];
2955        let sig = source.add_signature(Signature::new().with_returns(&returns));
2956        let callee = names.intern("g");
2957        Builder::new(&mut source, block).call(callee, sig, &[]);
2958        let failed = func(&source, &mut names, &SYSV).expect_err("a long double is on the x87");
2959        assert_eq!(failed.to_string(), "what this call gives back is on the x87 stack");
2960    }
2961
2962    /// A `long double` on its own is a different answer, because on its own it comes back on the
2963    /// x87 stack rather than in a register, which is somewhere the call cannot be said to write.
2964    ///
2965    /// So the call gives back nothing at all and the value is taken off the stack by the `fstp`
2966    /// straight after it. That instruction has to be straight after it: the stack is one place and
2967    /// anything else that touched it before this ran would be looking at the value still on it.
2968    #[test]
2969    fn a_call_that_gives_back_a_long_double_takes_it_off_the_stack_at_once() {
2970        let (mut names, mut source, block, _) = blank(&[]);
2971        let long_double = Type::float(rucc_ir::Float::F80);
2972        let sig = source.add_signature(Signature::new().with_returns(&[long_double]));
2973        let callee = names.intern("g");
2974        Builder::new(&mut source, block).call(callee, sig, &[]);
2975
2976        let lowered = func(&source, &mut names, &SYSV).expect("the value comes back in st0");
2977        let text = mir::print_func(&lowered.func, &names, &REGS);
2978        let after: Vec<&str> =
2979            text.lines().skip_while(|line| !line.contains("x64.call")).skip(1).collect();
2980        assert_eq!(after[0].trim(), "%0:gpr = x64.lea_64 [$rsp]", "{text}");
2981        assert_eq!(after[1].trim(), "x64.fstp_t [%0]", "{text}");
2982        // And the slot it went into is the sixteen bytes the type takes, like every other one.
2983        assert_eq!(lowered.stack.locals.len(), 1, "{text}");
2984        assert_eq!(lowered.stack.locals[0].size, X87_BYTES);
2985    }
2986
2987    #[test]
2988    fn a_call_through_an_address_goes_through_the_register_the_address_is_in() {
2989        let i32 = Type::int(32);
2990        let (mut names, mut source, block, args) = blank(&[Type::PTR, i32]);
2991        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
2992        let varargs = source.push_abis(&[]);
2993        let info = source.add_call(CallInfo { callee: None, signature: sig, varargs });
2994        let mut build = Builder::new(&mut source, block);
2995        let inst = InstData {
2996            args: build.func().push_values(&[args[0], args[1]]),
2997            extra: Extra::Call(info),
2998            ..InstData::new(Opcode::CallIndirect)
2999        };
3000        let called = build.inst(inst, &[i32]);
3001        let got = source[called].first_result.expect("an integer comes back");
3002        Builder::new(&mut source, block).ret(&[got]);
3003
3004        // `int f(int (*g)(int), int a) { return g(a); }`. The first operand is the address and
3005        // the arguments are the ones behind it, and everything else about the call is what a call
3006        // to a name would have been.
3007        let text = lower(&mut names, &source);
3008        assert!(text.contains("= x64.call_reg %0, %1($rdi)"), "{text}");
3009        assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
3010        assert!(!text.contains("@g"), "a call through an address names nobody: {text}");
3011    }
3012
3013    #[test]
3014    fn an_instruction_no_rule_covers_is_reported() {
3015        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
3016        let mut build = Builder::new(&mut source, block);
3017        let operands = build.func().push_values(&[args[0]]);
3018        build.inst(InstData { args: operands, ..InstData::new(Opcode::Prefetch) }, &[]);
3019
3020        // A hint about an address, which nothing writes an instruction for yet. Nothing about it
3021        // is a width or a register, so there is nothing for the message to add beyond the name.
3022        let failed = func(&source, &mut names, &SYSV).expect_err("no rule writes a prefetch");
3023        assert_eq!(failed.to_string(), "no rule lowers a `prefetch`");
3024
3025        // A `prefetch` produces nothing, so there is no type in the message and nothing invents
3026        // one, and the instruction comes back so a caller can ask the function where it was.
3027        let inst = failed.inst().expect("the instruction it is about");
3028        assert_eq!(source[inst].opcode, Opcode::Prefetch);
3029    }
3030
3031    /// A barrier is written by name here, and what it is depends on the ordering and on nothing
3032    /// else. `crate::expand` is where the reasoning about this machine's memory model lives.
3033    #[test]
3034    fn a_barrier_is_one_instruction_at_the_strongest_ordering_and_none_below_it() {
3035        for order in MemOrder::all().filter(|&order| order != MemOrder::NotAtomic) {
3036            let (mut names, mut source, block, _) = blank(&[]);
3037            let mut build = Builder::new(&mut source, block);
3038            build
3039                .inst(InstData { extra: Extra::Order(order), ..InstData::new(Opcode::Fence) }, &[]);
3040
3041            let text = lower(&mut names, &source);
3042            assert_eq!(text.contains("x64.mfence"), order == MemOrder::SeqCst, "{order:?}: {text}");
3043        }
3044    }
3045
3046    #[test]
3047    fn more_values_back_than_the_convention_has_registers_for_is_reported() {
3048        let i64 = Type::int(64);
3049        let (mut names, mut source, block, args) = blank(&[i64, i64, i64]);
3050        let mut build = Builder::new(&mut source, block);
3051        build.ret(&[args[0], args[1], args[2]]);
3052
3053        // Two integers come back in `rax` and `rdx` and a third has nowhere to go, which is not a
3054        // gap in the rules but the convention saying no. The front end classifies before it gets
3055        // here, so this is the shape that would mean the classification went wrong.
3056        let failed = func(&source, &mut names, &SYSV).expect_err("only two come back");
3057        assert_eq!(
3058            failed.to_string(),
3059            "what this function gives back takes more registers than this convention has for it"
3060        );
3061
3062        let inst = failed.inst().expect("the instruction it is about");
3063        assert_eq!(source[inst].opcode, Opcode::Return);
3064    }
3065
3066    /// A refusal about a signature has no instruction, which is what makes it the one arm apart.
3067    ///
3068    /// Everything else is about something written somewhere in the body and hands it back so a
3069    /// caller can ask the function where it came from. A parameter arrives before the first
3070    /// instruction runs, so there is nothing in the body to point at and the message is about
3071    /// the function.
3072    #[test]
3073    fn a_refusal_about_a_parameter_has_no_instruction_to_point_at() {
3074        let missing = Unsupported::Argument { index: 0, missing: Missing::OnX87 };
3075        assert_eq!(missing.inst(), None);
3076    }
3077
3078    /// An `alloca` of a fixed size, which is what every local whose address is taken becomes.
3079    fn slot(source: &mut Func, block: Block, size: u64, align: u32) -> Value {
3080        let info = MemInfo { size, align, ..plain() };
3081        let mut build = Builder::new(source, block);
3082        let mem = build.func().add_mem(info);
3083        build.value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR)
3084    }
3085
3086    #[test]
3087    fn a_local_is_memory_in_the_frame_and_one_instruction_that_says_where() {
3088        let (mut names, mut source, block, _) = blank(&[]);
3089        let slot = slot(&mut source, block, 4, 4);
3090        let mut build = Builder::new(&mut source, block);
3091        let nine = build.iconst(Type::int(32), 9);
3092        build.store(nine, slot, plain(), Flags::default());
3093        let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
3094        build.ret(&[loaded]);
3095
3096        let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
3097
3098        // Four bytes on the list the frame is laid out from, and the one instruction that reads
3099        // where they went. Its displacement is nothing here because there is no frame yet, and
3100        // which instruction is waiting for which local is what `finish` is handed.
3101        assert_eq!(lowered.stack.locals, vec![Local { size: 4, align: 4 }]);
3102        assert_eq!(lowered.stack.addresses.len(), 1);
3103        assert_eq!(lowered.stack.addresses[0].1, 0);
3104        assert_eq!(
3105            mir::print_func(&lowered.func, &names, &REGS),
3106            "mfunc @f {\nblock0:\n    %0:gpr = x64.lea_64 [$rsp]\n    \
3107             %1:gpr = x64.mov_ri_32 9\n    x64.mov_mr_32 %1, [%0]\n    \
3108             %2:gpr = x64.mov_rm_32 [%0]\n    x64.ret_val_32 %2($rax)\n}\n"
3109        );
3110    }
3111
3112    #[test]
3113    fn the_frame_is_what_fills_the_address_of_a_local_in() {
3114        let (mut names, mut source, block, _) = blank(&[]);
3115        let slot = slot(&mut source, block, 4, 4);
3116        let mut build = Builder::new(&mut source, block);
3117        let nine = build.iconst(Type::int(32), 9);
3118        build.store(nine, slot, plain(), Flags::default());
3119        let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
3120        build.ret(&[loaded]);
3121
3122        let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
3123        let stack = lowered.stack;
3124        let mut out = lowered.func;
3125        let env = env();
3126        let allocation = rucc_regalloc::run(&mut out, &env);
3127        let layout = stack.layout(Layout::new(&SYSV, REGS));
3128        let frame = Frame::of(&out, &allocation, &layout);
3129        finish(&mut out, &allocation, &frame, &stack, &SYSV, &FRAME, &mut names);
3130
3131        // `int f(void) { int x; x = 9; return x; }` with the address of `x` taken, end to end.
3132        // A leaf small enough to live in the red zone takes no frame at all, so the stack pointer
3133        // never moves and the four bytes are below it, which is what the negative offset is. The
3134        // instruction the lowering left with nothing in its displacement now has the answer in it.
3135        let text = mir::print_func(&out, &names, &REGS);
3136        assert!(text.contains("$rax = x64.lea_64 [$rsp - 8]"), "{text}");
3137        assert!(!text.contains("x64.sub_ri_64"), "{text}");
3138        assert_eq!(frame.size(), 0);
3139        assert_eq!(frame.local(0), Some(-8));
3140    }
3141
3142    #[test]
3143    fn a_stack_slot_whose_size_is_not_known_until_it_runs_is_reported() {
3144        let i64 = Type::int(64);
3145        let (mut names, mut source, block, args) = blank(&[i64]);
3146        let info = MemInfo { size: 0, align: 16, ..plain() };
3147        let mut build = Builder::new(&mut source, block);
3148        let mem = build.func().add_mem(info);
3149        let size = build.func().push_values(&[args[0]]);
3150        let slot = build.value(
3151            InstData { args: size, extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) },
3152            Type::PTR,
3153        );
3154        Builder::new(&mut source, block).ret(&[slot]);
3155
3156        // A variable length array. Growing the stack where the declaration stands means moving the
3157        // stack pointer in the middle of the function and reaching everything else through a
3158        // frame pointer afterwards, and the frame here lays out neither.
3159        let failed = func(&source, &mut names, &SYSV).expect_err("nothing grows the stack");
3160        assert_eq!(failed.to_string(), "nothing here grows the stack for a variable length array");
3161    }
3162
3163    #[test]
3164    fn an_address_is_read_written_and_added_to_like_the_integer_it_is() {
3165        let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
3166        let mut build = Builder::new(&mut source, block);
3167        let stepped = build.func().push_values(&[args[0], args[1]]);
3168        let next =
3169            build.value(InstData { args: stepped, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
3170        let loaded = build.load(Type::int(32), next, plain(), Flags::default());
3171        build.ret(&[loaded]);
3172
3173        // `int f(int *p, long i) { return *(int *)((char *)p + i); }`. Nothing about this is new
3174        // in the rule set, which is the point: the two addresses arrive in registers because an
3175        // address is an integer as wide as one, and the arithmetic on them is the add it always
3176        // was, so every rule written about an add reaches it.
3177        //
3178        // The add stays its own instruction rather than folding into the address the load reads
3179        // from. Two registers with no scale on either is the one addressing mode the rules have no
3180        // load through, because the folds that exist are the displacement one and the scaled ones,
3181        // and this is neither. That is a peephole worth having and not a thing this changes.
3182        assert_eq!(
3183            lower(&mut names, &source),
3184            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
3185             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n    \
3186             %3:gpr = x64.mov_rm_32 [%2]\n    x64.ret_val_32 %3($rax)\n}\n"
3187        );
3188    }
3189
3190    /// The address of a file scope name, which is what every use of a global and every string
3191    /// literal starts from.
3192    fn address_of(source: &mut Func, block: Block, names: &mut Interner, name: &str) -> Value {
3193        let symbol = names.intern(name);
3194        let mut build = Builder::new(source, block);
3195        build.value(
3196            InstData { extra: Extra::Symbol(symbol), ..InstData::new(Opcode::GlobalAddr) },
3197            Type::PTR,
3198        )
3199    }
3200
3201    #[test]
3202    fn the_address_of_a_name_is_one_instruction_carrying_the_name() {
3203        let (mut names, mut source, block, _) = blank(&[]);
3204        let counter = address_of(&mut source, block, &mut names, "counter");
3205        let mut build = Builder::new(&mut source, block);
3206        let loaded = build.load(Type::int(32), counter, plain(), Flags::default());
3207        build.ret(&[loaded]);
3208
3209        // `extern int counter; int f(void) { return counter; }`. The address is an addressing mode
3210        // that names no register and carries the symbol, which is what the assembler writes
3211        // relative to `%rip` and what the object writer leaves a relocation for.
3212        assert_eq!(
3213            lower(&mut names, &source),
3214            "mfunc @f {\nblock0:\n    %0:gpr = x64.lea_64 [@counter]\n    \
3215             %1:gpr = x64.mov_rm_32 [%0]\n    x64.ret_val_32 %1($rax)\n}\n"
3216        );
3217    }
3218
3219    /// A cast between a pointer and an integer, at whatever width the result is asked for.
3220    fn cast(source: &mut Func, block: Block, opcode: Opcode, from: Value, to: Type) -> Value {
3221        let mut build = Builder::new(source, block);
3222        let args = build.func().push_values(&[from]);
3223        build.value(InstData { args, ..InstData::new(opcode) }, to)
3224    }
3225
3226    #[test]
3227    fn a_cast_between_a_pointer_and_an_integer_as_wide_is_no_instruction_at_all() {
3228        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
3229        let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(64));
3230        Builder::new(&mut source, block).ret(&[number]);
3231
3232        // `long f(void *p) { return (long)p; }`. An address on this machine is an integer as wide
3233        // as the machine addresses, so the cast changes what the type system calls the value and
3234        // changes nothing about the value, and the register holding it is the one that held it.
3235        assert_eq!(
3236            lower(&mut names, &source),
3237            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
3238             x64.ret_val_64 %0($rax)\n}\n"
3239        );
3240    }
3241
3242    #[test]
3243    fn a_null_pointer_is_a_constant_that_reaches_a_register_before_anything_reads_it() {
3244        let (mut names, mut source, block, _) = blank(&[]);
3245        let mut build = Builder::new(&mut source, block);
3246        let zero = build.iconst(Type::int(64), 0);
3247        let null = cast(&mut source, block, Opcode::IntToPtr, zero, Type::PTR);
3248        Builder::new(&mut source, block).ret(&[null]);
3249
3250        // `void *f(void) { return 0; }`. The cast is nothing, and reading its operand is what
3251        // writes the zero down: a constant is materialized where it is wanted rather than where
3252        // the IR defined it, and without the read there would be no instruction at all.
3253        assert_eq!(
3254            lower(&mut names, &source),
3255            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_64 0\n    x64.ret_val_64 %0($rax)\n}\n"
3256        );
3257    }
3258
3259    #[test]
3260    fn the_five_linkages_the_ir_has_narrow_to_the_three_an_object_file_can_say() {
3261        let readings = [
3262            (Linkage::External, mir::Binding::Global),
3263            (Linkage::Common, mir::Binding::Global),
3264            (Linkage::Internal, mir::Binding::Local),
3265            (Linkage::Weak, mir::Binding::Weak),
3266            (Linkage::LinkOnce, mir::Binding::Weak),
3267        ];
3268        for (linkage, wanted) in readings {
3269            let (mut names, mut source, block, _) = blank(&[]);
3270            source.linkage = linkage;
3271            Builder::new(&mut source, block).ret(&[]);
3272            let out = func(&source, &mut names, &SYSV).expect("a return");
3273            // The narrowing is done here rather than where the object is written, because a
3274            // machine function is all the assembler and the writer are ever handed.
3275            assert_eq!(out.func.binding, wanted, "{linkage:?}");
3276        }
3277    }
3278
3279    #[test]
3280    fn a_cast_between_a_pointer_and_a_narrower_integer_is_reported() {
3281        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
3282        let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(32));
3283        Builder::new(&mut source, block).ret(&[number]);
3284
3285        // The front end never writes one: it casts at the address width and truncates or extends
3286        // around it, so both of those are the rules they always were. IR from somewhere else that
3287        // does write one is refused rather than compiled to a move that keeps the high half.
3288        let failed = func(&source, &mut names, &SYSV).expect_err("no rule narrows an address");
3289        assert_eq!(failed.to_string(), "no rule lowers a `ptrtoint` producing a `i32`");
3290    }
3291
3292    /// The type this machine has no register for.
3293    fn long_double() -> Type {
3294        Type::float(rucc_ir::Float::F80)
3295    }
3296
3297    #[test]
3298    fn a_double_widened_and_narrowed_again_goes_out_through_the_frame_and_back() {
3299        let f64 = Type::float(rucc_ir::Float::F64);
3300        let (mut names, mut source, block, args) = blank(&[f64]);
3301        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
3302        let back = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
3303        Builder::new(&mut source, block).ret(&[back]);
3304
3305        // `double f(double d) { long double x = d; return x; }`. The x87 reads memory and nothing
3306        // else, so the value is written to the crossing slot, loaded at the format that widens it
3307        // and put in the slot the eighty bit value lives in. Coming back is the same three the
3308        // other way. Both slots are addressed by a `lea` with nothing in it yet, which is what
3309        // every address in a frame looks like here until `finish` has the numbers.
3310        assert_eq!(
3311            lower(&mut names, &source),
3312            "mfunc @f {\nblock0:\n    \
3313             %0:xmm($xmm0) = x64.arg_val_f64\n    \
3314             %1:gpr = x64.lea_64 [$rsp]\n    \
3315             %2:gpr = x64.lea_64 [$rsp]\n    \
3316             x64.movsd_mr %0, [%1]\n    \
3317             x64.fld_l [%1]\n    \
3318             x64.fstp_t [%2]\n    \
3319             %3:gpr = x64.lea_64 [$rsp]\n    \
3320             %4:gpr = x64.lea_64 [$rsp]\n    \
3321             x64.fld_t [%3]\n    \
3322             x64.fstp_l [%4]\n    \
3323             %5:xmm = x64.movsd_rm [%4]\n    \
3324             x64.ret_val_f64 %5($xmm0)\n}\n"
3325        );
3326    }
3327
3328    #[test]
3329    fn a_long_double_has_sixteen_bytes_of_its_own_and_keeps_them() {
3330        let f64 = Type::float(rucc_ir::Float::F64);
3331        let (mut names, mut source, block, args) = blank(&[f64]);
3332        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
3333        let once = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
3334        let twice = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
3335        let mut build = Builder::new(&mut source, block);
3336        let sum = build.binary(Opcode::FAdd, once, twice, Flags::default());
3337        build.ret(&[sum]);
3338
3339        let out = func(&source, &mut names, &SYSV).expect("every instruction is written");
3340
3341        // Two slots and not four: sixteen bytes for the one eighty bit value, which is what the
3342        // psABI says one takes and is aligned to, and eight for the crossing, which every group
3343        // in the function shares because nothing is ever left in it. The value's slot is its own
3344        // for the whole function, so reading it twice reads the same sixteen bytes.
3345        assert_eq!(
3346            out.stack.locals,
3347            vec![Local { size: 8, align: 8 }, Local { size: 16, align: 16 }]
3348        );
3349    }
3350
3351    #[test]
3352    fn an_integer_becomes_a_long_double_by_being_loaded_as_one() {
3353        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
3354        let wide = cast(&mut source, block, Opcode::SIToFP, args[0], long_double());
3355        let back =
3356            cast(&mut source, block, Opcode::FPTrunc, wide, Type::float(rucc_ir::Float::F64));
3357        Builder::new(&mut source, block).ret(&[back]);
3358
3359        // `double f(long n) { long double x = n; return x; }`. `fild` is the same push at another
3360        // format, so the conversion is the load and there is no instruction that converts.
3361        let text = lower(&mut names, &source);
3362        assert!(text.contains("x64.mov_mr_64 %0, [%1]"), "{text}");
3363        assert!(text.contains("x64.fild_ll [%1]"), "{text}");
3364    }
3365
3366    #[test]
3367    fn a_long_double_becoming_an_integer_cuts_towards_zero_with_the_control_word() {
3368        let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
3369        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
3370        let whole = cast(&mut source, block, Opcode::FPToSI, wide, Type::int(32));
3371        Builder::new(&mut source, block).ret(&[whole]);
3372
3373        // The one conversion here with no single instruction behind it. C cuts towards zero and
3374        // the unit rounds the way its control word says, so the word is saved, ORed with the two
3375        // bits that mean truncate, loaded, used and put back. Nine instructions for what `fisttp`
3376        // does in one, and `spec/10-backend.md` section 10.8 says why that one is not used.
3377        let text = lower(&mut names, &source);
3378        let group: Vec<&str> = text
3379            .lines()
3380            .map(str::trim)
3381            .filter(|line| line.starts_with("x64.f") || line.contains("_16"))
3382            .collect();
3383        assert_eq!(
3384            group,
3385            [
3386                "x64.fld_l [%1]",
3387                "x64.fstp_t [%2]",
3388                "x64.fnstcw [%5]",
3389                "%6:gpr = x64.mov_rm_16 [%5]",
3390                "%7:gpr(reuse 1) = x64.or_ri_16 %6, 3072",
3391                "x64.mov_mr_16 %7, [%5 + 2]",
3392                "x64.fldcw [%5 + 2]",
3393                "x64.fld_t [%3]",
3394                "x64.fistp_l [%4]",
3395                "x64.fldcw [%5]",
3396            ],
3397            "{text}"
3398        );
3399    }
3400
3401    #[test]
3402    fn a_long_double_is_read_and_written_as_the_bits_it_already_is() {
3403        let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::PTR]);
3404        let mut build = Builder::new(&mut source, block);
3405        let value = build.load(long_double(), args[0], plain(), Flags::default());
3406        build.store(value, args[1], plain(), Flags::default());
3407        build.ret(&[]);
3408
3409        // `void f(long double *a, long double *b) { *b = *a; }`. A copy is a push and a pop at the
3410        // format the value is already in, which neither converts nor looks: a signalling NaN stays
3411        // one and nothing is raised, which is the whole of what makes it a copy.
3412        let text = lower(&mut names, &source);
3413        let group: Vec<&str> =
3414            text.lines().map(str::trim).filter(|line| line.starts_with("x64.f")).collect();
3415        assert_eq!(
3416            group,
3417            ["x64.fld_t [%0]", "x64.fstp_t [%2]", "x64.fld_t [%3]", "x64.fstp_t [%1]"],
3418            "{text}"
3419        );
3420    }
3421
3422    /// Two `long double` values, from two `double` parameters, and the instructions that made
3423    /// them, which every test below this one throws away.
3424    fn two_long_doubles(source: &mut Func, block: Block, args: &[Value]) -> (Value, Value) {
3425        let left = cast(source, block, Opcode::FPExt, args[0], long_double());
3426        let right = cast(source, block, Opcode::FPExt, args[1], long_double());
3427        (left, right)
3428    }
3429
3430    /// The x87 instructions of a function, in order, with everything else dropped.
3431    fn stack_only(text: &str) -> Vec<&str> {
3432        text.lines().map(str::trim).filter(|line| line.contains("x64.f")).collect()
3433    }
3434
3435    /// The two frame slots the last two addresses of a function were taken of, which in a
3436    /// comparison are the two operands in the order they go on the stack.
3437    fn pushed(out: &Lowered) -> Vec<usize> {
3438        let taken: Vec<usize> = out.stack.addresses.iter().map(|&(_, local)| local).collect();
3439        taken[taken.len() - 2..].to_vec()
3440    }
3441
3442    #[test]
3443    fn adding_two_long_doubles_pushes_both_and_leaves_the_answer_in_a_slot() {
3444        let f64 = Type::float(rucc_ir::Float::F64);
3445        let (mut names, mut source, block, args) = blank(&[f64, f64]);
3446        let (left, right) = two_long_doubles(&mut source, block, &args);
3447        let sum =
3448            Builder::new(&mut source, block).binary(Opcode::FAdd, left, right, Flags::default());
3449        let back = cast(&mut source, block, Opcode::FPTrunc, sum, f64);
3450        Builder::new(&mut source, block).ret(&[back]);
3451
3452        // `double f(double a, double b) { return (long double) a + (long double) b; }`. The last
3453        // four lines are the add: both operands pushed, the instruction that names neither of
3454        // them because they are the top two of a stack, and the answer taken off into its slot.
3455        let text = lower(&mut names, &source);
3456        assert_eq!(
3457            stack_only(&text),
3458            [
3459                "x64.fld_l [%2]",
3460                "x64.fstp_t [%3]",
3461                "x64.fld_l [%4]",
3462                "x64.fstp_t [%5]",
3463                "x64.fld_t [%6]",
3464                "x64.fld_t [%7]",
3465                "x64.fadd_p",
3466                "x64.fstp_t [%8]",
3467                "x64.fld_t [%9]",
3468                "x64.fstp_l [%10]",
3469            ],
3470            "{text}"
3471        );
3472    }
3473
3474    #[test]
3475    fn a_subtraction_pushes_the_left_operand_first_so_it_is_the_one_subtracted_from() {
3476        let f64 = Type::float(rucc_ir::Float::F64);
3477        let (mut names, mut source, block, args) = blank(&[f64, f64]);
3478        let (left, right) = two_long_doubles(&mut source, block, &args);
3479        let less =
3480            Builder::new(&mut source, block).binary(Opcode::FSub, left, right, Flags::default());
3481        let back = cast(&mut source, block, Opcode::FPTrunc, less, f64);
3482        Builder::new(&mut source, block).ret(&[back]);
3483
3484        // The left one goes on first, so it ends up under the right one, and `fsubp` takes the top
3485        // from the one below it. Which is `a - b` and is why the reversed mnemonic is never used
3486        // here: getting the order right at the push is the same answer for one fewer instruction
3487        // name to keep straight.
3488        let text = lower(&mut names, &source);
3489        assert_eq!(
3490            &stack_only(&text)[4..8],
3491            ["x64.fld_t [%6]", "x64.fld_t [%7]", "x64.fsub_p", "x64.fstp_t [%8]"],
3492            "{text}"
3493        );
3494        assert!(!text.contains("fsubr_p"), "{text}");
3495    }
3496
3497    #[test]
3498    fn negating_a_long_double_turns_the_sign_over_and_reads_nothing() {
3499        let f64 = Type::float(rucc_ir::Float::F64);
3500        let (mut names, mut source, block, args) = blank(&[f64]);
3501        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
3502        let flipped = Builder::new(&mut source, block).unary(Opcode::FNeg, wide, long_double());
3503        let back = cast(&mut source, block, Opcode::FPTrunc, flipped, f64);
3504        Builder::new(&mut source, block).ret(&[back]);
3505
3506        // `fchs` and not a subtraction from zero, which would give a different answer at a negative
3507        // zero and would signal at a NaN. It does not read the value as a number at all.
3508        let text = lower(&mut names, &source);
3509        assert_eq!(
3510            &stack_only(&text)[2..5],
3511            ["x64.fld_t [%3]", "x64.fchs", "x64.fstp_t [%4]"],
3512            "{text}"
3513        );
3514    }
3515
3516    #[test]
3517    fn comparing_two_long_doubles_puts_the_left_one_on_top() {
3518        let f64 = Type::float(rucc_ir::Float::F64);
3519        let (mut names, mut source, block, args) = blank(&[f64, f64]);
3520        let (left, right) = two_long_doubles(&mut source, block, &args);
3521        let mut build = Builder::new(&mut source, block);
3522        build.fcmp(FloatPred::Ogt, left, right, Flags::default());
3523        build.ret(&[]);
3524
3525        // `a > b`. `fucomip` asks about the top of the stack against what is under it, so the
3526        // operand the predicate is about has to go on last, which is the other way round from the
3527        // arithmetic above. The pop that clears the loser and the byte that reads the flags are
3528        // both inside the one opcode.
3529        let out = func(&source, &mut names, &SYSV).expect("every instruction is written");
3530        let slots = pushed(&out);
3531        assert_eq!(slots, [2, 1], "the right operand goes on first and the left one on top");
3532        let text = mir::print_func(&out.func, &names, &REGS);
3533        assert_eq!(
3534            &stack_only(&text)[4..],
3535            ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
3536            "{text}"
3537        );
3538    }
3539
3540    #[test]
3541    fn a_comparison_that_the_machine_has_backwards_swaps_the_two_pushes() {
3542        let f64 = Type::float(rucc_ir::Float::F64);
3543        let (mut names, mut source, block, args) = blank(&[f64, f64]);
3544        let (left, right) = two_long_doubles(&mut source, block, &args);
3545        let mut build = Builder::new(&mut source, block);
3546        build.fcmp(FloatPred::Olt, left, right, Flags::default());
3547        build.ret(&[]);
3548
3549        // `a < b` is `b > a` and this machine has the one condition, so the same opcode runs with
3550        // the operands the other way round. The same trade the vector rules make, and it has to
3551        // be the same one: a `long double` comparison that picked a different condition from the
3552        // `double` comparison of the same two numbers would be wrong at exactly the unordered
3553        // cases the two conditions differ on.
3554        //
3555        // Which slot each push names is the whole of the difference from the test above, and the
3556        // text does not show it, since an address in a frame is a `lea` with nothing in it until
3557        // `finish` has the numbers. So the slots are what is read here.
3558        let out = func(&source, &mut names, &SYSV).expect("every instruction is written");
3559        let slots = pushed(&out);
3560        assert_eq!(slots, [1, 2], "the left operand goes on first and the right one on top");
3561        let text = mir::print_func(&out.func, &names, &REGS);
3562        assert_eq!(
3563            &stack_only(&text)[4..],
3564            ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
3565            "{text}"
3566        );
3567    }
3568
3569    #[test]
3570    fn an_ordered_equal_needs_a_second_byte_to_put_the_two_conditions_together() {
3571        let f64 = Type::float(rucc_ir::Float::F64);
3572        let (mut names, mut source, block, args) = blank(&[f64, f64]);
3573        let (left, right) = two_long_doubles(&mut source, block, &args);
3574        let mut build = Builder::new(&mut source, block);
3575        build.fcmp(FloatPred::Oeq, left, right, Flags::default());
3576        build.ret(&[]);
3577
3578        // Equal and ordered are two conditions and the flags carry both, so the opcode writes a
3579        // second register as well as the one the value is in and ANDs them together. Said here by
3580        // handing it a spare, since an instruction that wrote a register nothing knew about would
3581        // be an instruction the allocator could put a live value in the way of.
3582        let text = lower(&mut names, &source);
3583        assert!(text.contains("%8:gpr, %9:gpr = x64.fucomip_set_e_and_np"), "{text}");
3584    }
3585
3586    #[test]
3587    fn a_comparison_that_is_never_asked_is_reported() {
3588        let f64 = Type::float(rucc_ir::Float::F64);
3589        let (mut names, mut source, block, args) = blank(&[f64, f64]);
3590        let (left, right) = two_long_doubles(&mut source, block, &args);
3591        let mut build = Builder::new(&mut source, block);
3592        build.fcmp(FloatPred::False, left, right, Flags::default());
3593        build.ret(&[]);
3594
3595        // Always false is a constant and not a comparison, so there is no condition to pick and
3596        // nothing here folds it into one: an instruction that quietly agreed with it would hide
3597        // that the optimizer left a comparison in that it should have taken out.
3598        let failed = func(&source, &mut names, &SYSV).expect_err("no condition is always false");
3599        assert_eq!(failed.to_string(), "no rule lowers a `fcmp` producing a `i1`");
3600    }
3601
3602    #[test]
3603    fn a_long_double_constant_is_the_bits_of_it_put_where_the_value_lives() {
3604        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
3605        let mut build = Builder::new(&mut source, block);
3606        // `1.5L`, which is the leading bit and one more of significand, and an exponent of zero.
3607        let one_and_a_half = build.fconst(long_double(), 0x3fff_c000_0000_0000_0000);
3608        build.store(one_and_a_half, args[0], plain(), Flags::default());
3609        build.ret(&[]);
3610
3611        // No x87 instruction at all. A slot holding one of these is the value, so a constant is
3612        // its ten bytes written where the value lives, and whatever reads it does the `fld`.
3613        let text = lower(&mut names, &source);
3614        assert!(text.contains("x64.mov_ri_64 -4611686018427387904"), "{text}");
3615        assert!(text.contains("x64.mov_ri_16 16383"), "{text}");
3616        assert!(text.contains("x64.mov_mr_16 %3, [%1 + 8]"), "{text}");
3617        // The six bytes above the ten are the padding that makes the type sixteen wide, and they
3618        // are unspecified rather than zero, so nothing writes them.
3619        assert_eq!(text.matches("x64.mov_mr").count(), 2, "{text}");
3620    }
3621
3622    #[test]
3623    fn a_negative_long_double_constant_keeps_the_bit_above_its_exponent() {
3624        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
3625        let mut build = Builder::new(&mut source, block);
3626        let minus = build.fconst(long_double(), 0xbfff_c000_0000_0000_0000);
3627        build.store(minus, args[0], plain(), Flags::default());
3628        build.ret(&[]);
3629
3630        // `-1.5L`. The sign is the top bit of the two byte half, so the immediate that half is put
3631        // in a register with is above the signed range of sixteen bits and has to stay there: read
3632        // as a number it would be negative, and it is not a number, it is two bytes.
3633        let text = lower(&mut names, &source);
3634        assert!(text.contains("x64.mov_ri_16 49151"), "{text}");
3635    }
3636
3637    #[test]
3638    fn a_long_double_crosses_an_edge_as_an_address_and_is_copied_where_it_lands() {
3639        let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
3640        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
3641        let next = source.create_block();
3642        let param = source.append_param(next, long_double());
3643        Builder::new(&mut source, block).jump(next, &[wide]);
3644        Builder::new(&mut source, next).ret(&[param]);
3645
3646        // What the edge carries is the address of the slot the value is already in, which is an
3647        // ordinary register the allocator has an opinion about. The block on the other side copies
3648        // the sixteen bytes into a slot of its own before anything reads them, so a second edge
3649        // handing over a second address would still leave one place for a reader to look.
3650        let text = lower(&mut names, &source);
3651        let second: Vec<&str> = text
3652            .lines()
3653            .skip_while(|line| !line.starts_with("block1"))
3654            .skip(1)
3655            .take(3)
3656            .map(str::trim)
3657            .collect();
3658        assert_eq!(
3659            second,
3660            ["x64.fld_t [%4]", "%5:gpr = x64.lea_64 [$rsp]", "x64.fstp_t [%5]"],
3661            "{text}"
3662        );
3663    }
3664
3665    #[test]
3666    fn more_long_doubles_at_a_block_than_the_stack_is_deep_are_reported() {
3667        let f64 = Type::float(rucc_ir::Float::F64);
3668        let (mut names, mut source, block, args) = blank(&[f64]);
3669        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
3670        let next = source.create_block();
3671        let params: Vec<Value> =
3672            (0..=X87_DEPTH).map(|_| source.append_param(next, long_double())).collect();
3673        let carried: Vec<Value> = params.iter().map(|_| wide).collect();
3674        Builder::new(&mut source, block).jump(next, &carried);
3675        Builder::new(&mut source, next).ret(&[params[0]]);
3676
3677        // The copies go through the x87 stack so that every one of them is read before any of them
3678        // is written, which is what makes a block that swaps two of these right. Nine of them do
3679        // not fit on the stack, and copying the ninth before or after the rest is the order that
3680        // could be wrong, so it is refused instead.
3681        let failed = func(&source, &mut names, &SYSV).expect_err("nine do not fit on the stack");
3682        assert_eq!(
3683            failed.to_string(),
3684            "block1 takes 9 parameters of type `f80` and only 8 can cross an edge at once"
3685        );
3686        assert_eq!(failed.inst(), None);
3687    }
3688}