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::collections::HashSet;
79use std::fmt;
80
81use rucc_base::Interner;
82use rucc_diag::Span;
83use rucc_ir::{
84    Abi, AsmOperands, Block, Def, Extra, FloatPred, Func, Inst, Linkage, MemOrder, Opcode, Param,
85    RmwOp, Type, Value, Visibility,
86};
87use rucc_mir as mir;
88use rucc_target::x86_64;
89use rucc_target::{CallRegs, Constraint, RegClass};
90
91use crate::abi::{self, Missing, Refused};
92use crate::coverage::Fired;
93use crate::elsewhere::Elsewhere;
94use crate::frame::{Layout, Local};
95use crate::select::{Match, Piece, Rule, Table};
96use crate::term::{MAX_ARGS, PLAIN, Plan, Shown, Term, Terms};
97use crate::varargs;
98
99/// The prefix a rule file puts in front of a machine term, which says which target it belongs
100/// to and is not part of the opcode.
101pub(crate) const PREFIX: &str = "x64.";
102
103/// The instruction a global offset table slot is read with.
104///
105/// Not in [`x86_64::FRAME`] with the other opcodes this file names, because a frame has no use for
106/// it. It is spelled out here because the relocation it takes is only legal on a `mov` with a REX
107/// prefix, so the width is part of the requirement rather than a choice.
108const GOT_LOAD: &str = "mov_rm_64";
109
110/// How wide an address is on this target, which is the width a cast between a pointer and an
111/// integer has to be at for the cast to be nothing.
112const ADDRESS_BITS: u32 = 64;
113
114/// How many bytes a `long double` takes in memory, and what it is aligned to, which are the same
115/// number and are both more than the ten bytes that mean anything.
116///
117/// The psABI's answer rather than a choice here. `sizeof (long double)` is sixteen on this
118/// machine, so an array of them is laid out this way whatever a slot holding one does, and a slot
119/// that agreed with the array is one fewer thing to get wrong.
120const X87_BYTES: u32 = 16;
121
122/// How many values the x87 stack holds at once.
123///
124/// Eight, which is the machine's number rather than a choice here, and it matters in one place:
125/// the parameters of a block are copied through the stack so that they all move at once, and a
126/// block with more of them than this has nowhere to put the ninth.
127const X87_DEPTH: usize = 8;
128
129/// How many bytes a value passes through on its way between a register and the x87 stack.
130///
131/// Eight, because the widest thing that crosses is a `double` or a sixty four bit integer, and
132/// nothing crosses at eighty bits: a value that wide is already in the frame and the stack reaches
133/// it where it is.
134const X87_CROSSING: u32 = 8;
135
136/// Where the rounding field of the x87 control word is and what it has to be set to for the unit
137/// to cut towards zero, which is the one rounding C asks for that the unit does not do by default.
138///
139/// Both bits on is truncate. The field is ORed into the word that was already there rather than
140/// written over it, so the precision control and the exception masks somebody else set stay set.
141const X87_TRUNCATE: i64 = 0x0c00;
142
143/// Whether a type is the one this machine has no register for.
144///
145/// Only the eighty bit float is, and that is a fact about x86-64 rather than about floats: every
146/// other scalar the front end produces is in a general purpose register or a vector one, and this
147/// one is on the x87 stack while it is being worked on and in memory the rest of the time. So it
148/// has no place in [`Lowering::class_of`] and no name in [`crate::term`], and every instruction
149/// that touches one is written out by hand in this file.
150fn on_x87(ty: Type) -> bool {
151    ty.is_scalar() && ty.is_float() && ty.bits() == 80
152}
153
154/// Why a function could not be lowered.
155///
156/// One reason and then nothing. A function with no rule for something in it is a function this
157/// cannot finish, and the second thing it could not lower is not news.
158#[derive(Debug, Clone, PartialEq, Eq)]
159pub enum Unsupported {
160    /// An instruction no rule fires on.
161    Inst {
162        /// The instruction that stopped it.
163        inst: Inst,
164        /// What the rule file would call it, or nothing if the rule language has no name for it
165        /// at all, which is what an instruction at a width nothing is written about looks like.
166        term: Option<&'static str>,
167        /// The opcode, which is what gets named when the rule language has no word for it.
168        ///
169        /// An opcode the rule language has no word for is exactly the opcode no rule lowers, so
170        /// without this the message would be empty in every case where somebody needs it.
171        opcode: Opcode,
172        /// What it produces, or nothing for an instruction that is only an effect.
173        ty: Option<Type>,
174    },
175    /// A parameter that does not arrive somewhere this can bring it in from.
176    ///
177    /// Not an instruction, which is why it is a separate arm: it is a fact about the signature
178    /// and there is nothing in the body of the function to point at.
179    Argument {
180        /// Its position in the signature.
181        index: usize,
182        /// What is wrong with where it arrives.
183        missing: Missing,
184    },
185    /// A call that passes or gives back a value this cannot put where the convention wants it.
186    Call {
187        /// The call.
188        inst: Inst,
189        /// Which value, and what is wrong with where it travels.
190        refused: Refused,
191    },
192    /// A `return` this cannot put where the convention wants it.
193    ///
194    /// A separate arm from [`Unsupported::Inst`] because it is not an instruction no rule fires
195    /// on. A return of more than one value is built from the convention rather than matched, the
196    /// same way a call is, so what goes wrong with one is what goes wrong with a call and not the
197    /// absence of a rule.
198    Returned {
199        /// The `return`.
200        inst: Inst,
201        /// What is wrong with where one of the values travels.
202        missing: Missing,
203    },
204    /// A stack slot the frame cannot give the bytes it asked for.
205    ///
206    /// Not an instruction no rule covers. An `alloca` is built here rather than matched, so what
207    /// goes wrong with one is what the frame can and cannot hold rather than what the rules spell.
208    Dynamic {
209        /// The `alloca`.
210        inst: Inst,
211        /// What the frame could not do about it.
212        growing: Growing,
213    },
214    /// More parameters of a type that travels on the x87 stack than the stack is deep.
215    ///
216    /// Not an instruction either, for the reason a function's parameter is not one: it is a fact
217    /// about the block and there is nothing in the block to point at. What crosses an edge for one
218    /// of these is the address of where the value is, and the block copies the bytes into a slot
219    /// of its own, all of them through the stack at once so that a block carrying two of them
220    /// swapped is copied in an order that is right. Eight is as many as the stack holds, and a
221    /// ninth would have to be copied before or after the rest, which is the order that could be
222    /// wrong.
223    Phi {
224        /// Which block it arrives at.
225        block: Block,
226        /// How many of them arrive there, which is the whole of what is wrong.
227        count: usize,
228        /// What they are.
229        ty: Type,
230    },
231    /// An `asm` statement this cannot build.
232    ///
233    /// Not an instruction no rule fires on, for the reason a call is not one: what it stands for is
234    /// whatever its template says, and no pattern over terms can read a string.
235    Assembly {
236        /// The `inline_asm`.
237        inst: Inst,
238        /// What about it is not built here yet.
239        refused: Written,
240    },
241}
242
243/// What about an `asm` statement is not built yet.
244#[derive(Debug, Clone, Copy, PartialEq, Eq)]
245pub enum Written {
246    /// A template with instructions in it.
247    Template,
248    /// An `asm goto`, whose labels make the statement a terminator.
249    Goto,
250    /// An operand this cannot put where the constraint says it goes.
251    Operand,
252}
253
254impl Written {
255    /// The rest of the sentence that starts with the statement.
256    #[must_use]
257    pub fn why(self) -> &'static str {
258        match self {
259            // The template is the assembler's to read and there is no assembler here yet, so a
260            // template with anything in it is a string nothing can turn into bytes. An empty one is
261            // no instructions, and no instructions is something this can write.
262            Written::Template => "has instructions in its template, which nothing here assembles",
263            Written::Goto => "jumps to a label, which nothing here builds an edge for",
264            Written::Operand => "has an operand this cannot place",
265        }
266    }
267}
268
269/// What the frame could not do about a stack slot.
270#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271pub enum Growing {
272    /// An object of a size the number a frame counts bytes in does not reach.
273    Huge,
274    /// A variable length array wanting more alignment than a call leaves the stack pointer with.
275    ///
276    /// Rounding the stack pointer down again after the bytes have been taken would put it
277    /// somewhere no constant reaches the rest of the frame from, so a frame like this needs a
278    /// second base register held for the whole of the function. Nothing here holds one.
279    Aligned,
280    /// A variable length array in a function whose frame is meant to be touched a page at a time.
281    ///
282    /// The pages a prologue takes are touched by the prologue, which knows how many there are when
283    /// it is written. The pages a variable length array takes are not known until the declaration
284    /// runs, so touching them is a loop next to the declaration, and there is no loop here yet.
285    Probed,
286}
287
288impl Growing {
289    /// The rest of the sentence that starts with the slot.
290    #[must_use]
291    pub fn why(self) -> &'static str {
292        match self {
293            Growing::Huge => "is more bytes than a frame counts",
294            Growing::Aligned => {
295                "wants more alignment than the stack pointer is left on, which needs a base \
296                 register nothing here keeps"
297            }
298            Growing::Probed => {
299                "grows the stack, and nothing here touches the pages it takes a page at a time"
300            }
301        }
302    }
303}
304
305impl Unsupported {
306    /// The instruction it is about, or nothing for the one arm that is about a signature.
307    ///
308    /// What a caller wants this for is the span. The function knows where every instruction in
309    /// it came from, so a caller holding both can point a message at the line somebody wrote
310    /// rather than at the file as a whole, and nothing here has to carry a span of its own.
311    pub fn inst(&self) -> Option<Inst> {
312        match *self {
313            Unsupported::Inst { inst, .. }
314            | Unsupported::Call { inst, .. }
315            | Unsupported::Returned { inst, .. }
316            | Unsupported::Dynamic { inst, .. }
317            | Unsupported::Assembly { inst, .. } => Some(inst),
318            Unsupported::Argument { .. } | Unsupported::Phi { .. } => None,
319        }
320    }
321}
322
323impl fmt::Display for Unsupported {
324    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
325        match *self {
326            Unsupported::Inst { term: Some(term), .. } => write!(f, "no rule lowers `{term}`"),
327            Unsupported::Inst { term: None, opcode, ty: Some(ty), .. } => {
328                write!(f, "no rule lowers a `{opcode}` producing a `{ty}`")
329            }
330            Unsupported::Inst { term: None, opcode, ty: None, .. } => {
331                write!(f, "no rule lowers a `{opcode}`")
332            }
333            Unsupported::Argument { index, missing } => {
334                write!(f, "parameter {index} {}", missing.why())
335            }
336            Unsupported::Call { refused: Refused { argument: Some(index), missing }, .. } => {
337                write!(f, "argument {index} of this call {}", missing.why())
338            }
339            Unsupported::Call { refused: Refused { argument: None, missing }, .. } => {
340                write!(f, "what this call gives back {}", missing.why())
341            }
342            Unsupported::Returned { missing, .. } => {
343                write!(f, "what this function gives back {}", missing.why())
344            }
345            Unsupported::Dynamic { growing, .. } => {
346                write!(f, "this local {}", growing.why())
347            }
348            Unsupported::Phi { block, count, ty } => {
349                let block = block.index();
350                write!(
351                    f,
352                    "block{block} takes {count} parameters of type `{ty}` and only {X87_DEPTH} can cross an edge at once"
353                )
354            }
355            Unsupported::Assembly { refused, .. } => write!(f, "this `asm` {}", refused.why()),
356        }
357    }
358}
359
360impl std::error::Error for Unsupported {}
361
362/// A lowered function, and what the frame needs that the machine IR does not hold.
363#[derive(Debug)]
364pub struct Lowered {
365    /// The function, in machine instructions.
366    pub func: mir::Func,
367    /// What it wants its stack to look like, which is separate from the function so that the two
368    /// can be read and written at the same time.
369    pub stack: Stack,
370    /// Which rules of the table lowered it, which is what `-Zrule-coverage` asks for and what
371    /// `crate::coverage` writes down.
372    pub fired: Fired,
373}
374
375/// What a function's stack has to hold, as far as selection is able to say.
376///
377/// All of it is answered here because selection is where a call is built and where an `alloca`
378/// is read, and nothing after it could tell what either of them needed.
379#[derive(Debug, Default)]
380pub struct Stack {
381    /// How many bytes the widest call in the function needs below the stack pointer for the
382    /// arguments it passes there, or `None` for a function that makes no call at all.
383    ///
384    /// `None` is a leaf, which is the function that may use the red zone and the one whose stack
385    /// pointer does not have to be left aligned for anybody.
386    pub calls: Option<u32>,
387    /// The memory the function asked for itself, one entry for every `alloca` in it, in the order
388    /// the walk reached them.
389    pub locals: Vec<Local>,
390    /// Which instruction computes the address of which of those locals.
391    ///
392    /// An address in the frame is a distance from the stack pointer, and there is no frame until
393    /// after allocation, so the instruction is written here with nothing in its displacement and
394    /// [`crate::finish`] writes the number in once [`crate::frame::Frame`] knows it.
395    pub addresses: Vec<(mir::Inst, usize)>,
396    /// Which instruction computes the address of a piece of memory whose size the function works
397    /// out while it runs, which is what a variable length array is.
398    ///
399    /// Waiting on [`crate::finish`] for a different number from the one the addresses above are:
400    /// the bytes were taken off the stack pointer by the instruction in front of this one, so where
401    /// they start is however much of the bottom of the frame belongs to the arguments of a call,
402    /// and that is not known until the frame is.
403    pub dynamic: Vec<mir::Inst>,
404    /// Where the function first moves the stack pointer while it runs, if it does at all.
405    ///
406    /// Two things are read off this. One is whether at all, which is what [`crate::frame::Layout`]
407    /// wants, because a frame that moves its stack pointer has a different shape from one that does
408    /// not and the layout is built before the instructions are looked at again. See `Growing` in
409    /// [`crate::frame`]. The other is where, so that a caller that cannot accept such a frame has
410    /// somewhere to point when it says so.
411    pub grown_at: Option<Inst>,
412    /// Which instruction reads which of the arguments the caller passed on the stack, as how far up
413    /// the caller's argument area it reads.
414    ///
415    /// Waiting on [`crate::finish`] for the same reason the addresses above are, and on one thing
416    /// more: where the caller's argument area is from inside this function depends on whether the
417    /// prologue had to force the stack pointer's alignment, so which register the load reads
418    /// through is not settled here either.
419    pub arguments: Vec<(mir::Inst, u32)>,
420}
421
422impl Stack {
423    /// The layout given, with the three fields only the lowering knows the answer to filled in.
424    ///
425    /// Everything else in a layout comes from the flags the function is compiled under or from the
426    /// allocation, so this takes one and returns it rather than building one.
427    #[must_use]
428    pub fn layout<'a>(&'a self, base: Layout<'a>) -> Layout<'a> {
429        Layout {
430            leaf: self.calls.is_none(),
431            outgoing: self.calls.unwrap_or(0),
432            locals: &self.locals,
433            grows: self.grown_at.is_some(),
434            ..base
435        }
436    }
437}
438
439/// The x86-64 machine IR for that function.
440///
441/// # Errors
442///
443/// The first instruction no rule fires on, which today is anything at a width the rule set is not
444/// written at, a parameter that does not arrive in a register this can read, or a call that
445/// passes something this cannot put where the convention wants it.
446pub fn func(
447    source: &Func,
448    names: &mut Interner,
449    conv: &'static CallRegs,
450    elsewhere: &Elsewhere,
451) -> Result<Lowered, Unsupported> {
452    Lowering::new(source, names, conv, elsewhere).run()
453}
454
455/// What the matcher settled on for one block, indexed the way the block's instructions are.
456struct Decided {
457    /// What each instruction matched, and nothing for one that matched no rule or was folded
458    /// into a later one.
459    found: Vec<Option<Match<Term>>>,
460    /// How each instruction showed its operands to the matcher, which is what says what it took.
461    plans: Vec<Option<Plan>>,
462    /// The instructions some other instruction took, which are the ones with nothing to write.
463    folded: Vec<Inst>,
464}
465
466/// One function being lowered.
467struct Lowering<'a> {
468    source: &'a Func,
469    names: &'a mut Interner,
470    out: mir::Func,
471    /// The machine register each IR value is in, once it has one.
472    regs: Vec<Option<mir::Reg>>,
473    /// For a constant that has been written into a register, the block it was written into,
474    /// which is the only block that register is any good in.
475    written: Vec<Option<mir::Block>>,
476    /// How many times each IR value is read, which is what says whether an instruction may be
477    /// folded into the one that reads it.
478    uses: Vec<u32>,
479    /// The block being filled.
480    at: Option<mir::Block>,
481    /// The machine IR block each IR block became.
482    blocks: Vec<Option<mir::Block>>,
483    /// The class an address is in, which is the general purpose one and is not a question: every
484    /// register an addressing mode names holds part of an address, and there is no machine here
485    /// that computes an address anywhere but in this file. Which class a *value* is in is
486    /// [`Lowering::class_of`], and it is a question, because a float is in the other one.
487    gpr: RegClass,
488    /// Where the convention this function is compiled for puts things, which is read for the
489    /// arguments and for the calls.
490    conv: &'static CallRegs,
491    /// Which names this function may not work an address out for itself, which is a fact about the
492    /// module and so is worked out before any of this and handed in.
493    elsewhere: &'a Elsewhere,
494    /// What the function wants its stack to look like, filled in as the walk finds out.
495    stack: Stack,
496    /// What a `va_start` in this function has to write, or nothing for a function that takes no
497    /// arguments its signature does not name.
498    ///
499    /// Worked out once, when the entry block binds the parameters, because every number in it is
500    /// about where those parameters left the walk over the argument registers and there is nowhere
501    /// else that knows.
502    varargs: Option<Varargs>,
503    /// Which of the function's stack objects each eighty bit value lives in, once it has asked
504    /// for one.
505    ///
506    /// One slot per value and it is never given back, which is what makes an eighty bit value
507    /// behave like every other one: it is written once and read wherever it is read, and no two
508    /// of them share a slot the way two of them would share a register. What is in a register is
509    /// the address, and that is worked out again at every use rather than kept, so nothing here
510    /// holds a general purpose register open across a whole function.
511    slots: Vec<Option<usize>>,
512    /// The eight bytes a value passes through between a register and the x87 stack, once
513    /// something has wanted them.
514    ///
515    /// One for the whole function, because every group that uses it is a handful of instructions
516    /// with nothing in between: the bytes are written, read straight back and never looked at
517    /// again, so a second slot would be a second slot holding the same nothing.
518    crossing: Option<usize>,
519    /// The four bytes the control word is saved in and the changed copy written to, once
520    /// something has wanted them.
521    ///
522    /// One for the whole function for the reason above, and four rather than two because it is
523    /// two words: the one the unit had and the one with the rounding field turned to truncate.
524    control: Option<usize>,
525    /// Which rules have fired so far.
526    fired: Fired,
527}
528
529/// What a `va_start` in a variadic function writes into the list it is given.
530///
531/// Three of the four are settled here and the fourth is not a number at all yet: where the save
532/// area is and where the caller's argument area is are both distances into a frame that does not
533/// exist until after allocation, so both are `lea` instructions [`crate::finish`] fills in.
534#[derive(Debug, Clone, Copy, PartialEq, Eq)]
535struct Varargs {
536    /// Which of the function's stack objects is the register save area.
537    save: usize,
538    /// How far up the caller's argument area the first argument the signature does not name is,
539    /// which is the whole of that area the named ones did not take.
540    incoming: u32,
541    /// What `gp_offset` starts at, which is past the general purpose registers the named arguments
542    /// took.
543    integers: u32,
544    /// What `fp_offset` starts at, which is past the vector ones.
545    floats: u32,
546}
547
548/// How far a function's name reaches, narrowed from the linkage the IR gave it.
549///
550/// The IR has five and an object file says three, and the two the linker cannot tell apart are
551/// the two weak ones: which of them a symbol had is a fact the optimizer reads and the linker has
552/// no way to record. A function is never `Common`, since that is what a tentative definition of an
553/// object is and there is no tentative definition of a function, and it is written here rather
554/// than left out so that a linkage added later has to come past this.
555const fn binding(linkage: Linkage) -> mir::Binding {
556    match linkage {
557        Linkage::Internal => mir::Binding::Local,
558        Linkage::Weak | Linkage::LinkOnce => mir::Binding::Weak,
559        Linkage::External | Linkage::Common => mir::Binding::Global,
560    }
561}
562
563/// How far a function's name reaches outside a shared library, carried across unchanged.
564///
565/// Nothing is narrowed here the way [`binding`] narrows the linkage, because ELF records all
566/// three of these and the two enumerations are the same three answers written twice: once in a
567/// crate that is not allowed to know what an object file is and once in one that is.
568const fn visibility(visibility: Visibility) -> mir::Visibility {
569    match visibility {
570        Visibility::Default => mir::Visibility::Default,
571        Visibility::Hidden => mir::Visibility::Hidden,
572        Visibility::Protected => mir::Visibility::Protected,
573    }
574}
575
576impl<'a> Lowering<'a> {
577    fn new(
578        source: &'a Func,
579        names: &'a mut Interner,
580        conv: &'static CallRegs,
581        elsewhere: &'a Elsewhere,
582    ) -> Self {
583        let counts = source.counts();
584        let name = source.name;
585        let mut uses = vec![0; counts.values];
586        for block in source.blocks() {
587            for inst in source.insts(block) {
588                for &arg in &source[source[inst].args] {
589                    uses[arg.index()] += 1;
590                }
591                for call in source.successors(inst) {
592                    for &arg in &source[call.args] {
593                        uses[arg.index()] += 1;
594                    }
595                }
596            }
597        }
598        let mut out = mir::Func::new(name);
599        out.align = source.align;
600        out.binding = binding(source.linkage);
601        out.visibility = visibility(source.visibility);
602        Self {
603            source,
604            names,
605            out,
606            regs: vec![None; counts.values],
607            written: vec![None; counts.values],
608            blocks: vec![None; counts.blocks],
609            uses,
610            at: None,
611            gpr: x86_64::GPR,
612            conv,
613            elsewhere,
614            stack: Stack::default(),
615            varargs: None,
616            slots: vec![None; counts.values],
617            crossing: None,
618            control: None,
619            fired: Fired::new(),
620        }
621    }
622
623    fn run(mut self) -> Result<Lowered, Unsupported> {
624        // Every block before any of them is filled, because a block that jumps forward has to
625        // name the block it jumps to and a machine IR block is named by a handle rather than by
626        // the IR block it came from.
627        for block in self.source.blocks() {
628            let out = self.out.create_block();
629            self.blocks[block.index()] = Some(out);
630        }
631        for block in self.order() {
632            self.block(block)?;
633        }
634        Ok(Lowered { func: self.out, stack: self.stack, fired: self.fired })
635    }
636
637    /// The order the blocks are filled in, which is not the order they are written in.
638    ///
639    /// Reverse postorder, because a value is written in a block that dominates every block that
640    /// reads it and a block in reverse postorder comes before every block it dominates. The order
641    /// the blocks are written in does not have that property: a block written early can read a
642    /// value a block below it writes, and reading a value with no register yet mints one, so the
643    /// register the definition writes later is not the register the read named. Nothing writes the
644    /// one the read named, and what comes out is a function that loads a stack slot no store ever
645    /// reached. It is the order this walk goes in rather than the order the blocks come out in,
646    /// which is what the loop above fixes, so the machine function is still written the way the IR
647    /// function was.
648    ///
649    /// Blocks the entry does not reach come last, in the order they are written in. Nothing runs
650    /// them and nothing they name is read by anything that does, but they still have to be filled,
651    /// because a machine block with no terminator is not one the passes below can read.
652    fn order(&self) -> Vec<Block> {
653        let Some(entry) = self.source.entry() else { return self.source.blocks().collect() };
654        let count = self.blocks.len();
655        let mut succs: Vec<Vec<Block>> = vec![Vec::new(); count];
656        for block in self.source.blocks() {
657            let Some(term) = self.source.terminator(block) else { continue };
658            succs[block.index()] = self.source.successors(term).map(|call| call.block).collect();
659        }
660        // An explicit stack, because the depth of the walk is the number of blocks and a function
661        // built by a generator has as many of those as it likes.
662        let mut seen = vec![false; count];
663        let mut order = Vec::with_capacity(count);
664        let mut stack = vec![(entry, 0usize)];
665        seen[entry.index()] = true;
666        while let Some((block, at)) = stack.pop() {
667            let Some(&next) = succs[block.index()].get(at) else {
668                order.push(block);
669                continue;
670            };
671            stack.push((block, at + 1));
672            if !seen[next.index()] {
673                seen[next.index()] = true;
674                stack.push((next, 0));
675            }
676        }
677        order.reverse();
678        order.extend(self.source.blocks().filter(|block| !seen[block.index()]));
679        order
680    }
681
682    /// One block: its parameters, then every instruction in it that is not folded into another.
683    fn block(&mut self, block: Block) -> Result<(), Unsupported> {
684        let out = self.out_block(block);
685        self.at = Some(out);
686        if self.source.entry() == Some(block) {
687            self.arrive(block, out)?;
688        } else {
689            let mut arriving = Vec::new();
690            for &param in &self.source[block].params {
691                // A value with no register to arrive in, which the class would not say, since
692                // `class_of` puts one of these in the general purpose file on purpose and what it
693                // means by that is that nothing there can hold it. What crosses the edge for one
694                // of those is the address of where the value already is, so the parameter is a
695                // pointer here and the bytes it points at are copied below.
696                let ty = self.source[param].ty;
697                let reg = self.out.append_param(out, self.class_of(ty));
698                self.regs[param.index()] = Some(reg);
699                if on_x87(ty) {
700                    arriving.push((param, reg));
701                }
702            }
703            self.settle(block, &arriving)?;
704        }
705
706        // What each instruction matched, and which instructions were folded into another. The
707        // decision is made for the whole block before any of it is written, and it is made more
708        // than once: a value that only some of its readers took has to be put back in a register
709        // for all of them, and taking it away from those readers changes what they match.
710        let insts: Vec<Inst> = self.source.insts(block).collect();
711        let mut refused: HashSet<Value> = HashSet::new();
712        let mut decided = self.decide(&insts, &refused);
713        while let Some(value) = self.left_alive(&insts, &decided.plans) {
714            refused.insert(value);
715            decided = self.decide(&insts, &refused);
716        }
717        let Decided { found, folded, .. } = decided;
718
719        for (&inst, matched) in insts.iter().zip(found) {
720            if folded.contains(&inst) || self.writes_nothing(inst) {
721                continue;
722            }
723            // A call is built from the convention rather than matched, which is why it is the one
724            // opcode looked at by name here. Through an address it is a different instruction and
725            // the same convention, so the two arrive at the same place and differ in one line of
726            // it.
727            match self.source[inst].opcode {
728                Opcode::Call | Opcode::CallIndirect => {
729                    self.called(inst)?;
730                    continue;
731                }
732                // Built from the frame rather than matched, for the same shape of reason a call
733                // is built from the convention: what a rule replaces a term with is instructions,
734                // and what an `alloca` needs first is bytes, which the rule language has no way
735                // to ask for.
736                Opcode::Alloca => {
737                    self.reserve(inst)?;
738                    continue;
739                }
740                // Reading the stack pointer and writing it back, which are the two ends of a scope
741                // holding a variable length array. Built here for the reason an `alloca` is: the
742                // value is a register the rule language has no way to name, because what it holds
743                // is not a value the program computed but where the machine's stack had got to.
744                Opcode::StackSave => {
745                    self.stack_pointer(inst, false)?;
746                    continue;
747                }
748                Opcode::StackRestore => {
749                    self.stack_pointer(inst, true)?;
750                    continue;
751                }
752                // The address of a name, built here for the same reason an `alloca` is: what a
753                // rule replaces a term with is instructions over values, and the operand of this
754                // one is a symbol, which is a thing the rule language has no way to bind and the
755                // solver has no way to say anything about. There is nothing in `lea sym(%rip)` a
756                // proof over bitvectors could discharge, because what makes it the right answer
757                // is the relocation and what the linker does with it.
758                Opcode::GlobalAddr => {
759                    self.address_of(inst)?;
760                    continue;
761                }
762                // Built from the frame for the reason an `alloca` is, and from the convention for
763                // the reason a call is: three of the four fields it writes are distances that do
764                // not exist until the frame does, and the fourth is where the walk over the
765                // argument registers stopped. A function that is not variadic has no such walk to
766                // report, so it has nothing here and is refused below, which is the right answer
767                // for a `va_start` in one.
768                Opcode::VaStart if self.varargs.is_some() => {
769                    self.va_start(inst)?;
770                    continue;
771                }
772                // A return of more than one value, which is a structure small enough to come
773                // back in a pair of registers. Built from the convention for the reason a call
774                // is: which register each half goes in depends on the halves in front of it,
775                // because the two register files are walked separately, and a pattern over a term
776                // cannot see them. A return of one value is a term with a name and a rule, and it
777                // stays one.
778                //
779                // A return of none in a function whose answer went through memory is here too,
780                // and for a different reason: what it gives back is not written in the IR at all.
781                // The convention says the address the caller handed over comes back, and only the
782                // signature says this function was handed one.
783                //
784                // And a return of one eighty bit value, for a third reason: what a rule would
785                // write is an instruction leaving the value in a register, and this one is left on
786                // the x87 stack instead. A rule could not name that stack any more than any other
787                // rule about this type could.
788                Opcode::Return
789                    if self.source[self.source[inst].args].len() > 1
790                        || self.sret().is_some()
791                        || self.gives_back_x87(inst) =>
792                {
793                    self.returned(inst)?;
794                    continue;
795                }
796                // A cast between a pointer and an integer of the same width, which on this
797                // machine is every one the front end writes. No instruction at all, so no rule
798                // could name one.
799                Opcode::PtrToInt | Opcode::IntToPtr => {
800                    self.rename(inst)?;
801                    continue;
802                }
803                // A barrier, which is one instruction or none depending on the ordering. Written
804                // by name because there is nothing about it a rule could be proved against, the
805                // way there is nothing to prove about the address of a symbol.
806                Opcode::Fence => {
807                    self.barrier(inst)?;
808                    continue;
809                }
810                // A compare and exchange, which is written by name because it produces two values
811                // and a rule produces one. The replacement of a rule is one term, a term names the
812                // value an instruction computes, and there is no way in that language to say that
813                // an instruction leaves an answer in one place and a yes or no in another.
814                Opcode::Cmpxchg => {
815                    self.exchange(inst)?;
816                    continue;
817                }
818                // A read modify write, which is written by name for a different reason: it produces
819                // one value, so a rule could name it, and what it does is not in the head a rule
820                // matches on. Every one of the thirteen operations is the same opcode at the same
821                // type and differs only in what is carried beside it, so one pattern would be all
822                // thirteen patterns. Of the thirteen only the three with an instruction reach here,
823                // since `crate::retry` turned the rest into loops a long way above this.
824                Opcode::AtomicRmw => {
825                    self.modify(inst)?;
826                    continue;
827                }
828                // An `asm` statement, whose lowering is its template and there is no term for a
829                // string. Written by name for the reason a barrier is, and before the x87 arm
830                // below so that an `asm` holding a `long double` is refused as the `asm` it is
831                // rather than as an instruction nothing computes.
832                Opcode::InlineAsm => {
833                    self.assembly(inst)?;
834                    continue;
835                }
836                // Anything at all with an eighty bit float in it, which is the one arm here
837                // chosen by a type rather than by an opcode, because what makes these different
838                // is not what they do but where the value is. A `long double` has no register,
839                // so it has no name in `crate::term` and no rule could bind one: every one of
840                // these is a group of instructions over a frame slot, written out below.
841                //
842                // Last of the arms, so that a call and a return with one of these in them reach
843                // the convention first and are refused by it, which is the truer answer: what is
844                // wrong there is where the value has to travel and not that nothing can compute
845                // it.
846                _ if self.touches_x87(inst) => {
847                    self.x87(inst)?;
848                    continue;
849                }
850                _ => {}
851            }
852            let matched = matched.ok_or_else(|| self.unsupported(inst))?;
853            self.emit(inst, &matched)?;
854            // After it is built rather than when it matched, so that what is recorded is the rules
855            // this function was lowered by and not the rules something was tried with.
856            self.fired.mark(matched.rule);
857        }
858        self.edges(block, out)
859    }
860
861    /// One call, which is built from the convention rather than matched against the table for the
862    /// same reason the arguments of the function itself are.
863    ///
864    /// The arguments are read before the call is built, which is what materializes a constant
865    /// argument into a register, since no call passes an immediate.
866    ///
867    /// A call to a name and a call through an address are both here, and what tells them apart is
868    /// the opcode rather than whether a callee was recorded, which is the same thing the verifier
869    /// reads. Through an address the first operand is the address and the arguments are the ones
870    /// behind it, and everything after that is the same: where each argument goes, where the value
871    /// comes back and which registers are gone across it are the convention's answers and the
872    /// convention does not ask what is being called.
873    fn called(&mut self, inst: Inst) -> Result<(), Unsupported> {
874        let data = &self.source[inst];
875        let Extra::Call(info) = data.extra else { return Err(self.unsupported(inst)) };
876        let info = self.source[info];
877        let indirect = data.opcode == Opcode::CallIndirect;
878
879        let values: Vec<Value> = self.source[data.args].to_vec();
880        let callee = if indirect {
881            let &address = values.first().ok_or_else(|| self.unsupported(inst))?;
882            abi::Callee::Through(self.reg_of(address)?)
883        } else {
884            abi::Callee::Named(info.callee.ok_or_else(|| self.unsupported(inst))?)
885        };
886
887        // What the ABI asks of each argument, read out before any of them is, because reading one
888        // borrows the function this is a table in. The ones the signature names are the signature's
889        // answer and the ones behind them are the call's, which is where a structure passed to a
890        // variadic callee by value says that its bytes travel: there is no parameter to say it on.
891        let signature = &self.source[info.signature];
892        let variadic = signature.variadic;
893        let named: Vec<Abi> = signature.params.iter().map(|param| param.abi).collect();
894        let beyond: Vec<Abi> = self.source[info.varargs].to_vec();
895        // Every value that comes back and not only the first. A structure small enough to travel
896        // in registers comes back in up to two of them, and which register each half is in is the
897        // convention's answer, which is why the whole list goes to the same place the arguments do
898        // rather than to a rule.
899        let returns: Vec<Type> = signature.return_types().collect();
900
901        let mut args = Vec::with_capacity(values.len());
902        for (index, value) in values.into_iter().skip(usize::from(indirect)).enumerate() {
903            let abi = named.get(index).or_else(|| beyond.get(index - named.len()));
904            let abi = abi.copied().unwrap_or_default();
905            let ty = self.source[value].ty;
906            // What travels for an eighty bit value is its bytes, so what the call is handed is
907            // where they are rather than a register they are in, and there is no register they
908            // could be in. Everything else about it is a sixteen byte object passed by value and
909            // is built by the same code.
910            let reg =
911                if abi::on_the_stack(ty) { self.x87_slot(value) } else { self.reg_of(value)? };
912            args.push(abi::Passing { ty, reg, abi });
913        }
914        let block = self.at.expect("a block is being filled");
915        let what = abi::Calling { callee, args: &args, returns: &returns, variadic };
916        let made = abi::call(&mut self.out, block, &what, self.conv, self.names)
917            .map_err(|refused| Unsupported::Call { inst, refused })?;
918        let calls = &mut self.stack.calls;
919        *calls = Some(calls.unwrap_or(0).max(made.outgoing));
920        // An eighty bit value came back on the x87 stack, and the one thing that has to happen
921        // before anything else touches that stack is taking it off. So the `fstp` goes here, in
922        // front of everything the block does next, and after it the value is in its slot and is
923        // read the way every other one is.
924        let results: Vec<Value> = self.source[inst].results().collect();
925        if let [result] = results[..] {
926            if abi::on_the_stack(self.source[result].ty) {
927                let span = self.source.span(inst);
928                let into = self.x87_slot(result);
929                let into = self.through(into);
930                self.x87_at("fstp_t", span, into);
931                return Ok(());
932            }
933        }
934        for (result, &reg) in results.into_iter().zip(&made.results) {
935            self.regs[result.index()] = Some(reg);
936        }
937        Ok(())
938    }
939
940    /// The pointer a function returning through memory was handed, or nothing in a function that
941    /// was not.
942    ///
943    /// It is the first parameter and the signature is what says so, since in the IR it is an
944    /// ordinary pointer and reads like one everywhere in the body. A function with a signature
945    /// like that and no entry block has nothing to give back and no body to give it back from.
946    fn sret(&self) -> Option<Value> {
947        let first = self.source.signature().params.first()?;
948        if !matches!(first.abi, Abi::Sret { .. }) {
949            return None;
950        }
951        self.source[self.source.entry()?].params.first().copied()
952    }
953
954    /// One `return` the convention has to write, as the place each value has to be in by the end.
955    ///
956    /// One pseudo per value, each a read constrained to a return register, which is what a return
957    /// of one value already is and is the whole of what either does. The `ret` itself comes from
958    /// the epilogue for both, long after this, because the frame has to be given back first.
959    ///
960    /// The two register files are counted separately, so a structure of a `double` and a `long`
961    /// leaves the `double` in the first vector register and the `long` in the first integer one
962    /// rather than in the second of either. That is the same walk `rucc_codegen::abi` makes on
963    /// the other side of the call, which is what makes the two ends agree.
964    ///
965    /// A function whose answer went through memory gives back the address it was handed, in front
966    /// of nothing else, because a signature that returns that way returns nothing else. That the
967    /// caller already knows the address is not enough: it is allowed to read the register instead,
968    /// and a caller that does gets whatever the allocator last left there. In a leaf function that
969    /// is usually the right answer by accident, and one call in the body is enough to make it a
970    /// wild pointer, which is why this is written rather than left to luck.
971    ///
972    /// Where everything goes is worked out before anything is written, so a return this cannot
973    /// make leaves no half of one behind.
974    /// Whether what a `return` gives back is the one value that goes back on the x87 stack.
975    fn gives_back_x87(&self, inst: Inst) -> bool {
976        let [value] = self.source[self.source[inst].args] else { return false };
977        abi::on_the_stack(self.source[value].ty)
978    }
979
980    fn returned(&mut self, inst: Inst) -> Result<(), Unsupported> {
981        let values: Vec<Value> = self.source[self.source[inst].args].to_vec();
982        let (mut ints, mut floats) = (0usize, 0usize);
983        let mut parts = Vec::with_capacity(values.len() + 1);
984        // An eighty bit value goes back on the x87 stack, which is where the convention says it is
985        // and is the one place a value is left rather than put in a register. So the whole of the
986        // return is an `fld` of its slot, and the stack it leaves the value on is not empty at the
987        // `ret`, which is the one time in this file that is true and is what the convention asks
988        // for. What comes after is the epilogue, which gives the frame back and touches nothing in
989        // the unit.
990        if let [value] = values[..] {
991            let ty = self.source[value].ty;
992            if abi::on_the_stack(ty) && self.sret().is_none() {
993                let span = self.source.span(inst);
994                let from = self.x87_slot(value);
995                let from = self.through(from);
996                self.x87_at("fld_t", span, from);
997                return Ok(());
998            }
999        }
1000        for value in self.sret().into_iter().chain(values) {
1001            let ty = self.source[value].ty;
1002            let at = if crate::term::float_slot(ty).is_some() { &mut floats } else { &mut ints };
1003            // Why it cannot come back, and not only that it cannot. A type that travels nowhere
1004            // says so itself, and a type that travels perfectly well ran out of registers.
1005            let missing = abi::refuses(ty).unwrap_or(Missing::NoRoom);
1006            let name = abi::ret_of(ty, *at).ok_or(Unsupported::Returned { inst, missing })?;
1007            *at += 1;
1008            // The register is the target's answer and not one worked out here, the same as it is
1009            // for a return of one value, so that both halves of a pair and every rule that writes
1010            // half of one are reading the same table.
1011            let opcode = name.strip_prefix(PREFIX).expect("a machine instruction of this target");
1012            let form = x86_64::form(opcode).ok_or_else(|| self.unsupported(inst))?;
1013            let [desc] = form.operands() else { return Err(self.unsupported(inst)) };
1014            parts.push((self.names.intern(name), self.reg_of(value)?, *desc));
1015        }
1016
1017        let block = self.at.expect("a block is being filled");
1018        let span = self.source.span(inst);
1019        for (opcode, reg, desc) in parts {
1020            let operand = mir::Operand {
1021                reg,
1022                class: desc.class,
1023                role: desc.role,
1024                constraint: desc.constraint,
1025            };
1026            self.out.build(block, mir::Opcode::new(opcode)).at(span).operand(operand).finish();
1027        }
1028        Ok(())
1029    }
1030
1031    /// One `alloca`: the bytes it asks for go on the list the frame is laid out from, and the
1032    /// address of them is one instruction.
1033    ///
1034    /// The instruction is a `lea` off the stack pointer, which is the one register that reaches
1035    /// the frame in every function, and its displacement is left at nothing because there is no
1036    /// frame yet. Which instruction is waiting for which local is remembered, and
1037    /// [`crate::finish`] fills the numbers in after [`crate::frame::Frame`] has placed them.
1038    ///
1039    /// There is deliberately no rule for `alloca` and no name for one in [`crate::term`], and
1040    /// that is what stops it being folded into something else. An operand shown as the
1041    /// instruction that computed it is offered to the matcher by its name, so an `alloca` with no
1042    /// name is one no pattern can reach past, and the address it computes is always in a register
1043    /// by the time anything reads it.
1044    fn reserve(&mut self, inst: Inst) -> Result<(), Unsupported> {
1045        let data = &self.source[inst];
1046        // A variable length array carries the size it wants as an operand rather than in the
1047        // instruction, which is the whole of what tells the two apart here.
1048        if let Some(&size) = self.source[data.args].first() {
1049            return self.grow(inst, size);
1050        }
1051        let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
1052        let info = self.source[mem];
1053        let size = u32::try_from(info.size)
1054            .map_err(|_| Unsupported::Dynamic { inst, growing: Growing::Huge })?;
1055        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1056
1057        // At least one, because the frame divides by the alignment and an object with no
1058        // alignment at all is one the front end had nothing to say about rather than one that may
1059        // go anywhere.
1060        let index = self.stack.locals.len();
1061        self.stack.locals.push(Local { size, align: info.align.max(1) });
1062
1063        let block = self.at.expect("a block is being filled");
1064        let reg = self.new_reg(result);
1065        let span = self.source.span(inst);
1066        let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
1067        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
1068        let made =
1069            self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
1070        self.stack.addresses.push((made, index));
1071        Ok(())
1072    }
1073
1074    /// The other kind of `alloca`: one whose size the function does not know until it runs, which
1075    /// is what a variable length array is.
1076    ///
1077    /// Nothing about it is a slot the frame laid out, because the frame is laid out once and this
1078    /// happens as often as control reaches the declaration. The bytes come off the stack pointer
1079    /// where the declaration stands, which is two instructions:
1080    ///
1081    /// ```text
1082    ///   sub sp, bytes     the stack pointer moves down over the memory, which is what takes it
1083    ///   lea reg, [sp+n]   where the memory starts, which is above the outgoing argument area
1084    /// ```
1085    ///
1086    /// The displacement is left at nothing for the reason the constant kind leaves its own at
1087    /// nothing, and for a different number: that area belongs to the arguments of whatever this
1088    /// function calls, it stays at the bottom of the frame wherever the bottom has moved to, and
1089    /// how big it is is not known until every call in the function has been seen.
1090    ///
1091    /// The bytes are already a multiple of the stack pointer's alignment by the time they arrive,
1092    /// because [`crate::expand::rounds`] rounded them up in the IR, so nothing here has to mask the
1093    /// stack pointer afterwards and the stack pointer stays somewhere a call can be made from.
1094    ///
1095    /// Refused for an array wanting more alignment than the convention leaves the stack pointer
1096    /// with. Forcing that would be a second rounding of a register the frame already rounded, and
1097    /// after it no constant reaches the rest of the frame from anywhere. See `Growing` in
1098    /// [`crate::frame`].
1099    fn grow(&mut self, inst: Inst, size: Value) -> Result<(), Unsupported> {
1100        let data = &self.source[inst];
1101        let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
1102        let info = self.source[mem];
1103        if info.align > self.conv.stack_align {
1104            return Err(Unsupported::Dynamic { inst, growing: Growing::Aligned });
1105        }
1106        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1107        let bytes = self.reg_of(size)?;
1108
1109        let block = self.at.expect("a block is being filled");
1110        let span = self.source.span(inst);
1111        let stack = mir::Reg::physical(self.conv.stack_pointer);
1112        let grow = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.grow)));
1113        self.out
1114            .build(block, grow)
1115            .at(span)
1116            .operand(mir::Operand::write(stack, self.gpr))
1117            .operand(mir::Operand::read(stack, self.gpr))
1118            .operand(mir::Operand::read(bytes, self.gpr))
1119            .finish();
1120
1121        let reg = self.new_reg(result);
1122        let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
1123        let sp = mir::Operand::read(stack, self.gpr);
1124        let made =
1125            self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
1126        self.stack.dynamic.push(made);
1127        self.stack.grown_at.get_or_insert(inst);
1128        Ok(())
1129    }
1130
1131    /// Where the stack pointer is, kept so that something later can put it back.
1132    ///
1133    /// One move out of the stack pointer and one move into it, which is the whole of what the two
1134    /// halves are. What makes them worth writing is where the front end puts them: a scope holding
1135    /// a variable length array saves the stack pointer as it opens and puts it back as it closes,
1136    /// so a loop declaring one takes its bytes once round rather than once per iteration, and a
1137    /// jump out of the scope gives the bytes back on the way out.
1138    ///
1139    /// The value travels in an ordinary register the allocator hands out, so it may be spilled like
1140    /// any other, and a spill slot in a frame that grows is reached through the frame pointer,
1141    /// which is exactly the register that still means something after the stack pointer has moved.
1142    fn stack_pointer(&mut self, inst: Inst, into: bool) -> Result<(), Unsupported> {
1143        let data = &self.source[inst];
1144        let block = self.at.expect("a block is being filled");
1145        let span = self.source.span(inst);
1146        let stack = mir::Reg::physical(self.conv.stack_pointer);
1147        let mov = x86_64::FRAME.moves(self.gpr).expect("a class the target says how to move").mov;
1148        let mov = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{mov}")));
1149        let (write, read) = if into {
1150            let &saved = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
1151            (stack, self.reg_of(saved)?)
1152        } else {
1153            let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1154            (self.new_reg(result), stack)
1155        };
1156        self.out
1157            .build(block, mov)
1158            .at(span)
1159            .operand(mir::Operand::write(write, self.gpr))
1160            .operand(mir::Operand::read(read, self.gpr))
1161            .finish();
1162        // Only the write is a move of the stack pointer, and it is the one that makes the frame a
1163        // growing one. A read of it in a function that never writes it back is a function that
1164        // asked where the stack was and did nothing with the answer.
1165        if into {
1166            self.stack.grown_at.get_or_insert(inst);
1167        }
1168        Ok(())
1169    }
1170
1171    /// Whether an instruction has an eighty bit float anywhere in it.
1172    ///
1173    /// Producing one and reading one are the same question here, because what makes one of these
1174    /// different from every other instruction is not the operation but where the value is. A
1175    /// `long double` is on the x87 stack while it is being worked on and in a frame slot the rest
1176    /// of the time, and neither of those is somewhere the operand of a rule could point.
1177    fn touches_x87(&self, inst: Inst) -> bool {
1178        let data = &self.source[inst];
1179        data.results().any(|value| on_x87(self.source[value].ty))
1180            || self.source[data.args].iter().any(|&arg| on_x87(self.source[arg].ty))
1181    }
1182
1183    /// Everything that happens to an eighty bit float, as the group of instructions it is.
1184    ///
1185    /// The first six move one, and every one of those is a load, a store, or a load and a store at
1186    /// two different formats, because that is the whole of what this machine converts with: the
1187    /// x87 has no instruction that turns one thing on its stack into another, so a widening is
1188    /// `fld` of the narrow format and a narrowing is `fstp` of it.
1189    ///
1190    /// The rest work on one, and they are here rather than in a rule for the same reason the six
1191    /// are. An add is a push, a push, the add and a pop, and what passes between those four is the
1192    /// top of a stack nothing allocates from, so there is no value in the middle of the group for
1193    /// a pattern to bind or a replacement to name. The comparison is the same shape with its last
1194    /// two instructions folded into one opcode, which is where the byte it produces comes from.
1195    ///
1196    /// Every group leaves the stack as empty as it found it, which is what `spec/10-backend.md`
1197    /// section 10.8 asks of one and is why nothing in this file has to track a depth: each push
1198    /// below is answered by a pop a line or two later, so no two groups can ever be looking at
1199    /// the same eight registers.
1200    fn x87(&mut self, inst: Inst) -> Result<(), Unsupported> {
1201        match self.source[inst].opcode {
1202            Opcode::Load => self.x87_load(inst),
1203            Opcode::Store => self.x87_store(inst),
1204            Opcode::FPExt => self.x87_widen(inst),
1205            Opcode::FPTrunc => self.x87_narrow(inst),
1206            Opcode::SIToFP => self.x87_from_signed(inst),
1207            Opcode::FPToSI => self.x87_to_signed(inst),
1208            Opcode::FAdd => self.x87_arith(inst, "fadd_p"),
1209            Opcode::FSub => self.x87_arith(inst, "fsubr_p"),
1210            Opcode::FMul => self.x87_arith(inst, "fmul_p"),
1211            Opcode::FDiv => self.x87_arith(inst, "fdivr_p"),
1212            Opcode::FNeg => self.x87_flip(inst),
1213            Opcode::FCmp => self.x87_compare(inst),
1214            Opcode::FConst => self.x87_const(inst),
1215            _ => Err(self.unsupported(inst)),
1216        }
1217    }
1218
1219    /// The eighty bit parameters of a block, copied out of the addresses an edge handed over and
1220    /// into slots of the block's own.
1221    ///
1222    /// What crosses an edge for a value of this type is an address, because the value is sixteen
1223    /// bytes of the frame and no register holds any of it. The block cannot keep that address: a
1224    /// second edge into the same block hands over a second one, and a read after the block would
1225    /// then be a read of whichever edge was taken rather than of one place. So the block has a
1226    /// slot per parameter and the bytes are copied into it here, which is the move on an edge that
1227    /// every other type gets from the allocator.
1228    ///
1229    /// Every load runs before every store and the stores run backwards, so all of the values are
1230    /// on the x87 stack at once and nothing reads a slot another one has already written. That
1231    /// costs nothing in the ordinary case of one parameter and is what makes the back edge of a
1232    /// loop that swaps two of these work. It is also the reason for the limit: the stack is eight
1233    /// deep, and a block with more of these than that is refused rather than copied in an order
1234    /// that could be wrong.
1235    fn settle(&mut self, block: Block, arriving: &[(Value, mir::Reg)]) -> Result<(), Unsupported> {
1236        let Some(&(first, _)) = arriving.first() else { return Ok(()) };
1237        if arriving.len() > X87_DEPTH {
1238            let ty = self.source[first].ty;
1239            return Err(Unsupported::Phi { block, count: arriving.len(), ty });
1240        }
1241        // A block parameter comes from no instruction, so what this points at is the first thing
1242        // in the block, which is where a reader looking for the copy would look.
1243        let first_inst = self.source.insts(block).next();
1244        let span = first_inst.map_or(Span::DUMMY, |it| self.source.span(it));
1245        for &(_, reg) in arriving {
1246            let from = self.through(reg);
1247            self.x87_at("fld_t", span, from);
1248        }
1249        for &(param, _) in arriving.iter().rev() {
1250            let into = self.x87_slot(param);
1251            let into = self.through(into);
1252            self.x87_at("fstp_t", span, into);
1253        }
1254        Ok(())
1255    }
1256
1257    /// The frame slot an eighty bit value lives in, as its address in a fresh register.
1258    ///
1259    /// The slot is the value's for the whole function and is taken the first time somebody asks.
1260    /// The address is worked out again every time, which is a `lea` per use and is deliberate: one
1261    /// address kept in a register from the definition to the last use would hold a general purpose
1262    /// register open across everything in between, and a function with a handful of these in it
1263    /// would spend its registers on addresses of things rather than on things.
1264    fn x87_slot(&mut self, value: Value) -> mir::Reg {
1265        // An argument of the function has a slot already and it is the caller's. The convention
1266        // puts the bytes in the argument area and hands over where they are, so the address that
1267        // arrived is the answer and no second copy of the value is made. Nothing ever writes to a
1268        // value of this type once it exists, so nothing writes to the caller's copy either. A
1269        // parameter of any other block is not this: what arrived there is an address a predecessor
1270        // chose, [`Lowering::settle`] has already copied the bytes out of it, and the slot those
1271        // bytes landed in is the one below.
1272        let entry = self.source.entry();
1273        if let (Def::Param { block, .. }, Some(reg)) =
1274            (self.source[value].def, self.regs[value.index()])
1275        {
1276            if entry == Some(block) {
1277                return reg;
1278            }
1279        }
1280        let index = match self.slots[value.index()] {
1281            Some(index) => index,
1282            None => {
1283                let index = self.stack.locals.len();
1284                self.stack.locals.push(Local { size: X87_BYTES, align: X87_BYTES });
1285                self.slots[value.index()] = Some(index);
1286                index
1287            }
1288        };
1289        let block = self.at.expect("a block is being filled");
1290        self.frame_address(block, index)
1291    }
1292
1293    /// The bytes a value crosses between a register and the x87 stack through, as their address
1294    /// in a fresh register.
1295    fn x87_crossing(&mut self) -> mir::Reg {
1296        let index = match self.crossing {
1297            Some(index) => index,
1298            None => {
1299                let index = self.stack.locals.len();
1300                self.stack.locals.push(Local { size: X87_CROSSING, align: X87_CROSSING });
1301                self.crossing = Some(index);
1302                index
1303            }
1304        };
1305        let block = self.at.expect("a block is being filled");
1306        self.frame_address(block, index)
1307    }
1308
1309    /// The two control words, as the address of the first of them in a fresh register.
1310    fn x87_control(&mut self) -> mir::Reg {
1311        let index = match self.control {
1312            Some(index) => index,
1313            None => {
1314                let index = self.stack.locals.len();
1315                self.stack.locals.push(Local { size: 4, align: 4 });
1316                self.control = Some(index);
1317                index
1318            }
1319        };
1320        let block = self.at.expect("a block is being filled");
1321        self.frame_address(block, index)
1322    }
1323
1324    /// An address held in a register, as the addressing mode that reaches it.
1325    fn through(&self, reg: mir::Reg) -> mir::Mem {
1326        mir::Mem::at(mir::Operand::read(reg, self.gpr))
1327    }
1328
1329    /// One instruction of a group, which names an address and nothing else.
1330    ///
1331    /// Every x87 instruction that moves a value is one of these. What it does to the stack is in
1332    /// the mnemonic rather than in an operand, so there is no register to write down and no
1333    /// register the allocator gets a say in.
1334    fn x87_at(&mut self, name: &str, span: Span, at: mir::Mem) {
1335        let block = self.at.expect("a block is being filled");
1336        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1337        self.out.build(block, opcode).at(span).mem(at).finish();
1338    }
1339
1340    /// One instruction of a group that names nothing at all.
1341    ///
1342    /// The arithmetic is these. Both of an add's operands are already on the stack when it runs
1343    /// and so is where the answer goes, and the stack is not somewhere an instruction says, so
1344    /// `faddp` has an argument in the assembler's syntax and nothing here for the argument to come
1345    /// from. What it works on is which two pushes came before it, which is a fact about the order
1346    /// of the group and is why the group is written in one place.
1347    fn x87_only(&mut self, name: &str, span: Span) {
1348        let block = self.at.expect("a block is being filled");
1349        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1350        self.out.build(block, opcode).at(span).finish();
1351    }
1352
1353    /// A `load` of a `long double`: onto the stack from where it was, and off it into the slot.
1354    ///
1355    /// Two instructions rather than the two general purpose moves the same sixteen bytes would
1356    /// take, because `fld` and `fstp` at this format neither convert nor look: the value goes on
1357    /// in the format it was already in and comes back off in it, so a signalling NaN stays one
1358    /// and nothing is raised. Which is what makes this a copy at all.
1359    fn x87_load(&mut self, inst: Inst) -> Result<(), Unsupported> {
1360        let (args, result) = self.ends(inst)?;
1361        let &address = args.first().ok_or_else(|| self.unsupported(inst))?;
1362        let span = self.source.span(inst);
1363        let from = self.reg_of(address)?;
1364        let from = self.through(from);
1365        let into = self.x87_slot(result);
1366        let into = self.through(into);
1367        self.x87_at("fld_t", span, from);
1368        self.x87_at("fstp_t", span, into);
1369        Ok(())
1370    }
1371
1372    /// A `store` of a `long double`: the same pair the other way round.
1373    fn x87_store(&mut self, inst: Inst) -> Result<(), Unsupported> {
1374        let args = self.source[self.source[inst].args].to_vec();
1375        let [value, address] = args[..] else { return Err(self.unsupported(inst)) };
1376        let span = self.source.span(inst);
1377        let from = self.x87_slot(value);
1378        let from = self.through(from);
1379        let into = self.reg_of(address)?;
1380        let into = self.through(into);
1381        self.x87_at("fld_t", span, from);
1382        self.x87_at("fstp_t", span, into);
1383        Ok(())
1384    }
1385
1386    /// A `float`, a `double` or an integer becoming a `long double`.
1387    ///
1388    /// Through memory, because the x87 reads memory and nothing else: the value is in a register
1389    /// the machine has and the unit has no way to be handed one, so it is written to the crossing
1390    /// bytes and loaded back at the format that widens it. Every one of these is exact. Sixty four
1391    /// bits of significand and fifteen of exponent hold every `float`, every `double` and every
1392    /// sixty four bit integer outright, so none of the four can round and none can raise.
1393    fn x87_across(
1394        &mut self,
1395        inst: Inst,
1396        put: &'static str,
1397        class: RegClass,
1398        get: &'static str,
1399    ) -> Result<(), Unsupported> {
1400        let (args, result) = self.ends(inst)?;
1401        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1402        let span = self.source.span(inst);
1403        let value = self.reg_of(source)?;
1404        let across = self.x87_crossing();
1405        let across = self.through(across);
1406        let into = self.x87_slot(result);
1407        let into = self.through(into);
1408
1409        let block = self.at.expect("a block is being filled");
1410        let store = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{put}")));
1411        self.out.build(block, store).at(span).uses(value, class).mem(across).finish();
1412        self.x87_at(get, span, across);
1413        self.x87_at("fstp_t", span, into);
1414        Ok(())
1415    }
1416
1417    /// A `long double` becoming a `float`, a `double` or an integer.
1418    ///
1419    /// Through memory for the reason above and in the same three instructions backwards. The two
1420    /// that go to a float round to nearest, which is what the control word says unless somebody
1421    /// has changed it and is what C wants. The two that go to an integer do not, which is why they
1422    /// do not come here.
1423    fn x87_back(
1424        &mut self,
1425        inst: Inst,
1426        put: &'static str,
1427        get: &'static str,
1428        class: RegClass,
1429    ) -> Result<(), Unsupported> {
1430        let (args, result) = self.ends(inst)?;
1431        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1432        let span = self.source.span(inst);
1433        let from = self.x87_slot(source);
1434        let from = self.through(from);
1435        let across = self.x87_crossing();
1436        let across = self.through(across);
1437
1438        self.x87_at("fld_t", span, from);
1439        self.x87_at(put, span, across);
1440        let block = self.at.expect("a block is being filled");
1441        let reg = self.new_reg(result);
1442        let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{get}")));
1443        self.out.build(block, load).at(span).def(reg, class).mem(across).finish();
1444        Ok(())
1445    }
1446
1447    /// An `fpext` up to a `long double`, which is the only direction this machine has one in.
1448    fn x87_widen(&mut self, inst: Inst) -> Result<(), Unsupported> {
1449        let sse = self.conv.sse_class;
1450        match self.source[self.narrow(inst)?].ty.bits() {
1451            32 => self.x87_across(inst, "movss_mr", sse, "fld_s"),
1452            64 => self.x87_across(inst, "movsd_mr", sse, "fld_l"),
1453            _ => Err(self.unsupported(inst)),
1454        }
1455    }
1456
1457    /// An `fptrunc` down from a `long double`, which is the other direction of the same.
1458    fn x87_narrow(&mut self, inst: Inst) -> Result<(), Unsupported> {
1459        let sse = self.conv.sse_class;
1460        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
1461        match self.source[result].ty.bits() {
1462            32 => self.x87_back(inst, "fstp_s", "movss_rm", sse),
1463            64 => self.x87_back(inst, "fstp_l", "movsd_rm", sse),
1464            _ => Err(self.unsupported(inst)),
1465        }
1466    }
1467
1468    /// A `sitofp` up to a `long double`.
1469    ///
1470    /// Thirty two bits and sixty four, and nothing narrower, because C widens an integer to `int`
1471    /// before it converts one and the front end writes that widening down. An unsigned integer is
1472    /// not here at all: `fild` reads its operand as signed, so a value above the signed range
1473    /// comes back short by two to the sixty fourth and has to be added back, which is arithmetic
1474    /// rather than a move and waits with the rest of it.
1475    fn x87_from_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
1476        let gpr = self.gpr;
1477        match self.source[self.narrow(inst)?].ty.bits() {
1478            32 => self.x87_across(inst, "mov_mr_32", gpr, "fild_l"),
1479            64 => self.x87_across(inst, "mov_mr_64", gpr, "fild_ll"),
1480            _ => Err(self.unsupported(inst)),
1481        }
1482    }
1483
1484    /// An `fptosi` down from a `long double`, which is the one conversion here with no single
1485    /// instruction behind it.
1486    ///
1487    /// C cuts towards zero and the unit rounds the way its control word says, so the store that
1488    /// takes the value off the stack is wrapped in the control word being saved, changed and put
1489    /// back. Five instructions around the one that does the work, and three more moving the word
1490    /// through a register, because this machine has no way to OR a constant into memory at this
1491    /// width. The unit has a shorter answer in `fisttp`, and `spec/10-backend.md` section 10.8
1492    /// says why it is not used: it is SSE3, the x86-64 baseline is not, and there is nothing here
1493    /// that can gate an instruction on a feature yet.
1494    fn x87_to_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
1495        let (args, result) = self.ends(inst)?;
1496        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1497        let (put, get) = match self.source[result].ty.bits() {
1498            32 => ("fistp_l", "mov_rm_32"),
1499            64 => ("fistp_ll", "mov_rm_64"),
1500            _ => return Err(self.unsupported(inst)),
1501        };
1502        let span = self.source.span(inst);
1503        let gpr = self.gpr;
1504        let from = self.x87_slot(source);
1505        let from = self.through(from);
1506        let across = self.x87_crossing();
1507        let across = self.through(across);
1508        let control = self.x87_control();
1509        let saved = self.through(control).plus(0);
1510        let cut = self.through(control).plus(2);
1511
1512        // The word the unit has now, into the first of the two slots and into a register, with the
1513        // rounding field turned to truncate on the way to the second.
1514        self.x87_at("fnstcw", span, saved);
1515        let block = self.at.expect("a block is being filled");
1516        let was = self.out.new_vreg(gpr);
1517        let read = mir::Opcode::new(self.names.intern("x64.mov_rm_16"));
1518        self.out.build(block, read).at(span).def(was, gpr).mem(saved).finish();
1519        let now = self.out.new_vreg(gpr);
1520        let set = mir::Opcode::new(self.names.intern("x64.or_ri_16"));
1521        // Two address, which is written out here rather than taken from the two shorthands
1522        // because the shorthands leave an operand unconstrained: this machine ORs into the
1523        // register it read, so the two have to be the same one and only the constraint says so.
1524        self.out
1525            .build(block, set)
1526            .at(span)
1527            .operand(mir::Operand::write(now, gpr).with(Constraint::Reuse(1)))
1528            .operand(mir::Operand::read(was, gpr))
1529            .imm(X87_TRUNCATE)
1530            .finish();
1531        let write = mir::Opcode::new(self.names.intern("x64.mov_mr_16"));
1532        self.out.build(block, write).at(span).uses(now, gpr).mem(cut).finish();
1533
1534        // The conversion itself, under the changed word, and then the word the unit had put back
1535        // before anything else runs.
1536        self.x87_at("fldcw", span, cut);
1537        self.x87_at("fld_t", span, from);
1538        self.x87_at(put, span, across);
1539        self.x87_at("fldcw", span, saved);
1540
1541        let block = self.at.expect("a block is being filled");
1542        let reg = self.new_reg(result);
1543        let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{get}")));
1544        self.out.build(block, load).at(span).def(reg, gpr).mem(across).finish();
1545        Ok(())
1546    }
1547
1548    /// A constant of this type, as the bits of it written into its slot.
1549    ///
1550    /// No x87 instruction at all, which is the surprise here. A slot holding an eighty bit value is
1551    /// the value, so a constant is ten bytes put where the value lives, and the unit never has to
1552    /// see it: whatever reads it will `fld` it out of the slot the way it reads any other one.
1553    ///
1554    /// Ten bytes in two goes, because the machine stores eight at a time and there is no store of
1555    /// an immediate to memory, so each half is put in a register first. The six bytes above the ten
1556    /// are left alone, since nothing reads them: they are the padding that makes the type sixteen
1557    /// wide and they are unspecified in the psABI rather than zero.
1558    ///
1559    /// The other way is a constant pool, an `fldt` of a symbol, and a relocation, which is what a
1560    /// compiler with somewhere to put a literal does. This back end has nowhere to put one yet, and
1561    /// four instructions in the frame is what that costs until it does.
1562    fn x87_const(&mut self, inst: Inst) -> Result<(), Unsupported> {
1563        let Extra::Imm(imm) = self.source[inst].extra else { return Err(self.unsupported(inst)) };
1564        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
1565        let bits = self.source[imm].bits();
1566        let span = self.source.span(inst);
1567        let gpr = self.gpr;
1568        let slot = self.x87_slot(result);
1569        let low = self.through(slot).plus(0);
1570        let high = self.through(slot).plus(8);
1571
1572        let block = self.at.expect("a block is being filled");
1573        for (bytes, at, into) in
1574            [(bits as u64 as i64, low, "64"), (((bits >> 64) & 0xffff) as i64, high, "16")]
1575        {
1576            let held = self.out.new_vreg(gpr);
1577            let put = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_ri_{into}")));
1578            self.out.build(block, put).at(span).def(held, gpr).imm(bytes).finish();
1579            let store = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_mr_{into}")));
1580            self.out.build(block, store).at(span).uses(held, gpr).mem(at).finish();
1581        }
1582        Ok(())
1583    }
1584
1585    /// One arithmetic instruction on two eighty bit values, as the four it takes.
1586    ///
1587    /// The left operand is pushed first and the right one on top of it, so the left ends up
1588    /// underneath and the answer wanted is the one below against the top in that order. Which of
1589    /// the two mnemonics computes that is a question about the spelling rather than about the
1590    /// machine, and the two spellings disagree. Intel's `FSUBP ST(i), ST(0)` is `ST(i) - ST(0)`
1591    /// and is `DE E8+i`, and AT&T's `fsubp` is `DE E0+i`, which is the other subtraction. This
1592    /// compiler writes AT&T and encodes what gas encodes, so what it asks for here is `fsubr_p`
1593    /// and `fdivr_p`, and the `r` is not a reversal of anything the code generator decided.
1594    ///
1595    /// An addition and a multiplication have one form each and do not care, which is why a test
1596    /// that reads the mnemonic back would not have caught this and one that computes a subtraction
1597    /// and checks the answer does.
1598    ///
1599    /// The answer is left where the deeper of the two was and the shallower is gone, which is what
1600    /// the `p` on the mnemonic means, so one push has already been paid back by the time the
1601    /// `fstp` runs and the stack is level again after it.
1602    ///
1603    /// Nothing here is folded and nothing is reused. Two values that are the same value get two
1604    /// pushes of the same slot, and an operand that was just computed is read back out of the slot
1605    /// it was written to rather than left on the stack, which costs a store and a load per
1606    /// instruction in an expression. Keeping a partial result on the stack across the next
1607    /// instruction's operands means knowing how deep the stack is at every point in the block, and
1608    /// that is a different thing from writing a group.
1609    fn x87_arith(&mut self, inst: Inst, with: &'static str) -> Result<(), Unsupported> {
1610        let (args, result) = self.ends(inst)?;
1611        let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
1612        let span = self.source.span(inst);
1613        let left = self.x87_slot(left);
1614        let left = self.through(left);
1615        let right = self.x87_slot(right);
1616        let right = self.through(right);
1617        let into = self.x87_slot(result);
1618        let into = self.through(into);
1619        self.x87_at("fld_t", span, left);
1620        self.x87_at("fld_t", span, right);
1621        self.x87_only(with, span);
1622        self.x87_at("fstp_t", span, into);
1623        Ok(())
1624    }
1625
1626    /// A negation, which is a push, the sign bit turned over and a pop.
1627    ///
1628    /// `fchs` does not read the value as a number, so this is right for a zero, for an infinity
1629    /// and for a NaN, and it raises nothing on any of them. Which is what C asks of a negation and
1630    /// is not what subtracting from zero would give: `0.0L - x` is a different answer at a
1631    /// negative zero and a signalling one at a NaN.
1632    fn x87_flip(&mut self, inst: Inst) -> Result<(), Unsupported> {
1633        let (args, result) = self.ends(inst)?;
1634        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1635        let span = self.source.span(inst);
1636        let from = self.x87_slot(source);
1637        let from = self.through(from);
1638        let into = self.x87_slot(result);
1639        let into = self.through(into);
1640        self.x87_at("fld_t", span, from);
1641        self.x87_only("fchs", span);
1642        self.x87_at("fstp_t", span, into);
1643        Ok(())
1644    }
1645
1646    /// A comparison of two eighty bit values, as the two pushes and the one opcode that reads them.
1647    ///
1648    /// The right operand is pushed first and the left one on top of it, which is the other way
1649    /// round from the arithmetic and is because `fucomip` asks about the top against what is under
1650    /// it: the comparison this machine can do is the top's, so the value the predicate is about
1651    /// has to be the top. The pop that gets the loser off the stack and the byte that reads the
1652    /// flags are both inside the opcode, since what passes between those and the comparison is the
1653    /// flags and the flags are not something anything here can name.
1654    ///
1655    /// Which of the ten opcodes, and which way round, is the same table the vector comparisons
1656    /// match against in `rules/x86-64.rules`, and it has to stay the same table: a predicate that
1657    /// picked a different condition here than there would be a `long double` comparison that
1658    /// disagreed with the `double` comparison of the same two numbers, which is the one thing a
1659    /// wider format is not allowed to do.
1660    ///
1661    /// The always false and the always true are refused rather than folded into a constant,
1662    /// because a comparison this machine never has to do is one the optimizer should have removed
1663    /// and an instruction here that quietly agreed with it would hide that it did not.
1664    fn x87_compare(&mut self, inst: Inst) -> Result<(), Unsupported> {
1665        let Extra::FloatPred(pred) = self.source[inst].extra else {
1666            return Err(self.unsupported(inst));
1667        };
1668        let (args, result) = self.ends(inst)?;
1669        let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
1670        // Two of the fourteen need a second byte and an instruction to put the two together,
1671        // because they are two conditions at once: an ordered equal is equal and not unordered,
1672        // and an unordered not equal is either. The opcode carries all of that and says here only
1673        // that it writes somewhere else as well.
1674        let (name, reversed, both) = match pred {
1675            FloatPred::Ogt => ("fucomip_set_a", false, false),
1676            FloatPred::Oge => ("fucomip_set_ae", false, false),
1677            FloatPred::Olt => ("fucomip_set_a", true, false),
1678            FloatPred::Ole => ("fucomip_set_ae", true, false),
1679            FloatPred::One => ("fucomip_set_ne", false, false),
1680            FloatPred::Ord => ("fucomip_set_np", false, false),
1681            FloatPred::Uno => ("fucomip_set_p", false, false),
1682            FloatPred::Ueq => ("fucomip_set_e", false, false),
1683            FloatPred::Ult => ("fucomip_set_b", false, false),
1684            FloatPred::Ule => ("fucomip_set_be", false, false),
1685            FloatPred::Ugt => ("fucomip_set_b", true, false),
1686            FloatPred::Uge => ("fucomip_set_be", true, false),
1687            FloatPred::Oeq => ("fucomip_set_e_and_np", false, true),
1688            FloatPred::Une => ("fucomip_set_ne_or_p", false, true),
1689            FloatPred::False | FloatPred::True => return Err(self.unsupported(inst)),
1690        };
1691        let (top, under) = if reversed { (right, left) } else { (left, right) };
1692
1693        let span = self.source.span(inst);
1694        let gpr = self.gpr;
1695        let under = self.x87_slot(under);
1696        let under = self.through(under);
1697        let top = self.x87_slot(top);
1698        let top = self.through(top);
1699        self.x87_at("fld_t", span, under);
1700        self.x87_at("fld_t", span, top);
1701
1702        let block = self.at.expect("a block is being filled");
1703        let reg = self.new_reg(result);
1704        // Taken before the instruction is started rather than inside it, since both come from the
1705        // same function being built and only one thing at a time may be adding to it.
1706        let spare = both.then(|| self.out.new_vreg(gpr));
1707        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1708        let mut build = self.out.build(block, opcode).at(span).def(reg, gpr);
1709        if let Some(spare) = spare {
1710            build = build.def(spare, gpr);
1711        }
1712        build.finish();
1713        Ok(())
1714    }
1715
1716    /// The operands and the one result of an instruction that has exactly one.
1717    fn ends(&self, inst: Inst) -> Result<(&'a [Value], Value), Unsupported> {
1718        let data = &self.source[inst];
1719        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1720        Ok((&self.source[data.args], result))
1721    }
1722
1723    /// The operand of a conversion, which is the end of it that is not the `long double`.
1724    fn narrow(&self, inst: Inst) -> Result<Value, Unsupported> {
1725        let args = &self.source[self.source[inst].args];
1726        args.first().copied().ok_or_else(|| self.unsupported(inst))
1727    }
1728
1729    /// One `va_start`, as the four fields of the list it was handed.
1730    ///
1731    /// Two of them are numbers this already knows, and each costs an instruction to put in a
1732    /// register before it can be stored, because the machine here has no store of an immediate to
1733    /// memory. The other two are addresses in the frame, and each is a `lea` [`crate::finish`]
1734    /// finishes: the save area is one of the function's own stack objects, and the caller's
1735    /// argument area is where the parameters that had no register came from, which is the same
1736    /// place and the same fixup a parameter past the sixth already uses.
1737    ///
1738    /// What is written is exactly the four fields [`crate::varargs`] describes, in the order they
1739    /// are laid out, so that reading this beside that table is the whole of the check.
1740    fn va_start(&mut self, inst: Inst) -> Result<(), Unsupported> {
1741        let Some(&list) = self.source[self.source[inst].args].first() else {
1742            return Err(self.unsupported(inst));
1743        };
1744        let started = self.varargs.ok_or_else(|| self.unsupported(inst))?;
1745        let list = self.reg_of(list)?;
1746        let block = self.at.expect("a block is being filled");
1747        let span = self.source.span(inst);
1748
1749        for (at, count) in
1750            [(varargs::GP_OFFSET, started.integers), (varargs::FP_OFFSET, started.floats)]
1751        {
1752            let held = self.out.new_vreg(self.gpr);
1753            let load = mir::Opcode::new(self.names.intern("x64.mov_ri_32"));
1754            self.out.build(block, load).at(span).def(held, self.gpr).imm(i64::from(count)).finish();
1755
1756            let store = mir::Opcode::new(self.names.intern("x64.mov_mr_32"));
1757            let mem = self.field(list, at);
1758            self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
1759        }
1760
1761        // The first argument the signature did not name, which is as far up the caller's argument
1762        // area as the ones it did name reached. Nothing here knows where that area is, so the
1763        // distance is recorded the way a parameter read out of it is and finished with it.
1764        let overflow = self.out.new_vreg(self.gpr);
1765        let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
1766        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
1767        let made = self
1768            .out
1769            .build(block, lea)
1770            .at(span)
1771            .def(overflow, self.gpr)
1772            .mem(mir::Mem::at(sp))
1773            .finish();
1774        self.stack.arguments.push((made, started.incoming));
1775
1776        let save = self.frame_address(block, started.save);
1777        for (at, held) in [(varargs::OVERFLOW, overflow), (varargs::SAVE_AREA, save)] {
1778            let store = mir::Opcode::new(self.names.intern("x64.mov_mr_64"));
1779            let mem = self.field(list, at);
1780            self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
1781        }
1782        Ok(())
1783    }
1784
1785    /// One field of a list, as the addressing mode that reaches it.
1786    fn field(&self, list: mir::Reg, at: i64) -> mir::Mem {
1787        let base = mir::Operand::read(list, self.gpr);
1788        mir::Mem::at(base).plus(i32::try_from(at).expect("a field of a list is a small offset"))
1789    }
1790
1791    /// The address of a name: one `lea` off the instruction pointer, with the name on it.
1792    ///
1793    /// The same instruction an `alloca` gets and for a related reason. An address that is not in
1794    /// the program is a `lea` of an addressing mode that names no register, and the mode carries
1795    /// the symbol so that [`rucc_asm`] can write it relative to `%rip` and leave the relocation
1796    /// for the assembler. Both halves of that already existed: the printer writes `sym(%rip)` and
1797    /// the encoder emits the relocation, because a call to a name the file does not define needed
1798    /// them first.
1799    ///
1800    /// One `mov` and not one `lea` when the name is one [`Elsewhere`] holds, because the distance
1801    /// the `lea` adds to the instruction pointer is a number only a link that puts the name in
1802    /// this program can work out, and the address of a function this file merely declares is not
1803    /// such a number. The load reads the address out of the slot the linker fills in instead. The
1804    /// linker turns it back into the `lea` when the name turns out to have been here all along,
1805    /// so this is not slower in the case that was already right.
1806    ///
1807    /// There is deliberately no name for this in [`crate::term`], which is what stops the address
1808    /// being folded into the instruction that reads it. Folding it is the right thing to do and
1809    /// is what turns a load of a global from two instructions into one, but it is a separate
1810    /// question about addressing modes and issue #282 is it. Until then the address is in a
1811    /// register before anything uses it, which is correct and one instruction longer.
1812    ///
1813    /// What this does not do is give the name anything to refer to. A module carries its globals
1814    /// and nothing writes them out, so a file that defines the variable it reads compiles to a
1815    /// reference the linker cannot resolve. Issue #293 is the other half.
1816    fn address_of(&mut self, inst: Inst) -> Result<(), Unsupported> {
1817        let data = &self.source[inst];
1818        let Extra::Symbol(symbol) = data.extra else { return Err(self.unsupported(inst)) };
1819        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1820
1821        let block = self.at.expect("a block is being filled");
1822        let reg = self.new_reg(result);
1823        let span = self.source.span(inst);
1824        let (mnemonic, mem) = if self.elsewhere.holds(symbol) {
1825            (GOT_LOAD, mir::Mem::got(symbol))
1826        } else {
1827            (x86_64::FRAME.lea, mir::Mem::of(symbol))
1828        };
1829        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{mnemonic}")));
1830        self.out.build(block, opcode).at(span).def(reg, self.gpr).mem(mem).finish();
1831        Ok(())
1832    }
1833
1834    /// A conversion that converts nothing: the result is the operand under another type.
1835    ///
1836    /// `ptrtoint` and `inttoptr` at one width are the whole of this. An address on this machine is
1837    /// an integer as wide as the machine addresses, so a cast between the two changes what the
1838    /// type system calls the value and changes nothing about the value, and the register holding
1839    /// it is the register that already held it. The front end never writes either of them at any
1840    /// other width, because it widens or narrows around the cast rather than through it, so the
1841    /// two widths disagreeing here means the IR came from somewhere else and is refused rather
1842    /// than guessed at.
1843    ///
1844    /// Reading the operand first is what materializes it when it is a constant, which is the case
1845    /// that matters: a null pointer is an `inttoptr` of zero, and that zero has to reach a
1846    /// register before anything can call it an address.
1847    fn rename(&mut self, inst: Inst) -> Result<(), Unsupported> {
1848        let data = &self.source[inst];
1849        let [arg] = self.source[data.args] else { return Err(self.unsupported(inst)) };
1850        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1851        if !self.is_address_width(self.source[arg].ty)
1852            || !self.is_address_width(self.source[result].ty)
1853        {
1854            return Err(self.unsupported(inst));
1855        }
1856        let reg = self.reg_of(arg)?;
1857        self.regs[result.index()] = Some(reg);
1858        Ok(())
1859    }
1860
1861    /// One barrier, which on this machine is one instruction at the strongest ordering and no
1862    /// instruction at all at every other one.
1863    ///
1864    /// x86-64 is total store order, so the only reordering the machine does is a store followed by
1865    /// a load of a different address, and the only ordering that forbids that is sequential
1866    /// consistency. An acquire, a release and an acquire release fence are therefore already true
1867    /// of every program running here, and what a program wanted from writing one is that the
1868    /// compiler not move memory accesses across it. The optimizer has finished by the time this
1869    /// runs and nothing below reorders one access past another, so the constraint is already
1870    /// discharged and there is nothing to write.
1871    ///
1872    /// The strongest one is `mfence`, which is what gcc 16.2.0 writes for
1873    /// `__atomic_thread_fence(__ATOMIC_SEQ_CST)` and for `__sync_synchronize`. A locked instruction
1874    /// on the stack is faster on most parts and is what some compilers write instead; it is also a
1875    /// write to memory the program did not ask for, and the plain barrier is the one that says what
1876    /// it means.
1877    ///
1878    /// Written here by name rather than by a rule, for the same reason a `lea` of a symbol is:
1879    /// there is nothing in a barrier that a proof over bitvectors could discharge. It computes
1880    /// nothing, so there is no equality to state, and what makes it the right answer is the memory
1881    /// model, which the rule language cannot talk about.
1882    fn barrier(&mut self, inst: Inst) -> Result<(), Unsupported> {
1883        let Extra::Order(order) = self.source[inst].extra else {
1884            return Err(self.unsupported(inst));
1885        };
1886        if order != MemOrder::SeqCst {
1887            return Ok(());
1888        }
1889        let block = self.at.expect("a block is being filled");
1890        let span = self.source.span(inst);
1891        let fence = mir::Opcode::new(self.names.intern("x64.mfence"));
1892        self.out.build(block, fence).at(span).finish();
1893        Ok(())
1894    }
1895
1896    /// One compare and exchange, which is the instruction every other atomic on this machine is
1897    /// built out of.
1898    ///
1899    /// What the IR asks for is: read what is at an address, compare it against a value the program
1900    /// expected, put a second value there if the two were equal, and say both what was read and
1901    /// whether the exchange happened. The machine has exactly that instruction, and the `lock` in
1902    /// front of it is what makes the whole of it one step as far as every other processor is
1903    /// concerned.
1904    ///
1905    /// The ordering is not read here, and that is the memory model rather than an omission. A
1906    /// locked instruction on x86-64 is a full barrier whatever the program asked for, so a relaxed
1907    /// compare and exchange and a sequentially consistent one are the same instruction, and there
1908    /// is nothing weaker to emit for the weaker orderings. The failure ordering is not read for the
1909    /// same reason.
1910    ///
1911    /// The two values it produces are why this is written by name. The one the program compares
1912    /// against and the one it gets back are both `rax`, which the instruction reads and writes
1913    /// without being told, and the table says so with a fixed constraint at each end rather than
1914    /// leaving the allocator to find out. The second value is the byte behind it, which is the zero
1915    /// flag read out by a `sete`, and it is a definition of the same instruction so that the
1916    /// allocator knows the two are live together and never gives the byte the register the answer
1917    /// is in.
1918    fn exchange(&mut self, inst: Inst) -> Result<(), Unsupported> {
1919        let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
1920        let results: Vec<Value> = self.source[inst].results().collect();
1921        let [addr, expected, desired] = args[..] else { return Err(self.unsupported(inst)) };
1922        let [old, exchanged] = results[..] else { return Err(self.unsupported(inst)) };
1923
1924        // A value the machine can compare in one instruction, which is an integer or an address at
1925        // one of the four widths it has a compare and exchange for. Anything else is a type this
1926        // has no instruction for rather than a program that is wrong, and the front end refuses it
1927        // before ever getting here.
1928        let ty = self.source[old].ty;
1929        let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
1930        if (!ty.is_int() && !ty.is_ptr()) || !matches!(bits, 8 | 16 | 32 | 64) {
1931            return Err(self.unsupported(inst));
1932        }
1933
1934        let base = self.reg_of(addr)?;
1935        let want = self.reg_of(expected)?;
1936        let put = self.reg_of(desired)?;
1937        let got = self.new_reg(old);
1938        let flag = self.new_reg(exchanged);
1939
1940        let name = format!("cmpxchg_{bits}");
1941        let form = x86_64::form(&name).ok_or_else(|| self.unsupported(inst))?;
1942        let block = self.at.expect("a block is being filled");
1943        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1944        let mut build = self.out.build(block, opcode).at(self.source.span(inst));
1945        for (desc, reg) in form.operands().iter().zip([got, flag, want, put]) {
1946            let operand = mir::Operand {
1947                reg,
1948                class: desc.class,
1949                role: desc.role,
1950                constraint: desc.constraint,
1951            };
1952            build = build.operand(operand);
1953        }
1954        build.mem(mir::Mem::at(mir::Operand::read(base, self.gpr))).finish();
1955        Ok(())
1956    }
1957
1958    /// One read modify write, for the three operations this machine does in a single instruction.
1959    ///
1960    /// What the IR asks for is: read what is at an address, do something to it, put the answer back,
1961    /// say what was there before, and let nothing get between the three steps. The machine has
1962    /// `xchg` for putting a value there and `lock xadd` for adding one, and both leave what they
1963    /// found in the register the operand arrived in, which is why the value that comes back and the
1964    /// value that went in are one register here.
1965    ///
1966    /// A subtraction is the add over the negated operand, which is right at every width because the
1967    /// machine's arithmetic wraps and negating then adding is subtracting in two's complement
1968    /// whatever the operands were. The negate is a separate instruction in front, over a register of
1969    /// its own, so that the value the program handed over is not the one written on: an operand may
1970    /// be live after this and a program that read it again would read the negation.
1971    ///
1972    /// The ordering is not read, for the reason the compare and exchange beside this does not read
1973    /// it. `xchg` with memory locks the bus whether it is asked to or not and `lock xadd` is asked
1974    /// to, so both are full barriers on this machine and there is nothing weaker to fall to.
1975    ///
1976    /// Eight of the other ten never arrive, because `crate::retry` turned each of them into a loop
1977    /// around a compare and exchange before anything here saw it. The two that do arrive are the
1978    /// ones on floating values, and they are refused: a compare and exchange of a float wants the
1979    /// value carried through an integer of the same width, and an eighty bit float has no such
1980    /// width. Neither family of builtins can write one yet either, so a program that reaches this
1981    /// refusal is a program that reached an unimplemented builtin first.
1982    fn modify(&mut self, inst: Inst) -> Result<(), Unsupported> {
1983        let Extra::Rmw(op, _) = self.source[inst].extra else {
1984            return Err(self.unsupported(inst));
1985        };
1986        let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
1987        let [addr, operand] = args[..] else { return Err(self.unsupported(inst)) };
1988        let old = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
1989
1990        // A value the machine can exchange in one instruction, which is an integer at one of the
1991        // four widths it has these for. A pointer arrives as an address, so it is an integer by the
1992        // time it is here, and anything else is a type this has no instruction for.
1993        let ty = self.source[old].ty;
1994        if !ty.is_int() || !matches!(ty.bits(), 8 | 16 | 32 | 64) {
1995            return Err(self.unsupported(inst));
1996        }
1997        let name = match op {
1998            RmwOp::Xchg => format!("xchg_{}", ty.bits()),
1999            RmwOp::Add | RmwOp::Sub => format!("xadd_{}", ty.bits()),
2000            _ => return Err(self.unsupported(inst)),
2001        };
2002
2003        let base = self.reg_of(addr)?;
2004        let mut put = self.reg_of(operand)?;
2005        let block = self.at.expect("a block is being filled");
2006        let span = self.source.span(inst);
2007        if op == RmwOp::Sub {
2008            let negated = self.out.new_vreg(self.gpr);
2009            let negate =
2010                mir::Opcode::new(self.names.intern(&format!("{PREFIX}neg_r_{}", ty.bits())));
2011            let form = x86_64::form(&format!("neg_r_{}", ty.bits()))
2012                .ok_or_else(|| self.unsupported(inst))?;
2013            let mut build = self.out.build(block, negate).at(span);
2014            for (desc, reg) in form.operands().iter().zip([negated, put]) {
2015                build = build.operand(mir::Operand {
2016                    reg,
2017                    class: desc.class,
2018                    role: desc.role,
2019                    constraint: desc.constraint,
2020                });
2021            }
2022            build.finish();
2023            put = negated;
2024        }
2025
2026        let got = self.new_reg(old);
2027        let form = x86_64::form(&name).ok_or_else(|| self.unsupported(inst))?;
2028        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
2029        let mut build = self.out.build(block, opcode).at(span);
2030        for (desc, reg) in form.operands().iter().zip([got, put]) {
2031            build = build.operand(mir::Operand {
2032                reg,
2033                class: desc.class,
2034                role: desc.role,
2035                constraint: desc.constraint,
2036            });
2037        }
2038        build.mem(mir::Mem::at(mir::Operand::read(base, self.gpr))).finish();
2039        Ok(())
2040    }
2041
2042    /// One `asm` statement, for as long as its template has no instructions in it.
2043    ///
2044    /// An empty template is most of the inline assembly in a test suite, and it is not a corner
2045    /// case somebody wrote by accident. A program that wants a value computed where it stands, or a
2046    /// loop the optimizer must not touch, writes `asm volatile ("" : : : "memory")`, and forty
2047    /// years of bug reports about optimizers are full of them. What such a statement asks for is
2048    /// the barrier and the operand places, and no instructions at all.
2049    ///
2050    /// So the instructions are the easy half here and there are none of them. The half that is
2051    /// real is the operands: a constraint says where a value has to be, and where it has to be is
2052    /// still true when the template between them is empty.
2053    ///
2054    /// What the constraints ask for, on an empty template, is only ever that two operands share a
2055    /// place. Nothing reads a register no text names, so `"r"` on its own asks for a register and
2056    /// no particular one, and any register at all answers it. A matching constraint is different,
2057    /// because it says the output the assembly leaves is the place the input arrived in, and with
2058    /// no instructions between them that is the input unchanged. So it is a rename and not a move:
2059    /// the value is already in a register and the result is that register.
2060    ///
2061    /// An output nothing is tied to is whatever the assembly left there, which for a template that
2062    /// writes nothing is whatever was in the register. That is a value the program is not entitled
2063    /// to, and this writes a zero rather than reading one, because the allocator has to be given a
2064    /// definition before a use whatever the program is entitled to.
2065    ///
2066    /// The clobber list is not read, and on an empty template that is right rather than an
2067    /// omission. A clobber says the assembly ruins a register, and a template with no instructions
2068    /// in it ruins nothing.
2069    fn assembly(&mut self, inst: Inst) -> Result<(), Unsupported> {
2070        let data = &self.source[inst];
2071        let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
2072        let info = self.source[asm];
2073        if !self.source[info.targets].is_empty() {
2074            return Err(Unsupported::Assembly { inst, refused: Written::Goto });
2075        }
2076        if !self.names.resolve(info.template).trim().is_empty() {
2077            return Err(Unsupported::Assembly { inst, refused: Written::Template });
2078        }
2079
2080        let constraints = self.names.resolve(info.constraints).to_string();
2081        let results: Vec<Value> = data.results().collect();
2082        let operands = AsmOperands::read(&constraints, &results, &self.source[data.args])
2083            .ok_or(Unsupported::Assembly { inst, refused: Written::Operand })?;
2084
2085        for (index, operand) in operands.iter().copied().enumerate().collect::<Vec<_>>() {
2086            let Some(result) = operand.result else { continue };
2087            let ty = self.source[result].ty;
2088            if on_x87(ty) {
2089                return Err(Unsupported::Assembly { inst, refused: Written::Operand });
2090            }
2091            match operands.tied_to(index) {
2092                // The place the input arrived in, which the assembly wrote nothing over.
2093                Some(from) => {
2094                    if self.class_of(self.source[from].ty) != self.class_of(ty) {
2095                        return Err(Unsupported::Assembly { inst, refused: Written::Operand });
2096                    }
2097                    let reg = self.reg_of(from)?;
2098                    self.regs[result.index()] = Some(reg);
2099                }
2100                None => self.undefined(inst, result)?,
2101            }
2102        }
2103        Ok(())
2104    }
2105
2106    /// A register holding a value the program has no claim on, written as a zero.
2107    ///
2108    /// Every other way of saying it costs the same instruction or needs a word the machine IR does
2109    /// not have, and a zero is the one that reads the same on every run.
2110    fn undefined(&mut self, inst: Inst, result: Value) -> Result<(), Unsupported> {
2111        let ty = self.source[result].ty;
2112        let refused = Unsupported::Assembly { inst, refused: Written::Operand };
2113        if self.class_of(ty) != self.gpr || !matches!(ty.bits(), 8 | 16 | 32 | 64) {
2114            return Err(refused);
2115        }
2116        let block = self.at.expect("a block is being filled");
2117        let span = self.source.span(inst);
2118        let reg = self.new_reg(result);
2119        let put = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_ri_{}", ty.bits())));
2120        self.out.build(block, put).at(span).def(reg, self.gpr).imm(0).finish();
2121        Ok(())
2122    }
2123
2124    /// Whether a type is the width an address is, which is what makes a cast to or from one free.
2125    fn is_address_width(&self, ty: Type) -> bool {
2126        ty.is_ptr() || (ty.is_int() && ty.bits() == ADDRESS_BITS)
2127    }
2128
2129    /// Where a block goes, which in machine IR is on the block rather than on its terminator.
2130    ///
2131    /// That is why no rule ever names a block: a branch is selected for what it reads and the
2132    /// edges are copied across here, arguments and all. The arguments are read last, after every
2133    /// instruction of the block is written, because an argument that is a constant is
2134    /// materialized where it is first wanted and the end of the block is where an edge wants it.
2135    ///
2136    /// Which is not quite the end. A block that leaves two ways has the branch as its last
2137    /// instruction, and anything appended after a branch is something the branch has already
2138    /// jumped past, so a constant materialized here would be a register the block below reads and
2139    /// nothing ever writes. The branch is put back on the end when that happened, which is the
2140    /// only reordering anything in this crate does and is why the branch is remembered before a
2141    /// single argument is read.
2142    fn edges(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
2143        let Some(term) = self.source.terminator(block) else { return Ok(()) };
2144        let branch =
2145            if self.source[term].opcode == Opcode::BrIf { self.out.terminator(out) } else { None };
2146
2147        let calls: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
2148        let mut succs = Vec::with_capacity(calls.len());
2149        for call in calls {
2150            let args: Vec<Value> = self.source[call.args].to_vec();
2151            let mut regs = Vec::with_capacity(args.len());
2152            for value in args {
2153                // The address of where the value is rather than the value, for the one type a
2154                // register holds none of. The block on the other side copies the bytes out of it
2155                // into a slot of its own, which is what makes a second edge into the same block
2156                // safe.
2157                let reg = if on_x87(self.source[value].ty) {
2158                    self.x87_slot(value)
2159                } else {
2160                    self.reg_of(value)?
2161                };
2162                regs.push(reg);
2163            }
2164            succs.push(mir::BlockCall { block: self.out_block(call.block), args: regs });
2165        }
2166        if let Some(branch) = branch {
2167            if self.out.terminator(out) != Some(branch) {
2168                self.out.remove_inst(branch);
2169                self.out.append_inst(out, branch);
2170            }
2171        }
2172        *self.out.succs_mut(out) = succs;
2173        Ok(())
2174    }
2175
2176    /// The machine IR block an IR block became.
2177    fn out_block(&self, block: Block) -> mir::Block {
2178        self.blocks[block.index()].expect("every block was created before any was filled")
2179    }
2180
2181    /// The parameters of the entry block, which are the function's arguments.
2182    ///
2183    /// They are not block parameters in the machine IR and they cannot be. A block parameter is
2184    /// given its value by a move on the edge into the block, and there is no edge into an entry
2185    /// block, so what arrives in a function is the convention's to say. [`crate::abi`] is what
2186    /// says it.
2187    ///
2188    /// The ones past the last register arrived in the caller's memory and are read out of it, and
2189    /// the loads that read them come back here so that the frame can finish them the way it
2190    /// finishes an `alloca`.
2191    fn arrive(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
2192        let params = self.source[block].params.clone();
2193        // The type of each is the block's answer and what the ABI asks of it is the signature's,
2194        // and the two lists are the same list: a parameter the classification turned into a
2195        // pointer is a pointer in the block too. A block with more parameters than the signature
2196        // names is not one the front end writes, and each of those is taken as a plain value.
2197        let asked: Vec<Abi> = self.source.signature().params.iter().map(|it| it.abi).collect();
2198        let types: Vec<Param> = params
2199            .iter()
2200            .enumerate()
2201            .map(|(index, &value)| {
2202                let abi = asked.get(index).copied().unwrap_or_default();
2203                Param { ty: self.source[value].ty, abi }
2204            })
2205            .collect();
2206        // A save area for a function that takes arguments its signature does not name, on a
2207        // convention whose list is the four field one. Windows is the other kind and has no area at
2208        // all, so a `va_start` in one is refused rather than built wrong.
2209        let variadic = self.source.signature().variadic && !self.conv.shared_positions;
2210        let area = variadic.then(|| varargs::Area::of(self.conv));
2211        let arrived = abi::entry(&mut self.out, out, &types, self.conv, self.names, area)
2212            .map_err(|(index, missing)| Unsupported::Argument { index, missing })?;
2213        for (&param, reg) in params.iter().zip(&arrived.regs) {
2214            self.regs[param.index()] = Some(*reg);
2215        }
2216        if let Some(area) = area {
2217            self.save_area(out, &arrived, area);
2218        }
2219        self.stack.arguments.extend(arrived.stack);
2220        Ok(())
2221    }
2222
2223    /// The prologue of a variadic function, which is every argument register it was handed written
2224    /// into the frame.
2225    ///
2226    /// Every one the signature did not name, that is. Which of those hold anything is a thing only
2227    /// the caller knew and there is nothing here to ask, so all of them are written, and the ones a
2228    /// named parameter took are not, because `va_start` sets the two offsets past them and nothing
2229    /// ever reads their slots.
2230    ///
2231    /// What that costs is up to fourteen stores in the prologue of a function that may read none of
2232    /// them, and the convention's answer to that is the count of vector registers in `%al`, which
2233    /// lets a callee skip the eight vector stores when the call passed no floats. Skipping them is a
2234    /// branch in a prologue, and a prologue is written long after this by [`crate::finish`], which
2235    /// has no blocks to branch between. So they are all written every time, which is correct and is
2236    /// what `-O0` costs. Issue #323 is the branch.
2237    ///
2238    /// A vector register is written eight bytes at a time and not sixteen, for the reason
2239    /// [`crate::varargs`] gives: the upper half of a slot is not something any reader of a list
2240    /// looks at.
2241    ///
2242    /// The address is computed once into a register rather than written as a displacement off the
2243    /// stack pointer, because a displacement into a frame is not known until after allocation and
2244    /// one `lea` costs less than a fixup list for a dozen stores. It is the same `lea` an `alloca`
2245    /// gets and [`crate::finish`] fills it in the same way.
2246    fn save_area(&mut self, out: mir::Block, arrived: &abi::Arrived, area: varargs::Area) {
2247        let save = self.stack.locals.len();
2248        self.stack.locals.push(Local { size: area.size, align: varargs::VECTOR_SLOT });
2249        self.varargs = Some(Varargs {
2250            save,
2251            incoming: arrived.used,
2252            integers: u32::try_from(arrived.took.0).unwrap_or(0) * area.stride(false),
2253            floats: area.starts_at(true)
2254                + u32::try_from(arrived.took.1).unwrap_or(0) * area.stride(true),
2255        });
2256
2257        let base = self.frame_address(out, save);
2258        for &(reg, class, at) in &arrived.spare {
2259            let name = if class == self.gpr { "x64.mov_mr_64" } else { "x64.movsd_mr" };
2260            let store = mir::Opcode::new(self.names.intern(name));
2261            let up = i32::try_from(at).expect("a register save area under two gigabytes");
2262            let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
2263            self.out.build(out, store).uses(reg, class).mem(mem).finish();
2264        }
2265    }
2266
2267    /// The address of one of the function's stack objects, in a fresh register.
2268    ///
2269    /// Written with nothing in its displacement, because where an object is in a frame is not known
2270    /// until after allocation, and given to [`crate::finish`] to fill in the way an `alloca` is.
2271    fn frame_address(&mut self, out: mir::Block, local: usize) -> mir::Reg {
2272        let reg = self.out.new_vreg(self.gpr);
2273        let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
2274        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
2275        let made = self.out.build(out, lea).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
2276        self.stack.addresses.push((made, local));
2277        reg
2278    }
2279
2280    /// Whether an instruction is one no machine instruction is written for where it stands.
2281    ///
2282    /// Four of them, and none is a lowering decision, which is why none is a rule. A constant is
2283    /// written where a register for it is first wanted rather than where the IR put it, and every
2284    /// reader of one may have folded it into an immediate, in which case nowhere is the right
2285    /// place. A return of nothing has nothing to put anywhere: the epilogue gives the frame back
2286    /// and leaves, and it is appended to every block with no successors long after this has
2287    /// finished, so a return with a value is one instruction here and a return without one is
2288    /// none. Unless the value went back through memory, in which case there is something to put
2289    /// somewhere after all and the IR does not carry it: the address the caller handed over has
2290    /// to be in `rax` on the way out, and [`Lowering::returned`] is what writes that.
2291    ///
2292    /// An unconditional jump is the third, and there is even less of it: the edge is on the
2293    /// block, and whether the block it goes to is the next one and needs no jump at all is the
2294    /// block layout's answer rather than this one's.
2295    ///
2296    /// The fourth is a point control does not arrive at, in both of the forms the IR has for it:
2297    /// the `unreachable` terminator the front end puts at the end of a function whose body can run
2298    /// off the bottom, and the `unreachable_hint` a call to `__builtin_unreachable` becomes. What
2299    /// to write for a place nothing reaches is a question with no wrong answer, and nothing is the
2300    /// smallest one and the one gcc 16.2.0 gives at `-O0`. The terminator leaves the block with no
2301    /// successors, so the epilogue lands at the end of it the way it does on any other block that
2302    /// goes nowhere, and the function cannot fall out of its own last instruction into whatever
2303    /// the assembler puts next.
2304    fn writes_nothing(&self, inst: Inst) -> bool {
2305        let data = &self.source[inst];
2306        match data.opcode {
2307            Opcode::IConst | Opcode::Jump | Opcode::Unreachable | Opcode::UnreachableHint => true,
2308            Opcode::Return => self.source[data.args].is_empty() && self.sret().is_none(),
2309            _ => false,
2310        }
2311    }
2312
2313    /// What every instruction in one block matched, with a set of values nobody may take.
2314    ///
2315    /// Backwards, because an instruction that has been folded into a later one does not get to
2316    /// fold anything into itself: the rule that took it only reached one level down, so what is
2317    /// under it is not in the term the matcher saw and cannot be replaced.
2318    fn decide(&self, insts: &[Inst], refused: &HashSet<Value>) -> Decided {
2319        let mut found: Vec<Option<Match<Term>>> = (0..insts.len()).map(|_| None).collect();
2320        let mut plans: Vec<Option<Plan>> = vec![None; insts.len()];
2321        let mut folded: Vec<Inst> = Vec::new();
2322        for (index, &inst) in insts.iter().enumerate().rev() {
2323            if folded.contains(&inst) {
2324                continue;
2325            }
2326            if let Some((plan, matched)) = self.select(inst, refused) {
2327                folded.extend(self.folds(inst, plan));
2328                found[index] = Some(matched);
2329                plans[index] = Some(plan);
2330            }
2331        }
2332        Decided { found, plans, folded }
2333    }
2334
2335    /// A value some of its readers took and some of them did not, which is the one case folding
2336    /// buys nothing.
2337    ///
2338    /// Folding does not delete the instruction that computed a value for anybody else, so a
2339    /// reader that did not take it still needs it in a register and the instruction stays. The
2340    /// reader that did take it now does that work again. Either all of them take it, in which
2341    /// case nothing is left to read it and the instruction goes, or none of them do.
2342    ///
2343    /// The count is over the whole function rather than over the block, since a value read from
2344    /// another block is read from a register there whatever this block decides. An instruction
2345    /// built by name rather than matched, a call being the one that matters, has no plan and so
2346    /// takes nothing, which is the right answer for it as well.
2347    fn left_alive(&self, insts: &[Inst], plans: &[Option<Plan>]) -> Option<Value> {
2348        let mut taken = vec![0u32; self.uses.len()];
2349        for (&inst, plan) in insts.iter().zip(plans) {
2350            let Some(plan) = plan else { continue };
2351            let args = &self.source[self.source[inst].args];
2352            for (index, &arg) in args.iter().take(MAX_ARGS).enumerate() {
2353                if plan[index] == Shown::Expand {
2354                    taken[arg.index()] += 1;
2355                }
2356            }
2357        }
2358        for (&inst, plan) in insts.iter().zip(plans) {
2359            let Some(plan) = plan else { continue };
2360            let args = &self.source[self.source[inst].args];
2361            for (index, &arg) in args.iter().take(MAX_ARGS).enumerate() {
2362                if plan[index] == Shown::Expand && taken[arg.index()] < self.uses[arg.index()] {
2363                    return Some(arg);
2364                }
2365            }
2366        }
2367        None
2368    }
2369
2370    /// The rule that fires on an instruction, and what it bound.
2371    ///
2372    /// The plans are tried in order and the first that matches wins, which is the maximal munch
2373    /// `spec/10-backend.md` asks for: a plan that offers more to the matcher is tried before one
2374    /// that offers less.
2375    fn select(&self, inst: Inst, refused: &HashSet<Value>) -> Option<(Plan, Match<Term>)> {
2376        for plan in self.plans(inst, refused) {
2377            let terms = Terms::new(self.source, inst, plan);
2378            if let Some(matched) = TABLE.find(&terms, Term::Root) {
2379                return Some((plan, matched));
2380            }
2381        }
2382        None
2383    }
2384
2385    /// Every way this instruction can be shown to the matcher, most offered first.
2386    fn plans(&self, inst: Inst, refused: &HashSet<Value>) -> Vec<Plan> {
2387        let args = &self.source[self.source[inst].args];
2388        let mut plans = vec![PLAIN];
2389        for (index, &arg) in args.iter().enumerate().take(MAX_ARGS) {
2390            let mut ways = Vec::new();
2391            if self.foldable(inst, arg, refused) {
2392                ways.push(Shown::Expand);
2393            }
2394            if Terms::new(self.source, inst, PLAIN).constant(arg).is_some() {
2395                ways.push(Shown::Const);
2396            }
2397            ways.push(Shown::Reg);
2398            plans = plans
2399                .into_iter()
2400                .flat_map(|plan| {
2401                    ways.iter().map(move |&way| {
2402                        let mut next = plan;
2403                        next[index] = way;
2404                        next
2405                    })
2406                })
2407                .collect();
2408        }
2409        plans
2410    }
2411
2412    /// Whether an operand may be shown as the instruction that computed it.
2413    ///
2414    /// It has to be in the same block, because a rule that folds one instruction into another
2415    /// moves the work to where the second one is. It has to be something rather than a block
2416    /// parameter, and not a constant, which is shown as a constant instead. And it has to be a
2417    /// value [`Lowering::left_alive`] has not put back, which is how the one reader at a time
2418    /// question is asked here: this says yes to a value with any number of readers, and a value
2419    /// only some of them could take is refused after the fact and asked again.
2420    ///
2421    /// A value with several readers used to be refused outright, on the reasoning that folding
2422    /// does not delete the instruction for anybody else. That reasoning is about the set of
2423    /// readers and was being applied to one reader at a time, which is stricter than it needs to
2424    /// be: when every reader takes it there is nobody left to read it and the instruction goes.
2425    /// An address a store and a load share is the shape that matters, since a memory operand has
2426    /// room for the whole of it and both readers have a memory operand.
2427    fn foldable(&self, into: Inst, value: Value, refused: &HashSet<Value>) -> bool {
2428        let Def::Result { inst, .. } = self.source[value].def else { return false };
2429        if self.source[inst].opcode == Opcode::IConst || refused.contains(&value) {
2430            return false;
2431        }
2432        self.source.block_of(inst).is_some()
2433            && self.source.block_of(inst) == self.source.block_of(into)
2434    }
2435
2436    /// The instructions a match folded into the one it matched.
2437    ///
2438    /// The plan is what says this, not the bindings: a binding is a register or a number either
2439    /// way, and an operand shown as the instruction that computed it is one no rule could have
2440    /// matched without taking that instruction, because the plan offered the matcher nothing
2441    /// else to call it.
2442    fn folds(&self, inst: Inst, plan: Plan) -> Vec<Inst> {
2443        let args = &self.source[self.source[inst].args];
2444        args.iter()
2445            .take(MAX_ARGS)
2446            .enumerate()
2447            .filter(|&(index, _)| plan[index] == Shown::Expand)
2448            .filter_map(|(_, &arg)| match self.source[arg].def {
2449                Def::Result { inst, .. } => Some(inst),
2450                Def::Param { .. } => None,
2451            })
2452            .collect()
2453    }
2454
2455    /// Build the machine instruction a match calls for.
2456    fn emit(&mut self, inst: Inst, matched: &Match<Term>) -> Result<(), Unsupported> {
2457        let rule: &Rule = TABLE.rule(matched);
2458        let pieces = rule.replacement;
2459        let Some(Piece::App { head, arity }) = pieces.first() else {
2460            return Err(self.unsupported(inst));
2461        };
2462        let opcode = head.strip_prefix(PREFIX).ok_or_else(|| self.unsupported(inst))?;
2463        let form = x86_64::form(opcode).ok_or_else(|| self.unsupported(inst))?;
2464
2465        let mut read = Read::default();
2466        let mut at = 1;
2467        for _ in 0..*arity {
2468            at = self.read(inst, pieces, at, &matched.bindings, &mut read)?;
2469        }
2470
2471        let descs = form.operands();
2472        let writes = descs.iter().take_while(|desc| desc.role.is_def()).count();
2473        if descs.len() - writes != read.regs.len() {
2474            return Err(self.unsupported(inst));
2475        }
2476
2477        // The first thing the instruction writes is what it computes, and any others are
2478        // registers the machine destroys on the way, which are fresh because nothing else is in
2479        // them and nothing reads them. An instruction that writes nothing at all is one whose
2480        // whole purpose is its effect, which is what a store is, and there is no result to put
2481        // anywhere.
2482        let mut regs = Vec::new();
2483        if writes > 0 {
2484            let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2485            regs.push(self.new_reg(result));
2486            // The rest are the registers the machine destroys on the way, and the class each is in
2487            // is the one the instruction's description gives it rather than a guess, so that an
2488            // instruction that wrecks a register in the other file says so.
2489            regs.extend(descs[1..writes].iter().map(|desc| self.out.new_vreg(desc.class)));
2490        } else if self.source[inst].first_result.is_some() {
2491            // A rule that throws away a value the IR gave a name to would leave every reader of
2492            // that name with nothing to read, so it is a rule this and the target disagree about.
2493            return Err(self.unsupported(inst));
2494        }
2495        regs.extend(read.regs.iter().copied());
2496
2497        let block = self.at.expect("a block is being filled");
2498        let opcode = mir::Opcode::new(self.names.intern(head));
2499        let mut build = self.out.build(block, opcode).at(self.source.span(inst));
2500        for (desc, reg) in descs.iter().zip(regs) {
2501            let operand = mir::Operand {
2502                reg,
2503                class: desc.class,
2504                role: desc.role,
2505                constraint: desc.constraint,
2506            };
2507            build = build.operand(operand);
2508        }
2509        if let Some(mem) = read.mem {
2510            build = build.mem(mem);
2511        }
2512        if let Some(imm) = read.imm {
2513            build = build.imm(imm);
2514        }
2515        build.finish();
2516        Ok(())
2517    }
2518
2519    /// Read one argument of a replacement, which is a register, a number or an address.
2520    ///
2521    /// Gives back the position after it, because a replacement is flat and an address takes
2522    /// arguments of its own.
2523    fn read(
2524        &mut self,
2525        inst: Inst,
2526        pieces: &'static [Piece],
2527        at: usize,
2528        bindings: &[Term],
2529        out: &mut Read,
2530    ) -> Result<usize, Unsupported> {
2531        match pieces.get(at) {
2532            Some(Piece::Int(value)) => {
2533                out.imm = i64::try_from(*value).ok();
2534                Ok(at + 1)
2535            }
2536            Some(Piece::Var { index, .. }) => {
2537                match bindings.get(*index) {
2538                    Some(&Term::Reg(value)) => {
2539                        let reg = self.reg_of(value)?;
2540                        out.regs.push(reg);
2541                    }
2542                    Some(&Term::Num(value)) => out.imm = i64::try_from(value).ok(),
2543                    // A pattern binds a register or a number and nothing else, so this is a
2544                    // rule the matcher and this file disagree about.
2545                    _ => return Err(self.unsupported(inst)),
2546                }
2547                Ok(at + 1)
2548            }
2549            Some(Piece::App { head, arity }) => {
2550                let kind = x86_64::address(head).ok_or_else(|| self.unsupported(inst))?;
2551                let mut inner = Read::default();
2552                let mut next = at + 1;
2553                for _ in 0..*arity {
2554                    next = self.read(inst, pieces, next, bindings, &mut inner)?;
2555                }
2556                let mem = address(kind, &inner, self.gpr).ok_or_else(|| self.unsupported(inst))?;
2557                out.mem = Some(mem);
2558                Ok(next)
2559            }
2560            None => Err(self.unsupported(inst)),
2561        }
2562    }
2563
2564    /// The register a value is in, materializing it if it is a constant that has not been put in
2565    /// one yet.
2566    ///
2567    /// A constant is written where it is wanted rather than where the IR defined it, and where it
2568    /// is wanted is a block that need not be the one the IR defined it in. So the register holding
2569    /// one is only good inside the block it was written into, and a second block that wants the
2570    /// same constant gets its own. Anything else is a register read where nothing wrote it: the
2571    /// IR guarantees a definition dominates its uses, and this moved the definition.
2572    ///
2573    /// Writing the number again is also the right answer and not merely the safe one. It is one
2574    /// instruction that reads nothing, which is cheaper than holding a register live across a
2575    /// branch for it, and it is what a rematerializing allocator would do with the value anyway.
2576    fn reg_of(&mut self, value: Value) -> Result<mir::Reg, Unsupported> {
2577        let constant = match self.source[value].def {
2578            Def::Result { inst, .. } => {
2579                (self.source[inst].opcode == Opcode::IConst).then_some(inst)
2580            }
2581            Def::Param { .. } => None,
2582        };
2583        let here = self.at.expect("a block is being filled");
2584        if let Some(reg) = self.regs[value.index()] {
2585            if constant.is_none() || self.written[value.index()] == Some(here) {
2586                return Ok(reg);
2587            }
2588        }
2589        if let Some(inst) = constant {
2590            // Cleared so that the register the constant is written into is a new one rather than
2591            // the one the block above wrote, which is still being read up there.
2592            self.regs[value.index()] = None;
2593            // Nothing is refused here. A constant is written on its own, out of the loop over the
2594            // block, and the operands of the rule that writes one are the number and nothing else.
2595            let matched = self
2596                .select(inst, &HashSet::new())
2597                .map(|(_, matched)| matched)
2598                .ok_or_else(|| self.unsupported(inst))?;
2599            self.emit(inst, &matched)?;
2600            // The same mark the loop over the instructions makes, and it has to be made here as
2601            // well because this is the only place a constant is ever selected: the loop skips one
2602            // where the IR wrote it, so a rule that lowers a constant fires from nowhere else and
2603            // would be reported as a rule nothing reaches.
2604            self.fired.mark(matched.rule);
2605            self.written[value.index()] = Some(here);
2606            return Ok(self.regs[value.index()].expect("a constant is written into a register"));
2607        }
2608        Ok(self.new_reg(value))
2609    }
2610
2611    /// Which register file a value of that type lives in.
2612    ///
2613    /// The vector one for the two float widths the machine has scalar instructions for, and the
2614    /// general purpose one for everything else. A `long double` is in neither, and it is here
2615    /// rather than in the vector class on purpose: it would be put in a register that cannot hold
2616    /// it, and there is no rule that names one, so the instruction computing it is reported. The
2617    /// wrong class would make that a wrong program instead of a refused one.
2618    fn class_of(&self, ty: Type) -> RegClass {
2619        match crate::term::float_slot(ty) {
2620            Some(_) => self.conv.sse_class,
2621            None => self.gpr,
2622        }
2623    }
2624
2625    /// A fresh register for a value, which is what the instruction computing it writes.
2626    fn new_reg(&mut self, value: Value) -> mir::Reg {
2627        if let Some(reg) = self.regs[value.index()] {
2628            return reg;
2629        }
2630        let reg = self.out.new_vreg(self.class_of(self.source[value].ty));
2631        self.regs[value.index()] = Some(reg);
2632        reg
2633    }
2634
2635    fn unsupported(&self, inst: Inst) -> Unsupported {
2636        let data = &self.source[inst];
2637        Unsupported::Inst {
2638            inst,
2639            term: Terms::new(self.source, inst, PLAIN).name(inst),
2640            opcode: data.opcode,
2641            ty: data.first_result.map(|result| self.source[result].ty),
2642        }
2643    }
2644}
2645
2646/// What the arguments of one replacement came to.
2647#[derive(Debug, Default)]
2648struct Read {
2649    regs: Vec<mir::Reg>,
2650    imm: Option<i64>,
2651    mem: Option<mir::Mem>,
2652}
2653
2654/// The addressing mode an address constructor's arguments make.
2655///
2656/// One arm per constructor rather than a question asked of the kind, because what the arguments
2657/// mean is the whole of what tells the four apart: the same register is a base in one and an
2658/// index in another, and the same constant is a scale in one and a displacement in another.
2659fn address(kind: x86_64::Address, read: &Read, gpr: RegClass) -> Option<mir::Mem> {
2660    let mut regs = read.regs.iter().copied().map(|reg| mir::Operand::read(reg, gpr));
2661    match kind {
2662        x86_64::Address::BaseIndexScale => {
2663            let base = regs.next()?;
2664            let index = regs.next()?;
2665            Some(mir::Mem::at(base).indexed(index, u8::try_from(read.imm?).ok()?))
2666        }
2667        x86_64::Address::IndexScale => Some(mir::Mem {
2668            base: None,
2669            index: Some(regs.next()?),
2670            scale: u8::try_from(read.imm?).ok()?,
2671            disp: 0,
2672            symbol: None,
2673            got: false,
2674            segment: None,
2675        }),
2676        x86_64::Address::Base => Some(mir::Mem::at(regs.next()?)),
2677        // The rule that writes this has a guard saying the constant fits, so a displacement that
2678        // does not is a rule and a target that disagree rather than a program this cannot compile.
2679        x86_64::Address::BaseOffset => {
2680            Some(mir::Mem { disp: i32::try_from(read.imm?).ok()?, ..mir::Mem::at(regs.next()?) })
2681        }
2682    }
2683}
2684
2685/// The table this selector matches with.
2686///
2687/// One target for now, because one target has a rule file. Which table to use becomes a question
2688/// the moment a second one does, and the answer will be the target the session was given rather
2689/// than a constant here.
2690static TABLE: &Table = &crate::select::x86_64::TABLE;
2691
2692#[cfg(test)]
2693mod tests {
2694    use rucc_ir::{
2695        AsmInfo, Builder, CallInfo, Flags, InstData, MemInfo, MemOrder, Restrict, Signature, Type,
2696    };
2697    use rucc_regalloc::assign::Env;
2698    use rucc_target::x86_64::{FRAME, REGS, SYSV};
2699
2700    use super::*;
2701    use crate::finish::{Convention, finish};
2702    use crate::frame::{Frame, Incoming, Layout};
2703
2704    /// A function of as many 64 bit parameters as the test wants, and the block they are in.
2705    fn blank(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
2706        let mut names = Interner::new();
2707        let mut func = Func::new(names.intern("f"), Signature::new());
2708        let block = func.create_block();
2709        let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
2710        (names, func, block, values)
2711    }
2712
2713    /// An ordinary access: not atomic, and aligned enough that nothing here has an opinion.
2714    /// Neither field reaches selection, which is the point of saying it once here.
2715    fn plain() -> MemInfo {
2716        MemInfo {
2717            size: 0,
2718            align: 1,
2719            order: MemOrder::NotAtomic,
2720            tbaa: None,
2721            owns: 0,
2722            restrict: Restrict::NONE,
2723        }
2724    }
2725
2726    /// What the allocator is given: every integer register the convention offers except two, held
2727    /// back so that a move on an edge has somewhere to break a cycle and a spilled value has
2728    /// somewhere to be read into. Which two does not matter, and holding back the last two the
2729    /// convention would reach for leaves every expectation below unchanged.
2730    fn env() -> Env {
2731        const SCRATCH: [rucc_target::PhysReg; 2] = [x86_64::R10, x86_64::R11];
2732        let order: Vec<rucc_target::PhysReg> =
2733            SYSV.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
2734        Env::new().with(x86_64::GPR, &order, &SCRATCH)
2735    }
2736
2737    /// The machine IR text a function lowers to.
2738    fn lower(names: &mut Interner, source: &Func) -> String {
2739        let out = func(source, names, &SYSV, &Elsewhere::default())
2740            .expect("every instruction has a rule");
2741        mir::print_func(&out.func, names, &REGS)
2742    }
2743
2744    #[test]
2745    fn an_addition_of_two_registers_is_one_instruction() {
2746        let i32 = Type::int(32);
2747        let (mut names, mut func, block, args) = blank(&[i32, i32]);
2748        let mut build = Builder::new(&mut func, block);
2749        build.binary(Opcode::Add, args[0], args[1], Flags::default());
2750
2751        assert_eq!(
2752            lower(&mut names, &func),
2753            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
2754             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr(reuse 1) = x64.add_rr_32 %0, %1\n}\n"
2755        );
2756    }
2757
2758    #[test]
2759    fn a_constant_operand_becomes_an_immediate() {
2760        let i32 = Type::int(32);
2761        let (mut names, mut func, block, args) = blank(&[i32]);
2762        let mut build = Builder::new(&mut func, block);
2763        let seven = build.iconst(i32, 7);
2764        build.binary(Opcode::Add, args[0], seven, Flags::default());
2765
2766        // The constant is in the instruction and nothing was written to hold it, which is what
2767        // materializing one where a register for it is wanted buys.
2768        assert_eq!(
2769            lower(&mut names, &func),
2770            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
2771             %1:gpr(reuse 1) = x64.add_ri_32 %0, 7\n}\n"
2772        );
2773    }
2774
2775    #[test]
2776    fn a_constant_too_wide_for_an_immediate_goes_into_a_register() {
2777        let i64 = Type::int(64);
2778        let (mut names, mut func, block, args) = blank(&[i64]);
2779        let mut build = Builder::new(&mut func, block);
2780        let big = build.iconst(i64, i128::from(i32::MAX) + 1);
2781        build.binary(Opcode::Add, args[0], big, Flags::default());
2782
2783        // Nobody wrote this fallback down. The rule that takes an immediate has a guard that
2784        // turns a number this wide down, so it does not fire, and the next way of showing the
2785        // operand puts it in a register.
2786        assert_eq!(
2787            lower(&mut names, &func),
2788            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
2789             %1:gpr = x64.mov_ri_64 2147483648\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n}\n"
2790        );
2791    }
2792
2793    #[test]
2794    fn an_index_calculation_folds_into_an_address() {
2795        let i64 = Type::int(64);
2796        let (mut names, mut func, block, args) = blank(&[i64, i64]);
2797        let mut build = Builder::new(&mut func, block);
2798        let four = build.iconst(i64, 4);
2799        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
2800        build.binary(Opcode::Add, args[0], scaled, Flags::default());
2801
2802        // Three IR instructions and one machine instruction. The multiply is gone because the
2803        // rule that matched reached down and took it.
2804        assert_eq!(
2805            lower(&mut names, &func),
2806            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
2807             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.lea_64 [%0 + %1*4]\n}\n"
2808        );
2809    }
2810
2811    #[test]
2812    fn an_instruction_every_reader_can_take_is_folded_into_all_of_them() {
2813        let i64 = Type::int(64);
2814        let (mut names, mut func, block, args) = blank(&[i64, i64]);
2815        let mut build = Builder::new(&mut func, block);
2816        let four = build.iconst(i64, 4);
2817        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
2818        let first = build.binary(Opcode::Add, args[0], scaled, Flags::default());
2819        build.binary(Opcode::Add, first, scaled, Flags::default());
2820
2821        // Both readers have room for a scaled index, so both of them take it and nothing is left
2822        // to read the multiply. Three IR instructions become two machine ones, where refusing to
2823        // fold into either reader would have left three.
2824        assert_eq!(
2825            lower(&mut names, &func),
2826            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
2827             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.lea_64 [%0 + %1*4]\n    \
2828             %3:gpr = x64.lea_64 [%2 + %1*4]\n}\n"
2829        );
2830    }
2831
2832    #[test]
2833    fn an_instruction_one_of_its_readers_cannot_take_is_folded_into_none_of_them() {
2834        let i64 = Type::int(64);
2835        let (mut names, mut func, block, args) = blank(&[i64, i64]);
2836        let mut build = Builder::new(&mut func, block);
2837        let four = build.iconst(i64, 4);
2838        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
2839        build.binary(Opcode::Add, args[0], scaled, Flags::default());
2840        build.store(scaled, args[0], plain(), Flags::default());
2841
2842        // The addition has room for the multiply and the store does not: what a store writes is
2843        // a register, and no rule reaches through it. Folding into the addition alone would
2844        // leave the multiply where it is for the store to read and do the work twice, so the
2845        // multiply is put back and both readers read the register it wrote.
2846        let text = lower(&mut names, &func);
2847        assert!(text.contains("x64.lea_64 [%1*4]"), "{text}");
2848        assert!(text.contains("x64.add_rr_64"), "{text}");
2849    }
2850
2851    #[test]
2852    fn a_shift_by_a_register_asks_for_it_in_cl() {
2853        let i32 = Type::int(32);
2854        let (mut names, mut func, block, args) = blank(&[i32, i32]);
2855        let mut build = Builder::new(&mut func, block);
2856        build.binary(Opcode::Shl, args[0], args[1], Flags::default());
2857
2858        // The fixed register is not in the rule. It is what the target says the instruction does
2859        // with its operands, and the allocator is what will act on it.
2860        let text = lower(&mut names, &func);
2861        assert!(text.contains("x64.shl_rcl_32 %0, %1($rcx)"), "{text}");
2862    }
2863
2864    #[test]
2865    fn a_division_names_the_registers_and_the_register_it_destroys() {
2866        let i32 = Type::int(32);
2867        let (mut names, mut func, block, args) = blank(&[i32, i32]);
2868        let mut build = Builder::new(&mut func, block);
2869        build.binary(Opcode::SDiv, args[0], args[1], Flags::default());
2870
2871        // Two definitions, because a division writes the remainder whether anybody wanted it or
2872        // not, and the second one is early because it is destroyed before the operands are read.
2873        let text = lower(&mut names, &func);
2874        assert!(
2875            text.contains("%2:gpr($rax), early %3:gpr($rdx) = x64.idiv_quo_32 %0($rax), %1"),
2876            "{text}"
2877        );
2878    }
2879
2880    #[test]
2881    fn a_load_reads_through_the_register_the_address_is_in() {
2882        let i64 = Type::int(64);
2883        let (mut names, mut func, block, args) = blank(&[i64]);
2884        let mut build = Builder::new(&mut func, block);
2885        build.load(Type::int(32), args[0], plain(), Flags::default());
2886
2887        assert_eq!(
2888            lower(&mut names, &func),
2889            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
2890             %1:gpr = x64.mov_rm_32 [%0]\n}\n"
2891        );
2892    }
2893
2894    #[test]
2895    fn a_store_writes_no_register_and_the_value_it_writes_is_the_one_the_ir_gave_it() {
2896        let (mut names, mut func, block, args) = blank(&[Type::int(32), Type::int(64)]);
2897        let mut build = Builder::new(&mut func, block);
2898        build.store(args[0], args[1], plain(), Flags::default());
2899
2900        // The value is the first parameter and the address is the second, and the instruction
2901        // takes them the other way round. Getting that backwards would compile to a store of the
2902        // address into the value, which is a program that runs and does the wrong thing.
2903        assert_eq!(
2904            lower(&mut names, &func),
2905            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
2906             %1:gpr($rsi) = x64.arg_val_64\n    x64.mov_mr_32 %0, [%1]\n}\n"
2907        );
2908    }
2909
2910    #[test]
2911    fn an_address_with_a_constant_added_folds_into_the_access() {
2912        let i64 = Type::int(64);
2913        let (mut names, mut func, block, args) = blank(&[i64]);
2914        let mut build = Builder::new(&mut func, block);
2915        let twelve = build.iconst(i64, 12);
2916        let field = build.binary(Opcode::Add, args[0], twelve, Flags::default());
2917        build.load(Type::int(64), field, plain(), Flags::default());
2918
2919        // Two IR instructions and one machine instruction, which is what every read of a field
2920        // of a structure comes to.
2921        assert_eq!(
2922            lower(&mut names, &func),
2923            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
2924             %1:gpr = x64.mov_rm_64 [%0 + 12]\n}\n"
2925        );
2926    }
2927
2928    #[test]
2929    fn a_displacement_too_wide_to_encode_leaves_the_addition_where_it_is() {
2930        let i64 = Type::int(64);
2931        let (mut names, mut func, block, args) = blank(&[i64]);
2932        let mut build = Builder::new(&mut func, block);
2933        let big = build.iconst(i64, i128::from(i32::MAX) + 1);
2934        let far = build.binary(Opcode::Add, args[0], big, Flags::default());
2935        build.load(Type::int(32), far, plain(), Flags::default());
2936
2937        // A displacement is signed and 32 bits. The rule that folds one has a guard that turns
2938        // this down, so the addition stays and the load reads through what it produced. Nobody
2939        // wrote that fallback: it is the next way of showing the operand.
2940        let text = lower(&mut names, &func);
2941        assert!(text.contains("x64.mov_rm_32 [%2]"), "{text}");
2942        assert!(text.contains("x64.add_rr_64"), "{text}");
2943    }
2944
2945    #[test]
2946    fn a_store_of_a_value_that_was_loaded_is_two_instructions_and_no_arithmetic() {
2947        let i64 = Type::int(64);
2948        let (mut names, mut func, block, args) = blank(&[i64, i64]);
2949        let mut build = Builder::new(&mut func, block);
2950        let got = build.load(Type::int(8), args[0], plain(), Flags::default());
2951        build.store(got, args[1], plain(), Flags::default());
2952
2953        // A load feeding a store is the one place folding would be wrong: an x86-64 `mov` has at
2954        // most one memory operand, and there is no rule that takes two, so the load is left where
2955        // it is and the store reads the register it wrote.
2956        assert_eq!(
2957            lower(&mut names, &func),
2958            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
2959             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.mov_rm_8 [%0]\n    \
2960             x64.mov_mr_8 %2, [%1]\n}\n"
2961        );
2962    }
2963
2964    #[test]
2965    fn an_access_at_a_width_no_rule_is_written_at_is_reported() {
2966        let i64 = Type::int(64);
2967        let (mut names, mut source, block, args) = blank(&[i64]);
2968        let mut build = Builder::new(&mut source, block);
2969        build.load(Type::int(128), args[0], plain(), Flags::default());
2970
2971        // The width is the whole of what is wrong here, so the width is in the message: `load`
2972        // on its own is written about at every other width and would send a reader looking in
2973        // the wrong place.
2974        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
2975            .expect_err("nothing loads 128 bits");
2976        assert_eq!(failed.to_string(), "no rule lowers a `load` producing a `i128`");
2977    }
2978
2979    #[test]
2980    fn a_return_asks_for_the_value_in_the_register_the_caller_reads() {
2981        let (mut names, mut func, block, args) = blank(&[Type::int(32)]);
2982        let mut build = Builder::new(&mut func, block);
2983        build.ret(&[args[0]]);
2984
2985        // The register is not in the rule, the same way `cl` is not in the rule for a shift. It
2986        // is what the target says the instruction does with its operand, and the allocator is
2987        // what will act on it. There is no `ret` here, because giving the frame back has to
2988        // happen between this and leaving and the frame is not worked out yet.
2989        assert_eq!(
2990            lower(&mut names, &func),
2991            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
2992             x64.ret_val_32 %0($rax)\n}\n"
2993        );
2994    }
2995
2996    #[test]
2997    fn a_return_of_two_values_asks_for_the_second_register_as_well() {
2998        let i64 = Type::int(64);
2999        let (mut names, mut func, block, args) = blank(&[i64, i64]);
3000        let mut build = Builder::new(&mut func, block);
3001        build.ret(&[args[0], args[1]]);
3002
3003        // `struct { long a, b; } f(long a, long b)`, after the front end has classified it. Both
3004        // halves are integers, so the second is in the second integer return register, and both
3005        // pseudos say so the same way the one for a single value does.
3006        assert_eq!(
3007            lower(&mut names, &func),
3008            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
3009             %1:gpr($rsi) = x64.arg_val_64\n    x64.ret_val_64 %0($rax)\n    \
3010             x64.ret_val2_64 %1($rdx)\n}\n"
3011        );
3012    }
3013
3014    #[test]
3015    fn two_values_back_in_different_files_are_both_the_first_of_their_own() {
3016        let f64 = Type::float(rucc_ir::Float::F64);
3017        let (mut names, mut func, block, args) = blank(&[f64, Type::int(64)]);
3018        let mut build = Builder::new(&mut func, block);
3019        build.ret(&[args[0], args[1]]);
3020
3021        // `struct { double a; long b; } f(double a, long b)`. The two files are counted apart, so
3022        // neither half is the second of anything and the `double` is in `xmm0` rather than in the
3023        // register a second `double` would have been in. Getting this wrong is not a crash: the
3024        // caller reads a register nobody wrote, and this is where that is ruled out.
3025        assert_eq!(
3026            lower(&mut names, &func),
3027            "mfunc @f {\nblock0:\n    %0:xmm($xmm0) = x64.arg_val_f64\n    \
3028             %1:gpr($rdi) = x64.arg_val_64\n    x64.ret_val_f64 %0($xmm0)\n    \
3029             x64.ret_val_64 %1($rax)\n}\n"
3030        );
3031    }
3032
3033    #[test]
3034    fn two_of_the_same_file_back_take_the_first_two_of_it() {
3035        let f64 = Type::float(rucc_ir::Float::F64);
3036        let (mut names, mut func, block, args) = blank(&[f64, f64]);
3037        let mut build = Builder::new(&mut func, block);
3038        build.ret(&[args[0], args[1]]);
3039
3040        // `struct { double x, y; } f(double x, double y)`, which is the vector half of the pair
3041        // above and counts in its own file the same way.
3042        assert_eq!(
3043            lower(&mut names, &func),
3044            "mfunc @f {\nblock0:\n    %0:xmm($xmm0) = x64.arg_val_f64\n    \
3045             %1:xmm($xmm1) = x64.arg_val_f64\n    x64.ret_val_f64 %0($xmm0)\n    \
3046             x64.ret_val2_f64 %1($xmm1)\n}\n"
3047        );
3048    }
3049
3050    /// A function whose answer goes back through memory, with the pointer to the space for it in
3051    /// front of whatever else it takes. Only the signature says it is one.
3052    fn returning_through_memory(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
3053        let mut names = Interner::new();
3054        let sret = Abi::Sret { size: 32, align: 8 };
3055        let mut signature = Signature::new().and_param(Param::with_abi(Type::PTR, sret));
3056        signature.params.extend(params.iter().copied().map(Param::new));
3057        let mut func = Func::new(names.intern("f"), signature);
3058        let block = func.create_block();
3059        let space = func.append_param(block, Type::PTR);
3060        let values = std::iter::once(space)
3061            .chain(params.iter().map(|&ty| func.append_param(block, ty)))
3062            .collect();
3063        (names, func, block, values)
3064    }
3065
3066    #[test]
3067    fn the_space_a_return_through_memory_was_given_goes_back_in_the_first_return_register() {
3068        let (mut names, mut func, block, _) = returning_through_memory(&[]);
3069        Builder::new(&mut func, block).ret(&[]);
3070
3071        // `struct big f(void)`, where `big` is too large to come back in registers. The `return`
3072        // carries nothing, because the value went into the space the caller handed over, and the
3073        // document still says that address comes back in `rax`. Nothing in the IR says it, so the
3074        // convention says it, and the pseudo is the one any other pointer return would use.
3075        assert_eq!(
3076            lower(&mut names, &func),
3077            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
3078             x64.ret_val_64 %0($rax)\n}\n"
3079        );
3080    }
3081
3082    #[test]
3083    fn what_the_function_did_in_between_does_not_take_the_register_off_it() {
3084        let (mut names, mut func, block, args) = returning_through_memory(&[Type::int(32)]);
3085        let mut build = Builder::new(&mut func, block);
3086        build.store(args[1], args[0], plain(), Flags::default());
3087        build.ret(&[]);
3088
3089        // The register is a read at the end and not a move at the start, so it is live across
3090        // everything between the two and the allocator has to keep it somewhere. In a function
3091        // with a call in it that somewhere is a callee saved register, and the address comes back
3092        // into `rax` here rather than whatever the last instruction happened to leave there. That
3093        // is issue #333, and a store is enough to show the value outlives the entry block.
3094        let text = lower(&mut names, &func);
3095        assert!(text.contains("x64.mov_mr_32 %1, [%0]"), "{text}");
3096        assert!(text.ends_with("    x64.ret_val_64 %0($rax)\n}\n"), "{text}");
3097    }
3098
3099    #[test]
3100    fn a_pointer_that_is_only_a_pointer_is_not_given_back() {
3101        let (mut names, mut func, block, args) = blank(&[Type::PTR]);
3102        let mut build = Builder::new(&mut func, block);
3103        build.store(args[0], args[0], plain(), Flags::default());
3104        build.ret(&[]);
3105
3106        // `void f(void **p)`. It takes a pointer first and returns nothing, which is the shape of
3107        // the one above and none of its meaning, and what tells them apart is the signature. A
3108        // `void` function leaves `rax` alone.
3109        assert!(!lower(&mut names, &func).contains("ret_val"));
3110    }
3111
3112    #[test]
3113    fn a_return_of_a_constant_puts_it_in_a_register_first() {
3114        let (mut names, mut func, block, _) = blank(&[]);
3115        let mut build = Builder::new(&mut func, block);
3116        let zero = build.iconst(Type::int(32), 0);
3117        build.ret(&[zero]);
3118
3119        // No rule returns an immediate, so the plan that offers one is turned down and the next
3120        // one materializes it. That is `int main(void) { return 0; }` in full, once the epilogue
3121        // is appended to it.
3122        assert_eq!(
3123            lower(&mut names, &func),
3124            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 0\n    x64.ret_val_32 %0($rax)\n}\n"
3125        );
3126    }
3127
3128    #[test]
3129    fn the_rule_that_writes_a_constant_down_is_recorded_as_a_rule_that_fired() {
3130        let (mut names, mut func, block, _) = blank(&[]);
3131        let mut build = Builder::new(&mut func, block);
3132        let zero = build.iconst(Type::int(32), 0);
3133        build.ret(&[zero]);
3134
3135        // The loop over the instructions passes a constant by, because a constant is written where
3136        // a register for it is first wanted rather than where the IR put it. So the only place a
3137        // rule about one is ever selected is the materialization, and a mark made in the loop
3138        // alone would report every rule about a constant as a rule nothing reaches.
3139        let out = super::func(&func, &mut names, &SYSV, &Elsewhere::default())
3140            .expect("every instruction has a rule");
3141        let rules = &crate::select::x86_64::TABLE.rules;
3142        let fired: Vec<&str> = rules
3143            .iter()
3144            .enumerate()
3145            .filter(|(index, _)| out.fired.has(*index))
3146            .map(|(_, rule)| rule.pattern)
3147            .collect();
3148        assert!(fired.contains(&"(iconst.i32 k)"), "{fired:?}");
3149    }
3150
3151    #[test]
3152    fn a_return_of_nothing_is_no_instruction_at_all() {
3153        let (mut names, mut func, block, _) = blank(&[]);
3154        let mut build = Builder::new(&mut func, block);
3155        build.ret(&[]);
3156
3157        // Every part of leaving a function that returns nothing is the epilogue's, and the
3158        // epilogue goes in after allocation. A block with nothing in it is the right answer here
3159        // rather than a function that could not be lowered.
3160        assert_eq!(lower(&mut names, &func), "mfunc @f {\nblock0:\n}\n");
3161    }
3162
3163    #[test]
3164    fn the_allocator_is_what_moves_the_answer_into_the_return_register() {
3165        let (mut names, mut source, block, _) = blank(&[]);
3166        let mut build = Builder::new(&mut source, block);
3167        let zero = build.iconst(Type::int(32), 0);
3168        build.ret(&[zero]);
3169
3170        let mut out = func(&source, &mut names, &SYSV, &Elsewhere::default())
3171            .expect("every instruction has a rule")
3172            .func;
3173        let env = env();
3174        let allocation = rucc_regalloc::run(&mut out, &env, "test");
3175        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
3176        finish(
3177            &mut out,
3178            &allocation,
3179            &frame,
3180            &Stack::default(),
3181            Convention::new(&SYSV, &FRAME),
3182            &mut names,
3183        );
3184
3185        // `int main(void) { return 0; }` end to end. Nothing here asked for `rax`: the rule said
3186        // the value goes back, the target said where, and the allocator is what made it true. The
3187        // epilogue is what leaves, and this function needs no frame, so it is the return alone.
3188        //
3189        // Two instructions and no copy, which is what a hint buys. The return insists on `rax`,
3190        // so `rax` is the register the allocator tries first for the value the return reads, and
3191        // the constant is written straight into it.
3192        assert_eq!(
3193            mir::print_func(&out, &names, &REGS),
3194            "mfunc @f {\nblock0:\n    $rax = x64.mov_ri_32 0\n    \
3195             x64.ret_val_32 $rax($rax)\n    x64.ret\n}\n"
3196        );
3197    }
3198
3199    #[test]
3200    fn a_function_of_two_arguments_is_a_whole_function_now() {
3201        let i32 = Type::int(32);
3202        let (mut names, mut source, block, args) = blank(&[i32, i32]);
3203        let mut build = Builder::new(&mut source, block);
3204        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
3205        build.ret(&[sum]);
3206
3207        let mut out = func(&source, &mut names, &SYSV, &Elsewhere::default())
3208            .expect("every instruction has a rule")
3209            .func;
3210        let env = env();
3211        let allocation = rucc_regalloc::run(&mut out, &env, "test");
3212        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
3213        finish(
3214            &mut out,
3215            &allocation,
3216            &frame,
3217            &Stack::default(),
3218            Convention::new(&SYSV, &FRAME),
3219            &mut names,
3220        );
3221
3222        // `int f(int a, int b) { return a + b; }` end to end, and this is the test the argument
3223        // side exists for. Before it there was no way to write one: the allocator refuses a
3224        // function whose entry block takes parameters, because there is no edge into an entry
3225        // block for the moves that give a block parameter its value to go on.
3226        //
3227        // One move, and it is the one the machine's addition needs rather than one the allocator
3228        // owes anybody. Each argument stays in the register it arrived in, because the pseudo
3229        // that defines it insists on that register and the allocator now tries it first, and the
3230        // sum stays in the register the addition wrote it to until the return reads it out. The
3231        // copy in front of a two address instruction is what makes its destination one of the
3232        // registers it reads, and the source operand keeps its own name because the destination
3233        // is what the encoder writes.
3234        assert_eq!(
3235            mir::print_func(&out, &names, &REGS),
3236            "mfunc @f {\nblock0:\n    $rdi($rdi) = x64.arg_val_32\n    \
3237             $rsi($rsi) = x64.arg_val_32\n    \
3238             $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n    $rax = x64.mov_rr_64 $rdi\n    \
3239             x64.ret_val_32 $rax($rax)\n    x64.ret\n}\n"
3240        );
3241    }
3242
3243    #[test]
3244    fn an_argument_with_no_register_left_for_it_is_read_out_of_the_caller_s_stack() {
3245        let i64 = Type::int(64);
3246        let (mut names, mut source, block, args) = blank(&[i64; 7]);
3247        let mut build = Builder::new(&mut source, block);
3248        build.ret(&[args[6]]);
3249
3250        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
3251            .expect("the seventh is read from memory");
3252
3253        // SysV passes six integers in registers and the seventh in the caller's memory, so six of
3254        // these are pseudos that encode to nothing and the seventh is a load that encodes to real
3255        // bytes. Its displacement is nothing here for the reason a local's is: there is no frame
3256        // yet. What the walk hands on is which instruction is waiting, and for how far up the
3257        // caller's argument area, which is the bottom of it because it is the first one there.
3258        assert_eq!(lowered.stack.arguments.len(), 1);
3259        assert_eq!(lowered.stack.arguments[0].1, 0);
3260        let text = mir::print_func(&lowered.func, &names, &REGS);
3261        assert!(text.contains("%6:gpr = x64.mov_rm_64 [$rsp]"), "{text}");
3262        assert_eq!(text.matches("x64.arg_val_64").count(), 6, "{text}");
3263    }
3264
3265    #[test]
3266    fn the_frame_is_what_says_how_far_up_the_caller_s_stack_an_argument_is() {
3267        let i64 = Type::int(64);
3268        let (mut names, mut source, block, args) = blank(&[i64; 8]);
3269        let mut build = Builder::new(&mut source, block);
3270        let sum = build.binary(Opcode::Add, args[6], args[7], Flags::default());
3271        build.ret(&[sum]);
3272
3273        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
3274            .expect("both are read from memory");
3275        let stack = lowered.stack;
3276        let mut out = lowered.func;
3277        let env = env();
3278        let allocation = rucc_regalloc::run(&mut out, &env, "test");
3279        let layout = stack.layout(Layout::new(&SYSV, REGS));
3280        let frame = Frame::of(&out, &allocation, &layout);
3281        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
3282
3283        // A leaf that takes no frame, so the stack pointer never moves and the only thing between
3284        // it and the caller's arguments is the return address the call pushed. The seventh
3285        // parameter is at the bottom of the caller's argument area and the eighth is one word
3286        // further up, which is the eight bytes between the two offsets.
3287        let text = mir::print_func(&out, &names, &REGS);
3288        assert_eq!(frame.size(), 0);
3289        assert_eq!(frame.incoming(), Incoming::from_stack(8));
3290        assert!(text.contains("x64.mov_rm_64 [$rsp + 8]"), "{text}");
3291        assert!(text.contains("x64.mov_rm_64 [$rsp + 16]"), "{text}");
3292    }
3293
3294    #[test]
3295    fn a_realigned_frame_reaches_the_caller_s_arguments_through_the_frame_pointer() {
3296        let i64 = Type::int(64);
3297        let (mut names, mut source, block, args) = blank(&[i64; 7]);
3298        let wide = slot(&mut source, block, 64, 32);
3299        let mut build = Builder::new(&mut source, block);
3300        build.store(args[6], wide, plain(), Flags::default());
3301        build.ret(&[args[6]]);
3302
3303        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
3304            .expect("every instruction has a rule");
3305        let stack = lowered.stack;
3306        let mut out = lowered.func;
3307        let env = env();
3308        let allocation = rucc_regalloc::run(&mut out, &env, "test");
3309        let layout = stack.layout(Layout::new(&SYSV, REGS));
3310        let frame = Frame::of(&out, &allocation, &layout);
3311        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
3312
3313        // A local wanting thirty two byte alignment makes the prologue force the stack pointer,
3314        // which throws away how far the caller's stack was. So the load the lowering wrote off the
3315        // stack pointer is rewritten to read through the frame pointer, at the one distance that
3316        // survives: the word the prologue pushed the frame pointer into, and the return address
3317        // above it.
3318        let text = mir::print_func(&out, &names, &REGS);
3319        assert_eq!(frame.realign(), Some(32));
3320        assert_eq!(frame.incoming(), Incoming::from_frame(16));
3321        assert!(text.contains("x64.mov_rm_64 [$rbp + 16]"), "{text}");
3322        assert!(!text.contains("x64.mov_rm_64 [$rsp"), "{text}");
3323    }
3324
3325    #[test]
3326    fn a_jump_is_the_edge_and_nothing_else() {
3327        let i32 = Type::int(32);
3328        let (mut names, mut source, entry, args) = blank(&[i32]);
3329        let next = source.create_block();
3330        let got = source.append_param(next, i32);
3331        Builder::new(&mut source, entry).jump(next, &[args[0]]);
3332        Builder::new(&mut source, next).ret(&[got]);
3333
3334        // Two blocks and two instructions, and the jump is neither of them. What it was is the
3335        // arm on the first block, and what the arm carries is the argument it was called with.
3336        assert_eq!(
3337            lower(&mut names, &source),
3338            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32 block1(%0)\n\n\
3339             block1(%1:gpr):\n    x64.ret_val_32 %1($rax)\n}\n"
3340        );
3341    }
3342
3343    /// A block that reads what a block below it writes is filled after it, not before it.
3344    ///
3345    /// The blocks are written entry, `early`, `late`, `exit`, and the entry jumps straight past
3346    /// `early` to `late`, so `late` dominates `early` while sitting below it in the function.
3347    /// Filling them in the order they are written reaches the read in `early` first, and reading
3348    /// a value with no register yet mints one. The cast in `late` is no instruction at all, so
3349    /// what it does is give its answer the register its operand is already in, and that is not
3350    /// the register the read minted. Nothing writes the register the read minted. The printer
3351    /// says `%?` for a register nothing defines, which is what this looks for, and what came out
3352    /// of the real bug was SQLite loading a stack slot no store ever reached.
3353    #[test]
3354    fn a_block_that_reads_what_a_block_below_it_writes_is_filled_after_it() {
3355        let i64 = Type::int(64);
3356        let (mut names, mut source, entry, args) = blank(&[i64, i64]);
3357        let early = source.create_block();
3358        let late = source.create_block();
3359        let exit = source.create_block();
3360
3361        Builder::new(&mut source, entry).jump(late, &[]);
3362        let ptr = cast(&mut source, late, Opcode::IntToPtr, args[0], Type::PTR);
3363        Builder::new(&mut source, early).ret(&[ptr]);
3364        let mut build = Builder::new(&mut source, late);
3365        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
3366        build.br_if(cond, early, &[], exit, &[]);
3367        Builder::new(&mut source, exit).ret(&[args[1]]);
3368
3369        let text = lower(&mut names, &source);
3370        assert!(!text.contains("%?"), "every register has something that writes it: {text}");
3371    }
3372
3373    /// A constant is written where it is wanted rather than where the IR defined it, and two
3374    /// blocks wanting the same one is two places. Writing it once and reading it in both is a
3375    /// register read where nothing wrote it, unless the block it was written in happens to
3376    /// dominate the other, which nothing here checks and which the second arm of a branch never
3377    /// does. Each block gets its own copy of the number instead.
3378    #[test]
3379    fn a_constant_two_blocks_want_is_written_in_both_of_them() {
3380        let i32 = Type::int(32);
3381        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
3382        let then = source.create_block();
3383        let other = source.create_block();
3384        let join = source.create_block();
3385        let got = source.append_param(join, i32);
3386
3387        let mut build = Builder::new(&mut source, entry);
3388        let seven = build.iconst(i32, 7);
3389        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
3390        build.br_if(cond, then, &[], other, &[]);
3391        // Both arms want the seven in a register, because a block argument is never an immediate,
3392        // and neither arm dominates the other.
3393        Builder::new(&mut source, then).jump(join, &[seven]);
3394        Builder::new(&mut source, other).jump(join, &[seven]);
3395        Builder::new(&mut source, join).ret(&[got]);
3396
3397        let text = lower(&mut names, &source);
3398        assert_eq!(text.matches("x64.mov_ri_32 7").count(), 2, "one seven per block: {text}");
3399    }
3400
3401    /// An argument on an edge out of a block that leaves two ways is read after every instruction
3402    /// of the block is written, and reading one can write an instruction, which would land after
3403    /// the branch that has already jumped past it. The branch goes back on the end.
3404    #[test]
3405    fn a_constant_an_edge_wants_is_written_before_the_branch_and_not_after_it() {
3406        let i32 = Type::int(32);
3407        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
3408        let then = source.create_block();
3409        let join = source.create_block();
3410        let got = source.append_param(join, i32);
3411
3412        let mut build = Builder::new(&mut source, entry);
3413        let nine = build.iconst(i32, 9);
3414        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
3415        build.br_if(cond, then, &[], join, &[nine]);
3416        Builder::new(&mut source, then).jump(join, &[args[0]]);
3417        Builder::new(&mut source, join).ret(&[got]);
3418
3419        let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
3420            .expect("every instruction has a rule")
3421            .func;
3422        let entry = out.entry().expect("an entry block");
3423        let last = out.terminator(entry).expect("a block that leaves two ways has a branch");
3424        let branch = names.intern("x64.br_cond_8");
3425        assert_eq!(
3426            out[last].opcode,
3427            mir::Opcode::new(branch),
3428            "the branch is last: {}",
3429            mir::print_func(&out, &names, &REGS)
3430        );
3431    }
3432
3433    #[test]
3434    fn a_conditional_branch_is_lowered_to_the_condition_and_nothing_about_where_it_goes() {
3435        let i32 = Type::int(32);
3436        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
3437        let then = source.create_block();
3438        let other = source.create_block();
3439        let mut build = Builder::new(&mut source, entry);
3440        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
3441        build.br_if(cond, then, &[], other, &[]);
3442        Builder::new(&mut source, then).ret(&[args[0]]);
3443        Builder::new(&mut source, other).ret(&[args[1]]);
3444
3445        // The comparison writes a byte and the branch reads it, and neither says a block. Both
3446        // arms are on the entry block, in the order the branch took them, so the arm that runs
3447        // when the condition holds is the first.
3448        assert_eq!(
3449            lower(&mut names, &source),
3450            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
3451             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr = x64.cmp_set_l_32 %0, %1\n    \
3452             x64.br_cond_8 %2, block1, block2\n\n\
3453             block1:\n    x64.ret_val_32 %0($rax)\n\n\
3454             block2:\n    x64.ret_val_32 %1($rax)\n}\n"
3455        );
3456    }
3457
3458    /// A choice between two values, which is one instruction and no blocks at all.
3459    ///
3460    /// The arms come out the other way round from the IR, because a conditional move overwrites its
3461    /// destination and the destination is the arm taken when the condition does not hold. The
3462    /// condition arrives last for the same reason: it is read by the test in front of the move
3463    /// rather than by the move.
3464    #[test]
3465    fn a_select_is_lowered_to_a_test_and_a_conditional_move() {
3466        let i32 = Type::int(32);
3467        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
3468        let mut build = Builder::new(&mut source, entry);
3469        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
3470        let picked = build.select(cond, args[0], args[1]);
3471        build.ret(&[picked]);
3472
3473        assert_eq!(
3474            lower(&mut names, &source),
3475            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
3476             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr = x64.cmp_set_l_32 %0, %1\n    \
3477             %3:gpr(reuse 1) = x64.test_cmov_ne_32 %1, %0, %2\n    \
3478             x64.ret_val_32 %3($rax)\n}\n"
3479        );
3480    }
3481
3482    #[test]
3483    fn a_branch_over_a_block_is_a_whole_function_now() {
3484        let i32 = Type::int(32);
3485        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
3486        let then = source.create_block();
3487        let other = source.create_block();
3488        let join = source.create_block();
3489        let got = source.append_param(join, i32);
3490        let mut build = Builder::new(&mut source, entry);
3491        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
3492        build.br_if(cond, then, &[], other, &[]);
3493        let mut build = Builder::new(&mut source, then);
3494        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
3495        build.jump(join, &[sum]);
3496        Builder::new(&mut source, other).jump(join, &[args[1]]);
3497        Builder::new(&mut source, join).ret(&[got]);
3498
3499        // `int f(int a, int b) { if (a < b) return a + b; else return b; }` end to end, written
3500        // the way a front end writes it: both arms of the branch are blocks of their own and the
3501        // return is the block they meet at. No edge here is critical, because the two arms out of
3502        // the entry carry nothing and the two arms into the join each leave a block that goes
3503        // nowhere else, so each has its own end to put its move at.
3504        let mut out = func(&source, &mut names, &SYSV, &Elsewhere::default())
3505            .expect("every instruction has a rule")
3506            .func;
3507        assert_eq!(crate::split::critical(&mut out), 0, "no edge here is critical");
3508        let env = env();
3509        let allocation = rucc_regalloc::run(&mut out, &env, "test");
3510        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
3511        finish(
3512            &mut out,
3513            &allocation,
3514            &frame,
3515            &Stack::default(),
3516            Convention::new(&SYSV, &FRAME),
3517            &mut names,
3518        );
3519
3520        // One epilogue, on the join, which is the one block the function leaves from, and the
3521        // moves that give the join its parameter are at the end of each arm. Every register is
3522        // physical and the branch is still a branch on a register, because turning it into a
3523        // `test` and a `jcc` is the block layout's and there is no block layout yet.
3524        let text = mir::print_func(&out, &names, &REGS);
3525        assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
3526        assert!(text.contains("x64.br_cond_8"), "{text}");
3527        assert!(text.contains("x64.add_rr_32"), "{text}");
3528        assert!(!text.contains('%'), "{text}");
3529    }
3530
3531    #[test]
3532    fn a_critical_edge_is_split_before_the_allocator_ever_sees_it() {
3533        let i32 = Type::int(32);
3534        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
3535        let then = source.create_block();
3536        let join = source.create_block();
3537        let got = source.append_param(join, i32);
3538        let mut build = Builder::new(&mut source, entry);
3539        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
3540        build.br_if(cond, then, &[], join, &[args[1]]);
3541        Builder::new(&mut source, then).jump(join, &[args[0]]);
3542        let mut build = Builder::new(&mut source, join);
3543        let twice = build.binary(Opcode::Add, got, got, Flags::default());
3544        build.ret(&[twice]);
3545
3546        // The else arm is critical: the entry block leaves two ways and the join is arrived at
3547        // two ways, and the arm carries a value. Without splitting it the allocator asserts,
3548        // because the move that gives the join its parameter would have to run at the end of a
3549        // block that also goes to the other arm.
3550        let mut out = func(&source, &mut names, &SYSV, &Elsewhere::default())
3551            .expect("every instruction has a rule")
3552            .func;
3553        assert_eq!(crate::split::critical(&mut out), 1);
3554        let env = env();
3555        let allocation = rucc_regalloc::run(&mut out, &env, "test");
3556        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
3557        finish(
3558            &mut out,
3559            &allocation,
3560            &frame,
3561            &Stack::default(),
3562            Convention::new(&SYSV, &FRAME),
3563            &mut names,
3564        );
3565
3566        // The block the split added is where the move went, and it is the whole of that block.
3567        let text = mir::print_func(&out, &names, &REGS);
3568        assert_eq!(out.block_count(), 4, "{text}");
3569        assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
3570    }
3571
3572    #[test]
3573    fn a_call_passes_what_the_convention_says_and_takes_back_what_it_says() {
3574        let i32 = Type::int(32);
3575        let (mut names, mut source, block, args) = blank(&[i32, i32]);
3576        let sig =
3577            source.add_signature(Signature::new().with_params(&[i32, i32]).with_returns(&[i32]));
3578        let callee = names.intern("g");
3579        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0], args[1]]);
3580        let got = source[call].first_result.expect("an integer comes back");
3581        Builder::new(&mut source, block).ret(&[got]);
3582
3583        // `int f(int a, int b) { return g(a, b); }`. The arguments arrived where the call wants
3584        // them, so what the call reads is what arrived, and the whole of the convention is in the
3585        // constraints rather than in a move.
3586        let text = lower(&mut names, &source);
3587        assert!(text.contains("= x64.call %0($rdi), %1($rsi), @g"), "{text}");
3588        assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
3589        // What the call writes is the value that comes back and then every register the callee is
3590        // free to destroy, in both classes, which is the whole of what stops the allocator from
3591        // leaving something in one of them.
3592        assert!(text.contains("%2:gpr($rax), $rcx, $rdx, $r8, $r9, $r10, $r11, $xmm0,"), "{text}");
3593        assert!(text.contains("$xmm15 = x64.call"), "{text}");
3594    }
3595
3596    #[test]
3597    fn what_the_frame_owes_a_call_comes_back_with_the_function() {
3598        let i32 = Type::int(32);
3599        let sig = |source: &mut Func| source.add_signature(Signature::new().with_params(&[i32]));
3600
3601        let (mut names, mut source, block, args) = blank(&[i32]);
3602        let sig = sig(&mut source);
3603        let callee = names.intern("g");
3604        Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
3605        let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
3606            .expect("every instruction has a rule");
3607
3608        // Nothing on the stack, so nothing owed, but not a leaf either: a function that calls
3609        // owes the callee an aligned stack pointer and may not use the red zone.
3610        assert_eq!(out.stack.calls, Some(0));
3611        let layout = out.stack.layout(Layout::new(&SYSV, REGS));
3612        assert!(!layout.leaf);
3613        assert_eq!(layout.outgoing, 0);
3614
3615        // The same call under the other convention owes thirty two bytes for the callee to spill
3616        // its register arguments into, which is a fact about the convention and not about the call.
3617        let out = func(&source, &mut names, &x86_64::WIN64, &Elsewhere::default())
3618            .expect("every instruction has a rule");
3619        assert_eq!(out.stack.calls, Some(32));
3620
3621        // And a function that calls nothing is a leaf, which is what says it may use the red zone.
3622        let (mut names, mut source, block, args) = blank(&[i32]);
3623        Builder::new(&mut source, block).ret(&[args[0]]);
3624        let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
3625            .expect("every instruction has a rule");
3626        assert_eq!(out.stack.calls, None);
3627        assert!(out.stack.layout(Layout::new(&SYSV, REGS)).leaf);
3628    }
3629
3630    #[test]
3631    fn a_value_that_outlives_a_call_is_not_left_where_the_call_destroys_it() {
3632        let i32 = Type::int(32);
3633        let (mut names, mut source, block, args) = blank(&[i32]);
3634        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
3635        let callee = names.intern("g");
3636        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
3637        let got = source[call].first_result.expect("an integer comes back");
3638        let mut build = Builder::new(&mut source, block);
3639        let sum = build.binary(Opcode::Add, got, args[0], Flags::default());
3640        build.ret(&[sum]);
3641
3642        // `int f(int a) { return g(a) + a; }`, which is the smallest program that asks the
3643        // question: `a` is read after the call and `rdi` is a register the call destroys.
3644        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
3645            .expect("every instruction has a rule");
3646        let layout = lowered.stack.layout(Layout::new(&SYSV, REGS));
3647        let mut out = lowered.func;
3648        let env = env();
3649        let allocation = rucc_regalloc::run(&mut out, &env, "test");
3650        let frame = Frame::of(&out, &allocation, &layout);
3651        finish(
3652            &mut out,
3653            &allocation,
3654            &frame,
3655            &Stack::default(),
3656            Convention::new(&SYSV, &FRAME),
3657            &mut names,
3658        );
3659
3660        // It went to a register the callee has to put back, and the prologue and epilogue are what
3661        // put it back, which is the whole bargain the two halves of a convention make.
3662        let text = mir::print_func(&out, &names, &REGS);
3663        assert!(text.contains("$rbx"), "{text}");
3664        assert!(!text.contains('%'), "{text}");
3665        assert_eq!(text.matches("x64.call").count(), 1, "{text}");
3666    }
3667
3668    #[test]
3669    fn a_call_with_more_arguments_than_registers_writes_the_rest_into_the_outgoing_area() {
3670        let i64 = Type::int(64);
3671        let (mut names, mut source, block, args) = blank(&[i64]);
3672        let seven = vec![i64; 7];
3673        let sig = source.add_signature(Signature::new().with_params(&seven));
3674        let callee = names.intern("g");
3675        let passed = vec![args[0]; 7];
3676        Builder::new(&mut source, block).call(callee, sig, &passed);
3677
3678        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
3679            .expect("the seventh goes to memory");
3680        // The bytes the call needs are on the layout the frame is worked out from, so that the
3681        // frame reserves as many as the widest call in the function asked for.
3682        assert_eq!(lowered.stack.calls, Some(8));
3683        let text = mir::print_func(&lowered.func, &names, &REGS);
3684        assert!(text.contains("x64.mov_mr_64 %0, [$rsp]\n"), "{text}");
3685    }
3686
3687    #[test]
3688    fn a_call_this_cannot_make_is_reported_rather_than_made() {
3689        let (mut names, mut source, block, _) = blank(&[]);
3690        let returns = [Type::float(rucc_ir::Float::F80), Type::int(64)];
3691        let sig = source.add_signature(Signature::new().with_returns(&returns));
3692        let callee = names.intern("g");
3693        Builder::new(&mut source, block).call(callee, sig, &[]);
3694        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
3695            .expect_err("a long double is on the x87");
3696        assert_eq!(failed.to_string(), "what this call gives back is on the x87 stack");
3697    }
3698
3699    /// A `long double` on its own is a different answer, because on its own it comes back on the
3700    /// x87 stack rather than in a register, which is somewhere the call cannot be said to write.
3701    ///
3702    /// So the call gives back nothing at all and the value is taken off the stack by the `fstp`
3703    /// straight after it. That instruction has to be straight after it: the stack is one place and
3704    /// anything else that touched it before this ran would be looking at the value still on it.
3705    #[test]
3706    fn a_call_that_gives_back_a_long_double_takes_it_off_the_stack_at_once() {
3707        let (mut names, mut source, block, _) = blank(&[]);
3708        let long_double = Type::float(rucc_ir::Float::F80);
3709        let sig = source.add_signature(Signature::new().with_returns(&[long_double]));
3710        let callee = names.intern("g");
3711        Builder::new(&mut source, block).call(callee, sig, &[]);
3712
3713        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
3714            .expect("the value comes back in st0");
3715        let text = mir::print_func(&lowered.func, &names, &REGS);
3716        let after: Vec<&str> =
3717            text.lines().skip_while(|line| !line.contains("x64.call")).skip(1).collect();
3718        assert_eq!(after[0].trim(), "%0:gpr = x64.lea_64 [$rsp]", "{text}");
3719        assert_eq!(after[1].trim(), "x64.fstp_t [%0]", "{text}");
3720        // And the slot it went into is the sixteen bytes the type takes, like every other one.
3721        assert_eq!(lowered.stack.locals.len(), 1, "{text}");
3722        assert_eq!(lowered.stack.locals[0].size, X87_BYTES);
3723    }
3724
3725    #[test]
3726    fn a_call_through_an_address_goes_through_the_register_the_address_is_in() {
3727        let i32 = Type::int(32);
3728        let (mut names, mut source, block, args) = blank(&[Type::PTR, i32]);
3729        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
3730        let varargs = source.push_abis(&[]);
3731        let info = source.add_call(CallInfo { callee: None, signature: sig, varargs });
3732        let mut build = Builder::new(&mut source, block);
3733        let inst = InstData {
3734            args: build.func().push_values(&[args[0], args[1]]),
3735            extra: Extra::Call(info),
3736            ..InstData::new(Opcode::CallIndirect)
3737        };
3738        let called = build.inst(inst, &[i32]);
3739        let got = source[called].first_result.expect("an integer comes back");
3740        Builder::new(&mut source, block).ret(&[got]);
3741
3742        // `int f(int (*g)(int), int a) { return g(a); }`. The first operand is the address and
3743        // the arguments are the ones behind it, and everything else about the call is what a call
3744        // to a name would have been.
3745        let text = lower(&mut names, &source);
3746        assert!(text.contains("= x64.call_reg %0, %1($rdi)"), "{text}");
3747        assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
3748        assert!(!text.contains("@g"), "a call through an address names nobody: {text}");
3749    }
3750
3751    #[test]
3752    fn an_instruction_no_rule_covers_is_reported() {
3753        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
3754        let mut build = Builder::new(&mut source, block);
3755        let operands = build.func().push_values(&[args[0]]);
3756        build.inst(InstData { args: operands, ..InstData::new(Opcode::Prefetch) }, &[]);
3757
3758        // A hint about an address, which nothing writes an instruction for yet. Nothing about it
3759        // is a width or a register, so there is nothing for the message to add beyond the name.
3760        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
3761            .expect_err("no rule writes a prefetch");
3762        assert_eq!(failed.to_string(), "no rule lowers a `prefetch`");
3763
3764        // A `prefetch` produces nothing, so there is no type in the message and nothing invents
3765        // one, and the instruction comes back so a caller can ask the function where it was.
3766        let inst = failed.inst().expect("the instruction it is about");
3767        assert_eq!(source[inst].opcode, Opcode::Prefetch);
3768    }
3769
3770    /// A barrier is written by name here, and what it is depends on the ordering and on nothing
3771    /// else. `crate::expand` is where the reasoning about this machine's memory model lives.
3772    #[test]
3773    fn a_barrier_is_one_instruction_at_the_strongest_ordering_and_none_below_it() {
3774        for order in MemOrder::all().filter(|&order| order != MemOrder::NotAtomic) {
3775            let (mut names, mut source, block, _) = blank(&[]);
3776            let mut build = Builder::new(&mut source, block);
3777            build
3778                .inst(InstData { extra: Extra::Order(order), ..InstData::new(Opcode::Fence) }, &[]);
3779
3780            let text = lower(&mut names, &source);
3781            assert_eq!(text.contains("x64.mfence"), order == MemOrder::SeqCst, "{order:?}: {text}");
3782        }
3783    }
3784
3785    /// A compare and exchange is written by name too, and at the width of the value rather than at
3786    /// the width of the address, which is the mistake worth pinning: everything here is a pointer
3787    /// and only the value says how many bytes the instruction touches.
3788    #[test]
3789    fn a_compare_and_exchange_is_one_instruction_at_the_width_of_the_value() {
3790        for bits in [8, 16, 32, 64] {
3791            let ty = Type::int(bits);
3792            let (mut names, mut source, block, args) = blank(&[Type::PTR, ty, ty]);
3793            let mut build = Builder::new(&mut source, block);
3794            let mem = build.func().add_mem(MemInfo {
3795                size: u64::from(bits / 8),
3796                align: bits / 8,
3797                order: MemOrder::SeqCst,
3798                ..plain()
3799            });
3800            let operands = build.func().push_values(&[args[0], args[1], args[2]]);
3801            build.inst(
3802                InstData {
3803                    args: operands,
3804                    extra: Extra::Mem(mem),
3805                    ..InstData::new(Opcode::Cmpxchg)
3806                },
3807                &[ty, Type::I1],
3808            );
3809
3810            // Two values out of one instruction, the first of them in the register the machine
3811            // reads the expected value out of, the second free for the allocator to place. The
3812            // address is the memory operand and neither of the two values is.
3813            let text = lower(&mut names, &source);
3814            let written = format!("%3:gpr($rax), %4:gpr = x64.cmpxchg_{bits} %1($rax), %2, [%0]");
3815            assert!(text.contains(&written), "{bits}: {text}");
3816        }
3817    }
3818
3819    #[test]
3820    fn more_values_back_than_the_convention_has_registers_for_is_reported() {
3821        let i64 = Type::int(64);
3822        let (mut names, mut source, block, args) = blank(&[i64, i64, i64]);
3823        let mut build = Builder::new(&mut source, block);
3824        build.ret(&[args[0], args[1], args[2]]);
3825
3826        // Two integers come back in `rax` and `rdx` and a third has nowhere to go, which is not a
3827        // gap in the rules but the convention saying no. The front end classifies before it gets
3828        // here, so this is the shape that would mean the classification went wrong.
3829        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
3830            .expect_err("only two come back");
3831        assert_eq!(
3832            failed.to_string(),
3833            "what this function gives back takes more registers than this convention has for it"
3834        );
3835
3836        let inst = failed.inst().expect("the instruction it is about");
3837        assert_eq!(source[inst].opcode, Opcode::Return);
3838    }
3839
3840    /// A refusal about a signature has no instruction, which is what makes it the one arm apart.
3841    ///
3842    /// Everything else is about something written somewhere in the body and hands it back so a
3843    /// caller can ask the function where it came from. A parameter arrives before the first
3844    /// instruction runs, so there is nothing in the body to point at and the message is about
3845    /// the function.
3846    #[test]
3847    fn a_refusal_about_a_parameter_has_no_instruction_to_point_at() {
3848        let missing = Unsupported::Argument { index: 0, missing: Missing::OnX87 };
3849        assert_eq!(missing.inst(), None);
3850    }
3851
3852    /// An `alloca` of a fixed size, which is what every local whose address is taken becomes.
3853    fn slot(source: &mut Func, block: Block, size: u64, align: u32) -> Value {
3854        let info = MemInfo { size, align, ..plain() };
3855        let mut build = Builder::new(source, block);
3856        let mem = build.func().add_mem(info);
3857        build.value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR)
3858    }
3859
3860    #[test]
3861    fn a_local_is_memory_in_the_frame_and_one_instruction_that_says_where() {
3862        let (mut names, mut source, block, _) = blank(&[]);
3863        let slot = slot(&mut source, block, 4, 4);
3864        let mut build = Builder::new(&mut source, block);
3865        let nine = build.iconst(Type::int(32), 9);
3866        build.store(nine, slot, plain(), Flags::default());
3867        let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
3868        build.ret(&[loaded]);
3869
3870        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
3871            .expect("every instruction has a rule");
3872
3873        // Four bytes on the list the frame is laid out from, and the one instruction that reads
3874        // where they went. Its displacement is nothing here because there is no frame yet, and
3875        // which instruction is waiting for which local is what `finish` is handed.
3876        assert_eq!(lowered.stack.locals, vec![Local { size: 4, align: 4 }]);
3877        assert_eq!(lowered.stack.addresses.len(), 1);
3878        assert_eq!(lowered.stack.addresses[0].1, 0);
3879        assert_eq!(
3880            mir::print_func(&lowered.func, &names, &REGS),
3881            "mfunc @f {\nblock0:\n    %0:gpr = x64.lea_64 [$rsp]\n    \
3882             %1:gpr = x64.mov_ri_32 9\n    x64.mov_mr_32 %1, [%0]\n    \
3883             %2:gpr = x64.mov_rm_32 [%0]\n    x64.ret_val_32 %2($rax)\n}\n"
3884        );
3885    }
3886
3887    #[test]
3888    fn the_frame_is_what_fills_the_address_of_a_local_in() {
3889        let (mut names, mut source, block, _) = blank(&[]);
3890        let slot = slot(&mut source, block, 4, 4);
3891        let mut build = Builder::new(&mut source, block);
3892        let nine = build.iconst(Type::int(32), 9);
3893        build.store(nine, slot, plain(), Flags::default());
3894        let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
3895        build.ret(&[loaded]);
3896
3897        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
3898            .expect("every instruction has a rule");
3899        let stack = lowered.stack;
3900        let mut out = lowered.func;
3901        let env = env();
3902        let allocation = rucc_regalloc::run(&mut out, &env, "test");
3903        let layout = stack.layout(Layout::new(&SYSV, REGS));
3904        let frame = Frame::of(&out, &allocation, &layout);
3905        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
3906
3907        // `int f(void) { int x; x = 9; return x; }` with the address of `x` taken, end to end.
3908        // A leaf small enough to live in the red zone takes no frame at all, so the stack pointer
3909        // never moves and the four bytes are below it, which is what the negative offset is. The
3910        // instruction the lowering left with nothing in its displacement now has the answer in it.
3911        let text = mir::print_func(&out, &names, &REGS);
3912        assert!(text.contains("$rax = x64.lea_64 [$rsp - 8]"), "{text}");
3913        assert!(!text.contains("x64.sub_ri_64"), "{text}");
3914        assert_eq!(frame.size(), 0);
3915        assert_eq!(frame.local(0), Some(-8));
3916    }
3917
3918    /// An `alloca` whose size is an operand, which is a variable length array.
3919    fn growing(source: &mut Func, block: Block, size: Value, align: u32) -> Value {
3920        let info = MemInfo { size: 0, align, ..plain() };
3921        let mut build = Builder::new(source, block);
3922        let mem = build.func().add_mem(info);
3923        let args = build.func().push_values(&[size]);
3924        build.value(
3925            InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) },
3926            Type::PTR,
3927        )
3928    }
3929
3930    #[test]
3931    fn a_stack_slot_whose_size_is_not_known_until_it_runs_takes_the_bytes_off_the_stack_pointer() {
3932        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
3933        let slot = growing(&mut source, block, args[0], 16);
3934        Builder::new(&mut source, block).ret(&[slot]);
3935
3936        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
3937            .expect("every instruction has a rule");
3938
3939        // The bytes come off the stack pointer where the declaration stands and the address is
3940        // where the stack pointer then is, which is one subtraction and one `lea` rather than a
3941        // slot the frame laid out. Nothing is on the list of locals, because there is nothing
3942        // about this the frame could place.
3943        let text = mir::print_func(&lowered.func, &names, &REGS);
3944        assert!(text.contains("$rsp = x64.sub_rr_64 $rsp, %0"), "{text}");
3945        assert!(text.contains("x64.lea_64 [$rsp]"), "{text}");
3946        assert!(lowered.stack.locals.is_empty(), "{text}");
3947        assert_eq!(lowered.stack.dynamic.len(), 1);
3948        assert!(lowered.stack.grown_at.is_some());
3949    }
3950
3951    #[test]
3952    fn a_growing_slot_wanting_more_alignment_than_the_stack_pointer_has_is_reported() {
3953        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
3954        let slot = growing(&mut source, block, args[0], 32);
3955        Builder::new(&mut source, block).ret(&[slot]);
3956
3957        // Thirty two is more than a call leaves the stack pointer on, so giving it what it asked
3958        // for means masking the stack pointer after moving it, and after that no constant reaches
3959        // the rest of the frame from the frame pointer either. A second pointer held for the
3960        // purpose is what fixes it and there is not one yet.
3961        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
3962            .expect_err("nothing realigns a frame that grows");
3963        assert_eq!(
3964            failed.to_string(),
3965            "this local wants more alignment than the stack pointer is left on, which needs a \
3966             base register nothing here keeps"
3967        );
3968    }
3969
3970    #[test]
3971    fn a_frame_that_grows_reaches_its_own_locals_through_the_frame_pointer() {
3972        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
3973        let fixed = slot(&mut source, block, 4, 4);
3974        let mut build = Builder::new(&mut source, block);
3975        let nine = build.iconst(Type::int(32), 9);
3976        build.store(nine, fixed, plain(), Flags::default());
3977        let grown = growing(&mut source, block, args[0], 16);
3978        Builder::new(&mut source, block).ret(&[grown]);
3979
3980        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
3981            .expect("every instruction has a rule");
3982        let stack = lowered.stack;
3983        let mut out = lowered.func;
3984        let env = env();
3985        let allocation = rucc_regalloc::run(&mut out, &env, "test");
3986        let layout = stack.layout(Layout::new(&SYSV, REGS));
3987        let frame = Frame::of(&out, &allocation, &layout);
3988        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
3989
3990        // The stack pointer moves in the middle of the function, so the four bytes of the fixed
3991        // local are not a constant away from it any more and the frame pointer is what reaches
3992        // them. The frame keeps one whatever the flags asked for, takes its bytes rather than
3993        // living in the red zone, and the address of the growing slot is off the stack pointer as
3994        // it stands after the subtraction rather than off anything the prologue left.
3995        let text = mir::print_func(&out, &names, &REGS);
3996        assert!(frame.grows());
3997        assert!(frame.frame_pointer());
3998        assert!(frame.size() > 0, "{text}");
3999        assert!(text.contains("x64.lea_64 [$rbp"), "{text}");
4000        assert!(text.contains("$rsp = x64.sub_rr_64 $rsp"), "{text}");
4001        assert!(text.contains("x64.lea_64 [$rsp]"), "{text}");
4002    }
4003
4004    #[test]
4005    fn an_address_is_read_written_and_added_to_like_the_integer_it_is() {
4006        let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
4007        let mut build = Builder::new(&mut source, block);
4008        let stepped = build.func().push_values(&[args[0], args[1]]);
4009        let next =
4010            build.value(InstData { args: stepped, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
4011        let loaded = build.load(Type::int(32), next, plain(), Flags::default());
4012        build.ret(&[loaded]);
4013
4014        // `int f(int *p, long i) { return *(int *)((char *)p + i); }`. Nothing about this is new
4015        // in the rule set, which is the point: the two addresses arrive in registers because an
4016        // address is an integer as wide as one, and the arithmetic on them is the add it always
4017        // was, so every rule written about an add reaches it.
4018        //
4019        // The add stays its own instruction rather than folding into the address the load reads
4020        // from. Two registers with no scale on either is the one addressing mode the rules have no
4021        // load through, because the folds that exist are the displacement one and the scaled ones,
4022        // and this is neither. That is a peephole worth having and not a thing this changes.
4023        assert_eq!(
4024            lower(&mut names, &source),
4025            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
4026             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n    \
4027             %3:gpr = x64.mov_rm_32 [%2]\n    x64.ret_val_32 %3($rax)\n}\n"
4028        );
4029    }
4030
4031    /// The address of a file scope name, which is what every use of a global and every string
4032    /// literal starts from.
4033    fn address_of(source: &mut Func, block: Block, names: &mut Interner, name: &str) -> Value {
4034        let symbol = names.intern(name);
4035        let mut build = Builder::new(source, block);
4036        build.value(
4037            InstData { extra: Extra::Symbol(symbol), ..InstData::new(Opcode::GlobalAddr) },
4038            Type::PTR,
4039        )
4040    }
4041
4042    #[test]
4043    fn the_address_of_a_name_is_one_instruction_carrying_the_name() {
4044        let (mut names, mut source, block, _) = blank(&[]);
4045        let counter = address_of(&mut source, block, &mut names, "counter");
4046        let mut build = Builder::new(&mut source, block);
4047        let loaded = build.load(Type::int(32), counter, plain(), Flags::default());
4048        build.ret(&[loaded]);
4049
4050        // `extern int counter; int f(void) { return counter; }`. The address is an addressing mode
4051        // that names no register and carries the symbol, which is what the assembler writes
4052        // relative to `%rip` and what the object writer leaves a relocation for.
4053        assert_eq!(
4054            lower(&mut names, &source),
4055            "mfunc @f {\nblock0:\n    %0:gpr = x64.lea_64 [@counter]\n    \
4056             %1:gpr = x64.mov_rm_32 [%0]\n    x64.ret_val_32 %1($rax)\n}\n"
4057        );
4058    }
4059
4060    #[test]
4061    fn the_address_of_a_name_outside_the_file_is_read_out_of_the_offset_table() {
4062        let (mut names, mut source, block, _) = blank(&[]);
4063        let away = address_of(&mut source, block, &mut names, "away");
4064        Builder::new(&mut source, block).ret(&[away]);
4065        let elsewhere: Elsewhere = [names.intern("away")].into_iter().collect();
4066
4067        // `extern void away(void); void *f(void) { return away; }`. A load and not an address
4068        // computation, because the distance from here to a name a shared library may be the one
4069        // that defines is not a number any link can work out, and the slot the linker fills in is
4070        // in this program and so is a distance it has.
4071        let out =
4072            func(&source, &mut names, &SYSV, &elsewhere).expect("every instruction has a rule");
4073        assert_eq!(
4074            mir::print_func(&out.func, &names, &REGS),
4075            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rm_64 [got @away]\n    \
4076             x64.ret_val_64 %0($rax)\n}\n"
4077        );
4078    }
4079
4080    /// One `asm` statement, with its template and its constraint list written as a program does.
4081    fn assembly(
4082        source: &mut Func,
4083        block: Block,
4084        names: &mut Interner,
4085        template: &str,
4086        constraints: &str,
4087        args: &[Value],
4088        results: &[Type],
4089    ) -> Inst {
4090        let info = AsmInfo {
4091            template: names.intern(template),
4092            constraints: names.intern(constraints),
4093            clobbers: names.intern("memory"),
4094            targets: rucc_ir::BlockCallList::EMPTY,
4095        };
4096        Builder::new(source, block).inline_asm(info, args, results, Flags::VOLATILE)
4097    }
4098
4099    #[test]
4100    fn an_asm_with_an_empty_template_and_no_operands_is_no_instructions() {
4101        let (mut names, mut source, block, _) = blank(&[]);
4102        assembly(&mut source, block, &mut names, "", "", &[], &[]);
4103        Builder::new(&mut source, block).ret(&[]);
4104
4105        // `asm volatile ("" : : : "memory")`, which is a barrier and nothing else. The barrier was
4106        // spent on the optimizer, which has finished by now, so what is left is nothing.
4107        assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n}\n");
4108    }
4109
4110    #[test]
4111    fn an_output_an_input_is_tied_to_is_the_register_that_input_arrived_in() {
4112        let i32 = Type::int(32);
4113        let (mut names, mut source, block, args) = blank(&[i32]);
4114        let out = assembly(&mut source, block, &mut names, "", "=r,0", &args, &[i32]);
4115        let produced = source[out].results().next().expect("one result");
4116        Builder::new(&mut source, block).ret(&[produced]);
4117
4118        // `asm ("" : "=r" (x) : "0" (x))`, which is how a program stops the optimizer following a
4119        // value without changing it. The two share a place and the template writes nothing over
4120        // it, so the value comes back out of the register it went in.
4121        assert_eq!(
4122            lower(&mut names, &source),
4123            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
4124             x64.ret_val_32 %0($rax)\n}\n"
4125        );
4126    }
4127
4128    #[test]
4129    fn an_output_written_plus_is_the_same_rename() {
4130        let i32 = Type::int(32);
4131        let (mut names, mut source, block, args) = blank(&[i32]);
4132        let out = assembly(&mut source, block, &mut names, "", "+r", &args, &[i32]);
4133        let produced = source[out].results().next().expect("one result");
4134        Builder::new(&mut source, block).ret(&[produced]);
4135
4136        // `asm ("" : "+r" (x))`, which says the same thing in one operand instead of two.
4137        assert_eq!(
4138            lower(&mut names, &source),
4139            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
4140             x64.ret_val_32 %0($rax)\n}\n"
4141        );
4142    }
4143
4144    #[test]
4145    fn an_output_nothing_is_tied_to_is_a_zero() {
4146        let i32 = Type::int(32);
4147        let (mut names, mut source, block, _) = blank(&[]);
4148        let out = assembly(&mut source, block, &mut names, "", "=r", &[], &[i32]);
4149        let produced = source[out].results().next().expect("one result");
4150        Builder::new(&mut source, block).ret(&[produced]);
4151
4152        // `asm ("" : "=r" (y))`, whose answer is whatever the assembly left in the register, and
4153        // an empty template leaves nothing. A definite value rather than a register nothing wrote,
4154        // because the allocator is owed a definition before the use however little the program is.
4155        assert_eq!(
4156            lower(&mut names, &source),
4157            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 0\n    x64.ret_val_32 %0($rax)\n}\n"
4158        );
4159    }
4160
4161    #[test]
4162    fn an_asm_with_instructions_in_its_template_is_refused_as_an_asm() {
4163        let (mut names, mut source, block, _) = blank(&[]);
4164        assembly(&mut source, block, &mut names, "nop", "", &[], &[]);
4165        Builder::new(&mut source, block).ret(&[]);
4166
4167        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
4168            .expect_err("nothing here assembles a template");
4169        assert_eq!(
4170            failed.to_string(),
4171            "this `asm` has instructions in its template, which nothing here assembles"
4172        );
4173    }
4174
4175    #[test]
4176    fn a_constraint_list_that_does_not_describe_the_operands_is_refused() {
4177        let i32 = Type::int(32);
4178        let (mut names, mut source, block, args) = blank(&[i32]);
4179        assembly(&mut source, block, &mut names, "", "=r", &args, &[]);
4180        Builder::new(&mut source, block).ret(&[]);
4181
4182        // An output with no result to be, which is what the front end never writes and what a
4183        // hand written module can. Refused rather than placed by a guess.
4184        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
4185            .expect_err("the list and the instruction disagree");
4186        assert_eq!(failed.to_string(), "this `asm` has an operand this cannot place");
4187    }
4188
4189    /// A cast between a pointer and an integer, at whatever width the result is asked for.
4190    fn cast(source: &mut Func, block: Block, opcode: Opcode, from: Value, to: Type) -> Value {
4191        let mut build = Builder::new(source, block);
4192        let args = build.func().push_values(&[from]);
4193        build.value(InstData { args, ..InstData::new(opcode) }, to)
4194    }
4195
4196    #[test]
4197    fn a_cast_between_a_pointer_and_an_integer_as_wide_is_no_instruction_at_all() {
4198        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
4199        let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(64));
4200        Builder::new(&mut source, block).ret(&[number]);
4201
4202        // `long f(void *p) { return (long)p; }`. An address on this machine is an integer as wide
4203        // as the machine addresses, so the cast changes what the type system calls the value and
4204        // changes nothing about the value, and the register holding it is the one that held it.
4205        assert_eq!(
4206            lower(&mut names, &source),
4207            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
4208             x64.ret_val_64 %0($rax)\n}\n"
4209        );
4210    }
4211
4212    #[test]
4213    fn a_null_pointer_is_a_constant_that_reaches_a_register_before_anything_reads_it() {
4214        let (mut names, mut source, block, _) = blank(&[]);
4215        let mut build = Builder::new(&mut source, block);
4216        let zero = build.iconst(Type::int(64), 0);
4217        let null = cast(&mut source, block, Opcode::IntToPtr, zero, Type::PTR);
4218        Builder::new(&mut source, block).ret(&[null]);
4219
4220        // `void *f(void) { return 0; }`. The cast is nothing, and reading its operand is what
4221        // writes the zero down: a constant is materialized where it is wanted rather than where
4222        // the IR defined it, and without the read there would be no instruction at all.
4223        assert_eq!(
4224            lower(&mut names, &source),
4225            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_64 0\n    x64.ret_val_64 %0($rax)\n}\n"
4226        );
4227    }
4228
4229    #[test]
4230    fn the_five_linkages_the_ir_has_narrow_to_the_three_an_object_file_can_say() {
4231        let readings = [
4232            (Linkage::External, mir::Binding::Global),
4233            (Linkage::Common, mir::Binding::Global),
4234            (Linkage::Internal, mir::Binding::Local),
4235            (Linkage::Weak, mir::Binding::Weak),
4236            (Linkage::LinkOnce, mir::Binding::Weak),
4237        ];
4238        for (linkage, wanted) in readings {
4239            let (mut names, mut source, block, _) = blank(&[]);
4240            source.linkage = linkage;
4241            Builder::new(&mut source, block).ret(&[]);
4242            let out = func(&source, &mut names, &SYSV, &Elsewhere::default()).expect("a return");
4243            // The narrowing is done here rather than where the object is written, because a
4244            // machine function is all the assembler and the writer are ever handed.
4245            assert_eq!(out.func.binding, wanted, "{linkage:?}");
4246        }
4247    }
4248
4249    /// The visibility makes the same trip and is not narrowed on the way, because ELF says all
4250    /// three of them.
4251    ///
4252    /// Here for the reason the linkage above is here. A machine function is the whole of what the
4253    /// assembler and the object writer are handed, so a fact about the symbol that does not get
4254    /// onto one is a fact that is gone by the time anything could write it down, and the way that
4255    /// shows up is a shared library exporting the wrong set of names with nothing said anywhere.
4256    #[test]
4257    fn the_visibility_survives_the_trip_from_the_ir_to_a_machine_function() {
4258        let readings = [
4259            (Visibility::Default, mir::Visibility::Default),
4260            (Visibility::Hidden, mir::Visibility::Hidden),
4261            (Visibility::Protected, mir::Visibility::Protected),
4262        ];
4263        for (visibility, wanted) in readings {
4264            let (mut names, mut source, block, _) = blank(&[]);
4265            source.visibility = visibility;
4266            Builder::new(&mut source, block).ret(&[]);
4267            let out = func(&source, &mut names, &SYSV, &Elsewhere::default()).expect("a return");
4268            assert_eq!(out.func.visibility, wanted, "{visibility:?}");
4269        }
4270    }
4271
4272    #[test]
4273    fn a_cast_between_a_pointer_and_a_narrower_integer_is_reported() {
4274        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
4275        let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(32));
4276        Builder::new(&mut source, block).ret(&[number]);
4277
4278        // The front end never writes one: it casts at the address width and truncates or extends
4279        // around it, so both of those are the rules they always were. IR from somewhere else that
4280        // does write one is refused rather than compiled to a move that keeps the high half.
4281        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
4282            .expect_err("no rule narrows an address");
4283        assert_eq!(failed.to_string(), "no rule lowers a `ptrtoint` producing a `i32`");
4284    }
4285
4286    /// The type this machine has no register for.
4287    fn long_double() -> Type {
4288        Type::float(rucc_ir::Float::F80)
4289    }
4290
4291    #[test]
4292    fn a_double_widened_and_narrowed_again_goes_out_through_the_frame_and_back() {
4293        let f64 = Type::float(rucc_ir::Float::F64);
4294        let (mut names, mut source, block, args) = blank(&[f64]);
4295        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
4296        let back = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
4297        Builder::new(&mut source, block).ret(&[back]);
4298
4299        // `double f(double d) { long double x = d; return x; }`. The x87 reads memory and nothing
4300        // else, so the value is written to the crossing slot, loaded at the format that widens it
4301        // and put in the slot the eighty bit value lives in. Coming back is the same three the
4302        // other way. Both slots are addressed by a `lea` with nothing in it yet, which is what
4303        // every address in a frame looks like here until `finish` has the numbers.
4304        assert_eq!(
4305            lower(&mut names, &source),
4306            "mfunc @f {\nblock0:\n    \
4307             %0:xmm($xmm0) = x64.arg_val_f64\n    \
4308             %1:gpr = x64.lea_64 [$rsp]\n    \
4309             %2:gpr = x64.lea_64 [$rsp]\n    \
4310             x64.movsd_mr %0, [%1]\n    \
4311             x64.fld_l [%1]\n    \
4312             x64.fstp_t [%2]\n    \
4313             %3:gpr = x64.lea_64 [$rsp]\n    \
4314             %4:gpr = x64.lea_64 [$rsp]\n    \
4315             x64.fld_t [%3]\n    \
4316             x64.fstp_l [%4]\n    \
4317             %5:xmm = x64.movsd_rm [%4]\n    \
4318             x64.ret_val_f64 %5($xmm0)\n}\n"
4319        );
4320    }
4321
4322    #[test]
4323    fn a_long_double_has_sixteen_bytes_of_its_own_and_keeps_them() {
4324        let f64 = Type::float(rucc_ir::Float::F64);
4325        let (mut names, mut source, block, args) = blank(&[f64]);
4326        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
4327        let once = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
4328        let twice = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
4329        let mut build = Builder::new(&mut source, block);
4330        let sum = build.binary(Opcode::FAdd, once, twice, Flags::default());
4331        build.ret(&[sum]);
4332
4333        let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
4334            .expect("every instruction is written");
4335
4336        // Two slots and not four: sixteen bytes for the one eighty bit value, which is what the
4337        // psABI says one takes and is aligned to, and eight for the crossing, which every group
4338        // in the function shares because nothing is ever left in it. The value's slot is its own
4339        // for the whole function, so reading it twice reads the same sixteen bytes.
4340        assert_eq!(
4341            out.stack.locals,
4342            vec![Local { size: 8, align: 8 }, Local { size: 16, align: 16 }]
4343        );
4344    }
4345
4346    #[test]
4347    fn an_integer_becomes_a_long_double_by_being_loaded_as_one() {
4348        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
4349        let wide = cast(&mut source, block, Opcode::SIToFP, args[0], long_double());
4350        let back =
4351            cast(&mut source, block, Opcode::FPTrunc, wide, Type::float(rucc_ir::Float::F64));
4352        Builder::new(&mut source, block).ret(&[back]);
4353
4354        // `double f(long n) { long double x = n; return x; }`. `fild` is the same push at another
4355        // format, so the conversion is the load and there is no instruction that converts.
4356        let text = lower(&mut names, &source);
4357        assert!(text.contains("x64.mov_mr_64 %0, [%1]"), "{text}");
4358        assert!(text.contains("x64.fild_ll [%1]"), "{text}");
4359    }
4360
4361    #[test]
4362    fn a_long_double_becoming_an_integer_cuts_towards_zero_with_the_control_word() {
4363        let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
4364        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
4365        let whole = cast(&mut source, block, Opcode::FPToSI, wide, Type::int(32));
4366        Builder::new(&mut source, block).ret(&[whole]);
4367
4368        // The one conversion here with no single instruction behind it. C cuts towards zero and
4369        // the unit rounds the way its control word says, so the word is saved, ORed with the two
4370        // bits that mean truncate, loaded, used and put back. Nine instructions for what `fisttp`
4371        // does in one, and `spec/10-backend.md` section 10.8 says why that one is not used.
4372        let text = lower(&mut names, &source);
4373        let group: Vec<&str> = text
4374            .lines()
4375            .map(str::trim)
4376            .filter(|line| line.starts_with("x64.f") || line.contains("_16"))
4377            .collect();
4378        assert_eq!(
4379            group,
4380            [
4381                "x64.fld_l [%1]",
4382                "x64.fstp_t [%2]",
4383                "x64.fnstcw [%5]",
4384                "%6:gpr = x64.mov_rm_16 [%5]",
4385                "%7:gpr(reuse 1) = x64.or_ri_16 %6, 3072",
4386                "x64.mov_mr_16 %7, [%5 + 2]",
4387                "x64.fldcw [%5 + 2]",
4388                "x64.fld_t [%3]",
4389                "x64.fistp_l [%4]",
4390                "x64.fldcw [%5]",
4391            ],
4392            "{text}"
4393        );
4394    }
4395
4396    #[test]
4397    fn a_long_double_is_read_and_written_as_the_bits_it_already_is() {
4398        let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::PTR]);
4399        let mut build = Builder::new(&mut source, block);
4400        let value = build.load(long_double(), args[0], plain(), Flags::default());
4401        build.store(value, args[1], plain(), Flags::default());
4402        build.ret(&[]);
4403
4404        // `void f(long double *a, long double *b) { *b = *a; }`. A copy is a push and a pop at the
4405        // format the value is already in, which neither converts nor looks: a signalling NaN stays
4406        // one and nothing is raised, which is the whole of what makes it a copy.
4407        let text = lower(&mut names, &source);
4408        let group: Vec<&str> =
4409            text.lines().map(str::trim).filter(|line| line.starts_with("x64.f")).collect();
4410        assert_eq!(
4411            group,
4412            ["x64.fld_t [%0]", "x64.fstp_t [%2]", "x64.fld_t [%3]", "x64.fstp_t [%1]"],
4413            "{text}"
4414        );
4415    }
4416
4417    /// Two `long double` values, from two `double` parameters, and the instructions that made
4418    /// them, which every test below this one throws away.
4419    fn two_long_doubles(source: &mut Func, block: Block, args: &[Value]) -> (Value, Value) {
4420        let left = cast(source, block, Opcode::FPExt, args[0], long_double());
4421        let right = cast(source, block, Opcode::FPExt, args[1], long_double());
4422        (left, right)
4423    }
4424
4425    /// The x87 instructions of a function, in order, with everything else dropped.
4426    fn stack_only(text: &str) -> Vec<&str> {
4427        text.lines().map(str::trim).filter(|line| line.contains("x64.f")).collect()
4428    }
4429
4430    /// The two frame slots the last two addresses of a function were taken of, which in a
4431    /// comparison are the two operands in the order they go on the stack.
4432    fn pushed(out: &Lowered) -> Vec<usize> {
4433        let taken: Vec<usize> = out.stack.addresses.iter().map(|&(_, local)| local).collect();
4434        taken[taken.len() - 2..].to_vec()
4435    }
4436
4437    #[test]
4438    fn adding_two_long_doubles_pushes_both_and_leaves_the_answer_in_a_slot() {
4439        let f64 = Type::float(rucc_ir::Float::F64);
4440        let (mut names, mut source, block, args) = blank(&[f64, f64]);
4441        let (left, right) = two_long_doubles(&mut source, block, &args);
4442        let sum =
4443            Builder::new(&mut source, block).binary(Opcode::FAdd, left, right, Flags::default());
4444        let back = cast(&mut source, block, Opcode::FPTrunc, sum, f64);
4445        Builder::new(&mut source, block).ret(&[back]);
4446
4447        // `double f(double a, double b) { return (long double) a + (long double) b; }`. The last
4448        // four lines are the add: both operands pushed, the instruction that names neither of
4449        // them because they are the top two of a stack, and the answer taken off into its slot.
4450        let text = lower(&mut names, &source);
4451        assert_eq!(
4452            stack_only(&text),
4453            [
4454                "x64.fld_l [%2]",
4455                "x64.fstp_t [%3]",
4456                "x64.fld_l [%4]",
4457                "x64.fstp_t [%5]",
4458                "x64.fld_t [%6]",
4459                "x64.fld_t [%7]",
4460                "x64.fadd_p",
4461                "x64.fstp_t [%8]",
4462                "x64.fld_t [%9]",
4463                "x64.fstp_l [%10]",
4464            ],
4465            "{text}"
4466        );
4467    }
4468
4469    #[test]
4470    fn a_subtraction_pushes_the_left_operand_first_and_asks_for_the_att_spelling() {
4471        let f64 = Type::float(rucc_ir::Float::F64);
4472        let (mut names, mut source, block, args) = blank(&[f64, f64]);
4473        let (left, right) = two_long_doubles(&mut source, block, &args);
4474        let less =
4475            Builder::new(&mut source, block).binary(Opcode::FSub, left, right, Flags::default());
4476        let back = cast(&mut source, block, Opcode::FPTrunc, less, f64);
4477        Builder::new(&mut source, block).ret(&[back]);
4478
4479        // The left one goes on first, so it ends up under the right one, and the answer wanted is
4480        // the one below minus the top. In AT&T that is `fsubrp`, since `fsubp` there is `DE E0+i`
4481        // and computes the other one. The `r` says which spelling this is and not which order the
4482        // pushes were in. `crates/rucc/tests/x87.rs` is what says the answer is right, because a
4483        // name is what got this wrong the first time.
4484        let text = lower(&mut names, &source);
4485        assert_eq!(
4486            &stack_only(&text)[4..8],
4487            ["x64.fld_t [%6]", "x64.fld_t [%7]", "x64.fsubr_p", "x64.fstp_t [%8]"],
4488            "{text}"
4489        );
4490    }
4491
4492    #[test]
4493    fn negating_a_long_double_turns_the_sign_over_and_reads_nothing() {
4494        let f64 = Type::float(rucc_ir::Float::F64);
4495        let (mut names, mut source, block, args) = blank(&[f64]);
4496        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
4497        let flipped = Builder::new(&mut source, block).unary(Opcode::FNeg, wide, long_double());
4498        let back = cast(&mut source, block, Opcode::FPTrunc, flipped, f64);
4499        Builder::new(&mut source, block).ret(&[back]);
4500
4501        // `fchs` and not a subtraction from zero, which would give a different answer at a negative
4502        // zero and would signal at a NaN. It does not read the value as a number at all.
4503        let text = lower(&mut names, &source);
4504        assert_eq!(
4505            &stack_only(&text)[2..5],
4506            ["x64.fld_t [%3]", "x64.fchs", "x64.fstp_t [%4]"],
4507            "{text}"
4508        );
4509    }
4510
4511    #[test]
4512    fn comparing_two_long_doubles_puts_the_left_one_on_top() {
4513        let f64 = Type::float(rucc_ir::Float::F64);
4514        let (mut names, mut source, block, args) = blank(&[f64, f64]);
4515        let (left, right) = two_long_doubles(&mut source, block, &args);
4516        let mut build = Builder::new(&mut source, block);
4517        build.fcmp(FloatPred::Ogt, left, right, Flags::default());
4518        build.ret(&[]);
4519
4520        // `a > b`. `fucomip` asks about the top of the stack against what is under it, so the
4521        // operand the predicate is about has to go on last, which is the other way round from the
4522        // arithmetic above. The pop that clears the loser and the byte that reads the flags are
4523        // both inside the one opcode.
4524        let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
4525            .expect("every instruction is written");
4526        let slots = pushed(&out);
4527        assert_eq!(slots, [2, 1], "the right operand goes on first and the left one on top");
4528        let text = mir::print_func(&out.func, &names, &REGS);
4529        assert_eq!(
4530            &stack_only(&text)[4..],
4531            ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
4532            "{text}"
4533        );
4534    }
4535
4536    #[test]
4537    fn a_comparison_that_the_machine_has_backwards_swaps_the_two_pushes() {
4538        let f64 = Type::float(rucc_ir::Float::F64);
4539        let (mut names, mut source, block, args) = blank(&[f64, f64]);
4540        let (left, right) = two_long_doubles(&mut source, block, &args);
4541        let mut build = Builder::new(&mut source, block);
4542        build.fcmp(FloatPred::Olt, left, right, Flags::default());
4543        build.ret(&[]);
4544
4545        // `a < b` is `b > a` and this machine has the one condition, so the same opcode runs with
4546        // the operands the other way round. The same trade the vector rules make, and it has to
4547        // be the same one: a `long double` comparison that picked a different condition from the
4548        // `double` comparison of the same two numbers would be wrong at exactly the unordered
4549        // cases the two conditions differ on.
4550        //
4551        // Which slot each push names is the whole of the difference from the test above, and the
4552        // text does not show it, since an address in a frame is a `lea` with nothing in it until
4553        // `finish` has the numbers. So the slots are what is read here.
4554        let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
4555            .expect("every instruction is written");
4556        let slots = pushed(&out);
4557        assert_eq!(slots, [1, 2], "the left operand goes on first and the right one on top");
4558        let text = mir::print_func(&out.func, &names, &REGS);
4559        assert_eq!(
4560            &stack_only(&text)[4..],
4561            ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
4562            "{text}"
4563        );
4564    }
4565
4566    #[test]
4567    fn an_ordered_equal_needs_a_second_byte_to_put_the_two_conditions_together() {
4568        let f64 = Type::float(rucc_ir::Float::F64);
4569        let (mut names, mut source, block, args) = blank(&[f64, f64]);
4570        let (left, right) = two_long_doubles(&mut source, block, &args);
4571        let mut build = Builder::new(&mut source, block);
4572        build.fcmp(FloatPred::Oeq, left, right, Flags::default());
4573        build.ret(&[]);
4574
4575        // Equal and ordered are two conditions and the flags carry both, so the opcode writes a
4576        // second register as well as the one the value is in and ANDs them together. Said here by
4577        // handing it a spare, since an instruction that wrote a register nothing knew about would
4578        // be an instruction the allocator could put a live value in the way of.
4579        let text = lower(&mut names, &source);
4580        assert!(text.contains("%8:gpr, %9:gpr = x64.fucomip_set_e_and_np"), "{text}");
4581    }
4582
4583    #[test]
4584    fn a_comparison_that_is_never_asked_is_reported() {
4585        let f64 = Type::float(rucc_ir::Float::F64);
4586        let (mut names, mut source, block, args) = blank(&[f64, f64]);
4587        let (left, right) = two_long_doubles(&mut source, block, &args);
4588        let mut build = Builder::new(&mut source, block);
4589        build.fcmp(FloatPred::False, left, right, Flags::default());
4590        build.ret(&[]);
4591
4592        // Always false is a constant and not a comparison, so there is no condition to pick and
4593        // nothing here folds it into one: an instruction that quietly agreed with it would hide
4594        // that the optimizer left a comparison in that it should have taken out.
4595        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
4596            .expect_err("no condition is always false");
4597        assert_eq!(failed.to_string(), "no rule lowers a `fcmp` producing a `i1`");
4598    }
4599
4600    #[test]
4601    fn a_long_double_constant_is_the_bits_of_it_put_where_the_value_lives() {
4602        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
4603        let mut build = Builder::new(&mut source, block);
4604        // `1.5L`, which is the leading bit and one more of significand, and an exponent of zero.
4605        let one_and_a_half = build.fconst(long_double(), 0x3fff_c000_0000_0000_0000);
4606        build.store(one_and_a_half, args[0], plain(), Flags::default());
4607        build.ret(&[]);
4608
4609        // No x87 instruction at all. A slot holding one of these is the value, so a constant is
4610        // its ten bytes written where the value lives, and whatever reads it does the `fld`.
4611        let text = lower(&mut names, &source);
4612        assert!(text.contains("x64.mov_ri_64 -4611686018427387904"), "{text}");
4613        assert!(text.contains("x64.mov_ri_16 16383"), "{text}");
4614        assert!(text.contains("x64.mov_mr_16 %3, [%1 + 8]"), "{text}");
4615        // The six bytes above the ten are the padding that makes the type sixteen wide, and they
4616        // are unspecified rather than zero, so nothing writes them.
4617        assert_eq!(text.matches("x64.mov_mr").count(), 2, "{text}");
4618    }
4619
4620    #[test]
4621    fn a_negative_long_double_constant_keeps_the_bit_above_its_exponent() {
4622        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
4623        let mut build = Builder::new(&mut source, block);
4624        let minus = build.fconst(long_double(), 0xbfff_c000_0000_0000_0000);
4625        build.store(minus, args[0], plain(), Flags::default());
4626        build.ret(&[]);
4627
4628        // `-1.5L`. The sign is the top bit of the two byte half, so the immediate that half is put
4629        // in a register with is above the signed range of sixteen bits and has to stay there: read
4630        // as a number it would be negative, and it is not a number, it is two bytes.
4631        let text = lower(&mut names, &source);
4632        assert!(text.contains("x64.mov_ri_16 49151"), "{text}");
4633    }
4634
4635    #[test]
4636    fn a_long_double_crosses_an_edge_as_an_address_and_is_copied_where_it_lands() {
4637        let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
4638        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
4639        let next = source.create_block();
4640        let param = source.append_param(next, long_double());
4641        Builder::new(&mut source, block).jump(next, &[wide]);
4642        Builder::new(&mut source, next).ret(&[param]);
4643
4644        // What the edge carries is the address of the slot the value is already in, which is an
4645        // ordinary register the allocator has an opinion about. The block on the other side copies
4646        // the sixteen bytes into a slot of its own before anything reads them, so a second edge
4647        // handing over a second address would still leave one place for a reader to look.
4648        let text = lower(&mut names, &source);
4649        let second: Vec<&str> = text
4650            .lines()
4651            .skip_while(|line| !line.starts_with("block1"))
4652            .skip(1)
4653            .take(3)
4654            .map(str::trim)
4655            .collect();
4656        assert_eq!(
4657            second,
4658            ["x64.fld_t [%4]", "%5:gpr = x64.lea_64 [$rsp]", "x64.fstp_t [%5]"],
4659            "{text}"
4660        );
4661    }
4662
4663    #[test]
4664    fn more_long_doubles_at_a_block_than_the_stack_is_deep_are_reported() {
4665        let f64 = Type::float(rucc_ir::Float::F64);
4666        let (mut names, mut source, block, args) = blank(&[f64]);
4667        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
4668        let next = source.create_block();
4669        let params: Vec<Value> =
4670            (0..=X87_DEPTH).map(|_| source.append_param(next, long_double())).collect();
4671        let carried: Vec<Value> = params.iter().map(|_| wide).collect();
4672        Builder::new(&mut source, block).jump(next, &carried);
4673        Builder::new(&mut source, next).ret(&[params[0]]);
4674
4675        // The copies go through the x87 stack so that every one of them is read before any of them
4676        // is written, which is what makes a block that swaps two of these right. Nine of them do
4677        // not fit on the stack, and copying the ninth before or after the rest is the order that
4678        // could be wrong, so it is refused instead.
4679        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
4680            .expect_err("nine do not fit on the stack");
4681        assert_eq!(
4682            failed.to_string(),
4683            "block1 takes 9 parameters of type `f80` and only 8 can cross an edge at once"
4684        );
4685        assert_eq!(failed.inst(), None);
4686    }
4687}