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