Skip to content

ty_holds opens a datatype once with DUMMY for its value arguments (#1513) - #1542

Merged
Lorenzobattistela merged 22 commits into
mainfrom
fix-1513-ty-holds
Oct 21, 2026
Merged

Lorenzobattistela merged 22 commits into
mainfrom
fix-1513-ty-holds

Conversation

@Lorenzobattistela

@Lorenzobattistela Lorenzobattistela commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #1513. Supersedes #1522 (its test is kept as gpu_reach_closure_instances).

The bug

ty_holds opens each datatype once per walk, keyed by name, with the arguments it first meets. For Duo{plain: Box<Num{}>, callable: Box<Fun{}>}, Box<Num{}> is opened (its field is U32) and Box<Fun{}> is skipped, so the bang's closure check says "no closure" and the GPU build fails with "a function the device does not hold". The same skip makes lay_of lay a family flat and overflow when it re-enters through a second instance, and makes lay_holds pick a spine by argument order (@nicolas-abril's review).

The fix

seen keys a datatype by its name and the term_key of its value arguments, so each instance's fields are looked into, for every caller (wide, lay_at, lay_of, lay_holds, ty_value).

A family can reach infinitely many instances (Ch<n> with a field Ch<1n + n>). When an instance re-enters its own family on the walk's path with a value argument whose key grew, the walk opens it once with its value arguments unknown (DUMMY), keyed by name. A field stuck on the unknown index (Pick(n)) is not an ADT, so the wide and lay_at predicates count it as holding: the safe side. An index that does not grow (Vec(2n) counting down) stays concrete, so the C is the same as main's.

The path keeps, per family, the shortest key of each value argument, so a step costs O(arguments), and an instance's answer is cached per file in FL.hold when it holds or met only instances opened under it (@nicolas-abril's suggestions). A predicate is keyed by its text, which is sound while no predicate captures a variable (true for all three call sites).

There is no constant: along a path, the concrete instances of a family have keys no longer than the first one's, so they are finitely many, and the unknown instance is opened once. The previous version's 8-deep / 64-key bound fell back to main's rule past it, so a big enough type still missed the closure; the two new tests show it.

Known approximations:

  • Keys are the raw syntax of the arguments, so one index written two ways counts twice.
  • ty_value has no safe side (either wrong answer can hurt). In it, a field stuck on the unknown index also counts as holding, so a kind whose family grows its own index with an index-computed field reads as a type, not a value. No test or repro reaches this.
  • lay_of's re-entry check reads the constructors' fields with the family's parameters free, so a re-entry behind a call stuck on the family's own index still overflows, as on main (@nicolas-abril's third repro of 10-21). Instances that differ only in a type-function argument still collapse, and a kind that re-enters its own family still loops, both as on main.

comp.ts: 66,000 tokens (main 65,612, cap 66,000).

Checks (merged with main 5ce1e07)

  • repo 54/54, test 1707/1707, ping 73/73, safe 1110 agree / 0 false reject; perf 123/124, the same cell as main (histogram PAR-CPU 1.25x, identical C).
  • The emitted C of all 1,786 tests, demos and benches is byte-identical to main, except chain, instances, mutual and family_cyclic_two, which fail on main.
  • New: wrapped (two Box instances under ten type arguments) and far (a closure only at index 12 of a growing chain). Both fail on main and on this PR's previous head with "a function the device does not hold".
  • All 15 tests of the PR pass on CPU, Metal and JS. deep, grow, nested and wrap check that the walk ends.
  • Vec(5000n) builds in 0.14 s (0.9 s before the path and cache changes) and a 32-way branching index in 0.2 s.
  • @nicolas-abril's repros:
    • The Vec(2n) bang emits the same C as main.
    • The two-instance Nest builds.
    • More's spine row is {2,0,1} in both argument orders.
    • The deep-kind Ch with 12, 70 and 300 wrappers builds and prints 9; main overflows.
    • The L<(k => Gr<k>)> lambda emits the same C as main.

Not run: CUDA, Linux, Windows (GPU checked on Metal only).

Please squash-merge.

🤖 Generated with Claude Code

ty_holds marked a datatype seen by name, so a later instance of the same
family (Chain<Num{}> after Chain<Fun{}>, or mutually nested A/B) was never
looked into, and a closure it held never reached the device. It now keys
seen by the instance, and stops 1000 datatypes deep.

Fixes #1513. Supersedes #1522.

Co-authored-by: oxura <[email protected]>
@Lorenzobattistela Lorenzobattistela self-assigned this Oct 13, 2026
Lorenzobattistela and others added 4 commits October 13, 2026 09:14
Type arguments are walked on their own, so keying them too let a nested
datatype (Grow<P<A, A>>) open 2^d instances. Tests: a nested datatype
compiles at once; a chain with a growing index stops at the cap.
…s may hold a closure (#1513)

Back to main's walk: each datatype is opened once, keyed by name. When
ty_clo meets it again with different arguments it answers yes, so the
GPU reach set takes the closures in. No per-instance walk, no depth cap.

Co-authored-by: oxura <[email protected]>
@Lorenzobattistela Lorenzobattistela changed the title ty_holds opens each datatype instance once (#1513) ty_clo takes a datatype met again with other value arguments to hold a closure (#1513) Oct 13, 2026

@nicolas-abril nicolas-abril left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fixes #1513, but the repeat check also says "may hold a closure" for common value-indexed families that hold none, which turns on wide and pulls every host closure into the device build. Nothing breaks, but it costs size and build time. Details inline.

One more point, outside the diff: ty_value (line 904) and lay_of's re-entry check (line 951) still call ty_holds with the name-keyed skip that caused #1513. In a kind like Duo{a: K<X>, b: K<Y>} where only K<Y> computes to Type, the second K is skipped, ty_value says "value", and that argument gets keyed by syntax instead of walked as a type argument. That breaks the assumption the new comment rests on, that type arguments are "looked into apart".

Comment thread bend2/comp.ts Resolved
Comment thread bend2/comp.ts Resolved
Comment thread bend2/comp.ts Resolved
Comment thread bend2/comp.ts Resolved
Comment thread bend2/comp.ts Resolved
Lorenzobattistela and others added 2 commits October 13, 2026 11:46
)

Its fields then cover every index it is met with, so a later instance
with another index needs no second walk, and plain index recursion
(Expr<-t>, Vec<A,-n>) still holds no closure. The value/type split of
the parameters is memoized per datatype (FL.vals).

Co-authored-by: oxura <[email protected]>
@Lorenzobattistela Lorenzobattistela changed the title ty_clo takes a datatype met again with other value arguments to hold a closure (#1513) ty_holds opens a datatype once with DUMMY for its value arguments (#1513) Oct 13, 2026
…1513)

lay_of's re-entry walk seeks one datatype, so a field stuck on DUMMY
read as no re-entry: Nest<n> hiding Nest<1n+n> behind a family in a
nested datatype was laid flat and lay_of overflowed the stack.
Lorenzobattistela and others added 2 commits October 20, 2026 11:05
main's ty_holds now takes p as a datatype name too (#1438); a name
predicate keeps the first-met arguments, as lay_of's re-entry check did.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
DUMMY is a Var, so every predicate took it as a hit and lay_at laid a
concrete Box<Num{}> open. Only wide needs an answer for every index;
lay_at, ty_value and lay_of keep the arguments first met, as on main.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@nicolas-abril

Copy link
Copy Markdown
Collaborator

Review

I found four problems. Line numbers refer to the PR head. Items 1–3 were reproduced by compiling small programs; 2 and 3 also happen on main 60ca80a, so this PR doesn't cause them, but it leaves them in place.

  1. Vectors now turn wide on, which contradicts "same as main" (comp.ts:2946). With DUMMY swapped in for value arguments, the usual length-indexed shape (Vec.Con<-p>{tail: Vec(p)}, Base's Word.Con<-p>{tail: Word(p)}) leaves Vec(DUMMY) stuck, and the predicate treats that as may-hold-closure. So a bang over a concrete-length vector pulls every host closure into the device build. Repro: def sum(v: Vec(2n)) -> U32 called as sum!(...), plus an unrelated lambda passed to a host function in main. On main the closure segments stay under #if !DEVICE (12 guards). On this PR, 2 of them move into the device build (10 guards). That is a bigger device build for a common pattern with no closure in it, not just the Pick corner case the PR names as the trade-off.

  2. lay_of can still recurse forever, from the same root cause as ty_holds skips a closure in a later instance of the same datatype #1513 (comp.ts:985). seen still opens a datatype once per walk, keyed by name, with the arguments it meets first. lay_of's re-entry check relies on it, so a type that re-enters itself through a second, differently indexed instance of something already seen is laid out flat, and lay_of never stops:

    def Cell(b: Bool, n: Nat) -> Data:
      match b:
        case False{}:
          U32
        case True{}:
          Nest<(1n + n : Nat)>
    
    type Hold<-b: Bool, -n: Nat> is Data:
      Hold{value: Cell(b, n)}
    
    type Nest<-n: Nat> is Data:
      End{}
      More{next: Two<Hold<False{}, n>, Hold<True{}, n>>}

    Hold<False{}, n> is opened first (U32) and marks Hold as seen. Hold<True{}, n> is then skipped, so Nest isn't treated as a box, and lay_of walks Nest<1n>, Nest<2n>, ... until "the machine stack overflowed". family_cyclic_nested only covers the single-instance case.

  3. The same flaw gives a wrong spine column (comp.ts:1090). lay_holds calls ty_holds(A, fam) with the same seen behaviour, so a field that reaches the family only through the second instance is turned from BOX into W32:

    def Cell(b: Bool) -> Data:
      match b:
        case False{}:
          U32
        case True{}:
          Nest
    
    type Hold<-b: Bool> is Data:
      Hold{value: Cell(b)}
    
    type Two<-A: Data, -B: Data> is Data:
      Two{a: A, b: B}
    
    type Nest is Data:
      End{}
      More{next: List<&2, Two<Hold<False{}>, Hold<True{}>>>, item: List<&2, U32>}

    More's CID_T row is { 2, 0, 0 } (no spine). Swapping Two's arguments to Two<Hold<True{}>, Hold<False{}>> gives { 2, 0, 1 } (spine = next), the correct answer. The two programs differ only in argument order. Here nothing is read back wrong, because with a spine of 0 no fields get swapped. But the tail-first drop order from fix(runtime): release tail-drop frames before the last child #1438 is lost for More: its node is freed only after the whole next chain has been dropped. The List around the instances is what lets this through instead of hitting item 2.

  4. The fix is at the wrong level (comp.ts:917). The any flag special-cases the one caller that wide uses. Items 2 and 3 are the same bug in other callers (lay_of, lay_holds, and lay_at and ty_value use the same walk). Keying seen by name plus the normalized value arguments, with a depth or fuel bound so growing indices can't loop forever, would fix ty_holds skips a closure in a later instance of the same datatype #1513 for every caller at once. It would also avoid the over-approximation behind item 1, so Vec/Word would stay as they are on main.

Item 1 is a regression and should be fixed before merging. 4 is the fix I'd suggest for 1–3 together.

🤖 Generated with Claude Code

Lorenzobattistela and others added 5 commits October 20, 2026 18:11
seen keys a datatype by its name and its normalized value arguments, so
each instance's fields are looked into; a type argument already walked is
skipped, and a walk 1000 calls deep or an index past 4096 characters
answers that it holds. This drops the DUMMY opening and the any flag:
Vec and Word keep main's answer, and lay_of and lay_holds no longer miss
a second instance's re-entry (family_cyclic_two).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…56 (#1513)

Normalizing an index expanded a big Nat into a Succ chain and overflowed
term_lower, and a growing index ran into the cap, whose true boxed closed
types and made wide true. The key is now the value arguments as written;
past 256 instances of a family the walk opens it once more with DUMMY for
them, and a walk 4000 calls deep holds. FL.vals is seeded before it is
computed, so a kind that meets its own family again does not loop.
family_cyclic_nested passed on main, so it goes; kind_reenter is new.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
FL.vals is seeded inside its memo, the depth cap joins the return, and
the comment is shorter; behaviour is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…es (#1513)

FL.tys flags type arguments, so its seed reads a family met again while
its kinds are worked out as value-indexed, as its own answer will say
(kind_reenter's d: D was a type argument). 64 instances per walk before
the DUMMY opening, and a walk 5000 entries long instead of 4000 calls
deep, keep growing families as cheap as main.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Lorenzobattistela

Copy link
Copy Markdown
Collaborator Author

@nicolas-abril thanks, this follows your item 4: seen now keys a datatype by name plus value arguments, for every caller, with bounds so a growing index ends (64 instances, then one DUMMY opening; a 5000-entry cap). Items 1–3: the Vec(2n) bang emits the same C as main, the two-instance Nest builds (new test family_cyclic_two), and More's spine is {2,0,1} in both argument orders. The emitted C of every test, demo and bench is byte-identical to main apart from the 5 tests that fail on main. The approximations left are listed in the description.

Lorenzobattistela and others added 2 commits October 21, 2026 06:32
…1513)

Past 64 instances a family is opened with DUMMY, so a field computed from
its index stays stuck; lay_of and lay_holds looking for a datatype by name
read that as "absent" and could lay a recursive type flat until the stack
overflowed. Once a walk widens, a stuck type counts as found. The depth
cap is back (4000 calls), so a large flat type is not boxed for its
field count. The FL.tys memo and kind_reenter go: the kind re-entry loop
is main's, not #1513's, and comp.ts needs the tokens.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@nicolas-abril

Copy link
Copy Markdown
Collaborator

Three repros against the PR head (59d3049), checked against main (042e797) with bun on macOS. Each one compiles to C with bend <file> -o out.c. The interpreted runs print the expected value in every case.

1. A type-function argument uses up the widened key K<~>

The Lam case in ty_holds opens Gr<DUMMY> before anything has widened. When Gr widens later, it computes the same key Gr<~>, finds it already in seen, and returns false. So the stuck field is never checked with the flag set.

import Base

# Ge(m, k) is T once k reaches m, else U32
def Ge(m: Nat, k: Nat) -> Data:
  match m:
    case 0n:
      T
    case 1n+p:
      match k:
        case 0n:
          U32
        case 1n+q:
          Ge(p, q)

# Gr<0n> reaches T at its 70th link, behind Ge(70n, k)
type Gr<-k: Nat> is Data:
  Stop{x: Ge(70n, k)}
  More{next: Gr<(1n + k : Nat)>}

type L<F: Nat -> Data> is Data:
  LNil{}
  LCons{x: F(0n), rest: L<F>}

type T is Data:
  Leaf{}
  Node{a: U32, l: L<(k => Gr<k>)>, b: U32}

def f(t: T) -> U32:
  match t:
    case Leaf{}:
      1
    case Node{a, l, b}:
      a

def main() -> U32:
  f(Node{3, LNil{}, 4})

#|3
  • Control: replace L with type L is Data: LNil{} / LCons{x: Gr<0n>, rest: L} and give Node the field l: L. This describes the same data without the lambda. The PR's widening then finds T: T becomes a box (STAT_LEN 0 → 3) and Node's spine row goes from {3,0,0} to {3,0,1}.
  • With the lambda: the PR's emitted C is byte-identical to main's. T is flat and the spine row is {3,0,0}, so lay_of and lay_holds both miss the re-entry.

This case doesn't crash. Any family that can widen re-enters itself and becomes a box, which stops lay_of from recursing. A wrong spine row only changes the order free walks a node in.

2. Hitting the depth cap makes ty_value call a value argument a type argument

This is family_cyclic_two with Bool replaced by a kind whose walk is deep:

import Base

type Bx<A: Data> is Data:
  Bx{v: A}

type Ch<-n: Nat> is Data:
  End{}
  Link{v: U32, next: Bx<Bx<...70 wrappers...<Ch<(1n + n : Nat)>>...>>}

type B is Data:
  Fa{}
  Tr{}
  Deep{d: Ch<0n>}

def Cell(b: B, n: Nat) -> Data:
  match b:
    case Fa{}:
      U32
    case Tr{}:
      Nest<(1n + n : Nat)>
    case Deep{d}:
      U32

type Hold<-b: B, -n: Nat> is Data:
  Hold{value: Cell(b, n)}

# Two, Nest, read and main exactly as in tests/compile/family_cyclic_two.bend
# (End renamed End2, since Ch already has an End)
Bx wrappers per link ty_value(B) main -o .c PR -o .c
12 true stack overflow builds
70 false (cap hit) stack overflow stack overflow

To confirm the cause, I temporarily logged ty_value(B). With 70 wrappers the walk over B reaches d > 3999 and reports "holds", so ty_value returns false. b is then treated as a type argument, Hold<Fa{}, n> and Hold<Tr{}, n> share the key Hold<,n>, the second instance is skipped, and #1513's overflow is back.

The cap makes ty_holds report "holds" when it gives up, and ty_value negates that result. Here, giving up should count as a value argument.

3. A re-entry behind a call stuck on the family's own index (on main too)

import Base

def Cell(n: Nat) -> Data:
  match n:
    case 0n:
      Nest<1n>
    case 1n+p:
      Nest<(2n + p : Nat)>

type Hold<-n: Nat> is Data:
  Hold{value: Cell(n)}

type Nest<-n: Nat> is Data:
  End{}
  More{next: Hold<n>}

def read(t: Nest<0n>) -> U32:
  match t:
    case End{}:
      7
    case More{next}:
      0

def main() -> U32:
  read(End{})

#|7

The C build overflows the stack on both main and the PR. lay_of's generic walk sees Cell(n) stuck on Nest's own parameter. That isn't DUMMY, and nothing has widened, so the stuck type doesn't count as found. Nest<0n> is then laid flat and recurses through Nest<1n>, Nest<2n>, and so on. The PR doesn't cause this, but its list of known approximations doesn't mention it.

🤖 Generated with Claude Code

Lorenzobattistela and others added 2 commits October 21, 2026 08:52
…#1513)

Drops the DUMMY widening, the stuck-type rule and the depth cap that
answered "holds": past 8 calls deep or 64 keys a walk falls back to
main's once-per-name rule, so the bound never flips ty_value or turns a
plain family wide.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Lorenzobattistela

Copy link
Copy Markdown
Collaborator Author

@nicolas-abril thanks. I've replaced the widening with a smaller rule. seen keys a datatype by name and value arguments for the first 8 calls of depth and 64 keys of a walk, and by name alone after that, as on main. There's no DUMMY, no stuck-type rule, and no cap that answers "holds".

  1. The lambda case no longer interacts with widening. L<(k => Gr<k>)> and the control both emit the same C as main.
  2. ty_value can no longer flip: the bound falls back to main's rule instead of answering "holds". Your deep-kind repro builds and prints 9 with 12, 70 and 300 wrappers.
  3. This one is lay_of's re-entry check on the generic constructor fields, which is main's. Passing the instance's arguments there fixes it, but it changes the layout of about 140 tests and demos, so I've listed it under known approximations rather than folding it in here.

The emitted C of every test, demo and bench is identical to main except chain, instances, mutual and family_cyclic_two. comp.ts is +81 tokens. The description has the details.

🤖 Generated with Claude Code

… walked once with it unknown (#1513)

Drops the 8-deep / 64-key bound: past it the walk fell back to main's
name rule and missed later instances, so a big enough type still failed.
A field stuck on the unknown index counts as holding, the safe side, and
keys of bounded length keep the walk finite. New tests: wrapped (two
instances under ten type arguments) and far (a closure at index 12 of a
growing chain); both fail on main.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

@nicolas-abril nicolas-abril left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Written by an AI agent for @nicolas-abril.

I looked into the slowdowns listed under "Known approximations" (Vec(5000n), the branching index). Two changes bring them back to about main's speed. The emitted C is byte-identical to this PR's head everywhere I checked. Both are in the two suggestions below. They also need one line in file_new, which is outside this PR's diff, so it can't be a suggestion: after holds: new Map<string, Lay>(), add

    hold: new Map<string, boolean>(),
compile_book, median of 5 runs main this PR + path fix + cache
Vec(5000n) (counting down, under a bang) 34 ms 776 ms 62 ms 57 ms
32-way branching index (G<-n> with 32 fields G<(k+1n + n : Nat)>) 6 ms 78–148 ms 80 ms 13 ms
Chromi examples/eco/main.bend 8.00 s 8.04 s – 8.01 s

1. The path costs O(depth) at every step. The profile of Vec(5000n) puts almost all of ty_holds's time in on.some(...) and [...on, [t.k, xs]]. Each step scans and copies the whole path, so a 5000-deep walk is quadratic. The suggestion keeps, per family on the path, the shortest key of each value argument, and restores it on the way out. "Some ancestor's key is shorter" is the same test as "longer than the shortest", so re gives the same answers, and a step now costs O(arguments).

2. Walks repeat across calls. On the branching index, lay_at runs ty_holds from 37 roots that share subtrees. Together they open 1,098 instances, only 74 of them distinct (Eco: 7,171 opened, 1,373 distinct). The suggestion keeps each instance's answer in FL.hold, keyed by the predicate, the instance key and the path state on. The path state is part of the key because re depends on it. Not every answer is safe to keep:

  • A true is always kept.
  • A false is kept only when the instance's fields met (in seen) nothing but instances opened under it. Its walk then never depended on anything outside it, so a fresh walk from it would answer the same. seen now numbers instances in opening order, and low carries the earliest one met back up.
  • An instance whose walk was cut short by an ancestor or an earlier sibling is not cached, because its false may be provisional.

A predicate is keyed by String(p): the TypeScript text of the lambda in comp.ts, such as (t) => ty_tag(t, "Var App"). Nothing from the user's program goes into it. That's sound only while every predicate captures nothing, which holds for all three call sites today, and the comment says so. Named predicate functions would be sturdier but cost about 55 tokens, and with them comp.ts is over its cap.

Checks (on top of 1f5df71, macOS M-series):

  • Emitted C: I compiled every .bend under tests/, demos/ and bench/ in one process with this PR's head and with the suggestions. All 867 programs that compile give byte-identical C. The other 925 are tests meant to fail, and they fail with the same errors.
  • This PR's tests: all 10 pass as Metal binaries.
  • Earlier repros: the two Box instances behind a 64-key field and behind 7 wrappers still print 42.
  • repo: 54/54. comp.ts is 65,996 ttok (cap 66,000).
  • Not run: gates/test.ts on the minis, CUDA, Linux.

🤖 Generated with Claude Code

Comment thread bend2/comp.ts Resolved
Comment thread bend2/comp.ts Resolved
…cache

From @nicolas-abril's review: the path keeps each family's shortest value
keys (O(arguments) per step instead of scanning and copying the path), and
an instance's answer is kept in FL.hold when it holds or met only
instances opened under it. Vec(5000n) and the branching index build at
about main's speed.

Co-authored-by: nicolas-abril <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Lorenzobattistela
Lorenzobattistela merged commit 9bc7df3 into main Oct 21, 2026
1 check passed
wakamex added a commit to wakamex/bend that referenced this pull request Oct 22, 2026
…on-tail recursion under ! no longer faults at 1023 frames (bendlang#1393, bendlang#1394)

Today on main (de26a91, after bendlang#1809 reverted bendlang#1439), emit_fork emits WL_ROOM(N) before pushing each sequential continuation frame, and WL_ROOM(N) posts ERR_DEEP and returns 0 on DEVICE once a lane's 2048-word stack fills, faulting at 1023 frames of List.append (bendlang#1393) or on an unbalanced fork tree (bendlang#1394). bendlang#1439 (40402b4) replaced WL_ROOM(N) with WL_ROOM(N, D) calling a 4-argument lane_spill(e, sp, N, D) at every sequential call site while the caller segment's local variables were still live, followed by a second branch if (!(sp = ...)) { err_post(e.mem, ERR_DEEP); return 0; }, and added a separate unspill block in WL_CASE(FID_EXIT). That grew the device CFG at every WL_ROOM site (27 device sites in symreg, 8 in merkle) and slowed bend -o's --gpu-build step by 17% on symreg and merkle (bendlang#1809).

This change moves the stack-room check to emit_jump, after the sequential frame push and after r0..rn are loaded (where all caller segment local variables are dead and the entire continuation frame is already on the stack below sp), and makes WL_ROOM(F) on DEVICE jump to one cold sp_spill: label at the bottom of switch (fid) in work_loop:

- emit_fork removes WL_ROOM(fr.length) before STK(j) = w and passes push = true to emit_jump(sc, cargs, c.k!, !fork && c.b, true). No other emit_jump caller passes push = true, so tail jumps and self-tail loops without a frame push emit no WL_ROOM.
- emit_jump with push = true emits WL_ROOM(seg_ref(sc, fid)) right after r0..rn are assigned, before WL_JMP or WL_AGAIN. Self-recursive calls in emit_fork still set sc.seg.spin = true and take WL_AGAIN on the normal path when the stack is not full.
- Because WL_ROOM runs after STK(j) = w; WL_PUSHN(fr.length) and after r0..rn are loaded, all caller segment locals are dead and the caller's complete continuation frame sits below sp. In bendlang#1439, WL_ROOM ran before WL_PUSHN, so spilling at a second fork call (such as walk in tests/compile/bang_lane_spill.bend) split the earlier call's stack words from the new frame's words across the exit frame unless lane_spill took D and copied D words back above the exit frame. Emitting WL_ROOM after WL_PUSHN places the exit frame above the complete continuation frame, so lane_spill(e, sp) needs neither N nor D.
- On !DEVICE, WL_ROOM(F) expands to nothing (host SEQ-CPU and PAR-CPU machine code is byte-for-byte identical).
- On DEVICE, WL_ROOM(F) checks if (sp >= e.mem + STAT_OFF - 247 * CUBE) { fid = (F); goto sp_spill; }. Because comp.ts caps each continuation segment's parameter count at WIDE (247), a single frame push adds at most WIDE + 1 (248) words, so STAK_LEN - WIDE (1801 words) is a static watermark: starting below 1801 words, pushing a frame reaches at most 2048 words (STAK_LEN), and every word below sp belongs to a complete pushed frame.
- At the bottom of switch (fid) in work_loop on DEVICE, inside default: after return 0;, sp_spill: sp = lane_spill(e, sp); calls FAR DEV Term* lane_spill(Env e, DEV Term* sp) at a single call site where only e, sp, fid, and r0..rn are live, then exits switch (fid) to loop back to WL_SPIN -> switch (fid) without placing a label before switch (fid).
- In WL_CASE(FID_EXIT), unspilling shares the existing WL_ARGS + heap_free + WL_TAKE block with continuation dispatch under cont != TERM_HOLE && ((DEVICE && wf == FID_EXIT) || fid_resw(wf)), ending with if (DEVICE && wf == FID_EXIT) { WL_RETN(n); }.

comp.ts goes from 66,000 to 66,268 ttok (+268 ttok, vs +283 in bendlang#1439; main is at the 66,000 cap after bendlang#1809 kept bendlang#1439's token cuts and bendlang#1542 used the 283 tokens).
@Lorenzobattistela Lorenzobattistela mentioned this pull request Oct 23, 2026
@nicolas-abril
nicolas-abril deleted the fix-1513-ty-holds branch October 28, 2026 15:52
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.

ty_holds skips a closure in a later instance of the same datatype

2 participants