Skip to content

A loop's mask-free copy covers the accesses in its helper defs, and a loop that runs to the array's last cell - #2149

Closed
nicolas-abril wants to merge 7 commits into
bendlang:mainfrom
nicolas-abril:opt/index-bounds-helpers
Closed

nicolas-abril wants to merge 7 commits into
bendlang:mainfrom
nicolas-abril:opt/index-bounds-helpers

Conversation

@nicolas-abril

@nicolas-abril nicolas-abril commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Stacks on #2137 (branch opt/index-bounds): this branch is #2137's two commits, two of its own and a merge of #2137's second, so until #2137 merges the diff here shows both. comp.ts is 70,235 ttok, 4,235 over the 66,000 cap (#2137 alone is 69,093; this adds 1,142), so repo-gate fails until that is settled. Measured on one Mac (M4), not on the cluster: the test and perf gates have not been run.

2026-11-23, two fixes for the losses this showed in the integration branch (3d772230, 72ce6fbb; +139 ttok, 70,374). The mask-free copy is now entered by one & test of its checks, and only when the loop's countdown allows 16 steps, with the checks computed under that test. A chain of && read to clang as a copy run once in 2^n, so its calls fell under the cold-call threshold: seam-carve-index's row loop called spin_dist twice per cell where the masked copy inlined and vectorised it. Short loops paid the checks on every entry, and the copy pushed fannkuch-redux's step over clang's inline threshold (cost 340-370 for 325). Against this PR's base (instructions / cycles): seam-carve-index 26.23G / 3.21G to 24.62G / 3.03G (41.3G / 5.5G in the integration before); fannkuch-redux 37.00G / 8.91G to 37.65G / 8.94G (40.20G / 10.19G before); editdist 36.88G, histogram 30.80G, terrain 41.15G, bfs 23.92G as before.

What it does

#2137 emits a loop (a spin) a second time without the index masks when each index has a bound that is fixed for the loop. It leaves the masks in two common places, and this covers both:

  • Accesses in a helper def. Bend needs a helper to take a read apart ((a, x) = r), so a loop's reads and writes often sit in small defs it calls, and those were compiled apart from the loop. Now the analysis and the copy without the masks emit a helper's body in place of the call, so its accesses are the loop's own and get the same check. A helper is a flat def that takes an Array (alone or in a record or pair) and does not call itself. The copy with the masks still calls the helper, as before.
  • A loop that runs to the array's last cell. For case 1n+p: f(p, i + 1, a[i] <- ..) over n cells from i, A loop whose Array indexes have a bound fixed for the loop runs a copy without the index masks #2137 bounds i by i0 + n0, one more than the last index it reads, so a loop over a whole array always failed its check and ran the masked copy. Under an arm that took k successors off the countdown, the counter is now at most i0 + c * (n0 - k).

What makes the helpers work:

  • An array in a record or pair (st: Dp, r: Array<U32> & U32) is followed word by word, so a loop that threads Dp{a, b, prev, cur} through a chain of helpers keeps all four arrays.
  • A helper's result is the array it was given only when every arm answers that same array. A helper that swaps two arrays, picks one of two, or answers a new one makes the array not fixed for the loop, and its accesses keep their masks.
  • At most 32 helper bodies are emitted in place per loop; past that the calls stay calls and what they return has no bound.

Two smaller changes to #2137's own output:

  • No copy for a check that cannot hold. a[x - 1] with x unbounded gave a bound of 2^32 - 1 through a temporary, so the loop got a second copy that could never run (histogram's col.go, app_slash_boss_3d's Mix.list). An operator with an unbounded operand now gives no bound.
  • A spin's size class is read off its masked copy alone, as on main. A loop whose Array indexes have a bound fixed for the loop runs a copy without the index masks #2137 measured both copies together, which can turn a spin into a device call (DFAR) or a host far call (FAR, for F32 loops) that main inlines; with helper bodies in the second copy that would happen more often.

A bound that was wrong, and three more like it

The first commit here had a memory-safety bug, fixed by the second:

  • A Nat fixed for the loop and matched in it. With m fixed and case 1n+p on it inside the loop, p got the bound of m itself, so a[x - from_nat(p)] passed its check one short and wrote past the array (4 cells, index 4: main prints 7, the first commit printed 0). The line is A loop whose Array indexes have a bound fixed for the loop runs a copy without the index masks #2137's, where nothing reached it: a matched parameter passed back to the loop was not seen as fixed. Following words by name made it fixed. The successors a match takes off a word now come off its bounds whatever the word's role.

Reading every place a bound is carried (a match, a subtraction, a conversion, a helper) found three more, two of them in #2137 too (since fixed there, in debfcdc6):

tests/run/array_index_carry.bend runs each of these in range and out of it; #2137 before that fix printed 2 of its 29 lines wrong, and the first commit here 4.

Results

One M4, GPU off. Other jobs were running on the machine, so these are instructions retired and cycles from /usr/bin/time -l (the best of 5 runs by cycles), not wall time. Each program prints the same result as on #2137.

bench instructions, #2137 this cycles, #2137 this
editdist 49.75G 36.89G 1.35x 11.76G 8.50G 1.38x
histogram 32.96G 30.82G 1.07x 5.66G 5.47G 1.04x
terrain 43.84G 41.15G 1.07x 9.07G 8.99G 1.01x
hashmap 18.51G 18.45G 1.00x 10.79G 10.78G 1.00x
bfs 23.93G 23.93G 1.00x 15.23G 15.22G 1.00x

One thread, measured on the second commit. The instruction counts repeat to 0.1% across runs; the cycles do not. editdist on #2137 ran between 10.6G and 13.4G cycles from one run to the next and between 8.3G and 8.7G here, so its cycle ratio was 1.28x in the quietest run and 1.51x in the busiest.

On 8 threads (totals over the threads, best of 4, measured on the first commit; the second changes no instruction count): editdist 49.75G to 36.89G instructions and 13.31G to 8.68G cycles, histogram 33.36G to 31.18G and 7.64G to 7.60G, terrain 43.84G to 41.16G and 10.14G to 9.90G, hashmap 18.51G to 18.47G and 11.07G to 10.95G.

The other 12 bench/runtime programs compile to byte-identical C. bfs differs only in the check's temporaries (its loop reads its indexes from the queue, which no interval bounds), and hashmap's three loops get a copy that changes nothing measurable (each step there is a chain walk).

editdist's gain is not the masks' own cost. In the assembly, the masked loop reads cur[j] back from memory right after the previous cell stored it (23 instructions a cell); without the masks clang keeps that value in a register (17 a cell). My reading is that the store and reload on the loop's carried path is also why the masked loop's cycles vary so much. (The log of #2137 put a hand-edit result of 1.28x there down to clang's inlining moving; the same hand edit on #2137's output gives 36.82G instructions, and this change gives 36.88G.)

A microbench of the common shape (m1.bend, not in the repo): a fill of a whole Array<U32> of 2^16 cells, then two in-place updates through a helper (upd(p, i + 1, upd.at(i, a[i]))), 20,000 rounds.

instructions cycles
main 28.22G 5.08G
#2137 28.22G 5.08G
this 4.03G (7.0x) 0.95G (5.3x)

#2137 changes nothing there: the fill's check fails by one, and the update's array goes through a helper.

Compile time: no difference I could measure. Instructions retired by the compiler, 7 runs each, lowest and median: app_slash_boss_3d 20.93G and 21.18G on #2137, 19.86G and 20.07G here; histogram 3.77G and 3.84G, then 3.73G and 4.10G; terrain 3.31G and 3.94G, then 3.55G and 3.99G; editdist 4.95G and 5.18G, then 4.89G and 5.19G. The emitted C grows 20% for terrain (the step of its loop is a chain of over 20 helpers), 5% for hashmap, 4% for editdist, 2% for histogram and 0.2% for the demo.

Checks

All local, against #2137 (b2086270), rerun on the second commit:

Not covered

  • Cluster gates and CUDA have not run.
  • An index read from memory and used as it is keeps its mask: bfs's loop (cells popped from its queue) is the suite's case, about 6% of its cycles by hand edit.
  • A call in an index that is no operator still gives the whole range (terrain's i - b2u(..)).
  • A counter kept in a record that a helper steps (St{.., head, tail}) has no bound; a counter must be a parameter of the loop.
  • A countdown that steps by two bounds its counter as if it stepped by one: sound, and loose.
  • Segments: as in A loop whose Array indexes have a bound fixed for the loop runs a copy without the index masks #2137, only flat defs get the two copies.

Cost

+1,142 ttok over #2137 (+4,273 over main). A loop that calls a helper is emitted three times instead of two (once more to read what its self calls pass with the helpers in place).

🤖 Generated with Claude Code

nicolas-abril and others added 5 commits November 12, 2026 19:40
…y without the index masks

An Array index wraps, so every access masks it by the block's size, and
the mask keeps clang from reading and writing a loop's cells side by
side. A spin is now emitted twice when the index of an access to a
fixed array has a bound that can be computed before the loop: the copy
without the masks runs when every bound is under its array's size, the
copy as before otherwise. The bound is an interval over the operators
of U32 and Nat, a Nat countdown, a U32 counter and the conversions.

histogram: 1.572 s to 1.280 s on one thread. comp.ts is 69,018 ttok.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
… loop that runs to the array's last cell

bendlang#2137 emits a spin a second time without the index masks when each
index has a bound fixed for the loop. Two shapes kept their masks:

- An access in a helper def the loop calls. The analysis and the
  mask-free copy now emit a helper's body in place of the call (a flat
  def that takes an Array and does not call itself, 32 a loop at most),
  so its accesses get the loop's checks. An array in a record or a pair
  is followed word by word, and a helper's result is the array it took
  only when every arm answers it.
- A loop over n cells from i: its counter was bounded by i0 + n0, one
  past the last index read, so a loop over a whole array failed its
  check. Under an arm that took k successors off the countdown the
  bound is i0 + c * (n0 - k).

An operator with an unbounded operand gives no bound, so a check that
cannot hold asks for no copy, and a spin's size class is read off its
masked copy alone, as on main.

Instructions retired, one thread, against bendlang#2137: editdist 49.74G to
36.88G, histogram 32.94G to 30.80G, terrain 43.83G to 41.15G; the
other benches the same. comp.ts is 70,103 ttok.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…o bound stays none

A Nat that is fixed for a loop and matched in it (`case 1n+p`) gave p
the bound of the whole word, so `a[x - from_nat(p)]` could pass its
check one short and write past the array: ix_word's `same` branch
ignored the successors the match took off. The branch is bendlang#2137's; the
word-by-word roles of the commit before made it reachable. The
successors now come off the bounds of any role.

Three more, found reading every place a bound is carried:

- A countdown past 2^32 saturates to 2^32 - 1, which stands for no
  bound; taking a successor off it made it a bound again (also in
  bendlang#2137). It stays 2^32 - 1.
- The same under the countdown floor of the commit before: a counter's
  steps have no bound when the countdown's entry value has none.
- An operator was known by its name alone, so a file's own
  `U32.is_far` had the bound of a comparison (also in bendlang#2137). An
  operator is now Base's def of that name.

tests/run/array_index_carry.bend runs each shape in range and out of
it; bendlang#2137 prints two of its 29 lines wrong and the commit before four.
The benches' instruction counts are unchanged. comp.ts is 70,235 ttok.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ator is Base's def

Two bounds that let an index out of range into the copy without masks,
so it wrote outside the array where main wraps:

- A countdown past 2^32 saturates to 2^32 - 1, which stands for no
  bound; taking a successor off it made it a bound again. With
  n = 2^32 + 5 the index (n - 1) - 4294967290 is 10 and the bound said
  4. It stays 2^32 - 1.
- An operator was known by its name alone, so a file's own
  `U32.is_far` had a comparison's bound of [0, 1]. An operator is now
  Base's def of that name.

tests/run/array_index_bound.bend gets both shapes, in range and out of
it, with counts the compiler cannot see; the commit before prints two
of the five new lines wrong. bfs and terrain change only in the bound
temporaries (same instruction counts); the other 15 benches emit the
same C. comp.ts is 69,093 ttok.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
nicolas-abril added a commit to nicolas-abril/bend that referenced this pull request Nov 17, 2026
…lending

Interaction of bendlang#2135 and bendlang#2149. bendlang#2135 marks an Array's word with the reads
lent from it (unit.arrs, by the word's C name) and makes those reads owned
when the word is dropped. bendlang#2149 emits a spin's body up to three times in one
unit, and each pass names its words as the one before. So the drop of the
table in a later pass of hashmap's sweep found the read the first pass had
lent from a word of the same name, and made that read a copy: the masked
copy of sweep kept and dropped every chain, which forces the chain's type
hot for the whole program. hashmap went from 6.08G to 8.04G instructions at
the merge of bendlang#2149 (18.45G with bendlang#2149 alone, where there is nothing to
lose); with the marks cleared at the head of each pass it is 6.10G.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
nicolas-abril added a commit to nicolas-abril/bend that referenced this pull request Nov 22, 2026
…the node, inline take and wrap, recursive drop, lent flat defs

With e34e9ce (the use-after-free fix for an erased field). Conflicts, all
in comp.ts:
- emit_args (three hunks; bendlang#2207 against bendlang#2135): bendlang#2135 added `inl` (an
  inlined callee roots its borrowed parameters) and `slot` (an Array slot
  passed as a variable is owned); bendlang#2207 added `lend` (a flat def that does
  not loop is lent a box its caller still uses) and makes an owned
  argument's words the ones val_own answers (term_keep of a lent word).
  Both kept: the parameters are (jump, fork, inl, lend); an owned argument
  takes val_own's words except when inlined, where bendlang#2135 leaves it to the
  callee's body, as before. lend[i] is only computed for an argument that
  is not borrowed, so it never meets a slot or a borrowed root.
- emit_spin (bendlang#2207 against bendlang#2149, bendlang#2152, bendlang#2154, bendlang#2135): the in-place
  helper (bendlang#2149's ix_inl) passes no lend array, since it has no lent copy;
  the out-of-line spin computes lend and calls its lent copy, and keeps
  bendlang#2152's HOT prefix, bendlang#2154's lanes (which refuse a def with a box
  parameter, so never meet a lent copy) and bendlang#2135's ret_root.
- emit_open / emit_native (bendlang#2207 against bendlang#2135 and bendlang#2149, bendlang#2154): bendlang#2135's
  def_vals now takes lend (a lent parameter's rent is "+", before the
  borrowed key); emit_native is (sc, k, to?, lend), its unit key and name
  carry the lent positions as bendlang#2207 has them, and every one of bendlang#2149's
  passes opens the lent copy the same way (74e27d5's clear stays first).
- the C macros after FAR: bendlang#2152's HOT and bendlang#2207's NEAR, both kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A chain of && reads to clang as a branch taken once in 2^n: the mask-free
copy's calls fell under its cold-call threshold (45) and stayed calls.
seam-carve-index's row loop called spin_dist twice per cell where the
masked copy inlined and vectorised it. The checks are now and-ed with &.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nicolas-abril added a commit to nicolas-abril/bend that referenced this pull request Nov 23, 2026
…opy is entered by one test of all its checks

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nicolas-abril added a commit to nicolas-abril/bend that referenced this pull request Nov 23, 2026
…, bendlang#2177 and bendlang#2207

Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	bend2/comp.ts
nicolas-abril added a commit to nicolas-abril/bend that referenced this pull request Nov 23, 2026
nicolas-abril added a commit to nicolas-abril/bend that referenced this pull request Nov 23, 2026
…s 16 steps

A loop that runs a few steps paid the checks' arithmetic on every entry,
and the copy made its spin too large for clang to inline into its callers
(fannkuch-redux's step, at cost 340-370 for 325). The countdown is now
tested first and the checks are computed under that test: fannkuch-redux
37.65G instructions against 37.00G on the base (40.20G before), cycles
level; seam-carve-index 24.62G against 26.23G, editdist, histogram,
terrain and bfs as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nicolas-abril added a commit to nicolas-abril/bend that referenced this pull request Nov 23, 2026
…opy is entered only when its countdown allows 16 steps

Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	bend2/comp.ts
nicolas-abril added a commit to nicolas-abril/bend that referenced this pull request Nov 23, 2026
…ed only when its countdown allows 16 steps

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nicolas-abril added a commit to nicolas-abril/bend that referenced this pull request Nov 23, 2026
…ed only when its countdown allows 16 steps

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nicolas-abril added a commit to nicolas-abril/bend that referenced this pull request Nov 23, 2026
…ed only when its countdown allows 16 steps

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nicolas-abril

Copy link
Copy Markdown
Collaborator Author

Moved to nicolas-abril#11, which keeps it saved off the main queue until it can be accepted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant