Skip to main content

rucc_opt/
pipeline.rs

1//! The pipelines, one per optimization level, and the manager that runs one.
2//!
3//! Section 9.1 of `spec/09-optimizer.md` says the pipelines are written out rather than assembled
4//! from flags, and gives the reason: the prior art ran the same pipeline at every level and named
5//! that as a limitation. A level here is a list of pass names, and the list is the definition of
6//! the level rather than something that emerges from which flags happen to be set.
7//!
8//! Section 9.10 says the manager is deliberately boring. There is no adaptive ordering and no
9//! scheduling heuristic, because document 03's determinism rule needs the same input to produce
10//! the same output on every host and predictability is worth more than the last percent.
11//!
12//! What the manager does beyond running the list is the four things that make a pass debuggable:
13//! it counts each pass's transformations against its fuel, it collects what each pass said it did
14//! and did not do, it dumps the IR around whichever passes were asked for, and it verifies any
15//! function a pass changed.
16//!
17//! That last one is section 41.4 of `spec/optimizer/41-correctness.md`, which reads GCC's
18//! `execute_function_todo` and takes six things from it. Three of them are already true here by
19//! construction and are worth naming so that nobody looks for them. GCC verifies what the IR
20//! currently is, by consulting `curr_properties`, because its IR passes through GENERIC, GIMPLE
21//! with and without a CFG, GIMPLE in SSA, and RTL. rucc has one IR, it is in SSA from the moment
22//! the lowering walk builds it, and it always has a CFG, so the applicable set never varies and a
23//! bitmask saying so would have nothing to say. GCC guards the verifiers with `!seen_error()`,
24//! because after a user error the IR is legitimately malformed and an internal error raised over
25//! it hides the real diagnostic. Here the optimizer is not reached at all after a parse, check or
26//! lowering error, which is the same guard placed one level up where it cannot be forgotten. And
27//! GCC asserts that a verifier did not change the dominator state. Here a verifier takes the
28//! module by shared reference, so that is a type error rather than an assertion.
29//!
30//! What is left of the six is the part below: verify what changed, not everything, and say which
31//! function it was.
32
33use std::collections::HashMap;
34use std::fmt::Write as _;
35
36use rucc_base::{Interner, Symbol};
37use rucc_ir::{FuncId, Module, Pic};
38use rucc_session::OptLevel;
39
40use crate::{
41    Analyses, Fuel, Gates, Machine, Pass, Preserved, Stats, extents, heap, nofree, params, pass,
42};
43
44/// The passes that read a summary [`nofree::annotate`], [`extents::annotate`],
45/// [`params::annotate`] or [`heap::annotate`] writes onto the IR.
46///
47/// A list rather than one name because there will be more of them: section 7.5 asks for three more
48/// summary fields and section 7.3's lifetime elimination is the next thing to want this one. A pass
49/// that reads a summary and is not named here reads whatever the last build left, which is nothing,
50/// so the cost of forgetting to add a name is a missed optimization.
51///
52/// The five after the first are `crate::discharge`'s measurement runs, and leaving them out was a
53/// missed optimization of exactly that kind: a run measuring what an object says about itself, with
54/// no table saying how big any global is, answers that objects say nothing, and the number looks
55/// like a result rather than like a list with a name missing from it.
56const READS_SUMMARIES: &[&str] = &[
57    "discharge",
58    "discharge-objects",
59    "discharge-dominance",
60    "discharge-summaries",
61    "discharge-narrow",
62    "discharge-every",
63];
64
65/// `-O0`. One pass, and it is not an optimization. Section 9.1 gives this level SSA
66/// construction, which the lowering walk in `spec/08-ir.md` already does, and mem2reg for the
67/// allocas that are left, which is the next pass to be written.
68///
69/// `simplify-cfg` is here because a branch on a condition that is a constant is not a missed
70/// optimization, it is a call to a function the program never calls, and a program that calls a
71/// function it never calls is one that does not link. That is issue 359, gcc removes the code at
72/// every level including this one, and a `-O0` that emitted it would be a `-O0` some correct
73/// programs cannot be built at. Nothing else runs, and no analysis beyond the graph the pass
74/// reads reachability out of is computed.
75const O0: &[&str] = &["simplify-cfg"];
76
77/// `-O1`. Section 9.1 asks for one e-graph round, conservative inlining, simplify-CFG, SROA,
78/// GVN, DCE, LICM and the loop canonicalizations. Folding, control flow simplification and dead
79/// code elimination are the part of that which exists, with the peephole among them. They run in
80/// that order because folding and the peephole are what make most of the dead code there is to
81/// eliminate, because a constant a fold produced is a branch condition the control flow pass can
82/// then read, and because the comparison that branch was on is dead once it has.
83///
84/// The peephole runs on both sides of `narrow`, which is the one place in this list where a pass
85/// is named twice, so the reason is worth stating. The rewrite table is written at a width, and
86/// the widths below `int` are unreachable from C source: the integer promotions mean an addition
87/// of two `char` values arrives here as an `add.i32`, so a rule about `add.i8` matches nothing
88/// that a front end can produce. `narrow` is what puts the width back, and it is therefore the
89/// only producer the narrow half of the table has. Running the peephole only before it left
90/// sixty nine of the first hundred and twenty five rules unable to fire on any program, which is
91/// issue 505 and is what the corpus measured. Running it only after it would give up the smaller
92/// trees the peephole hands `narrow`, since a subtree `narrow` redoes has to have one reader and
93/// an identity left standing is a second one. Both sides costs one more walk over each function
94/// and is what the pass is for.
95///
96/// `phiopt` comes after `thread` and the order between them is not arbitrary. Both look at a
97/// diamond whose arms carry a value to a join. Where the join then branches on that value,
98/// threading removes a branch and costs nothing, and if-conversion would have turned the same
99/// shape into a `select` the join branches on instead, which is strictly worse. Threading first
100/// leaves if-conversion the diamonds whose value is used rather than tested, which are the ones it
101/// is for.
102///
103/// `prune` is between `phiopt` and `simplify-cfg` and both sides of that are load bearing. It reads
104/// document 10's ranges off the graph to find a branch that can only go one way and a switch case
105/// nothing can reach, so it has to run after the two passes that change the graph most. What it
106/// leaves is a jump where a branch was and a block nothing reaches, and `simplify-cfg` is the pass
107/// that takes those out, so it has to run before it rather than after.
108///
109/// `canon` is where document 26's loop pipeline opens, so it goes after the value level passes and
110/// before the cleanup. It gives every loop a preheader, one latch, exits of its own and loop closed
111/// form, which is what lets the loop passes that follow it write `insert at the end of the
112/// preheader` rather than each making one. On its own it generates nothing: the blocks it adds are
113/// empty and the parameters it adds have one argument each, and `simplify-cfg` runs straight after
114/// it and takes both back out to a fixed point. That is section 26.7's arrangement, and it is why
115/// the position matters more than the pass does until the loop passes land on top of it.
116///
117/// `header-copy` is section 26.7's third step and `canon` runs again after it, which is the same
118/// section's instruction to re-canonicalize the loops it changed. It has to: what the copy leaves
119/// is a loop entered from a block that branches two ways, and a block that branches two ways is not
120/// a preheader. Nothing between the two needs the properties, so the second run is bookkeeping
121/// against the loop passes that come later rather than something this level's output depends on,
122/// and `simplify-cfg` after it takes out the blocks and parameters both runs added that nothing
123/// used.
124///
125/// `licm` comes after the copy and the canonicalization behind it, and section 27.1 says why it has
126/// to. What it may move in front of a loop depends on what runs on every entry to the loop, and
127/// after that pair that is the whole body rather than the header alone. Running it before the
128/// copy would leave it the header, which is most of the pass's value gone. It is also the reason
129/// the copy exists, so the two are one arrangement read from either end.
130///
131/// It is in the three speed levels and not in `-Os` or `-Oz`. Moving a computation out of a loop
132/// does not remove one, so there are no bytes in it for a level whose cost model is size, and the
133/// one thing it can cost is a spill inside the loop, which is bytes. That trade is worth making for
134/// time and there is nothing on the other side of it for space.
135///
136/// `unroll` runs after `licm` and only at the two speed levels. After, because what it does is copy
137/// the body, and a computation licm has already moved in front of the loop is one the copies do not
138/// each get their own of. It needs the same shape licm does and for the same reason, a loop that
139/// tests at the bottom with a preheader in front of it, so it sits at the end of the same run of
140/// loop passes rather than anywhere of its own. `simplify-cfg` straight after it is what turns the
141/// chain of copies into one block, since each copy now ends in a jump to the next and a block with
142/// one way in and one way out is a block that goes away.
143///
144/// `number` goes straight after that `simplify-cfg` and immediately before `load-forward`, and the
145/// two are one arrangement rather than two passes that happen to be adjacent. On its own it removes
146/// an instruction here and there, because the arithmetic a person writes is not usually written
147/// twice. What it is really for is the arithmetic the front end writes underneath: a subscript
148/// lowered twice is the same multiply and add twice, and giving the two one name is what turns a
149/// store and a load that `load-forward` was refusing into a store and a load of the same address.
150/// Running it the other way round would leave the pass after it nothing it did not already have.
151///
152/// `load-forward` goes next, and the position is the whole of what
153/// the pass is worth. It is the block local half of document 16, so what it can find is bounded by
154/// how much code is in one block, and `simplify-cfg` merging the straight line chains is what makes
155/// the blocks the largest they are ever going to be. At the two speed levels that position is also
156/// just after `unroll`, which is where the case the pass was written for lives: the body
157/// copies now sit in one block, and a copy that stored to an array slot and read it straight back
158/// is a store and a load of the same address with nothing in between.
159///
160/// `fold` runs a second time after it, and it is not there out of habit. What forwarding leaves
161/// behind is a value that arrived as a constant through memory, `grid[i] = 3` read back as a load
162/// that is now the literal three, and nothing else this late in the list would fold the arithmetic
163/// on top of it. The first `fold` ran before any of this existed.
164///
165/// `simplify` runs after that second `fold` for the same reason the second `fold` runs at all.
166/// Folding does not remove an instruction whose answer is a constant somebody still adds, it only
167/// writes the constant down, and an index folded to zero leaves a `ptr_add x, 0` behind. That is
168/// an identity the peephole takes and nothing else in the list is about. The unrolled body is
169/// where they come from: the copy that runs first subscripts the array at zero, so the multiply
170/// that worked its offset out is a multiply by zero, and until now the last thing any level did to
171/// that arithmetic was fold it. The add of zero reached the selector and was written out as an
172/// `addq $0`. Over the corpus at `-O2` the run is worth 3000 bytes across 1830 programs, 224 of
173/// them smaller and 4 larger, with every result unchanged.
174///
175/// `hoist` is the first of the two check passes and it runs where it does because of what is above
176/// it. It needs a loop that tests at the bottom, which is what `header-copy` makes, and it needs a
177/// preheader to put a check in, which is what the `canon` after it puts back. Running it before
178/// `discharge` rather than after is deliberate as well: what it leaves in the preheader is a check
179/// over the whole range the loop sweeps, and that is a fact `discharge` can then use on anything
180/// else in front of the loop that is about the same bytes.
181///
182/// `discharge` is second to last, between `hoist` and `dce`, and both neighbours are the reason. It
183/// reads the dominator tree to find a safety check whose bytes an earlier check already covered, so
184/// it wants the graph after the block merging rather than before, when a straight run of code is
185/// still several blocks and a fact does not reach the check it would cover. What it leaves behind
186/// is the `cap_of` the check it removed was reading, which nothing now reads, so `dce` after it is
187/// what makes the function smaller rather than shorter by one instruction. It is in every level
188/// except `-O0`, which keeps every check on purpose: document 14 measures against a build where
189/// nothing was discharged, and that build is `-O0`.
190const O1: &[&str] = &[
191    "fold",
192    "simplify",
193    "narrow",
194    "simplify",
195    "thread",
196    "phiopt",
197    "prune",
198    "canon",
199    "header-copy",
200    "canon",
201    "licm",
202    "simplify-cfg",
203    "number",
204    "load-forward",
205    "fold",
206    "simplify",
207    "hoist",
208    "discharge",
209    "dce",
210];
211
212/// `-O2`. The level the code quality claim is about. Section 9.1 asks for two e-graph rounds
213/// around the loop pipeline, the full inlining cost model, Memory SSA and the full alias
214/// analysis stack, and then the scalar and machine passes on top.
215///
216/// `short-circuit` is the one pass here that `-O1` does not have, and section 22.5 is where the
217/// level comes from. It folds the two branches of an `a && b` into one, which costs the right
218/// operand's work on the path that was skipping it and buys a branch the machine no longer has to
219/// guess. That is a trade worth making when the aim is speed and the branch is hard to call, and
220/// it is not one to make by default, which is what `-O1` is.
221///
222/// It runs before `thread` and `phiopt` rather than after, and the order is not arbitrary. Both of
223/// those look at edges, and the collapse removes a block and turns two edges into one, so running
224/// it first hands them a smaller graph with nothing lost. The other way round, threading is free
225/// to give the second branch's block another predecessor, and a block two edges reach is one the
226/// collapse will not touch, so a chain that was foldable stops being foldable.
227///
228/// `canon` and `licm` run a second time after `split`, and that pair is the only thing here that
229/// looks at what `split` wrote. A guard goes in the preheader of the loop being split, which for an
230/// inner loop is a block inside the loops around it, and the guard asks the runtime how big each
231/// object is. On a matrix multiply that is four queries per entry to the innermost loop, two of
232/// them about a pointer that has not changed since it was allocated, and the pass that would take
233/// those out ran seven passes ago. `spec/safe-memory/13-performance.md` section 13.1 measured the
234/// cost and tamnd/rucc#893 is the rest of it.
235///
236/// `ivopts` goes last of the loop passes, because it is the one that decides what the loop's
237/// variables finally are and everything above it is still moving code around. It is followed by
238/// `simplify-cfg` and the pair cannot be separated. Section 28.4 has a loop stop asking its counter
239/// anything, and the counter goes on being incremented round the loop until the parameter carrying
240/// it is taken away. `crate::dce` says in its own documentation that it cannot do that, because the
241/// only reader left is the addition feeding the parameter back and a use count never reaches zero
242/// on a cycle. `crate::simplify_cfg` can, and says it was written for this. Without it the loop
243/// pays for the new pointer and keeps the old counter as well, which over the corpus is about half
244/// of what choosing badly costs.
245const O2: &[&str] = &[
246    "fold",
247    "simplify",
248    "narrow",
249    "simplify",
250    "switch-conv",
251    "short-circuit",
252    "thread",
253    "phiopt",
254    "prune",
255    "canon",
256    "header-copy",
257    "canon",
258    "licm",
259    "unroll",
260    "simplify-cfg",
261    "number",
262    "load-forward",
263    "fold",
264    "simplify",
265    "hoist",
266    "split",
267    "canon",
268    "licm",
269    "ivopts",
270    "simplify-cfg",
271    "discharge",
272    "dce",
273];
274
275/// `-O3`. `-O2` plus loop vectorization, larger inlining and unrolling thresholds, interchange
276/// and distribution where the dependence analysis is confident, and function specialization.
277const O3: &[&str] = &[
278    "fold",
279    "simplify",
280    "narrow",
281    "simplify",
282    "switch-conv",
283    "short-circuit",
284    "thread",
285    "phiopt",
286    "prune",
287    "canon",
288    "header-copy",
289    "canon",
290    "licm",
291    "unroll",
292    "simplify-cfg",
293    "number",
294    "load-forward",
295    "fold",
296    "simplify",
297    "hoist",
298    "split",
299    "canon",
300    "licm",
301    "ivopts",
302    "simplify-cfg",
303    "discharge",
304    "dce",
305];
306
307/// `-Os`. `-O2`'s passes under a size cost model: inlining only where it shrinks, no unrolling
308/// and no vectorization.
309///
310/// The second peephole is here rather than cut for size, because every rule it can fire replaces
311/// a term with a strictly smaller one. Tier one of `spec/optimizer/13-rewrite-rules.md` is
312/// defined that way, so a level that wants smaller code wants more of it and not less.
313///
314/// `short-circuit` is the pass this level drops from `-O2`, for the mirror of that reason. What it
315/// removes is a branch, which is time, and what it adds is the right operand's instructions on a
316/// path that did not run them and an and on top. The code comes out no smaller and usually a byte
317/// or two larger, so a level whose cost model is size has nothing to gain from it.
318///
319/// `hoist` is dropped here as well, and the reason is the same trade read the other way.
320/// It takes a check out of a loop body and puts one in the preheader, plus the address arithmetic
321/// the new check needs, so the loop runs faster and the function is a few instructions larger. That
322/// is a speed transformation with a size cost, which is what `-Os` and `-Oz` are for declining.
323///
324/// `header-copy-small` is the same pass `-O1` and above run under section 26.6's smaller budget.
325/// The copy is code growth and this level pays for it once per loop, so five instructions is what
326/// it will pay. What it gets back is a body that is one region and an exit test at the bottom,
327/// which is slightly smaller in the steady state, so the trade is worth making at a limit that
328/// keeps the header small and not at one that copies twenty instructions to save two.
329const OS: &[&str] = &[
330    "fold",
331    "simplify",
332    "narrow",
333    "simplify",
334    "switch-conv",
335    "thread",
336    "phiopt",
337    "prune",
338    "canon",
339    "header-copy-small",
340    "canon",
341    "simplify-cfg",
342    "number",
343    "load-forward",
344    "fold",
345    "simplify",
346    "discharge",
347    "dce",
348];
349
350/// `-Oz`. `-Os` and additionally the outliner, with instruction selection preferring the smaller
351/// encoding wherever there is a choice.
352///
353/// Header copying is the pass this level drops from `-Os`, which section 26.6 asks for by name. It
354/// is the one loop canonicalization that makes the function bigger, `-Oz` is the level that would
355/// rather have the branch than the bytes, and every reason to want the do-while form here is a
356/// speed reason.
357const OZ: &[&str] = &[
358    "fold",
359    "simplify",
360    "narrow",
361    "simplify",
362    "switch-conv",
363    "thread",
364    "phiopt",
365    "prune",
366    "canon",
367    "simplify-cfg",
368    "number",
369    "load-forward",
370    "fold",
371    "simplify",
372    "discharge",
373    "dce",
374];
375
376/// The passes this level runs, before the command line adds to or removes from them.
377#[must_use]
378pub const fn for_level(level: OptLevel) -> &'static [&'static str] {
379    match level {
380        OptLevel::O0 => O0,
381        OptLevel::O1 => O1,
382        OptLevel::O2 => O2,
383        OptLevel::O3 => O3,
384        OptLevel::Os => OS,
385        OptLevel::Oz => OZ,
386    }
387}
388
389/// Which passes the IR is written out around.
390///
391/// Empty by default, which is the whole point: a dump is a debugging aid and writing files
392/// nobody asked for is not one.
393#[derive(Debug, Clone, Default, PartialEq, Eq)]
394pub struct Dumps {
395    /// Every pass, on both sides.
396    all: bool,
397    /// The passes to write out before.
398    before: Vec<String>,
399    /// The passes to write out after.
400    after: Vec<String>,
401}
402
403impl Dumps {
404    /// Adds one `-fdump-ir=` argument.
405    ///
406    /// # Errors
407    ///
408    /// When the argument is not `all`, `before-<pass>` or `after-<pass>`, or when it names a
409    /// pass this compiler does not have. A misspelled pass name that quietly dumped nothing
410    /// would look exactly like a pass that did not run.
411    pub fn add(&mut self, spec: &str) -> Result<(), String> {
412        if spec == "all" {
413            self.all = true;
414            return Ok(());
415        }
416        let (side, name) = match spec.split_once('-') {
417            Some(("before", name)) => (&mut self.before, name),
418            Some(("after", name)) => (&mut self.after, name),
419            _ => {
420                return Err(format!(
421                    "`{spec}` is not a dump this compiler makes, which are `all`, \
422                     `before-<pass>` and `after-<pass>`"
423                ));
424            }
425        };
426        if pass::find(name).is_none() {
427            return Err(format!("`{name}` is not a pass this compiler has, see --print-pipeline"));
428        }
429        side.push(name.to_owned());
430        Ok(())
431    }
432
433    /// Whether anything is dumped at all.
434    #[must_use]
435    pub fn is_empty(&self) -> bool {
436        !self.all && self.before.is_empty() && self.after.is_empty()
437    }
438
439    /// Whether the IR is written out before this pass runs.
440    #[must_use]
441    pub fn wants_before(&self, name: &str) -> bool {
442        self.all || self.before.iter().any(|it| it == name)
443    }
444
445    /// Whether the IR is written out after this pass runs.
446    #[must_use]
447    pub fn wants_after(&self, name: &str) -> bool {
448        self.all || self.after.iter().any(|it| it == name)
449    }
450}
451
452/// What the command line asked the optimizer for.
453#[derive(Debug, Clone, PartialEq, Eq)]
454pub struct Options {
455    /// Which pipeline to start from.
456    pub level: OptLevel,
457    /// The passes `-f<name>` added and `-fno-<name>` removed, in the order they were given, so
458    /// that the last mention of a pass is the one that decides.
459    pub toggles: Vec<(String, bool)>,
460    /// What `-fpass-fuel=<pass>=<n>` limited, by pass name.
461    pub fuel: HashMap<String, u32>,
462    /// What `-fpass-fuel-global=<n>` limited the whole pipeline to, across every pass.
463    ///
464    /// This is the outer search of the two in section 4.5 of
465    /// `spec/optimizer/04-pass-manager.md`. Halving this finds the pass, and halving
466    /// `-fpass-fuel` for that pass finds the rewrite inside it. Two searches of twenty
467    /// compilations each beat one search over a space nobody knows the shape of.
468    pub global_fuel: Option<u32>,
469    /// What `-fdisable-<pass>` and `-fenable-<pass>` said about which functions a pass runs on.
470    pub gates: Gates,
471    /// What `-fdump-ir=` asked to see.
472    pub dumps: Dumps,
473    /// Whether the verifier runs after every pass that changed anything.
474    pub verify: bool,
475    /// Which definitions in this module something else may replace at load time.
476    ///
477    /// The analyses that read a body and write down what they found have to stop at a name like
478    /// that, because the body they read is not the one that will run. [`Pic::Library`] is the
479    /// answer when the object may end up in a shared library and the exported names in it are
480    /// interposable, which is what `-fPIC` alone means and is gcc's default.
481    ///
482    /// [`Pic::Executable`] is the answer for everything else, and that includes
483    /// `-fno-semantic-interposition`, where the build has promised that the definition here is the
484    /// one that runs. It is a promise and not a deduction, and it is the one every distribution
485    /// makes, because a library that cannot inline its own functions into each other pays for the
486    /// possibility of an interposition that never happens.
487    ///
488    /// This is not the same value the code generator is given. How an address is reached does not
489    /// change under that promise, and gcc does not change it either: a variable a shared library
490    /// exports is still read out of the global offset table, because the promise is about which
491    /// definition runs rather than about how many copies of the variable there are.
492    pub interposition: Pic,
493}
494
495impl Default for Options {
496    /// The default level with nothing added to it, and the verifier on in a debug build, which
497    /// is what section 9.10 asks for.
498    fn default() -> Self {
499        Self {
500            level: OptLevel::default(),
501            toggles: Vec::new(),
502            fuel: HashMap::new(),
503            global_fuel: None,
504            gates: Gates::default(),
505            dumps: Dumps::default(),
506            verify: cfg!(debug_assertions),
507            interposition: Pic::Executable,
508        }
509    }
510}
511
512impl Options {
513    /// The options a level asks for on its own.
514    #[must_use]
515    pub fn for_level(level: OptLevel) -> Self {
516        Self { level, ..Self::default() }
517    }
518
519    /// The passes the level and the `-f` flags chose, in order, before the gates are consulted.
520    ///
521    /// A pass named by `-f<name>` that the level did not choose is appended, because the only
522    /// place it could go that does not need an ordering rule nobody wrote down is the end.
523    #[must_use]
524    pub fn chosen(&self) -> Vec<&'static str> {
525        let mut names: Vec<&str> = for_level(self.level).to_vec();
526        for (name, on) in &self.toggles {
527            let name = name.as_str();
528            match *on {
529                true if !names.contains(&name) => names.push(name),
530                true => {}
531                false => names.retain(|it| *it != name),
532            }
533        }
534        names.into_iter().filter_map(pass::find).map(Pass::name).collect()
535    }
536
537    /// The passes that will run, in order, over at least one function.
538    ///
539    /// A pass `-fenable-<name>` reached that the level did not choose is appended after them,
540    /// for the same reason and in the same place. It runs only over the functions the gate names,
541    /// which is the whole point of the flag: a pass being in this list is not the same question as
542    /// a pass running on the function somebody is looking at.
543    #[must_use]
544    pub fn passes(&self) -> Vec<&'static dyn Pass> {
545        let mut names = self.chosen();
546        for name in self.gates.enabled() {
547            // Through the pass list rather than straight from the gate, because the name the
548            // pass holds outlives this call and the one the gate holds does not.
549            let Some(found) = pass::find(name) else { continue };
550            if !names.contains(&found.name()) {
551                names.push(found.name());
552            }
553        }
554        names.into_iter().filter_map(pass::find).collect()
555    }
556}
557
558/// One written out copy of the IR.
559#[derive(Debug, Clone, PartialEq, Eq)]
560pub struct Dump {
561    /// What to call it, which is a number, a side and a pass name, as in `01-after-fold`. The
562    /// number is there so that a directory listing is in the order the passes ran.
563    pub name: String,
564    /// The module, in the textual form from `spec/08-ir.md`.
565    pub text: String,
566}
567
568/// What one pass had to say about one function.
569///
570/// One of these per pass per function with a body, whether or not the pass said anything, because
571/// a pass that reports nothing being visible as a pass that reports nothing is the point of the
572/// record. Section 42.2 of `spec/optimizer/42-measurement.md` has the argument.
573#[derive(Debug, Clone, PartialEq, Eq)]
574pub struct Remark {
575    /// Which pass, by the name a `-f` flag spells.
576    pub pass: &'static str,
577    /// Which function, by the name in the source.
578    pub func: Symbol,
579    /// What it said.
580    pub stats: Stats,
581}
582
583/// What running the pipeline produced beyond the changed module.
584#[derive(Debug, Clone, Default, PartialEq, Eq)]
585pub struct Report {
586    /// The dumps asked for, in the order they were taken. The manager does not write files,
587    /// because nothing below the driver in `spec/18-package-layout.md` knows what a file is.
588    pub dumps: Vec<Dump>,
589    /// A pass that left the IR in a state the verifier refuses, named, with what it said.
590    pub broke: Vec<String>,
591    /// How much fuel each pass spent, which is the number a bisection halves.
592    pub spent: Vec<(&'static str, u32)>,
593    /// What every pass said about every function, in the order the passes ran and then in the
594    /// order the module holds its functions. This is what `-fopt-info` prints.
595    pub remarks: Vec<Remark>,
596}
597
598impl Report {
599    /// Everything one pass said across the whole module, added up.
600    ///
601    /// The counts of an event are addable across functions because an event names a site in a
602    /// pass rather than a fact about a program, which is the reason [`crate::stats::Event::what`]
603    /// is a fixed string.
604    #[must_use]
605    pub fn totals(&self, pass: &str) -> Stats {
606        let mut total = Stats::new();
607        for remark in self.remarks.iter().filter(|it| it.pass == pass) {
608            total.merge(&remark.stats);
609        }
610        total
611    }
612}
613
614/// Runs the pipeline over the module.
615///
616/// Every pass sees every function with a body, one at a time, and a pass runs over the whole
617/// module before the next one starts. That order is what makes the dumps readable: a dump is
618/// the state of the program between two passes rather than between two functions.
619pub fn run(module: &mut Module, names: &Interner, opts: &Options) -> Report {
620    let mut report = Report::default();
621    let chosen = opts.chosen();
622    // One cache per function, kept across passes because a pass runs over the whole module
623    // before the next one starts. A cache that lived only as long as one function would be
624    // thrown away between every pass and would never answer a second question. Section 4.2 of
625    // `spec/optimizer/04-pass-manager.md` is the plan for turning the loop inside out, and the
626    // day that happens this map becomes a local in the inner loop.
627    let mut cached: HashMap<FuncId, Analyses> = HashMap::new();
628    // The machine, once for the module, because every function in it is compiled for the same
629    // target at the same goal. It goes into each function's cache rather than into a parameter of
630    // its own, per `crate::machine`.
631    let machine = Machine::of(module, opts.level);
632    // What the whole pipeline has left, which every pass draws its own allowance out of and
633    // gives the unspent part of back. A pass past the end of it is given nothing rather than
634    // skipped, so it still runs, still reports, and still transforms nothing.
635    let mut budget = opts.global_fuel;
636    // What each pass has left of what `-fpass-fuel` gave it. One allowance across every place
637    // the list names that pass, rather than one allowance each, because the number in the flag
638    // is meant to be the number of rewrites that happened. A peephole that runs twice under
639    // `-fpass-fuel=simplify=5` and rewrites ten things would make the bisection in section 4.5
640    // of `spec/optimizer/04-pass-manager.md` step over the rewrite it was looking for.
641    let mut allowance = opts.fuel.clone();
642    let passes = opts.passes();
643    // Before anything runs, because each of these is a fact about the module and every pass after
644    // this sees one function. Only when a pass in this run reads them: a flag nothing looks at
645    // would show up in every `-O0` dump and mean nothing to anybody reading one.
646    if passes.iter().any(|pass| READS_SUMMARIES.contains(&pass.name())) {
647        nofree::annotate(module, names, opts.interposition);
648        extents::annotate(module, opts.interposition);
649        params::annotate(module, opts.interposition);
650        heap::annotate(module, names);
651    }
652    for (index, pass) in passes.into_iter().enumerate() {
653        let name = pass.name();
654        if opts.dumps.wants_before(name) {
655            report.dumps.push(dump(index, "before", name, module, names));
656        }
657        let mut fuel = match (allowance.get(name).copied(), budget) {
658            // Whichever limit is tighter, because two limits that disagree mean the one that
659            // stops first, and a bisection that started with the global one has to stay inside
660            // it while the per pass one is halved.
661            (Some(count), Some(left)) => Fuel::of(count.min(left)),
662            (Some(count), None) => Fuel::of(count),
663            (None, Some(left)) => Fuel::of(left),
664            (None, None) => Fuel::unlimited(),
665        };
666        // What the level and the `-f` flags decided, which is what a gate overrides for the
667        // functions it names and leaves alone for the ones it does not.
668        let default = chosen.contains(&name);
669        for id in module.funcs() {
670            if module[id].is_declaration() {
671                continue;
672            }
673            if !opts.gates.allows(name, default, id.raw(), names.resolve(module[id].name)) {
674                // No remark either. A pass that did not run on a function has nothing to say
675                // about it, and a record saying it found nothing would read as a pass that
676                // looked.
677                continue;
678            }
679            let an = cached.entry(id).or_insert_with(|| Analyses::new(machine));
680            let stats = pass.run(&mut module[id], an, &mut fuel);
681            // A pass that changed nothing preserved everything, whatever it says about itself,
682            // so the cheap case does not need every pass to have a second opinion about it.
683            // A pass that did change something is taken at its word, and in a checked build the
684            // word is checked.
685            let keeps = if stats.changed() { pass.preserves() } else { Preserved::ALL };
686            for broken in an.settle(&module[id], keeps, opts.verify) {
687                let func = names.resolve(module[id].name);
688                report.broke.push(format!(
689                    "the {name} pass said it preserved {} of {func} and did not",
690                    broken.name()
691                ));
692            }
693            // Here rather than after the pass, and this function rather than the module. A pass
694            // is a function pass, so the only thing it can have broken is the function it was
695            // given, and walking the other ones again after every one of them is the quadratic
696            // walk `rucc_ir::verify_func` exists to avoid. Doing it here is also what lets the
697            // message name the function, which the module walk could not, and it puts the
698            // failure next to the pass that caused it rather than at the end of the module.
699            if stats.changed() && opts.verify {
700                if let Err(errors) = rucc_ir::verify_func(module, &module[id], names) {
701                    let func = names.resolve(module[id].name);
702                    for error in errors {
703                        report
704                            .broke
705                            .push(format!("the {name} pass left invalid IR in {func}, {error}"));
706                    }
707                }
708            }
709            // The record is the only place the manager learns that anything happened, which is
710            // why the pass cannot leave recording until later. See `crate::stats`.
711            report.remarks.push(Remark { pass: name, func: module[id].name, stats });
712        }
713        // Added to rather than pushed, so a pass the list names twice is one line here with what
714        // both of its runs spent. That is the number a bisection halves, and two lines under one
715        // name would be two numbers where the flag takes one.
716        match report.spent.iter_mut().find(|(it, _)| *it == name) {
717            Some((_, total)) => *total += fuel.spent(),
718            None => report.spent.push((name, fuel.spent())),
719        }
720        if let Some(left) = &mut budget {
721            // Never below zero, because the allowance the pass was given was at most this.
722            *left -= fuel.spent();
723        }
724        if let Some(left) = allowance.get_mut(name) {
725            // Same, and for the same reason.
726            *left -= fuel.spent();
727        }
728        if opts.dumps.wants_after(name) {
729            report.dumps.push(dump(index, "after", name, module, names));
730        }
731    }
732    report
733}
734
735/// The module written out, under a name that sorts in the order the passes ran.
736fn dump(index: usize, side: &str, name: &str, module: &Module, names: &Interner) -> Dump {
737    Dump { name: format!("{index:02}-{side}-{name}"), text: rucc_ir::print(module, names) }
738}
739
740/// Renders what `--print-pipeline` prints.
741///
742/// One line per pass, numbered from one, with what the pass does after it. A level that runs
743/// nothing says so rather than printing an empty list, because an empty answer and a broken
744/// command look the same.
745#[must_use]
746pub fn print(opts: &Options) -> String {
747    let mut out = String::new();
748    let _ = writeln!(out, "level: {}", opts.level);
749    // Only when it was asked for, so the listing of a compilation nobody is bisecting is the
750    // same listing it has always been. A run under a budget is a run whose output is not the
751    // one the level asked for, and the listing is where that has to be visible.
752    if let Some(count) = opts.global_fuel {
753        let _ = writeln!(out, "global fuel: {count}");
754    }
755    let passes = opts.passes();
756    if passes.is_empty() {
757        let _ = writeln!(out, "no passes");
758        return out;
759    }
760    for (index, pass) in passes.iter().enumerate() {
761        let _ = write!(out, "{}: {}, {}", index + 1, pass.name(), pass.describe());
762        // Only when a gate mentions the pass, so the listing of a compilation nobody is
763        // debugging is the same listing it has always been.
764        if let Some(note) = opts.gates.note(pass.name()) {
765            let _ = write!(out, " [{note}]");
766        }
767        out.push('\n');
768    }
769    out
770}
771
772#[cfg(test)]
773mod tests {
774    use rucc_base::Interner;
775    use rucc_ir::{
776        Builder, Extra, Flags, Func, IntPred, MemInfo, MemOrder, Module, Opcode, Restrict,
777        Signature, Type,
778    };
779    use rucc_session::OptLevel;
780    use rucc_target::{Arch, Env, Os, TargetInfo, Triple};
781
782    use super::{Dumps, Options, for_level};
783    use crate::stats::Kind;
784    use crate::{Pass, pass};
785
786    /// A module with one function whose body has something to fold in it.
787    fn module() -> (Interner, Module) {
788        let mut names = Interner::new();
789        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
790        let mut module = Module::new(names.intern("test.c"), &target);
791        let func = foldable(&mut names, "f");
792        module.add_func(func);
793        (names, module)
794    }
795
796    /// A module with two of them, called `f` and `g`, in that order, so `f` is function 0.
797    fn two_functions() -> (Interner, Module) {
798        let mut names = Interner::new();
799        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
800        let mut module = Module::new(names.intern("test.c"), &target);
801        for name in ["f", "g"] {
802            let func = foldable(&mut names, name);
803            module.add_func(func);
804        }
805        (names, module)
806    }
807
808    /// A module with one function holding two identities the peephole takes, on a value that
809    /// arrives as a parameter so that folding cannot get to them first.
810    fn identities() -> (Interner, Module) {
811        let mut names = Interner::new();
812        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
813        let mut module = Module::new(names.intern("test.c"), &target);
814        let i32_ = Type::int(32);
815        let mut func = Func::new(
816            names.intern("h"),
817            Signature::new().with_params(&[i32_]).with_returns(&[i32_]),
818        );
819        let entry = func.create_block();
820        let x = func.append_param(entry, i32_);
821        let mut build = Builder::new(&mut func, entry);
822        let zero = build.iconst(i32_, 0);
823        let one = build.iconst(i32_, 1);
824        let sum = build.binary(Opcode::Add, x, zero, Flags::NONE);
825        let product = build.binary(Opcode::Mul, sum, one, Flags::NONE);
826        build.ret(&[product]);
827        module.add_func(func);
828        (names, module)
829    }
830
831    /// A function that returns a sign extension of a constant, which folding rewrites.
832    fn foldable(names: &mut Interner, name: &str) -> Func {
833        let mut func =
834            Func::new(names.intern(name), Signature::new().with_returns(&[Type::int(64)]));
835        let block = func.create_block();
836        let mut build = Builder::new(&mut func, block);
837        let narrow = build.iconst(Type::int(32), 7);
838        let wide = build.unary(Opcode::SExt, narrow, Type::int(64));
839        build.ret(&[wide]);
840        func
841    }
842
843    /// Whether the pass said anything about the function, which it only does when it ran on it.
844    fn spoke_about(report: &super::Report, pass: &str, func: &str, names: &Interner) -> bool {
845        report.remarks.iter().any(|it| it.pass == pass && names.resolve(it.func) == func)
846    }
847
848    /// A module with a loop short enough for the unroller to flatten, over an array a parameter
849    /// points at.
850    ///
851    /// Four iterations, which is a trip count the unroller takes whole. The copy that runs first
852    /// subscripts the array at zero, so what works its offset out is a multiply by zero, and
853    /// folding that is what leaves the addition this is here to look for.
854    fn a_short_loop() -> (Interner, Module) {
855        let mut names = Interner::new();
856        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
857        let mut module = Module::new(names.intern("test.c"), &target);
858        let (i32_, i64_) = (Type::int(32), Type::int(64));
859        let signature = Signature::new().with_params(&[Type::PTR]).with_returns(&[i32_]);
860        let mut func = Func::new(names.intern("sum"), signature);
861        let entry = func.create_block();
862        let head = func.create_block();
863        let body = func.create_block();
864        let exit = func.create_block();
865        let p = func.append_param(entry, Type::PTR);
866        let i = func.append_param(head, i32_);
867        let acc = func.append_param(head, i32_);
868
869        let mut build = Builder::new(&mut func, entry);
870        let zero = build.iconst(i32_, 0);
871        build.jump(head, &[zero, zero]);
872
873        let mut build = Builder::new(&mut func, head);
874        let four = build.iconst(i32_, 4);
875        let more = build.icmp(IntPred::Slt, i, four);
876        build.br_if(more, body, &[], exit, &[]);
877
878        let mut build = Builder::new(&mut func, body);
879        let wide = build.unary(Opcode::SExt, i, i64_);
880        let scale = build.iconst(i64_, 4);
881        let offset = build.binary(Opcode::Mul, wide, scale, Flags::NSW);
882        let at = build.binary(Opcode::PtrAdd, p, offset, Flags::NONE);
883        let read = build.load(i32_, at, plain(), Flags::NONE);
884        let total = build.binary(Opcode::Add, acc, read, Flags::NONE);
885        let one = build.iconst(i32_, 1);
886        let next = build.binary(Opcode::Add, i, one, Flags::NSW);
887        build.jump(head, &[next, total]);
888
889        let mut build = Builder::new(&mut func, exit);
890        build.ret(&[acc]);
891        module.add_func(func);
892        (names, module)
893    }
894
895    /// Memory with nothing said about it, which is what a plain subscript reads through.
896    fn plain() -> MemInfo {
897        MemInfo {
898            size: 4,
899            align: 4,
900            order: MemOrder::NotAtomic,
901            tbaa: None,
902            owns: 0,
903            restrict: Restrict::NONE,
904        }
905    }
906
907    /// Every addition in the module whose right operand is the constant zero.
908    fn adds_of_zero(module: &Module) -> usize {
909        let mut found = 0;
910        for id in module.funcs() {
911            let func = &module[id];
912            for block in func.blocks() {
913                for inst in func.insts(block) {
914                    if !matches!(func[inst].opcode, Opcode::Add | Opcode::PtrAdd) {
915                        continue;
916                    }
917                    let args = &func[func[inst].args];
918                    let Some(&rhs) = args.get(1) else { continue };
919                    let rucc_ir::Def::Result { inst: from, .. } = func[rhs].def else { continue };
920                    if func[from].opcode != Opcode::IConst {
921                        continue;
922                    }
923                    let Extra::Imm(at) = func[from].extra else { continue };
924                    found += usize::from(func[at].signed(func[rhs].ty) == 0);
925                }
926            }
927        }
928        found
929    }
930
931    /// An index the unroller worked out to zero does not leave the addition behind.
932    ///
933    /// The peephole is what removes it and the peephole used to run only near the top of the
934    /// list, before the unroller had made any of these. Folding writes the constant down and
935    /// leaves the addition, so an `add x, 0` reached the selector and was written out as an
936    /// `addq $0` the machine runs for nothing. tamnd/rucc#875.
937    #[test]
938    fn an_index_folded_to_zero_is_not_added_to_anything() {
939        let (names, mut module) = a_short_loop();
940        assert_eq!(adds_of_zero(&module), 0, "the fixture already has one before anything runs");
941        let report = super::run(&mut module, &names, &Options::for_level(OptLevel::O2));
942        assert!(report.broke.is_empty(), "{:?}", report.broke);
943        assert!(spent(&report, "unroll").is_some_and(|it| it > 0), "the loop was not unrolled");
944        assert_eq!(adds_of_zero(&module), 0, "{}", rucc_ir::print(&module, &names));
945    }
946
947    #[test]
948    fn every_pass_a_pipeline_names_is_a_pass_that_exists() {
949        for level in
950            [OptLevel::O0, OptLevel::O1, OptLevel::O2, OptLevel::O3, OptLevel::Os, OptLevel::Oz]
951        {
952            for name in for_level(level) {
953                assert!(
954                    pass::find(name).is_some(),
955                    "{level} names `{name}` and no pass answers to it"
956                );
957            }
958        }
959    }
960
961    #[test]
962    fn a_pass_a_pipeline_names_twice_is_never_named_twice_in_a_row() {
963        // Running a pass again after another pass has been through is the point of naming it
964        // twice, and `simplify` around `narrow` is why the rule that used to be here, which was
965        // that no level names a pass twice at all, is not the rule any more. Two runs with
966        // nothing between them is still a mistake: the second one sees exactly what the first
967        // one finished with, so it can only report that it found nothing.
968        for level in
969            [OptLevel::O0, OptLevel::O1, OptLevel::O2, OptLevel::O3, OptLevel::Os, OptLevel::Oz]
970        {
971            for pair in for_level(level).windows(2) {
972                assert_ne!(pair[0], pair[1], "{level} runs `{}` twice in a row", pair[0]);
973            }
974        }
975    }
976
977    #[test]
978    fn a_pass_the_pipeline_runs_twice_gets_one_allowance_and_reports_one_number() {
979        // `-fpass-fuel=<pass>=<n>` is halved to find one rewrite, so the number in the flag has
980        // to be the number of rewrites that happened however many times the list names the pass.
981        // The peephole is named more than once from `-O1` up and the function below holds two
982        // identities it takes, so a cap of one has to stop after one rather than after one per
983        // occurrence.
984        assert!(for_level(OptLevel::O2).iter().filter(|it| **it == "simplify").count() > 1);
985
986        let (names, mut module) = identities();
987        let free = super::run(&mut module, &names, &Options::for_level(OptLevel::O2));
988        assert_eq!(spent(&free, "simplify"), Some(2), "{:?}", free.spent);
989
990        let (names, mut module) = identities();
991        let mut opts = Options::for_level(OptLevel::O2);
992        opts.fuel.insert("simplify".to_owned(), 1);
993        let capped = super::run(&mut module, &names, &opts);
994        assert_eq!(capped.spent.iter().filter(|(name, _)| *name == "simplify").count(), 1);
995        assert_eq!(spent(&capped, "simplify"), Some(1), "{:?}", capped.spent);
996    }
997
998    #[test]
999    fn an_identity_only_the_narrow_pass_can_produce_is_still_taken() {
1000        // Issue 505, and the reason the peephole is named on both sides of `narrow`. C promotes
1001        // before it operates, so `unsigned char x; (unsigned char)(x & 255)` arrives here as a
1002        // thirty two bit `and` of a zero extension, and the rule that says `and` with every bit
1003        // set is the value has nothing at eight bits to match. `narrow` is the only producer that
1004        // width has. Before this ran twice the `and.i8` below reached the back end untouched.
1005        let mut names = Interner::new();
1006        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
1007        let mut module = Module::new(names.intern("test.c"), &target);
1008        let (i8_, i32_) = (Type::int(8), Type::int(32));
1009        let mut func =
1010            Func::new(names.intern("f"), Signature::new().with_params(&[i8_]).with_returns(&[i8_]));
1011        let entry = func.create_block();
1012        let x = func.append_param(entry, i8_);
1013        let mut build = Builder::new(&mut func, entry);
1014        let wide = build.unary(Opcode::ZExt, x, i32_);
1015        let mask = build.iconst(i32_, 255);
1016        let kept = build.binary(Opcode::And, wide, mask, Flags::NONE);
1017        let back = build.unary(Opcode::Trunc, kept, i8_);
1018        build.ret(&[back]);
1019        module.add_func(func);
1020
1021        let report = super::run(&mut module, &names, &Options::for_level(OptLevel::O2));
1022        assert!(report.broke.is_empty(), "{:?}", report.broke);
1023        let text = rucc_ir::print(&module, &names);
1024        assert!(!text.contains("and."), "the masking survived the pipeline\n{text}");
1025    }
1026
1027    /// What a pass spent, or `None` if it did not run.
1028    fn spent(report: &super::Report, pass: &str) -> Option<u32> {
1029        report.spent.iter().find(|(name, _)| *name == pass).map(|&(_, count)| count)
1030    }
1031
1032    /// The names of the passes a set of options would run, in order.
1033    fn names(opts: &Options) -> Vec<&'static str> {
1034        opts.passes().into_iter().map(Pass::name).collect()
1035    }
1036
1037    #[test]
1038    fn every_level_that_splits_a_loop_looks_at_what_the_split_wrote() {
1039        // A guard goes in the preheader of the loop being split, which for an inner loop is inside
1040        // the loops around it, and it asks the runtime how big an object is. Nothing after `split`
1041        // moves anything, so a level that splits and then stops leaves those queries where they
1042        // cost the most.
1043        for level in [super::O1, super::O2, super::O3, super::OS, super::OZ] {
1044            let Some(at) = level.iter().position(|pass| *pass == "split") else {
1045                continue;
1046            };
1047            assert!(
1048                level[at..].contains(&"licm"),
1049                "a level splits a loop and never looks at the guard again"
1050            );
1051        }
1052    }
1053
1054    #[test]
1055    fn every_level_that_chooses_induction_variables_takes_the_old_one_away_afterwards() {
1056        // The counter a loop stops asking anything is still incremented round it, and what removes
1057        // the parameter carrying it is `simplify-cfg` rather than `dce`. See the comment on `O2`.
1058        // A level that chooses and then stops keeps both variables and is worse off than if it had
1059        // never chosen at all.
1060        for level in [super::O1, super::O2, super::O3, super::OS, super::OZ] {
1061            let Some(at) = level.iter().position(|pass| *pass == "ivopts") else {
1062                continue;
1063            };
1064            assert!(
1065                level[at + 1..].contains(&"simplify-cfg"),
1066                "a level chooses induction variables and leaves the one it stopped using behind"
1067            );
1068        }
1069    }
1070
1071    #[test]
1072    fn every_run_of_the_pass_that_reads_a_summary_is_named_as_one_that_does() {
1073        // A run left off the list gets no table of globals and no caller guarantees, and answers
1074        // that there were none rather than that nobody built them.
1075        for pass in pass::PASSES {
1076            let name = pass.name();
1077            assert_eq!(
1078                name.starts_with("discharge"),
1079                super::READS_SUMMARIES.contains(&name),
1080                "`{name}` and READS_SUMMARIES disagree about whether it reads a summary"
1081            );
1082        }
1083    }
1084
1085    #[test]
1086    fn the_level_that_optimizes_nothing_still_removes_what_nothing_reaches() {
1087        // One pass at `-O0`, and it is the one that is not an optimization. See the comment on
1088        // the level itself, and issue 359.
1089        assert_eq!(names(&Options::for_level(OptLevel::O0)), ["simplify-cfg"]);
1090        assert!(names(&Options::for_level(OptLevel::O2)).len() > 1);
1091    }
1092
1093    #[test]
1094    fn a_pass_is_removed_by_no_and_added_by_the_bare_name_and_the_last_word_wins() {
1095        let mut opts = Options::for_level(OptLevel::O2);
1096        opts.toggles.push(("fold".to_owned(), false));
1097        assert!(!names(&opts).contains(&"fold"), "{:?}", names(&opts));
1098        opts.toggles.push(("fold".to_owned(), true));
1099        assert!(names(&opts).contains(&"fold"), "{:?}", names(&opts));
1100
1101        let mut off = Options::for_level(OptLevel::O0);
1102        off.toggles.push(("fold".to_owned(), true));
1103        assert_eq!(
1104            names(&off),
1105            ["simplify-cfg", "fold"],
1106            "a pass the level did not choose is still reachable"
1107        );
1108    }
1109
1110    #[test]
1111    fn asking_for_a_pass_twice_does_not_run_it_twice() {
1112        let mut opts = Options::for_level(OptLevel::O2);
1113        let before = names(&opts);
1114        opts.toggles.push(("fold".to_owned(), true));
1115        assert_eq!(names(&opts), before);
1116    }
1117
1118    #[test]
1119    fn the_pipeline_listing_names_the_level_and_every_pass_in_order() {
1120        let text = super::print(&Options::for_level(OptLevel::O2));
1121        assert!(text.starts_with("level: -O2\n"), "{text}");
1122        assert!(text.contains("1: fold, "), "{text}");
1123        let mut none = Options::for_level(OptLevel::O0);
1124        none.toggles.push(("simplify-cfg".to_owned(), false));
1125        let none = super::print(&none);
1126        assert!(none.contains("no passes"), "{none}");
1127    }
1128
1129    #[test]
1130    fn running_the_pipeline_changes_the_module_and_reports_what_it_spent() {
1131        let (names, mut module) = module();
1132        let report = super::run(&mut module, &names, &Options::for_level(OptLevel::O2));
1133        // Folding rewrites the sign extension into a constant, and then the constant it was
1134        // extending is read by nothing and dead code elimination takes it out. One
1135        // transformation each, which is what the two of them together are for. Asserted by
1136        // name rather than as the whole vector, so a pass added later does not fail this.
1137        assert_eq!(spent(&report, "fold"), Some(1));
1138        assert_eq!(spent(&report, "dce"), Some(1));
1139        assert!(report.broke.is_empty(), "{:?}", report.broke);
1140        assert!(report.dumps.is_empty(), "nothing asked for a dump");
1141        assert!(rucc_ir::print(&module, &names).contains("iconst.i64 7"));
1142    }
1143
1144    #[test]
1145    fn the_analyses_survive_a_pass_that_keeps_them_and_not_one_that_does_not() {
1146        // The pipeline half of the analysis manager. A branch on a constant, so `simplify-cfg`
1147        // has something to do and says it preserved nothing, and the whole run comes out with
1148        // the verifier and the manager both satisfied. What a pass that lied would produce is in
1149        // `crate::analysis`, where a lie can be told on purpose.
1150        let mut names = Interner::new();
1151        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
1152        let mut module = Module::new(names.intern("test.c"), &target);
1153        let mut func = Func::new(names.intern("f"), Signature::new());
1154        let entry = func.create_block();
1155        let dead = func.create_block();
1156        let exit = func.create_block();
1157        let mut build = Builder::new(&mut func, entry);
1158        let never = build.iconst(Type::int(1), 0);
1159        build.br_if(never, dead, &[], exit, &[]);
1160        for block in [dead, exit] {
1161            let mut build = Builder::new(&mut func, block);
1162            build.ret(&[]);
1163        }
1164        module.add_func(func);
1165        let report = super::run(&mut module, &names, &Options::for_level(OptLevel::O2));
1166        // The fold, and then the merge of the arm it left with one way into it.
1167        assert_eq!(spent(&report, "simplify-cfg"), Some(2));
1168        assert!(report.broke.is_empty(), "{:?}", report.broke);
1169        let text = rucc_ir::print(&module, &names);
1170        // The labels, which start a line, and not the mentions of one, which are indented. One
1171        // left: the arm nothing reaches went, and the arm that is always taken came up into the
1172        // entry, which is what is left of the branch.
1173        assert_eq!(text.matches("\nblock").count(), 1, "there is more than one block:\n{text}");
1174    }
1175
1176    #[test]
1177    fn no_pass_that_optimizes_runs_at_no_optimization_however_much_there_is_to_do() {
1178        let (names, mut module) = module();
1179        let before = rucc_ir::print(&module, &names);
1180        let report = super::run(&mut module, &names, &Options::for_level(OptLevel::O0));
1181        // The one pass the level runs looked, found no branch it could read and no block nothing
1182        // reaches, and spent nothing. The constant arithmetic the fixture is full of is still
1183        // there, which is the part of `-O0` that has not changed.
1184        assert_eq!(report.spent, vec![("simplify-cfg", 0)]);
1185        assert_eq!(rucc_ir::print(&module, &names), before);
1186    }
1187
1188    #[test]
1189    fn a_gate_takes_a_pass_away_from_one_function_and_leaves_the_other_alone() {
1190        let (names, mut module) = two_functions();
1191        let mut opts = Options::for_level(OptLevel::O2);
1192        opts.gates.add(false, "fold=g").expect("g is a function and fold is a pass");
1193        let report = super::run(&mut module, &names, &opts);
1194        assert!(spoke_about(&report, "fold", "f", &names));
1195        assert!(!spoke_about(&report, "fold", "g", &names), "fold ran where it was gated off");
1196        assert!(spoke_about(&report, "dce", "g", &names), "one pass gated off is not all of them");
1197        // What the gate is for: the two functions came out different, and the difference is one
1198        // pass on one function rather than a level on a file.
1199        let text = rucc_ir::print(&module, &names);
1200        assert_eq!(text.matches("sext.i64").count(), 1, "{text}");
1201    }
1202
1203    #[test]
1204    fn a_function_can_be_gated_by_the_number_it_has_in_the_module() {
1205        let (names, mut module) = two_functions();
1206        let mut opts = Options::for_level(OptLevel::O2);
1207        opts.gates.add(false, "fold=0").expect("0 is a function and fold is a pass");
1208        let report = super::run(&mut module, &names, &opts);
1209        assert!(!spoke_about(&report, "fold", "f", &names), "function 0 is the first one");
1210        assert!(spoke_about(&report, "fold", "g", &names));
1211    }
1212
1213    #[test]
1214    fn enabling_a_pass_reaches_one_function_at_a_level_that_did_not_ask_for_it() {
1215        let (names, mut module) = two_functions();
1216        let mut opts = Options::for_level(OptLevel::O0);
1217        opts.gates.add(true, "fold=1").expect("1 is a function and fold is a pass");
1218        let running: Vec<&str> = opts.passes().into_iter().map(Pass::name).collect();
1219        assert_eq!(
1220            running,
1221            ["simplify-cfg", "fold"],
1222            "the flag has to put the pass in the pipeline"
1223        );
1224        let report = super::run(&mut module, &names, &opts);
1225        assert!(!spoke_about(&report, "fold", "f", &names), "nothing asked for f");
1226        assert!(spoke_about(&report, "fold", "g", &names));
1227        let text = rucc_ir::print(&module, &names);
1228        assert_eq!(text.matches("sext.i64").count(), 1, "{text}");
1229    }
1230
1231    #[test]
1232    fn a_pass_gated_off_everywhere_runs_on_nothing_and_still_says_so() {
1233        let (names, mut module) = two_functions();
1234        let before = rucc_ir::print(&module, &names);
1235        let mut opts = Options::for_level(OptLevel::O2);
1236        for pass in pass::PASSES {
1237            opts.gates.add(false, pass.name()).expect("a pass in the list is a pass that exists");
1238        }
1239        let report = super::run(&mut module, &names, &opts);
1240        assert!(report.remarks.is_empty(), "a pass that did not run has nothing to report");
1241        assert_eq!(spent(&report, "fold"), Some(0), "the pass is still in the pipeline");
1242        assert_eq!(rucc_ir::print(&module, &names), before);
1243    }
1244
1245    #[test]
1246    fn the_pipeline_listing_says_which_passes_a_gate_touched() {
1247        let mut opts = Options::for_level(OptLevel::O2);
1248        // `narrow` rather than `fold`, because a gate names a pass and the level runs some of its
1249        // passes more than once. A note on one of those is printed against every run of it, and
1250        // the count at the bottom would then be counting repeats rather than what it is asking.
1251        opts.gates.add(false, "narrow=2-4").expect("narrow is a pass");
1252        let text = super::print(&opts);
1253        assert!(text.contains("3: narrow, "), "{text}");
1254        assert!(text.contains("[off for 2-4]"), "{text}");
1255        assert_eq!(text.matches('[').count(), 1, "a pass no gate mentions says nothing extra");
1256    }
1257
1258    #[test]
1259    fn every_pass_at_no_fuel_leaves_the_module_exactly_as_it_found_it() {
1260        // The check section 9.10 asks for by name, and the reason it is here rather than in each
1261        // pass is that it has to hold for every pass that is ever added.
1262        for pass in pass::PASSES {
1263            let (names, mut module) = module();
1264            let before = rucc_ir::print(&module, &names);
1265            let mut opts = Options::for_level(OptLevel::O0);
1266            // The level's own pass out of the way first, so that what this measures is the one
1267            // pass under test. A pass turned off and then on again is on, so this is right for
1268            // that pass as well as for the others.
1269            opts.toggles.push(("simplify-cfg".to_owned(), false));
1270            opts.toggles.push((pass.name().to_owned(), true));
1271            opts.fuel.insert(pass.name().to_owned(), 0);
1272            let report = super::run(&mut module, &names, &opts);
1273            assert_eq!(
1274                report.spent,
1275                vec![(pass.name(), 0)],
1276                "{} spent fuel it had none of",
1277                pass.name()
1278            );
1279            assert_eq!(
1280                rucc_ir::print(&module, &names),
1281                before,
1282                "{} transformed the module at fuel zero",
1283                pass.name()
1284            );
1285        }
1286    }
1287
1288    #[test]
1289    fn fuel_is_shared_across_the_functions_of_a_module() {
1290        let mut names = Interner::new();
1291        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
1292        let mut module = Module::new(names.intern("test.c"), &target);
1293        for which in ["f", "g"] {
1294            let mut func =
1295                Func::new(names.intern(which), Signature::new().with_returns(&[Type::int(64)]));
1296            let block = func.create_block();
1297            let mut build = Builder::new(&mut func, block);
1298            let narrow = build.iconst(Type::int(32), 7);
1299            let wide = build.unary(Opcode::SExt, narrow, Type::int(64));
1300            build.ret(&[wide]);
1301            module.add_func(func);
1302        }
1303        let mut opts = Options::for_level(OptLevel::O2);
1304        opts.fuel.insert("fold".to_owned(), 1);
1305        let report = super::run(&mut module, &names, &opts);
1306        // One fold across both functions, because fuel is per pass and per compilation. Dead
1307        // code elimination has its own and spends it on the constant the one fold orphaned.
1308        assert_eq!(spent(&report, "fold"), Some(1));
1309        assert_eq!(spent(&report, "dce"), Some(1));
1310        let text = rucc_ir::print(&module, &names);
1311        assert_eq!(text.matches("sext.i64").count(), 1, "{text}");
1312    }
1313
1314    #[test]
1315    fn global_fuel_is_spent_by_the_passes_in_order_and_the_rest_get_none() {
1316        let (names, mut module) = module();
1317        let mut opts = Options::for_level(OptLevel::O2);
1318        opts.global_fuel = Some(1);
1319        let report = super::run(&mut module, &names, &opts);
1320        // Folding is first and there is one thing to fold, so it takes the one unit and dead
1321        // code elimination gets nothing. Without the budget it would have taken the constant
1322        // that fold orphaned, which is what the other test measures.
1323        assert_eq!(spent(&report, "fold"), Some(1));
1324        assert_eq!(spent(&report, "dce"), Some(0));
1325        let text = rucc_ir::print(&module, &names);
1326        assert!(text.contains("iconst.i64 7"), "{text}");
1327        assert!(text.contains("iconst.i32 7"), "the orphaned constant is still there, {text}");
1328    }
1329
1330    #[test]
1331    fn a_budget_of_nothing_leaves_the_module_alone_and_still_runs_every_pass() {
1332        let (names, mut module) = module();
1333        let before = rucc_ir::print(&module, &names);
1334        let mut opts = Options::for_level(OptLevel::O2);
1335        opts.global_fuel = Some(0);
1336        let report = super::run(&mut module, &names, &opts);
1337        assert_eq!(rucc_ir::print(&module, &names), before);
1338        assert!(report.spent.iter().all(|(_, spent)| *spent == 0), "{:?}", report.spent);
1339        // Every pass, because a pass out of fuel is a pass that ran and did nothing rather than
1340        // a pass that was skipped, and a bisection that skipped passes would be searching a
1341        // different pipeline at every step. One line per name rather than one per place the list
1342        // names it, because what a name was given is one allowance across all of them.
1343        let mut want: Vec<&str> = opts.passes().into_iter().map(Pass::name).collect();
1344        want.sort_unstable();
1345        want.dedup();
1346        let mut got: Vec<&str> = report.spent.iter().map(|&(name, _)| name).collect();
1347        got.sort_unstable();
1348        assert_eq!(got, want);
1349    }
1350
1351    #[test]
1352    fn the_tighter_of_the_two_limits_is_the_one_that_stops_the_pass() {
1353        // A pass allowed more than the budget gets the budget.
1354        let (names, mut under) = module();
1355        let mut opts = Options::for_level(OptLevel::O2);
1356        opts.global_fuel = Some(0);
1357        opts.fuel.insert("fold".to_owned(), 9);
1358        assert_eq!(spent(&super::run(&mut under, &names, &opts), "fold"), Some(0));
1359
1360        // And a pass allowed less than the budget keeps its own limit, with the budget left
1361        // over for whatever comes after it.
1362        let (names, mut over) = module();
1363        let mut opts = Options::for_level(OptLevel::O2);
1364        opts.global_fuel = Some(9);
1365        opts.fuel.insert("fold".to_owned(), 0);
1366        let report = super::run(&mut over, &names, &opts);
1367        assert_eq!(spent(&report, "fold"), Some(0));
1368        assert_eq!(spent(&report, "dce"), Some(0), "nothing was orphaned for it to remove");
1369    }
1370
1371    #[test]
1372    fn the_pipeline_listing_says_when_there_is_a_budget_and_says_nothing_when_there_is_not() {
1373        let opts = Options::for_level(OptLevel::O2);
1374        assert!(!super::print(&opts).contains("global fuel"));
1375        let with = Options { global_fuel: Some(12), ..Options::for_level(OptLevel::O2) };
1376        assert!(super::print(&with).contains("global fuel: 12"), "{}", super::print(&with));
1377    }
1378
1379    #[test]
1380    fn a_dump_is_taken_on_the_side_that_asked_for_it_and_not_the_other() {
1381        let (names, mut module) = module();
1382        let mut opts = Options::for_level(OptLevel::O2);
1383        opts.dumps.add("after-fold").expect("a pass that exists");
1384        let report = super::run(&mut module, &names, &opts);
1385        // The level folds twice, once at the top and once after the loop pipeline, and what a
1386        // dump request names is a pass rather than a position, so both runs are written out. The
1387        // side is what this is about: not one of the two is a `before`.
1388        assert_eq!(report.dumps.len(), 2, "both runs of the pass, one dump each");
1389        assert!(
1390            report.dumps.iter().all(|dump| dump.name.ends_with("-after-fold")),
1391            "{:?}",
1392            report.dumps.iter().map(|dump| &dump.name).collect::<Vec<&String>>()
1393        );
1394        assert_eq!(report.dumps[0].name, "00-after-fold");
1395        assert!(report.dumps[0].text.contains("iconst.i64 7"));
1396    }
1397
1398    #[test]
1399    fn asking_for_all_dumps_gives_both_sides_of_every_pass() {
1400        let (interner, mut module) = module();
1401        let opts = {
1402            let mut opts = Options::for_level(OptLevel::O2);
1403            opts.dumps.add("all").expect("all is always a dump");
1404            opts
1405        };
1406        let report = super::run(&mut module, &interner, &opts);
1407        // Both sides of every pass in the level, numbered by position, whatever the level
1408        // holds. Written out of the pipeline rather than as a literal, because the point of
1409        // the test is the pairing and the numbering and not which passes exist this month.
1410        let taken: Vec<&str> = report.dumps.iter().map(|d| d.name.as_str()).collect();
1411        let expected: Vec<String> = names(&opts)
1412            .into_iter()
1413            .enumerate()
1414            .flat_map(|(at, name)| {
1415                [format!("{at:02}-before-{name}"), format!("{at:02}-after-{name}")]
1416            })
1417            .collect();
1418        assert_eq!(taken, expected);
1419        assert!(report.dumps[0].text.contains("sext.i64"));
1420        assert!(!report.dumps[1].text.contains("sext.i64"));
1421    }
1422
1423    #[test]
1424    fn every_pass_leaves_a_record_for_every_function_whether_or_not_it_had_anything_to_say() {
1425        let (names, mut module) = module();
1426        let opts = Options::for_level(OptLevel::O2);
1427        let report = super::run(&mut module, &names, &opts);
1428        let ran: Vec<&'static str> = opts.passes().into_iter().map(Pass::name).collect();
1429        // One function in the fixture, so one record per pass, and the passes in the order they
1430        // ran. A pass that found nothing is in here with an empty record, which is the point:
1431        // a pass that fires on nothing is either dead code or a bug, and output that leaves it
1432        // out cannot say which.
1433        let seen: Vec<&'static str> = report.remarks.iter().map(|it| it.pass).collect();
1434        assert_eq!(seen, ran);
1435        assert!(report.remarks.iter().all(|it| names.resolve(it.func) == "f"));
1436        assert!(
1437            report.remarks.iter().any(|it| it.pass == "simplify" && it.stats.is_empty()),
1438            "there is nothing in the fixture for the peephole to do"
1439        );
1440    }
1441
1442    #[test]
1443    fn a_pass_spends_one_unit_of_fuel_for_each_rewrite_it_reports() {
1444        // The invariant that keeps the record honest, checked over every pass rather than
1445        // written into each one. Fuel is taken immediately before a transformation and a
1446        // rewrite is recorded immediately after it, so the two counts are the same number
1447        // arrived at from two directions. A pass where they disagree either transformed without
1448        // asking, which breaks bisection, or rewrote without recording, which means the manager
1449        // did not run the verifier over what it produced.
1450        let (names, mut module) = module();
1451        let report = super::run(&mut module, &names, &Options::for_level(OptLevel::O2));
1452        for (pass, spent) in &report.spent {
1453            assert_eq!(
1454                report.totals(pass).total(Kind::Optimized),
1455                *spent,
1456                "{pass} spent {spent} units of fuel and did not say on what"
1457            );
1458        }
1459        assert!(report.spent.iter().any(|(_, spent)| *spent > 0), "nothing happened at all");
1460    }
1461
1462    #[test]
1463    fn what_the_passes_said_is_what_opt_info_prints() {
1464        let (names, mut module) = module();
1465        let report = super::run(&mut module, &names, &Options::for_level(OptLevel::O2));
1466        let text = crate::optinfo::render("t.c", &report, &names, crate::Wants::all());
1467        assert!(
1468            text.contains("t.c: f: optimized: integer instruction folded to a constant (1) [fold]"),
1469            "{text}"
1470        );
1471        assert!(
1472            text.contains(
1473                "t.c: f: optimized: instruction with no effects and no users removed (1) [dce]"
1474            ),
1475            "{text}"
1476        );
1477        // Nothing in the fixture is a miss, so asking only for the misses gets nothing back,
1478        // and that is different from the flag having been left off.
1479        let mut misses = crate::Wants::none();
1480        misses.add("missed").expect("that kind exists");
1481        assert_eq!(crate::optinfo::render("t.c", &report, &names, misses), "");
1482    }
1483
1484    #[test]
1485    fn the_verifier_says_which_function_it_refused_and_leaves_the_others_out_of_it() {
1486        // Two functions with the same foldable body, and a block in the second one that nothing
1487        // reaches, which the verifier refuses. The pass is not what put it there, and the
1488        // complaint says the pass anyway, because a pass that hands back a function the
1489        // verifier will not take is where the search has to start whoever wrote the block.
1490        let mut names = Interner::new();
1491        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
1492        let mut module = Module::new(names.intern("test.c"), &target);
1493        module.add_func(foldable(&mut names, "f"));
1494        let mut g = foldable(&mut names, "g");
1495        let stranded = g.create_block();
1496        let mut build = Builder::new(&mut g, stranded);
1497        let seven = build.iconst(Type::int(64), 7);
1498        build.ret(&[seven]);
1499        module.add_func(g);
1500
1501        // Folding on its own, because simplify-CFG would take the stranded block out and there
1502        // would be nothing left to complain about.
1503        let mut opts = Options::for_level(OptLevel::O0);
1504        opts.toggles.push(("simplify-cfg".to_owned(), false));
1505        opts.toggles.push(("fold".to_owned(), true));
1506        opts.verify = true;
1507        let report = super::run(&mut module, &names, &opts);
1508
1509        assert_eq!(report.broke.len(), 1, "{:?}", report.broke);
1510        let complaint = &report.broke[0];
1511        assert!(complaint.starts_with("the fold pass left invalid IR in g,"), "{complaint}");
1512        assert!(complaint.contains("this block is not reachable"), "{complaint}");
1513    }
1514
1515    #[test]
1516    fn a_function_a_pass_did_not_change_is_not_verified_after_it() {
1517        // The stranded block is in `f` this time and `f` has nothing to fold, so the pass runs
1518        // over an invalid function, changes nothing, and says nothing. That is the whole trade:
1519        // the verifier answers for the rewrite that just happened, and a function no rewrite
1520        // touched was already answered for when it was built.
1521        let mut names = Interner::new();
1522        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
1523        let mut module = Module::new(names.intern("test.c"), &target);
1524        let mut f = Func::new(names.intern("f"), Signature::new().with_returns(&[Type::int(64)]));
1525        for _ in 0..2 {
1526            let block = f.create_block();
1527            let mut build = Builder::new(&mut f, block);
1528            let seven = build.iconst(Type::int(64), 7);
1529            build.ret(&[seven]);
1530        }
1531        module.add_func(f);
1532        module.add_func(foldable(&mut names, "g"));
1533
1534        let mut opts = Options::for_level(OptLevel::O0);
1535        opts.toggles.push(("simplify-cfg".to_owned(), false));
1536        opts.toggles.push(("fold".to_owned(), true));
1537        opts.verify = true;
1538        let report = super::run(&mut module, &names, &opts);
1539
1540        assert!(report.broke.is_empty(), "{:?}", report.broke);
1541        // And it did run on it, so this is the verifier staying quiet rather than the pass
1542        // being skipped.
1543        assert!(spoke_about(&report, "fold", "f", &names));
1544    }
1545
1546    #[test]
1547    fn a_dump_of_a_pass_that_does_not_exist_is_refused_rather_than_ignored() {
1548        let mut dumps = Dumps::default();
1549        assert!(dumps.add("after-no-such-pass").is_err());
1550        assert!(dumps.add("sideways-fold").is_err());
1551        assert!(dumps.add("fold").is_err());
1552        assert!(dumps.is_empty());
1553    }
1554}