Skip to main content

rucc_codegen/
lowering.rs

1//! The passes that run before selection, as a group with a name and a stated membership.
2//!
3//! Design: `spec/optimizer/36-lowering-and-isel.md` section 36.1.
4//!
5//! Section 36.1 reads the list of passes gcc runs immediately before `pass_expand` and draws one
6//! conclusion from it. Nine of them are lowerings, and each one turns a construct into a shape of
7//! control flow or a shape of arithmetic that the expander would otherwise have to invent. The
8//! expander is the wrong place to invent control flow, because by the time it runs the graph is
9//! being consumed rather than edited. That is spec 10.2's rule arrived at from the other side: a
10//! lowering rule replaces a term with a term and has nowhere to put a block, so any construct whose
11//! lowering is a new shape of control flow is rewritten before selection runs.
12//!
13//! Every one of these passes already existed and every one of them was already called from
14//! `crate::pipeline`, one line at a time, in this order. What did not exist was the thing the
15//! section asks for, which is that they are a group rather than a set of unrelated passes that
16//! happen to run next to each other. The reason gcc's list is nine passes long is that it grew one
17//! pass at a time over three decades, and a group with a written down membership is the thing that
18//! stops the same happening here.
19//!
20//! # The name
21//!
22//! The lowering group, which is what gcc calls its own and is what this module is named after. The
23//! longer and more honest description section 36.1 gives is everything the selector cannot express,
24//! and that is the test for whether something belongs here: not that it is a rewrite of the IR, but
25//! that the thing it rewrites is one no rule in the table can be written for.
26//!
27//! # What is in it
28//!
29//! [`Step::GROUP`], in the order it runs, and that list is the membership. A new lowering is a new
30//! variant of [`Step`] and a new line in that list, which is one place rather than whichever line
31//! of the pipeline looked convenient.
32//!
33//! # What the order is for
34//!
35//! Most of it does not matter and the parts that do are on the variants. The rule behind them is
36//! the same one every time: a pass is written about the constructs the machine has, so anything
37//! that produces a construct somebody below is written about has to run above them. An integer of
38//! forty bits is not a width this machine has, an ordered load is not a load any pass below is
39//! written about, and a quad float is not a float the pass that rewrites floats knows anything of.
40//!
41//! # What it is not
42//!
43//! Not the selector, and not a fixed point. Each step runs once, and a step that produces work for
44//! a step above it would be a bug in this order rather than a reason to run the group twice.
45//!
46//! Not a promise that the construct is gone either, and this is the part worth reading twice. Every
47//! step here has cases it walks away from: a copy too large to be a run of moves, an ordered access
48//! wider than the machine does in one go, a conversion the machine already has an instruction for
49//! and so has no reason to touch. Some of those are the machine having the construct after all and
50//! some of them are a refusal, and a refusal is left standing on purpose, because the selector is
51//! what names the construct it had no rule for and that is a better error than a rewrite that
52//! guessed.
53//!
54//! So what [`Ran`] records is what each step found and what it left, and reading one of those is
55//! how you tell the two apart. What the group promises is only that every construct in the list was
56//! put in front of the step that answers for it, which is the thing that stops being true when
57//! somebody adds a lowering to whichever line of the pipeline looked convenient.
58
59use std::fmt::Write as _;
60
61use rucc_base::Interner;
62use rucc_cost::Goal;
63use rucc_ir::{Func, Opcode};
64use rucc_target::CallRegs;
65
66use crate::switch::{Force, Lowered};
67use crate::{expand, half, quad, retry, switch, varargs, wide, widths};
68
69/// One member of the group.
70///
71/// The name of the variant is the name of the construct rather than the name of the function that
72/// takes it out, because the membership is a list of constructs. Which function answers for one is
73/// something this file knows and nothing outside it needs to.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
75pub enum Step {
76    /// A `switch`, as the decision tree document 24 describes.
77    Switches,
78    /// A read modify write this machine has no single instruction for, as a loop around the compare
79    /// and exchange.
80    ///
81    /// Beside the switches rather than down with the rest of the rewriting, because both of them
82    /// make blocks and nothing in [`crate::expand`] may.
83    Retries,
84    /// An ordered load or store, as the plain access and a barrier.
85    ///
86    /// Above everything below it, since what an ordered access becomes here is a plain one and
87    /// every pass below is written about a plain one by name. It is also why this is above the
88    /// retries rather than below: the head of the loop they build reads with an ordered load.
89    Orderings,
90    /// An arithmetic operation that also says whether it overflowed, as the arithmetic and the test.
91    ///
92    /// Above the splitting rather than below it, because an overflow check is the one instruction
93    /// whose result is two things and the splitting has no answer for that, while the arithmetic it
94    /// becomes here is adds, multiplies and comparisons the splitting knows already. Nothing is
95    /// lost by running it this early: the widths it is written for are the widths the machine has,
96    /// so a check at any other width is refused by name either way round.
97    Overflows,
98    /// Anything at all at the half float format, as the work at a wider one.
99    ///
100    /// Above the two that rewrite an integer and above the quad, because what it leaves behind is
101    /// a conversion at a wider format and a call, and each of those three is written about one of
102    /// those. A `__int128` becoming a `_Float16` is a conversion to a `double` and a narrowing
103    /// after it once this has run, and the conversion is then the splitting's work in the ordinary
104    /// way rather than a shape it has never seen. A `_Float128` becoming one is a call this writes
105    /// and the quad step never sees, which is what keeps the narrowing a single rounding.
106    HalfFloats,
107    /// An integer wider than a register, as the two halves of one.
108    ///
109    /// Ahead of the width legalisation and not part of it, because the two go in opposite
110    /// directions: an integer of forty bits becomes one of sixty four down there and one of a
111    /// hundred and twenty eight becomes two of sixty four here. Doing this first means a function
112    /// holding both is one the step below still works on.
113    Halves,
114    /// An integer at a width the machine does not have, as the width it is held in.
115    ///
116    /// Before everything after it, because every pass after it is written about widths the machine
117    /// has and an integer of forty bits is not one of them.
118    Widths,
119    /// A byte reversal, as the halving run of swaps it is.
120    Bytes,
121    /// A leading zero, trailing zero or set bit count, as the arithmetic that answers it.
122    Counts,
123    /// Anything at all at the quad float format, as a call to the routine for it.
124    ///
125    /// Above the float rewriting rather than part of it, because the two are written about
126    /// different machines: every rewrite down there ends at an instruction this machine has, and
127    /// every operation up here ends at a call because this machine has no instruction at the format
128    /// at all. Running first means the step below never sees a quad.
129    Quads,
130    /// A float constant, a negation and the conversions, as the integer work spec 10.2 asks for.
131    Floats,
132    /// A `memcpy`, a `memset` or a `memmove`, as the moves it is or as the call it is too big for.
133    Bulk,
134    /// The size of a stack allocation, rounded up to what the stack pointer has to stay on.
135    ///
136    /// The one step here that takes nothing out. It rewrites an operand of the instruction and
137    /// leaves the instruction where it is, which is why [`Step::opcodes`] answers with nothing for
138    /// it.
139    Rounds,
140    /// A variable argument list, as spec 10.7's split describes.
141    Varargs,
142}
143
144impl Step {
145    /// The group, in the order it runs, which is the membership section 36.1 asks to see.
146    pub const GROUP: &'static [Self] = &[
147        Self::Switches,
148        Self::Retries,
149        Self::Orderings,
150        Self::Overflows,
151        Self::HalfFloats,
152        Self::Halves,
153        Self::Widths,
154        Self::Bytes,
155        Self::Counts,
156        Self::Quads,
157        Self::Floats,
158        Self::Bulk,
159        Self::Rounds,
160        Self::Varargs,
161    ];
162
163    /// What it is called in a dump.
164    #[must_use]
165    pub const fn name(self) -> &'static str {
166        match self {
167            Self::Switches => "switches",
168            Self::Retries => "retries",
169            Self::Orderings => "orderings",
170            Self::Overflows => "overflows",
171            Self::HalfFloats => "half-floats",
172            Self::Halves => "halves",
173            Self::Widths => "widths",
174            Self::Bytes => "bytes",
175            Self::Counts => "counts",
176            Self::Quads => "quads",
177            Self::Floats => "floats",
178            Self::Bulk => "bulk",
179            Self::Rounds => "rounds",
180            Self::Varargs => "varargs",
181        }
182    }
183
184    /// The construct it is the answer to, in the words section 36.1 uses for it.
185    #[must_use]
186    pub const fn construct(self) -> &'static str {
187        match self {
188            Self::Switches => "a switch",
189            Self::Retries => "a read modify write with no instruction behind it",
190            Self::Orderings => "an ordered load or store",
191            Self::Overflows => "arithmetic that reports whether it overflowed",
192            Self::HalfFloats => "the half float format",
193            Self::Halves => "an integer wider than a register",
194            Self::Widths => "an integer at a width the machine does not have",
195            Self::Bytes => "a byte reversal",
196            Self::Counts => "a bit count",
197            Self::Quads => "the quad float format",
198            Self::Floats => "a float constant, a negation or a conversion",
199            Self::Bulk => "a bulk copy or fill",
200            Self::Rounds => "a stack allocation whose size is not a multiple of the alignment",
201            Self::Varargs => "a variable argument list",
202        }
203    }
204
205    /// The opcodes it is the answer to, which is what [`Did::found`] and [`Did::left`] count.
206    ///
207    /// Not a promise that none of them survive. Several of these steps have a case they leave where
208    /// it stands, either because the machine turns out to have the construct after all or because
209    /// this is a refusal being handed to the selector to name, and both of those show up here as a
210    /// count that did not reach zero. What the pair of numbers is for is telling somebody reading a
211    /// dump which of those happened.
212    ///
213    /// Empty for [`Step::Rounds`], which rewrites an operand rather than taking an instruction out,
214    /// and empty for the four that work by type rather than by opcode: an integer of forty bits,
215    /// one of a hundred and twenty eight, a quad float and a half float are all spelled with the
216    /// same opcodes as anything else, and what makes them the construct is the type on the values.
217    #[must_use]
218    pub const fn opcodes(self) -> &'static [Opcode] {
219        match self {
220            Self::Switches => &[Opcode::Switch],
221            Self::Retries => &[],
222            Self::Orderings => &[Opcode::AtomicLoad, Opcode::AtomicStore],
223            Self::Overflows => &[
224                Opcode::UAddOverflow,
225                Opcode::SAddOverflow,
226                Opcode::USubOverflow,
227                Opcode::SSubOverflow,
228                Opcode::UMulOverflow,
229                Opcode::SMulOverflow,
230            ],
231            Self::HalfFloats | Self::Halves | Self::Widths | Self::Rounds => &[],
232            Self::Bytes => &[Opcode::Bswap],
233            Self::Counts => &[Opcode::Ctlz, Opcode::Cttz, Opcode::Ctpop],
234            Self::Quads => &[],
235            Self::Floats => &[
236                Opcode::FConst,
237                Opcode::FNeg,
238                Opcode::SIToFP,
239                Opcode::UIToFP,
240                Opcode::FPToSI,
241                Opcode::FPToUI,
242            ],
243            Self::Bulk => &[Opcode::Memcpy, Opcode::Memset, Opcode::Memmove],
244            Self::Varargs => &[Opcode::VaArg, Opcode::VaObject, Opcode::VaCopy, Opcode::VaEnd],
245        }
246    }
247
248    /// Whether this step works on the whole function at once and says whether it rewrote it.
249    ///
250    /// Two of them do. Both retype every value of a width, so either the whole function can be
251    /// rewritten or none of it can, and they answer with a boolean for that reason. A `false` from
252    /// one covers two different things, a function with nothing at that width in it and a function
253    /// holding something the step did not understand, and neither is an error: the second leaves
254    /// the selector to refuse by naming the construct it had no rule for.
255    ///
256    /// Everything else here works instruction by instruction and has nothing to say at that scale,
257    /// which is why [`Did::untouched`] is only ever true for these two.
258    #[must_use]
259    pub const fn whole_function(self) -> bool {
260        matches!(self, Self::Halves | Self::Widths)
261    }
262
263    /// Runs this one step, answering whether it rewrote the function.
264    ///
265    /// Only the two that [`Step::whole_function`] names ever answer `false`, because they are the
266    /// only two that know. The rest work instruction by instruction and are not asked.
267    ///
268    /// `switching` is the level's goal and the shape `-Zswitch=` forced, and what the `switch`
269    /// lowering says it did goes into `switched`.
270    fn run(
271        self,
272        func: &mut Func,
273        names: &mut Interner,
274        conv: &CallRegs,
275        switching: (Goal, Option<Force>),
276        switched: &mut Vec<Lowered>,
277    ) -> bool {
278        let (goal, force) = switching;
279        match self {
280            Self::Switches => switched.extend(switch::lowered(func, goal, force)),
281            Self::Retries => retry::loops(func),
282            Self::Orderings => expand::orderings(func, conv.word, conv.total_store_order),
283            Self::Overflows => expand::overflows(func),
284            Self::HalfFloats => half::calls(func, names, conv.abi),
285            Self::Halves => return wide::halves(func, names, conv),
286            Self::Widths => return widths::integers(func),
287            Self::Bytes => expand::bytes(func),
288            Self::Counts => expand::counts(func),
289            Self::Quads => quad::calls(func, names, conv.abi),
290            Self::Floats => expand::floats(func),
291            Self::Bulk => expand::bulk(func, names, conv.word),
292            Self::Rounds => expand::rounds(func, conv.stack_align),
293            Self::Varargs => varargs::lists(func, conv),
294        }
295        true
296    }
297}
298
299/// What one step did to one function.
300#[derive(Debug, Clone, Copy, PartialEq, Eq)]
301pub struct Did {
302    /// Which step it was.
303    pub step: Step,
304    /// How many instructions of the kind it answers for were there when it started.
305    pub found: usize,
306    /// How many were still there when it finished, which is not always zero. See [`Step::opcodes`].
307    pub left: usize,
308    /// How many instructions the function had before it ran.
309    pub before: usize,
310    /// How many it had after.
311    pub after: usize,
312    /// Whether it said it left the function exactly as it was, which only the two that
313    /// [`Step::whole_function`] names ever say.
314    pub untouched: bool,
315}
316
317/// What the whole group did to one function.
318#[derive(Debug, Default, Clone, PartialEq, Eq)]
319pub struct Ran {
320    /// One entry per step, in the order they ran, including the ones that found nothing.
321    ///
322    /// Including them on purpose. A dump that lists only the steps that fired is a dump that cannot
323    /// tell a step that found nothing from a step somebody forgot to add to the group.
324    pub did: Vec<Did>,
325    /// What each `switch` became, which is filled in whether or not the steps are counted, since
326    /// `-fopt-info` reads it and costs nothing when there is no `switch`.
327    pub switches: Vec<Lowered>,
328}
329
330impl Ran {
331    /// What one step of the group did, which every step has an entry for.
332    ///
333    /// # Panics
334    ///
335    /// Panics if this record did not come from [`group`], since that is the only way a step of
336    /// [`Step::GROUP`] can be missing from it.
337    #[must_use]
338    pub fn of(&self, step: Step) -> Did {
339        *self.did.iter().find(|did| did.step == step).expect("every step has an entry")
340    }
341
342    /// The dump, one line per step.
343    ///
344    /// Plain text with the name first, because the thing anybody reads this for is which step
345    /// changed the function, and a format that has to be parsed to answer that is the wrong format
346    /// for a debugging aid. `-Zlowering=` writes it.
347    #[must_use]
348    pub fn render(&self, func: &str) -> String {
349        let mut out = format!("lowering {func}\n");
350        for did in &self.did {
351            let _ = write!(
352                out,
353                "  {:<10} {:>4} -> {:>4} insts",
354                did.step.name(),
355                did.before,
356                did.after
357            );
358            // Said the rare way round on purpose. The two whole function steps answer `false` for
359            // every function with nothing at their width in it, which is nearly all of them, so a
360            // line per function saying so would bury the one that matters.
361            if did.step.whole_function() && !did.untouched {
362                let _ = write!(out, ", retyped every value at that width");
363            }
364            if did.found > 0 {
365                let _ = write!(out, ", found {}, left {}", did.found, did.left);
366            }
367            let _ = writeln!(out, " ({})", did.step.construct());
368        }
369        out
370    }
371}
372
373/// What the group did to every function a run lowered, in the order they came through.
374///
375/// The same shape [`crate::pressure::Pressure`] has and for the same reason: a caller collects one
376/// of these over a whole command line and asks for the listing once at the end.
377#[derive(Debug, Default, Clone, PartialEq, Eq)]
378pub struct Lowerings {
379    /// One per function, in the order they were lowered.
380    rows: Vec<(String, Ran)>,
381    /// Whether anything is going to read this, which is whether `-Zlowering` was given.
382    wanted: bool,
383    /// What each `switch` became, by function, which is recorded whether `-Zlowering` was given
384    /// or not because `-fopt-info` is what reads it.
385    switches: Vec<(String, Lowered)>,
386}
387
388impl Lowerings {
389    /// Nothing recorded, and nothing counted either.
390    #[must_use]
391    pub fn new() -> Self {
392        Self::default()
393    }
394
395    /// The same, told whether to count, which is what `-Zlowering=FILE` decides.
396    #[must_use]
397    pub fn asked(wanted: bool) -> Self {
398        Self { wanted, ..Self::default() }
399    }
400
401    /// Whether the counting is worth doing, which is what [`group`] is passed.
402    ///
403    /// This is a question and not an assumption for a reason that showed up as soon as the numbers
404    /// were measured on something large. Counting is a walk of the function per step, and a
405    /// function's instructions are a linked list, so on the SQLite amalgamation the walks cost
406    /// about two seconds on top of nine, which is more than several of the passes they are
407    /// measuring. A debugging aid nobody asked for should cost nothing, so a run without the flag
408    /// runs the group and records no numbers at all.
409    #[must_use]
410    pub fn wanted(&self) -> bool {
411        self.wanted
412    }
413
414    /// Writes down what the group did to one function.
415    pub fn record(&mut self, name: &str, ran: Ran) {
416        self.rows.push((name.to_owned(), ran));
417    }
418
419    /// Writes down what the `switch` statements of one function became.
420    pub fn switched(&mut self, name: &str, lowered: &[Lowered]) {
421        self.switches.extend(lowered.iter().map(|one| (name.to_owned(), *one)));
422    }
423
424    /// Takes in everything another one recorded, which is how one file's answer joins a run's.
425    pub fn merge(&mut self, other: &Self) {
426        self.rows.extend(other.rows.iter().cloned());
427        self.switches.extend(other.switches.iter().cloned());
428    }
429
430    /// The `-fopt-info` lines for what every `switch` became, in the optimizer's format, with
431    /// `file` the name the optimizer's lines use.
432    #[must_use]
433    pub fn remarks(&self, file: &str) -> String {
434        let mut out = String::new();
435        for (name, lowered) in &self.switches {
436            let said = lowered.describe();
437            let _ = writeln!(out, "{file}: {name}: optimized: {said} (1) [switch-lowering]");
438        }
439        out
440    }
441
442    /// How many functions went through the group.
443    #[must_use]
444    pub fn functions(&self) -> usize {
445        self.rows.len()
446    }
447
448    /// What `-Zlowering=FILE` writes.
449    ///
450    /// A comment holding the count and then one block per function. Whoever reads one of these is
451    /// looking for which step changed a function they are surprised by, so the file is the same
452    /// text in the same order as the group ran, and every step is there whether it did anything or
453    /// not. A dump listing only the steps that fired could not tell a step that found nothing from
454    /// a step somebody forgot to put in the group, which is half of what this is read for.
455    #[must_use]
456    pub fn listing(&self) -> String {
457        let mut out = format!("# rucc lowering: {} functions\n", self.rows.len());
458        for (name, ran) in &self.rows {
459            out.push_str(&ran.render(name));
460        }
461        out
462    }
463}
464
465/// Runs the whole group over one function, in the order [`Step::GROUP`] gives.
466///
467/// This is the entry point section 36.1 asks for. Every caller wanting a function lowered calls
468/// this and nothing else, so adding a lowering is adding it to [`Step::GROUP`] rather than to
469/// whichever line of `crate::pipeline` looked convenient.
470///
471/// `counting` is whether to work out what each step found and left, which is what
472/// [`Lowerings::wanted`] answers and which costs what it says there. The steps run either way and
473/// the function comes out the same; what a `false` gives back is an empty [`Ran`].
474///
475/// `goal` is whether the level asked for small code, which the `switch` lowering reads to decide
476/// when a table is worth writing, and `force` is the shape `-Zswitch=` forced on it, if any.
477pub fn group(
478    func: &mut Func,
479    names: &mut Interner,
480    conv: &CallRegs,
481    goal: Goal,
482    force: Option<Force>,
483    counting: bool,
484) -> Ran {
485    let mut ran = Ran::default();
486    for &step in Step::GROUP {
487        if !counting {
488            step.run(func, names, conv, (goal, force), &mut ran.switches);
489            continue;
490        }
491        let (before, found) = tally(func, step);
492        let did = step.run(func, names, conv, (goal, force), &mut ran.switches);
493        let (after, left) = tally(func, step);
494        ran.did.push(Did { step, found, left, before, after, untouched: !did });
495    }
496    ran
497}
498
499/// How many instructions the function has, and how many of them are the kind this step answers for.
500///
501/// Both in one walk rather than one walk each, since the walk is the expensive part.
502fn tally(func: &Func, step: Step) -> (usize, usize) {
503    let wanted = step.opcodes();
504    let (mut all, mut mine) = (0, 0);
505    for block in func.blocks() {
506        for inst in func.insts(block) {
507            all += 1;
508            if wanted.contains(&func[inst].opcode) {
509                mine += 1;
510            }
511        }
512    }
513    (all, mine)
514}
515
516#[cfg(test)]
517mod tests {
518    use rucc_base::Interner;
519    use rucc_ir::{
520        Builder, Extra, Flags, Float, Func, InstData, MemInfo, MemOrder, Opcode, Restrict,
521        Signature, Type, Value,
522    };
523    use rucc_target::x86_64;
524
525    use super::{Goal, Lowerings, Ran, Step, group};
526
527    /// A function with a body somebody else writes, which is the same helper the passes being
528    /// grouped are each tested with.
529    fn one(
530        params: &[Type],
531        returns: &[Type],
532        body: impl FnOnce(&mut Builder<'_>, &[Value]),
533    ) -> (Interner, Func) {
534        let mut names = Interner::new();
535        let mut func = Func::new(
536            names.intern("f"),
537            Signature::new().with_params(params).with_returns(returns),
538        );
539        let entry = func.create_block();
540        let args: Vec<_> = params.iter().map(|&ty| func.append_param(entry, ty)).collect();
541        let mut build = Builder::new(&mut func, entry);
542        body(&mut build, &args);
543        (names, func)
544    }
545
546    fn run(func: &mut Func, names: &mut Interner) -> Ran {
547        group(func, names, &x86_64::SYSV, Goal::Speed, None, true)
548    }
549
550    fn i32() -> Type {
551        Type::int(32)
552    }
553
554    #[test]
555    fn the_group_is_the_passes_the_pipeline_used_to_call_one_line_at_a_time() {
556        // The list rather than the length, because a list checked only for its length is a list
557        // anybody can reorder without noticing, and the order is half of what this file is for.
558        let names: Vec<&str> = Step::GROUP.iter().map(|step| step.name()).collect();
559        assert_eq!(
560            names,
561            [
562                "switches",
563                "retries",
564                "orderings",
565                "overflows",
566                // Ahead of the integer splitting, because the calls it writes take and give back
567                // whole words that the splitting then has nothing left to say about.
568                "half-floats",
569                "halves",
570                "widths",
571                "bytes",
572                "counts",
573                "quads",
574                "floats",
575                "bulk",
576                "rounds",
577                "varargs",
578            ]
579        );
580    }
581
582    #[test]
583    fn every_step_says_what_it_is_for_and_no_two_say_the_same_thing() {
584        let mut names: Vec<&str> = Step::GROUP.iter().map(|step| step.name()).collect();
585        let mut constructs: Vec<&str> = Step::GROUP.iter().map(|step| step.construct()).collect();
586        assert!(constructs.iter().all(|construct| !construct.is_empty()));
587        for list in [&mut names, &mut constructs] {
588            let was = list.len();
589            list.sort_unstable();
590            list.dedup();
591            assert_eq!(list.len(), was, "two steps say the same thing");
592        }
593    }
594
595    #[test]
596    fn a_function_with_nothing_in_it_leaves_every_step_with_nothing_to_say() {
597        let (mut names, mut func) = one(&[], &[], |build, _| {
598            build.ret(&[]);
599        });
600        let ran = run(&mut func, &mut names);
601        assert_eq!(ran.did.len(), Step::GROUP.len());
602        assert!(ran.did.iter().all(|did| did.found == 0 && did.before == did.after));
603    }
604
605    #[test]
606    fn nothing_in_the_group_is_left_out_of_the_record() {
607        let (mut names, mut func) = one(&[], &[], |build, _| {
608            build.ret(&[]);
609        });
610        let ran = run(&mut func, &mut names);
611        let ordered: Vec<Step> = ran.did.iter().map(|did| did.step).collect();
612        assert_eq!(ordered, Step::GROUP);
613    }
614
615    /// `unsigned b(unsigned x) { return __builtin_bswap32(x); }`, which is one of the constructs
616    /// in the list and therefore one the group owes an answer for.
617    #[test]
618    fn a_byte_reversal_does_not_survive_the_group() {
619        let (mut names, mut func) = one(&[i32()], &[i32()], |build, args| {
620            let swapped = build.unary(Opcode::Bswap, args[0], i32());
621            build.ret(&[swapped]);
622        });
623        let ran = run(&mut func, &mut names);
624        let did = ran.of(Step::Bytes);
625        assert_eq!(did.found, 1);
626        assert_eq!(did.left, 0);
627        assert!(did.after > did.before, "one instruction became several");
628    }
629
630    /// `int c(unsigned x) { return __builtin_popcount(x); }`.
631    #[test]
632    fn a_bit_count_does_not_survive_the_group() {
633        let (mut names, mut func) = one(&[i32()], &[i32()], |build, args| {
634            let ones = build.unary(Opcode::Ctpop, args[0], i32());
635            build.ret(&[ones]);
636        });
637        let ran = run(&mut func, &mut names);
638        assert_eq!(ran.of(Step::Counts).found, 1);
639        assert_eq!(ran.of(Step::Counts).left, 0);
640    }
641
642    /// `double n(double x) { return -x; }`, which is a float rather than an integer and so reaches
643    /// a different member of the group.
644    #[test]
645    fn a_float_negation_does_not_survive_the_group() {
646        let f64 = Type::float(Float::F64);
647        let (mut names, mut func) = one(&[f64], &[f64], |build, args| {
648            let negated = build.unary(Opcode::FNeg, args[0], f64);
649            build.ret(&[negated]);
650        });
651        let ran = run(&mut func, &mut names);
652        assert_eq!(ran.of(Step::Floats).found, 1);
653        assert_eq!(ran.of(Step::Floats).left, 0);
654    }
655
656    /// `long a(long *p) { return __atomic_load_n(p, __ATOMIC_SEQ_CST); }`, which on this machine is
657    /// the same `mov` an ordinary read is, and which nothing below this step in the group knows the
658    /// name of.
659    #[test]
660    fn an_ordered_load_does_not_survive_the_group() {
661        let i64 = Type::int(64);
662        let (mut names, mut func) = one(&[Type::PTR], &[i64], |build, args| {
663            let info = MemInfo {
664                size: 8,
665                align: 8,
666                order: MemOrder::SeqCst,
667                tbaa: None,
668                owns: 0,
669                restrict: Restrict::NONE,
670            };
671            let value = build.atomic_load(i64, args[0], info, Flags::NONE);
672            build.ret(&[value]);
673        });
674        let ran = run(&mut func, &mut names);
675        assert_eq!(ran.of(Step::Orderings).found, 1);
676        assert_eq!(ran.of(Step::Orderings).left, 0);
677    }
678
679    /// Every construct with an opcode behind it, checked the same way in one loop, so that a
680    /// thirteenth member added to the group without an answer is a failure here rather than
681    /// something noticed later by the selector refusing it by name.
682    #[test]
683    fn nothing_the_group_names_an_opcode_for_is_still_there_afterwards() {
684        for step in Step::GROUP {
685            let Some((mut names, mut func)) = holding(*step) else {
686                continue;
687            };
688            let ran = run(&mut func, &mut names);
689            let did = ran.of(*step);
690            assert_eq!(did.found, 1, "{}: the construct was not built", step.name());
691            assert_eq!(did.left, 0, "{}: the construct survived the group", step.name());
692        }
693    }
694
695    /// One small function holding exactly one of the construct that step answers for, for the
696    /// steps whose construct is an opcode. The rest answer `None`: three of them are about a type
697    /// rather than an opcode, one rewrites an operand and takes nothing out, and the variable
698    /// argument list needs a whole calling convention around it to be worth building here.
699    fn holding(step: Step) -> Option<(Interner, Func)> {
700        let i32 = i32();
701        let i64 = Type::int(64);
702        let f64 = Type::float(Float::F64);
703        Some(match step {
704            Step::Bytes => one(&[i32], &[i32], |build, args| {
705                let swapped = build.unary(Opcode::Bswap, args[0], i32);
706                build.ret(&[swapped]);
707            }),
708            Step::Counts => one(&[i32], &[i32], |build, args| {
709                let ones = build.unary(Opcode::Ctlz, args[0], i32);
710                build.ret(&[ones]);
711            }),
712            Step::Floats => one(&[], &[f64], |build, _| {
713                let k = build.fconst(f64, 0x3ff8_0000_0000_0000);
714                build.ret(&[k]);
715            }),
716            Step::Orderings => one(&[Type::PTR], &[i64], |build, args| {
717                let info = MemInfo {
718                    size: 8,
719                    align: 8,
720                    order: MemOrder::SeqCst,
721                    tbaa: None,
722                    owns: 0,
723                    restrict: Restrict::NONE,
724                };
725                let value = build.atomic_load(i64, args[0], info, Flags::NONE);
726                build.ret(&[value]);
727            }),
728            Step::Overflows => one(&[i32, i32], &[i32], |build, args| {
729                let (sum, _) = build.checked(Opcode::UAddOverflow, args[0], args[1]);
730                build.ret(&[sum]);
731            }),
732            // `struct point { int x, y; } a, b; a = b;`, where the size and the alignment are on
733            // the access rather than in an operand, which is the shape the front end writes.
734            Step::Bulk => one(&[Type::PTR, Type::PTR], &[], |build, args| {
735                let info = MemInfo {
736                    size: 16,
737                    align: 8,
738                    order: MemOrder::NotAtomic,
739                    tbaa: None,
740                    owns: 0,
741                    restrict: Restrict::NONE,
742                };
743                let mem = build.func().add_mem(info);
744                let operands = build.func().push_values(&[args[0], args[1]]);
745                build.inst(
746                    InstData {
747                        args: operands,
748                        extra: Extra::Mem(mem),
749                        ..InstData::new(Opcode::Memcpy)
750                    },
751                    &[],
752                );
753                build.ret(&[]);
754            }),
755            _ => return None,
756        })
757    }
758
759    /// The cheap path, which is what a build that did not ask for the dump takes. The steps still
760    /// run and the function still comes out lowered, and what is skipped is a walk of the function
761    /// per step, which is not free on anything the size of a real translation unit.
762    #[test]
763    fn a_run_that_did_not_ask_for_the_dump_still_lowers_and_counts_nothing() {
764        let build = |build: &mut Builder<'_>, args: &[Value]| {
765            let swapped = build.unary(Opcode::Bswap, args[0], i32());
766            build.ret(&[swapped]);
767        };
768        let (mut names, mut func) = one(&[i32()], &[i32()], build);
769        let quiet = group(&mut func, &mut names, &x86_64::SYSV, Goal::Speed, None, false);
770        assert!(quiet.did.is_empty(), "nothing was counted");
771        assert_eq!(super::tally(&func, Step::Bytes), (super::tally(&func, Step::Bytes).0, 0));
772
773        // The same function through the counting path comes out the same size, so what the flag
774        // changes is what was written down and not what was done.
775        let (mut names, mut func) = one(&[i32()], &[i32()], build);
776        let loud = group(&mut func, &mut names, &x86_64::SYSV, Goal::Speed, None, true);
777        assert_eq!(loud.of(Step::Bytes).left, 0);
778        assert_eq!(
779            loud.did.last().expect("thirteen of them").after,
780            super::tally(&func, Step::Bytes).0
781        );
782    }
783
784    #[test]
785    fn nothing_is_recorded_for_a_run_that_did_not_ask() {
786        let mut quiet = Lowerings::new();
787        assert!(!quiet.wanted());
788        quiet.record("f", Ran::default());
789        assert_eq!(quiet.functions(), 1, "recording still works if somebody does it anyway");
790
791        let asked = Lowerings::asked(true);
792        assert!(asked.wanted());
793        assert_eq!(asked.listing(), "# rucc lowering: 0 functions\n");
794    }
795
796    #[test]
797    fn the_dump_names_every_step_whether_it_fired_or_not() {
798        // A dump listing only the steps that fired cannot tell a step that found nothing from a
799        // step somebody forgot to put in the group, which is the one thing it is read for.
800        let (mut names, mut func) = one(&[i32()], &[i32()], |build, args| {
801            let swapped = build.unary(Opcode::Bswap, args[0], i32());
802            build.ret(&[swapped]);
803        });
804        let ran = run(&mut func, &mut names);
805        let text = ran.render("f");
806        assert!(text.starts_with("lowering f\n"), "{text}");
807        for step in Step::GROUP {
808            assert!(text.contains(step.name()), "{} is missing from {text}", step.name());
809        }
810        assert!(text.contains("found 1, left 0"), "{text}");
811        assert_eq!(text.lines().count(), Step::GROUP.len() + 1);
812    }
813
814    #[test]
815    fn only_the_two_steps_that_retype_a_whole_function_ever_say_they_touched_nothing() {
816        // The rest work instruction by instruction and are never asked, so a `true` from one of
817        // them is not evidence of anything and the dump does not print it.
818        assert_eq!(
819            Step::GROUP.iter().filter(|step| step.whole_function()).copied().collect::<Vec<_>>(),
820            [Step::Halves, Step::Widths]
821        );
822        for step in Step::GROUP {
823            if step.whole_function() {
824                // Both of them are about the width on a value rather than about an opcode, so
825                // there is nothing for `found` and `left` to count.
826                assert!(step.opcodes().is_empty(), "{} counts opcodes", step.name());
827            }
828        }
829    }
830
831    #[test]
832    fn an_instruction_nothing_in_the_group_is_about_is_left_exactly_where_it_was() {
833        let (mut names, mut func) = one(&[i32()], &[i32()], |build, args| {
834            let seven = build.iconst(i32(), 7);
835            let sum = build.binary(Opcode::Add, args[0], seven, Flags::NONE);
836            build.ret(&[sum]);
837        });
838        let before = super::tally(&func, Step::Rounds).0;
839        let ran = run(&mut func, &mut names);
840        assert_eq!(super::tally(&func, Step::Rounds).0, before);
841        assert!(ran.did.iter().all(|did| did.found == 0));
842    }
843}