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