Skip to content

A flat generic def's spin takes words at its instance's layouts (#1195) - #1588

Merged
Lorenzobattistela merged 1 commit into
mainfrom
fix/1195-generic-flat-instance
Oct 16, 2026
Merged

Lorenzobattistela merged 1 commit into
mainfrom
fix/1195-generic-flat-instance

Conversation

@Lorenzobattistela

Copy link
Copy Markdown
Collaborator

Closes #1195.

Root cause

A generic def (-A: Type) already gets one spin per layout of its erased types, but every spin kept the generic calling convention: a value of type A crosses the call as one boxed word. So Bool.pick(Tint, ...) with a flat Tint{r, g, b} made the caller heap-allocate a node, the callee drop the unpicked one through the generic term_drop, and the result come back boxed to be unpacked again (ctr_take + free). On the device each small spin is inlined at every call site into the one kernel, so that heap round trip is copied per site, which is what blows up the Metal program.

Fix

A flat def's spin takes and returns words at its own instance's layouts. An open type takes the layout of the value that reaches it (lay_at). If a self-call changes an erased type (polymorphic recursion, e.g. grow(Dup<A>, ...)), the def keeps the generic convention, so there is no extra copy. Spins are the ones that already existed: the corpus has 1825 spins before and after.

Numbers

  • Issue repro (Bool.pick(Tint, ...)): Metal program 96,176 -> 74,816 B (the match version is 74,784); heap_alloc 14 -> 13.
  • Bendcraft at af8da15 with the issue's Bool.pick(Tint, ...): main 17 s / 4.20 MB Metal, this PR 9 s / 2.15 MB (no-pick baseline: 9 s / 2.25 MB). v2.0.34 did not finish (killed at 240 s, 3.4 GB). make test-native passes, bench checksums identical.
  • Emitted C over the 775 test files: 85 change, heap_alloc 16,223 -> 16,100, no file gains an allocation, total -57 KB.
  • Repro scaled to tree 22n: 1 thread 33 -> 15 ms, GPU 86 -> 81 ms.

New test tests/compile/generic_flat_instance.bend covers pick at Tint/V2/U32/List, a type-changing self-call (grow) and a type-keeping loop (last).

Gates

repo 54/54, test 1636/1636, ping 58/58, perf 124/124. comp.ts 63,997 / 64k tokens. Not run: safe (local bendtt not built; change is comp.ts only), CUDA, Linux, Windows.

@Lorenzobattistela Lorenzobattistela self-assigned this Oct 15, 2026
@Lorenzobattistela
Lorenzobattistela merged commit 096de7a into main Oct 16, 2026
1 check passed
@Lorenzobattistela
Lorenzobattistela deleted the fix/1195-generic-flat-instance branch October 16, 2026 13:03
@Lorenzobattistela Lorenzobattistela mentioned this pull request Oct 20, 2026
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.

A generic def over a Data record boxes it on the device heap: a Bool.pick of two records took Metal's compile from 8 s to over 11 minutes

1 participant