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;
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/// Why a function could not be lowered.
96///
97/// One reason and then nothing. A function with no rule for something in it is a function this
98/// cannot finish, and the second thing it could not lower is not news.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum Unsupported {
101    /// An instruction no rule fires on.
102    Inst {
103        /// The instruction that stopped it.
104        inst: Inst,
105        /// What the rule file would call it, or nothing if the rule language has no name for it
106        /// at all, which is what an instruction at a width nothing is written about looks like.
107        term: Option<&'static str>,
108    },
109    /// A parameter that does not arrive somewhere this can bring it in from.
110    ///
111    /// Not an instruction, which is why it is a separate arm: it is a fact about the signature
112    /// and there is nothing in the body of the function to point at.
113    Argument {
114        /// Its position in the signature.
115        index: usize,
116        /// What is wrong with where it arrives.
117        missing: Missing,
118    },
119    /// A call that passes or gives back a value this cannot put where the convention wants it.
120    Call {
121        /// The call.
122        inst: Inst,
123        /// Which value, and what is wrong with where it travels.
124        refused: Refused,
125    },
126    /// A call through an address rather than to a name.
127    ///
128    /// The address is a value in a register and the instruction that calls one is a different
129    /// instruction, which nothing describes yet.
130    Indirect {
131        /// The call.
132        inst: Inst,
133    },
134}
135
136impl fmt::Display for Unsupported {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        match *self {
139            Unsupported::Inst { term: Some(term), .. } => write!(f, "no rule lowers `{term}`"),
140            Unsupported::Inst { term: None, .. } => f.write_str("no rule lowers this instruction"),
141            Unsupported::Argument { index, missing } => {
142                write!(f, "parameter {index} {}", missing.why())
143            }
144            Unsupported::Call { refused: Refused { argument: Some(index), missing }, .. } => {
145                write!(f, "argument {index} of this call {}", missing.why())
146            }
147            Unsupported::Call { refused: Refused { argument: None, missing }, .. } => {
148                write!(f, "what this call gives back {}", missing.why())
149            }
150            Unsupported::Indirect { .. } => f.write_str("no rule calls through an address"),
151        }
152    }
153}
154
155impl std::error::Error for Unsupported {}
156
157/// A lowered function, and the one thing about it the frame needs that the machine IR does not
158/// hold.
159#[derive(Debug)]
160pub struct Lowered {
161    /// The function, in machine instructions.
162    pub func: mir::Func,
163    /// How many bytes the widest call in the function needs below the stack pointer for the
164    /// arguments it passes there, or `None` for a function that makes no call at all.
165    ///
166    /// Both halves of that are what [`crate::frame::Layout`] asks for, and both are answered here
167    /// because selection is where a call is built and nothing after it can tell what a call
168    /// needed. `None` is a leaf, which is the function that may use the red zone and the one
169    /// whose stack pointer does not have to be left aligned for anybody.
170    pub calls: Option<u32>,
171}
172
173impl Lowered {
174    /// The layout given, with the two fields only the lowering knows the answer to filled in.
175    ///
176    /// Everything else in a layout comes from the flags the function is compiled under or from the
177    /// allocation, so this takes one and returns it rather than building one.
178    #[must_use]
179    pub fn layout<'a>(&self, base: Layout<'a>) -> Layout<'a> {
180        Layout { leaf: self.calls.is_none(), outgoing: self.calls.unwrap_or(0), ..base }
181    }
182}
183
184/// The x86-64 machine IR for that function.
185///
186/// # Errors
187///
188/// The first instruction no rule fires on, which today is anything at a width the rule set is not
189/// written at, a parameter that does not arrive in a register this can read, or a call that
190/// passes something this cannot put where the convention wants it.
191pub fn func(
192    source: &Func,
193    names: &mut Interner,
194    conv: &'static CallRegs,
195) -> Result<Lowered, Unsupported> {
196    Lowering::new(source, names, conv).run()
197}
198
199/// One function being lowered.
200struct Lowering<'a> {
201    source: &'a Func,
202    names: &'a mut Interner,
203    out: mir::Func,
204    /// The machine register each IR value is in, once it has one.
205    regs: Vec<Option<mir::Reg>>,
206    /// How many times each IR value is read, which is what says whether an instruction may be
207    /// folded into the one that reads it.
208    uses: Vec<u32>,
209    /// The block being filled.
210    at: Option<mir::Block>,
211    /// The machine IR block each IR block became.
212    blocks: Vec<Option<mir::Block>>,
213    /// The class everything is in until there is a rule about a float.
214    gpr: RegClass,
215    /// Where the convention this function is compiled for puts things, which is read for the
216    /// arguments and for the calls.
217    conv: &'static CallRegs,
218    /// The widest call so far, in bytes of argument area, or `None` until there is a call.
219    calls: Option<u32>,
220}
221
222impl<'a> Lowering<'a> {
223    fn new(source: &'a Func, names: &'a mut Interner, conv: &'static CallRegs) -> Self {
224        let counts = source.counts();
225        let name = source.name;
226        let mut uses = vec![0; counts.values];
227        for block in source.blocks() {
228            for inst in source.insts(block) {
229                for &arg in &source[source[inst].args] {
230                    uses[arg.index()] += 1;
231                }
232                for call in source.successors(inst) {
233                    for &arg in &source[call.args] {
234                        uses[arg.index()] += 1;
235                    }
236                }
237            }
238        }
239        Self {
240            source,
241            names,
242            out: mir::Func::new(name),
243            regs: vec![None; counts.values],
244            blocks: vec![None; counts.blocks],
245            uses,
246            at: None,
247            gpr: x86_64::GPR,
248            conv,
249            calls: None,
250        }
251    }
252
253    fn run(mut self) -> Result<Lowered, Unsupported> {
254        // Every block before any of them is filled, because a block that jumps forward has to
255        // name the block it jumps to and a machine IR block is named by a handle rather than by
256        // the IR block it came from.
257        for block in self.source.blocks() {
258            let out = self.out.create_block();
259            self.blocks[block.index()] = Some(out);
260        }
261        for block in self.source.blocks() {
262            self.block(block)?;
263        }
264        Ok(Lowered { func: self.out, calls: self.calls })
265    }
266
267    /// One block: its parameters, then every instruction in it that is not folded into another.
268    fn block(&mut self, block: Block) -> Result<(), Unsupported> {
269        let out = self.out_block(block);
270        self.at = Some(out);
271        if self.source.entry() == Some(block) {
272            self.arrive(block, out)?;
273        } else {
274            for &param in self.source[block].params.iter() {
275                let reg = self.out.append_param(out, self.gpr);
276                self.regs[param.index()] = Some(reg);
277            }
278        }
279
280        // What each instruction matched, and which instructions were folded into another. The
281        // instruction that is folded comes before the one that folds it, so the decision has to
282        // be made for the whole block before any of it is written, and it is made backwards: an
283        // instruction that has been folded into a later one does not get to fold anything into
284        // itself, because the rule that took it only reached one level down.
285        let insts: Vec<Inst> = self.source.insts(block).collect();
286        let mut found: Vec<Option<Match<Term>>> = (0..insts.len()).map(|_| None).collect();
287        let mut folded: Vec<Inst> = Vec::new();
288        for (index, &inst) in insts.iter().enumerate().rev() {
289            if folded.contains(&inst) {
290                continue;
291            }
292            if let Some((plan, matched)) = self.select(inst) {
293                folded.extend(self.folds(inst, plan));
294                found[index] = Some(matched);
295            }
296        }
297
298        for (&inst, matched) in insts.iter().zip(found) {
299            if folded.contains(&inst) || self.writes_nothing(inst) {
300                continue;
301            }
302            // A call is built from the convention rather than matched, which is why it is the one
303            // opcode looked at by name here. Through an address it is a different instruction and
304            // nothing describes that one yet, so it is reported as itself rather than as a term
305            // no rule covers, which would be true and would say nothing.
306            match self.source[inst].opcode {
307                Opcode::Call => {
308                    self.called(inst)?;
309                    continue;
310                }
311                Opcode::CallIndirect => return Err(Unsupported::Indirect { inst }),
312                _ => {}
313            }
314            let matched = matched.ok_or_else(|| self.unsupported(inst))?;
315            self.emit(inst, &matched)?;
316        }
317        self.edges(block, out)
318    }
319
320    /// One call, which is built from the convention rather than matched against the table for the
321    /// same reason the arguments of the function itself are.
322    ///
323    /// The arguments are read before the call is built, which is what materializes a constant
324    /// argument into a register, since no call passes an immediate.
325    fn called(&mut self, inst: Inst) -> Result<(), Unsupported> {
326        let data = &self.source[inst];
327        let Extra::Call(info) = data.extra else { return Err(self.unsupported(inst)) };
328        let info = self.source[info];
329        let Some(callee) = info.callee else { return Err(Unsupported::Indirect { inst }) };
330
331        let values: Vec<Value> = self.source[data.args].to_vec();
332        let mut args = Vec::with_capacity(values.len());
333        for value in values {
334            args.push((self.source[value].ty, self.reg_of(value)?));
335        }
336        let signature = &self.source[info.signature];
337        let variadic = signature.variadic;
338        let returns = signature.return_types().next();
339        // More than one value back is the convention's answer rather than a term's, the same way
340        // a return of two values is, and nothing here has a name for it.
341        if signature.return_types().count() > 1 {
342            return Err(self.unsupported(inst));
343        }
344
345        let block = self.at.expect("a block is being filled");
346        let what = abi::Calling { callee, args: &args, returns, variadic };
347        let made = abi::call(&mut self.out, block, &what, self.conv, self.names)
348            .map_err(|refused| Unsupported::Call { inst, refused })?;
349        self.calls = Some(self.calls.unwrap_or(0).max(made.outgoing));
350        if let (Some(result), Some(reg)) = (data.first_result, made.result) {
351            self.regs[result.index()] = Some(reg);
352        }
353        Ok(())
354    }
355
356    /// Where a block goes, which in machine IR is on the block rather than on its terminator.
357    ///
358    /// That is why no rule ever names a block: a branch is selected for what it reads and the
359    /// edges are copied across here, arguments and all. The arguments are read last, after every
360    /// instruction of the block is written, because an argument that is a constant is
361    /// materialized where it is first wanted and the end of the block is where an edge wants it.
362    fn edges(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
363        let Some(term) = self.source.terminator(block) else { return Ok(()) };
364        let calls: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
365        let mut succs = Vec::with_capacity(calls.len());
366        for call in calls {
367            let args: Vec<Value> = self.source[call.args].to_vec();
368            let mut regs = Vec::with_capacity(args.len());
369            for value in args {
370                regs.push(self.reg_of(value)?);
371            }
372            succs.push(mir::BlockCall { block: self.out_block(call.block), args: regs });
373        }
374        *self.out.succs_mut(out) = succs;
375        Ok(())
376    }
377
378    /// The machine IR block an IR block became.
379    fn out_block(&self, block: Block) -> mir::Block {
380        self.blocks[block.index()].expect("every block was created before any was filled")
381    }
382
383    /// The parameters of the entry block, which are the function's arguments.
384    ///
385    /// They are not block parameters in the machine IR and they cannot be. A block parameter is
386    /// given its value by a move on the edge into the block, and there is no edge into an entry
387    /// block, so what arrives in a function is the convention's to say. [`crate::abi`] is what
388    /// says it.
389    fn arrive(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
390        let params = self.source[block].params.clone();
391        let types: Vec<Type> = params.iter().map(|&value| self.source[value].ty).collect();
392        let regs = abi::entry(&mut self.out, out, &types, self.conv, self.names)
393            .map_err(|(index, missing)| Unsupported::Argument { index, missing })?;
394        for (&param, reg) in params.iter().zip(regs) {
395            self.regs[param.index()] = Some(reg);
396        }
397        Ok(())
398    }
399
400    /// Whether an instruction is one no machine instruction is written for where it stands.
401    ///
402    /// Three of them, and none is a lowering decision, which is why none is a rule. A constant is
403    /// written where a register for it is first wanted rather than where the IR put it, and every
404    /// reader of one may have folded it into an immediate, in which case nowhere is the right
405    /// place. A return of nothing has nothing to put anywhere: the epilogue gives the frame back
406    /// and leaves, and it is appended to every block with no successors long after this has
407    /// finished, so a return with a value is one instruction here and a return without one is
408    /// none. An unconditional jump is the third, and there is even less of it: the edge is on the
409    /// block, and whether the block it goes to is the next one and needs no jump at all is the
410    /// block layout's answer rather than this one's.
411    fn writes_nothing(&self, inst: Inst) -> bool {
412        let data = &self.source[inst];
413        match data.opcode {
414            Opcode::IConst | Opcode::Jump => true,
415            Opcode::Return => self.source[data.args].is_empty(),
416            _ => false,
417        }
418    }
419
420    /// The rule that fires on an instruction, and what it bound.
421    ///
422    /// The plans are tried in order and the first that matches wins, which is the maximal munch
423    /// `spec/10-backend.md` asks for: a plan that offers more to the matcher is tried before one
424    /// that offers less.
425    fn select(&self, inst: Inst) -> Option<(Plan, Match<Term>)> {
426        for plan in self.plans(inst) {
427            let terms = Terms::new(self.source, inst, plan);
428            if let Some(matched) = TABLE.find(&terms, Term::Root) {
429                return Some((plan, matched));
430            }
431        }
432        None
433    }
434
435    /// Every way this instruction can be shown to the matcher, most offered first.
436    fn plans(&self, inst: Inst) -> Vec<Plan> {
437        let args = &self.source[self.source[inst].args];
438        let mut plans = vec![PLAIN];
439        for (index, &arg) in args.iter().enumerate().take(MAX_ARGS) {
440            let mut ways = Vec::new();
441            if self.foldable(inst, arg) {
442                ways.push(Shown::Expand);
443            }
444            if Terms::new(self.source, inst, PLAIN).constant(arg).is_some() {
445                ways.push(Shown::Const);
446            }
447            ways.push(Shown::Reg);
448            plans = plans
449                .into_iter()
450                .flat_map(|plan| {
451                    ways.iter().map(move |&way| {
452                        let mut next = plan;
453                        next[index] = way;
454                        next
455                    })
456                })
457                .collect();
458        }
459        plans
460    }
461
462    /// Whether an operand may be shown as the instruction that computed it.
463    ///
464    /// It has to be in the same block, because a rule that folds one instruction into another
465    /// moves the work to where the second one is. It has to be read only by this instruction,
466    /// because folding it does not delete it for anybody else and doing the work twice is not a
467    /// saving. And it has to be something rather than a block parameter, and not a constant,
468    /// which is shown as a constant instead.
469    fn foldable(&self, into: Inst, value: Value) -> bool {
470        let Def::Result { inst, .. } = self.source[value].def else { return false };
471        if self.source[inst].opcode == Opcode::IConst || self.uses[value.index()] != 1 {
472            return false;
473        }
474        self.source.block_of(inst).is_some()
475            && self.source.block_of(inst) == self.source.block_of(into)
476    }
477
478    /// The instructions a match folded into the one it matched.
479    ///
480    /// The plan is what says this, not the bindings: a binding is a register or a number either
481    /// way, and an operand shown as the instruction that computed it is one no rule could have
482    /// matched without taking that instruction, because the plan offered the matcher nothing
483    /// else to call it.
484    fn folds(&self, inst: Inst, plan: Plan) -> Vec<Inst> {
485        let args = &self.source[self.source[inst].args];
486        args.iter()
487            .take(MAX_ARGS)
488            .enumerate()
489            .filter(|&(index, _)| plan[index] == Shown::Expand)
490            .filter_map(|(_, &arg)| match self.source[arg].def {
491                Def::Result { inst, .. } => Some(inst),
492                Def::Param { .. } => None,
493            })
494            .collect()
495    }
496
497    /// Build the machine instruction a match calls for.
498    fn emit(&mut self, inst: Inst, matched: &Match<Term>) -> Result<(), Unsupported> {
499        let rule: &Rule = TABLE.rule(matched);
500        let pieces = rule.replacement;
501        let Some(Piece::App { head, arity }) = pieces.first() else {
502            return Err(self.unsupported(inst));
503        };
504        let opcode = head.strip_prefix(PREFIX).ok_or_else(|| self.unsupported(inst))?;
505        let form = x86_64::form(opcode).ok_or_else(|| self.unsupported(inst))?;
506
507        let mut read = Read::default();
508        let mut at = 1;
509        for _ in 0..*arity {
510            at = self.read(inst, pieces, at, &matched.bindings, &mut read)?;
511        }
512
513        let descs = form.operands();
514        let writes = descs.iter().take_while(|desc| desc.role.is_def()).count();
515        if descs.len() - writes != read.regs.len() {
516            return Err(self.unsupported(inst));
517        }
518
519        // The first thing the instruction writes is what it computes, and any others are
520        // registers the machine destroys on the way, which are fresh because nothing else is in
521        // them and nothing reads them. An instruction that writes nothing at all is one whose
522        // whole purpose is its effect, which is what a store is, and there is no result to put
523        // anywhere.
524        let mut regs = Vec::new();
525        if writes > 0 {
526            let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
527            regs.push(self.new_reg(result));
528            regs.extend((1..writes).map(|_| self.out.new_vreg(self.gpr)));
529        } else if self.source[inst].first_result.is_some() {
530            // A rule that throws away a value the IR gave a name to would leave every reader of
531            // that name with nothing to read, so it is a rule this and the target disagree about.
532            return Err(self.unsupported(inst));
533        }
534        regs.extend(read.regs.iter().copied());
535
536        let block = self.at.expect("a block is being filled");
537        let opcode = mir::Opcode::new(self.names.intern(head));
538        let mut build = self.out.build(block, opcode).at(self.source.span(inst));
539        for (desc, reg) in descs.iter().zip(regs) {
540            let operand = mir::Operand {
541                reg,
542                class: desc.class,
543                role: desc.role,
544                constraint: desc.constraint,
545            };
546            build = build.operand(operand);
547        }
548        if let Some(mem) = read.mem {
549            build = build.mem(mem);
550        }
551        if let Some(imm) = read.imm {
552            build = build.imm(imm);
553        }
554        build.finish();
555        Ok(())
556    }
557
558    /// Read one argument of a replacement, which is a register, a number or an address.
559    ///
560    /// Gives back the position after it, because a replacement is flat and an address takes
561    /// arguments of its own.
562    fn read(
563        &mut self,
564        inst: Inst,
565        pieces: &'static [Piece],
566        at: usize,
567        bindings: &[Term],
568        out: &mut Read,
569    ) -> Result<usize, Unsupported> {
570        match pieces.get(at) {
571            Some(Piece::Int(value)) => {
572                out.imm = i64::try_from(*value).ok();
573                Ok(at + 1)
574            }
575            Some(Piece::Var { index, .. }) => {
576                match bindings.get(*index) {
577                    Some(&Term::Reg(value)) => {
578                        let reg = self.reg_of(value)?;
579                        out.regs.push(reg);
580                    }
581                    Some(&Term::Num(value)) => out.imm = i64::try_from(value).ok(),
582                    // A pattern binds a register or a number and nothing else, so this is a
583                    // rule the matcher and this file disagree about.
584                    _ => return Err(self.unsupported(inst)),
585                }
586                Ok(at + 1)
587            }
588            Some(Piece::App { head, arity }) => {
589                let kind = x86_64::address(head).ok_or_else(|| self.unsupported(inst))?;
590                let mut inner = Read::default();
591                let mut next = at + 1;
592                for _ in 0..*arity {
593                    next = self.read(inst, pieces, next, bindings, &mut inner)?;
594                }
595                let mem = address(kind, &inner, self.gpr).ok_or_else(|| self.unsupported(inst))?;
596                out.mem = Some(mem);
597                Ok(next)
598            }
599            None => Err(self.unsupported(inst)),
600        }
601    }
602
603    /// The register a value is in, materializing it if it is a constant that has not been put in
604    /// one yet.
605    fn reg_of(&mut self, value: Value) -> Result<mir::Reg, Unsupported> {
606        if let Some(reg) = self.regs[value.index()] {
607            return Ok(reg);
608        }
609        let constant = match self.source[value].def {
610            Def::Result { inst, .. } => {
611                (self.source[inst].opcode == Opcode::IConst).then_some(inst)
612            }
613            Def::Param { .. } => None,
614        };
615        if let Some(inst) = constant {
616            let matched = self
617                .select(inst)
618                .map(|(_, matched)| matched)
619                .ok_or_else(|| self.unsupported(inst))?;
620            self.emit(inst, &matched)?;
621            return Ok(self.regs[value.index()].expect("a constant is written into a register"));
622        }
623        Ok(self.new_reg(value))
624    }
625
626    /// A fresh register for a value, which is what the instruction computing it writes.
627    fn new_reg(&mut self, value: Value) -> mir::Reg {
628        if let Some(reg) = self.regs[value.index()] {
629            return reg;
630        }
631        let reg = self.out.new_vreg(self.gpr);
632        self.regs[value.index()] = Some(reg);
633        reg
634    }
635
636    fn unsupported(&self, inst: Inst) -> Unsupported {
637        Unsupported::Inst { inst, term: Terms::new(self.source, inst, PLAIN).name(inst) }
638    }
639}
640
641/// What the arguments of one replacement came to.
642#[derive(Debug, Default)]
643struct Read {
644    regs: Vec<mir::Reg>,
645    imm: Option<i64>,
646    mem: Option<mir::Mem>,
647}
648
649/// The addressing mode an address constructor's arguments make.
650///
651/// One arm per constructor rather than a question asked of the kind, because what the arguments
652/// mean is the whole of what tells the four apart: the same register is a base in one and an
653/// index in another, and the same constant is a scale in one and a displacement in another.
654fn address(kind: x86_64::Address, read: &Read, gpr: RegClass) -> Option<mir::Mem> {
655    let mut regs = read.regs.iter().copied().map(|reg| mir::Operand::read(reg, gpr));
656    match kind {
657        x86_64::Address::BaseIndexScale => {
658            let base = regs.next()?;
659            let index = regs.next()?;
660            Some(mir::Mem::at(base).indexed(index, u8::try_from(read.imm?).ok()?))
661        }
662        x86_64::Address::IndexScale => Some(mir::Mem {
663            base: None,
664            index: Some(regs.next()?),
665            scale: u8::try_from(read.imm?).ok()?,
666            disp: 0,
667            symbol: None,
668        }),
669        x86_64::Address::Base => Some(mir::Mem::at(regs.next()?)),
670        // The rule that writes this has a guard saying the constant fits, so a displacement that
671        // does not is a rule and a target that disagree rather than a program this cannot compile.
672        x86_64::Address::BaseOffset => {
673            Some(mir::Mem { disp: i32::try_from(read.imm?).ok()?, ..mir::Mem::at(regs.next()?) })
674        }
675    }
676}
677
678/// The table this selector matches with.
679///
680/// One target for now, because one target has a rule file. Which table to use becomes a question
681/// the moment a second one does, and the answer will be the target the session was given rather
682/// than a constant here.
683static TABLE: &Table = &crate::select::x86_64::TABLE;
684
685#[cfg(test)]
686mod tests {
687    use rucc_ir::{Builder, CallInfo, Flags, InstData, MemInfo, MemOrder, Signature, Type};
688    use rucc_regalloc::assign::Env;
689    use rucc_target::x86_64::{FRAME, REGS, SYSV};
690
691    use super::*;
692    use crate::finish::finish;
693    use crate::frame::{Frame, Layout};
694
695    /// A function of as many 64 bit parameters as the test wants, and the block they are in.
696    fn blank(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
697        let mut names = Interner::new();
698        let mut func = Func::new(names.intern("f"), Signature::new());
699        let block = func.create_block();
700        let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
701        (names, func, block, values)
702    }
703
704    /// An ordinary access: not atomic, and aligned enough that nothing here has an opinion.
705    /// Neither field reaches selection, which is the point of saying it once here.
706    fn plain() -> MemInfo {
707        MemInfo { size: 0, align: 1, order: MemOrder::NotAtomic, tbaa: None }
708    }
709
710    /// What the allocator is given: every integer register the convention offers except two, held
711    /// back so that a move on an edge has somewhere to break a cycle and a spilled value has
712    /// somewhere to be read into. Which two does not matter, and holding back the last two the
713    /// convention would reach for leaves every expectation below unchanged.
714    fn env() -> Env {
715        const SCRATCH: [rucc_target::PhysReg; 2] = [x86_64::R10, x86_64::R11];
716        let order: Vec<rucc_target::PhysReg> =
717            SYSV.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
718        Env::new().with(x86_64::GPR, &order, &SCRATCH)
719    }
720
721    /// The machine IR text a function lowers to.
722    fn lower(names: &mut Interner, source: &Func) -> String {
723        let out = func(source, names, &SYSV).expect("every instruction has a rule");
724        mir::print_func(&out.func, names, &REGS)
725    }
726
727    #[test]
728    fn an_addition_of_two_registers_is_one_instruction() {
729        let i32 = Type::int(32);
730        let (mut names, mut func, block, args) = blank(&[i32, i32]);
731        let mut build = Builder::new(&mut func, block);
732        build.binary(Opcode::Add, args[0], args[1], Flags::default());
733
734        assert_eq!(
735            lower(&mut names, &func),
736            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
737             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr(reuse 1) = x64.add_rr_32 %0, %1\n}\n"
738        );
739    }
740
741    #[test]
742    fn a_constant_operand_becomes_an_immediate() {
743        let i32 = Type::int(32);
744        let (mut names, mut func, block, args) = blank(&[i32]);
745        let mut build = Builder::new(&mut func, block);
746        let seven = build.iconst(i32, 7);
747        build.binary(Opcode::Add, args[0], seven, Flags::default());
748
749        // The constant is in the instruction and nothing was written to hold it, which is what
750        // materializing one where a register for it is wanted buys.
751        assert_eq!(
752            lower(&mut names, &func),
753            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
754             %1:gpr(reuse 1) = x64.add_ri_32 %0, 7\n}\n"
755        );
756    }
757
758    #[test]
759    fn a_constant_too_wide_for_an_immediate_goes_into_a_register() {
760        let i64 = Type::int(64);
761        let (mut names, mut func, block, args) = blank(&[i64]);
762        let mut build = Builder::new(&mut func, block);
763        let big = build.iconst(i64, i128::from(i32::MAX) + 1);
764        build.binary(Opcode::Add, args[0], big, Flags::default());
765
766        // Nobody wrote this fallback down. The rule that takes an immediate has a guard that
767        // turns a number this wide down, so it does not fire, and the next way of showing the
768        // operand puts it in a register.
769        assert_eq!(
770            lower(&mut names, &func),
771            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
772             %1:gpr = x64.mov_ri_64 2147483648\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n}\n"
773        );
774    }
775
776    #[test]
777    fn an_index_calculation_folds_into_an_address() {
778        let i64 = Type::int(64);
779        let (mut names, mut func, block, args) = blank(&[i64, i64]);
780        let mut build = Builder::new(&mut func, block);
781        let four = build.iconst(i64, 4);
782        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
783        build.binary(Opcode::Add, args[0], scaled, Flags::default());
784
785        // Three IR instructions and one machine instruction. The multiply is gone because the
786        // rule that matched reached down and took it.
787        assert_eq!(
788            lower(&mut names, &func),
789            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
790             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.lea_64 [%0 + %1*4]\n}\n"
791        );
792    }
793
794    #[test]
795    fn an_instruction_read_twice_is_not_folded_into_either_reader() {
796        let i64 = Type::int(64);
797        let (mut names, mut func, block, args) = blank(&[i64, i64]);
798        let mut build = Builder::new(&mut func, block);
799        let four = build.iconst(i64, 4);
800        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
801        let first = build.binary(Opcode::Add, args[0], scaled, Flags::default());
802        build.binary(Opcode::Add, first, scaled, Flags::default());
803
804        // Folding it into both would compute it twice, which is not a saving, so it stays where
805        // it is and both readers read the register it wrote.
806        let text = lower(&mut names, &func);
807        assert!(text.contains("x64.lea_64 [%1*4]"), "{text}");
808        assert_eq!(text.matches("x64.add_rr_64").count(), 2, "{text}");
809    }
810
811    #[test]
812    fn a_shift_by_a_register_asks_for_it_in_cl() {
813        let i32 = Type::int(32);
814        let (mut names, mut func, block, args) = blank(&[i32, i32]);
815        let mut build = Builder::new(&mut func, block);
816        build.binary(Opcode::Shl, args[0], args[1], Flags::default());
817
818        // The fixed register is not in the rule. It is what the target says the instruction does
819        // with its operands, and the allocator is what will act on it.
820        let text = lower(&mut names, &func);
821        assert!(text.contains("x64.shl_rcl_32 %0, %1($rcx)"), "{text}");
822    }
823
824    #[test]
825    fn a_division_names_the_registers_and_the_register_it_destroys() {
826        let i32 = Type::int(32);
827        let (mut names, mut func, block, args) = blank(&[i32, i32]);
828        let mut build = Builder::new(&mut func, block);
829        build.binary(Opcode::SDiv, args[0], args[1], Flags::default());
830
831        // Two definitions, because a division writes the remainder whether anybody wanted it or
832        // not, and the second one is early because it is destroyed before the operands are read.
833        let text = lower(&mut names, &func);
834        assert!(
835            text.contains("%2:gpr($rax), early %3:gpr($rdx) = x64.idiv_quo_32 %0($rax), %1"),
836            "{text}"
837        );
838    }
839
840    #[test]
841    fn a_load_reads_through_the_register_the_address_is_in() {
842        let i64 = Type::int(64);
843        let (mut names, mut func, block, args) = blank(&[i64]);
844        let mut build = Builder::new(&mut func, block);
845        build.load(Type::int(32), args[0], plain(), Flags::default());
846
847        assert_eq!(
848            lower(&mut names, &func),
849            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
850             %1:gpr = x64.mov_rm_32 [%0]\n}\n"
851        );
852    }
853
854    #[test]
855    fn a_store_writes_no_register_and_the_value_it_writes_is_the_one_the_ir_gave_it() {
856        let (mut names, mut func, block, args) = blank(&[Type::int(32), Type::int(64)]);
857        let mut build = Builder::new(&mut func, block);
858        build.store(args[0], args[1], plain(), Flags::default());
859
860        // The value is the first parameter and the address is the second, and the instruction
861        // takes them the other way round. Getting that backwards would compile to a store of the
862        // address into the value, which is a program that runs and does the wrong thing.
863        assert_eq!(
864            lower(&mut names, &func),
865            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
866             %1:gpr($rsi) = x64.arg_val_64\n    x64.mov_mr_32 %0, [%1]\n}\n"
867        );
868    }
869
870    #[test]
871    fn an_address_with_a_constant_added_folds_into_the_access() {
872        let i64 = Type::int(64);
873        let (mut names, mut func, block, args) = blank(&[i64]);
874        let mut build = Builder::new(&mut func, block);
875        let twelve = build.iconst(i64, 12);
876        let field = build.binary(Opcode::Add, args[0], twelve, Flags::default());
877        build.load(Type::int(64), field, plain(), Flags::default());
878
879        // Two IR instructions and one machine instruction, which is what every read of a field
880        // of a structure comes to.
881        assert_eq!(
882            lower(&mut names, &func),
883            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
884             %1:gpr = x64.mov_rm_64 [%0 + 12]\n}\n"
885        );
886    }
887
888    #[test]
889    fn a_displacement_too_wide_to_encode_leaves_the_addition_where_it_is() {
890        let i64 = Type::int(64);
891        let (mut names, mut func, block, args) = blank(&[i64]);
892        let mut build = Builder::new(&mut func, block);
893        let big = build.iconst(i64, i128::from(i32::MAX) + 1);
894        let far = build.binary(Opcode::Add, args[0], big, Flags::default());
895        build.load(Type::int(32), far, plain(), Flags::default());
896
897        // A displacement is signed and 32 bits. The rule that folds one has a guard that turns
898        // this down, so the addition stays and the load reads through what it produced. Nobody
899        // wrote that fallback: it is the next way of showing the operand.
900        let text = lower(&mut names, &func);
901        assert!(text.contains("x64.mov_rm_32 [%2]"), "{text}");
902        assert!(text.contains("x64.add_rr_64"), "{text}");
903    }
904
905    #[test]
906    fn a_store_of_a_value_that_was_loaded_is_two_instructions_and_no_arithmetic() {
907        let i64 = Type::int(64);
908        let (mut names, mut func, block, args) = blank(&[i64, i64]);
909        let mut build = Builder::new(&mut func, block);
910        let got = build.load(Type::int(8), args[0], plain(), Flags::default());
911        build.store(got, args[1], plain(), Flags::default());
912
913        // A load feeding a store is the one place folding would be wrong: an x86-64 `mov` has at
914        // most one memory operand, and there is no rule that takes two, so the load is left where
915        // it is and the store reads the register it wrote.
916        assert_eq!(
917            lower(&mut names, &func),
918            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
919             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.mov_rm_8 [%0]\n    \
920             x64.mov_mr_8 %2, [%1]\n}\n"
921        );
922    }
923
924    #[test]
925    fn an_access_at_a_width_no_rule_is_written_at_is_reported() {
926        let i64 = Type::int(64);
927        let (mut names, mut source, block, args) = blank(&[i64]);
928        let mut build = Builder::new(&mut source, block);
929        build.load(Type::int(128), args[0], plain(), Flags::default());
930
931        let failed = func(&source, &mut names, &SYSV).expect_err("nothing loads 128 bits");
932        assert_eq!(failed.to_string(), "no rule lowers this instruction");
933    }
934
935    #[test]
936    fn a_return_asks_for_the_value_in_the_register_the_caller_reads() {
937        let (mut names, mut func, block, args) = blank(&[Type::int(32)]);
938        let mut build = Builder::new(&mut func, block);
939        build.ret(&[args[0]]);
940
941        // The register is not in the rule, the same way `cl` is not in the rule for a shift. It
942        // is what the target says the instruction does with its operand, and the allocator is
943        // what will act on it. There is no `ret` here, because giving the frame back has to
944        // happen between this and leaving and the frame is not worked out yet.
945        assert_eq!(
946            lower(&mut names, &func),
947            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
948             x64.ret_val_32 %0($rax)\n}\n"
949        );
950    }
951
952    #[test]
953    fn a_return_of_a_constant_puts_it_in_a_register_first() {
954        let (mut names, mut func, block, _) = blank(&[]);
955        let mut build = Builder::new(&mut func, block);
956        let zero = build.iconst(Type::int(32), 0);
957        build.ret(&[zero]);
958
959        // No rule returns an immediate, so the plan that offers one is turned down and the next
960        // one materializes it. That is `int main(void) { return 0; }` in full, once the epilogue
961        // is appended to it.
962        assert_eq!(
963            lower(&mut names, &func),
964            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 0\n    x64.ret_val_32 %0($rax)\n}\n"
965        );
966    }
967
968    #[test]
969    fn a_return_of_nothing_is_no_instruction_at_all() {
970        let (mut names, mut func, block, _) = blank(&[]);
971        let mut build = Builder::new(&mut func, block);
972        build.ret(&[]);
973
974        // Every part of leaving a function that returns nothing is the epilogue's, and the
975        // epilogue goes in after allocation. A block with nothing in it is the right answer here
976        // rather than a function that could not be lowered.
977        assert_eq!(lower(&mut names, &func), "mfunc @f {\nblock0:\n}\n");
978    }
979
980    #[test]
981    fn the_allocator_is_what_moves_the_answer_into_the_return_register() {
982        let (mut names, mut source, block, _) = blank(&[]);
983        let mut build = Builder::new(&mut source, block);
984        let zero = build.iconst(Type::int(32), 0);
985        build.ret(&[zero]);
986
987        let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
988        let env = env();
989        let allocation = rucc_regalloc::run(&mut out, &env);
990        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
991        finish(&mut out, &allocation, &frame, &SYSV, &FRAME, &mut names);
992
993        // `int main(void) { return 0; }` end to end. Nothing here asked for `rax`: the rule said
994        // the value goes back, the target said where, and the allocator is what made it true. The
995        // epilogue is what leaves, and this function needs no frame, so it is the return alone.
996        //
997        // The copy is a register allocator that takes no hints. It hands `%0` a register at the
998        // instruction that writes it, where it does not yet know that a later use insists on
999        // `rax`, and `rax` is not free to hand out because that later use is holding it. So the
1000        // value goes somewhere else and is copied in. Every division and every shift by a
1001        // register already pays the same thing, and paying it once per return is what makes it
1002        // worth fixing rather than a new problem.
1003        assert_eq!(
1004            mir::print_func(&out, &names, &REGS),
1005            "mfunc @f {\nblock0:\n    $rcx = x64.mov_ri_32 0\n    $rax = x64.mov_rr_64 $rcx\n    \
1006             x64.ret_val_32 $rax($rax)\n    x64.ret\n}\n"
1007        );
1008    }
1009
1010    #[test]
1011    fn a_function_of_two_arguments_is_a_whole_function_now() {
1012        let i32 = Type::int(32);
1013        let (mut names, mut source, block, args) = blank(&[i32, i32]);
1014        let mut build = Builder::new(&mut source, block);
1015        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
1016        build.ret(&[sum]);
1017
1018        let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1019        let env = env();
1020        let allocation = rucc_regalloc::run(&mut out, &env);
1021        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
1022        finish(&mut out, &allocation, &frame, &SYSV, &FRAME, &mut names);
1023
1024        // `int f(int a, int b) { return a + b; }` end to end, and this is the test the argument
1025        // side exists for. Before it there was no way to write one: the allocator refuses a
1026        // function whose entry block takes parameters, because there is no edge into an entry
1027        // block for the moves that give a block parameter its value to go on.
1028        //
1029        // Four moves that a good allocator writes none of, and it is the same allocator that
1030        // takes no hints as in the return above rather than anything new. It hands each argument
1031        // a register at the pseudo that defines it, without looking at the fixed register that
1032        // pseudo insists on, so every argument is copied straight back out of where it already
1033        // was. Issue #255 is this, and this function is the shortest program that shows what it
1034        // costs: one hint per argument and one per return would leave nothing here but the
1035        // addition. What the test is for meanwhile is that the answer is right, and it is: the
1036        // copy in front of a two address instruction is what makes its destination one of the
1037        // registers it reads, and the source operand keeps its own name because the destination
1038        // is what the encoder writes.
1039        assert_eq!(
1040            mir::print_func(&out, &names, &REGS),
1041            "mfunc @f {\nblock0:\n    $rdi($rdi) = x64.arg_val_32\n    \
1042             $rax = x64.mov_rr_64 $rdi\n    $rsi($rsi) = x64.arg_val_32\n    \
1043             $rcx = x64.mov_rr_64 $rsi\n    $rdx = x64.mov_rr_64 $rax\n    \
1044             $rdx(reuse 1) = x64.add_rr_32 $rax, $rcx\n    $rax = x64.mov_rr_64 $rdx\n    \
1045             x64.ret_val_32 $rax($rax)\n    x64.ret\n}\n"
1046        );
1047    }
1048
1049    #[test]
1050    fn an_argument_with_no_register_left_for_it_is_reported() {
1051        let i64 = Type::int(64);
1052        let (mut names, mut source, block, args) = blank(&[i64; 7]);
1053        let mut build = Builder::new(&mut source, block);
1054        build.ret(&[args[6]]);
1055
1056        // SysV passes six integers in registers and the seventh on the stack, and reading it from
1057        // there means knowing where the frame put it, which nothing knows until the allocator has
1058        // finished. So this is reported rather than compiled to a read of whatever `r9` still had.
1059        let failed = func(&source, &mut names, &SYSV).expect_err("the seventh is on the stack");
1060        assert_eq!(failed.to_string(), "parameter 6 is passed on the stack");
1061    }
1062
1063    #[test]
1064    fn a_jump_is_the_edge_and_nothing_else() {
1065        let i32 = Type::int(32);
1066        let (mut names, mut source, entry, args) = blank(&[i32]);
1067        let next = source.create_block();
1068        let got = source.append_param(next, i32);
1069        Builder::new(&mut source, entry).jump(next, &[args[0]]);
1070        Builder::new(&mut source, next).ret(&[got]);
1071
1072        // Two blocks and two instructions, and the jump is neither of them. What it was is the
1073        // arm on the first block, and what the arm carries is the argument it was called with.
1074        assert_eq!(
1075            lower(&mut names, &source),
1076            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32 block1(%0)\n\n\
1077             block1(%1:gpr):\n    x64.ret_val_32 %1($rax)\n}\n"
1078        );
1079    }
1080
1081    #[test]
1082    fn a_conditional_branch_is_lowered_to_the_condition_and_nothing_about_where_it_goes() {
1083        let i32 = Type::int(32);
1084        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1085        let then = source.create_block();
1086        let other = source.create_block();
1087        let mut build = Builder::new(&mut source, entry);
1088        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1089        build.br_if(cond, then, &[], other, &[]);
1090        Builder::new(&mut source, then).ret(&[args[0]]);
1091        Builder::new(&mut source, other).ret(&[args[1]]);
1092
1093        // The comparison writes a byte and the branch reads it, and neither says a block. Both
1094        // arms are on the entry block, in the order the branch took them, so the arm that runs
1095        // when the condition holds is the first.
1096        assert_eq!(
1097            lower(&mut names, &source),
1098            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
1099             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr = x64.cmp_set_l_32 %0, %1\n    \
1100             x64.br_cond_8 %2, block1, block2\n\n\
1101             block1:\n    x64.ret_val_32 %0($rax)\n\n\
1102             block2:\n    x64.ret_val_32 %1($rax)\n}\n"
1103        );
1104    }
1105
1106    #[test]
1107    fn a_branch_over_a_block_is_a_whole_function_now() {
1108        let i32 = Type::int(32);
1109        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1110        let then = source.create_block();
1111        let other = source.create_block();
1112        let join = source.create_block();
1113        let got = source.append_param(join, i32);
1114        let mut build = Builder::new(&mut source, entry);
1115        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1116        build.br_if(cond, then, &[], other, &[]);
1117        let mut build = Builder::new(&mut source, then);
1118        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
1119        build.jump(join, &[sum]);
1120        Builder::new(&mut source, other).jump(join, &[args[1]]);
1121        Builder::new(&mut source, join).ret(&[got]);
1122
1123        // `int f(int a, int b) { if (a < b) return a + b; else return b; }` end to end, written
1124        // the way a front end writes it: both arms of the branch are blocks of their own and the
1125        // return is the block they meet at. No edge here is critical, because the two arms out of
1126        // the entry carry nothing and the two arms into the join each leave a block that goes
1127        // nowhere else, so each has its own end to put its move at.
1128        let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1129        assert_eq!(crate::split::critical(&mut out), 0, "no edge here is critical");
1130        let env = env();
1131        let allocation = rucc_regalloc::run(&mut out, &env);
1132        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
1133        finish(&mut out, &allocation, &frame, &SYSV, &FRAME, &mut names);
1134
1135        // One epilogue, on the join, which is the one block the function leaves from, and the
1136        // moves that give the join its parameter are at the end of each arm. Every register is
1137        // physical and the branch is still a branch on a register, because turning it into a
1138        // `test` and a `jcc` is the block layout's and there is no block layout yet.
1139        let text = mir::print_func(&out, &names, &REGS);
1140        assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
1141        assert!(text.contains("x64.br_cond_8"), "{text}");
1142        assert!(text.contains("x64.add_rr_32"), "{text}");
1143        assert!(!text.contains('%'), "{text}");
1144    }
1145
1146    #[test]
1147    fn a_critical_edge_is_split_before_the_allocator_ever_sees_it() {
1148        let i32 = Type::int(32);
1149        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1150        let then = source.create_block();
1151        let join = source.create_block();
1152        let got = source.append_param(join, i32);
1153        let mut build = Builder::new(&mut source, entry);
1154        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1155        build.br_if(cond, then, &[], join, &[args[1]]);
1156        Builder::new(&mut source, then).jump(join, &[args[0]]);
1157        let mut build = Builder::new(&mut source, join);
1158        let twice = build.binary(Opcode::Add, got, got, Flags::default());
1159        build.ret(&[twice]);
1160
1161        // The else arm is critical: the entry block leaves two ways and the join is arrived at
1162        // two ways, and the arm carries a value. Without splitting it the allocator asserts,
1163        // because the move that gives the join its parameter would have to run at the end of a
1164        // block that also goes to the other arm.
1165        let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1166        assert_eq!(crate::split::critical(&mut out), 1);
1167        let env = env();
1168        let allocation = rucc_regalloc::run(&mut out, &env);
1169        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
1170        finish(&mut out, &allocation, &frame, &SYSV, &FRAME, &mut names);
1171
1172        // The block the split added is where the move went, and it is the whole of that block.
1173        let text = mir::print_func(&out, &names, &REGS);
1174        assert_eq!(out.block_count(), 4, "{text}");
1175        assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
1176    }
1177
1178    #[test]
1179    fn a_call_passes_what_the_convention_says_and_takes_back_what_it_says() {
1180        let i32 = Type::int(32);
1181        let (mut names, mut source, block, args) = blank(&[i32, i32]);
1182        let sig =
1183            source.add_signature(Signature::new().with_params(&[i32, i32]).with_returns(&[i32]));
1184        let callee = names.intern("g");
1185        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0], args[1]]);
1186        let got = source[call].first_result.expect("an integer comes back");
1187        Builder::new(&mut source, block).ret(&[got]);
1188
1189        // `int f(int a, int b) { return g(a, b); }`. The arguments arrived where the call wants
1190        // them, so what the call reads is what arrived, and the whole of the convention is in the
1191        // constraints rather than in a move.
1192        let text = lower(&mut names, &source);
1193        assert!(text.contains("= x64.call %0($rdi), %1($rsi), @g"), "{text}");
1194        assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
1195        // What the call writes is the value that comes back and then every register the callee is
1196        // free to destroy, in both classes, which is the whole of what stops the allocator from
1197        // leaving something in one of them.
1198        assert!(text.contains("%2:gpr($rax), $rcx, $rdx, $r8, $r9, $r10, $r11, $xmm0,"), "{text}");
1199        assert!(text.contains("$xmm15 = x64.call"), "{text}");
1200    }
1201
1202    #[test]
1203    fn what_the_frame_owes_a_call_comes_back_with_the_function() {
1204        let i32 = Type::int(32);
1205        let sig = |source: &mut Func| source.add_signature(Signature::new().with_params(&[i32]));
1206
1207        let (mut names, mut source, block, args) = blank(&[i32]);
1208        let sig = sig(&mut source);
1209        let callee = names.intern("g");
1210        Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
1211        let out = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1212
1213        // Nothing on the stack, so nothing owed, but not a leaf either: a function that calls
1214        // owes the callee an aligned stack pointer and may not use the red zone.
1215        assert_eq!(out.calls, Some(0));
1216        let layout = out.layout(Layout::new(&SYSV, REGS));
1217        assert!(!layout.leaf);
1218        assert_eq!(layout.outgoing, 0);
1219
1220        // The same call under the other convention owes thirty two bytes for the callee to spill
1221        // its register arguments into, which is a fact about the convention and not about the call.
1222        let out = func(&source, &mut names, &x86_64::WIN64).expect("every instruction has a rule");
1223        assert_eq!(out.calls, Some(32));
1224
1225        // And a function that calls nothing is a leaf, which is what says it may use the red zone.
1226        let (mut names, mut source, block, args) = blank(&[i32]);
1227        Builder::new(&mut source, block).ret(&[args[0]]);
1228        let out = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1229        assert_eq!(out.calls, None);
1230        assert!(out.layout(Layout::new(&SYSV, REGS)).leaf);
1231    }
1232
1233    #[test]
1234    fn a_value_that_outlives_a_call_is_not_left_where_the_call_destroys_it() {
1235        let i32 = Type::int(32);
1236        let (mut names, mut source, block, args) = blank(&[i32]);
1237        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
1238        let callee = names.intern("g");
1239        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
1240        let got = source[call].first_result.expect("an integer comes back");
1241        let mut build = Builder::new(&mut source, block);
1242        let sum = build.binary(Opcode::Add, got, args[0], Flags::default());
1243        build.ret(&[sum]);
1244
1245        // `int f(int a) { return g(a) + a; }`, which is the smallest program that asks the
1246        // question: `a` is read after the call and `rdi` is a register the call destroys.
1247        let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1248        let layout = lowered.layout(Layout::new(&SYSV, REGS));
1249        let mut out = lowered.func;
1250        let env = env();
1251        let allocation = rucc_regalloc::run(&mut out, &env);
1252        let frame = Frame::of(&out, &allocation, &layout);
1253        finish(&mut out, &allocation, &frame, &SYSV, &FRAME, &mut names);
1254
1255        // It went to a register the callee has to put back, and the prologue and epilogue are what
1256        // put it back, which is the whole bargain the two halves of a convention make.
1257        let text = mir::print_func(&out, &names, &REGS);
1258        assert!(text.contains("$rbx"), "{text}");
1259        assert!(!text.contains('%'), "{text}");
1260        assert_eq!(text.matches("x64.call").count(), 1, "{text}");
1261    }
1262
1263    #[test]
1264    fn a_call_this_cannot_make_is_reported_rather_than_made() {
1265        let i64 = Type::int(64);
1266        let (mut names, mut source, block, args) = blank(&[i64]);
1267        let seven = vec![i64; 7];
1268        let sig = source.add_signature(Signature::new().with_params(&seven));
1269        let callee = names.intern("g");
1270        let passed = vec![args[0]; 7];
1271        Builder::new(&mut source, block).call(callee, sig, &passed);
1272
1273        // The seventh argument travels on the stack, and where the stack put it is a distance into
1274        // a frame that does not exist until after allocation.
1275        let failed = func(&source, &mut names, &SYSV).expect_err("the seventh is on the stack");
1276        assert_eq!(failed.to_string(), "argument 6 of this call is passed on the stack");
1277
1278        let (mut names, mut source, block, _) = blank(&[]);
1279        let sig = source
1280            .add_signature(Signature::new().with_returns(&[Type::float(rucc_ir::Float::F64)]));
1281        let callee = names.intern("g");
1282        Builder::new(&mut source, block).call(callee, sig, &[]);
1283        let failed = func(&source, &mut names, &SYSV).expect_err("a double comes back in xmm0");
1284        assert_eq!(failed.to_string(), "what this call gives back is in a vector register");
1285    }
1286
1287    #[test]
1288    fn a_call_through_an_address_is_reported_as_one() {
1289        let i32 = Type::int(32);
1290        let (mut names, mut source, block, args) = blank(&[i32]);
1291        let sig = source.add_signature(Signature::new().with_params(&[i32]));
1292        let varargs = source.push_abis(&[]);
1293        let info = source.add_call(CallInfo { callee: None, signature: sig, varargs });
1294        let mut build = Builder::new(&mut source, block);
1295        let inst = InstData {
1296            args: build.func().push_values(&[args[0], args[0]]),
1297            extra: Extra::Call(info),
1298            ..InstData::new(Opcode::CallIndirect)
1299        };
1300        build.inst(inst, &[]);
1301
1302        // The address is a value in a register and the instruction that calls one of those is a
1303        // different instruction, which nothing describes yet.
1304        let failed = func(&source, &mut names, &SYSV).expect_err("nothing calls through a value");
1305        assert_eq!(failed.to_string(), "no rule calls through an address");
1306    }
1307
1308    #[test]
1309    fn an_instruction_no_rule_covers_is_reported() {
1310        let i64 = Type::int(64);
1311        let (mut names, mut source, block, args) = blank(&[i64, i64]);
1312        let mut build = Builder::new(&mut source, block);
1313        build.ret(&[args[0], args[1]]);
1314
1315        // Two values back at once. Where each of them goes is the convention's answer rather than
1316        // a term's, so the rule language has no name for it and no rule fires.
1317        let failed = func(&source, &mut names, &SYSV).expect_err("nothing returns two values");
1318        assert_eq!(failed.to_string(), "no rule lowers this instruction");
1319    }
1320}