rucc_opt/scev.rs
1//! Scalar evolution: how a value changes across the iterations of a loop, and how many
2//! iterations there are.
3//!
4//! Design: `spec/optimizer/07-loops-and-scev.md` sections 7.4 through 7.7. This is the second
5//! half of document 07 and it answers the last two of the four questions section 7.6 says loop
6//! analysis exists for. The first two are in [`crate::loops`].
7//!
8//! # Chains of recurrences, and how much of one
9//!
10//! GCC writes how a value changes as a chain of recurrences, `{base, +, step}`, meaning a value
11//! that is `base` on the first iteration and `step` more on each one after. The representation is
12//! good because it is closed under the operations anyone wants: adding two chrecs of the same
13//! loop adds componentwise, multiplying by something invariant scales both parts, and evaluating
14//! one at a given iteration is arithmetic rather than a special case. That closure is why
15//! `j = 2 * i + 3` is as easy as `i = i + 1`, and pattern matching the second would run out of
16//! road on the first.
17//!
18//! Section 7.4 says what rucc builds and it is a subset: affine chrecs only. A value is
19//! invariant, or `{base, +, step}` with both parts invariant, or unknown. Addition, subtraction,
20//! multiplication by an invariant, shifting by a constant, and extension where the extension
21//! provably does not wrap. Nothing polynomial and nothing mutually recursive. That covers every
22//! induction variable a C programmer writes and every array subscript document 31 could use, and
23//! what it leaves out of GCC's four thousand lines is the part serving Fortran and the polyhedral
24//! framework.
25//!
26//! The one extension past affine is pointer chrecs, because C loops walk pointers and `p = p + 1`
27//! is `i = i + 1` with a scale. A `ptr_add` is addition with the byte offset as the step, which
28//! is the difference between analysing half of real C loops and analysing nearly all of them.
29//!
30//! # Trip counts, and the part that is uncomfortable
31//!
32//! Given an exit that compares an affine chrec against something invariant, solving for the
33//! iteration at which the comparison first fails is arithmetic. What makes it hard is that the
34//! answer is almost always conditional: on the loop being entered at all, and on the induction
35//! variable not wrapping before it gets there. Section 7.5 says a trip count returned without its
36//! assumptions is a miscompilation generator, and that the temptation to return one is strong
37//! because the assumptions are usually true.
38//!
39//! So [`Bound`] carries them and there is no way to read the count without seeing them.
40//! [`Bound::parts`] hands back both, and [`Bound::proven`] hands back the count only when there
41//! is nothing left to prove. A caller that means to emit a runtime check reads the assumptions
42//! and emits it, and a caller that forgets cannot get at the number.
43//!
44//! [`Bound`] and [`Estimate`] are different types on purpose. A bound is used for correctness, an
45//! estimate is used to decide whether a transformation is worth doing, and section 7.5 calls
46//! conflating them a category error that costs correctness. GCC keeps them apart as
47//! `max_loop_iterations` and `estimate_numbers_of_iterations` and the names do not stop anyone.
48//! Different structs do.
49
50use std::collections::HashMap;
51
52use rucc_ir::{Block, Def, Extra, Flags, Func, Imm, Inst, IntPred, Opcode, Type, Value};
53
54use crate::cfg::Cfg;
55use crate::loops::{LoopId, Loops};
56
57/// How deep the search for a step walks back through arithmetic.
58///
59/// The chain from a header parameter to the value fed back to it is two or three instructions in
60/// anything a person writes, and the walk terminates on its own because SSA has no cycles except
61/// through block parameters. The limit is here so a generated function with a thousand additions
62/// in the increment costs a bounded amount rather than a stack.
63const STEP_LIMIT: u32 = 16;
64
65/// How many blocks that do nothing but pass a value on the walk reads through.
66///
67/// One is what a canonicalized loop has. The limit is here for the same reason the one above is,
68/// which is that a generated function can have a chain of them and the cost of following it should
69/// not depend on how long somebody made it.
70const FORWARD_LIMIT: u32 = 8;
71
72/// How many times a loop is assumed to run when nothing better is known.
73///
74/// GCC's `--param avg-loop-niter`, whose default is the same number. It is a guess and it is only
75/// ever used through [`Estimate`], which is only ever used to decide whether something is worth
76/// doing.
77const ASSUMED_ITERATIONS: u64 = 10;
78
79/// A value that does not change inside the loop, read as `scale * value + offset`.
80///
81/// The `value` is a value defined outside the loop, or `None` when the expression is a plain
82/// number. Keeping the shape rather than a bare [`Value`] is what lets `j = 2 * i + 3` come out
83/// as `{3, +, 2}` instead of unknown: the base and the step of that chrec are expressions nothing
84/// in the function computes, so a representation that could only name existing values would have
85/// to give up.
86///
87/// Arithmetic on two of these is refused when both are symbolic and the symbols differ, because
88/// `x + y` is not of this shape. That is the boundary of the subset and it is where the answer
89/// becomes unknown rather than wrong.
90#[derive(Clone, Copy, Debug, PartialEq, Eq)]
91pub struct Invariant {
92 /// What it is built on, or `None` for a plain number.
93 pub value: Option<Value>,
94 /// How many of it.
95 pub scale: i128,
96 /// What is added to it.
97 pub offset: i128,
98}
99
100impl Invariant {
101 /// A plain number.
102 #[must_use]
103 pub fn number(offset: i128) -> Self {
104 Self { value: None, scale: 0, offset }
105 }
106
107 /// One of a value.
108 #[must_use]
109 pub fn of(value: Value) -> Self {
110 Self { value: Some(value), scale: 1, offset: 0 }
111 }
112
113 /// The number this is, when it is one.
114 #[must_use]
115 pub fn as_number(self) -> Option<i128> {
116 (self.value.is_none() || self.scale == 0).then_some(self.offset)
117 }
118
119 /// Whether this is the number zero.
120 #[must_use]
121 pub fn is_zero(self) -> bool {
122 self.as_number() == Some(0)
123 }
124
125 /// The symbol both expressions are built on, when they agree on one or one has none.
126 fn shared(self, other: Self) -> Option<Option<Value>> {
127 match (self.as_number().is_some(), other.as_number().is_some()) {
128 (true, _) => Some(other.value),
129 (_, true) => Some(self.value),
130 _ => (self.value == other.value).then_some(self.value),
131 }
132 }
133
134 /// The two added, when the sum is of this shape.
135 #[must_use]
136 pub fn plus(self, other: Self) -> Option<Self> {
137 let value = self.shared(other)?;
138 Some(Self {
139 value,
140 scale: self.scale.checked_add(other.scale)?,
141 offset: self.offset.checked_add(other.offset)?,
142 })
143 }
144
145 /// The second subtracted from the first, when the difference is of this shape.
146 #[must_use]
147 pub fn minus(self, other: Self) -> Option<Self> {
148 self.plus(other.negated()?)
149 }
150
151 /// This with its sign flipped.
152 #[must_use]
153 pub fn negated(self) -> Option<Self> {
154 Some(Self {
155 value: self.value,
156 scale: self.scale.checked_neg()?,
157 offset: self.offset.checked_neg()?,
158 })
159 }
160
161 /// The two multiplied, which needs one of them to be a plain number.
162 #[must_use]
163 pub fn times(self, other: Self) -> Option<Self> {
164 let (symbol, by) = match (self.as_number(), other.as_number()) {
165 (Some(by), _) => (other, by),
166 (_, Some(by)) => (self, by),
167 _ => return None,
168 };
169 Some(Self {
170 value: symbol.value,
171 scale: symbol.scale.checked_mul(by)?,
172 offset: symbol.offset.checked_mul(by)?,
173 })
174 }
175}
176
177/// How a value changes from one iteration of a loop to the next.
178#[derive(Clone, Copy, Debug, PartialEq, Eq)]
179pub enum Evolution {
180 /// The same on every iteration.
181 Invariant(Invariant),
182 /// `{base, +, step}`: `base` the first time round and `step` more each time after.
183 Affine(Chrec),
184 /// Not something this analysis describes. Never a claim that the value does not evolve.
185 Unknown,
186}
187
188impl Evolution {
189 /// The chrec, when this is one.
190 #[must_use]
191 pub fn chrec(self) -> Option<Chrec> {
192 match self {
193 Self::Affine(chrec) => Some(chrec),
194 _ => None,
195 }
196 }
197
198 /// The invariant expression, when this is one.
199 #[must_use]
200 pub fn invariant(self) -> Option<Invariant> {
201 match self {
202 Self::Invariant(inv) => Some(inv),
203 _ => None,
204 }
205 }
206}
207
208/// An affine chain of recurrences, `{base, +, step}`, evolving in a named type.
209///
210/// The type is not decoration. `{0, +, 1}` in `unsigned char` is not the sequence `0, 1, 2, ...`,
211/// it is that sequence modulo two hundred and fifty six, and section 7.7 says this is where a
212/// naive implementation is wrong constantly and in ways that pass every test written by someone
213/// thinking in `int`. Every operation here checks the type and every one that cannot stay right
214/// in it answers unknown.
215#[derive(Clone, Copy, Debug, PartialEq, Eq)]
216pub struct Chrec {
217 /// What the value is on the first iteration.
218 pub base: Invariant,
219 /// What is added each time round.
220 pub step: Invariant,
221 /// The type it evolves in, which is what says when it wraps.
222 pub ty: Type,
223 /// What the instruction that increments it promised. `nsw` means the sequence does not wrap
224 /// when read as signed and `nuw` means it does not when read as unsigned, and both come from
225 /// the increment rather than from anything this analysis proved.
226 pub flags: Flags,
227}
228
229impl Chrec {
230 /// Whether the sequence is known not to wrap under the reading this predicate takes.
231 #[must_use]
232 pub fn does_not_wrap(self, signed: bool) -> bool {
233 self.flags.contains(if signed { Flags::NSW } else { Flags::NUW })
234 }
235}
236
237/// Something that has to be true for a trip count to be the right answer.
238///
239/// Section 7.5 asks for exactly this: not a trip count but a trip count plus a predicate under
240/// which it holds, so the consumer either proves the predicate, emits a runtime check for it, or
241/// gives up. These are the predicates.
242#[derive(Clone, Copy, Debug, PartialEq, Eq)]
243pub enum Assumption {
244 /// The counter starts on the near side of its limit, so the distance between them is a
245 /// number that is not negative.
246 ///
247 /// For a loop ending on an ordering this is the loop being entered at all.
248 /// `for (i = 0; i < n; i++)` with `n` of zero runs no times and the distance is zero, but `n`
249 /// of minus one also runs no times and the distance is minus one, so a count taken from the
250 /// distance has to be told which case it is in. For a loop ending on `!=` it is the limit
251 /// being somewhere the counter is heading, because one stepping away from its limit never
252 /// arrives.
253 ///
254 /// Only ever present on a symbolic count. When the distance is a number the sign of it is
255 /// there to be read, so this is settled rather than assumed.
256 Approaching,
257 /// The induction variable does not wrap in its own type before the exit is taken.
258 ///
259 /// Present whenever the increment did not carry the matching `nsw` or `nuw` flag. With the
260 /// flag there is nothing to assume, because the flag is the promise.
261 NoWrap(Chrec),
262 /// Signed overflow is undefined here, which is what makes `for (int i = 0; i <= n; i++)`
263 /// finite.
264 ///
265 /// GCC infers loop bounds from this in `infer_loop_bounds_from_signedness`, and it is the
266 /// single most common source of a report that the compiler broke a working program. It is
267 /// recorded rather than assumed silently so that `-fwrapv` can withdraw the count and so that
268 /// a dump can name it.
269 StrictOverflow,
270}
271
272impl Assumption {
273 /// What it says, in a line, for a dump to print.
274 ///
275 /// Section 7.5 asks that every inference of this kind be dumpable and say what it rests on,
276 /// because a user who has been bitten by one deserves a command that tells them which line
277 /// the compiler used against them. This is the sentence that command prints.
278 #[must_use]
279 pub fn describe(&self) -> String {
280 match self {
281 Self::Approaching => "the counter starts on the near side of its limit".to_string(),
282 Self::NoWrap(chrec) => {
283 format!("the induction variable does not wrap in i{}", chrec.ty.bits())
284 }
285 Self::StrictOverflow => {
286 "signed overflow is undefined, so -fwrapv withdraws this count".to_string()
287 }
288 }
289 }
290}
291
292/// How many iterations, as a number or as an expression.
293#[derive(Clone, Copy, Debug, PartialEq, Eq)]
294pub enum Count {
295 /// Exactly this many.
296 Exact(u128),
297 /// This many, worked out from something the loop does not change.
298 Symbolic(Invariant),
299}
300
301/// Which reading of its operands the test the count came from took.
302///
303/// It matters to anybody widening the value a symbolic count is built out of. The count is the
304/// distance to the limit of the exit test, the limit is a value of the counter's own type, and
305/// what that value means is the reading its test took. A limit past the middle of a thirty two bit
306/// type is a large number to an unsigned test and a negative one to a signed test, and a consumer
307/// that sign extends what an unsigned test compared has turned a loop over three billion elements
308/// into a loop that runs no times.
309#[derive(Clone, Copy, Debug, PartialEq, Eq)]
310pub enum Reading {
311 /// The test read its operands as signed, so widening the count means sign extending it.
312 Signed,
313 /// The test read them as unsigned, so widening the count means zero extending it.
314 Unsigned,
315}
316
317/// How many times a loop runs at most, and what that rests on.
318///
319/// For correctness. A pass that deletes an iteration, peels one off, or decides a memory access
320/// is in bounds needs one of these. The count cannot be read without the assumptions, which is
321/// section 7.7's defence against a caller proving two of three and forgetting the third.
322#[derive(Clone, Debug, PartialEq, Eq)]
323pub struct Bound {
324 count: Count,
325 assumptions: Vec<Assumption>,
326 reading: Reading,
327}
328
329impl Bound {
330 /// The count and everything it rests on, together, because they cannot be asked for apart.
331 #[must_use]
332 pub fn parts(&self) -> (Count, &[Assumption]) {
333 (self.count, &self.assumptions)
334 }
335
336 /// How the value a symbolic count is built out of has to be read.
337 ///
338 /// Meaningless on a count that is a number, since a number has already been read.
339 #[must_use]
340 pub fn reading(&self) -> Reading {
341 self.reading
342 }
343
344 /// What has to be proved before the count means anything.
345 #[must_use]
346 pub fn assumptions(&self) -> &[Assumption] {
347 &self.assumptions
348 }
349
350 /// The count, for a caller with nothing left to prove.
351 ///
352 /// `None` does not mean the count is unknown. It means there are assumptions and this is not
353 /// the accessor for reading a count that has them.
354 #[must_use]
355 pub fn proven(&self) -> Option<Count> {
356 self.assumptions.is_empty().then_some(self.count)
357 }
358
359 /// The count, for a caller compiling a language where signed overflow is undefined.
360 ///
361 /// [`Bound::proven`] answers nothing for any `for (int i = 0; i < n; i++)` in any C program,
362 /// because `solve` puts [`Assumption::StrictOverflow`] on every count taken from a signed
363 /// test, and a pass built on `proven` alone is a pass that never fires. What that assumption
364 /// says is that the count rests on signed overflow being undefined, and `-fwrapv` is
365 /// implemented in `rucc-lower` by not setting `nsw` rather than by a flag anything down here
366 /// reads. So an increment that still carries `nsw` under `-fwrapv` does not exist, and a bound
367 /// with `StrictOverflow` and nothing else on it is a bound whose counter the front end
368 /// promised does not wrap. That promise is exactly what the assumption wanted.
369 ///
370 /// [`Assumption::NoWrap`] is the case where there is no such promise, and it is refused here.
371 /// So is [`Assumption::Approaching`], though only in passing, because it never appears on a
372 /// count that is a number.
373 #[must_use]
374 pub fn under_undefined_overflow(&self) -> Option<Count> {
375 self.assumptions
376 .iter()
377 .all(|rests_on| matches!(rests_on, Assumption::StrictOverflow))
378 .then_some(self.count)
379 }
380}
381
382/// How many times a loop probably runs.
383///
384/// For cost decisions and never for correctness. A pass asking whether unrolling pays for itself
385/// wants one of these, and it is fine for the answer to be a guess, because being wrong makes the
386/// code slower rather than wrong. Nothing here can be turned into a [`Bound`].
387#[derive(Clone, Copy, Debug, PartialEq, Eq)]
388pub struct Estimate {
389 iterations: u64,
390 guessed: bool,
391}
392
393impl Estimate {
394 /// The number to do arithmetic with.
395 #[must_use]
396 pub fn iterations(self) -> u64 {
397 self.iterations
398 }
399
400 /// Whether nothing was known and this is the default.
401 #[must_use]
402 pub fn is_guess(self) -> bool {
403 self.guessed
404 }
405}
406
407/// An exit test, read so that the loop keeps going while it holds.
408///
409/// Not public. It is the shape [`Scev::bound_at`] and [`Scev::holds`] both want out of the same
410/// branch, and what either of them says about it is what the outside sees.
411#[derive(Clone, Copy, Debug)]
412struct Test {
413 /// The side that moves, with the predicate already turned round to put it on the left.
414 chrec: Chrec,
415 /// The side that does not.
416 limit: Invariant,
417 /// The comparison that has to hold for the loop to go round again.
418 pred: IntPred,
419 /// Whether every iteration that goes round asks it.
420 each: bool,
421}
422
423/// The analysis, which works out an answer when asked and remembers it.
424///
425/// Demand driven and memoized, per section 7.8, because the cost of scalar evolution is a
426/// function of how many distinct values get asked about rather than of the size of the function.
427/// The cache holds one loop's worth of answers per loop and the whole thing is thrown away when
428/// anything about the loops changes, which per document 04.4 is any pass that touches one.
429#[derive(Debug)]
430pub struct Scev<'a> {
431 func: &'a Func,
432 cfg: &'a Cfg,
433 loops: &'a Loops,
434 known: HashMap<(LoopId, Value), Evolution>,
435 held: HashMap<LoopId, Option<Chrec>>,
436}
437
438impl<'a> Scev<'a> {
439 /// A fresh analysis over these loops, knowing nothing yet.
440 #[must_use]
441 pub fn new(func: &'a Func, cfg: &'a Cfg, loops: &'a Loops) -> Self {
442 Self { func, cfg, loops, known: HashMap::new(), held: HashMap::new() }
443 }
444
445 /// How this value changes across the iterations of this loop.
446 ///
447 /// The way in, and what it does before answering is settle `Scev::holds` for the loop. That has
448 /// to happen out here rather than at the point `Scev::extend` wants it, because settling it
449 /// means asking about other values and `Scev::at` parks a marker on the value it is working on.
450 /// Asked from in there, the answer would depend on what was already in flight.
451 pub fn evolution(&mut self, id: LoopId, value: Value) -> Evolution {
452 self.holds(id);
453 self.at(id, value)
454 }
455
456 /// How this value changes, with the loop's own facts already settled.
457 fn at(&mut self, id: LoopId, value: Value) -> Evolution {
458 if let Some(&known) = self.known.get(&(id, value)) {
459 return known;
460 }
461 // Unknown while the answer is being worked out, so the cycle from a header parameter back
462 // to itself terminates instead of asking the same question forever. Anything that reaches
463 // the parameter again gets unknown and the shape it was matching fails, which is the
464 // right answer for a value defined in terms of itself through arithmetic this does not
465 // describe.
466 self.known.insert((id, value), Evolution::Unknown);
467 let found = self.compute(id, value);
468 self.known.insert((id, value), found);
469 found
470 }
471
472 /// How many times this loop runs at most, and what that rests on.
473 ///
474 /// Any one exit gives a valid upper bound, because a loop cannot run more times than the
475 /// first exit that fires, so this takes the first exit it can solve rather than the smallest.
476 /// That is `max_loop_iterations` and not `estimate_numbers_of_iterations`, which is why the
477 /// answer is a [`Bound`].
478 pub fn bound(&mut self, id: LoopId) -> Option<Bound> {
479 self.holds(id);
480 let exits: Vec<Block> = self.loops.exits(id).iter().map(|exit| exit.from).collect();
481 exits.into_iter().find_map(|from| self.bound_at(id, from))
482 }
483
484 /// The counter an exit test of this loop keeps inside its own type, when there is one.
485 ///
486 /// [`bounded_by_its_test`] is the argument and this is where its answer is written down as a
487 /// fact about the loop rather than spent on one trip count. What it buys is [`Scev::extend`]:
488 /// an unsigned counter carries no `nuw`, so widening anything built out of one used to be
489 /// refused, and the test that holds the counter holds everything walking beside it.
490 ///
491 /// Settled once per loop and then read. It is settled from [`Scev::evolution`] and
492 /// [`Scev::bound`], which are the two ways in, so that it is worked out with nothing in flight.
493 /// The cache for the loop is emptied afterwards, because the answers already in it were worked
494 /// out while this was still unknown and a conservative answer that stayed would make what the
495 /// analysis says depend on which question was asked first.
496 fn holds(&mut self, id: LoopId) -> Option<Chrec> {
497 if let Some(&known) = self.held.get(&id) {
498 return known;
499 }
500 // Unknown while it is being worked out, which is what stops the recursion below from
501 // asking the same question forever, and which is why the cache is emptied after.
502 self.held.insert(id, None);
503 let exits: Vec<Block> = self.loops.exits(id).iter().map(|exit| exit.from).collect();
504 let found = exits.into_iter().find_map(|from| {
505 let test = self.test_at(id, from)?;
506 let step = test.chrec.step.as_number()?;
507 (test.each && bounded_by_its_test(test.pred, step)).then_some(test.chrec)
508 });
509 self.held.insert(id, found);
510 self.known.retain(|&(of, _), _| of != id);
511 found
512 }
513
514 /// How many times this loop probably runs.
515 pub fn estimate(&mut self, id: LoopId) -> Estimate {
516 match self.bound(id).map(|bound| bound.count) {
517 Some(Count::Exact(exact)) => {
518 Estimate { iterations: u64::try_from(exact).unwrap_or(u64::MAX), guessed: false }
519 }
520 _ => Estimate { iterations: ASSUMED_ITERATIONS, guessed: true },
521 }
522 }
523
524 /// The evolution of a value nothing is known about yet.
525 fn compute(&mut self, id: LoopId, value: Value) -> Evolution {
526 if let Some(invariant) = self.invariant(id, value) {
527 return Evolution::Invariant(invariant);
528 }
529 match self.func[value].def {
530 Def::Param { block, index } if block == self.loops.header(id) => {
531 self.at_header(id, value, index as usize)
532 }
533 // A parameter of a block inside the loop that is not the header takes a different
534 // value depending on which way control came, and describing that is a job for the
535 // value range work of document 10 rather than for a chrec. Unless there is only one
536 // way in, in which case it does not.
537 Def::Param { .. } => match self.forwarded(value) {
538 same if same == value => Evolution::Unknown,
539 through => self.at(id, through),
540 },
541 Def::Result { inst, .. } => self.at_inst(id, inst, value),
542 }
543 }
544
545 /// The value as an expression that does not change inside the loop, if it is one.
546 fn invariant(&self, id: LoopId, value: Value) -> Option<Invariant> {
547 if let Some((imm, ty)) = constant(self.func, value) {
548 return Some(Invariant::number(imm.signed(ty)));
549 }
550 // A constant is invariant wherever it sits, which is why it is asked about first. Anything
551 // else has to be defined outside the loop.
552 self.loops.is_invariant(self.func, id, value).then(|| Invariant::of(value))
553 }
554
555 /// The evolution of a parameter of the loop header, which is where an induction variable is.
556 ///
557 /// The parameter takes one value on the way in and another on the way round, which is what
558 /// other IRs spell as a phi node. If the way round is the parameter plus something invariant,
559 /// the parameter is an affine chrec and that something is its step.
560 fn at_header(&mut self, id: LoopId, value: Value, index: usize) -> Evolution {
561 let (func, cfg, loops) = (self.func, self.cfg, self.loops);
562 let header = loops.header(id);
563 // Section 7.3 wants exactly one latch and the canonicalizer makes one. Two of them means
564 // two ways round with two different increments, and picking one would be a guess.
565 let [latch] = loops.latches(id) else { return Evolution::Unknown };
566 let mut entering = None;
567 let mut around = None;
568 for &pred in cfg.predecessors(header) {
569 let Some(arg) = argument(func, pred, header, index) else { return Evolution::Unknown };
570 let arg = self.forwarded(arg);
571 let slot = if pred == *latch { &mut around } else { &mut entering };
572 if slot.replace(arg).is_some_and(|old| old != arg) {
573 return Evolution::Unknown;
574 }
575 }
576 let (Some(entering), Some(around)) = (entering, around) else { return Evolution::Unknown };
577 let Some(base) = self.invariant(id, entering) else { return Evolution::Unknown };
578 let Some((step, flags)) = self.step(id, around, value, 0) else {
579 return Evolution::Unknown;
580 };
581 affine(base, step, func[value].ty, flags)
582 }
583
584 /// The value a block parameter stands for, when there is only one way into its block.
585 ///
586 /// This is not an analysis, it is undoing a rename. A block with one predecessor has one value
587 /// for each of its parameters and it is the argument that predecessor passes, so reading
588 /// through it loses nothing and assumes nothing.
589 ///
590 /// It is here because of what canonicalization does. `crate::canon` splits the back edge of a
591 /// loop to give it a latch of its own, and after that the value going round the loop is not the
592 /// increment the loop computed, it is a parameter of a block that does nothing but pass the
593 /// increment on. Without this, every counted loop the pipeline actually produces looks like a
594 /// loop whose counter comes from somewhere unknown, and the trip count of a `for` loop in a
595 /// real function comes back as nothing.
596 fn forwarded(&self, value: Value) -> Value {
597 let mut value = value;
598 for _ in 0..FORWARD_LIMIT {
599 let Def::Param { block, index } = self.func[value].def else { return value };
600 let [pred] = self.cfg.predecessors(block) else { return value };
601 let Some(arg) = argument(self.func, *pred, block, index as usize) else { return value };
602 if arg == value {
603 return value;
604 }
605 value = arg;
606 }
607 value
608 }
609
610 /// What is added to `of` to get `value`, and what the additions promised.
611 ///
612 /// Written as its own walk rather than as the general combination below, because at the point
613 /// this runs the parameter's own evolution is not known yet and the general walk would ask
614 /// for it and get unknown.
615 fn step(&self, id: LoopId, value: Value, of: Value, depth: u32) -> Option<(Invariant, Flags)> {
616 let value = self.forwarded(value);
617 if value == of {
618 // Nothing added yet, and nothing has had a chance to overflow either.
619 return Some((Invariant::number(0), Flags::NSW.union(Flags::NUW)));
620 }
621 if depth >= STEP_LIMIT {
622 return None;
623 }
624 let Def::Result { inst, .. } = self.func[value].def else { return None };
625 let data = &self.func[inst];
626 let args = &self.func[data.args];
627 let (&lhs, &rhs) = (args.first()?, args.get(1)?);
628 let combine = |carried: (Invariant, Flags), other: Invariant, subtract: bool| {
629 let (delta, flags) = carried;
630 let moved = if subtract { delta.minus(other)? } else { delta.plus(other)? };
631 Some((moved, flags.intersection(data.flags)))
632 };
633 match data.opcode {
634 Opcode::Add => {
635 if let Some(carried) = self.step(id, lhs, of, depth + 1) {
636 return combine(carried, self.invariant(id, rhs)?, false);
637 }
638 combine(self.step(id, rhs, of, depth + 1)?, self.invariant(id, lhs)?, false)
639 }
640 Opcode::Sub => {
641 combine(self.step(id, lhs, of, depth + 1)?, self.invariant(id, rhs)?, true)
642 }
643 // A pointer walks by bytes, and only the pointer side can be the one carrying the
644 // induction variable. The offset is the step, which is the element size the front end
645 // already multiplied in.
646 Opcode::PtrAdd => {
647 combine(self.step(id, lhs, of, depth + 1)?, self.invariant(id, rhs)?, false)
648 }
649 _ => None,
650 }
651 }
652
653 /// The evolution of an instruction's result, from the evolutions of its operands.
654 fn at_inst(&mut self, id: LoopId, inst: Inst, value: Value) -> Evolution {
655 let func = self.func;
656 let data = &func[inst];
657 let (opcode, flags) = (data.opcode, data.flags);
658 let args = &func[data.args];
659 let ty = func[value].ty;
660 let Some(&lhs) = args.first() else { return Evolution::Unknown };
661 match opcode {
662 Opcode::Add | Opcode::PtrAdd => {
663 let Some(&rhs) = args.get(1) else { return Evolution::Unknown };
664 let (left, right) = (self.at(id, lhs), self.at(id, rhs));
665 combine(left, right, ty, flags, false)
666 }
667 Opcode::Sub => {
668 let Some(&rhs) = args.get(1) else { return Evolution::Unknown };
669 let (left, right) = (self.at(id, lhs), self.at(id, rhs));
670 combine(left, right, ty, flags, true)
671 }
672 Opcode::Mul => {
673 let Some(&rhs) = args.get(1) else { return Evolution::Unknown };
674 let (left, right) = (self.at(id, lhs), self.at(id, rhs));
675 scale(left, right, ty, flags)
676 }
677 // A shift by a constant is a multiplication by a power of two, and only by a constant:
678 // a variable count is invariant in the loop and still not a number this can multiply
679 // by. A count at or above the width is poison rather than a shift to zero, so the
680 // range is checked here rather than assumed.
681 Opcode::Shl => {
682 let Some(&rhs) = args.get(1) else { return Evolution::Unknown };
683 let Some((count, count_ty)) = constant(func, rhs) else {
684 return Evolution::Unknown;
685 };
686 let count = count.unsigned();
687 if count >= u128::from(ty.bits()) || !count_ty.is_int() {
688 return Evolution::Unknown;
689 }
690 let by = Evolution::Invariant(Invariant::number(1i128 << count));
691 scale(self.at(id, lhs), by, ty, flags)
692 }
693 Opcode::SExt | Opcode::ZExt => self.extend(id, opcode, lhs, ty),
694 // A truncation is a wrap by construction, so a chrec through one describes a sequence
695 // that restarts, and this does not have a representation for that.
696 _ => Evolution::Unknown,
697 }
698 }
699
700 /// A chrec widened, which needs the sequence not to wrap at the narrow width.
701 ///
702 /// Section 7.4 allows extension only where the extension provably does not wrap, and the first
703 /// proof here is the flag the increment carries. `nsw` on the increment is the promise that the
704 /// signed sequence does not wrap, which is exactly what makes the wide sequence the same
705 /// numbers as the narrow one.
706 ///
707 /// The second proof is the loop's own exit test, through [`Scev::holds`] and [`trails`], and it
708 /// is here because of what an unsigned counter looks like. `for (unsigned i = 0; i < n; i++)`
709 /// carries no `nuw`, because C says unsigned arithmetic wraps, so `a[i]` on that counter used
710 /// to come back unwidened and every bounds check in the loop stayed where it was. The test that
711 /// keeps the counter inside its type keeps everything walking beside it inside too.
712 ///
713 /// Both parts have to be plain numbers. A symbolic base or step is a value of the narrow type
714 /// and the widened chrec would need it widened too, which is an expression nothing computes
715 /// and which [`Invariant`] has no room to describe. Saying so is the honest answer, the case
716 /// that matters most is a counter from a constant by a constant, and lifting the restriction
717 /// is work for whoever needs a symbolic one.
718 fn extend(&mut self, id: LoopId, opcode: Opcode, from: Value, to: Type) -> Evolution {
719 let narrow = self.func[from].ty;
720 let signed = opcode == Opcode::SExt;
721 let held = self.held.get(&id).copied().flatten();
722 let settled = |chrec: Chrec| {
723 chrec.does_not_wrap(signed) || (!signed && held.is_some_and(|held| trails(chrec, held)))
724 };
725 match self.at(id, from) {
726 Evolution::Invariant(inv) => match inv.as_number() {
727 // A number read at the narrow width means the same thing at the wide one under
728 // sign extension, and under zero extension once it is not negative.
729 Some(number) if signed || number >= 0 => Evolution::Invariant(inv),
730 _ => Evolution::Unknown,
731 },
732 Evolution::Affine(chrec) if chrec.ty == narrow && settled(chrec) => {
733 let (Some(base), Some(step)) = (chrec.base.as_number(), chrec.step.as_number())
734 else {
735 return Evolution::Unknown;
736 };
737 Evolution::Affine(Chrec {
738 base: Invariant::number(base),
739 step: Invariant::number(step),
740 ty: to,
741 flags: chrec.flags,
742 })
743 }
744 _ => Evolution::Unknown,
745 }
746 }
747
748 /// The trip count from the exit leaving this block, if this exit can be solved.
749 fn bound_at(&mut self, id: LoopId, from: Block) -> Option<Bound> {
750 let test = self.test_at(id, from)?;
751 solve(test.chrec, test.limit, test.pred, test.each)
752 }
753
754 /// The exit test leaving this block, read into the pieces its two readers want.
755 ///
756 /// [`Scev::bound_at`] spends it on a trip count and [`Scev::holds`] spends it on whether the
757 /// counter can wrap, and both want the same reading of the same branch, so the reading is
758 /// written once.
759 fn test_at(&mut self, id: LoopId, from: Block) -> Option<Test> {
760 let func = self.func;
761 let term = func.terminator(from)?;
762 if func[term].opcode != Opcode::BrIf {
763 return None;
764 }
765 let args = &func[func[term].args];
766 let &cond = args.first()?;
767 let calls = &func[func.target_list(term)];
768 let (&taken, ¬_taken) = (calls.first()?, calls.get(1)?);
769 // Which arm keeps going. If both stay in or both leave, the branch is not the test that
770 // ends the loop and there is nothing here to solve.
771 let stays = match (
772 self.loops.contains(id, taken.block),
773 self.loops.contains(id, not_taken.block),
774 ) {
775 (true, false) => true,
776 (false, true) => false,
777 _ => return None,
778 };
779
780 let Def::Result { inst, .. } = func[cond].def else { return None };
781 if func[inst].opcode != Opcode::ICmp {
782 return None;
783 }
784 let Extra::IntPred(pred) = func[inst].extra else { return None };
785 // The loop keeps going while the test says so, so an exit taken when the test is true is
786 // an exit whose continuing condition is the opposite one.
787 let pred = if stays { pred } else { invert(pred) };
788 let operands = &func[func[inst].args];
789 let (&lhs, &rhs) = (operands.first()?, operands.get(1)?);
790
791 // One side evolves and the other does not. Swapping puts the one that evolves on the left
792 // and turns the predicate round with it, so only one direction has to be solved.
793 let (chrec, limit, pred) = match (self.at(id, lhs), self.at(id, rhs)) {
794 (Evolution::Affine(chrec), other) => (chrec, other.invariant()?, pred),
795 (other, Evolution::Affine(chrec)) => (chrec, other.invariant()?, swap(pred)),
796 _ => return None,
797 };
798
799 // Whether every iteration that goes round asks this test. The header runs on all of them by
800 // being the header. A latch runs on all of them only when it is the loop's one latch, since
801 // with two of them an iteration can go round the other and never reach the test. Anywhere
802 // else is a test under a condition, which [`bounded_by_its_test`] must not be given.
803 //
804 // The one latch is written out rather than taken for granted. `at_header` refuses a loop
805 // with two of them already, so nothing reaching here has two, but the two conditions are
806 // about different things and a later loosening of that one should not quietly loosen this.
807 let each = from == self.loops.header(id) || self.loops.latches(id) == [from];
808 Some(Test { chrec, limit, pred, each })
809 }
810}
811
812/// Two evolutions added, or subtracted when asked.
813fn combine(left: Evolution, right: Evolution, ty: Type, flags: Flags, subtract: bool) -> Evolution {
814 let apply = |a: Invariant, b: Invariant| if subtract { a.minus(b) } else { a.plus(b) };
815 match (left, right) {
816 (Evolution::Invariant(a), Evolution::Invariant(b)) => {
817 apply(a, b).map_or(Evolution::Unknown, Evolution::Invariant)
818 }
819 (Evolution::Affine(chrec), Evolution::Invariant(b)) => {
820 // Adding something that does not move only moves the base.
821 let Some(base) = apply(chrec.base, b) else { return Evolution::Unknown };
822 affine(base, chrec.step, ty, flags.intersection(chrec.flags))
823 }
824 (Evolution::Invariant(a), Evolution::Affine(chrec)) => {
825 let (Some(base), Some(step)) = (
826 apply(a, chrec.base),
827 if subtract { chrec.step.negated() } else { Some(chrec.step) },
828 ) else {
829 return Evolution::Unknown;
830 };
831 affine(base, step, ty, flags.intersection(chrec.flags))
832 }
833 (Evolution::Affine(a), Evolution::Affine(b)) => {
834 // Two chrecs of the same loop add componentwise, which is the closure property that
835 // makes the representation worth having. Of different types they do not, because the
836 // two sequences wrap at different widths.
837 if a.ty != b.ty {
838 return Evolution::Unknown;
839 }
840 let (Some(base), Some(step)) = (apply(a.base, b.base), apply(a.step, b.step)) else {
841 return Evolution::Unknown;
842 };
843 affine(base, step, ty, flags.intersection(a.flags).intersection(b.flags))
844 }
845 _ => Evolution::Unknown,
846 }
847}
848
849/// One evolution multiplied by another, which needs one of them to stand still.
850fn scale(left: Evolution, right: Evolution, ty: Type, flags: Flags) -> Evolution {
851 let (chrec, by) = match (left, right) {
852 (Evolution::Invariant(a), Evolution::Invariant(b)) => {
853 return a.times(b).map_or(Evolution::Unknown, Evolution::Invariant);
854 }
855 (Evolution::Affine(chrec), Evolution::Invariant(by))
856 | (Evolution::Invariant(by), Evolution::Affine(chrec)) => (chrec, by),
857 // Two chrecs multiplied give a quadratic, which is a chain of recurrences with a second
858 // step and is outside the subset section 7.4 chose.
859 _ => return Evolution::Unknown,
860 };
861 let (Some(base), Some(step)) = (chrec.base.times(by), chrec.step.times(by)) else {
862 return Evolution::Unknown;
863 };
864 affine(base, step, ty, flags.intersection(chrec.flags))
865}
866
867/// A chrec, or invariant when the step turns out to be nothing.
868///
869/// A step of zero is a valid affine chrec describing a value that does not move, and section 7.7
870/// warns that code dividing by the step to get a trip count divides by zero. Reporting it as
871/// invariant here means the shape is right for every reader rather than only for the careful
872/// ones, and the trip count solver still checks, because a step can also come out zero from a
873/// header parameter incremented by an invariant that happens to be zero.
874fn affine(base: Invariant, step: Invariant, ty: Type, flags: Flags) -> Evolution {
875 if step.is_zero() {
876 return Evolution::Invariant(base);
877 }
878 Evolution::Affine(Chrec { base, step, ty, flags })
879}
880
881/// The iteration at which `chrec pred limit` first fails, with what that rests on.
882///
883/// `each` says the test runs on every iteration that goes round, which is what lets the test itself
884/// stand in for a promise the counter does not carry. See [`bounded_by_its_test`].
885fn solve(chrec: Chrec, limit: Invariant, pred: IntPred, each: bool) -> Option<Bound> {
886 // Section 7.7's first way of being wrong. A step of zero is a loop that never leaves through
887 // this exit, and dividing the distance by it is a crash rather than an answer.
888 let step = chrec.step.as_number()?;
889 if step == 0 {
890 return None;
891 }
892 let signed = matches!(pred, IntPred::Slt | IntPred::Sle | IntPred::Sgt | IntPred::Sge);
893
894 let mut assumptions = Vec::new();
895 if !chrec.does_not_wrap(signed) && !(each && bounded_by_its_test(pred, step)) {
896 assumptions.push(Assumption::NoWrap(chrec));
897 }
898 if signed {
899 assumptions.push(Assumption::StrictOverflow);
900 }
901
902 // A test that does not read its operands as signed does not read the constants in them that
903 // way either, and every constant reaching here was read as signed on the way in.
904 let (base, limit) = if signed {
905 (chrec.base, limit)
906 } else {
907 (as_unsigned(chrec.base, chrec.ty)?, as_unsigned(limit, chrec.ty)?)
908 };
909
910 // The distance the counter has to travel, always counting up. A loop going down is the same
911 // problem with the ends swapped, which is why the step is used by size below and its sign is
912 // spent here.
913 let apart = step.unsigned_abs();
914 let found = match (pred, step > 0) {
915 (IntPred::Slt | IntPred::Ult, true) => {
916 ordered(limit.minus(base)?, apart, false, assumptions)
917 }
918 (IntPred::Sle | IntPred::Ule, true) => {
919 ordered(limit.minus(base)?, apart, true, assumptions)
920 }
921 (IntPred::Sgt | IntPred::Ugt, false) => {
922 ordered(base.minus(limit)?, apart, false, assumptions)
923 }
924 (IntPred::Sge | IntPred::Uge, false) => {
925 ordered(base.minus(limit)?, apart, true, assumptions)
926 }
927 (IntPred::Ne, _) => {
928 let distance = if step > 0 { limit.minus(base)? } else { base.minus(limit)? };
929 landing(distance, apart, assumptions)
930 }
931 // Either the counter steps away from the limit, in which case the loop is endless rather
932 // than long, or the test is one this does not solve. Silence is the answer to both.
933 _ => None,
934 };
935 // Written once here rather than threaded through the two solvers, because it is a fact about
936 // the test and neither of them looks at the test. A count taken from a test with no sign to it,
937 // which is `!=`, is read unsigned, because that is the reading `as_unsigned` above already put
938 // its operands through.
939 let reading = if signed { Reading::Signed } else { Reading::Unsigned };
940 found.map(|(count, assumptions)| Bound { count, assumptions, reading })
941}
942
943/// Whether the exit test by itself rules out the counter wrapping before the loop ends.
944///
945/// An unsigned counter carries no `nuw`, because C says unsigned arithmetic wraps, so without this
946/// every `for (unsigned i = 0; i < n; i++)` comes back resting on an assumption nothing downstream
947/// can discharge. What discharges it is the test. A counter stepping up by exactly one is at the
948/// limit before it is anywhere past it, and the test ends the loop there, so it never reaches the
949/// top of its type. GCC works the same thing out in `scev_probably_wraps_p`.
950///
951/// Every part of that is load bearing. The step has to be one: `i += 2` can go from one below the
952/// limit to one above the top of the type and come back round at the bottom, which is a loop that
953/// runs forever rather than one that runs twice as fast. The test has to be the strict one: `<=`
954/// lets the counter reach the limit and step once more, and a limit that is the largest number of
955/// its type makes that last step the one that wraps. And the test has to run on every iteration
956/// that goes round, or the counter can be stepped by a path that never asks it anything.
957///
958/// Nothing is claimed here about a signed counter, which needs no help: a signed counter that would
959/// wrap is a program with undefined behaviour in it and [`Assumption::StrictOverflow`] is where
960/// that is recorded.
961fn bounded_by_its_test(pred: IntPred, step: i128) -> bool {
962 matches!((pred, step), (IntPred::Ult, 1) | (IntPred::Ugt, -1))
963}
964
965/// Whether this sequence stays behind one the exit test already keeps inside its type.
966///
967/// [`bounded_by_its_test`] says the counter the test compares never reaches the top of its type.
968/// Everything else the loop counts with is that counter plus a fixed distance, because two affine
969/// chrecs of the same loop with the same step differ by a constant, so a sequence starting no
970/// further along than the counter is a sequence that gets to the top no sooner than the counter
971/// does, which is never.
972///
973/// Same base is the case that matters most and the easiest to see: the test compares `i + 1` and
974/// the subscript reads `i`, which is one loop written two ways, and the two chrecs differ only in
975/// where they start.
976///
977/// Going up only. A counter going down wraps at the bottom rather than the top, so the sequence
978/// that is safe is the one that starts further along rather than the one that starts behind, and
979/// nothing measured so far walks an array downwards. Doing it would be turning the comparison
980/// round, and it should come with the program that wants it.
981fn trails(chrec: Chrec, held: Chrec) -> bool {
982 if chrec.ty != held.ty || chrec.step != held.step {
983 return false;
984 }
985 if chrec.base == held.base {
986 return true;
987 }
988 let (Some(step), Some(mine), Some(theirs)) =
989 (chrec.step.as_number(), chrec.base.as_number(), held.base.as_number())
990 else {
991 return false;
992 };
993 // Read as unsigned, which is the reading the test took, so a base that came in negative is a
994 // large number rather than a small one and starting behind is not what it is doing.
995 step > 0 && mine >= 0 && theirs >= 0 && mine <= theirs
996}
997
998/// The same expression, read the way a test without a sign reads it.
999///
1000/// Constants arrive here as the number their bits are when the sign bit is taken seriously,
1001/// because that is the only reading available before anybody knows what will be done with them.
1002/// An unsigned test disagrees about half of them. `for (unsigned char i = 0; i < 200; i++)` holds
1003/// its limit as minus fifty six, and a distance worked out from that is negative, which reads as
1004/// a loop that runs no times rather than one that runs two hundred.
1005///
1006/// The step is not put through this, because a step is a difference rather than a value and its
1007/// signed reading is the one that says which way the counter goes.
1008fn as_unsigned(inv: Invariant, ty: Type) -> Option<Invariant> {
1009 match inv.as_number() {
1010 Some(number) if number >= 0 => Some(inv),
1011 Some(number) => {
1012 // Only an integer constant was read as signed in the first place. A pointer never
1013 // was, so a negative number sitting in one is an expression this cannot reinterpret.
1014 let bits = ty.is_int().then(|| ty.bits()).filter(|&bits| bits < 127)?;
1015 Some(Invariant::number(number & ((1i128 << bits) - 1)))
1016 }
1017 // A symbolic operand is whatever it is at run time, and the subtraction below cancels it
1018 // rather than reading it, so long as nothing signed has been folded in beside it.
1019 None => (inv.scale == 1 && inv.offset == 0).then_some(inv),
1020 }
1021}
1022
1023/// The count for an exit tested with an ordering, where overshooting the limit still ends it.
1024fn ordered(
1025 distance: Invariant,
1026 step: u128,
1027 inclusive: bool,
1028 mut assumptions: Vec<Assumption>,
1029) -> Option<(Count, Vec<Assumption>)> {
1030 match distance.as_number() {
1031 Some(exact) => {
1032 if exact < 0 {
1033 // The counter starts past the limit, so the test fails the first time it runs.
1034 // That is a count of zero and it rests on nothing at all, not even on the counter
1035 // behaving, because the counter never moves.
1036 return Some((Count::Exact(0), Vec::new()));
1037 }
1038 // Rounding up, because a step that overshoots still took the iteration that overshot.
1039 let count = (exact.unsigned_abs() + u128::from(inclusive)).div_ceil(step);
1040 Some((Count::Exact(count), assumptions))
1041 }
1042 // Symbolic, and only for a step of one, because dividing an expression by anything else
1043 // needs a representation for a division and there is not one here.
1044 None if step == 1 => {
1045 assumptions.push(Assumption::Approaching);
1046 let count = distance.plus(Invariant::number(i128::from(inclusive)))?;
1047 Some((Count::Symbolic(count), assumptions))
1048 }
1049 None => None,
1050 }
1051}
1052
1053/// The count for an exit tested with `!=`, where the counter has to land on the limit exactly.
1054///
1055/// This is a different problem from the one above and not a special case of it. An ordering test
1056/// ends the loop the moment the counter is past the limit, so a step that overshoots still stops.
1057/// `!=` only ends the loop on the one iteration where the counter is the limit, so a counter that
1058/// steps over the limit, or that starts on the far side of it, keeps going until it wraps. Both
1059/// of those are endless loops rather than short ones, and answering zero for either was the bug
1060/// this function exists to not have.
1061fn landing(
1062 distance: Invariant,
1063 step: u128,
1064 mut assumptions: Vec<Assumption>,
1065) -> Option<(Count, Vec<Assumption>)> {
1066 match distance.as_number() {
1067 Some(exact) => {
1068 let travel = u128::try_from(exact).ok()?;
1069 // Checked outright rather than assumed, which is why nothing here needs an assumption
1070 // about the step dividing anything.
1071 (travel % step == 0).then(|| (Count::Exact(travel / step), assumptions))
1072 }
1073 // A step of one lands on everything ahead of it, so the only thing left to establish is
1074 // that the limit is ahead. `while (p != end)` is this case, and a step of anything else
1075 // would need the division a symbolic distance has no room for.
1076 None if step == 1 => {
1077 assumptions.push(Assumption::Approaching);
1078 Some((Count::Symbolic(distance), assumptions))
1079 }
1080 None => None,
1081 }
1082}
1083
1084/// The predicate that is true exactly when this one is not.
1085fn invert(pred: IntPred) -> IntPred {
1086 match pred {
1087 IntPred::Eq => IntPred::Ne,
1088 IntPred::Ne => IntPred::Eq,
1089 IntPred::Slt => IntPred::Sge,
1090 IntPred::Sle => IntPred::Sgt,
1091 IntPred::Sgt => IntPred::Sle,
1092 IntPred::Sge => IntPred::Slt,
1093 IntPred::Ult => IntPred::Uge,
1094 IntPred::Ule => IntPred::Ugt,
1095 IntPred::Ugt => IntPred::Ule,
1096 IntPred::Uge => IntPred::Ult,
1097 }
1098}
1099
1100/// The predicate that says the same thing with the operands the other way round.
1101fn swap(pred: IntPred) -> IntPred {
1102 match pred {
1103 IntPred::Eq => IntPred::Eq,
1104 IntPred::Ne => IntPred::Ne,
1105 IntPred::Slt => IntPred::Sgt,
1106 IntPred::Sle => IntPred::Sge,
1107 IntPred::Sgt => IntPred::Slt,
1108 IntPred::Sge => IntPred::Sle,
1109 IntPred::Ult => IntPred::Ugt,
1110 IntPred::Ule => IntPred::Uge,
1111 IntPred::Ugt => IntPred::Ult,
1112 IntPred::Uge => IntPred::Ule,
1113 }
1114}
1115
1116/// The constant a value is, if it is one.
1117fn constant(func: &Func, value: Value) -> Option<(Imm, Type)> {
1118 let Def::Result { inst, .. } = func[value].def else { return None };
1119 if func[inst].opcode != Opcode::IConst {
1120 return None;
1121 }
1122 let Extra::Imm(at) = func[inst].extra else { return None };
1123 let ty = func[value].ty;
1124 ty.is_int().then(|| (func[at], ty))
1125}
1126
1127/// What this predecessor passes to the block's parameter at this position.
1128///
1129/// `None` when the predecessor branches to the block more than once with different arguments,
1130/// which a `br_if` with both arms on the same block can do and which means the parameter takes a
1131/// value that depends on the test rather than on the edge.
1132fn argument(func: &Func, pred: Block, block: Block, index: usize) -> Option<Value> {
1133 let term = func.terminator(pred)?;
1134 let mut found = None;
1135 for call in func.successors(term) {
1136 if call.block != block {
1137 continue;
1138 }
1139 let arg = *func[call.args].get(index)?;
1140 if found.replace(arg).is_some_and(|old| old != arg) {
1141 return None;
1142 }
1143 }
1144 found
1145}
1146
1147#[cfg(test)]
1148mod tests {
1149 use rucc_base::Interner;
1150 use rucc_ir::{Builder, Flags, Func, IntPred, Opcode, Signature, Type, Value};
1151
1152 use crate::cfg::Cfg;
1153 use crate::dom::Dominators;
1154 use crate::loops::{LoopId, Loops};
1155 use crate::scev::{Assumption, Bound, Count, Evolution, Invariant, Reading, Scev};
1156
1157 /// A loop counting in `ty` from `from` by `step` while the counter is below `to`.
1158 ///
1159 /// ```text
1160 /// entry: jump header(from)
1161 /// header(i): test = icmp pred i, to ; br_if test, body, exit
1162 /// body: next = add i, step ; jump header(next)
1163 /// exit: ret
1164 /// ```
1165 ///
1166 /// The counter is the header's only parameter, which is what the tests ask about.
1167 struct Counted {
1168 func: Func,
1169 counter: Value,
1170 next: Value,
1171 }
1172
1173 fn counted(ty: Type, from: i128, to: i128, step: i128, pred: IntPred, flags: Flags) -> Counted {
1174 let (it, ()) = counted_with(ty, from, to, step, pred, flags, |_, _| ());
1175 it
1176 }
1177
1178 /// The same loop, with `extra` run in the body on the counter before the counter steps.
1179 ///
1180 /// The builder appends, and the body's `jump` back to the header has to stay the last
1181 /// instruction in it or the block has no terminator and the loop stops being one. So anything
1182 /// a test wants derived from the counter goes in here rather than being tacked on afterwards.
1183 fn counted_with<T>(
1184 ty: Type,
1185 from: i128,
1186 to: i128,
1187 step: i128,
1188 pred: IntPred,
1189 flags: Flags,
1190 extra: impl FnOnce(&mut Builder<'_>, Value) -> T,
1191 ) -> (Counted, T) {
1192 let mut names = Interner::new();
1193 let mut func = Func::new(names.intern("f"), Signature::new());
1194 let entry = func.create_block();
1195 let header = func.create_block();
1196 let body = func.create_block();
1197 let exit = func.create_block();
1198 let counter = func.append_param(header, ty);
1199
1200 let mut build = Builder::new(&mut func, entry);
1201 let start = build.iconst(ty, from);
1202 build.jump(header, &[start]);
1203
1204 let mut build = Builder::new(&mut func, header);
1205 let limit = build.iconst(ty, to);
1206 let test = build.icmp(pred, counter, limit);
1207 build.br_if(test, body, &[], exit, &[]);
1208
1209 let mut build = Builder::new(&mut func, body);
1210 let derived = extra(&mut build, counter);
1211 let by = build.iconst(ty, step);
1212 let next = build.binary(Opcode::Add, counter, by, flags);
1213 build.jump(header, &[next]);
1214
1215 let mut build = Builder::new(&mut func, exit);
1216 build.ret(&[]);
1217
1218 (Counted { func, counter, next }, derived)
1219 }
1220
1221 /// The analysis over a function, along with the one loop it has.
1222 fn analyse(func: &Func) -> (Cfg, Loops) {
1223 let cfg = Cfg::new(func);
1224 let doms = Dominators::new(&cfg);
1225 let loops = Loops::new(&cfg, &doms);
1226 (cfg, loops)
1227 }
1228
1229 /// The chrec of a value in the one loop of a function.
1230 fn evolution(func: &Func, value: Value) -> Evolution {
1231 let (cfg, loops) = analyse(func);
1232 let id = loops.roots()[0];
1233 Scev::new(func, &cfg, &loops).evolution(id, value)
1234 }
1235
1236 /// The trip count of the one loop of a function.
1237 fn bound(func: &Func) -> Option<Bound> {
1238 let (cfg, loops) = analyse(func);
1239 let id: LoopId = loops.roots()[0];
1240 Scev::new(func, &cfg, &loops).bound(id)
1241 }
1242
1243 #[test]
1244 fn a_counter_from_zero_by_one_is_the_chrec_everyone_expects() {
1245 let it = counted(Type::int(32), 0, 100, 1, IntPred::Slt, Flags::NSW);
1246 let chrec = evolution(&it.func, it.counter).chrec().expect("the counter evolves");
1247 assert_eq!(chrec.base, Invariant::number(0));
1248 assert_eq!(chrec.step, Invariant::number(1));
1249 assert_eq!(chrec.ty, Type::int(32));
1250 assert!(chrec.does_not_wrap(true));
1251 }
1252
1253 #[test]
1254 fn the_value_fed_back_is_the_chrec_one_step_along() {
1255 let it = counted(Type::int(32), 5, 100, 3, IntPred::Slt, Flags::NSW);
1256 let chrec = evolution(&it.func, it.next).chrec().expect("the increment evolves");
1257 assert_eq!(chrec.base, Invariant::number(8));
1258 assert_eq!(chrec.step, Invariant::number(3));
1259 }
1260
1261 #[test]
1262 fn a_multiple_of_the_counter_plus_a_number_is_a_chrec_of_its_own() {
1263 // `j = 2 * i + 3` where `i = {0, +, 1}`, which is the shape section 7.4 says pattern
1264 // matching runs out of road on and chains of recurrences do not.
1265 let (it, shifted) =
1266 counted_with(Type::int(32), 0, 100, 1, IntPred::Slt, Flags::NSW, |build, counter| {
1267 let two = build.iconst(Type::int(32), 2);
1268 let three = build.iconst(Type::int(32), 3);
1269 let doubled = build.binary(Opcode::Mul, counter, two, Flags::NSW);
1270 build.binary(Opcode::Add, doubled, three, Flags::NSW)
1271 });
1272
1273 let chrec = evolution(&it.func, shifted).chrec().expect("it evolves");
1274 assert_eq!(chrec.base, Invariant::number(3));
1275 assert_eq!(chrec.step, Invariant::number(2));
1276 }
1277
1278 #[test]
1279 fn a_shift_by_a_constant_scales_the_chrec_and_a_shift_past_the_width_does_not() {
1280 let (it, (scaled, poison)) =
1281 counted_with(Type::int(32), 1, 100, 1, IntPred::Slt, Flags::NSW, |build, counter| {
1282 let three = build.iconst(Type::int(32), 3);
1283 let wide = build.iconst(Type::int(32), 32);
1284 (
1285 build.binary(Opcode::Shl, counter, three, Flags::NSW),
1286 build.binary(Opcode::Shl, counter, wide, Flags::NSW),
1287 )
1288 });
1289
1290 let chrec = evolution(&it.func, scaled).chrec().expect("it evolves");
1291 assert_eq!(chrec.base, Invariant::number(8));
1292 assert_eq!(chrec.step, Invariant::number(8));
1293 // A count at the width is poison rather than a shift to zero, so there is no sequence to
1294 // describe.
1295 assert_eq!(evolution(&it.func, poison), Evolution::Unknown);
1296 }
1297
1298 #[test]
1299 fn a_pointer_walked_by_the_element_size_is_a_chrec_in_bytes() {
1300 // What `for (p = a; p != end; p++)` lowers to on an array of four byte elements. Section
1301 // 7.4 calls this the one deliberate extension past affine and the difference between
1302 // analysing half of real C loops and nearly all of them.
1303 let mut names = Interner::new();
1304 let mut func = Func::new(names.intern("f"), Signature::new());
1305 let entry = func.create_block();
1306 let header = func.create_block();
1307 let body = func.create_block();
1308 let exit = func.create_block();
1309 let start = func.append_param(entry, Type::PTR);
1310 let cursor = func.append_param(header, Type::PTR);
1311
1312 let mut build = Builder::new(&mut func, entry);
1313 build.jump(header, &[start]);
1314 let mut build = Builder::new(&mut func, header);
1315 let done = build.icmp(IntPred::Eq, cursor, start);
1316 build.br_if(done, exit, &[], body, &[]);
1317 let mut build = Builder::new(&mut func, body);
1318 let four = build.iconst(Type::int(64), 4);
1319 let next = build.binary(Opcode::PtrAdd, cursor, four, Flags::NONE);
1320 build.jump(header, &[next]);
1321 let mut build = Builder::new(&mut func, exit);
1322 build.ret(&[]);
1323
1324 let chrec = evolution(&func, cursor).chrec().expect("the cursor evolves");
1325 assert_eq!(chrec.base, Invariant::of(start));
1326 assert_eq!(chrec.step, Invariant::number(4));
1327 assert_eq!(chrec.ty, Type::PTR);
1328 }
1329
1330 #[test]
1331 fn a_counter_in_unsigned_char_wraps_and_does_not_widen_without_a_promise() {
1332 // Section 7.7's second way of being wrong. `{0, +, 1}` in `unsigned char` is not
1333 // `0, 1, 2, ...`, it is that modulo two hundred and fifty six, and widening it is only
1334 // the same sequence if it does not get that far.
1335 //
1336 // An inclusive test, because a strict one is a proof of its own and the case below is
1337 // about what happens when there is no proof at all. This loop does not in fact wrap, and
1338 // the point is that nothing here can say so.
1339 let (it, wide) =
1340 counted_with(Type::int(8), 0, 100, 1, IntPred::Ule, Flags::NONE, |build, counter| {
1341 build.unary(Opcode::ZExt, counter, Type::int(32))
1342 });
1343 let chrec = evolution(&it.func, it.counter).chrec().expect("the counter evolves");
1344 assert_eq!(chrec.ty, Type::int(8));
1345 assert!(!chrec.does_not_wrap(false));
1346 assert_eq!(evolution(&it.func, wide), Evolution::Unknown);
1347 }
1348
1349 #[test]
1350 fn a_counter_its_own_test_holds_widens_without_a_promise() {
1351 // The same counter under the strict test, which is the shape `for (unsigned i = 0; i < n;
1352 // i++)` has. Nothing promised anything, and the test is the proof: the counter is at the
1353 // limit before it is anywhere past it, and the loop ends there.
1354 let (it, wide) =
1355 counted_with(Type::int(8), 0, 100, 1, IntPred::Ult, Flags::NONE, |build, counter| {
1356 build.unary(Opcode::ZExt, counter, Type::int(32))
1357 });
1358 let narrow = evolution(&it.func, it.counter).chrec().expect("the counter evolves");
1359 assert!(!narrow.does_not_wrap(false), "nothing was promised, so nothing carries a flag");
1360 let chrec = evolution(&it.func, wide).chrec().expect("its own test holds it");
1361 assert_eq!(chrec.ty, Type::int(32));
1362 assert_eq!(chrec.base, Invariant::number(0));
1363 assert_eq!(chrec.step, Invariant::number(1));
1364 }
1365
1366 #[test]
1367 fn a_sequence_that_starts_further_along_than_the_counter_does_not_widen() {
1368 // `trails` in the direction it refuses. The test holds `i`, which starts at zero, and this
1369 // asks about `i + 1`, which starts one further along. One further along is where the
1370 // counter would be if it had gone round once more, and going round once more is the step
1371 // nothing here rules out.
1372 let (it, wide) =
1373 counted_with(Type::int(8), 0, 100, 1, IntPred::Ult, Flags::NONE, |build, counter| {
1374 let one = build.iconst(Type::int(8), 1);
1375 let ahead = build.binary(Opcode::Add, counter, one, Flags::NONE);
1376 build.unary(Opcode::ZExt, ahead, Type::int(32))
1377 });
1378 assert_eq!(evolution(&it.func, wide), Evolution::Unknown);
1379 }
1380
1381 #[test]
1382 fn a_counter_in_short_widens_when_the_increment_promised_it_would_not_wrap() {
1383 let (it, (wide, zero_extended)) =
1384 counted_with(Type::int(16), 0, 100, 1, IntPred::Slt, Flags::NSW, |build, counter| {
1385 (
1386 build.unary(Opcode::SExt, counter, Type::int(32)),
1387 build.unary(Opcode::ZExt, counter, Type::int(32)),
1388 )
1389 });
1390
1391 let chrec = evolution(&it.func, wide).chrec().expect("it widens");
1392 assert_eq!(chrec.ty, Type::int(32));
1393 assert_eq!(chrec.base, Invariant::number(0));
1394 assert_eq!(chrec.step, Invariant::number(1));
1395 // `nsw` is a promise about the signed reading and says nothing about the unsigned one.
1396 assert_eq!(evolution(&it.func, zero_extended), Evolution::Unknown);
1397 }
1398
1399 #[test]
1400 fn a_step_of_zero_is_invariant_and_has_no_trip_count() {
1401 // Section 7.7's first way of being wrong. `i += k` with `k` of zero is a valid affine
1402 // chrec of a loop that never leaves through this exit, and code dividing the distance by
1403 // the step divides by zero.
1404 let it = counted(Type::int(32), 0, 100, 0, IntPred::Slt, Flags::NSW);
1405 assert!(matches!(evolution(&it.func, it.counter), Evolution::Invariant(_)));
1406 assert_eq!(bound(&it.func), None);
1407 }
1408
1409 #[test]
1410 fn a_counted_loop_has_the_count_anyone_would_work_out_by_hand() {
1411 let it = counted(Type::int(32), 0, 100, 1, IntPred::Slt, Flags::NSW);
1412 let found = bound(&it.func).expect("it is counted");
1413 let (count, assumptions) = found.parts();
1414 assert_eq!(count, Count::Exact(100));
1415 // The distance is a number and it is not negative, so being entered is not in question.
1416 // Signed overflow being undefined still is, which is what `-fwrapv` would withdraw.
1417 assert_eq!(assumptions, [Assumption::StrictOverflow]);
1418 assert_eq!(found.proven(), None);
1419 }
1420
1421 #[test]
1422 fn a_step_that_overshoots_still_takes_the_iteration_that_overshot() {
1423 // Zero, three, six, nine, and the test fails at twelve, so four iterations rather than
1424 // three and a third. Rounding the other way is an off by one in every unroller.
1425 let it = counted(Type::int(32), 0, 10, 3, IntPred::Slt, Flags::NSW);
1426 let (count, _) = bound(&it.func).expect("it is counted").parts();
1427 assert_eq!(count, Count::Exact(4));
1428 }
1429
1430 #[test]
1431 fn an_inclusive_test_runs_one_more_time() {
1432 let it = counted(Type::int(32), 0, 10, 1, IntPred::Sle, Flags::NSW);
1433 let (count, _) = bound(&it.func).expect("it is counted").parts();
1434 assert_eq!(count, Count::Exact(11));
1435 }
1436
1437 #[test]
1438 fn a_loop_whose_test_fails_first_time_runs_no_times_and_rests_on_nothing() {
1439 let it = counted(Type::int(32), 10, 0, 1, IntPred::Slt, Flags::NSW);
1440 let found = bound(&it.func).expect("it is counted");
1441 assert_eq!(found.proven(), Some(Count::Exact(0)));
1442 assert!(found.assumptions().is_empty());
1443 }
1444
1445 #[test]
1446 fn counting_down_is_the_same_problem_with_the_ends_swapped() {
1447 let it = counted(Type::int(32), 10, 0, -1, IntPred::Sgt, Flags::NSW);
1448 let (count, _) = bound(&it.func).expect("it is counted").parts();
1449 assert_eq!(count, Count::Exact(10));
1450 }
1451
1452 #[test]
1453 fn an_unsigned_test_does_not_drag_in_the_signed_overflow_assumption() {
1454 let it = counted(Type::int(32), 0, 100, 1, IntPred::Ult, Flags::NUW);
1455 let found = bound(&it.func).expect("it is counted");
1456 assert_eq!(found.proven(), Some(Count::Exact(100)));
1457 }
1458
1459 #[test]
1460 fn a_test_against_something_the_loop_does_not_change_gives_a_symbolic_count() {
1461 // `for (i = 0; i < n; i++)`, where the answer is `n` and is only `n` if the loop is
1462 // entered, because `n` of minus one runs no times and the distance is minus one.
1463 let mut names = Interner::new();
1464 let mut func = Func::new(names.intern("f"), Signature::new());
1465 let entry = func.create_block();
1466 let header = func.create_block();
1467 let body = func.create_block();
1468 let exit = func.create_block();
1469 let limit = func.append_param(entry, Type::int(32));
1470 let counter = func.append_param(header, Type::int(32));
1471
1472 let mut build = Builder::new(&mut func, entry);
1473 let zero = build.iconst(Type::int(32), 0);
1474 build.jump(header, &[zero]);
1475 let mut build = Builder::new(&mut func, header);
1476 let test = build.icmp(IntPred::Slt, counter, limit);
1477 build.br_if(test, body, &[], exit, &[]);
1478 let mut build = Builder::new(&mut func, body);
1479 let one = build.iconst(Type::int(32), 1);
1480 let next = build.binary(Opcode::Add, counter, one, Flags::NSW);
1481 build.jump(header, &[next]);
1482 let mut build = Builder::new(&mut func, exit);
1483 build.ret(&[]);
1484
1485 let found = bound(&func).expect("it is counted");
1486 let (count, assumptions) = found.parts();
1487 assert_eq!(count, Count::Symbolic(Invariant::of(limit)));
1488 assert!(assumptions.contains(&Assumption::Approaching), "{assumptions:?}");
1489 assert!(assumptions.contains(&Assumption::StrictOverflow), "{assumptions:?}");
1490 assert_eq!(found.proven(), None);
1491 }
1492
1493 #[test]
1494 fn the_count_records_which_reading_its_test_took() {
1495 // What a consumer widening a symbolic count has to know. The limit is a value of the
1496 // counter's type and which number that value is depends on how its test read it.
1497 let signed = counted(Type::int(32), 0, 100, 1, IntPred::Slt, Flags::NSW);
1498 assert_eq!(bound(&signed.func).expect("it is counted").reading(), Reading::Signed);
1499 let unsigned = counted(Type::int(32), 0, 100, 1, IntPred::Ult, Flags::NUW);
1500 assert_eq!(bound(&unsigned.func).expect("it is counted").reading(), Reading::Unsigned);
1501 }
1502
1503 #[test]
1504 fn a_counter_without_a_no_wrap_promise_carries_the_assumption_instead() {
1505 // An inclusive test, because the strict one is the case the test itself answers. Under
1506 // `<=` the counter reaches the limit and is stepped once more, so a limit at the top of
1507 // the type makes that last step the one that wraps and nothing here rules it out.
1508 let it = counted(Type::int(32), 0, 100, 1, IntPred::Ule, Flags::NONE);
1509 let found = bound(&it.func).expect("it is counted");
1510 let (_, assumptions) = found.parts();
1511 assert!(assumptions.iter().any(|a| matches!(a, Assumption::NoWrap(_))), "{assumptions:?}");
1512 }
1513
1514 #[test]
1515 fn an_unsigned_counter_stepping_by_one_is_held_by_its_own_test() {
1516 // `for (unsigned i = 0; i < n; i++)` written out. Unsigned arithmetic wraps in C so the
1517 // increment carries no `nuw`, and without reading the test this would rest on an
1518 // assumption nothing downstream can discharge.
1519 let it = counted(Type::int(32), 0, 100, 1, IntPred::Ult, Flags::NONE);
1520 let found = bound(&it.func).expect("it is counted");
1521 assert_eq!(found.assumptions(), &[]);
1522 assert_eq!(found.proven(), Some(Count::Exact(100)));
1523 }
1524
1525 #[test]
1526 fn counting_down_by_one_is_held_the_same_way() {
1527 let it = counted(Type::int(32), 100, 0, -1, IntPred::Ugt, Flags::NONE);
1528 let found = bound(&it.func).expect("it is counted");
1529 assert_eq!(found.assumptions(), &[]);
1530 assert_eq!(found.proven(), Some(Count::Exact(100)));
1531 }
1532
1533 #[test]
1534 fn a_step_of_two_can_jump_the_limit_so_the_test_holds_nothing() {
1535 // The counter is never at the limit, so the loop can be left by a step that goes from one
1536 // below the limit to one past the top of the type and comes back round at the bottom.
1537 let it = counted(Type::int(32), 0, 100, 2, IntPred::Ult, Flags::NONE);
1538 let found = bound(&it.func).expect("it is counted");
1539 let (_, assumptions) = found.parts();
1540 assert!(assumptions.iter().any(|a| matches!(a, Assumption::NoWrap(_))), "{assumptions:?}");
1541 }
1542
1543 #[test]
1544 fn a_test_the_counter_can_be_stepped_without_being_asked_holds_nothing_either() {
1545 // ```text
1546 // header(i): br_if flag, check, latch
1547 // check: br_if i <u 100, latch, exit
1548 // latch: jump header(i + 1)
1549 // ```
1550 // The counter goes round by a path that never reaches the test, so the test says nothing
1551 // about how far the counter got.
1552 let mut names = Interner::new();
1553 let mut func = Func::new(names.intern("f"), Signature::new());
1554 let entry = func.create_block();
1555 let header = func.create_block();
1556 let check = func.create_block();
1557 let latch = func.create_block();
1558 let exit = func.create_block();
1559 let flag = func.append_param(entry, Type::int(1));
1560 let counter = func.append_param(header, Type::int(32));
1561
1562 let mut build = Builder::new(&mut func, entry);
1563 let zero = build.iconst(Type::int(32), 0);
1564 build.jump(header, &[zero]);
1565 let mut build = Builder::new(&mut func, header);
1566 build.br_if(flag, check, &[], latch, &[]);
1567 let mut build = Builder::new(&mut func, check);
1568 let limit = build.iconst(Type::int(32), 100);
1569 let test = build.icmp(IntPred::Ult, counter, limit);
1570 build.br_if(test, latch, &[], exit, &[]);
1571 let mut build = Builder::new(&mut func, latch);
1572 let one = build.iconst(Type::int(32), 1);
1573 let next = build.binary(Opcode::Add, counter, one, Flags::NONE);
1574 build.jump(header, &[next]);
1575 let mut build = Builder::new(&mut func, exit);
1576 build.ret(&[]);
1577
1578 let found = bound(&func).expect("it is counted");
1579 let (_, assumptions) = found.parts();
1580 assert!(assumptions.iter().any(|a| matches!(a, Assumption::NoWrap(_))), "{assumptions:?}");
1581 }
1582
1583 #[test]
1584 fn a_test_that_ends_the_loop_when_it_succeeds_is_read_the_other_way_round() {
1585 // `for (i = 0; ; i++) if (i >= 100) break;`, which is the same loop with the arms of the
1586 // branch swapped. The test that keeps the loop going is the opposite of the one written.
1587 let mut names = Interner::new();
1588 let mut func = Func::new(names.intern("f"), Signature::new());
1589 let entry = func.create_block();
1590 let header = func.create_block();
1591 let body = func.create_block();
1592 let exit = func.create_block();
1593 let counter = func.append_param(header, Type::int(32));
1594
1595 let mut build = Builder::new(&mut func, entry);
1596 let zero = build.iconst(Type::int(32), 0);
1597 build.jump(header, &[zero]);
1598 let mut build = Builder::new(&mut func, header);
1599 let limit = build.iconst(Type::int(32), 100);
1600 let done = build.icmp(IntPred::Sge, counter, limit);
1601 build.br_if(done, exit, &[], body, &[]);
1602 let mut build = Builder::new(&mut func, body);
1603 let one = build.iconst(Type::int(32), 1);
1604 let next = build.binary(Opcode::Add, counter, one, Flags::NSW);
1605 build.jump(header, &[next]);
1606 let mut build = Builder::new(&mut func, exit);
1607 build.ret(&[]);
1608
1609 let (count, _) = bound(&func).expect("it is counted").parts();
1610 assert_eq!(count, Count::Exact(100));
1611 }
1612
1613 #[test]
1614 fn an_unsigned_limit_past_the_middle_of_its_type_is_not_a_negative_one() {
1615 // `for (unsigned char i = 0; i < 200; i++)`. Two hundred does not fit in a signed byte
1616 // and the constant is held as minus fifty six, so a distance taken at face value is
1617 // negative and reads as a loop that runs no times.
1618 let it = counted(Type::int(8), 0, 200, 1, IntPred::Ult, Flags::NUW);
1619 let found = bound(&it.func).expect("it is counted");
1620 assert_eq!(found.proven(), Some(Count::Exact(200)));
1621 }
1622
1623 #[test]
1624 fn a_walk_that_lands_on_a_not_equal_limit_exactly_is_counted() {
1625 // `while (i != 10)` counting by one, which is `while (p != end)` over an array once the
1626 // element size has been divided out. `!=` says nothing about how its operands are read,
1627 // so the promise it wants is the unsigned one and an `nsw` on its own is not enough.
1628 let it = counted(Type::int(32), 0, 10, 1, IntPred::Ne, Flags::NSW.union(Flags::NUW));
1629 let found = bound(&it.func).expect("it lands on its limit");
1630 // The step divides the distance and both are numbers, so it was checked rather than
1631 // assumed and there is nothing left over.
1632 assert_eq!(found.proven(), Some(Count::Exact(10)));
1633 }
1634
1635 #[test]
1636 fn a_counter_stepping_away_from_a_not_equal_limit_is_not_a_loop_that_runs_no_times() {
1637 // The distance is negative and an ordering test would read that as the loop never being
1638 // entered. `!=` reads it as the counter never arriving, which is an endless loop, and
1639 // answering zero for it was a real bug that the property test in `tests/scev.rs` found.
1640 let it = counted(Type::int(32), 48, 15, 1, IntPred::Ne, Flags::NSW);
1641 assert_eq!(bound(&it.func), None);
1642 }
1643
1644 #[test]
1645 fn a_counter_stepping_over_a_not_equal_limit_never_arrives_either() {
1646 // Zero, three, six, nine, twelve, and ten is never one of them. An ordering test would
1647 // have stopped at twelve.
1648 let it = counted(Type::int(32), 0, 10, 3, IntPred::Ne, Flags::NSW);
1649 assert_eq!(bound(&it.func), None);
1650 }
1651
1652 #[test]
1653 fn an_estimate_is_the_count_when_there_is_one_and_a_guess_when_there_is_not() {
1654 let counted_loop = counted(Type::int(32), 0, 7, 1, IntPred::Slt, Flags::NSW);
1655 let (cfg, loops) = analyse(&counted_loop.func);
1656 let id = loops.roots()[0];
1657 let estimate = Scev::new(&counted_loop.func, &cfg, &loops).estimate(id);
1658 assert_eq!(estimate.iterations(), 7);
1659 assert!(!estimate.is_guess());
1660
1661 // A loop this cannot count still has to answer, because the caller is deciding whether
1662 // something is worth doing rather than whether it is legal.
1663 let uncounted = counted(Type::int(32), 0, 100, 0, IntPred::Slt, Flags::NSW);
1664 let (cfg, loops) = analyse(&uncounted.func);
1665 let id = loops.roots()[0];
1666 let estimate = Scev::new(&uncounted.func, &cfg, &loops).estimate(id);
1667 assert!(estimate.is_guess());
1668 assert_eq!(estimate.iterations(), super::ASSUMED_ITERATIONS);
1669 }
1670
1671 #[test]
1672 fn a_value_the_loop_does_not_touch_is_invariant_rather_than_unknown() {
1673 let it = counted(Type::int(32), 0, 100, 1, IntPred::Slt, Flags::NSW);
1674 let (cfg, loops) = analyse(&it.func);
1675 let id = loops.roots()[0];
1676 let mut scev = Scev::new(&it.func, &cfg, &loops);
1677 // The counter's start is an `iconst` in the entry block, which is both.
1678 assert_eq!(
1679 scev.evolution(id, it.counter).chrec().expect("it evolves").base,
1680 Invariant::number(0)
1681 );
1682 }
1683
1684 #[test]
1685 fn a_back_edge_of_its_own_does_not_hide_the_counter() {
1686 // What canonicalization leaves behind. The back edge goes through a block that does nothing
1687 // but pass the increment on, so the value arriving at the header is a parameter of that
1688 // block rather than the increment itself. Reading through it is undoing a rename and not an
1689 // analysis, and without it the trip count of every loop the pipeline produces is nothing.
1690 let mut names = Interner::new();
1691 let mut func = Func::new(names.intern("f"), Signature::new());
1692 let entry = func.create_block();
1693 let header = func.create_block();
1694 let body = func.create_block();
1695 let latch = func.create_block();
1696 let exit = func.create_block();
1697 let counter = func.append_param(header, Type::int(32));
1698 let carried = func.append_param(latch, Type::int(32));
1699
1700 let start = Builder::new(&mut func, entry).iconst(Type::int(32), 0);
1701 Builder::new(&mut func, entry).jump(header, &[start]);
1702
1703 let mut build = Builder::new(&mut func, header);
1704 let limit = build.iconst(Type::int(32), 100);
1705 let test = build.icmp(IntPred::Slt, counter, limit);
1706 build.br_if(test, body, &[], exit, &[]);
1707
1708 let mut build = Builder::new(&mut func, body);
1709 let by = build.iconst(Type::int(32), 1);
1710 let next = build.binary(Opcode::Add, counter, by, Flags::NSW);
1711 build.jump(latch, &[next]);
1712
1713 Builder::new(&mut func, latch).jump(header, &[carried]);
1714 Builder::new(&mut func, exit).ret(&[]);
1715
1716 let chrec = evolution(&func, counter).chrec().expect("the counter still evolves");
1717 assert_eq!(chrec.base, Invariant::number(0));
1718 assert_eq!(chrec.step, Invariant::number(1));
1719 let (count, _) = bound(&func).expect("it is still counted").parts();
1720 assert_eq!(count, Count::Exact(100));
1721 }
1722
1723 #[test]
1724 fn every_assumption_says_what_it_is_in_a_line() {
1725 let it = counted(Type::int(8), 0, 100, 1, IntPred::Ult, Flags::NONE);
1726 let found = bound(&it.func).expect("it is counted");
1727 for assumption in found.assumptions() {
1728 let line = assumption.describe();
1729 assert!(!line.is_empty());
1730 assert!(!line.contains('\n'), "an assumption is one line: {line}");
1731 }
1732 }
1733}