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_base::Symbol;
53use rucc_ir::{Block, Def, Extra, Flags, Func, Imm, Inst, IntPred, Opcode, Type, Value};
54
55use crate::cfg::Cfg;
56use crate::loops::{LoopId, Loops};
57
58/// How deep the search for a step walks back through arithmetic.
59///
60/// The chain from a header parameter to the value fed back to it is two or three instructions in
61/// anything a person writes, and the walk terminates on its own because SSA has no cycles except
62/// through block parameters. The limit is here so a generated function with a thousand additions
63/// in the increment costs a bounded amount rather than a stack.
64const STEP_LIMIT: u32 = 16;
65
66/// How many blocks that do nothing but pass a value on the walk reads through.
67///
68/// One is what a canonicalized loop has. The limit is here for the same reason the one above is,
69/// which is that a generated function can have a chain of them and the cost of following it should
70/// not depend on how long somebody made it.
71const FORWARD_LIMIT: u32 = 8;
72
73/// How many times a loop is assumed to run when nothing better is known.
74///
75/// GCC's `--param avg-loop-niter`, whose default is the same number. It is a guess, so nothing may
76/// rest on it. It reaches [`Estimate`], which is only ever used to decide whether something is
77/// worth doing, and [`crate::split`], which spends it on how far to ask the runtime to look and is
78/// answered with a true count of bytes whatever it asked for.
79pub(crate) const ASSUMED_ITERATIONS: u64 = 10;
80
81/// A value that does not change inside the loop, read as `on + scale * value + offset`.
82///
83/// The `value` is a value defined outside the loop, or `None` when the linear part is a plain
84/// number. Keeping the shape rather than a bare [`Value`] is what lets `j = 2 * i + 3` come out
85/// as `{3, +, 2}` instead of unknown: the base and the step of that chrec are expressions nothing
86/// in the function computes, so a representation that could only name existing values would have
87/// to give up.
88///
89/// The `on` is a second symbol, and it is there for one shape: a pointer plus an index the loop
90/// did not start at zero. `a[i]` with `i` starting at a parameter has a first address of
91/// `a + start * 4`, which is two symbols, and a representation with room for one has to answer
92/// unknown to it. Nothing scales `on` and nothing negates it, because the thing it was added for
93/// is a pointer and a pointer is not something a loop multiplies. It is an [`Anchor`] rather than
94/// a value so that the address of a global can be one of them.
95///
96/// The `read` is the other half of the same shape, since in C that index is an `int` and what
97/// reaches the address is `sext(start)`. It is described rather than named, for the reason on
98/// [`Widening`]. The two together are what let `a[start + i]` be followed, and on the SQLite
99/// amalgamation they take 158 checks and 12 sites off the largest row of loop splitting's census.
100/// See tamnd/rucc#810.
101///
102/// Arithmetic on two of these is refused once the sum would need a third symbol, because
103/// `x + y + z` is not of this shape. That is the boundary of the subset and it is where the answer
104/// becomes unknown rather than wrong.
105///
106/// The fields are private on purpose. Every reader has to go through [`Invariant::plain`], which
107/// hands back the one symbol reading and refuses when there is a pointer in it, or through
108/// [`Invariant::on`], which hands back both halves. A reader that helped itself to `value` and
109/// `scale` would quietly drop the `on` and build an address off the wrong object.
110#[derive(Clone, Copy, Debug, PartialEq, Eq)]
111pub struct Invariant {
112 /// A second symbol the whole expression is measured from, or `None`. Always one of it.
113 on: Option<Anchor>,
114 /// What the linear part is built on, or `None` for a plain number.
115 value: Option<Value>,
116 /// How that value is read, when it is read at a width that is not its own.
117 read: Option<Widening>,
118 /// How many of it.
119 scale: i128,
120 /// What is added.
121 offset: i128,
122}
123
124/// What an expression is measured from.
125///
126/// Usually a value the function computed somewhere outside the loop, which whoever reads the
127/// invariant can name. Sometimes the address of a global, which nothing has to compute because it
128/// is settled at link time and is the same number everywhere in the program.
129///
130/// The second one is here because of where a `global_addr` sits. [`crate::licm`] gives it a cost of
131/// zero and so never moves it out of a loop, which is the right call: working the address out again
132/// is one instruction and holding it in a register across a loop is a register. But that leaves the
133/// instruction inside the loop, and [`Loops::is_invariant`] answers by where a value is defined, so
134/// `a[i]` on a file scope `a` came out unknown. Describing the address rather than naming a value
135/// is the same move [`Widening`] makes, and it means a reader that wants the address in front of
136/// the loop writes another `global_addr` there for the one instruction it costs. On the SQLite
137/// amalgamation that is 178 checks at 47 sites of loop splitting's largest census row.
138/// See tamnd/rucc#810.
139#[derive(Clone, Copy, Debug, PartialEq, Eq)]
140pub enum Anchor {
141 /// A value, which is defined outside the loop and so can be named where it is wanted.
142 Value(Value),
143 /// The address of a global, which is written again wherever it is wanted.
144 Address(Symbol),
145}
146
147impl Anchor {
148 /// The value, when it is one. `None` for an address, which no value names.
149 #[must_use]
150 pub fn value(self) -> Option<Value> {
151 match self {
152 Self::Value(value) => Some(value),
153 Self::Address(_) => None,
154 }
155 }
156}
157
158/// A value read at a type wider than its own.
159///
160/// Widening `{start, +, 1}` in `int` gives `{sext(start), +, 1}` in `long`, and `sext(start)` is an
161/// expression nothing in the function computes. A representation that could only name values had
162/// to refuse the whole widening on that account, which is what shut the door on a walk from an
163/// index the caller handed in, because in C that index is an `int`. So the extension is described
164/// rather than named and whoever builds code from the invariant emits it.
165///
166/// The value stays the narrow one. Reading it at a third width later is an extension of an
167/// extension, and the two collapse into one wherever they mean the same thing, which is everywhere
168/// except a zero extension read as signed afterwards.
169#[derive(Clone, Copy, Debug, PartialEq, Eq)]
170pub struct Widening {
171 /// Sign extended or zero extended.
172 pub reading: Reading,
173 /// The type it is read at, which is wider than the value's own.
174 pub to: Type,
175}
176
177/// An invariant with no second symbol in it, read as `scale * value + offset`.
178///
179/// What every reader but [`crate::split`] wants, and what every reader wanted before there was an
180/// `on` at all. [`Invariant::plain`] is the only way to one, so a reader that does not know about
181/// the second symbol cannot get an expression that has one.
182#[derive(Clone, Copy, Debug, PartialEq, Eq)]
183pub struct Plain {
184 /// What it is built on, or `None` for a plain number.
185 pub value: Option<Value>,
186 /// How that value is read, when it is read at a width that is not its own.
187 pub read: Option<Widening>,
188 /// How many of it.
189 pub scale: i128,
190 /// What is added to it.
191 pub offset: i128,
192}
193
194impl Invariant {
195 /// A plain number.
196 #[must_use]
197 pub fn number(offset: i128) -> Self {
198 Self { on: None, value: None, read: None, scale: 0, offset }
199 }
200
201 /// One of a value.
202 #[must_use]
203 pub fn of(value: Value) -> Self {
204 Self { on: None, value: Some(value), read: None, scale: 1, offset: 0 }
205 }
206
207 /// So many of a value, plus a number.
208 #[must_use]
209 pub fn scaled(value: Value, scale: i128, offset: i128) -> Self {
210 Self { on: None, value: Some(value), read: None, scale, offset }
211 }
212
213 /// The address of a global.
214 ///
215 /// It goes straight into the `on` slot rather than into `value`, because that slot is the one
216 /// for the thing an address is measured from and an address is the only thing this ever is.
217 /// Nothing scales it and nothing negates it, which the rest of the arithmetic here already
218 /// refuses for whatever is in that slot.
219 #[must_use]
220 pub fn address(symbol: Symbol) -> Self {
221 Self { on: Some(Anchor::Address(symbol)), value: None, read: None, scale: 0, offset: 0 }
222 }
223
224 /// The one symbol reading, and `None` when there is a second symbol in it.
225 #[must_use]
226 pub fn plain(self) -> Option<Plain> {
227 self.on.is_none().then_some(Plain {
228 value: self.value,
229 read: self.read,
230 scale: self.scale,
231 offset: self.offset,
232 })
233 }
234
235 /// What it is measured from and how far past that, when there is a second symbol in it.
236 ///
237 /// Exactly one of this and [`Invariant::plain`] answers, so a reader that handles both has
238 /// handled every invariant there is.
239 #[must_use]
240 pub fn on(self) -> Option<(Anchor, Plain)> {
241 let on = self.on?;
242 Some((
243 on,
244 Plain { value: self.value, read: self.read, scale: self.scale, offset: self.offset },
245 ))
246 }
247
248 /// Whether the two are the same expression apart from the number added to them.
249 #[must_use]
250 pub fn alike(self, other: Self) -> bool {
251 self.on == other.on
252 && self.value == other.value
253 && self.read == other.read
254 && self.scale == other.scale
255 }
256
257 /// The number added to it, whatever else it has in it.
258 #[must_use]
259 pub fn offset(self) -> i128 {
260 self.offset
261 }
262
263 /// The number this is, when it is one.
264 #[must_use]
265 pub fn as_number(self) -> Option<i128> {
266 (self.on.is_none() && self.symbol().is_none()).then_some(self.offset)
267 }
268
269 /// Whether this is the number zero.
270 #[must_use]
271 pub fn is_zero(self) -> bool {
272 self.as_number() == Some(0)
273 }
274
275 /// The value the linear part is built on, when the linear part has one.
276 fn symbol(self) -> Option<Value> {
277 if self.scale == 0 { None } else { self.value }
278 }
279
280 /// This as something to measure from, when it is one of a value and a number.
281 ///
282 /// Never a widened one. What an expression is measured from is a pointer, and a pointer is not
283 /// something anything here extends.
284 fn measure(self) -> Option<Anchor> {
285 (self.on.is_none() && self.read.is_none() && self.scale == 1)
286 .then_some(self.value)
287 .flatten()
288 .map(Anchor::Value)
289 }
290
291 /// The symbol both linear parts are built on and how it is read, when they agree on one or one
292 /// of them has none.
293 ///
294 /// The same value read two ways is two different numbers, so agreeing on the value is not
295 /// enough. `sext(x)` and `zext(x)` are the same bits and not the same quantity.
296 fn shared(self, other: Self) -> Option<(Option<Value>, Option<Widening>)> {
297 match (self.symbol(), other.symbol()) {
298 (None, _) => Some((other.value, other.read)),
299 (_, None) => Some((self.value, self.read)),
300 (left, right) => {
301 (left == right && self.read == other.read).then_some((left, self.read))
302 }
303 }
304 }
305
306 /// This same value read at a wider type, when the widening has a form here.
307 ///
308 /// A number means the same thing at both widths under a sign extension, and under a zero
309 /// extension once it is not negative. One of a value becomes that value read through the
310 /// extension. Anything else is refused, because the narrow arithmetic may already have wrapped
311 /// and `sext(2 * x + 3)` is not `2 * sext(x) + 3`.
312 fn widened(self, reading: Reading, to: Type) -> Option<Self> {
313 if let Some(number) = self.as_number() {
314 return (reading == Reading::Signed || number >= 0).then_some(Self::number(number));
315 }
316 if self.on.is_some() || self.scale != 1 || self.offset != 0 {
317 return None;
318 }
319 let value = self.value?;
320 // An extension of an extension. A zero extension is never negative, so reading its result
321 // as signed afterwards is the same numbers and the pair collapses into the zero extension
322 // at the outer width. The other way round it does not: a sign extension of a negative
323 // number read as unsigned afterwards is a different number entirely.
324 let reading = match (self.read.map(|read| read.reading), reading) {
325 (None, outer) => outer,
326 (Some(Reading::Unsigned), _) => Reading::Unsigned,
327 (Some(Reading::Signed), Reading::Signed) => Reading::Signed,
328 (Some(Reading::Signed), Reading::Unsigned) => return None,
329 };
330 Some(Self {
331 on: None,
332 value: Some(value),
333 read: Some(Widening { reading, to }),
334 scale: 1,
335 offset: 0,
336 })
337 }
338
339 /// The two added, when the sum is of this shape.
340 #[must_use]
341 pub fn plus(self, other: Self) -> Option<Self> {
342 let offset = self.offset.checked_add(other.offset)?;
343 // At most one of the two brought something to measure from, since a sum measured from two
344 // pointers is not an address.
345 let on = match (self.on, other.on) {
346 (None, on) | (on, None) => on,
347 (Some(_), Some(_)) => return None,
348 };
349 // The linear parts are about the same symbol, or one of them is a number, so they add.
350 if let Some((value, read)) = self.shared(other) {
351 let scale = self.scale.checked_add(other.scale)?;
352 return Some(Self { on, value, read, scale, offset });
353 }
354 // Two different symbols, which is what a pointer plus an index the loop did not start at
355 // zero is. Nothing may already be measured from anything, and one of the two has to be one
356 // of a value and a number, and that one becomes what the sum is measured from.
357 if on.is_some() {
358 return None;
359 }
360 let (on, rest) = match (self.measure(), other.measure()) {
361 (Some(on), _) => (on, other),
362 (_, Some(on)) => (on, self),
363 _ => return None,
364 };
365 Some(Self { on: Some(on), value: rest.value, read: rest.read, scale: rest.scale, offset })
366 }
367
368 /// The second subtracted from the first, when the difference is of this shape.
369 #[must_use]
370 pub fn minus(self, other: Self) -> Option<Self> {
371 self.plus(other.negated()?)
372 }
373
374 /// This with its sign flipped, which needs nothing to measure from.
375 ///
376 /// A pointer is not a thing to negate, and the second symbol is only ever there because a
377 /// pointer put it there.
378 #[must_use]
379 pub fn negated(self) -> Option<Self> {
380 if self.on.is_some() {
381 return None;
382 }
383 Some(Self {
384 on: None,
385 value: self.value,
386 read: self.read,
387 scale: self.scale.checked_neg()?,
388 offset: self.offset.checked_neg()?,
389 })
390 }
391
392 /// The two multiplied, which needs one of them to be a plain number and neither to be measured
393 /// from anything.
394 #[must_use]
395 pub fn times(self, other: Self) -> Option<Self> {
396 if self.on.is_some() || other.on.is_some() {
397 return None;
398 }
399 let (symbol, by) = match (self.as_number(), other.as_number()) {
400 (Some(by), _) => (other, by),
401 (_, Some(by)) => (self, by),
402 _ => return None,
403 };
404 Some(Self {
405 on: None,
406 value: symbol.value,
407 read: symbol.read,
408 scale: symbol.scale.checked_mul(by)?,
409 offset: symbol.offset.checked_mul(by)?,
410 })
411 }
412}
413
414/// How a value changes from one iteration of a loop to the next.
415#[derive(Clone, Copy, Debug, PartialEq, Eq)]
416pub enum Evolution {
417 /// The same on every iteration.
418 Invariant(Invariant),
419 /// `{base, +, step}`: `base` the first time round and `step` more each time after.
420 Affine(Chrec),
421 /// Not something this analysis describes. Never a claim that the value does not evolve.
422 Unknown,
423}
424
425impl Evolution {
426 /// The chrec, when this is one.
427 #[must_use]
428 pub fn chrec(self) -> Option<Chrec> {
429 match self {
430 Self::Affine(chrec) => Some(chrec),
431 _ => None,
432 }
433 }
434
435 /// The invariant expression, when this is one.
436 #[must_use]
437 pub fn invariant(self) -> Option<Invariant> {
438 match self {
439 Self::Invariant(inv) => Some(inv),
440 _ => None,
441 }
442 }
443}
444
445/// An affine chain of recurrences, `{base, +, step}`, evolving in a named type.
446///
447/// The type is not decoration. `{0, +, 1}` in `unsigned char` is not the sequence `0, 1, 2, ...`,
448/// it is that sequence modulo two hundred and fifty six, and section 7.7 says this is where a
449/// naive implementation is wrong constantly and in ways that pass every test written by someone
450/// thinking in `int`. Every operation here checks the type and every one that cannot stay right
451/// in it answers unknown.
452#[derive(Clone, Copy, Debug, PartialEq, Eq)]
453pub struct Chrec {
454 /// What the value is on the first iteration.
455 pub base: Invariant,
456 /// What is added each time round.
457 pub step: Invariant,
458 /// The type it evolves in, which is what says when it wraps.
459 pub ty: Type,
460 /// What the instruction that increments it promised. `nsw` means the sequence does not wrap
461 /// when read as signed and `nuw` means it does not when read as unsigned, and both come from
462 /// the increment rather than from anything this analysis proved.
463 pub flags: Flags,
464}
465
466impl Chrec {
467 /// Whether the sequence is known not to wrap under the reading this predicate takes.
468 #[must_use]
469 pub fn does_not_wrap(self, signed: bool) -> bool {
470 self.flags.contains(if signed { Flags::NSW } else { Flags::NUW })
471 }
472}
473
474/// Something that has to be true for a trip count to be the right answer.
475///
476/// Section 7.5 asks for exactly this: not a trip count but a trip count plus a predicate under
477/// which it holds, so the consumer either proves the predicate, emits a runtime check for it, or
478/// gives up. These are the predicates.
479#[derive(Clone, Copy, Debug, PartialEq, Eq)]
480pub enum Assumption {
481 /// The loop is entered at all, so the distance from the counter to its limit is a number that
482 /// is not negative.
483 ///
484 /// `for (i = 0; i < n; i++)` with `n` of zero runs no times and the distance is zero, but `n`
485 /// of minus one also runs no times and the distance is minus one, so a count taken from the
486 /// distance has to be told which case it is in.
487 ///
488 /// What it does not say anything about is whether the loop comes back. A counter stepping
489 /// toward a limit under an ordering test either reaches it or is already past it, and either
490 /// way that is a finite number of steps, so a caller whose question is whether the loop ends
491 /// may have this one for nothing. [`crate::hoist`] discharges it by clamping the count at zero
492 /// and [`crate::loop_delete`] by never reading the count. That is the whole of why this is a
493 /// separate assumption from [`Assumption::Approaching`] rather than the same one worded to
494 /// cover both.
495 ///
496 /// Only ever present on a symbolic count. When the distance is a number the sign of it is
497 /// there to be read, so this is settled rather than assumed.
498 Entered,
499 /// The limit is somewhere the counter is heading, which for a loop ending on `!=` is what
500 /// makes it end at all.
501 ///
502 /// A counter stepping away from its limit never arrives, and one stepping past it keeps going
503 /// until it wraps, so what is unproven here is termination rather than which number the count
504 /// is. Nothing discharges it by clamping, because there is no number to clamp when the loop
505 /// does not come back. Document 17.2 says rucc does not take out a loop that might not end,
506 /// so a pass that deletes loops refuses this one outright.
507 ///
508 /// Only ever present on a symbolic count, for the same reason [`Assumption::Entered`] is.
509 Approaching,
510 /// The induction variable does not wrap in its own type before the exit is taken.
511 ///
512 /// Present whenever the increment did not carry the matching `nsw` or `nuw` flag. With the
513 /// flag there is nothing to assume, because the flag is the promise.
514 NoWrap(Chrec),
515 /// Signed overflow is undefined here, which is what makes `for (int i = 0; i <= n; i++)`
516 /// finite.
517 ///
518 /// GCC infers loop bounds from this in `infer_loop_bounds_from_signedness`, and it is the
519 /// single most common source of a report that the compiler broke a working program. It is
520 /// recorded rather than assumed silently so that `-fwrapv` can withdraw the count and so that
521 /// a dump can name it.
522 StrictOverflow,
523}
524
525impl Assumption {
526 /// What it says, in a line, for a dump to print.
527 ///
528 /// Section 7.5 asks that every inference of this kind be dumpable and say what it rests on,
529 /// because a user who has been bitten by one deserves a command that tells them which line
530 /// the compiler used against them. This is the sentence that command prints.
531 #[must_use]
532 pub fn describe(&self) -> String {
533 match self {
534 Self::Entered => "the loop is entered at all".to_string(),
535 Self::Approaching => "the counter is heading towards its limit".to_string(),
536 Self::NoWrap(chrec) => {
537 format!("the induction variable does not wrap in i{}", chrec.ty.bits())
538 }
539 Self::StrictOverflow => {
540 "signed overflow is undefined, so -fwrapv withdraws this count".to_string()
541 }
542 }
543 }
544}
545
546/// How many iterations, as a number or as an expression.
547#[derive(Clone, Copy, Debug, PartialEq, Eq)]
548pub enum Count {
549 /// Exactly this many.
550 Exact(u128),
551 /// This many, worked out from something the loop does not change.
552 Symbolic(Invariant),
553}
554
555/// Which reading of its operands the test the count came from took.
556///
557/// It matters to anybody widening the value a symbolic count is built out of. The count is the
558/// distance to the limit of the exit test, the limit is a value of the counter's own type, and
559/// what that value means is the reading its test took. A limit past the middle of a thirty two bit
560/// type is a large number to an unsigned test and a negative one to a signed test, and a consumer
561/// that sign extends what an unsigned test compared has turned a loop over three billion elements
562/// into a loop that runs no times.
563#[derive(Clone, Copy, Debug, PartialEq, Eq)]
564pub enum Reading {
565 /// The test read its operands as signed, so widening the count means sign extending it.
566 Signed,
567 /// The test read them as unsigned, so widening the count means zero extending it.
568 Unsigned,
569}
570
571/// How many times a loop runs at most, and what that rests on.
572///
573/// For correctness. A pass that deletes an iteration, peels one off, or decides a memory access
574/// is in bounds needs one of these. The count cannot be read without the assumptions, which is
575/// section 7.7's defence against a caller proving two of three and forgetting the third.
576#[derive(Clone, Debug, PartialEq, Eq)]
577pub struct Bound {
578 count: Count,
579 assumptions: Vec<Assumption>,
580 reading: Reading,
581}
582
583impl Bound {
584 /// The count and everything it rests on, together, because they cannot be asked for apart.
585 #[must_use]
586 pub fn parts(&self) -> (Count, &[Assumption]) {
587 (self.count, &self.assumptions)
588 }
589
590 /// How the value a symbolic count is built out of has to be read.
591 ///
592 /// Meaningless on a count that is a number, since a number has already been read.
593 #[must_use]
594 pub fn reading(&self) -> Reading {
595 self.reading
596 }
597
598 /// What has to be proved before the count means anything.
599 #[must_use]
600 pub fn assumptions(&self) -> &[Assumption] {
601 &self.assumptions
602 }
603
604 /// The count, for a caller with nothing left to prove.
605 ///
606 /// `None` does not mean the count is unknown. It means there are assumptions and this is not
607 /// the accessor for reading a count that has them.
608 #[must_use]
609 pub fn proven(&self) -> Option<Count> {
610 self.assumptions.is_empty().then_some(self.count)
611 }
612
613 /// The count, for a caller compiling a language where signed overflow is undefined.
614 ///
615 /// [`Bound::proven`] answers nothing for any `for (int i = 0; i < n; i++)` in any C program,
616 /// because `solve` puts [`Assumption::StrictOverflow`] on every count taken from a signed
617 /// test, and a pass built on `proven` alone is a pass that never fires. What that assumption
618 /// says is that the count rests on signed overflow being undefined, and `-fwrapv` is
619 /// implemented in `rucc-lower` by not setting `nsw` rather than by a flag anything down here
620 /// reads. So an increment that still carries `nsw` under `-fwrapv` does not exist, and a bound
621 /// with `StrictOverflow` and nothing else on it is a bound whose counter the front end
622 /// promised does not wrap. That promise is exactly what the assumption wanted.
623 ///
624 /// [`Assumption::NoWrap`] is the case where there is no such promise, and it is refused here.
625 /// So are [`Assumption::Entered`] and [`Assumption::Approaching`], though only in passing,
626 /// because neither ever appears on a count that is a number.
627 #[must_use]
628 pub fn under_undefined_overflow(&self) -> Option<Count> {
629 self.assumptions
630 .iter()
631 .all(|rests_on| matches!(rests_on, Assumption::StrictOverflow))
632 .then_some(self.count)
633 }
634
635 /// The count, for a caller that needs the loop to come back and not how many times.
636 ///
637 /// One assumption wider than [`Bound::under_undefined_overflow`], and the one it adds is
638 /// [`Assumption::Entered`]. What that says is whether the count is the distance to the limit
639 /// or zero, and both of those are numbers of iterations the loop has, so a pass asking whether
640 /// the loop ends has already been answered whichever way it goes. A pass multiplying by the
641 /// count has not, which is why this is a second accessor and not a loosening of the first.
642 ///
643 /// [`Assumption::Approaching`] is refused, and telling those two apart is the reason they are
644 /// two assumptions. A loop ending on `!=` whose counter steps past its limit runs until it
645 /// wraps, document 17.2 is explicit that rucc does not take out a loop that might not end, and
646 /// a count that comes back from here is one no caller has to check that against.
647 #[must_use]
648 pub fn comes_back(&self) -> Option<Count> {
649 self.assumptions
650 .iter()
651 .all(|rests_on| matches!(rests_on, Assumption::StrictOverflow | Assumption::Entered))
652 .then_some(self.count)
653 }
654}
655
656/// How many times a loop probably runs.
657///
658/// For cost decisions and never for correctness. A pass asking whether unrolling pays for itself
659/// wants one of these, and it is fine for the answer to be a guess, because being wrong makes the
660/// code slower rather than wrong. Nothing here can be turned into a [`Bound`].
661#[derive(Clone, Copy, Debug, PartialEq, Eq)]
662pub struct Estimate {
663 iterations: u64,
664 guessed: bool,
665}
666
667impl Estimate {
668 /// The number to do arithmetic with.
669 #[must_use]
670 pub fn iterations(self) -> u64 {
671 self.iterations
672 }
673
674 /// Whether nothing was known and this is the default.
675 #[must_use]
676 pub fn is_guess(self) -> bool {
677 self.guessed
678 }
679}
680
681/// An exit test, read so that the loop keeps going while it holds.
682///
683/// Not public. It is the shape [`Scev::bound_at`] and [`Scev::holds`] both want out of the same
684/// branch, and what either of them says about it is what the outside sees.
685#[derive(Clone, Copy, Debug)]
686struct Test {
687 /// The side that moves, with the predicate already turned round to put it on the left.
688 chrec: Chrec,
689 /// The side that does not.
690 limit: Invariant,
691 /// The comparison that has to hold for the loop to go round again.
692 pred: IntPred,
693 /// Whether every iteration that goes round asks it.
694 each: bool,
695}
696
697/// The analysis, which works out an answer when asked and remembers it.
698///
699/// Demand driven and memoized, per section 7.8, because the cost of scalar evolution is a
700/// function of how many distinct values get asked about rather than of the size of the function.
701/// The cache holds one loop's worth of answers per loop and the whole thing is thrown away when
702/// anything about the loops changes, which per document 04.4 is any pass that touches one.
703#[derive(Debug)]
704pub struct Scev<'a> {
705 func: &'a Func,
706 cfg: &'a Cfg,
707 loops: &'a Loops,
708 known: HashMap<(LoopId, Value), Evolution>,
709 held: HashMap<LoopId, Option<Chrec>>,
710}
711
712impl<'a> Scev<'a> {
713 /// A fresh analysis over these loops, knowing nothing yet.
714 #[must_use]
715 pub fn new(func: &'a Func, cfg: &'a Cfg, loops: &'a Loops) -> Self {
716 Self { func, cfg, loops, known: HashMap::new(), held: HashMap::new() }
717 }
718
719 /// How this value changes across the iterations of this loop.
720 ///
721 /// The way in, and what it does before answering is settle `Scev::holds` for the loop. That has
722 /// to happen out here rather than at the point `Scev::extend` wants it, because settling it
723 /// means asking about other values and `Scev::at` parks a marker on the value it is working on.
724 /// Asked from in there, the answer would depend on what was already in flight.
725 pub fn evolution(&mut self, id: LoopId, value: Value) -> Evolution {
726 self.holds(id);
727 self.at(id, value)
728 }
729
730 /// How this value changes, with the loop's own facts already settled.
731 fn at(&mut self, id: LoopId, value: Value) -> Evolution {
732 if let Some(&known) = self.known.get(&(id, value)) {
733 return known;
734 }
735 // Unknown while the answer is being worked out, so the cycle from a header parameter back
736 // to itself terminates instead of asking the same question forever. Anything that reaches
737 // the parameter again gets unknown and the shape it was matching fails, which is the
738 // right answer for a value defined in terms of itself through arithmetic this does not
739 // describe.
740 self.known.insert((id, value), Evolution::Unknown);
741 let found = self.compute(id, value);
742 self.known.insert((id, value), found);
743 found
744 }
745
746 /// How many times this loop runs at most, and what that rests on.
747 ///
748 /// Any one exit gives a valid upper bound, because a loop cannot run more times than the
749 /// first exit that fires, so this takes the first exit it can solve rather than the smallest.
750 /// That is `max_loop_iterations` and not `estimate_numbers_of_iterations`, which is why the
751 /// answer is a [`Bound`].
752 pub fn bound(&mut self, id: LoopId) -> Option<Bound> {
753 self.holds(id);
754 let exits: Vec<Block> = self.loops.exits(id).iter().map(|exit| exit.from).collect();
755 exits.into_iter().find_map(|from| self.bound_at(id, from))
756 }
757
758 /// The counter an exit test of this loop keeps inside its own type, when there is one.
759 ///
760 /// [`bounded_by_its_test`] is the argument and this is where its answer is written down as a
761 /// fact about the loop rather than spent on one trip count. What it buys is [`Scev::extend`]:
762 /// an unsigned counter carries no `nuw`, so widening anything built out of one used to be
763 /// refused, and the test that holds the counter holds everything walking beside it.
764 ///
765 /// Settled once per loop and then read. It is settled from [`Scev::evolution`] and
766 /// [`Scev::bound`], which are the two ways in, so that it is worked out with nothing in flight.
767 /// The cache for the loop is emptied afterwards, because the answers already in it were worked
768 /// out while this was still unknown and a conservative answer that stayed would make what the
769 /// analysis says depend on which question was asked first.
770 fn holds(&mut self, id: LoopId) -> Option<Chrec> {
771 if let Some(&known) = self.held.get(&id) {
772 return known;
773 }
774 // Unknown while it is being worked out, which is what stops the recursion below from
775 // asking the same question forever, and which is why the cache is emptied after.
776 self.held.insert(id, None);
777 let exits: Vec<Block> = self.loops.exits(id).iter().map(|exit| exit.from).collect();
778 let found = exits.into_iter().find_map(|from| {
779 let test = self.test_at(id, from)?;
780 let step = test.chrec.step.as_number()?;
781 (test.each && bounded_by_its_test(test.pred, step)).then_some(test.chrec)
782 });
783 self.held.insert(id, found);
784 self.known.retain(|&(of, _), _| of != id);
785 found
786 }
787
788 /// How many times this loop probably runs.
789 pub fn estimate(&mut self, id: LoopId) -> Estimate {
790 match self.bound(id).map(|bound| bound.count) {
791 Some(Count::Exact(exact)) => {
792 Estimate { iterations: u64::try_from(exact).unwrap_or(u64::MAX), guessed: false }
793 }
794 _ => Estimate { iterations: ASSUMED_ITERATIONS, guessed: true },
795 }
796 }
797
798 /// The evolution of a value nothing is known about yet.
799 fn compute(&mut self, id: LoopId, value: Value) -> Evolution {
800 if let Some(invariant) = self.invariant(id, value) {
801 return Evolution::Invariant(invariant);
802 }
803 match self.func[value].def {
804 Def::Param { block, index } if block == self.loops.header(id) => {
805 self.at_header(id, value, index as usize)
806 }
807 // A parameter of a block inside the loop that is not the header takes a different
808 // value depending on which way control came, and describing that is a job for the
809 // value range work of document 10 rather than for a chrec. Unless there is only one
810 // way in, in which case it does not.
811 Def::Param { .. } => match self.forwarded(value) {
812 same if same == value => Evolution::Unknown,
813 through => self.at(id, through),
814 },
815 Def::Result { inst, .. } => self.at_inst(id, inst, value),
816 }
817 }
818
819 /// The value as an expression that does not change inside the loop, if it is one.
820 fn invariant(&self, id: LoopId, value: Value) -> Option<Invariant> {
821 if let Some((imm, ty)) = constant(self.func, value) {
822 return Some(Invariant::number(imm.signed(ty)));
823 }
824 // A constant is invariant wherever it sits, which is why it is asked about first. Anything
825 // else has to be defined outside the loop.
826 if self.loops.is_invariant(self.func, id, value) {
827 return Some(Invariant::of(value));
828 }
829 // Except the address of a global, which is a link time constant and so does not change
830 // inside a loop wherever it is written. Asked after the question above and not instead of
831 // it, so that a `global_addr` already sitting outside the loop stays a value every reader
832 // can name, and this arm is only the case that used to come out unknown. See [`Anchor`].
833 symbol(self.func, value).map(Invariant::address)
834 }
835
836 /// The evolution of a parameter of the loop header, which is where an induction variable is.
837 ///
838 /// The parameter takes one value on the way in and another on the way round, which is what
839 /// other IRs spell as a phi node. If the way round is the parameter plus something invariant,
840 /// the parameter is an affine chrec and that something is its step.
841 fn at_header(&mut self, id: LoopId, value: Value, index: usize) -> Evolution {
842 let (func, cfg, loops) = (self.func, self.cfg, self.loops);
843 let header = loops.header(id);
844 // Section 7.3 wants exactly one latch and the canonicalizer makes one. Two of them means
845 // two ways round with two different increments, and picking one would be a guess.
846 let [latch] = loops.latches(id) else { return Evolution::Unknown };
847 let mut entering = None;
848 let mut around = None;
849 for &pred in cfg.predecessors(header) {
850 let Some(arg) = argument(func, pred, header, index) else { return Evolution::Unknown };
851 let arg = self.forwarded(arg);
852 let slot = if pred == *latch { &mut around } else { &mut entering };
853 if slot.replace(arg).is_some_and(|old| old != arg) {
854 return Evolution::Unknown;
855 }
856 }
857 let (Some(entering), Some(around)) = (entering, around) else { return Evolution::Unknown };
858 let Some(base) = self.invariant(id, entering) else { return Evolution::Unknown };
859 let Some((step, flags)) = self.step(id, around, value, 0) else {
860 return Evolution::Unknown;
861 };
862 affine(base, step, func[value].ty, flags)
863 }
864
865 /// The value a block parameter stands for, when there is only one way into its block.
866 ///
867 /// This is not an analysis, it is undoing a rename. A block with one predecessor has one value
868 /// for each of its parameters and it is the argument that predecessor passes, so reading
869 /// through it loses nothing and assumes nothing.
870 ///
871 /// It is here because of what canonicalization does. `crate::canon` splits the back edge of a
872 /// loop to give it a latch of its own, and after that the value going round the loop is not the
873 /// increment the loop computed, it is a parameter of a block that does nothing but pass the
874 /// increment on. Without this, every counted loop the pipeline actually produces looks like a
875 /// loop whose counter comes from somewhere unknown, and the trip count of a `for` loop in a
876 /// real function comes back as nothing.
877 fn forwarded(&self, value: Value) -> Value {
878 let mut value = value;
879 for _ in 0..FORWARD_LIMIT {
880 let Def::Param { block, index } = self.func[value].def else { return value };
881 let [pred] = self.cfg.predecessors(block) else { return value };
882 let Some(arg) = argument(self.func, *pred, block, index as usize) else { return value };
883 if arg == value {
884 return value;
885 }
886 value = arg;
887 }
888 value
889 }
890
891 /// What is added to `of` to get `value`, and what the additions promised.
892 ///
893 /// Written as its own walk rather than as the general combination below, because at the point
894 /// this runs the parameter's own evolution is not known yet and the general walk would ask
895 /// for it and get unknown.
896 fn step(&self, id: LoopId, value: Value, of: Value, depth: u32) -> Option<(Invariant, Flags)> {
897 let value = self.forwarded(value);
898 if value == of {
899 // Nothing added yet, and nothing has had a chance to overflow either.
900 return Some((Invariant::number(0), Flags::NSW.union(Flags::NUW)));
901 }
902 if depth >= STEP_LIMIT {
903 return None;
904 }
905 let Def::Result { inst, .. } = self.func[value].def else { return None };
906 let data = &self.func[inst];
907 let args = &self.func[data.args];
908 let (&lhs, &rhs) = (args.first()?, args.get(1)?);
909 let combine = |carried: (Invariant, Flags), other: Invariant, subtract: bool| {
910 let (delta, flags) = carried;
911 let moved = if subtract { delta.minus(other)? } else { delta.plus(other)? };
912 Some((moved, flags.intersection(data.flags)))
913 };
914 match data.opcode {
915 Opcode::Add => {
916 if let Some(carried) = self.step(id, lhs, of, depth + 1) {
917 return combine(carried, self.invariant(id, rhs)?, false);
918 }
919 combine(self.step(id, rhs, of, depth + 1)?, self.invariant(id, lhs)?, false)
920 }
921 Opcode::Sub => {
922 combine(self.step(id, lhs, of, depth + 1)?, self.invariant(id, rhs)?, true)
923 }
924 // A pointer walks by bytes, and only the pointer side can be the one carrying the
925 // induction variable. The offset is the step, which is the element size the front end
926 // already multiplied in.
927 Opcode::PtrAdd => {
928 combine(self.step(id, lhs, of, depth + 1)?, self.invariant(id, rhs)?, false)
929 }
930 _ => None,
931 }
932 }
933
934 /// The evolution of an instruction's result, from the evolutions of its operands.
935 fn at_inst(&mut self, id: LoopId, inst: Inst, value: Value) -> Evolution {
936 let func = self.func;
937 let data = &func[inst];
938 let (opcode, flags) = (data.opcode, data.flags);
939 let args = &func[data.args];
940 let ty = func[value].ty;
941 let Some(&lhs) = args.first() else { return Evolution::Unknown };
942 match opcode {
943 Opcode::Add | Opcode::PtrAdd => {
944 let Some(&rhs) = args.get(1) else { return Evolution::Unknown };
945 let (left, right) = (self.at(id, lhs), self.at(id, rhs));
946 combine(left, right, ty, flags, false)
947 }
948 Opcode::Sub => {
949 let Some(&rhs) = args.get(1) else { return Evolution::Unknown };
950 let (left, right) = (self.at(id, lhs), self.at(id, rhs));
951 combine(left, right, ty, flags, true)
952 }
953 Opcode::Mul => {
954 let Some(&rhs) = args.get(1) else { return Evolution::Unknown };
955 let (left, right) = (self.at(id, lhs), self.at(id, rhs));
956 scale(left, right, ty, flags)
957 }
958 // A shift by a constant is a multiplication by a power of two, and only by a constant:
959 // a variable count is invariant in the loop and still not a number this can multiply
960 // by. A count at or above the width is poison rather than a shift to zero, so the
961 // range is checked here rather than assumed.
962 Opcode::Shl => {
963 let Some(&rhs) = args.get(1) else { return Evolution::Unknown };
964 let Some((count, count_ty)) = constant(func, rhs) else {
965 return Evolution::Unknown;
966 };
967 let count = count.unsigned();
968 if count >= u128::from(ty.bits()) || !count_ty.is_int() {
969 return Evolution::Unknown;
970 }
971 let by = Evolution::Invariant(Invariant::number(1i128 << count));
972 scale(self.at(id, lhs), by, ty, flags)
973 }
974 Opcode::SExt | Opcode::ZExt => self.extend(id, opcode, lhs, ty),
975 // A truncation is a wrap by construction, so a chrec through one describes a sequence
976 // that restarts, and this does not have a representation for that.
977 _ => Evolution::Unknown,
978 }
979 }
980
981 /// A chrec widened, which needs the sequence not to wrap at the narrow width.
982 ///
983 /// Section 7.4 allows extension only where the extension provably does not wrap, and the first
984 /// proof here is the flag the increment carries. `nsw` on the increment is the promise that the
985 /// signed sequence does not wrap, which is exactly what makes the wide sequence the same
986 /// numbers as the narrow one.
987 ///
988 /// The second proof is the loop's own exit test, through [`Scev::holds`] and [`trails`], and it
989 /// is here because of what an unsigned counter looks like. `for (unsigned i = 0; i < n; i++)`
990 /// carries no `nuw`, because C says unsigned arithmetic wraps, so `a[i]` on that counter used
991 /// to come back unwidened and every bounds check in the loop stayed where it was. The test that
992 /// keeps the counter inside its type keeps everything walking beside it inside too.
993 ///
994 /// Each part is either a plain number or one of a value, and nothing else. A number means the
995 /// same thing at both widths, and one of a value becomes that value read through the extension,
996 /// which is what [`Widening`] is for. Anything with arithmetic in it is refused, because the
997 /// narrow arithmetic may already have wrapped and `sext(2 * x + 3)` is not `2 * sext(x) + 3`.
998 /// What that leaves out is a base like `start + 1`, and what it lets in is `start`, which is
999 /// the shape a walk from an index the caller handed in is in. See #810.
1000 ///
1001 /// A value the loop does not change is widened by the same rule. It used to be widened only
1002 /// when it was a number, and everything else came back unknown, which is a sequence that does
1003 /// not move being harder to widen than one that does. What it cost is the row of a two
1004 /// dimensional array: `a[row * N + k]` round `k` has `(long)row * N` in it, that is invariant
1005 /// and is not a number, so the address of the whole subscript came back unknown and every pass
1006 /// reading it had nothing to work with. There is no wrapping question to answer here, because
1007 /// there is no sequence and so nothing to wrap, and the shapes that get through are the same
1008 /// ones [`Invariant::widened`] lets through for a chrec's base.
1009 fn extend(&mut self, id: LoopId, opcode: Opcode, from: Value, to: Type) -> Evolution {
1010 let narrow = self.func[from].ty;
1011 let signed = opcode == Opcode::SExt;
1012 let held = self.held.get(&id).copied().flatten();
1013 let settled = |chrec: Chrec| {
1014 chrec.does_not_wrap(signed) || (!signed && held.is_some_and(|held| trails(chrec, held)))
1015 };
1016 let reading = if signed { Reading::Signed } else { Reading::Unsigned };
1017 match self.at(id, from) {
1018 Evolution::Invariant(inv) => match inv.as_number() {
1019 // A number read at the narrow width means the same thing at the wide one under
1020 // sign extension, and under zero extension once it is not negative.
1021 Some(number) if signed || number >= 0 => Evolution::Invariant(inv),
1022 Some(_) => Evolution::Unknown,
1023 // Not a number, and still the same value read wider. This is the widening a chrec
1024 // gets, asked about something that does not move: `(long)row * 64` inside a loop
1025 // over `k` is an expression the loop does not change, and it used to come back
1026 // unknown, which made the whole of `a[row * N + k]` unknown. [`Invariant::widened`]
1027 // is the one that decides, and it refuses anything with arithmetic in it for the
1028 // reason written on it, so what gets through is one of a value and nothing else.
1029 None => match inv.widened(reading, to) {
1030 Some(wide) => Evolution::Invariant(wide),
1031 None => Evolution::Unknown,
1032 },
1033 },
1034 Evolution::Affine(chrec) if chrec.ty == narrow && settled(chrec) => {
1035 let (Some(base), Some(step)) =
1036 (chrec.base.widened(reading, to), chrec.step.widened(reading, to))
1037 else {
1038 return Evolution::Unknown;
1039 };
1040 Evolution::Affine(Chrec { base, step, ty: to, flags: chrec.flags })
1041 }
1042 _ => Evolution::Unknown,
1043 }
1044 }
1045
1046 /// The trip count from the exit leaving this block, if this exit can be solved.
1047 fn bound_at(&mut self, id: LoopId, from: Block) -> Option<Bound> {
1048 let test = self.test_at(id, from)?;
1049 solve(test.chrec, test.limit, test.pred, test.each)
1050 }
1051
1052 /// The exit test leaving this block, read into the pieces its two readers want.
1053 ///
1054 /// [`Scev::bound_at`] spends it on a trip count and [`Scev::holds`] spends it on whether the
1055 /// counter can wrap, and both want the same reading of the same branch, so the reading is
1056 /// written once.
1057 fn test_at(&mut self, id: LoopId, from: Block) -> Option<Test> {
1058 let func = self.func;
1059 let term = func.terminator(from)?;
1060 if func[term].opcode != Opcode::BrIf {
1061 return None;
1062 }
1063 let args = &func[func[term].args];
1064 let &cond = args.first()?;
1065 let calls = &func[func.target_list(term)];
1066 let (&taken, ¬_taken) = (calls.first()?, calls.get(1)?);
1067 // Which arm keeps going. If both stay in or both leave, the branch is not the test that
1068 // ends the loop and there is nothing here to solve.
1069 let stays = match (
1070 self.loops.contains(id, taken.block),
1071 self.loops.contains(id, not_taken.block),
1072 ) {
1073 (true, false) => true,
1074 (false, true) => false,
1075 _ => return None,
1076 };
1077
1078 let Def::Result { inst, .. } = func[cond].def else { return None };
1079 if func[inst].opcode != Opcode::ICmp {
1080 return None;
1081 }
1082 let Extra::IntPred(pred) = func[inst].extra else { return None };
1083 // The loop keeps going while the test says so, so an exit taken when the test is true is
1084 // an exit whose continuing condition is the opposite one.
1085 let pred = if stays { pred } else { invert(pred) };
1086 let operands = &func[func[inst].args];
1087 let (&lhs, &rhs) = (operands.first()?, operands.get(1)?);
1088
1089 // One side evolves and the other does not. Swapping puts the one that evolves on the left
1090 // and turns the predicate round with it, so only one direction has to be solved.
1091 let (chrec, limit, pred) = match (self.at(id, lhs), self.at(id, rhs)) {
1092 (Evolution::Affine(chrec), other) => (chrec, other.invariant()?, pred),
1093 (other, Evolution::Affine(chrec)) => (chrec, other.invariant()?, swap(pred)),
1094 _ => return None,
1095 };
1096
1097 // Whether every iteration that goes round asks this test. The header runs on all of them by
1098 // being the header. A latch runs on all of them only when it is the loop's one latch, since
1099 // with two of them an iteration can go round the other and never reach the test. Anywhere
1100 // else is a test under a condition, which [`bounded_by_its_test`] must not be given.
1101 //
1102 // The one latch is written out rather than taken for granted. `at_header` refuses a loop
1103 // with two of them already, so nothing reaching here has two, but the two conditions are
1104 // about different things and a later loosening of that one should not quietly loosen this.
1105 let each = from == self.loops.header(id) || self.loops.latches(id) == [from];
1106 Some(Test { chrec, limit, pred, each })
1107 }
1108}
1109
1110/// Two evolutions added, or subtracted when asked.
1111fn combine(left: Evolution, right: Evolution, ty: Type, flags: Flags, subtract: bool) -> Evolution {
1112 let apply = |a: Invariant, b: Invariant| if subtract { a.minus(b) } else { a.plus(b) };
1113 match (left, right) {
1114 (Evolution::Invariant(a), Evolution::Invariant(b)) => {
1115 apply(a, b).map_or(Evolution::Unknown, Evolution::Invariant)
1116 }
1117 (Evolution::Affine(chrec), Evolution::Invariant(b)) => {
1118 // Adding something that does not move only moves the base.
1119 let Some(base) = apply(chrec.base, b) else { return Evolution::Unknown };
1120 affine(base, chrec.step, ty, flags.intersection(chrec.flags))
1121 }
1122 (Evolution::Invariant(a), Evolution::Affine(chrec)) => {
1123 let (Some(base), Some(step)) = (
1124 apply(a, chrec.base),
1125 if subtract { chrec.step.negated() } else { Some(chrec.step) },
1126 ) else {
1127 return Evolution::Unknown;
1128 };
1129 affine(base, step, ty, flags.intersection(chrec.flags))
1130 }
1131 (Evolution::Affine(a), Evolution::Affine(b)) => {
1132 // Two chrecs of the same loop add componentwise, which is the closure property that
1133 // makes the representation worth having. Of different types they do not, because the
1134 // two sequences wrap at different widths.
1135 if a.ty != b.ty {
1136 return Evolution::Unknown;
1137 }
1138 let (Some(base), Some(step)) = (apply(a.base, b.base), apply(a.step, b.step)) else {
1139 return Evolution::Unknown;
1140 };
1141 affine(base, step, ty, flags.intersection(a.flags).intersection(b.flags))
1142 }
1143 _ => Evolution::Unknown,
1144 }
1145}
1146
1147/// One evolution multiplied by another, which needs one of them to stand still.
1148fn scale(left: Evolution, right: Evolution, ty: Type, flags: Flags) -> Evolution {
1149 let (chrec, by) = match (left, right) {
1150 (Evolution::Invariant(a), Evolution::Invariant(b)) => {
1151 return a.times(b).map_or(Evolution::Unknown, Evolution::Invariant);
1152 }
1153 (Evolution::Affine(chrec), Evolution::Invariant(by))
1154 | (Evolution::Invariant(by), Evolution::Affine(chrec)) => (chrec, by),
1155 // Two chrecs multiplied give a quadratic, which is a chain of recurrences with a second
1156 // step and is outside the subset section 7.4 chose.
1157 _ => return Evolution::Unknown,
1158 };
1159 let (Some(base), Some(step)) = (chrec.base.times(by), chrec.step.times(by)) else {
1160 return Evolution::Unknown;
1161 };
1162 affine(base, step, ty, flags.intersection(chrec.flags))
1163}
1164
1165/// A chrec, or invariant when the step turns out to be nothing.
1166///
1167/// A step of zero is a valid affine chrec describing a value that does not move, and section 7.7
1168/// warns that code dividing by the step to get a trip count divides by zero. Reporting it as
1169/// invariant here means the shape is right for every reader rather than only for the careful
1170/// ones, and the trip count solver still checks, because a step can also come out zero from a
1171/// header parameter incremented by an invariant that happens to be zero.
1172fn affine(base: Invariant, step: Invariant, ty: Type, flags: Flags) -> Evolution {
1173 if step.is_zero() {
1174 return Evolution::Invariant(base);
1175 }
1176 Evolution::Affine(Chrec { base, step, ty, flags })
1177}
1178
1179/// The iteration at which `chrec pred limit` first fails, with what that rests on.
1180///
1181/// `each` says the test runs on every iteration that goes round, which is what lets the test itself
1182/// stand in for a promise the counter does not carry. See [`bounded_by_its_test`].
1183fn solve(chrec: Chrec, limit: Invariant, pred: IntPred, each: bool) -> Option<Bound> {
1184 // Section 7.7's first way of being wrong. A step of zero is a loop that never leaves through
1185 // this exit, and dividing the distance by it is a crash rather than an answer.
1186 let step = chrec.step.as_number()?;
1187 if step == 0 {
1188 return None;
1189 }
1190 let signed = matches!(pred, IntPred::Slt | IntPred::Sle | IntPred::Sgt | IntPred::Sge);
1191
1192 let mut assumptions = Vec::new();
1193 if !chrec.does_not_wrap(signed) && !(each && bounded_by_its_test(pred, step)) {
1194 assumptions.push(Assumption::NoWrap(chrec));
1195 }
1196 if signed {
1197 assumptions.push(Assumption::StrictOverflow);
1198 }
1199
1200 // A test that does not read its operands as signed does not read the constants in them that
1201 // way either, and every constant reaching here was read as signed on the way in.
1202 let (base, limit) = if signed {
1203 (chrec.base, limit)
1204 } else {
1205 (unsigned_base(chrec)?, as_unsigned(limit, chrec.ty)?)
1206 };
1207
1208 // The distance the counter has to travel, always counting up. A loop going down is the same
1209 // problem with the ends swapped, which is why the step is used by size below and its sign is
1210 // spent here.
1211 let apart = step.unsigned_abs();
1212 let found = match (pred, step > 0) {
1213 (IntPred::Slt | IntPred::Ult, true) => {
1214 ordered(limit.minus(base)?, apart, false, assumptions)
1215 }
1216 (IntPred::Sle | IntPred::Ule, true) => {
1217 ordered(limit.minus(base)?, apart, true, assumptions)
1218 }
1219 (IntPred::Sgt | IntPred::Ugt, false) => {
1220 ordered(base.minus(limit)?, apart, false, assumptions)
1221 }
1222 (IntPred::Sge | IntPred::Uge, false) => {
1223 ordered(base.minus(limit)?, apart, true, assumptions)
1224 }
1225 (IntPred::Ne, _) => {
1226 let distance = if step > 0 { limit.minus(base)? } else { base.minus(limit)? };
1227 landing(distance, apart, step < 0 && limit.is_zero(), assumptions)
1228 }
1229 // Either the counter steps away from the limit, in which case the loop is endless rather
1230 // than long, or the test is one this does not solve. Silence is the answer to both.
1231 _ => None,
1232 };
1233 // Written once here rather than threaded through the two solvers, because it is a fact about
1234 // the test and neither of them looks at the test. A count taken from a test with no sign to it,
1235 // which is `!=`, is read unsigned, because that is the reading `as_unsigned` above already put
1236 // its operands through.
1237 let reading = if signed { Reading::Signed } else { Reading::Unsigned };
1238 found.map(|(count, assumptions)| Bound { count, assumptions, reading })
1239}
1240
1241/// Whether the exit test by itself rules out the counter wrapping before the loop ends.
1242///
1243/// An unsigned counter carries no `nuw`, because C says unsigned arithmetic wraps, so without this
1244/// every `for (unsigned i = 0; i < n; i++)` comes back resting on an assumption nothing downstream
1245/// can discharge. What discharges it is the test. A counter stepping up by exactly one is at the
1246/// limit before it is anywhere past it, and the test ends the loop there, so it never reaches the
1247/// top of its type. GCC works the same thing out in `scev_probably_wraps_p`.
1248///
1249/// Every part of that is load bearing. The step has to be one: `i += 2` can go from one below the
1250/// limit to one above the top of the type and come back round at the bottom, which is a loop that
1251/// runs forever rather than one that runs twice as fast. The test has to be the strict one: `<=`
1252/// lets the counter reach the limit and step once more, and a limit that is the largest number of
1253/// its type makes that last step the one that wraps. And the test has to run on every iteration
1254/// that goes round, or the counter can be stepped by a path that never asks it anything.
1255///
1256/// Nothing is claimed here about a signed counter, which needs no help: a signed counter that would
1257/// wrap is a program with undefined behaviour in it and [`Assumption::StrictOverflow`] is where
1258/// that is recorded.
1259fn bounded_by_its_test(pred: IntPred, step: i128) -> bool {
1260 matches!((pred, step), (IntPred::Ult, 1) | (IntPred::Ugt, -1))
1261}
1262
1263/// Whether this sequence stays behind one the exit test already keeps inside its type.
1264///
1265/// [`bounded_by_its_test`] says the counter the test compares never reaches the top of its type.
1266/// Everything else the loop counts with is that counter plus a fixed distance, because two affine
1267/// chrecs of the same loop with the same step differ by a constant, so a sequence starting no
1268/// further along than the counter is a sequence that gets to the top no sooner than the counter
1269/// does, which is never.
1270///
1271/// Same base is the case that matters most and the easiest to see: the test compares `i + 1` and
1272/// the subscript reads `i`, which is one loop written two ways, and the two chrecs differ only in
1273/// where they start.
1274///
1275/// Going up only. A counter going down wraps at the bottom rather than the top, so the sequence
1276/// that is safe is the one that starts further along rather than the one that starts behind, and
1277/// nothing measured so far walks an array downwards. Doing it would be turning the comparison
1278/// round, and it should come with the program that wants it.
1279fn trails(chrec: Chrec, held: Chrec) -> bool {
1280 if chrec.ty != held.ty || chrec.step != held.step {
1281 return false;
1282 }
1283 if chrec.base == held.base {
1284 return true;
1285 }
1286 let (Some(step), Some(mine), Some(theirs)) =
1287 (chrec.step.as_number(), chrec.base.as_number(), held.base.as_number())
1288 else {
1289 return false;
1290 };
1291 // Read as unsigned, which is the reading the test took, so a base that came in negative is a
1292 // large number rather than a small one and starting behind is not what it is doing.
1293 step > 0 && mine >= 0 && theirs >= 0 && mine <= theirs
1294}
1295
1296/// The same expression, read the way a test without a sign reads it.
1297///
1298/// Constants arrive here as the number their bits are when the sign bit is taken seriously,
1299/// because that is the only reading available before anybody knows what will be done with them.
1300/// An unsigned test disagrees about half of them. `for (unsigned char i = 0; i < 200; i++)` holds
1301/// its limit as minus fifty six, and a distance worked out from that is negative, which reads as
1302/// a loop that runs no times rather than one that runs two hundred.
1303///
1304/// The step is not put through this, because a step is a difference rather than a value and its
1305/// signed reading is the one that says which way the counter goes.
1306/// Where a counter starts, read unsigned.
1307///
1308/// What [`as_unsigned`] says, and one more case it has to refuse without the counter to ask. A base
1309/// with a number folded in beside its symbol is safe to read unsigned when the counter promises not
1310/// to wrap that way, because the base is the first value the counter took and it took it without
1311/// wrapping, so the sum is the number it looks like. The countdown ivopts writes tests its variable
1312/// after taking one off, and this is what its base looks like.
1313fn unsigned_base(chrec: Chrec) -> Option<Invariant> {
1314 let base = chrec.base;
1315 let plain = base.on.is_none() && base.read.is_none() && base.scale == 1;
1316 as_unsigned(base, chrec.ty).or_else(|| (plain && chrec.does_not_wrap(false)).then_some(base))
1317}
1318
1319fn as_unsigned(inv: Invariant, ty: Type) -> Option<Invariant> {
1320 match inv.as_number() {
1321 Some(number) if number >= 0 => Some(inv),
1322 Some(number) => {
1323 // Only an integer constant was read as signed in the first place. A pointer never
1324 // was, so a negative number sitting in one is an expression this cannot reinterpret.
1325 let bits = ty.is_int().then(|| ty.bits()).filter(|&bits| bits < 127)?;
1326 Some(Invariant::number(number & ((1i128 << bits) - 1)))
1327 }
1328 // A symbolic operand is whatever it is at run time, and the subtraction below cancels it
1329 // rather than reading it, so long as nothing signed has been folded in beside it. Two
1330 // symbols is two things to cancel and the subtraction only ever cancels one.
1331 None => (inv.on.is_none() && inv.scale == 1 && inv.offset == 0).then_some(inv),
1332 }
1333}
1334
1335/// The count for an exit tested with an ordering, where overshooting the limit still ends it.
1336fn ordered(
1337 distance: Invariant,
1338 step: u128,
1339 inclusive: bool,
1340 mut assumptions: Vec<Assumption>,
1341) -> Option<(Count, Vec<Assumption>)> {
1342 match distance.as_number() {
1343 Some(exact) => {
1344 if exact < 0 {
1345 // The counter starts past the limit, so the test fails the first time it runs.
1346 // That is a count of zero and it rests on nothing at all, not even on the counter
1347 // behaving, because the counter never moves.
1348 return Some((Count::Exact(0), Vec::new()));
1349 }
1350 // Rounding up, because a step that overshoots still took the iteration that overshot.
1351 let count = (exact.unsigned_abs() + u128::from(inclusive)).div_ceil(step);
1352 Some((Count::Exact(count), assumptions))
1353 }
1354 // Symbolic, and only for a step of one, because dividing an expression by anything else
1355 // needs a representation for a division and there is not one here.
1356 None if step == 1 => {
1357 assumptions.push(Assumption::Entered);
1358 let count = distance.plus(Invariant::number(i128::from(inclusive)))?;
1359 Some((Count::Symbolic(count), assumptions))
1360 }
1361 None => None,
1362 }
1363}
1364
1365/// The count for an exit tested with `!=`, where the counter has to land on the limit exactly.
1366///
1367/// This is a different problem from the one above and not a special case of it. An ordering test
1368/// ends the loop the moment the counter is past the limit, so a step that overshoots still stops.
1369/// `!=` only ends the loop on the one iteration where the counter is the limit, so a counter that
1370/// steps over the limit, or that starts on the far side of it, keeps going until it wraps. Both
1371/// of those are endless loops rather than short ones, and answering zero for either was the bug
1372/// this function exists to not have.
1373fn landing(
1374 distance: Invariant,
1375 step: u128,
1376 bottom: bool,
1377 mut assumptions: Vec<Assumption>,
1378) -> Option<(Count, Vec<Assumption>)> {
1379 match distance.as_number() {
1380 Some(exact) => {
1381 let travel = u128::try_from(exact).ok()?;
1382 // Checked outright rather than assumed, which is why nothing here needs an assumption
1383 // about the step dividing anything.
1384 (travel % step == 0).then(|| (Count::Exact(travel / step), assumptions))
1385 }
1386 // A step of one lands on everything ahead of it, so the only thing left to establish is
1387 // that the limit is ahead. `while (p != end)` is this case, and a step of anything else
1388 // would need the division a symbolic distance has no room for.
1389 //
1390 // A counter going down to zero has it established already, because `!=` reads it unsigned
1391 // and nothing unsigned is below zero, so zero is ahead of wherever it starts. The `!=`
1392 // that ivopts writes for a countdown is this case. A promise not to wrap would not do
1393 // instead, since a loop with a limit behind its counter can stop on something else, a
1394 // bounds check for one, long before the counter comes round to break the promise.
1395 None if step == 1 => {
1396 if !bottom {
1397 assumptions.push(Assumption::Approaching);
1398 }
1399 Some((Count::Symbolic(distance), assumptions))
1400 }
1401 None => None,
1402 }
1403}
1404
1405/// The predicate that is true exactly when this one is not.
1406fn invert(pred: IntPred) -> IntPred {
1407 match pred {
1408 IntPred::Eq => IntPred::Ne,
1409 IntPred::Ne => IntPred::Eq,
1410 IntPred::Slt => IntPred::Sge,
1411 IntPred::Sle => IntPred::Sgt,
1412 IntPred::Sgt => IntPred::Sle,
1413 IntPred::Sge => IntPred::Slt,
1414 IntPred::Ult => IntPred::Uge,
1415 IntPred::Ule => IntPred::Ugt,
1416 IntPred::Ugt => IntPred::Ule,
1417 IntPred::Uge => IntPred::Ult,
1418 }
1419}
1420
1421/// The predicate that says the same thing with the operands the other way round.
1422fn swap(pred: IntPred) -> IntPred {
1423 match pred {
1424 IntPred::Eq => IntPred::Eq,
1425 IntPred::Ne => IntPred::Ne,
1426 IntPred::Slt => IntPred::Sgt,
1427 IntPred::Sle => IntPred::Sge,
1428 IntPred::Sgt => IntPred::Slt,
1429 IntPred::Sge => IntPred::Sle,
1430 IntPred::Ult => IntPred::Ugt,
1431 IntPred::Ule => IntPred::Uge,
1432 IntPred::Ugt => IntPred::Ult,
1433 IntPred::Uge => IntPred::Ule,
1434 }
1435}
1436
1437/// The constant a value is, if it is one.
1438fn constant(func: &Func, value: Value) -> Option<(Imm, Type)> {
1439 let Def::Result { inst, .. } = func[value].def else { return None };
1440 if func[inst].opcode != Opcode::IConst {
1441 return None;
1442 }
1443 let Extra::Imm(at) = func[inst].extra else { return None };
1444 let ty = func[value].ty;
1445 ty.is_int().then(|| (func[at], ty))
1446}
1447
1448/// The global whose address a value is, if it is one.
1449fn symbol(func: &Func, value: Value) -> Option<Symbol> {
1450 let Def::Result { inst, .. } = func[value].def else { return None };
1451 if func[inst].opcode != Opcode::GlobalAddr {
1452 return None;
1453 }
1454 let Extra::Symbol(symbol) = func[inst].extra else { return None };
1455 Some(symbol)
1456}
1457
1458/// What this predecessor passes to the block's parameter at this position.
1459///
1460/// `None` when the predecessor branches to the block more than once with different arguments,
1461/// which a `br_if` with both arms on the same block can do and which means the parameter takes a
1462/// value that depends on the test rather than on the edge.
1463fn argument(func: &Func, pred: Block, block: Block, index: usize) -> Option<Value> {
1464 let term = func.terminator(pred)?;
1465 let mut found = None;
1466 for call in func.successors(term) {
1467 if call.block != block {
1468 continue;
1469 }
1470 let arg = *func[call.args].get(index)?;
1471 if found.replace(arg).is_some_and(|old| old != arg) {
1472 return None;
1473 }
1474 }
1475 found
1476}
1477
1478#[cfg(test)]
1479mod tests {
1480 use rucc_base::Interner;
1481 use rucc_ir::{Builder, Extra, Flags, Func, InstData, IntPred, Opcode, Signature, Type, Value};
1482
1483 use crate::cfg::Cfg;
1484 use crate::dom::Dominators;
1485 use crate::loops::{LoopId, Loops};
1486 use crate::scev::{
1487 Anchor, Assumption, Bound, Count, Evolution, Invariant, Reading, Scev, Widening,
1488 };
1489
1490 /// A loop counting in `ty` from `from` by `step` while the counter is below `to`.
1491 ///
1492 /// ```text
1493 /// entry: jump header(from)
1494 /// header(i): test = icmp pred i, to ; br_if test, body, exit
1495 /// body: next = add i, step ; jump header(next)
1496 /// exit: ret
1497 /// ```
1498 ///
1499 /// The counter is the header's only parameter, which is what the tests ask about.
1500 struct Counted {
1501 func: Func,
1502 counter: Value,
1503 next: Value,
1504 }
1505
1506 fn counted(ty: Type, from: i128, to: i128, step: i128, pred: IntPred, flags: Flags) -> Counted {
1507 let (it, ()) = counted_with(ty, from, to, step, pred, flags, |_, _| ());
1508 it
1509 }
1510
1511 /// The same loop, with `extra` run in the body on the counter before the counter steps.
1512 ///
1513 /// The builder appends, and the body's `jump` back to the header has to stay the last
1514 /// instruction in it or the block has no terminator and the loop stops being one. So anything
1515 /// a test wants derived from the counter goes in here rather than being tacked on afterwards.
1516 fn counted_with<T>(
1517 ty: Type,
1518 from: i128,
1519 to: i128,
1520 step: i128,
1521 pred: IntPred,
1522 flags: Flags,
1523 extra: impl FnOnce(&mut Builder<'_>, Value) -> T,
1524 ) -> (Counted, T) {
1525 let mut names = Interner::new();
1526 let mut func = Func::new(names.intern("f"), Signature::new());
1527 let entry = func.create_block();
1528 let header = func.create_block();
1529 let body = func.create_block();
1530 let exit = func.create_block();
1531 let counter = func.append_param(header, ty);
1532
1533 let mut build = Builder::new(&mut func, entry);
1534 let start = build.iconst(ty, from);
1535 build.jump(header, &[start]);
1536
1537 let mut build = Builder::new(&mut func, header);
1538 let limit = build.iconst(ty, to);
1539 let test = build.icmp(pred, counter, limit);
1540 build.br_if(test, body, &[], exit, &[]);
1541
1542 let mut build = Builder::new(&mut func, body);
1543 let derived = extra(&mut build, counter);
1544 let by = build.iconst(ty, step);
1545 let next = build.binary(Opcode::Add, counter, by, flags);
1546 build.jump(header, &[next]);
1547
1548 let mut build = Builder::new(&mut func, exit);
1549 build.ret(&[]);
1550
1551 (Counted { func, counter, next }, derived)
1552 }
1553
1554 /// The analysis over a function, along with the one loop it has.
1555 fn analyse(func: &Func) -> (Cfg, Loops) {
1556 let cfg = Cfg::new(func);
1557 let doms = Dominators::new(&cfg);
1558 let loops = Loops::new(&cfg, &doms);
1559 (cfg, loops)
1560 }
1561
1562 /// The chrec of a value in the one loop of a function.
1563 fn evolution(func: &Func, value: Value) -> Evolution {
1564 let (cfg, loops) = analyse(func);
1565 let id = loops.roots()[0];
1566 Scev::new(func, &cfg, &loops).evolution(id, value)
1567 }
1568
1569 /// The trip count of the one loop of a function.
1570 fn bound(func: &Func) -> Option<Bound> {
1571 let (cfg, loops) = analyse(func);
1572 let id: LoopId = loops.roots()[0];
1573 Scev::new(func, &cfg, &loops).bound(id)
1574 }
1575
1576 #[test]
1577 fn a_counter_from_zero_by_one_is_the_chrec_everyone_expects() {
1578 let it = counted(Type::int(32), 0, 100, 1, IntPred::Slt, Flags::NSW);
1579 let chrec = evolution(&it.func, it.counter).chrec().expect("the counter evolves");
1580 assert_eq!(chrec.base, Invariant::number(0));
1581 assert_eq!(chrec.step, Invariant::number(1));
1582 assert_eq!(chrec.ty, Type::int(32));
1583 assert!(chrec.does_not_wrap(true));
1584 }
1585
1586 #[test]
1587 fn a_walk_over_a_file_scope_array_is_a_chrec_measured_from_the_symbol() {
1588 // The `global_addr` is inside the loop, which is where the compiler leaves one: working
1589 // the address out again is a single instruction and `crate::licm` would rather do that
1590 // than hold it in a register the whole way round. Answering by where a value is defined
1591 // meant `a[i]` on a file scope `a` was an address with nothing to say about it.
1592 let mut names = Interner::new();
1593 let tab = names.intern("tab");
1594 let (it, address) =
1595 counted_with(Type::int(64), 0, 100, 1, IntPred::Slt, Flags::NSW, |build, counter| {
1596 let four = build.iconst(Type::int(64), 4);
1597 let by = build.binary(Opcode::Mul, counter, four, Flags::NSW);
1598 let extra = Extra::Symbol(tab);
1599 let at =
1600 build.value(InstData { extra, ..InstData::new(Opcode::GlobalAddr) }, Type::PTR);
1601 let args = build.func().push_values(&[at, by]);
1602 build.value(InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR)
1603 });
1604
1605 let chrec = evolution(&it.func, address).chrec().expect("the address evolves");
1606 assert_eq!(chrec.step, Invariant::number(4));
1607 // Described rather than named, so there is nothing for `plain` to hand back and a reader
1608 // of the base has to go through `on` and see what it is measured from.
1609 assert!(chrec.base.plain().is_none());
1610 let (base, rest) = chrec.base.on().expect("the base is measured from the symbol");
1611 assert_eq!(base, Anchor::Address(tab));
1612 assert_eq!(base.value(), None);
1613 assert_eq!(rest.value, None);
1614 assert_eq!(rest.offset, 0);
1615 }
1616
1617 #[test]
1618 fn the_value_fed_back_is_the_chrec_one_step_along() {
1619 let it = counted(Type::int(32), 5, 100, 3, IntPred::Slt, Flags::NSW);
1620 let chrec = evolution(&it.func, it.next).chrec().expect("the increment evolves");
1621 assert_eq!(chrec.base, Invariant::number(8));
1622 assert_eq!(chrec.step, Invariant::number(3));
1623 }
1624
1625 #[test]
1626 fn a_multiple_of_the_counter_plus_a_number_is_a_chrec_of_its_own() {
1627 // `j = 2 * i + 3` where `i = {0, +, 1}`, which is the shape section 7.4 says pattern
1628 // matching runs out of road on and chains of recurrences do not.
1629 let (it, shifted) =
1630 counted_with(Type::int(32), 0, 100, 1, IntPred::Slt, Flags::NSW, |build, counter| {
1631 let two = build.iconst(Type::int(32), 2);
1632 let three = build.iconst(Type::int(32), 3);
1633 let doubled = build.binary(Opcode::Mul, counter, two, Flags::NSW);
1634 build.binary(Opcode::Add, doubled, three, Flags::NSW)
1635 });
1636
1637 let chrec = evolution(&it.func, shifted).chrec().expect("it evolves");
1638 assert_eq!(chrec.base, Invariant::number(3));
1639 assert_eq!(chrec.step, Invariant::number(2));
1640 }
1641
1642 #[test]
1643 fn a_shift_by_a_constant_scales_the_chrec_and_a_shift_past_the_width_does_not() {
1644 let (it, (scaled, poison)) =
1645 counted_with(Type::int(32), 1, 100, 1, IntPred::Slt, Flags::NSW, |build, counter| {
1646 let three = build.iconst(Type::int(32), 3);
1647 let wide = build.iconst(Type::int(32), 32);
1648 (
1649 build.binary(Opcode::Shl, counter, three, Flags::NSW),
1650 build.binary(Opcode::Shl, counter, wide, Flags::NSW),
1651 )
1652 });
1653
1654 let chrec = evolution(&it.func, scaled).chrec().expect("it evolves");
1655 assert_eq!(chrec.base, Invariant::number(8));
1656 assert_eq!(chrec.step, Invariant::number(8));
1657 // A count at the width is poison rather than a shift to zero, so there is no sequence to
1658 // describe.
1659 assert_eq!(evolution(&it.func, poison), Evolution::Unknown);
1660 }
1661
1662 #[test]
1663 fn a_pointer_walked_by_the_element_size_is_a_chrec_in_bytes() {
1664 // What `for (p = a; p != end; p++)` lowers to on an array of four byte elements. Section
1665 // 7.4 calls this the one deliberate extension past affine and the difference between
1666 // analysing half of real C loops and nearly all of them.
1667 let mut names = Interner::new();
1668 let mut func = Func::new(names.intern("f"), Signature::new());
1669 let entry = func.create_block();
1670 let header = func.create_block();
1671 let body = func.create_block();
1672 let exit = func.create_block();
1673 let start = func.append_param(entry, Type::PTR);
1674 let cursor = func.append_param(header, Type::PTR);
1675
1676 let mut build = Builder::new(&mut func, entry);
1677 build.jump(header, &[start]);
1678 let mut build = Builder::new(&mut func, header);
1679 let done = build.icmp(IntPred::Eq, cursor, start);
1680 build.br_if(done, exit, &[], body, &[]);
1681 let mut build = Builder::new(&mut func, body);
1682 let four = build.iconst(Type::int(64), 4);
1683 let next = build.binary(Opcode::PtrAdd, cursor, four, Flags::NONE);
1684 build.jump(header, &[next]);
1685 let mut build = Builder::new(&mut func, exit);
1686 build.ret(&[]);
1687
1688 let chrec = evolution(&func, cursor).chrec().expect("the cursor evolves");
1689 assert_eq!(chrec.base, Invariant::of(start));
1690 assert_eq!(chrec.step, Invariant::number(4));
1691 assert_eq!(chrec.ty, Type::PTR);
1692 }
1693
1694 #[test]
1695 fn a_value_the_loop_does_not_change_widens_the_way_a_sequence_does() {
1696 // `(long)row` inside a loop over something else. There is no sequence here and so nothing
1697 // that could wrap, and the answer was unknown all the same, which made a sequence that does
1698 // not move harder to widen than one that does. What it cost is `a[row * N + k]` round `k`,
1699 // whose address came back unknown on account of the widening in the middle of it.
1700 let mut names = Interner::new();
1701 let mut func = Func::new(names.intern("f"), Signature::new());
1702 let entry = func.create_block();
1703 let header = func.create_block();
1704 let body = func.create_block();
1705 let exit = func.create_block();
1706 let row = func.append_param(entry, Type::int(32));
1707 let counter = func.append_param(header, Type::int(64));
1708
1709 let mut build = Builder::new(&mut func, entry);
1710 let zero = build.iconst(Type::int(64), 0);
1711 build.jump(header, &[zero]);
1712
1713 let mut build = Builder::new(&mut func, header);
1714 let limit = build.iconst(Type::int(64), 100);
1715 let test = build.icmp(IntPred::Slt, counter, limit);
1716 build.br_if(test, body, &[], exit, &[]);
1717
1718 let mut build = Builder::new(&mut func, body);
1719 let wide = build.unary(Opcode::SExt, row, Type::int(64));
1720 let one = build.iconst(Type::int(64), 1);
1721 let next = build.binary(Opcode::Add, counter, one, Flags::NSW);
1722 build.jump(header, &[next]);
1723 Builder::new(&mut func, exit).ret(&[]);
1724
1725 let word = Type::int(64);
1726 let widened =
1727 Invariant::of(row).widened(Reading::Signed, word).expect("one of a value widens");
1728 assert_eq!(evolution(&func, wide), Evolution::Invariant(widened));
1729 }
1730
1731 /// A value to hang an invariant on, which these never look inside.
1732 fn some_value() -> Value {
1733 let mut names = Interner::new();
1734 let mut func = Func::new(names.intern("f"), Signature::new());
1735 let entry = func.create_block();
1736 func.append_param(entry, Type::int(8))
1737 }
1738
1739 #[test]
1740 fn one_of_a_value_widens_and_arithmetic_on_it_does_not() {
1741 // What `Scev::extend` may take. A value is widened by describing the extension rather than
1742 // by naming a value nothing computes, which is what lets `for (i = start; i < n; i++)`
1743 // have a chrec at pointer width. `2 * x + 3` is refused, because the narrow arithmetic may
1744 // already have wrapped and `sext(2 * x + 3)` is not `2 * sext(x) + 3`.
1745 let value = some_value();
1746 let word = Type::int(64);
1747 assert_eq!(
1748 Invariant::of(value).widened(Reading::Signed, word),
1749 Some(Invariant {
1750 on: None,
1751 value: Some(value),
1752 read: Some(Widening { reading: Reading::Signed, to: word }),
1753 scale: 1,
1754 offset: 0,
1755 }),
1756 );
1757 assert_eq!(Invariant::scaled(value, 2, 3).widened(Reading::Signed, word), None);
1758 assert_eq!(Invariant::scaled(value, 1, 3).widened(Reading::Signed, word), None);
1759 // A number is the same number at both widths under a sign extension, and under a zero
1760 // extension once it is not negative.
1761 assert_eq!(
1762 Invariant::number(-1).widened(Reading::Signed, word),
1763 Some(Invariant::number(-1)),
1764 );
1765 assert_eq!(Invariant::number(-1).widened(Reading::Unsigned, word), None);
1766 }
1767
1768 #[test]
1769 fn an_extension_of_an_extension_collapses_only_where_it_means_the_same_thing() {
1770 // A zero extension is never negative, so reading its result as signed afterwards is the
1771 // same numbers and the pair is one zero extension at the outer width. The other way round
1772 // it is not: a sign extended negative number read as unsigned is a different quantity, and
1773 // there is nothing to collapse to.
1774 let value = some_value();
1775 let (half, word) = (Type::int(32), Type::int(64));
1776 let read = |inv: Invariant| inv.read.expect("a widened value carries how it is read");
1777
1778 let zeroed = Invariant::of(value).widened(Reading::Unsigned, half).expect("it widens");
1779 let again = zeroed.widened(Reading::Signed, word).expect("and it widens again");
1780 assert_eq!(read(again), Widening { reading: Reading::Unsigned, to: word });
1781
1782 let signed = Invariant::of(value).widened(Reading::Signed, half).expect("it widens");
1783 assert_eq!(signed.widened(Reading::Unsigned, word), None);
1784 let again = signed.widened(Reading::Signed, word).expect("and it widens again");
1785 assert_eq!(read(again), Widening { reading: Reading::Signed, to: word });
1786 }
1787
1788 #[test]
1789 fn two_invariants_on_the_same_value_read_two_ways_do_not_add() {
1790 // `sext(x)` and `zext(x)` are the same bits and not the same quantity, so a sum of them is
1791 // not two of anything and there is no shape here for it.
1792 let value = some_value();
1793 let word = Type::int(64);
1794 let signed = Invariant::of(value).widened(Reading::Signed, word).expect("it widens");
1795 let zeroed = Invariant::of(value).widened(Reading::Unsigned, word).expect("it widens");
1796 assert_eq!(signed.plus(zeroed), None);
1797 assert_eq!(
1798 signed.plus(signed),
1799 Some(Invariant {
1800 on: None,
1801 value: Some(value),
1802 read: Some(Widening { reading: Reading::Signed, to: word }),
1803 scale: 2,
1804 offset: 0,
1805 }),
1806 "the same value read the same way adds to two of it",
1807 );
1808 }
1809
1810 #[test]
1811 fn a_counter_in_unsigned_char_wraps_and_does_not_widen_without_a_promise() {
1812 // Section 7.7's second way of being wrong. `{0, +, 1}` in `unsigned char` is not
1813 // `0, 1, 2, ...`, it is that modulo two hundred and fifty six, and widening it is only
1814 // the same sequence if it does not get that far.
1815 //
1816 // An inclusive test, because a strict one is a proof of its own and the case below is
1817 // about what happens when there is no proof at all. This loop does not in fact wrap, and
1818 // the point is that nothing here can say so.
1819 let (it, wide) =
1820 counted_with(Type::int(8), 0, 100, 1, IntPred::Ule, Flags::NONE, |build, counter| {
1821 build.unary(Opcode::ZExt, counter, Type::int(32))
1822 });
1823 let chrec = evolution(&it.func, it.counter).chrec().expect("the counter evolves");
1824 assert_eq!(chrec.ty, Type::int(8));
1825 assert!(!chrec.does_not_wrap(false));
1826 assert_eq!(evolution(&it.func, wide), Evolution::Unknown);
1827 }
1828
1829 #[test]
1830 fn a_counter_its_own_test_holds_widens_without_a_promise() {
1831 // The same counter under the strict test, which is the shape `for (unsigned i = 0; i < n;
1832 // i++)` has. Nothing promised anything, and the test is the proof: the counter is at the
1833 // limit before it is anywhere past it, and the loop ends there.
1834 let (it, wide) =
1835 counted_with(Type::int(8), 0, 100, 1, IntPred::Ult, Flags::NONE, |build, counter| {
1836 build.unary(Opcode::ZExt, counter, Type::int(32))
1837 });
1838 let narrow = evolution(&it.func, it.counter).chrec().expect("the counter evolves");
1839 assert!(!narrow.does_not_wrap(false), "nothing was promised, so nothing carries a flag");
1840 let chrec = evolution(&it.func, wide).chrec().expect("its own test holds it");
1841 assert_eq!(chrec.ty, Type::int(32));
1842 assert_eq!(chrec.base, Invariant::number(0));
1843 assert_eq!(chrec.step, Invariant::number(1));
1844 }
1845
1846 #[test]
1847 fn a_sequence_that_starts_further_along_than_the_counter_does_not_widen() {
1848 // `trails` in the direction it refuses. The test holds `i`, which starts at zero, and this
1849 // asks about `i + 1`, which starts one further along. One further along is where the
1850 // counter would be if it had gone round once more, and going round once more is the step
1851 // nothing here rules out.
1852 let (it, wide) =
1853 counted_with(Type::int(8), 0, 100, 1, IntPred::Ult, Flags::NONE, |build, counter| {
1854 let one = build.iconst(Type::int(8), 1);
1855 let ahead = build.binary(Opcode::Add, counter, one, Flags::NONE);
1856 build.unary(Opcode::ZExt, ahead, Type::int(32))
1857 });
1858 assert_eq!(evolution(&it.func, wide), Evolution::Unknown);
1859 }
1860
1861 #[test]
1862 fn a_counter_in_short_widens_when_the_increment_promised_it_would_not_wrap() {
1863 let (it, (wide, zero_extended)) =
1864 counted_with(Type::int(16), 0, 100, 1, IntPred::Slt, Flags::NSW, |build, counter| {
1865 (
1866 build.unary(Opcode::SExt, counter, Type::int(32)),
1867 build.unary(Opcode::ZExt, counter, Type::int(32)),
1868 )
1869 });
1870
1871 let chrec = evolution(&it.func, wide).chrec().expect("it widens");
1872 assert_eq!(chrec.ty, Type::int(32));
1873 assert_eq!(chrec.base, Invariant::number(0));
1874 assert_eq!(chrec.step, Invariant::number(1));
1875 // `nsw` is a promise about the signed reading and says nothing about the unsigned one.
1876 assert_eq!(evolution(&it.func, zero_extended), Evolution::Unknown);
1877 }
1878
1879 #[test]
1880 fn a_step_of_zero_is_invariant_and_has_no_trip_count() {
1881 // Section 7.7's first way of being wrong. `i += k` with `k` of zero is a valid affine
1882 // chrec of a loop that never leaves through this exit, and code dividing the distance by
1883 // the step divides by zero.
1884 let it = counted(Type::int(32), 0, 100, 0, IntPred::Slt, Flags::NSW);
1885 assert!(matches!(evolution(&it.func, it.counter), Evolution::Invariant(_)));
1886 assert_eq!(bound(&it.func), None);
1887 }
1888
1889 #[test]
1890 fn a_counted_loop_has_the_count_anyone_would_work_out_by_hand() {
1891 let it = counted(Type::int(32), 0, 100, 1, IntPred::Slt, Flags::NSW);
1892 let found = bound(&it.func).expect("it is counted");
1893 let (count, assumptions) = found.parts();
1894 assert_eq!(count, Count::Exact(100));
1895 // The distance is a number and it is not negative, so being entered is not in question.
1896 // Signed overflow being undefined still is, which is what `-fwrapv` would withdraw.
1897 assert_eq!(assumptions, [Assumption::StrictOverflow]);
1898 assert_eq!(found.proven(), None);
1899 }
1900
1901 #[test]
1902 fn a_step_that_overshoots_still_takes_the_iteration_that_overshot() {
1903 // Zero, three, six, nine, and the test fails at twelve, so four iterations rather than
1904 // three and a third. Rounding the other way is an off by one in every unroller.
1905 let it = counted(Type::int(32), 0, 10, 3, IntPred::Slt, Flags::NSW);
1906 let (count, _) = bound(&it.func).expect("it is counted").parts();
1907 assert_eq!(count, Count::Exact(4));
1908 }
1909
1910 #[test]
1911 fn an_inclusive_test_runs_one_more_time() {
1912 let it = counted(Type::int(32), 0, 10, 1, IntPred::Sle, Flags::NSW);
1913 let (count, _) = bound(&it.func).expect("it is counted").parts();
1914 assert_eq!(count, Count::Exact(11));
1915 }
1916
1917 #[test]
1918 fn a_loop_whose_test_fails_first_time_runs_no_times_and_rests_on_nothing() {
1919 let it = counted(Type::int(32), 10, 0, 1, IntPred::Slt, Flags::NSW);
1920 let found = bound(&it.func).expect("it is counted");
1921 assert_eq!(found.proven(), Some(Count::Exact(0)));
1922 assert!(found.assumptions().is_empty());
1923 }
1924
1925 #[test]
1926 fn counting_down_is_the_same_problem_with_the_ends_swapped() {
1927 let it = counted(Type::int(32), 10, 0, -1, IntPred::Sgt, Flags::NSW);
1928 let (count, _) = bound(&it.func).expect("it is counted").parts();
1929 assert_eq!(count, Count::Exact(10));
1930 }
1931
1932 #[test]
1933 fn an_unsigned_test_does_not_drag_in_the_signed_overflow_assumption() {
1934 let it = counted(Type::int(32), 0, 100, 1, IntPred::Ult, Flags::NUW);
1935 let found = bound(&it.func).expect("it is counted");
1936 assert_eq!(found.proven(), Some(Count::Exact(100)));
1937 }
1938
1939 #[test]
1940 fn a_test_against_something_the_loop_does_not_change_gives_a_symbolic_count() {
1941 // `for (i = 0; i < n; i++)`, where the answer is `n` and is only `n` if the loop is
1942 // entered, because `n` of minus one runs no times and the distance is minus one.
1943 let mut names = Interner::new();
1944 let mut func = Func::new(names.intern("f"), Signature::new());
1945 let entry = func.create_block();
1946 let header = func.create_block();
1947 let body = func.create_block();
1948 let exit = func.create_block();
1949 let limit = func.append_param(entry, Type::int(32));
1950 let counter = func.append_param(header, Type::int(32));
1951
1952 let mut build = Builder::new(&mut func, entry);
1953 let zero = build.iconst(Type::int(32), 0);
1954 build.jump(header, &[zero]);
1955 let mut build = Builder::new(&mut func, header);
1956 let test = build.icmp(IntPred::Slt, counter, limit);
1957 build.br_if(test, body, &[], exit, &[]);
1958 let mut build = Builder::new(&mut func, body);
1959 let one = build.iconst(Type::int(32), 1);
1960 let next = build.binary(Opcode::Add, counter, one, Flags::NSW);
1961 build.jump(header, &[next]);
1962 let mut build = Builder::new(&mut func, exit);
1963 build.ret(&[]);
1964
1965 let found = bound(&func).expect("it is counted");
1966 let (count, assumptions) = found.parts();
1967 assert_eq!(count, Count::Symbolic(Invariant::of(limit)));
1968 assert!(assumptions.contains(&Assumption::Entered), "{assumptions:?}");
1969 assert!(assumptions.contains(&Assumption::StrictOverflow), "{assumptions:?}");
1970 assert_eq!(found.proven(), None);
1971 }
1972
1973 /// `for (c = n; c != limit; c--)`, with the counter in sixty four bits and no flags on it.
1974 fn down_to(limit: i128) -> (Func, Value) {
1975 let mut names = Interner::new();
1976 let mut func = Func::new(names.intern("f"), Signature::new());
1977 let entry = func.create_block();
1978 let header = func.create_block();
1979 let body = func.create_block();
1980 let exit = func.create_block();
1981 let start = func.append_param(entry, Type::int(64));
1982 let counter = func.append_param(header, Type::int(64));
1983
1984 let mut build = Builder::new(&mut func, entry);
1985 build.jump(header, &[start]);
1986 let mut build = Builder::new(&mut func, header);
1987 let limit = build.iconst(Type::int(64), limit);
1988 let test = build.icmp(IntPred::Ne, counter, limit);
1989 build.br_if(test, body, &[], exit, &[]);
1990 let mut build = Builder::new(&mut func, body);
1991 let one = build.iconst(Type::int(64), 1);
1992 let next = build.binary(Opcode::Sub, counter, one, Flags::NONE);
1993 build.jump(header, &[next]);
1994 let mut build = Builder::new(&mut func, exit);
1995 build.ret(&[]);
1996 (func, start)
1997 }
1998
1999 #[test]
2000 fn a_countdown_to_zero_is_always_heading_for_it() {
2001 let (func, start) = down_to(0);
2002 let found = bound(&func).expect("it is counted");
2003 let (count, assumptions) = found.parts();
2004 assert_eq!(count, Count::Symbolic(Invariant::of(start)));
2005 assert!(!assumptions.contains(&Assumption::Approaching), "{assumptions:?}");
2006 }
2007
2008 #[test]
2009 fn a_countdown_tested_after_its_step_is_counted_when_it_cannot_wrap() {
2010 // The shape ivopts writes: the variable starts one above the count and the header takes
2011 // one off before the test, so what the test sees starts at the start less one.
2012 for (flags, counted) in [(Flags::NSW | Flags::NUW, true), (Flags::NSW, false)] {
2013 let mut names = Interner::new();
2014 let mut func = Func::new(names.intern("f"), Signature::new());
2015 let entry = func.create_block();
2016 let header = func.create_block();
2017 let body = func.create_block();
2018 let exit = func.create_block();
2019 let start = func.append_param(entry, Type::int(64));
2020 let counter = func.append_param(header, Type::int(64));
2021
2022 Builder::new(&mut func, entry).jump(header, &[start]);
2023 let mut build = Builder::new(&mut func, header);
2024 let one = build.iconst(Type::int(64), 1);
2025 let next = build.binary(Opcode::Sub, counter, one, flags);
2026 let zero = build.iconst(Type::int(64), 0);
2027 let test = build.icmp(IntPred::Ne, next, zero);
2028 build.br_if(test, body, &[], exit, &[]);
2029 Builder::new(&mut func, body).jump(header, &[next]);
2030 Builder::new(&mut func, exit).ret(&[]);
2031
2032 let found = bound(&func);
2033 assert_eq!(found.is_some(), counted, "{flags:?}");
2034 if let Some(found) = found {
2035 let at = Invariant::of(start).plus(Invariant::number(-1)).expect("it adds");
2036 assert_eq!(found.comes_back(), Some(Count::Symbolic(at)));
2037 }
2038 }
2039 }
2040
2041 #[test]
2042 fn a_countdown_to_anything_else_may_have_started_below_it() {
2043 // Started at zero, this one goes all the way round before it gets to one.
2044 let (func, _) = down_to(1);
2045 let found = bound(&func).expect("it is counted");
2046 let (_, assumptions) = found.parts();
2047 assert!(assumptions.contains(&Assumption::Approaching), "{assumptions:?}");
2048 }
2049
2050 #[test]
2051 fn the_count_records_which_reading_its_test_took() {
2052 // What a consumer widening a symbolic count has to know. The limit is a value of the
2053 // counter's type and which number that value is depends on how its test read it.
2054 let signed = counted(Type::int(32), 0, 100, 1, IntPred::Slt, Flags::NSW);
2055 assert_eq!(bound(&signed.func).expect("it is counted").reading(), Reading::Signed);
2056 let unsigned = counted(Type::int(32), 0, 100, 1, IntPred::Ult, Flags::NUW);
2057 assert_eq!(bound(&unsigned.func).expect("it is counted").reading(), Reading::Unsigned);
2058 }
2059
2060 #[test]
2061 fn a_counter_without_a_no_wrap_promise_carries_the_assumption_instead() {
2062 // An inclusive test, because the strict one is the case the test itself answers. Under
2063 // `<=` the counter reaches the limit and is stepped once more, so a limit at the top of
2064 // the type makes that last step the one that wraps and nothing here rules it out.
2065 let it = counted(Type::int(32), 0, 100, 1, IntPred::Ule, Flags::NONE);
2066 let found = bound(&it.func).expect("it is counted");
2067 let (_, assumptions) = found.parts();
2068 assert!(assumptions.iter().any(|a| matches!(a, Assumption::NoWrap(_))), "{assumptions:?}");
2069 }
2070
2071 #[test]
2072 fn an_unsigned_counter_stepping_by_one_is_held_by_its_own_test() {
2073 // `for (unsigned i = 0; i < n; i++)` written out. Unsigned arithmetic wraps in C so the
2074 // increment carries no `nuw`, and without reading the test this would rest on an
2075 // assumption nothing downstream can discharge.
2076 let it = counted(Type::int(32), 0, 100, 1, IntPred::Ult, Flags::NONE);
2077 let found = bound(&it.func).expect("it is counted");
2078 assert_eq!(found.assumptions(), &[]);
2079 assert_eq!(found.proven(), Some(Count::Exact(100)));
2080 }
2081
2082 #[test]
2083 fn counting_down_by_one_is_held_the_same_way() {
2084 let it = counted(Type::int(32), 100, 0, -1, IntPred::Ugt, Flags::NONE);
2085 let found = bound(&it.func).expect("it is counted");
2086 assert_eq!(found.assumptions(), &[]);
2087 assert_eq!(found.proven(), Some(Count::Exact(100)));
2088 }
2089
2090 #[test]
2091 fn a_step_of_two_can_jump_the_limit_so_the_test_holds_nothing() {
2092 // The counter is never at the limit, so the loop can be left by a step that goes from one
2093 // below the limit to one past the top of the type and comes back round at the bottom.
2094 let it = counted(Type::int(32), 0, 100, 2, IntPred::Ult, Flags::NONE);
2095 let found = bound(&it.func).expect("it is counted");
2096 let (_, assumptions) = found.parts();
2097 assert!(assumptions.iter().any(|a| matches!(a, Assumption::NoWrap(_))), "{assumptions:?}");
2098 }
2099
2100 #[test]
2101 fn a_test_the_counter_can_be_stepped_without_being_asked_holds_nothing_either() {
2102 // ```text
2103 // header(i): br_if flag, check, latch
2104 // check: br_if i <u 100, latch, exit
2105 // latch: jump header(i + 1)
2106 // ```
2107 // The counter goes round by a path that never reaches the test, so the test says nothing
2108 // about how far the counter got.
2109 let mut names = Interner::new();
2110 let mut func = Func::new(names.intern("f"), Signature::new());
2111 let entry = func.create_block();
2112 let header = func.create_block();
2113 let check = func.create_block();
2114 let latch = func.create_block();
2115 let exit = func.create_block();
2116 let flag = func.append_param(entry, Type::int(1));
2117 let counter = func.append_param(header, Type::int(32));
2118
2119 let mut build = Builder::new(&mut func, entry);
2120 let zero = build.iconst(Type::int(32), 0);
2121 build.jump(header, &[zero]);
2122 let mut build = Builder::new(&mut func, header);
2123 build.br_if(flag, check, &[], latch, &[]);
2124 let mut build = Builder::new(&mut func, check);
2125 let limit = build.iconst(Type::int(32), 100);
2126 let test = build.icmp(IntPred::Ult, counter, limit);
2127 build.br_if(test, latch, &[], exit, &[]);
2128 let mut build = Builder::new(&mut func, latch);
2129 let one = build.iconst(Type::int(32), 1);
2130 let next = build.binary(Opcode::Add, counter, one, Flags::NONE);
2131 build.jump(header, &[next]);
2132 let mut build = Builder::new(&mut func, exit);
2133 build.ret(&[]);
2134
2135 let found = bound(&func).expect("it is counted");
2136 let (_, assumptions) = found.parts();
2137 assert!(assumptions.iter().any(|a| matches!(a, Assumption::NoWrap(_))), "{assumptions:?}");
2138 }
2139
2140 #[test]
2141 fn a_test_that_ends_the_loop_when_it_succeeds_is_read_the_other_way_round() {
2142 // `for (i = 0; ; i++) if (i >= 100) break;`, which is the same loop with the arms of the
2143 // branch swapped. The test that keeps the loop going is the opposite of the one written.
2144 let mut names = Interner::new();
2145 let mut func = Func::new(names.intern("f"), Signature::new());
2146 let entry = func.create_block();
2147 let header = func.create_block();
2148 let body = func.create_block();
2149 let exit = func.create_block();
2150 let counter = func.append_param(header, Type::int(32));
2151
2152 let mut build = Builder::new(&mut func, entry);
2153 let zero = build.iconst(Type::int(32), 0);
2154 build.jump(header, &[zero]);
2155 let mut build = Builder::new(&mut func, header);
2156 let limit = build.iconst(Type::int(32), 100);
2157 let done = build.icmp(IntPred::Sge, counter, limit);
2158 build.br_if(done, exit, &[], body, &[]);
2159 let mut build = Builder::new(&mut func, body);
2160 let one = build.iconst(Type::int(32), 1);
2161 let next = build.binary(Opcode::Add, counter, one, Flags::NSW);
2162 build.jump(header, &[next]);
2163 let mut build = Builder::new(&mut func, exit);
2164 build.ret(&[]);
2165
2166 let (count, _) = bound(&func).expect("it is counted").parts();
2167 assert_eq!(count, Count::Exact(100));
2168 }
2169
2170 #[test]
2171 fn an_unsigned_limit_past_the_middle_of_its_type_is_not_a_negative_one() {
2172 // `for (unsigned char i = 0; i < 200; i++)`. Two hundred does not fit in a signed byte
2173 // and the constant is held as minus fifty six, so a distance taken at face value is
2174 // negative and reads as a loop that runs no times.
2175 let it = counted(Type::int(8), 0, 200, 1, IntPred::Ult, Flags::NUW);
2176 let found = bound(&it.func).expect("it is counted");
2177 assert_eq!(found.proven(), Some(Count::Exact(200)));
2178 }
2179
2180 #[test]
2181 fn a_walk_that_lands_on_a_not_equal_limit_exactly_is_counted() {
2182 // `while (i != 10)` counting by one, which is `while (p != end)` over an array once the
2183 // element size has been divided out. `!=` says nothing about how its operands are read,
2184 // so the promise it wants is the unsigned one and an `nsw` on its own is not enough.
2185 let it = counted(Type::int(32), 0, 10, 1, IntPred::Ne, Flags::NSW.union(Flags::NUW));
2186 let found = bound(&it.func).expect("it lands on its limit");
2187 // The step divides the distance and both are numbers, so it was checked rather than
2188 // assumed and there is nothing left over.
2189 assert_eq!(found.proven(), Some(Count::Exact(10)));
2190 }
2191
2192 #[test]
2193 fn a_counter_stepping_away_from_a_not_equal_limit_is_not_a_loop_that_runs_no_times() {
2194 // The distance is negative and an ordering test would read that as the loop never being
2195 // entered. `!=` reads it as the counter never arriving, which is an endless loop, and
2196 // answering zero for it was a real bug that the property test in `tests/scev.rs` found.
2197 let it = counted(Type::int(32), 48, 15, 1, IntPred::Ne, Flags::NSW);
2198 assert_eq!(bound(&it.func), None);
2199 }
2200
2201 #[test]
2202 fn a_counter_stepping_over_a_not_equal_limit_never_arrives_either() {
2203 // Zero, three, six, nine, twelve, and ten is never one of them. An ordering test would
2204 // have stopped at twelve.
2205 let it = counted(Type::int(32), 0, 10, 3, IntPred::Ne, Flags::NSW);
2206 assert_eq!(bound(&it.func), None);
2207 }
2208
2209 #[test]
2210 fn an_estimate_is_the_count_when_there_is_one_and_a_guess_when_there_is_not() {
2211 let counted_loop = counted(Type::int(32), 0, 7, 1, IntPred::Slt, Flags::NSW);
2212 let (cfg, loops) = analyse(&counted_loop.func);
2213 let id = loops.roots()[0];
2214 let estimate = Scev::new(&counted_loop.func, &cfg, &loops).estimate(id);
2215 assert_eq!(estimate.iterations(), 7);
2216 assert!(!estimate.is_guess());
2217
2218 // A loop this cannot count still has to answer, because the caller is deciding whether
2219 // something is worth doing rather than whether it is legal.
2220 let uncounted = counted(Type::int(32), 0, 100, 0, IntPred::Slt, Flags::NSW);
2221 let (cfg, loops) = analyse(&uncounted.func);
2222 let id = loops.roots()[0];
2223 let estimate = Scev::new(&uncounted.func, &cfg, &loops).estimate(id);
2224 assert!(estimate.is_guess());
2225 assert_eq!(estimate.iterations(), super::ASSUMED_ITERATIONS);
2226 }
2227
2228 #[test]
2229 fn a_value_the_loop_does_not_touch_is_invariant_rather_than_unknown() {
2230 let it = counted(Type::int(32), 0, 100, 1, IntPred::Slt, Flags::NSW);
2231 let (cfg, loops) = analyse(&it.func);
2232 let id = loops.roots()[0];
2233 let mut scev = Scev::new(&it.func, &cfg, &loops);
2234 // The counter's start is an `iconst` in the entry block, which is both.
2235 assert_eq!(
2236 scev.evolution(id, it.counter).chrec().expect("it evolves").base,
2237 Invariant::number(0)
2238 );
2239 }
2240
2241 #[test]
2242 fn a_back_edge_of_its_own_does_not_hide_the_counter() {
2243 // What canonicalization leaves behind. The back edge goes through a block that does nothing
2244 // but pass the increment on, so the value arriving at the header is a parameter of that
2245 // block rather than the increment itself. Reading through it is undoing a rename and not an
2246 // analysis, and without it the trip count of every loop the pipeline produces is nothing.
2247 let mut names = Interner::new();
2248 let mut func = Func::new(names.intern("f"), Signature::new());
2249 let entry = func.create_block();
2250 let header = func.create_block();
2251 let body = func.create_block();
2252 let latch = func.create_block();
2253 let exit = func.create_block();
2254 let counter = func.append_param(header, Type::int(32));
2255 let carried = func.append_param(latch, Type::int(32));
2256
2257 let start = Builder::new(&mut func, entry).iconst(Type::int(32), 0);
2258 Builder::new(&mut func, entry).jump(header, &[start]);
2259
2260 let mut build = Builder::new(&mut func, header);
2261 let limit = build.iconst(Type::int(32), 100);
2262 let test = build.icmp(IntPred::Slt, counter, limit);
2263 build.br_if(test, body, &[], exit, &[]);
2264
2265 let mut build = Builder::new(&mut func, body);
2266 let by = build.iconst(Type::int(32), 1);
2267 let next = build.binary(Opcode::Add, counter, by, Flags::NSW);
2268 build.jump(latch, &[next]);
2269
2270 Builder::new(&mut func, latch).jump(header, &[carried]);
2271 Builder::new(&mut func, exit).ret(&[]);
2272
2273 let chrec = evolution(&func, counter).chrec().expect("the counter still evolves");
2274 assert_eq!(chrec.base, Invariant::number(0));
2275 assert_eq!(chrec.step, Invariant::number(1));
2276 let (count, _) = bound(&func).expect("it is still counted").parts();
2277 assert_eq!(count, Count::Exact(100));
2278 }
2279
2280 #[test]
2281 fn every_assumption_says_what_it_is_in_a_line() {
2282 let it = counted(Type::int(8), 0, 100, 1, IntPred::Ult, Flags::NONE);
2283 let found = bound(&it.func).expect("it is counted");
2284 for assumption in found.assumptions() {
2285 let line = assumption.describe();
2286 assert!(!line.is_empty());
2287 assert!(!line.contains('\n'), "an assumption is one line: {line}");
2288 }
2289 }
2290}