Skip to main content

rucc_codegen/
lower.rs

1//! The selector: an IR function becomes a machine IR function.
2//!
3//! Design: `spec/10-backend.md` sections 10.2 and 10.3.
4//!
5//! What the matcher in [`crate::select`] does is answer one question about one term. What this
6//! does is ask it: walk a function, decide which terms are worth asking about, and build machine
7//! instructions out of what comes back. Nothing here decides what an IR term lowers to. That is
8//! in `rules/x86-64.rules` and it is proved before it is used, which is the whole point of the
9//! arrangement and the reason this file is short.
10//!
11//! # What it does with an instruction
12//!
13//! It tries the ways the instruction can be shown to the matcher, in order, and takes the first
14//! that a rule fires on. [`crate::term`] is what a way of showing one is, and the order is the
15//! most specific first: an operand that is a constant is offered as a constant before it is
16//! offered as a register, and an operand computed by an instruction of its own is offered as
17//! that instruction before it is offered as a register. A rule that wants an immediate too wide
18//! for the machine has a guard that turns it down, and the search carries on to the way of
19//! showing it that puts the constant in a register, which is the right answer and is one nobody
20//! had to write down.
21//!
22//! A constant is not lowered where it is written. It is materialized where a register for it is
23//! first wanted, which is what keeps a constant that every use folded into an immediate from
24//! leaving a dead instruction behind, and it also gives the value the shortest live range it
25//! could have. The instruction that materializes it comes from the rule set like everything else.
26//!
27//! # What it does not do yet
28//!
29//! Everything is in the general purpose registers, because every rule in the set is about an
30//! integer, so a call that passes a `double` and a function that returns one are both reported
31//! rather than lowered. So is an argument that travels on the stack, on either side of a call,
32//! and so is a call through an address rather than to a name.
33//!
34//! # A call
35//!
36//! Not a rule, because a rule pattern sees one term and what a call's operands are is whatever
37//! the signature made them. [`crate::abi`] builds one instead, out of the same description of the
38//! convention the arguments come from: the values it passes are reads constrained to the
39//! registers the convention places them in, what comes back is a write constrained to the
40//! register it comes back in, and every other register the callee is free to destroy is a write
41//! of that register and nothing else, which is all the allocator needs to keep a value out of it.
42//!
43//! What that costs the frame is an argument area, and nothing after selection could work out how
44//! big, so the size of the widest call is given back with the function. A function that makes no
45//! call at all is a leaf, and a leaf is the function that may use the red zone.
46//!
47//! # Where a block goes
48//!
49//! On the block, which is what machine IR does with an edge and is why the branches need no more
50//! rule language than the arithmetic did. A rule never names a block, so an unconditional jump
51//! has no rule at all and a conditional branch has one that is about its condition and nothing
52//! else. The arms are copied across after the block is filled, arguments and all, because an
53//! argument that is a constant is materialized where a register for it is first wanted and the
54//! end of the block is where an edge wants it.
55//!
56//! What this leaves behind is a function whose blocks are in the order the IR held them and whose
57//! branches are still branches on a register. Turning one into a `test` and a `jcc` is the block
58//! layout's, since which of the two arms falls through is the layout's answer, and [`crate::split`]
59//! has to run before allocation so that every edge carrying a value has somewhere to put it.
60//!
61//! A store and a return are the two things here that write no register. A store is emitted like
62//! everything else and the only difference is that there is no result to put anywhere, so the
63//! operands the target describes are all reads. A return is the same, and what it is for is its
64//! one operand: the target constrains it to the register the caller reads the value out of, and
65//! the allocator is what gets it there. The instruction that leaves is not chosen here at all,
66//! because the epilogue has to give the frame back first and [`crate::finish`] writes that after
67//! allocation, so a return of nothing is lowered to nothing.
68//!
69//! The entry block is the one block whose parameters are not block parameters here. They are the
70//! function's arguments, they are already somewhere when it starts, and [`crate::abi`] is what
71//! says where. An argument that arrives on the stack is reported rather than read, because where
72//! the stack put it is a distance into a frame and no frame exists until after allocation.
73//!
74//! Blocks are walked in the order the function holds them and a value is expected to be defined
75//! before it is used, which is true of the IR this is given because every pass before it keeps
76//! definitions ahead of uses.
77
78use std::fmt;
79
80use rucc_base::Interner;
81use rucc_ir::{Block, Def, Extra, Func, Inst, Opcode, Type, Value};
82use rucc_mir as mir;
83use rucc_target::x86_64;
84use rucc_target::{CallRegs, RegClass};
85
86use crate::abi::{self, Missing, Refused};
87use crate::frame::{Layout, Local};
88use crate::select::{Match, Piece, Rule, Table};
89use crate::term::{MAX_ARGS, PLAIN, Plan, Shown, Term, Terms};
90
91/// The prefix a rule file puts in front of a machine term, which says which target it belongs
92/// to and is not part of the opcode.
93const PREFIX: &str = "x64.";
94
95/// How wide an address is on this target, which is the width a cast between a pointer and an
96/// integer has to be at for the cast to be nothing.
97const ADDRESS_BITS: u32 = 64;
98
99/// Why a function could not be lowered.
100///
101/// One reason and then nothing. A function with no rule for something in it is a function this
102/// cannot finish, and the second thing it could not lower is not news.
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub enum Unsupported {
105    /// An instruction no rule fires on.
106    Inst {
107        /// The instruction that stopped it.
108        inst: Inst,
109        /// What the rule file would call it, or nothing if the rule language has no name for it
110        /// at all, which is what an instruction at a width nothing is written about looks like.
111        term: Option<&'static str>,
112        /// The opcode, which is what gets named when the rule language has no word for it.
113        ///
114        /// An opcode the rule language has no word for is exactly the opcode no rule lowers, so
115        /// without this the message would be empty in every case where somebody needs it.
116        opcode: Opcode,
117        /// What it produces, or nothing for an instruction that is only an effect.
118        ty: Option<Type>,
119    },
120    /// A parameter that does not arrive somewhere this can bring it in from.
121    ///
122    /// Not an instruction, which is why it is a separate arm: it is a fact about the signature
123    /// and there is nothing in the body of the function to point at.
124    Argument {
125        /// Its position in the signature.
126        index: usize,
127        /// What is wrong with where it arrives.
128        missing: Missing,
129    },
130    /// A call that passes or gives back a value this cannot put where the convention wants it.
131    Call {
132        /// The call.
133        inst: Inst,
134        /// Which value, and what is wrong with where it travels.
135        refused: Refused,
136    },
137    /// A stack slot whose size is not known until the function runs, which is what a variable
138    /// length array is.
139    ///
140    /// Not an instruction no rule covers. Growing the stack where the declaration stands is
141    /// arithmetic on the stack pointer, and everything else in the frame then has to be reached
142    /// through a frame pointer instead, and neither of those is a term a rule could be written
143    /// about or a thing the frame here knows how to lay out.
144    Dynamic {
145        /// The `alloca`.
146        inst: Inst,
147    },
148}
149
150impl Unsupported {
151    /// The instruction it is about, or nothing for the one arm that is about a signature.
152    ///
153    /// What a caller wants this for is the span. The function knows where every instruction in
154    /// it came from, so a caller holding both can point a message at the line somebody wrote
155    /// rather than at the file as a whole, and nothing here has to carry a span of its own.
156    pub fn inst(&self) -> Option<Inst> {
157        match *self {
158            Unsupported::Inst { inst, .. }
159            | Unsupported::Call { inst, .. }
160            | Unsupported::Dynamic { inst, .. } => Some(inst),
161            Unsupported::Argument { .. } => None,
162        }
163    }
164}
165
166impl fmt::Display for Unsupported {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        match *self {
169            Unsupported::Inst { term: Some(term), .. } => write!(f, "no rule lowers `{term}`"),
170            Unsupported::Inst { term: None, opcode, ty: Some(ty), .. } => {
171                write!(f, "no rule lowers a `{opcode}` producing a `{ty}`")
172            }
173            Unsupported::Inst { term: None, opcode, ty: None, .. } => {
174                write!(f, "no rule lowers a `{opcode}`")
175            }
176            Unsupported::Argument { index, missing } => {
177                write!(f, "parameter {index} {}", missing.why())
178            }
179            Unsupported::Call { refused: Refused { argument: Some(index), missing }, .. } => {
180                write!(f, "argument {index} of this call {}", missing.why())
181            }
182            Unsupported::Call { refused: Refused { argument: None, missing }, .. } => {
183                write!(f, "what this call gives back {}", missing.why())
184            }
185            Unsupported::Dynamic { .. } => {
186                f.write_str("nothing here grows the stack for a variable length array")
187            }
188        }
189    }
190}
191
192impl std::error::Error for Unsupported {}
193
194/// A lowered function, and what the frame needs that the machine IR does not hold.
195#[derive(Debug)]
196pub struct Lowered {
197    /// The function, in machine instructions.
198    pub func: mir::Func,
199    /// What it wants its stack to look like, which is separate from the function so that the two
200    /// can be read and written at the same time.
201    pub stack: Stack,
202}
203
204/// What a function's stack has to hold, as far as selection is able to say.
205///
206/// All of it is answered here because selection is where a call is built and where an `alloca`
207/// is read, and nothing after it could tell what either of them needed.
208#[derive(Debug, Default)]
209pub struct Stack {
210    /// How many bytes the widest call in the function needs below the stack pointer for the
211    /// arguments it passes there, or `None` for a function that makes no call at all.
212    ///
213    /// `None` is a leaf, which is the function that may use the red zone and the one whose stack
214    /// pointer does not have to be left aligned for anybody.
215    pub calls: Option<u32>,
216    /// The memory the function asked for itself, one entry for every `alloca` in it, in the order
217    /// the walk reached them.
218    pub locals: Vec<Local>,
219    /// Which instruction computes the address of which of those locals.
220    ///
221    /// An address in the frame is a distance from the stack pointer, and there is no frame until
222    /// after allocation, so the instruction is written here with nothing in its displacement and
223    /// [`crate::finish`] writes the number in once [`crate::frame::Frame`] knows it.
224    pub addresses: Vec<(mir::Inst, usize)>,
225}
226
227impl Stack {
228    /// The layout given, with the three fields only the lowering knows the answer to filled in.
229    ///
230    /// Everything else in a layout comes from the flags the function is compiled under or from the
231    /// allocation, so this takes one and returns it rather than building one.
232    #[must_use]
233    pub fn layout<'a>(&'a self, base: Layout<'a>) -> Layout<'a> {
234        Layout {
235            leaf: self.calls.is_none(),
236            outgoing: self.calls.unwrap_or(0),
237            locals: &self.locals,
238            ..base
239        }
240    }
241}
242
243/// The x86-64 machine IR for that function.
244///
245/// # Errors
246///
247/// The first instruction no rule fires on, which today is anything at a width the rule set is not
248/// written at, a parameter that does not arrive in a register this can read, or a call that
249/// passes something this cannot put where the convention wants it.
250pub fn func(
251    source: &Func,
252    names: &mut Interner,
253    conv: &'static CallRegs,
254) -> Result<Lowered, Unsupported> {
255    Lowering::new(source, names, conv).run()
256}
257
258/// One function being lowered.
259struct Lowering<'a> {
260    source: &'a Func,
261    names: &'a mut Interner,
262    out: mir::Func,
263    /// The machine register each IR value is in, once it has one.
264    regs: Vec<Option<mir::Reg>>,
265    /// For a constant that has been written into a register, the block it was written into,
266    /// which is the only block that register is any good in.
267    written: Vec<Option<mir::Block>>,
268    /// How many times each IR value is read, which is what says whether an instruction may be
269    /// folded into the one that reads it.
270    uses: Vec<u32>,
271    /// The block being filled.
272    at: Option<mir::Block>,
273    /// The machine IR block each IR block became.
274    blocks: Vec<Option<mir::Block>>,
275    /// The class an address is in, which is the general purpose one and is not a question: every
276    /// register an addressing mode names holds part of an address, and there is no machine here
277    /// that computes an address anywhere but in this file. Which class a *value* is in is
278    /// [`Lowering::class_of`], and it is a question, because a float is in the other one.
279    gpr: RegClass,
280    /// Where the convention this function is compiled for puts things, which is read for the
281    /// arguments and for the calls.
282    conv: &'static CallRegs,
283    /// What the function wants its stack to look like, filled in as the walk finds out.
284    stack: Stack,
285}
286
287impl<'a> Lowering<'a> {
288    fn new(source: &'a Func, names: &'a mut Interner, conv: &'static CallRegs) -> Self {
289        let counts = source.counts();
290        let name = source.name;
291        let mut uses = vec![0; counts.values];
292        for block in source.blocks() {
293            for inst in source.insts(block) {
294                for &arg in &source[source[inst].args] {
295                    uses[arg.index()] += 1;
296                }
297                for call in source.successors(inst) {
298                    for &arg in &source[call.args] {
299                        uses[arg.index()] += 1;
300                    }
301                }
302            }
303        }
304        Self {
305            source,
306            names,
307            out: mir::Func::new(name),
308            regs: vec![None; counts.values],
309            written: vec![None; counts.values],
310            blocks: vec![None; counts.blocks],
311            uses,
312            at: None,
313            gpr: x86_64::GPR,
314            conv,
315            stack: Stack::default(),
316        }
317    }
318
319    fn run(mut self) -> Result<Lowered, Unsupported> {
320        // Every block before any of them is filled, because a block that jumps forward has to
321        // name the block it jumps to and a machine IR block is named by a handle rather than by
322        // the IR block it came from.
323        for block in self.source.blocks() {
324            let out = self.out.create_block();
325            self.blocks[block.index()] = Some(out);
326        }
327        for block in self.source.blocks() {
328            self.block(block)?;
329        }
330        Ok(Lowered { func: self.out, stack: self.stack })
331    }
332
333    /// One block: its parameters, then every instruction in it that is not folded into another.
334    fn block(&mut self, block: Block) -> Result<(), Unsupported> {
335        let out = self.out_block(block);
336        self.at = Some(out);
337        if self.source.entry() == Some(block) {
338            self.arrive(block, out)?;
339        } else {
340            for &param in self.source[block].params.iter() {
341                let reg = self.out.append_param(out, self.class_of(self.source[param].ty));
342                self.regs[param.index()] = Some(reg);
343            }
344        }
345
346        // What each instruction matched, and which instructions were folded into another. The
347        // instruction that is folded comes before the one that folds it, so the decision has to
348        // be made for the whole block before any of it is written, and it is made backwards: an
349        // instruction that has been folded into a later one does not get to fold anything into
350        // itself, because the rule that took it only reached one level down.
351        let insts: Vec<Inst> = self.source.insts(block).collect();
352        let mut found: Vec<Option<Match<Term>>> = (0..insts.len()).map(|_| None).collect();
353        let mut folded: Vec<Inst> = Vec::new();
354        for (index, &inst) in insts.iter().enumerate().rev() {
355            if folded.contains(&inst) {
356                continue;
357            }
358            if let Some((plan, matched)) = self.select(inst) {
359                folded.extend(self.folds(inst, plan));
360                found[index] = Some(matched);
361            }
362        }
363
364        for (&inst, matched) in insts.iter().zip(found) {
365            if folded.contains(&inst) || self.writes_nothing(inst) {
366                continue;
367            }
368            // A call is built from the convention rather than matched, which is why it is the one
369            // opcode looked at by name here. Through an address it is a different instruction and
370            // the same convention, so the two arrive at the same place and differ in one line of
371            // it.
372            match self.source[inst].opcode {
373                Opcode::Call | Opcode::CallIndirect => {
374                    self.called(inst)?;
375                    continue;
376                }
377                // Built from the frame rather than matched, for the same shape of reason a call
378                // is built from the convention: what a rule replaces a term with is instructions,
379                // and what an `alloca` needs first is bytes, which the rule language has no way
380                // to ask for.
381                Opcode::Alloca => {
382                    self.reserve(inst)?;
383                    continue;
384                }
385                // The address of a name, built here for the same reason an `alloca` is: what a
386                // rule replaces a term with is instructions over values, and the operand of this
387                // one is a symbol, which is a thing the rule language has no way to bind and the
388                // solver has no way to say anything about. There is nothing in `lea sym(%rip)` a
389                // proof over bitvectors could discharge, because what makes it the right answer
390                // is the relocation and what the linker does with it.
391                Opcode::GlobalAddr => {
392                    self.address_of(inst)?;
393                    continue;
394                }
395                // A cast between a pointer and an integer of the same width, which on this
396                // machine is every one the front end writes. No instruction at all, so no rule
397                // could name one.
398                Opcode::PtrToInt | Opcode::IntToPtr => {
399                    self.rename(inst)?;
400                    continue;
401                }
402                _ => {}
403            }
404            let matched = matched.ok_or_else(|| self.unsupported(inst))?;
405            self.emit(inst, &matched)?;
406        }
407        self.edges(block, out)
408    }
409
410    /// One call, which is built from the convention rather than matched against the table for the
411    /// same reason the arguments of the function itself are.
412    ///
413    /// The arguments are read before the call is built, which is what materializes a constant
414    /// argument into a register, since no call passes an immediate.
415    ///
416    /// A call to a name and a call through an address are both here, and what tells them apart is
417    /// the opcode rather than whether a callee was recorded, which is the same thing the verifier
418    /// reads. Through an address the first operand is the address and the arguments are the ones
419    /// behind it, and everything after that is the same: where each argument goes, where the value
420    /// comes back and which registers are gone across it are the convention's answers and the
421    /// convention does not ask what is being called.
422    fn called(&mut self, inst: Inst) -> Result<(), Unsupported> {
423        let data = &self.source[inst];
424        let Extra::Call(info) = data.extra else { return Err(self.unsupported(inst)) };
425        let info = self.source[info];
426        let indirect = data.opcode == Opcode::CallIndirect;
427
428        let values: Vec<Value> = self.source[data.args].to_vec();
429        let callee = if indirect {
430            let &address = values.first().ok_or_else(|| self.unsupported(inst))?;
431            abi::Callee::Through(self.reg_of(address)?)
432        } else {
433            abi::Callee::Named(info.callee.ok_or_else(|| self.unsupported(inst))?)
434        };
435
436        let mut args = Vec::with_capacity(values.len());
437        for value in values.into_iter().skip(usize::from(indirect)) {
438            args.push((self.source[value].ty, self.reg_of(value)?));
439        }
440        let signature = &self.source[info.signature];
441        let variadic = signature.variadic;
442        let returns = signature.return_types().next();
443        // More than one value back is the convention's answer rather than a term's, the same way
444        // a return of two values is, and nothing here has a name for it.
445        if signature.return_types().count() > 1 {
446            return Err(self.unsupported(inst));
447        }
448
449        let block = self.at.expect("a block is being filled");
450        let what = abi::Calling { callee, args: &args, returns, variadic };
451        let made = abi::call(&mut self.out, block, &what, self.conv, self.names)
452            .map_err(|refused| Unsupported::Call { inst, refused })?;
453        let calls = &mut self.stack.calls;
454        *calls = Some(calls.unwrap_or(0).max(made.outgoing));
455        if let (Some(result), Some(reg)) = (data.first_result, made.result) {
456            self.regs[result.index()] = Some(reg);
457        }
458        Ok(())
459    }
460
461    /// One `alloca`: the bytes it asks for go on the list the frame is laid out from, and the
462    /// address of them is one instruction.
463    ///
464    /// The instruction is a `lea` off the stack pointer, which is the one register that reaches
465    /// the frame in every function, and its displacement is left at nothing because there is no
466    /// frame yet. Which instruction is waiting for which local is remembered, and
467    /// [`crate::finish`] fills the numbers in after [`crate::frame::Frame`] has placed them.
468    ///
469    /// There is deliberately no rule for `alloca` and no name for one in [`crate::term`], and
470    /// that is what stops it being folded into something else. An operand shown as the
471    /// instruction that computed it is offered to the matcher by its name, so an `alloca` with no
472    /// name is one no pattern can reach past, and the address it computes is always in a register
473    /// by the time anything reads it.
474    fn reserve(&mut self, inst: Inst) -> Result<(), Unsupported> {
475        let data = &self.source[inst];
476        // A variable length array carries the size it wants as an operand rather than in the
477        // instruction, which is the whole of what tells the two apart here.
478        if !self.source[data.args].is_empty() {
479            return Err(Unsupported::Dynamic { inst });
480        }
481        let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
482        let info = self.source[mem];
483        let size = u32::try_from(info.size).map_err(|_| Unsupported::Dynamic { inst })?;
484        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
485
486        // At least one, because the frame divides by the alignment and an object with no
487        // alignment at all is one the front end had nothing to say about rather than one that may
488        // go anywhere.
489        let index = self.stack.locals.len();
490        self.stack.locals.push(Local { size, align: info.align.max(1) });
491
492        let block = self.at.expect("a block is being filled");
493        let reg = self.new_reg(result);
494        let span = self.source.span(inst);
495        let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
496        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
497        let made =
498            self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
499        self.stack.addresses.push((made, index));
500        Ok(())
501    }
502
503    /// The address of a name: one `lea` off the instruction pointer, with the name on it.
504    ///
505    /// The same instruction an `alloca` gets and for a related reason. An address that is not in
506    /// the program is a `lea` of an addressing mode that names no register, and the mode carries
507    /// the symbol so that [`rucc_asm`] can write it relative to `%rip` and leave the relocation
508    /// for the assembler. Both halves of that already existed: the printer writes `sym(%rip)` and
509    /// the encoder emits the relocation, because a call to a name the file does not define needed
510    /// them first.
511    ///
512    /// There is deliberately no name for this in [`crate::term`], which is what stops the address
513    /// being folded into the instruction that reads it. Folding it is the right thing to do and
514    /// is what turns a load of a global from two instructions into one, but it is a separate
515    /// question about addressing modes and issue #282 is it. Until then the address is in a
516    /// register before anything uses it, which is correct and one instruction longer.
517    ///
518    /// What this does not do is give the name anything to refer to. A module carries its globals
519    /// and nothing writes them out, so a file that defines the variable it reads compiles to a
520    /// reference the linker cannot resolve. Issue #293 is the other half.
521    fn address_of(&mut self, inst: Inst) -> Result<(), Unsupported> {
522        let data = &self.source[inst];
523        let Extra::Symbol(symbol) = data.extra else { return Err(self.unsupported(inst)) };
524        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
525
526        let block = self.at.expect("a block is being filled");
527        let reg = self.new_reg(result);
528        let span = self.source.span(inst);
529        let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
530        self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::of(symbol)).finish();
531        Ok(())
532    }
533
534    /// A conversion that converts nothing: the result is the operand under another type.
535    ///
536    /// `ptrtoint` and `inttoptr` at one width are the whole of this. An address on this machine is
537    /// an integer as wide as the machine addresses, so a cast between the two changes what the
538    /// type system calls the value and changes nothing about the value, and the register holding
539    /// it is the register that already held it. The front end never writes either of them at any
540    /// other width, because it widens or narrows around the cast rather than through it, so the
541    /// two widths disagreeing here means the IR came from somewhere else and is refused rather
542    /// than guessed at.
543    ///
544    /// Reading the operand first is what materializes it when it is a constant, which is the case
545    /// that matters: a null pointer is an `inttoptr` of zero, and that zero has to reach a
546    /// register before anything can call it an address.
547    fn rename(&mut self, inst: Inst) -> Result<(), Unsupported> {
548        let data = &self.source[inst];
549        let [arg] = self.source[data.args] else { return Err(self.unsupported(inst)) };
550        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
551        if !self.is_address_width(self.source[arg].ty)
552            || !self.is_address_width(self.source[result].ty)
553        {
554            return Err(self.unsupported(inst));
555        }
556        let reg = self.reg_of(arg)?;
557        self.regs[result.index()] = Some(reg);
558        Ok(())
559    }
560
561    /// Whether a type is the width an address is, which is what makes a cast to or from one free.
562    fn is_address_width(&self, ty: Type) -> bool {
563        ty.is_ptr() || (ty.is_int() && ty.bits() == ADDRESS_BITS)
564    }
565
566    /// Where a block goes, which in machine IR is on the block rather than on its terminator.
567    ///
568    /// That is why no rule ever names a block: a branch is selected for what it reads and the
569    /// edges are copied across here, arguments and all. The arguments are read last, after every
570    /// instruction of the block is written, because an argument that is a constant is
571    /// materialized where it is first wanted and the end of the block is where an edge wants it.
572    ///
573    /// Which is not quite the end. A block that leaves two ways has the branch as its last
574    /// instruction, and anything appended after a branch is something the branch has already
575    /// jumped past, so a constant materialized here would be a register the block below reads and
576    /// nothing ever writes. The branch is put back on the end when that happened, which is the
577    /// only reordering anything in this crate does and is why the branch is remembered before a
578    /// single argument is read.
579    fn edges(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
580        let Some(term) = self.source.terminator(block) else { return Ok(()) };
581        let branch =
582            if self.source[term].opcode == Opcode::BrIf { self.out.terminator(out) } else { None };
583
584        let calls: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
585        let mut succs = Vec::with_capacity(calls.len());
586        for call in calls {
587            let args: Vec<Value> = self.source[call.args].to_vec();
588            let mut regs = Vec::with_capacity(args.len());
589            for value in args {
590                regs.push(self.reg_of(value)?);
591            }
592            succs.push(mir::BlockCall { block: self.out_block(call.block), args: regs });
593        }
594        if let Some(branch) = branch {
595            if self.out.terminator(out) != Some(branch) {
596                self.out.remove_inst(branch);
597                self.out.append_inst(out, branch);
598            }
599        }
600        *self.out.succs_mut(out) = succs;
601        Ok(())
602    }
603
604    /// The machine IR block an IR block became.
605    fn out_block(&self, block: Block) -> mir::Block {
606        self.blocks[block.index()].expect("every block was created before any was filled")
607    }
608
609    /// The parameters of the entry block, which are the function's arguments.
610    ///
611    /// They are not block parameters in the machine IR and they cannot be. A block parameter is
612    /// given its value by a move on the edge into the block, and there is no edge into an entry
613    /// block, so what arrives in a function is the convention's to say. [`crate::abi`] is what
614    /// says it.
615    fn arrive(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
616        let params = self.source[block].params.clone();
617        let types: Vec<Type> = params.iter().map(|&value| self.source[value].ty).collect();
618        let regs = abi::entry(&mut self.out, out, &types, self.conv, self.names)
619            .map_err(|(index, missing)| Unsupported::Argument { index, missing })?;
620        for (&param, reg) in params.iter().zip(regs) {
621            self.regs[param.index()] = Some(reg);
622        }
623        Ok(())
624    }
625
626    /// Whether an instruction is one no machine instruction is written for where it stands.
627    ///
628    /// Three of them, and none is a lowering decision, which is why none is a rule. A constant is
629    /// written where a register for it is first wanted rather than where the IR put it, and every
630    /// reader of one may have folded it into an immediate, in which case nowhere is the right
631    /// place. A return of nothing has nothing to put anywhere: the epilogue gives the frame back
632    /// and leaves, and it is appended to every block with no successors long after this has
633    /// finished, so a return with a value is one instruction here and a return without one is
634    /// none. An unconditional jump is the third, and there is even less of it: the edge is on the
635    /// block, and whether the block it goes to is the next one and needs no jump at all is the
636    /// block layout's answer rather than this one's.
637    fn writes_nothing(&self, inst: Inst) -> bool {
638        let data = &self.source[inst];
639        match data.opcode {
640            Opcode::IConst | Opcode::Jump => true,
641            Opcode::Return => self.source[data.args].is_empty(),
642            _ => false,
643        }
644    }
645
646    /// The rule that fires on an instruction, and what it bound.
647    ///
648    /// The plans are tried in order and the first that matches wins, which is the maximal munch
649    /// `spec/10-backend.md` asks for: a plan that offers more to the matcher is tried before one
650    /// that offers less.
651    fn select(&self, inst: Inst) -> Option<(Plan, Match<Term>)> {
652        for plan in self.plans(inst) {
653            let terms = Terms::new(self.source, inst, plan);
654            if let Some(matched) = TABLE.find(&terms, Term::Root) {
655                return Some((plan, matched));
656            }
657        }
658        None
659    }
660
661    /// Every way this instruction can be shown to the matcher, most offered first.
662    fn plans(&self, inst: Inst) -> Vec<Plan> {
663        let args = &self.source[self.source[inst].args];
664        let mut plans = vec![PLAIN];
665        for (index, &arg) in args.iter().enumerate().take(MAX_ARGS) {
666            let mut ways = Vec::new();
667            if self.foldable(inst, arg) {
668                ways.push(Shown::Expand);
669            }
670            if Terms::new(self.source, inst, PLAIN).constant(arg).is_some() {
671                ways.push(Shown::Const);
672            }
673            ways.push(Shown::Reg);
674            plans = plans
675                .into_iter()
676                .flat_map(|plan| {
677                    ways.iter().map(move |&way| {
678                        let mut next = plan;
679                        next[index] = way;
680                        next
681                    })
682                })
683                .collect();
684        }
685        plans
686    }
687
688    /// Whether an operand may be shown as the instruction that computed it.
689    ///
690    /// It has to be in the same block, because a rule that folds one instruction into another
691    /// moves the work to where the second one is. It has to be read only by this instruction,
692    /// because folding it does not delete it for anybody else and doing the work twice is not a
693    /// saving. And it has to be something rather than a block parameter, and not a constant,
694    /// which is shown as a constant instead.
695    fn foldable(&self, into: Inst, value: Value) -> bool {
696        let Def::Result { inst, .. } = self.source[value].def else { return false };
697        if self.source[inst].opcode == Opcode::IConst || self.uses[value.index()] != 1 {
698            return false;
699        }
700        self.source.block_of(inst).is_some()
701            && self.source.block_of(inst) == self.source.block_of(into)
702    }
703
704    /// The instructions a match folded into the one it matched.
705    ///
706    /// The plan is what says this, not the bindings: a binding is a register or a number either
707    /// way, and an operand shown as the instruction that computed it is one no rule could have
708    /// matched without taking that instruction, because the plan offered the matcher nothing
709    /// else to call it.
710    fn folds(&self, inst: Inst, plan: Plan) -> Vec<Inst> {
711        let args = &self.source[self.source[inst].args];
712        args.iter()
713            .take(MAX_ARGS)
714            .enumerate()
715            .filter(|&(index, _)| plan[index] == Shown::Expand)
716            .filter_map(|(_, &arg)| match self.source[arg].def {
717                Def::Result { inst, .. } => Some(inst),
718                Def::Param { .. } => None,
719            })
720            .collect()
721    }
722
723    /// Build the machine instruction a match calls for.
724    fn emit(&mut self, inst: Inst, matched: &Match<Term>) -> Result<(), Unsupported> {
725        let rule: &Rule = TABLE.rule(matched);
726        let pieces = rule.replacement;
727        let Some(Piece::App { head, arity }) = pieces.first() else {
728            return Err(self.unsupported(inst));
729        };
730        let opcode = head.strip_prefix(PREFIX).ok_or_else(|| self.unsupported(inst))?;
731        let form = x86_64::form(opcode).ok_or_else(|| self.unsupported(inst))?;
732
733        let mut read = Read::default();
734        let mut at = 1;
735        for _ in 0..*arity {
736            at = self.read(inst, pieces, at, &matched.bindings, &mut read)?;
737        }
738
739        let descs = form.operands();
740        let writes = descs.iter().take_while(|desc| desc.role.is_def()).count();
741        if descs.len() - writes != read.regs.len() {
742            return Err(self.unsupported(inst));
743        }
744
745        // The first thing the instruction writes is what it computes, and any others are
746        // registers the machine destroys on the way, which are fresh because nothing else is in
747        // them and nothing reads them. An instruction that writes nothing at all is one whose
748        // whole purpose is its effect, which is what a store is, and there is no result to put
749        // anywhere.
750        let mut regs = Vec::new();
751        if writes > 0 {
752            let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
753            regs.push(self.new_reg(result));
754            // The rest are the registers the machine destroys on the way, and the class each is in
755            // is the one the instruction's description gives it rather than a guess, so that an
756            // instruction that wrecks a register in the other file says so.
757            regs.extend(descs[1..writes].iter().map(|desc| self.out.new_vreg(desc.class)));
758        } else if self.source[inst].first_result.is_some() {
759            // A rule that throws away a value the IR gave a name to would leave every reader of
760            // that name with nothing to read, so it is a rule this and the target disagree about.
761            return Err(self.unsupported(inst));
762        }
763        regs.extend(read.regs.iter().copied());
764
765        let block = self.at.expect("a block is being filled");
766        let opcode = mir::Opcode::new(self.names.intern(head));
767        let mut build = self.out.build(block, opcode).at(self.source.span(inst));
768        for (desc, reg) in descs.iter().zip(regs) {
769            let operand = mir::Operand {
770                reg,
771                class: desc.class,
772                role: desc.role,
773                constraint: desc.constraint,
774            };
775            build = build.operand(operand);
776        }
777        if let Some(mem) = read.mem {
778            build = build.mem(mem);
779        }
780        if let Some(imm) = read.imm {
781            build = build.imm(imm);
782        }
783        build.finish();
784        Ok(())
785    }
786
787    /// Read one argument of a replacement, which is a register, a number or an address.
788    ///
789    /// Gives back the position after it, because a replacement is flat and an address takes
790    /// arguments of its own.
791    fn read(
792        &mut self,
793        inst: Inst,
794        pieces: &'static [Piece],
795        at: usize,
796        bindings: &[Term],
797        out: &mut Read,
798    ) -> Result<usize, Unsupported> {
799        match pieces.get(at) {
800            Some(Piece::Int(value)) => {
801                out.imm = i64::try_from(*value).ok();
802                Ok(at + 1)
803            }
804            Some(Piece::Var { index, .. }) => {
805                match bindings.get(*index) {
806                    Some(&Term::Reg(value)) => {
807                        let reg = self.reg_of(value)?;
808                        out.regs.push(reg);
809                    }
810                    Some(&Term::Num(value)) => out.imm = i64::try_from(value).ok(),
811                    // A pattern binds a register or a number and nothing else, so this is a
812                    // rule the matcher and this file disagree about.
813                    _ => return Err(self.unsupported(inst)),
814                }
815                Ok(at + 1)
816            }
817            Some(Piece::App { head, arity }) => {
818                let kind = x86_64::address(head).ok_or_else(|| self.unsupported(inst))?;
819                let mut inner = Read::default();
820                let mut next = at + 1;
821                for _ in 0..*arity {
822                    next = self.read(inst, pieces, next, bindings, &mut inner)?;
823                }
824                let mem = address(kind, &inner, self.gpr).ok_or_else(|| self.unsupported(inst))?;
825                out.mem = Some(mem);
826                Ok(next)
827            }
828            None => Err(self.unsupported(inst)),
829        }
830    }
831
832    /// The register a value is in, materializing it if it is a constant that has not been put in
833    /// one yet.
834    ///
835    /// A constant is written where it is wanted rather than where the IR defined it, and where it
836    /// is wanted is a block that need not be the one the IR defined it in. So the register holding
837    /// one is only good inside the block it was written into, and a second block that wants the
838    /// same constant gets its own. Anything else is a register read where nothing wrote it: the
839    /// IR guarantees a definition dominates its uses, and this moved the definition.
840    ///
841    /// Writing the number again is also the right answer and not merely the safe one. It is one
842    /// instruction that reads nothing, which is cheaper than holding a register live across a
843    /// branch for it, and it is what a rematerializing allocator would do with the value anyway.
844    fn reg_of(&mut self, value: Value) -> Result<mir::Reg, Unsupported> {
845        let constant = match self.source[value].def {
846            Def::Result { inst, .. } => {
847                (self.source[inst].opcode == Opcode::IConst).then_some(inst)
848            }
849            Def::Param { .. } => None,
850        };
851        let here = self.at.expect("a block is being filled");
852        if let Some(reg) = self.regs[value.index()] {
853            if constant.is_none() || self.written[value.index()] == Some(here) {
854                return Ok(reg);
855            }
856        }
857        if let Some(inst) = constant {
858            // Cleared so that the register the constant is written into is a new one rather than
859            // the one the block above wrote, which is still being read up there.
860            self.regs[value.index()] = None;
861            let matched = self
862                .select(inst)
863                .map(|(_, matched)| matched)
864                .ok_or_else(|| self.unsupported(inst))?;
865            self.emit(inst, &matched)?;
866            self.written[value.index()] = Some(here);
867            return Ok(self.regs[value.index()].expect("a constant is written into a register"));
868        }
869        Ok(self.new_reg(value))
870    }
871
872    /// Which register file a value of that type lives in.
873    ///
874    /// The vector one for the two float widths the machine has scalar instructions for, and the
875    /// general purpose one for everything else. A `long double` is in neither, and it is here
876    /// rather than in the vector class on purpose: it would be put in a register that cannot hold
877    /// it, and there is no rule that names one, so the instruction computing it is reported. The
878    /// wrong class would make that a wrong program instead of a refused one.
879    fn class_of(&self, ty: Type) -> RegClass {
880        match crate::term::float_slot(ty) {
881            Some(_) => self.conv.sse_class,
882            None => self.gpr,
883        }
884    }
885
886    /// A fresh register for a value, which is what the instruction computing it writes.
887    fn new_reg(&mut self, value: Value) -> mir::Reg {
888        if let Some(reg) = self.regs[value.index()] {
889            return reg;
890        }
891        let reg = self.out.new_vreg(self.class_of(self.source[value].ty));
892        self.regs[value.index()] = Some(reg);
893        reg
894    }
895
896    fn unsupported(&self, inst: Inst) -> Unsupported {
897        let data = &self.source[inst];
898        Unsupported::Inst {
899            inst,
900            term: Terms::new(self.source, inst, PLAIN).name(inst),
901            opcode: data.opcode,
902            ty: data.first_result.map(|result| self.source[result].ty),
903        }
904    }
905}
906
907/// What the arguments of one replacement came to.
908#[derive(Debug, Default)]
909struct Read {
910    regs: Vec<mir::Reg>,
911    imm: Option<i64>,
912    mem: Option<mir::Mem>,
913}
914
915/// The addressing mode an address constructor's arguments make.
916///
917/// One arm per constructor rather than a question asked of the kind, because what the arguments
918/// mean is the whole of what tells the four apart: the same register is a base in one and an
919/// index in another, and the same constant is a scale in one and a displacement in another.
920fn address(kind: x86_64::Address, read: &Read, gpr: RegClass) -> Option<mir::Mem> {
921    let mut regs = read.regs.iter().copied().map(|reg| mir::Operand::read(reg, gpr));
922    match kind {
923        x86_64::Address::BaseIndexScale => {
924            let base = regs.next()?;
925            let index = regs.next()?;
926            Some(mir::Mem::at(base).indexed(index, u8::try_from(read.imm?).ok()?))
927        }
928        x86_64::Address::IndexScale => Some(mir::Mem {
929            base: None,
930            index: Some(regs.next()?),
931            scale: u8::try_from(read.imm?).ok()?,
932            disp: 0,
933            symbol: None,
934        }),
935        x86_64::Address::Base => Some(mir::Mem::at(regs.next()?)),
936        // The rule that writes this has a guard saying the constant fits, so a displacement that
937        // does not is a rule and a target that disagree rather than a program this cannot compile.
938        x86_64::Address::BaseOffset => {
939            Some(mir::Mem { disp: i32::try_from(read.imm?).ok()?, ..mir::Mem::at(regs.next()?) })
940        }
941    }
942}
943
944/// The table this selector matches with.
945///
946/// One target for now, because one target has a rule file. Which table to use becomes a question
947/// the moment a second one does, and the answer will be the target the session was given rather
948/// than a constant here.
949static TABLE: &Table = &crate::select::x86_64::TABLE;
950
951#[cfg(test)]
952mod tests {
953    use rucc_ir::{Builder, CallInfo, Flags, InstData, MemInfo, MemOrder, Signature, Type};
954    use rucc_regalloc::assign::Env;
955    use rucc_target::x86_64::{FRAME, REGS, SYSV};
956
957    use super::*;
958    use crate::finish::finish;
959    use crate::frame::{Frame, Layout};
960
961    /// A function of as many 64 bit parameters as the test wants, and the block they are in.
962    fn blank(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
963        let mut names = Interner::new();
964        let mut func = Func::new(names.intern("f"), Signature::new());
965        let block = func.create_block();
966        let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
967        (names, func, block, values)
968    }
969
970    /// An ordinary access: not atomic, and aligned enough that nothing here has an opinion.
971    /// Neither field reaches selection, which is the point of saying it once here.
972    fn plain() -> MemInfo {
973        MemInfo { size: 0, align: 1, order: MemOrder::NotAtomic, tbaa: None }
974    }
975
976    /// What the allocator is given: every integer register the convention offers except two, held
977    /// back so that a move on an edge has somewhere to break a cycle and a spilled value has
978    /// somewhere to be read into. Which two does not matter, and holding back the last two the
979    /// convention would reach for leaves every expectation below unchanged.
980    fn env() -> Env {
981        const SCRATCH: [rucc_target::PhysReg; 2] = [x86_64::R10, x86_64::R11];
982        let order: Vec<rucc_target::PhysReg> =
983            SYSV.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
984        Env::new().with(x86_64::GPR, &order, &SCRATCH)
985    }
986
987    /// The machine IR text a function lowers to.
988    fn lower(names: &mut Interner, source: &Func) -> String {
989        let out = func(source, names, &SYSV).expect("every instruction has a rule");
990        mir::print_func(&out.func, names, &REGS)
991    }
992
993    #[test]
994    fn an_addition_of_two_registers_is_one_instruction() {
995        let i32 = Type::int(32);
996        let (mut names, mut func, block, args) = blank(&[i32, i32]);
997        let mut build = Builder::new(&mut func, block);
998        build.binary(Opcode::Add, args[0], args[1], Flags::default());
999
1000        assert_eq!(
1001            lower(&mut names, &func),
1002            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
1003             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr(reuse 1) = x64.add_rr_32 %0, %1\n}\n"
1004        );
1005    }
1006
1007    #[test]
1008    fn a_constant_operand_becomes_an_immediate() {
1009        let i32 = Type::int(32);
1010        let (mut names, mut func, block, args) = blank(&[i32]);
1011        let mut build = Builder::new(&mut func, block);
1012        let seven = build.iconst(i32, 7);
1013        build.binary(Opcode::Add, args[0], seven, Flags::default());
1014
1015        // The constant is in the instruction and nothing was written to hold it, which is what
1016        // materializing one where a register for it is wanted buys.
1017        assert_eq!(
1018            lower(&mut names, &func),
1019            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
1020             %1:gpr(reuse 1) = x64.add_ri_32 %0, 7\n}\n"
1021        );
1022    }
1023
1024    #[test]
1025    fn a_constant_too_wide_for_an_immediate_goes_into_a_register() {
1026        let i64 = Type::int(64);
1027        let (mut names, mut func, block, args) = blank(&[i64]);
1028        let mut build = Builder::new(&mut func, block);
1029        let big = build.iconst(i64, i128::from(i32::MAX) + 1);
1030        build.binary(Opcode::Add, args[0], big, Flags::default());
1031
1032        // Nobody wrote this fallback down. The rule that takes an immediate has a guard that
1033        // turns a number this wide down, so it does not fire, and the next way of showing the
1034        // operand puts it in a register.
1035        assert_eq!(
1036            lower(&mut names, &func),
1037            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
1038             %1:gpr = x64.mov_ri_64 2147483648\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n}\n"
1039        );
1040    }
1041
1042    #[test]
1043    fn an_index_calculation_folds_into_an_address() {
1044        let i64 = Type::int(64);
1045        let (mut names, mut func, block, args) = blank(&[i64, i64]);
1046        let mut build = Builder::new(&mut func, block);
1047        let four = build.iconst(i64, 4);
1048        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
1049        build.binary(Opcode::Add, args[0], scaled, Flags::default());
1050
1051        // Three IR instructions and one machine instruction. The multiply is gone because the
1052        // rule that matched reached down and took it.
1053        assert_eq!(
1054            lower(&mut names, &func),
1055            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
1056             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.lea_64 [%0 + %1*4]\n}\n"
1057        );
1058    }
1059
1060    #[test]
1061    fn an_instruction_read_twice_is_not_folded_into_either_reader() {
1062        let i64 = Type::int(64);
1063        let (mut names, mut func, block, args) = blank(&[i64, i64]);
1064        let mut build = Builder::new(&mut func, block);
1065        let four = build.iconst(i64, 4);
1066        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
1067        let first = build.binary(Opcode::Add, args[0], scaled, Flags::default());
1068        build.binary(Opcode::Add, first, scaled, Flags::default());
1069
1070        // Folding it into both would compute it twice, which is not a saving, so it stays where
1071        // it is and both readers read the register it wrote.
1072        let text = lower(&mut names, &func);
1073        assert!(text.contains("x64.lea_64 [%1*4]"), "{text}");
1074        assert_eq!(text.matches("x64.add_rr_64").count(), 2, "{text}");
1075    }
1076
1077    #[test]
1078    fn a_shift_by_a_register_asks_for_it_in_cl() {
1079        let i32 = Type::int(32);
1080        let (mut names, mut func, block, args) = blank(&[i32, i32]);
1081        let mut build = Builder::new(&mut func, block);
1082        build.binary(Opcode::Shl, args[0], args[1], Flags::default());
1083
1084        // The fixed register is not in the rule. It is what the target says the instruction does
1085        // with its operands, and the allocator is what will act on it.
1086        let text = lower(&mut names, &func);
1087        assert!(text.contains("x64.shl_rcl_32 %0, %1($rcx)"), "{text}");
1088    }
1089
1090    #[test]
1091    fn a_division_names_the_registers_and_the_register_it_destroys() {
1092        let i32 = Type::int(32);
1093        let (mut names, mut func, block, args) = blank(&[i32, i32]);
1094        let mut build = Builder::new(&mut func, block);
1095        build.binary(Opcode::SDiv, args[0], args[1], Flags::default());
1096
1097        // Two definitions, because a division writes the remainder whether anybody wanted it or
1098        // not, and the second one is early because it is destroyed before the operands are read.
1099        let text = lower(&mut names, &func);
1100        assert!(
1101            text.contains("%2:gpr($rax), early %3:gpr($rdx) = x64.idiv_quo_32 %0($rax), %1"),
1102            "{text}"
1103        );
1104    }
1105
1106    #[test]
1107    fn a_load_reads_through_the_register_the_address_is_in() {
1108        let i64 = Type::int(64);
1109        let (mut names, mut func, block, args) = blank(&[i64]);
1110        let mut build = Builder::new(&mut func, block);
1111        build.load(Type::int(32), args[0], plain(), Flags::default());
1112
1113        assert_eq!(
1114            lower(&mut names, &func),
1115            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
1116             %1:gpr = x64.mov_rm_32 [%0]\n}\n"
1117        );
1118    }
1119
1120    #[test]
1121    fn a_store_writes_no_register_and_the_value_it_writes_is_the_one_the_ir_gave_it() {
1122        let (mut names, mut func, block, args) = blank(&[Type::int(32), Type::int(64)]);
1123        let mut build = Builder::new(&mut func, block);
1124        build.store(args[0], args[1], plain(), Flags::default());
1125
1126        // The value is the first parameter and the address is the second, and the instruction
1127        // takes them the other way round. Getting that backwards would compile to a store of the
1128        // address into the value, which is a program that runs and does the wrong thing.
1129        assert_eq!(
1130            lower(&mut names, &func),
1131            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
1132             %1:gpr($rsi) = x64.arg_val_64\n    x64.mov_mr_32 %0, [%1]\n}\n"
1133        );
1134    }
1135
1136    #[test]
1137    fn an_address_with_a_constant_added_folds_into_the_access() {
1138        let i64 = Type::int(64);
1139        let (mut names, mut func, block, args) = blank(&[i64]);
1140        let mut build = Builder::new(&mut func, block);
1141        let twelve = build.iconst(i64, 12);
1142        let field = build.binary(Opcode::Add, args[0], twelve, Flags::default());
1143        build.load(Type::int(64), field, plain(), Flags::default());
1144
1145        // Two IR instructions and one machine instruction, which is what every read of a field
1146        // of a structure comes to.
1147        assert_eq!(
1148            lower(&mut names, &func),
1149            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
1150             %1:gpr = x64.mov_rm_64 [%0 + 12]\n}\n"
1151        );
1152    }
1153
1154    #[test]
1155    fn a_displacement_too_wide_to_encode_leaves_the_addition_where_it_is() {
1156        let i64 = Type::int(64);
1157        let (mut names, mut func, block, args) = blank(&[i64]);
1158        let mut build = Builder::new(&mut func, block);
1159        let big = build.iconst(i64, i128::from(i32::MAX) + 1);
1160        let far = build.binary(Opcode::Add, args[0], big, Flags::default());
1161        build.load(Type::int(32), far, plain(), Flags::default());
1162
1163        // A displacement is signed and 32 bits. The rule that folds one has a guard that turns
1164        // this down, so the addition stays and the load reads through what it produced. Nobody
1165        // wrote that fallback: it is the next way of showing the operand.
1166        let text = lower(&mut names, &func);
1167        assert!(text.contains("x64.mov_rm_32 [%2]"), "{text}");
1168        assert!(text.contains("x64.add_rr_64"), "{text}");
1169    }
1170
1171    #[test]
1172    fn a_store_of_a_value_that_was_loaded_is_two_instructions_and_no_arithmetic() {
1173        let i64 = Type::int(64);
1174        let (mut names, mut func, block, args) = blank(&[i64, i64]);
1175        let mut build = Builder::new(&mut func, block);
1176        let got = build.load(Type::int(8), args[0], plain(), Flags::default());
1177        build.store(got, args[1], plain(), Flags::default());
1178
1179        // A load feeding a store is the one place folding would be wrong: an x86-64 `mov` has at
1180        // most one memory operand, and there is no rule that takes two, so the load is left where
1181        // it is and the store reads the register it wrote.
1182        assert_eq!(
1183            lower(&mut names, &func),
1184            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
1185             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.mov_rm_8 [%0]\n    \
1186             x64.mov_mr_8 %2, [%1]\n}\n"
1187        );
1188    }
1189
1190    #[test]
1191    fn an_access_at_a_width_no_rule_is_written_at_is_reported() {
1192        let i64 = Type::int(64);
1193        let (mut names, mut source, block, args) = blank(&[i64]);
1194        let mut build = Builder::new(&mut source, block);
1195        build.load(Type::int(128), args[0], plain(), Flags::default());
1196
1197        // The width is the whole of what is wrong here, so the width is in the message: `load`
1198        // on its own is written about at every other width and would send a reader looking in
1199        // the wrong place.
1200        let failed = func(&source, &mut names, &SYSV).expect_err("nothing loads 128 bits");
1201        assert_eq!(failed.to_string(), "no rule lowers a `load` producing a `i128`");
1202    }
1203
1204    #[test]
1205    fn a_return_asks_for_the_value_in_the_register_the_caller_reads() {
1206        let (mut names, mut func, block, args) = blank(&[Type::int(32)]);
1207        let mut build = Builder::new(&mut func, block);
1208        build.ret(&[args[0]]);
1209
1210        // The register is not in the rule, the same way `cl` is not in the rule for a shift. It
1211        // is what the target says the instruction does with its operand, and the allocator is
1212        // what will act on it. There is no `ret` here, because giving the frame back has to
1213        // happen between this and leaving and the frame is not worked out yet.
1214        assert_eq!(
1215            lower(&mut names, &func),
1216            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
1217             x64.ret_val_32 %0($rax)\n}\n"
1218        );
1219    }
1220
1221    #[test]
1222    fn a_return_of_a_constant_puts_it_in_a_register_first() {
1223        let (mut names, mut func, block, _) = blank(&[]);
1224        let mut build = Builder::new(&mut func, block);
1225        let zero = build.iconst(Type::int(32), 0);
1226        build.ret(&[zero]);
1227
1228        // No rule returns an immediate, so the plan that offers one is turned down and the next
1229        // one materializes it. That is `int main(void) { return 0; }` in full, once the epilogue
1230        // is appended to it.
1231        assert_eq!(
1232            lower(&mut names, &func),
1233            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 0\n    x64.ret_val_32 %0($rax)\n}\n"
1234        );
1235    }
1236
1237    #[test]
1238    fn a_return_of_nothing_is_no_instruction_at_all() {
1239        let (mut names, mut func, block, _) = blank(&[]);
1240        let mut build = Builder::new(&mut func, block);
1241        build.ret(&[]);
1242
1243        // Every part of leaving a function that returns nothing is the epilogue's, and the
1244        // epilogue goes in after allocation. A block with nothing in it is the right answer here
1245        // rather than a function that could not be lowered.
1246        assert_eq!(lower(&mut names, &func), "mfunc @f {\nblock0:\n}\n");
1247    }
1248
1249    #[test]
1250    fn the_allocator_is_what_moves_the_answer_into_the_return_register() {
1251        let (mut names, mut source, block, _) = blank(&[]);
1252        let mut build = Builder::new(&mut source, block);
1253        let zero = build.iconst(Type::int(32), 0);
1254        build.ret(&[zero]);
1255
1256        let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1257        let env = env();
1258        let allocation = rucc_regalloc::run(&mut out, &env);
1259        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
1260        finish(&mut out, &allocation, &frame, &[], &SYSV, &FRAME, &mut names);
1261
1262        // `int main(void) { return 0; }` end to end. Nothing here asked for `rax`: the rule said
1263        // the value goes back, the target said where, and the allocator is what made it true. The
1264        // epilogue is what leaves, and this function needs no frame, so it is the return alone.
1265        //
1266        // The copy is a register allocator that takes no hints. It hands `%0` a register at the
1267        // instruction that writes it, where it does not yet know that a later use insists on
1268        // `rax`, and `rax` is not free to hand out because that later use is holding it. So the
1269        // value goes somewhere else and is copied in. Every division and every shift by a
1270        // register already pays the same thing, and paying it once per return is what makes it
1271        // worth fixing rather than a new problem.
1272        assert_eq!(
1273            mir::print_func(&out, &names, &REGS),
1274            "mfunc @f {\nblock0:\n    $rcx = x64.mov_ri_32 0\n    $rax = x64.mov_rr_64 $rcx\n    \
1275             x64.ret_val_32 $rax($rax)\n    x64.ret\n}\n"
1276        );
1277    }
1278
1279    #[test]
1280    fn a_function_of_two_arguments_is_a_whole_function_now() {
1281        let i32 = Type::int(32);
1282        let (mut names, mut source, block, args) = blank(&[i32, i32]);
1283        let mut build = Builder::new(&mut source, block);
1284        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
1285        build.ret(&[sum]);
1286
1287        let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1288        let env = env();
1289        let allocation = rucc_regalloc::run(&mut out, &env);
1290        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
1291        finish(&mut out, &allocation, &frame, &[], &SYSV, &FRAME, &mut names);
1292
1293        // `int f(int a, int b) { return a + b; }` end to end, and this is the test the argument
1294        // side exists for. Before it there was no way to write one: the allocator refuses a
1295        // function whose entry block takes parameters, because there is no edge into an entry
1296        // block for the moves that give a block parameter its value to go on.
1297        //
1298        // Four moves that a good allocator writes none of, and it is the same allocator that
1299        // takes no hints as in the return above rather than anything new. It hands each argument
1300        // a register at the pseudo that defines it, without looking at the fixed register that
1301        // pseudo insists on, so every argument is copied straight back out of where it already
1302        // was. Issue #255 is this, and this function is the shortest program that shows what it
1303        // costs: one hint per argument and one per return would leave nothing here but the
1304        // addition. What the test is for meanwhile is that the answer is right, and it is: the
1305        // copy in front of a two address instruction is what makes its destination one of the
1306        // registers it reads, and the source operand keeps its own name because the destination
1307        // is what the encoder writes.
1308        assert_eq!(
1309            mir::print_func(&out, &names, &REGS),
1310            "mfunc @f {\nblock0:\n    $rdi($rdi) = x64.arg_val_32\n    \
1311             $rax = x64.mov_rr_64 $rdi\n    $rsi($rsi) = x64.arg_val_32\n    \
1312             $rcx = x64.mov_rr_64 $rsi\n    $rdx = x64.mov_rr_64 $rax\n    \
1313             $rdx(reuse 1) = x64.add_rr_32 $rax, $rcx\n    $rax = x64.mov_rr_64 $rdx\n    \
1314             x64.ret_val_32 $rax($rax)\n    x64.ret\n}\n"
1315        );
1316    }
1317
1318    #[test]
1319    fn an_argument_with_no_register_left_for_it_is_reported() {
1320        let i64 = Type::int(64);
1321        let (mut names, mut source, block, args) = blank(&[i64; 7]);
1322        let mut build = Builder::new(&mut source, block);
1323        build.ret(&[args[6]]);
1324
1325        // SysV passes six integers in registers and the seventh on the stack, and reading it from
1326        // there means knowing where the frame put it, which nothing knows until the allocator has
1327        // finished. So this is reported rather than compiled to a read of whatever `r9` still had.
1328        let failed = func(&source, &mut names, &SYSV).expect_err("the seventh is on the stack");
1329        assert_eq!(failed.to_string(), "parameter 6 is passed on the stack");
1330    }
1331
1332    #[test]
1333    fn a_jump_is_the_edge_and_nothing_else() {
1334        let i32 = Type::int(32);
1335        let (mut names, mut source, entry, args) = blank(&[i32]);
1336        let next = source.create_block();
1337        let got = source.append_param(next, i32);
1338        Builder::new(&mut source, entry).jump(next, &[args[0]]);
1339        Builder::new(&mut source, next).ret(&[got]);
1340
1341        // Two blocks and two instructions, and the jump is neither of them. What it was is the
1342        // arm on the first block, and what the arm carries is the argument it was called with.
1343        assert_eq!(
1344            lower(&mut names, &source),
1345            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32 block1(%0)\n\n\
1346             block1(%1:gpr):\n    x64.ret_val_32 %1($rax)\n}\n"
1347        );
1348    }
1349
1350    /// A constant is written where it is wanted rather than where the IR defined it, and two
1351    /// blocks wanting the same one is two places. Writing it once and reading it in both is a
1352    /// register read where nothing wrote it, unless the block it was written in happens to
1353    /// dominate the other, which nothing here checks and which the second arm of a branch never
1354    /// does. Each block gets its own copy of the number instead.
1355    #[test]
1356    fn a_constant_two_blocks_want_is_written_in_both_of_them() {
1357        let i32 = Type::int(32);
1358        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1359        let then = source.create_block();
1360        let other = source.create_block();
1361        let join = source.create_block();
1362        let got = source.append_param(join, i32);
1363
1364        let mut build = Builder::new(&mut source, entry);
1365        let seven = build.iconst(i32, 7);
1366        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1367        build.br_if(cond, then, &[], other, &[]);
1368        // Both arms want the seven in a register, because a block argument is never an immediate,
1369        // and neither arm dominates the other.
1370        Builder::new(&mut source, then).jump(join, &[seven]);
1371        Builder::new(&mut source, other).jump(join, &[seven]);
1372        Builder::new(&mut source, join).ret(&[got]);
1373
1374        let text = lower(&mut names, &source);
1375        assert_eq!(text.matches("x64.mov_ri_32 7").count(), 2, "one seven per block: {text}");
1376    }
1377
1378    /// An argument on an edge out of a block that leaves two ways is read after every instruction
1379    /// of the block is written, and reading one can write an instruction, which would land after
1380    /// the branch that has already jumped past it. The branch goes back on the end.
1381    #[test]
1382    fn a_constant_an_edge_wants_is_written_before_the_branch_and_not_after_it() {
1383        let i32 = Type::int(32);
1384        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1385        let then = source.create_block();
1386        let join = source.create_block();
1387        let got = source.append_param(join, i32);
1388
1389        let mut build = Builder::new(&mut source, entry);
1390        let nine = build.iconst(i32, 9);
1391        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1392        build.br_if(cond, then, &[], join, &[nine]);
1393        Builder::new(&mut source, then).jump(join, &[args[0]]);
1394        Builder::new(&mut source, join).ret(&[got]);
1395
1396        let out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1397        let entry = out.entry().expect("an entry block");
1398        let last = out.terminator(entry).expect("a block that leaves two ways has a branch");
1399        let branch = names.intern("x64.br_cond_8");
1400        assert_eq!(
1401            out[last].opcode,
1402            mir::Opcode::new(branch),
1403            "the branch is last: {}",
1404            mir::print_func(&out, &names, &REGS)
1405        );
1406    }
1407
1408    #[test]
1409    fn a_conditional_branch_is_lowered_to_the_condition_and_nothing_about_where_it_goes() {
1410        let i32 = Type::int(32);
1411        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1412        let then = source.create_block();
1413        let other = source.create_block();
1414        let mut build = Builder::new(&mut source, entry);
1415        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1416        build.br_if(cond, then, &[], other, &[]);
1417        Builder::new(&mut source, then).ret(&[args[0]]);
1418        Builder::new(&mut source, other).ret(&[args[1]]);
1419
1420        // The comparison writes a byte and the branch reads it, and neither says a block. Both
1421        // arms are on the entry block, in the order the branch took them, so the arm that runs
1422        // when the condition holds is the first.
1423        assert_eq!(
1424            lower(&mut names, &source),
1425            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
1426             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr = x64.cmp_set_l_32 %0, %1\n    \
1427             x64.br_cond_8 %2, block1, block2\n\n\
1428             block1:\n    x64.ret_val_32 %0($rax)\n\n\
1429             block2:\n    x64.ret_val_32 %1($rax)\n}\n"
1430        );
1431    }
1432
1433    #[test]
1434    fn a_branch_over_a_block_is_a_whole_function_now() {
1435        let i32 = Type::int(32);
1436        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1437        let then = source.create_block();
1438        let other = source.create_block();
1439        let join = source.create_block();
1440        let got = source.append_param(join, i32);
1441        let mut build = Builder::new(&mut source, entry);
1442        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1443        build.br_if(cond, then, &[], other, &[]);
1444        let mut build = Builder::new(&mut source, then);
1445        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
1446        build.jump(join, &[sum]);
1447        Builder::new(&mut source, other).jump(join, &[args[1]]);
1448        Builder::new(&mut source, join).ret(&[got]);
1449
1450        // `int f(int a, int b) { if (a < b) return a + b; else return b; }` end to end, written
1451        // the way a front end writes it: both arms of the branch are blocks of their own and the
1452        // return is the block they meet at. No edge here is critical, because the two arms out of
1453        // the entry carry nothing and the two arms into the join each leave a block that goes
1454        // nowhere else, so each has its own end to put its move at.
1455        let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1456        assert_eq!(crate::split::critical(&mut out), 0, "no edge here is critical");
1457        let env = env();
1458        let allocation = rucc_regalloc::run(&mut out, &env);
1459        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
1460        finish(&mut out, &allocation, &frame, &[], &SYSV, &FRAME, &mut names);
1461
1462        // One epilogue, on the join, which is the one block the function leaves from, and the
1463        // moves that give the join its parameter are at the end of each arm. Every register is
1464        // physical and the branch is still a branch on a register, because turning it into a
1465        // `test` and a `jcc` is the block layout's and there is no block layout yet.
1466        let text = mir::print_func(&out, &names, &REGS);
1467        assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
1468        assert!(text.contains("x64.br_cond_8"), "{text}");
1469        assert!(text.contains("x64.add_rr_32"), "{text}");
1470        assert!(!text.contains('%'), "{text}");
1471    }
1472
1473    #[test]
1474    fn a_critical_edge_is_split_before_the_allocator_ever_sees_it() {
1475        let i32 = Type::int(32);
1476        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1477        let then = source.create_block();
1478        let join = source.create_block();
1479        let got = source.append_param(join, i32);
1480        let mut build = Builder::new(&mut source, entry);
1481        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1482        build.br_if(cond, then, &[], join, &[args[1]]);
1483        Builder::new(&mut source, then).jump(join, &[args[0]]);
1484        let mut build = Builder::new(&mut source, join);
1485        let twice = build.binary(Opcode::Add, got, got, Flags::default());
1486        build.ret(&[twice]);
1487
1488        // The else arm is critical: the entry block leaves two ways and the join is arrived at
1489        // two ways, and the arm carries a value. Without splitting it the allocator asserts,
1490        // because the move that gives the join its parameter would have to run at the end of a
1491        // block that also goes to the other arm.
1492        let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1493        assert_eq!(crate::split::critical(&mut out), 1);
1494        let env = env();
1495        let allocation = rucc_regalloc::run(&mut out, &env);
1496        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
1497        finish(&mut out, &allocation, &frame, &[], &SYSV, &FRAME, &mut names);
1498
1499        // The block the split added is where the move went, and it is the whole of that block.
1500        let text = mir::print_func(&out, &names, &REGS);
1501        assert_eq!(out.block_count(), 4, "{text}");
1502        assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
1503    }
1504
1505    #[test]
1506    fn a_call_passes_what_the_convention_says_and_takes_back_what_it_says() {
1507        let i32 = Type::int(32);
1508        let (mut names, mut source, block, args) = blank(&[i32, i32]);
1509        let sig =
1510            source.add_signature(Signature::new().with_params(&[i32, i32]).with_returns(&[i32]));
1511        let callee = names.intern("g");
1512        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0], args[1]]);
1513        let got = source[call].first_result.expect("an integer comes back");
1514        Builder::new(&mut source, block).ret(&[got]);
1515
1516        // `int f(int a, int b) { return g(a, b); }`. The arguments arrived where the call wants
1517        // them, so what the call reads is what arrived, and the whole of the convention is in the
1518        // constraints rather than in a move.
1519        let text = lower(&mut names, &source);
1520        assert!(text.contains("= x64.call %0($rdi), %1($rsi), @g"), "{text}");
1521        assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
1522        // What the call writes is the value that comes back and then every register the callee is
1523        // free to destroy, in both classes, which is the whole of what stops the allocator from
1524        // leaving something in one of them.
1525        assert!(text.contains("%2:gpr($rax), $rcx, $rdx, $r8, $r9, $r10, $r11, $xmm0,"), "{text}");
1526        assert!(text.contains("$xmm15 = x64.call"), "{text}");
1527    }
1528
1529    #[test]
1530    fn what_the_frame_owes_a_call_comes_back_with_the_function() {
1531        let i32 = Type::int(32);
1532        let sig = |source: &mut Func| source.add_signature(Signature::new().with_params(&[i32]));
1533
1534        let (mut names, mut source, block, args) = blank(&[i32]);
1535        let sig = sig(&mut source);
1536        let callee = names.intern("g");
1537        Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
1538        let out = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1539
1540        // Nothing on the stack, so nothing owed, but not a leaf either: a function that calls
1541        // owes the callee an aligned stack pointer and may not use the red zone.
1542        assert_eq!(out.stack.calls, Some(0));
1543        let layout = out.stack.layout(Layout::new(&SYSV, REGS));
1544        assert!(!layout.leaf);
1545        assert_eq!(layout.outgoing, 0);
1546
1547        // The same call under the other convention owes thirty two bytes for the callee to spill
1548        // its register arguments into, which is a fact about the convention and not about the call.
1549        let out = func(&source, &mut names, &x86_64::WIN64).expect("every instruction has a rule");
1550        assert_eq!(out.stack.calls, Some(32));
1551
1552        // And a function that calls nothing is a leaf, which is what says it may use the red zone.
1553        let (mut names, mut source, block, args) = blank(&[i32]);
1554        Builder::new(&mut source, block).ret(&[args[0]]);
1555        let out = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1556        assert_eq!(out.stack.calls, None);
1557        assert!(out.stack.layout(Layout::new(&SYSV, REGS)).leaf);
1558    }
1559
1560    #[test]
1561    fn a_value_that_outlives_a_call_is_not_left_where_the_call_destroys_it() {
1562        let i32 = Type::int(32);
1563        let (mut names, mut source, block, args) = blank(&[i32]);
1564        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
1565        let callee = names.intern("g");
1566        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
1567        let got = source[call].first_result.expect("an integer comes back");
1568        let mut build = Builder::new(&mut source, block);
1569        let sum = build.binary(Opcode::Add, got, args[0], Flags::default());
1570        build.ret(&[sum]);
1571
1572        // `int f(int a) { return g(a) + a; }`, which is the smallest program that asks the
1573        // question: `a` is read after the call and `rdi` is a register the call destroys.
1574        let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1575        let layout = lowered.stack.layout(Layout::new(&SYSV, REGS));
1576        let mut out = lowered.func;
1577        let env = env();
1578        let allocation = rucc_regalloc::run(&mut out, &env);
1579        let frame = Frame::of(&out, &allocation, &layout);
1580        finish(&mut out, &allocation, &frame, &[], &SYSV, &FRAME, &mut names);
1581
1582        // It went to a register the callee has to put back, and the prologue and epilogue are what
1583        // put it back, which is the whole bargain the two halves of a convention make.
1584        let text = mir::print_func(&out, &names, &REGS);
1585        assert!(text.contains("$rbx"), "{text}");
1586        assert!(!text.contains('%'), "{text}");
1587        assert_eq!(text.matches("x64.call").count(), 1, "{text}");
1588    }
1589
1590    #[test]
1591    fn a_call_this_cannot_make_is_reported_rather_than_made() {
1592        let i64 = Type::int(64);
1593        let (mut names, mut source, block, args) = blank(&[i64]);
1594        let seven = vec![i64; 7];
1595        let sig = source.add_signature(Signature::new().with_params(&seven));
1596        let callee = names.intern("g");
1597        let passed = vec![args[0]; 7];
1598        Builder::new(&mut source, block).call(callee, sig, &passed);
1599
1600        // The seventh argument travels on the stack, and where the stack put it is a distance into
1601        // a frame that does not exist until after allocation.
1602        let failed = func(&source, &mut names, &SYSV).expect_err("the seventh is on the stack");
1603        assert_eq!(failed.to_string(), "argument 6 of this call is passed on the stack");
1604
1605        let (mut names, mut source, block, _) = blank(&[]);
1606        let sig = source
1607            .add_signature(Signature::new().with_returns(&[Type::float(rucc_ir::Float::F80)]));
1608        let callee = names.intern("g");
1609        Builder::new(&mut source, block).call(callee, sig, &[]);
1610        let failed = func(&source, &mut names, &SYSV).expect_err("a long double is on the x87");
1611        assert_eq!(failed.to_string(), "what this call gives back is on the x87 stack");
1612    }
1613
1614    #[test]
1615    fn a_call_through_an_address_goes_through_the_register_the_address_is_in() {
1616        let i32 = Type::int(32);
1617        let (mut names, mut source, block, args) = blank(&[Type::PTR, i32]);
1618        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
1619        let varargs = source.push_abis(&[]);
1620        let info = source.add_call(CallInfo { callee: None, signature: sig, varargs });
1621        let mut build = Builder::new(&mut source, block);
1622        let inst = InstData {
1623            args: build.func().push_values(&[args[0], args[1]]),
1624            extra: Extra::Call(info),
1625            ..InstData::new(Opcode::CallIndirect)
1626        };
1627        let called = build.inst(inst, &[i32]);
1628        let got = source[called].first_result.expect("an integer comes back");
1629        Builder::new(&mut source, block).ret(&[got]);
1630
1631        // `int f(int (*g)(int), int a) { return g(a); }`. The first operand is the address and
1632        // the arguments are the ones behind it, and everything else about the call is what a call
1633        // to a name would have been.
1634        let text = lower(&mut names, &source);
1635        assert!(text.contains("= x64.call_reg %0, %1($rdi)"), "{text}");
1636        assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
1637        assert!(!text.contains("@g"), "a call through an address names nobody: {text}");
1638    }
1639
1640    #[test]
1641    fn an_instruction_no_rule_covers_is_reported() {
1642        let i64 = Type::int(64);
1643        let (mut names, mut source, block, args) = blank(&[i64, i64]);
1644        let mut build = Builder::new(&mut source, block);
1645        build.ret(&[args[0], args[1]]);
1646
1647        // Two values back at once. Where each of them goes is the convention's answer rather than
1648        // a term's, so the rule language has no name for it and no rule fires.
1649        let failed = func(&source, &mut names, &SYSV).expect_err("nothing returns two values");
1650        assert_eq!(failed.to_string(), "no rule lowers a `return`");
1651
1652        // A `return` produces nothing, so there is no type in the message and nothing invents
1653        // one, and the instruction comes back so a caller can ask the function where it was.
1654        let inst = failed.inst().expect("the instruction it is about");
1655        assert_eq!(source[inst].opcode, Opcode::Return);
1656    }
1657
1658    /// A refusal about a signature has no instruction, which is what makes it the one arm apart.
1659    ///
1660    /// Everything else is about something written somewhere in the body and hands it back so a
1661    /// caller can ask the function where it came from. A parameter arrives before the first
1662    /// instruction runs, so there is nothing in the body to point at and the message is about
1663    /// the function.
1664    #[test]
1665    fn a_refusal_about_a_parameter_has_no_instruction_to_point_at() {
1666        let missing = Unsupported::Argument { index: 0, missing: Missing::OnStack };
1667        assert_eq!(missing.inst(), None);
1668    }
1669
1670    /// An `alloca` of a fixed size, which is what every local whose address is taken becomes.
1671    fn slot(source: &mut Func, block: Block, size: u64, align: u32) -> Value {
1672        let info = MemInfo { size, align, ..plain() };
1673        let mut build = Builder::new(source, block);
1674        let mem = build.func().add_mem(info);
1675        build.value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR)
1676    }
1677
1678    #[test]
1679    fn a_local_is_memory_in_the_frame_and_one_instruction_that_says_where() {
1680        let (mut names, mut source, block, _) = blank(&[]);
1681        let slot = slot(&mut source, block, 4, 4);
1682        let mut build = Builder::new(&mut source, block);
1683        let nine = build.iconst(Type::int(32), 9);
1684        build.store(nine, slot, plain(), Flags::default());
1685        let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
1686        build.ret(&[loaded]);
1687
1688        let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1689
1690        // Four bytes on the list the frame is laid out from, and the one instruction that reads
1691        // where they went. Its displacement is nothing here because there is no frame yet, and
1692        // which instruction is waiting for which local is what `finish` is handed.
1693        assert_eq!(lowered.stack.locals, vec![Local { size: 4, align: 4 }]);
1694        assert_eq!(lowered.stack.addresses.len(), 1);
1695        assert_eq!(lowered.stack.addresses[0].1, 0);
1696        assert_eq!(
1697            mir::print_func(&lowered.func, &names, &REGS),
1698            "mfunc @f {\nblock0:\n    %0:gpr = x64.lea_64 [$rsp]\n    \
1699             %1:gpr = x64.mov_ri_32 9\n    x64.mov_mr_32 %1, [%0]\n    \
1700             %2:gpr = x64.mov_rm_32 [%0]\n    x64.ret_val_32 %2($rax)\n}\n"
1701        );
1702    }
1703
1704    #[test]
1705    fn the_frame_is_what_fills_the_address_of_a_local_in() {
1706        let (mut names, mut source, block, _) = blank(&[]);
1707        let slot = slot(&mut source, block, 4, 4);
1708        let mut build = Builder::new(&mut source, block);
1709        let nine = build.iconst(Type::int(32), 9);
1710        build.store(nine, slot, plain(), Flags::default());
1711        let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
1712        build.ret(&[loaded]);
1713
1714        let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1715        let stack = lowered.stack;
1716        let mut out = lowered.func;
1717        let env = env();
1718        let allocation = rucc_regalloc::run(&mut out, &env);
1719        let layout = stack.layout(Layout::new(&SYSV, REGS));
1720        let frame = Frame::of(&out, &allocation, &layout);
1721        finish(&mut out, &allocation, &frame, &stack.addresses, &SYSV, &FRAME, &mut names);
1722
1723        // `int f(void) { int x; x = 9; return x; }` with the address of `x` taken, end to end.
1724        // A leaf small enough to live in the red zone takes no frame at all, so the stack pointer
1725        // never moves and the four bytes are below it, which is what the negative offset is. The
1726        // instruction the lowering left with nothing in its displacement now has the answer in it.
1727        let text = mir::print_func(&out, &names, &REGS);
1728        assert!(text.contains("$rax = x64.lea_64 [$rsp - 8]"), "{text}");
1729        assert!(!text.contains("x64.sub_ri_64"), "{text}");
1730        assert_eq!(frame.size(), 0);
1731        assert_eq!(frame.local(0), Some(-8));
1732    }
1733
1734    #[test]
1735    fn a_stack_slot_whose_size_is_not_known_until_it_runs_is_reported() {
1736        let i64 = Type::int(64);
1737        let (mut names, mut source, block, args) = blank(&[i64]);
1738        let info = MemInfo { size: 0, align: 16, ..plain() };
1739        let mut build = Builder::new(&mut source, block);
1740        let mem = build.func().add_mem(info);
1741        let size = build.func().push_values(&[args[0]]);
1742        let slot = build.value(
1743            InstData { args: size, extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) },
1744            Type::PTR,
1745        );
1746        Builder::new(&mut source, block).ret(&[slot]);
1747
1748        // A variable length array. Growing the stack where the declaration stands means moving the
1749        // stack pointer in the middle of the function and reaching everything else through a
1750        // frame pointer afterwards, and the frame here lays out neither.
1751        let failed = func(&source, &mut names, &SYSV).expect_err("nothing grows the stack");
1752        assert_eq!(failed.to_string(), "nothing here grows the stack for a variable length array");
1753    }
1754
1755    #[test]
1756    fn an_address_is_read_written_and_added_to_like_the_integer_it_is() {
1757        let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
1758        let mut build = Builder::new(&mut source, block);
1759        let stepped = build.func().push_values(&[args[0], args[1]]);
1760        let next =
1761            build.value(InstData { args: stepped, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
1762        let loaded = build.load(Type::int(32), next, plain(), Flags::default());
1763        build.ret(&[loaded]);
1764
1765        // `int f(int *p, long i) { return *(int *)((char *)p + i); }`. Nothing about this is new
1766        // in the rule set, which is the point: the two addresses arrive in registers because an
1767        // address is an integer as wide as one, and the arithmetic on them is the add it always
1768        // was, so every rule written about an add reaches it.
1769        //
1770        // The add stays its own instruction rather than folding into the address the load reads
1771        // from. Two registers with no scale on either is the one addressing mode the rules have no
1772        // load through, because the folds that exist are the displacement one and the scaled ones,
1773        // and this is neither. That is a peephole worth having and not a thing this changes.
1774        assert_eq!(
1775            lower(&mut names, &source),
1776            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
1777             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n    \
1778             %3:gpr = x64.mov_rm_32 [%2]\n    x64.ret_val_32 %3($rax)\n}\n"
1779        );
1780    }
1781
1782    /// The address of a file scope name, which is what every use of a global and every string
1783    /// literal starts from.
1784    fn address_of(source: &mut Func, block: Block, names: &mut Interner, name: &str) -> Value {
1785        let symbol = names.intern(name);
1786        let mut build = Builder::new(source, block);
1787        build.value(
1788            InstData { extra: Extra::Symbol(symbol), ..InstData::new(Opcode::GlobalAddr) },
1789            Type::PTR,
1790        )
1791    }
1792
1793    #[test]
1794    fn the_address_of_a_name_is_one_instruction_carrying_the_name() {
1795        let (mut names, mut source, block, _) = blank(&[]);
1796        let counter = address_of(&mut source, block, &mut names, "counter");
1797        let mut build = Builder::new(&mut source, block);
1798        let loaded = build.load(Type::int(32), counter, plain(), Flags::default());
1799        build.ret(&[loaded]);
1800
1801        // `extern int counter; int f(void) { return counter; }`. The address is an addressing mode
1802        // that names no register and carries the symbol, which is what the assembler writes
1803        // relative to `%rip` and what the object writer leaves a relocation for.
1804        assert_eq!(
1805            lower(&mut names, &source),
1806            "mfunc @f {\nblock0:\n    %0:gpr = x64.lea_64 [@counter]\n    \
1807             %1:gpr = x64.mov_rm_32 [%0]\n    x64.ret_val_32 %1($rax)\n}\n"
1808        );
1809    }
1810
1811    /// A cast between a pointer and an integer, at whatever width the result is asked for.
1812    fn cast(source: &mut Func, block: Block, opcode: Opcode, from: Value, to: Type) -> Value {
1813        let mut build = Builder::new(source, block);
1814        let args = build.func().push_values(&[from]);
1815        build.value(InstData { args, ..InstData::new(opcode) }, to)
1816    }
1817
1818    #[test]
1819    fn a_cast_between_a_pointer_and_an_integer_as_wide_is_no_instruction_at_all() {
1820        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
1821        let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(64));
1822        Builder::new(&mut source, block).ret(&[number]);
1823
1824        // `long f(void *p) { return (long)p; }`. An address on this machine is an integer as wide
1825        // as the machine addresses, so the cast changes what the type system calls the value and
1826        // changes nothing about the value, and the register holding it is the one that held it.
1827        assert_eq!(
1828            lower(&mut names, &source),
1829            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
1830             x64.ret_val_64 %0($rax)\n}\n"
1831        );
1832    }
1833
1834    #[test]
1835    fn a_null_pointer_is_a_constant_that_reaches_a_register_before_anything_reads_it() {
1836        let (mut names, mut source, block, _) = blank(&[]);
1837        let mut build = Builder::new(&mut source, block);
1838        let zero = build.iconst(Type::int(64), 0);
1839        let null = cast(&mut source, block, Opcode::IntToPtr, zero, Type::PTR);
1840        Builder::new(&mut source, block).ret(&[null]);
1841
1842        // `void *f(void) { return 0; }`. The cast is nothing, and reading its operand is what
1843        // writes the zero down: a constant is materialized where it is wanted rather than where
1844        // the IR defined it, and without the read there would be no instruction at all.
1845        assert_eq!(
1846            lower(&mut names, &source),
1847            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_64 0\n    x64.ret_val_64 %0($rax)\n}\n"
1848        );
1849    }
1850
1851    #[test]
1852    fn a_cast_between_a_pointer_and_a_narrower_integer_is_reported() {
1853        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
1854        let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(32));
1855        Builder::new(&mut source, block).ret(&[number]);
1856
1857        // The front end never writes one: it casts at the address width and truncates or extends
1858        // around it, so both of those are the rules they always were. IR from somewhere else that
1859        // does write one is refused rather than compiled to a move that keeps the high half.
1860        let failed = func(&source, &mut names, &SYSV).expect_err("no rule narrows an address");
1861        assert_eq!(failed.to_string(), "no rule lowers a `ptrtoint` producing a `i32`");
1862    }
1863}