ADR 0078: Loop variables that borrow their element¶
Status: Accepted Type: Architecture Created: 2026-11-16 Amends: 0024 (a loop variable that meets the conditions below holds a borrowed value and is not a slot; there "there are no borrowed temporaries") Related-ADRs: 0007 (the raisers analysis, the shape the drop summary takes), 0028 (comprehensions are loops), 0053. Provenance: 0.3's task 5, neural1 and kmeanspp against Shed Skin's C++.
Context¶
ADR 0024 makes each reference a frame holds live in a slot. A loop variable is one of the slot kinds. A for x in xs over a list of instances therefore does three things per element besides the body: it reads the element (a borrowed pointer), increments the element's count as it lands in the slot, and decrements the count of the previous element. The unwind path and the epilogue release the slot once more. The rule exists so that a release point is never a dominance question.
On the census, this pair is the largest cost left in the loops the census programs spend their time in. neural1's sum([exciter.output for exciter in self.exciters], 0.0) reads one float field per element and pays a count pair for it; in kmeanspp's nearest_cluster_center, __pp_obj_decref takes 393 of about 3,000 working samples.
The pair protects against one thing: the element being freed while the variable still points at it. While the walked container is alive, it holds a reference to each element it has not dropped, so the element can only be freed after the container drops it. A container that is freed is one nothing holds, so it is not the walked one if the loop holds it. That leaves the operations that remove an element from a live list or set: an item or slice store, a del, pop, remove, discard or clear. Such an operation can reach the walked container through any alias of its type, from the body or from any code the body runs.
A review of the first draft found five programs that met the conditions and read a freed element. Each did it through code that runs without a call: with (__enter__), an augmented assignment or a comparison (an operator dunder), a yield in an inlined generator (the consumer runs there), a tuple target (for a, b in pairs with a store on list[tuple[Node, int]]), and a return inside a try with a finally that releases the element. It also found that the first draft's conditions admitted none of the loops it was measured on except one. This version replaces condition 3's "no call" with a summary of what calls and implicit dunders can drop, and states the consumer rule once.
Decision¶
A loop variable is borrowed (no count taken when an element lands in it, no release on rebinding, at unwind or in the epilogue) when all of these hold. The decision is made per function, once, before the function's first lowering, and recorded like held_iterables, so a versioned nest (ADR 0077) lowers both copies of a loop the same way.
-
The walk is over a list or a set, held for the whole loop. The loop walks a list, a set, or
enumerateorzipof lists. Each walked container is a parameter or a local that is not a cell (ADR 0076) and that no binding in the body rebinds, or else_hold_iterablesbinds it to a hidden local before the loop. When the variable is borrowed, the hold is taken whatever_may_rebindsays, at a cost of one count pair per loop. -
Nothing the loop runs drops an element of the walked type. Let
Tbe the walked container's element type. Neither the body nor any function it can reach may remove an element from a list or set whose element type isT. Covariant list aliasing is refused (PP100), so the alias of alist[T]is alist[T]; the test is on the exact type.This is decided by a drop summary: for each function and method of the module, the set of element types whose lists or sets it may remove an element from. It is a may-analysis over the call graph, computed as the least fixed point from the empty set, the way the raisers analysis (ADR 0007) computes which functions can raise. A function contributes:
Tfor each item or slice store, item or slicedel, augmented item store, and call ofpop,remove,discardorclearon a list or set ofT;- the summary of each function or method it calls by name;
- the summary of each dunder it runs without a call: an operator, a comparison,
in,with(__enter__and__exit__),str(),printand%formatting (__str__,__repr__), found the wayraisers._implicit_dundersfinds them; - all types for a call through a value (a
Callable, a lambda, a bound method stored in a field), an FFI call, a pygo operation, ayield,yield fromorawait, and anything the summary cannot name statically.
The body is summarized the same way. The loop qualifies when
Tis not in the result. Stores into fields, globals and dict values contribute nothing: they can free other objects but cannot make a live list or set drop an element. -
The variable is a plain function local, bound only by qualifying loops and read only inside their bodies. The target is a plain name, or the element position of
enumerateorzipover lists (for i, cc in enumerate(xs)). A tuple target that unpacks an element is not borrowed, because its parts are held by the element, which a store can free. The name is not a module global and not a cell. Every binding of the name in the function is the target of a loop that meets all three conditions, so all of them borrow or none does; comprehension variables are renamed per comprehension and meet this by construction. No read of the name falls outside those loops' bodies: a loop'selseclause, the code after it, an exception handler and a nesteddefor lambda are all outside. A walrus, an augmented assignment or adelof the name counts as a binding.
Uses of a borrowed variable. A use of a borrowed variable is lowered exactly as a use of a field read's result, which is already a borrowed producer. A store into a field, a list, a dict, a set or a tuple display, a union box, a raise and a return each take a count where the value is consumed. A return inside a try takes it where return evaluates its value, into the stash a finally path holds, before any finally runs. A borrowed variable is not a slot, so IR18 (a reference is released only through a slot the entry block owns) holds unchanged.
Consequences¶
- On neural1 the conditions admit five loop variables:
run'spoolandunit(all four loops; the methods they call store only float fields),computenewact'sexciterandupdatesum'smember, over a set. On kmeanspp they admitnearest_cluster_center'scc(sqr_distance_2Ddrops nothing) and thepandccloops ofkppandlloyd. Deleting the pair and the slot's releases for exactly those variables by hand in the kept C, and adding the two holds condition 1 requires for the field walks incomputenewactandupdatesum, gave the same output on both programs. Over five alternated rounds (2026-11-16, M1, CPU time, load 2.7 to 5), neural1's median went from 12.01 s to 9.96 s (17%) and kmeanspp's from 60.46 s to 56.00 s (7%). - A loop that calls code of the program's own is borrowed when that code's summary allows it, which covers the object-oriented loops of both programs. A loop whose body or callees remove an element from a list of the walked type keeps its slot, even when the list is a different one, since the summary does not track which list.
- AddressSanitizer is the only check of a wrong borrow. A borrowed element that is freed and then only read is never released again, so
decref's abort on a zero count does not fire, and in a release build the read is of freed memory and may return a wrong value without any error. IR18 cannot see a missing increment either. Somake asanover the new tests and over neural1 and kmeanspp is part of the implementation, not an optional check. A missed borrow leaves today's code. - Tests: an IR-level test for each way the variable stays a slot: a
with, an augmented assignment and a comparison that run a dropping dunder, ayieldin an inlined generator, a tuple target, a call to a function that drops from a list of the type (directly and two calls deep, and through recursion), a call through aCallable, a rebinding, a second binding by a loop that fails, and a read after the loop or in itselse. One test for each consumer of a borrowed variable (field, list, dict, set, tuple display, union box,raise,returnunderfinally) that the count is taken. The five programs the review found, held to CPython under ASan. The census differential on neural1 and kmeanspp.
Implementation (2026-11-16)¶
frontend/borrows.py computes the drop summary once per module, after the raisers analysis (pipeline.py), and stores it on the module (Module.drops). It also reads each function's candidate names off the function body. LoopLowering.borrows decides a name the first time a loop binding it is lowered, for all such loops at once. A comprehension decides the renamed variable where it builds the loop. The list and set walks then declare the variable with declare_loop_element and bind it with bind_loop_element.
The implementation admits less than the decision allows:
- The summary does not record types. A function that removes an element from any list or set counts as dropping, whatever the element type. Only the loop's own body is checked by type, and only where the container is a local or a field of one: there a store into a
list[float]or a dict is harmless. - A method is resolved by name. A call
o.m()reaches every method namedmin the module, so one droppingmmakes them all count. If any special method other than__init__drops, every operator, comparison,printandstr()counts as dropping. - Only instances borrow (classes and heap tuples). A
stror a list element keeps its slot. - Nothing borrows in a module that imports from pygo or from CPython, in a generator, or in a script's top level, whose loop variables are module globals.
- The in-place operators that would drop (
s -= t,s &= t,s ^= t,xs *= 0) are refused today (PP900), so the summary does not count them;test_borrowed_loopsfails if one starts to lower. raise eof a borrowed exception takes its own count before the raise.
On neural1, the loops load binds through an assignment keep their slots. Every other loop over instances borrows, in run, reset, computenewact, updatesum and display. On kmeanspp, every loop over instances borrows. Built by ppc in release and timed as before (CPU time, alternated, the same output on both), neural1 went from 7.65 s to 5.00 s over five rounds and kmeanspp from 70.66 s to 65.68 s over three, under a load of 30 to 50 from other processes. That noise puts the gains at about a third and about 7%.