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