Skip to content

ADR 0053: Proven-bounds list loops: the IndexError a loop's shape makes dead

Status: Final Type: Feature Created: 2026-08-06 Amends: 0002 (the Array bounds hoist and the modes story, extended to lists), 0027 (a list's IndexError check, elided where it is provably dead) Amended-By: 0068 (the unchecked twins widened to every narrow element kind) Related-ADRs: 0027 (the two-type split, the checked helpers), 0030 (the IR-level IndexError check), 0055 (the counted loop each lowered loop records), 0067 (the programs that asked for each extension)

Context

The benchmark page's identical-source lane (benchmarks) priced ADR 0027's two-type split and ordered this work: the same numeric kernel runs far slower over list[float] than over Array[Float64]. The costs, read from the emitted code: an xs[i] pays for the IR-level IndexError check (normalize, compare, raise-branch) plus the runtime helper's bounds backstop. The raise, a side exit in the loop body, blocks vectorization outright and forces per-iteration reloads.

Decision

For a loop whose shape proves its subscripts, the frontend elides the IR-level check and calls unchecked twin helpers (raw indexed access, no branches) for those subscripts. The base shape is for i in range(len(L)) (or range(n) after n = len(L)), counting up, with i and L never rebound. This is the Array bounds hoist (ADR 0002) extended to lists, with the two differences lists force:

  • Both modes. An Array's per-element check is a debug feature; a list's IndexError is semantics. Eliding it is legal exactly and only where it is provably dead, so the proof pays in release too.
  • The body must be provably resize-free. An Array cannot change shape; a list can shrink. A shrink under an elided check would turn a raise into a read of freed memory. So the body may call nothing but range and len, which also excludes a user call that could hold an alias, and may not del anything or store to a slice, since both resize a list without a call (notes/accept-then-wrong.md §64). A program the rule excludes keeps both check layers and the exact CPython behavior, IndexError included.

Numeric elements only: a Str or instance element stays on the checked, borrow-classified helpers. The twins cover int, float and bool, and since 0068 every narrow numeric element kind.

The backstop stays for everyone else. The runtime's bounds check still covers each unproven site in both modes (ADR 0027's argument is untouched). The checked helpers remain the only spelling the general subscript path has. The twins are reachable solely through the proof; the analysis is held by dedicated unit tests and by the differential suite, which is the same insurance the release-mode Array path lives on.

Stage A and stage B

Stage A proves the bound list only. In for i in range(len(x)): out[i] = x[i] * x[i], the reads of x go unchecked; the store to out stays checked, because a too-short companion must raise CPython's IndexError after the partial writes, which an aborting preheader guard cannot express.

Stage B, the min-prefix loop, covers companions without versioning semantics. Run the unchecked loop for i < min(len(L), len(M), …), provably safe for the lists involved, then continue in the ordinary checked loop for the remainder, which performs the partial writes and raises exactly where CPython does (usually zero iterations). The body is lowered twice, with no behavioral fork and no guard that changes what a too-short program prints. It applies only where the body subscripts a companion with the bare counter, so every loop stage A covers alone lowers as stage A lowers it.

The prefix, generalized

A loop no list bounds gets the stage-B prefix. The split needs nothing from a bound list but a start that cannot be negative, a step that counts up, and a limit every subscripted list reaches. So a range loop with no bound list (for i in range(n), for j in range(a, n, s)) runs unchecked while i < min(stop, len(L), …) over the lists L the body subscripts with the counter, then continues in the checked loop from the counter, so a step other than 1 keeps its progression. A start or step not known at compile time is tested once before the loop. When the start may be negative (a negative index means something else in Python) or the step may not count up, the limit is the start and no iteration runs unchecked. With a literal negative start or a non-positive literal step, the loop lowers as before. The other conditions are stage A's: the body rebinds neither the counter nor the lists, it resizes no list, and only element types with unchecked twins take part.

The prefix proves L[i + c] for an int literal c (also spelt c + i and i - c), as dynamic-programming and stencil loops write prev[j - 1] and x[i + 1]. The limit is len(L) - max(c) for each list. The start must reach -min(c) over all proven offsets, tested once when the start is not a literal and decided at compile time when it is (an offset a literal start makes negative is not proven, so that subscript stays checked). Both sides are spelt with the literal on the constant side, so nothing can overflow.

It proves L[e + i] for an offset expression e, as flat two-dimensional indexing writes a grid (g[up + c - 1], a[row * w + col]). The index is read as a +/- chain in which the counter is one added, unscaled term; the other terms may be names of int locals the body does not rebind, int literals, and +, - and * over them. The offset is evaluated once before the loop in plain arithmetic (so a loop that runs no iteration cannot trap on it in debug; the body evaluates it again, checked, before any access uses it). It is proven only while 0 <= e <= len(L) and the start is not negative; outside that, the whole loop runs checked. Names must be int exactly, because a narrower one wraps at its own width in the body and not in the guard (notes/accept-then-wrong.md §72). Where int grows (0075), the proof also holds only while every name in the offset holds a machine integer; a name past 64 bits sends the whole loop down the checked path, which computes with it as CPython does.

A local str subscripted by the counter is proven the same way. A str cannot change length, so the only conditions are a list's: the body does not rebind the name and resizes no list (which also keeps the string alive). The proven s[i] drops the IR's IndexError check; the runtime backstop remains.

A short literal range keeps its single loop. A loop whose start and stop are both literals and that runs at most 16 iterations takes no prefix. The C compiler unrolls a loop of known trip count, which a computed limit prevents, and a few iterations cannot pay for the split.

An ASCII str, and a nest of short loops

The prefix proves a str subscript only while the string is ASCII. For each str it proves, the prefix also tests once, before the loop, that the string holds one byte per code point; if not, the whole loop runs checked. No other loop proves a str subscript, so a proven s[i] is byte i of s. A non-ASCII string loses nothing CPython can see: the loop runs the checked path, which raises the same IndexError at the same iteration.

A proven s[i] == x is one byte compared, with no branch. x (a local str, a literal or another t[j]) equals s[i] exactly when it is one byte long and that byte is s[i]; the read is in bounds even for an empty x, whose byte 0 is its terminator and whose length already fails the test. The general compare's branches, inlined into an inner loop, kept the C compiler from holding the loop's other values in registers.

A nest of short loops is versioned once, at its outermost short loop. A short literal loop takes no prefix, so the subscripts in it would keep their checks. In a nest of range(b) or range(a, b) loops over int literals, each of at most 16 iterations, every counter's range is known when the code is compiled. A subscript L[e + Σ c·v] is proven when each v is the counter of a short loop around it inside the nest that the nest binds nowhere else, each c is an int literal, and e reads only int locals the nest does not bind. Σ c·v then lies between two constants low and high, and one guard before the nest tests -low <= e < len(L) - high for each list and offset. If all of them hold, a copy of the nest with those subscripts unchecked runs; otherwise the nest runs as it always did and raises CPython's IndexError at the same iteration, after the same writes. Both copies keep their literal bounds, and neither versions a short loop inside it again.

The conditions are a proven loop's. The list's elements have unchecked twins. The nest does not rebind the list, calls only range and len, and deletes nothing, so no length changes under it. A nest holding a function, a lambda or a comprehension is not versioned, since a name there may not be the nest's. low and high are below 2**40 in magnitude, so the guard cannot overflow. e is evaluated in plain arithmetic: in release the body's index wraps as e does, and in debug the body raises OverflowError before any access, so whenever the body reads an element, its index is e + Σ c·v.

What this does not touch

for v in xs: and comprehension walks use the runtime's counter against the current length each iteration and were never miscompilable. This ADR leaves unchanged negative indices, slices, an offset that is neither a literal nor an expression of unrebound int locals, and any subscript outside a proven loop or a versioned nest.

Consequences

  • Where the check was the difference, a proven list loop reaches the speed of the same loop over an Array, in both modes (stage B's square did). The gains on the programs of 0067 that asked for each extension are in notes/measurements.md.
  • A prefix loop and a versioned nest lower their body twice, which costs code size and is why short literal loops take no prefix.
  • What a program prints does not depend on the proof: a too-short companion, a negative start, an offset out of range or a non-ASCII string falls back to the checked loop, which raises where CPython does.