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