From e1b6a3e58c27d8bf16d6f377b325c1d038830453 Mon Sep 17 00:00:00 2001 From: Nico Abril Date: Sun, 15 Nov 2026 23:44:18 +0100 Subject: [PATCH 1/3] perf(comp): a def whose tail adds one call to itself to a Nat runs as a loop Nat.add(e, f(..)) or 1n+f(..) in tail position was a non-tail call: a frame on the heap stack and an indirect return per step, where C carries the sum in a register (String.length, List.length, any count or digit sum written the plain way). Such a call no longer keeps its def from being flat: the def's spin holds the sum in acc, adds the other operand at the call and jumps to itself, and adds acc to whatever it answers. Nats only grow under add, so a partial sum in either order is at most the whole one and both orders stop at 2^48-1 together. C lane only. Co-Authored-By: Claude Fable 5.2 --- bend2/comp.ts | 38 +++++++++- tests/run/nat_sum_loop.bend | 122 ++++++++++++++++++++++++++++++++ tests/run/nat_sum_overflow.bend | 23 ++++++ 3 files changed, 181 insertions(+), 2 deletions(-) create mode 100644 tests/run/nat_sum_loop.bend create mode 100644 tests/run/nat_sum_overflow.bend diff --git a/bend2/comp.ts b/bend2/comp.ts index be82a5d8b..545431783 100644 --- a/bend2/comp.ts +++ b/bend2/comp.ts @@ -1095,6 +1095,19 @@ function loop_of(k: Name): Name[] { return memo(FL.loops, k, () => (visit(k), FL.loops.get(k)!)); } +// A tail Nat.add, or successors, of a call to d: a flat d loops on that call +// and sums the other operand in acc. No partial sum of Nats passes the whole. +// A second call to d, in the other operand, keeps d from being flat. +function acc_of(d: Name, t: HTerm): [HTerm | number, HTerm] | null { + const s = term_strip(t); + const m = term_spine(s); + const [b, n] = s.$ === "Ctr" && s.k === "Succ" ? nat_peel(s) : [null, 0]; + const i = m.t.$ === "Ref" && m.t.k === "Nat.add" && intr_of(m.t.k) + ? m.args.findIndex((a) => term_spine(a).k === d) : -1; + return b !== null && term_spine(b).k === d ? [n, b] + : i < 0 ? null : [m.args[1 - i], m.args[i]]; +} + function flat_of(k: Name): boolean { return memo(FL.flats, k, () => { const deps = FL.srcs.get(k); @@ -1148,6 +1161,7 @@ function file_new(book: Bend.Book, js: boolean) { srcs: new Map | null>(), loops: new Map(), flats: new Map(), + accs: new Set(), funs: new Map(), nodes: new Map(), lays: new Map(), @@ -1229,7 +1243,13 @@ function file_book(roots: Name[]): void { } const deps = new Set(); let flat = true; + let acc: HTerm | null = null; term_any(fun_of(d).h!, (s, tail) => { + const ac = tail && !FL.js && fun_of(d).ret === W64 ? acc_of(d, s) : null; + if (ac) { + acc = term_strip(ac[1]); + FL.accs.add(d); + } if (s.$ === "Ref") { if (s.b) { FL.bangs.add(s.k); @@ -1244,7 +1264,8 @@ function file_book(roots: Name[]): void { deps.add(ck.k); } flat &&= !((s.$ === "Let" && s.k.length >= 2) - || (ck.k !== null && (ck.b || (ck.k === d && !tail)))); + || (ck.k !== null && (ck.b + || (ck.k === d && !tail && term_strip(s) !== acc)))); return false; }); FL.srcs.set(d, flat ? deps : null); @@ -2052,13 +2073,18 @@ function emit_each(sc: Scope, xs: HTerm[], ats: Lay[] = [], ...sc.rest] }, x, tys[i] ?? null, ats[i] ?? null)); } +function acc_on(sc: Scope): boolean { + return sc.seg.native && FL.accs.has(sc.seg.def); +} + function emit_put(sc: Scope, dst: Val | null, v: Val): void { bind_dead(sc, []); if (dst === null) { spare_flush(sc); } const ws = val_own(val_to(sc, v, dst?.lay ?? sc.seg.ret)); - file_push(sc, ...ws.map((w, j) => `${dst?.ws[j] ?? "r" + j} = ${w};`)); + file_push(sc, ...ws.map((w, j) => `${dst?.ws[j] ?? "r" + j} = ${ + acc_on(sc) ? `nat_chk(e, acc + ${w})` : w};`)); if (dst === null) { file_push(sc, `WL_RETN(${ws.length});`); } @@ -2104,6 +2130,7 @@ function emit_native(sc: Scope, k: Name): string { val_new(seg.ret.ks.map((_, j) => `o[${j}]`), seg.ret)); const body = [...seg_text([...seg.ks.flatMap((kd, i) => arr_q(kd) ? [`Term h${i} = r${i};`] : []), ...seg_take(seg), + ...FL.accs.has(k) ? ["u64 acc = 0;"] : [], seg.spin ? "WL_SPIN" : "for (;;) {"], 1), ...seg_text(seg.lines, 2), " break;", " }", " return 1;", "}"]; const text = body.join("\n"); @@ -2398,6 +2425,13 @@ function emit_body(sc: Scope, tm: HTerm, ty0: HTerm | null, args: Val[], return emit_body(sc, term_eta(x, ty!, 1), ty, args, dst); } sc = { ...sc, rest: [] }; + const ac = acc_on(sc) ? acc_of(sc.seg.def, x) : null; + if (ac) { + file_push(sc, `acc = nat_chk(e, acc + ${typeof ac[0] === "number" + ? ac[0] : emit_expr({ ...sc, rest: [ac[1]] }, ac[0], null, W64) + .ws[0]});`); + return emit_body(sc, ac[1], ty, [], dst); + } const ck = term_spine(x); if (ck.k === null) { return emit_put(sc, dst, emit_expr(sc, x, ty, dst?.lay ?? sc.seg.ret)); diff --git a/tests/run/nat_sum_loop.bend b/tests/run/nat_sum_loop.bend new file mode 100644 index 000000000..2010c0188 --- /dev/null +++ b/tests/run/nat_sum_loop.bend @@ -0,0 +1,122 @@ +# A def whose tail is Nat.add, or successors, of one call to itself runs as +# a loop on the C lane: the other operand is summed in the loop and added to +# whatever the def answers last, so the recursion holds no frame. Every +# count comes from the command line's length (1 in the harness), which no +# compiler sees. The shapes: the call on either side of Nat.add, under +# successors, beside a plain tail call and a tail call to another def, an +# operand that consumes a list while the call takes its tail, a sum that +# lands on 2^48-1, fifty thousand steps, and the same def under a fork. Two +# recursive calls under one Nat.add, and a call bound by a let first, stay +# recursions and must answer the same. +import Base + +def digits(+k: Nat, +n: Nat) -> Nat: + match k: + case 0n: + n + case 1n+p: + Nat.add(Nat.mod(n, 10n), digits(p, Nat.div(n, 10n))) + +def left(+n: Nat) -> Nat: + match n: + case 0n: + 7n + case 1n+p: + Nat.add(left(p), n) + +def succ(+n: Nat) -> Nat: + match n: + case 0n: + 0n + case 1n+p: + 3n+succ(p) + +def other(+n: Nat) -> Nat: + Nat.mul(n, 1000n) + +def mixed(+n: Nat, +m: Nat) -> Nat: + match n: + case 0n: + other(m) + case 1n+p: + match m: + case 0n: + mixed(p, 5n) + case 1n+q: + Nat.add(Nat.mul(n, m), mixed(p, q)) + +def lens(xss: List<&2, List<&2, Nat>>) -> Nat: + match xss: + case Nil{}: + 0n + case Con{h, t}: + Nat.add(List.length(&2, Nat, h), lens(t)) + +def rows(+n: Nat, acc: List<&2, List<&2, Nat>>) -> List<&2, List<&2, Nat>>: + match n: + case 0n: + acc + case 1n+p: + rows(p, Con{List.range(n), acc}) + +def big() -> Nat: + Nat.add(Nat.mul(16777215n, 16777216n), 16777215n) + +def edge(+n: Nat, +x: Nat) -> Nat: + match n: + case 0n: + x + case 1n+p: + Nat.add(x, edge(p, x)) + +def both(+n: Nat) -> Nat: + match n: + case 0n: + 1n + case 1n+p: + Nat.add(both(p), both(p)) + +def bound(+n: Nat) -> Nat: + match n: + case 0n: + 0n + case 1n+p: + r = bound(p) + Nat.add(n, r) + +def fork(+d: Nat, +n: Nat) -> Nat: + match d: + case 0n: + left(n) + case 1n+p: + a b = fork(p, n) left(Nat.add(n, d)) + Nat.add(a, b) + +def show(+one: Nat) -> String: + String.join([ + Nat.show(digits(Nat.mul(9n, one), Nat.mul(987654321n, one))), + Nat.show(left(Nat.mul(100n, one))), + Nat.show(succ(Nat.mul(100n, one))), + Nat.show(mixed(Nat.mul(40n, one), Nat.mul(9n, one))), + Nat.show(lens(rows(Nat.mul(50n, one), Nil{}))), + Nat.show(edge(Nat.mul(254n, one), Nat.div(big(), Nat.mul(255n, one)))), + Nat.show(left(Nat.mul(50000n, one))), + Nat.show(both(Nat.mul(12n, one))), + Nat.show(bound(Nat.mul(1000n, one))), + Nat.show(fork(Nat.mul(6n, one), Nat.mul(1000n, one)))], "\n") + +def main() -> IO(Unit): + do IO: + xs : List <- IO.args() + IO.print(show(List.length(&1, String, xs))) + +#|45 +#|5057 +#|300 +#|7930 +#|1275 +#|281474976710655 +#|1250025007 +#|4096 +#|500500 +#|3524605 diff --git a/tests/run/nat_sum_overflow.bend b/tests/run/nat_sum_overflow.bend new file mode 100644 index 000000000..03e7d4809 --- /dev/null +++ b/tests/run/nat_sum_overflow.bend @@ -0,0 +1,23 @@ +# A sum carried by a loop (nat_sum_loop) stops at the same wall as the +# recursion it replaces: 255 steps of (2^48-1) / 255 land on 2^48-1, and +# the step count here is one more. The count is scaled by the command +# line's length (1 in the harness), which no compiler sees. +import Base + +def big() -> Nat: + Nat.add(Nat.mul(16777215n, 16777216n), 16777215n) + +def edge(+n: Nat, +x: Nat) -> Nat: + match n: + case 0n: + x + case 1n+p: + Nat.add(x, edge(p, x)) + +def main() -> IO(Unit): + do IO: + xs : List <- IO.args() + IO.print(Nat.show(edge(Nat.mul(255n, List.length(&1, String, xs)), Nat.div(big(), 255n)))) + +#|bend: a Nat past the largest immediate 2^48-1 +#|exit 1 From 2707077e908f604656cf72660b732fbb89d57105 Mon Sep 17 00:00:00 2001 From: Nico Abril Date: Mon, 16 Nov 2026 18:20:12 +0100 Subject: [PATCH 2/3] perf(comp): a tail add of calls to itself carries its sum in a parameter A def that answers a Nat or a U32 and whose every call to itself, past its tail calls, is an operand of a tail add goes on in d~acc, a second def that takes the sum so far as its first parameter. The other operands join the sum, each call takes it in turn and answers it grown, and the last call is a tail call, so one call under the add is a loop and two or more keep every call but the last. The add may be spelled with nested adds, successors on either side, or a call bound by a let that is used once. d calls d~acc with 0. This replaces the loop-local sum of the previous commit (acc_of and its four emitter sites) with one rewrite on the checked terms in file_book, C lane only. Left as they are: F32, a def in a tail cycle with another def, a call behind !, a fork's calls, and a def with a call to itself anywhere else. tests/io/stack_fault_trap.bend xors the result of its self-call before the adds, so the recursion it needs to fault the stack stays one. tests/run/nat_sum_loop.bend asks for twenty thousand steps, which the JS lanes hold. Co-Authored-By: Claude Fable 5.2 --- bend2/comp.ts | 116 +++++++++++----- tests/io/stack_fault_trap.bend | 4 +- tests/run/nat_sum_loop.bend | 23 ++-- tests/run/sum_loop_calls.bend | 219 +++++++++++++++++++++++++++++++ tests/run/sum_loop_overflow.bend | 28 ++++ tests/run/sum_loop_shapes.bend | 180 +++++++++++++++++++++++++ 6 files changed, 523 insertions(+), 47 deletions(-) create mode 100644 tests/run/sum_loop_calls.bend create mode 100644 tests/run/sum_loop_overflow.bend create mode 100644 tests/run/sum_loop_shapes.bend diff --git a/bend2/comp.ts b/bend2/comp.ts index 545431783..be8ac8107 100644 --- a/bend2/comp.ts +++ b/bend2/comp.ts @@ -669,7 +669,7 @@ function ty_key(T: HTerm): string { } function tld_of(k: Name): Bend.TLD { - return FL.book.tlds[k]; + return FL.book.tlds[k] ?? FL.made[k]; } function ty_tag(t: HTerm | null, tags: string): boolean { @@ -1095,17 +1095,82 @@ function loop_of(k: Name): Name[] { return memo(FL.loops, k, () => (visit(k), FL.loops.get(k)!)); } -// A tail Nat.add, or successors, of a call to d: a flat d loops on that call -// and sums the other operand in acc. No partial sum of Nats passes the whole. -// A second call to d, in the other operand, keeps d from being flat. -function acc_of(d: Name, t: HTerm): [HTerm | number, HTerm] | null { - const s = term_strip(t); - const m = term_spine(s); - const [b, n] = s.$ === "Ctr" && s.k === "Succ" ? nat_peel(s) : [null, 0]; - const i = m.t.$ === "Ref" && m.t.k === "Nat.add" && intr_of(m.t.k) - ? m.args.findIndex((a) => term_spine(a).k === d) : -1; - return b !== null && term_spine(b).k === d ? [n, b] - : i < 0 ? null : [m.args[1 - i], m.args[i]]; +// A def that answers a Nat or a U32 and calls itself outside a tail goes on +// in d~acc, which takes the sum so far first, if every such call is an +// operand of a tail add: there, under successors, or bound by a let used +// once. The other operands join the sum, bound before the calls, each call +// takes it in turn (the last as a tail call), and any other answer is added +// to it: no part of a sum of Nats passes the whole, and U32 wraps. d calls +// d~acc with 0. A def in a tail cycle with another keeps its tail calls. +// loop_of opens d's body, so a let's probe is past every index term_lower +// gives. +function acc_def(d: Name): void { + const f = fun_of(d); + const { T } = tld_of(d) as Bend.Def; + const R = ty_adt(tele_fill(T, Array(f.n).fill(DUMMY))); + const op = R?.k + ".add"; + const w = d + "~acc"; + if (FL.js || !intr_of(op) || R!.k === "F32" || f.lays.length >= WIDE + || !term_any(f.h!, (s, tail) => !tail && term_spine(s).k === d) + || loop_of(d).length > 1) { + return; + } + const go = (t: HTerm, a: HTerm, env: Map): any => { + const s = term_force(t); + const on = (x: HTerm) => go(x, a, env); + if (s.$ === "Lam") { + return { ...s, f: (x: HTerm) => on(s.f(x)) }; + } + if (s.$ === "Let") { + const o = term_open(s); + const m = term_spine(s.v[0]); + const one = s.k.length === 1 && m.k === d && !m.b + && rest_use([o.b], o.ps[0]) === 1; + return { ...s, f: (xs: Of<"Var">[]) => go(s.f(xs), a, + one ? new Map(env).set(xs[0].i, m) : env) }; + } + if (s.$ === "Mat") { + return { ...s, h: on(s.h), m: on(s.m) }; + } + if (s.$ === "Ann") { + return { ...s, x: on(s.x) }; + } + if (s.$ === "Rwt") { + return { ...s, f: on(s.f) }; + } + if (s.$ === "Efq") { + return s; + } + const cs: Spine[] = []; + const flat = (x: HTerm): void => { + const y = term_strip(x); + const m = term_spine(y); + const [b, n] = y.$ === "Ctr" && y.k === "Succ" ? nat_peel(y) : [null, 0]; + const c = m.k === d && !m.b ? m : y.$ === "Var" && env.get(y.i); + if (b !== null) { + flat(b); + flat(Bend.Lit("Nat", n)); + } else if (m.t.$ === "Ref" && m.t.k === op) { + m.args.forEach(flat); + } else if (c) { + cs.push(c); + } else { + a = Bend.Ann(Bend.App(Bend.App(Bend.Ref(op), a), Bend.Ann(x, R!)), R!); + } + }; + flat(s); + return cs.length === 0 ? a : Bend.Let(["a"], [0], [Bend.Ann(a, R!)], + (xs: HTerm[]) => cs.reduce((a, m) => Bend.Ann(m.all.reduce((g, x) => + Bend.App(g, x), Bend.App(Bend.Ref(w), a)), R!), xs[0])); + }; + const e = Bend.term_lower(Bend.Lam("acc", 0, (a: HTerm) => + go(f.h!, a, new Map()))); + const v = Bend.term_higher(e); + if (!term_any(v, (s) => s.$ === "Ref" && s.k === d)) { + FL.made[w] = { $: "Def", n: f.n + 1, x: 0, v, e, + T: Bend.All(Bend.Many(), "acc", 0, R!, () => T) }; + f.h = term_eta(Bend.App(Bend.Ref(w), Bend.Lit(R!.k as "Nat", 0)), T, f.n); + } } function flat_of(k: Name): boolean { @@ -1161,7 +1226,7 @@ function file_new(book: Bend.Book, js: boolean) { srcs: new Map | null>(), loops: new Map(), flats: new Map(), - accs: new Set(), + made: Object.create(null) as Record, funs: new Map(), nodes: new Map(), lays: new Map(), @@ -1241,15 +1306,10 @@ function file_book(roots: Name[]): void { if (!done_live(tld)) { continue; } + acc_def(d); const deps = new Set(); let flat = true; - let acc: HTerm | null = null; term_any(fun_of(d).h!, (s, tail) => { - const ac = tail && !FL.js && fun_of(d).ret === W64 ? acc_of(d, s) : null; - if (ac) { - acc = term_strip(ac[1]); - FL.accs.add(d); - } if (s.$ === "Ref") { if (s.b) { FL.bangs.add(s.k); @@ -1264,8 +1324,7 @@ function file_book(roots: Name[]): void { deps.add(ck.k); } flat &&= !((s.$ === "Let" && s.k.length >= 2) - || (ck.k !== null && (ck.b - || (ck.k === d && !tail && term_strip(s) !== acc)))); + || (ck.k !== null && (ck.b || (ck.k === d && !tail)))); return false; }); FL.srcs.set(d, flat ? deps : null); @@ -2073,18 +2132,13 @@ function emit_each(sc: Scope, xs: HTerm[], ats: Lay[] = [], ...sc.rest] }, x, tys[i] ?? null, ats[i] ?? null)); } -function acc_on(sc: Scope): boolean { - return sc.seg.native && FL.accs.has(sc.seg.def); -} - function emit_put(sc: Scope, dst: Val | null, v: Val): void { bind_dead(sc, []); if (dst === null) { spare_flush(sc); } const ws = val_own(val_to(sc, v, dst?.lay ?? sc.seg.ret)); - file_push(sc, ...ws.map((w, j) => `${dst?.ws[j] ?? "r" + j} = ${ - acc_on(sc) ? `nat_chk(e, acc + ${w})` : w};`)); + file_push(sc, ...ws.map((w, j) => `${dst?.ws[j] ?? "r" + j} = ${w};`)); if (dst === null) { file_push(sc, `WL_RETN(${ws.length});`); } @@ -2130,7 +2184,6 @@ function emit_native(sc: Scope, k: Name): string { val_new(seg.ret.ks.map((_, j) => `o[${j}]`), seg.ret)); const body = [...seg_text([...seg.ks.flatMap((kd, i) => arr_q(kd) ? [`Term h${i} = r${i};`] : []), ...seg_take(seg), - ...FL.accs.has(k) ? ["u64 acc = 0;"] : [], seg.spin ? "WL_SPIN" : "for (;;) {"], 1), ...seg_text(seg.lines, 2), " break;", " }", " return 1;", "}"]; const text = body.join("\n"); @@ -2425,13 +2478,6 @@ function emit_body(sc: Scope, tm: HTerm, ty0: HTerm | null, args: Val[], return emit_body(sc, term_eta(x, ty!, 1), ty, args, dst); } sc = { ...sc, rest: [] }; - const ac = acc_on(sc) ? acc_of(sc.seg.def, x) : null; - if (ac) { - file_push(sc, `acc = nat_chk(e, acc + ${typeof ac[0] === "number" - ? ac[0] : emit_expr({ ...sc, rest: [ac[1]] }, ac[0], null, W64) - .ws[0]});`); - return emit_body(sc, ac[1], ty, [], dst); - } const ck = term_spine(x); if (ck.k === null) { return emit_put(sc, dst, emit_expr(sc, x, ty, dst?.lay ?? sc.seg.ret)); diff --git a/tests/io/stack_fault_trap.bend b/tests/io/stack_fault_trap.bend index f4afd10b2..d97c02887 100644 --- a/tests/io/stack_fault_trap.bend +++ b/tests/io/stack_fault_trap.bend @@ -13,6 +13,8 @@ # Nat is a native immediate) matched ahead of the self-call, and # 300M levels overrun the 2GB window into the guard page in under # a second, on whichever lane owns the deep child. +# The result of the self-call is xored before the adds: a tail sum of one +# self-call would run as a loop on the C lane and push no frame. # The JS walls join the numbered-error law at io_run: a cut there # is a nested host call, so the host stack throws RangeError long # before the machine's depth, and io_run's catch translates it into @@ -41,7 +43,7 @@ def deep(n, a, b, c, d): (a + b + c + d : U32) case 1n+p: x = deep(p, (a + 1 : U32), (b + 2 : U32), (c + 3 : U32), (d + 4 : U32)) - (x + a + b + c + d : U32) + (U32.xor(x, a) + b + c + d : U32) law run: for n: U32 diff --git a/tests/run/nat_sum_loop.bend b/tests/run/nat_sum_loop.bend index 2010c0188..060bda1f8 100644 --- a/tests/run/nat_sum_loop.bend +++ b/tests/run/nat_sum_loop.bend @@ -1,13 +1,14 @@ # A def whose tail is Nat.add, or successors, of one call to itself runs as -# a loop on the C lane: the other operand is summed in the loop and added to -# whatever the def answers last, so the recursion holds no frame. Every -# count comes from the command line's length (1 in the harness), which no -# compiler sees. The shapes: the call on either side of Nat.add, under -# successors, beside a plain tail call and a tail call to another def, an -# operand that consumes a list while the call takes its tail, a sum that -# lands on 2^48-1, fifty thousand steps, and the same def under a fork. Two -# recursive calls under one Nat.add, and a call bound by a let first, stay -# recursions and must answer the same. +# a loop on the C lane: the other operand joins a sum the loop carries, and +# whatever the def answers last is added to it, so the recursion holds no +# frame. Every count comes from the command line's length (1 in the +# harness), which no compiler sees. The shapes: the call on either side of +# Nat.add, under successors, beside a plain tail call and a tail call to +# another def, an operand that consumes a list while the call takes its +# tail, a sum that lands on 2^48-1, twenty thousand steps (the JS lanes +# hold about thirty thousand frames), and the same def under a fork. Two +# calls under one Nat.add (both) and a call bound by a let first (bound) +# loop too: sum_loop_calls and sum_loop_shapes hold the rest. import Base def digits(+k: Nat, +n: Nat) -> Nat: @@ -100,7 +101,7 @@ def show(+one: Nat) -> String: Nat.show(mixed(Nat.mul(40n, one), Nat.mul(9n, one))), Nat.show(lens(rows(Nat.mul(50n, one), Nil{}))), Nat.show(edge(Nat.mul(254n, one), Nat.div(big(), Nat.mul(255n, one)))), - Nat.show(left(Nat.mul(50000n, one))), + Nat.show(left(Nat.mul(20000n, one))), Nat.show(both(Nat.mul(12n, one))), Nat.show(bound(Nat.mul(1000n, one))), Nat.show(fork(Nat.mul(6n, one), Nat.mul(1000n, one)))], "\n") @@ -116,7 +117,7 @@ def main() -> IO(Unit): #|7930 #|1275 #|281474976710655 -#|1250025007 +#|200010007 #|4096 #|500500 #|3524605 diff --git a/tests/run/sum_loop_calls.bend b/tests/run/sum_loop_calls.bend new file mode 100644 index 000000000..80b910450 --- /dev/null +++ b/tests/run/sum_loop_calls.bend @@ -0,0 +1,219 @@ +# A def that adds two or more calls to itself in its tail keeps every call +# but the last, which becomes the loop: each call takes the sum so far as +# the first parameter of d~acc and answers it grown, so the sum crosses the +# calls that stay without a frame of its own (C lane). The spellings: the +# calls bound by lets and added in either order, calls inside nested adds +# and under successors, an operand that consumes a list beside them, three +# calls, U32.add past 2^32, erased parameters, a tree lent to two folds +# and then given to a third, a sum that lands on 2^48-1, the def under a +# fork with another def beside the sum, a tree twenty thousand nodes deep +# on either side, and an Array of closures called at its leaves. A bound +# call used twice keeps the def a recursion. Every count comes from the +# command line's length (1 in the harness), which no compiler sees. +import Base + +type Tree is Data: + Leaf{v: Nat} + Node{l: Tree, x: List<&2, Nat>, r: Tree} + +def build(+d: Nat, +k: Nat) -> Tree: + match d: + case 0n: + Leaf{k} + case 1n+p: + Node{build(p, Nat.mul(k, 2n)), List.range(Nat.mod(k, 5n)), build(p, Nat.add(Nat.mul(k, 2n), 1n))} + +def total(xs: List<&2, Nat>) -> Nat: + match xs: + case Nil{}: + 0n + case Con{h, t}: + Nat.add(h, total(t)) + +def fold(t: Tree) -> Nat: + match t: + case Leaf{v}: + v + case Node{l, x, r}: + Nat.add(total(x), Nat.add(fold(l), fold(r))) + +def flip(t: Tree) -> Nat: + match t: + case Leaf{v}: + v + case Node{l, x, r}: + Nat.add(flip(r), 1n+Nat.add(List.length(&2, Nat, x), flip(l))) + +def uses(+t: Tree) -> Nat: + Nat.add(fold(t), Nat.add(flip(t), fold(t))) + +def fib(+n: Nat) -> Nat: + match n: + case 0n: + 0n + case 1n+p: + match p: + case 0n: + 1n + case 1n+pp: + a = fib(p) + b = fib(pp) + Nat.add(a, b) + +def bif(+n: Nat) -> Nat: + match n: + case 0n: + 0n + case 1n+p: + match p: + case 0n: + 1n + case 1n+pp: + a = bif(p) + b = bif(pp) + Nat.add(b, a) + +def ufib(+n: Nat) -> U32: + match n: + case 0n: + 4000000000 + case 1n+p: + match p: + case 0n: + 300000001 + case 1n+pp: + U32.add(ufib(pp), U32.add(ufib(p), 7)) + +def third(+n: Nat) -> Nat: + match n: + case 0n: + 1n + case 1n+p: + match p: + case 0n: + 2n + case 1n+pp: + +a = third(p) + b = third(pp) + Nat.add(a, Nat.add(b, a)) + +def three(+n: Nat) -> Nat: + match n: + case 0n: + 1n + case 1n+p: + Nat.add(three(p), Nat.add(three(p), three(p))) + +type Rose<-A: Data> is Data: + Tip{} + Bin{l: Rose, v: A, r: Rose} + +def size(-A: Data, t: Rose) -> Nat: + match t: + case Tip{}: + 0n + case Bin{l, v, r}: + 1n+Nat.add(size(A, l), size(A, r)) + +def grow(+d: Nat) -> Rose: + match d: + case 0n: + Tip{} + case 1n+p: + Bin{grow(p), 7, grow(p)} + +def spine(+n: Nat, acc: Tree, right: Bool) -> Tree: + match n: + case 0n: + acc + case 1n+p: + match right: + case True{}: + spine(p, Node{Leaf{n}, Nil{}, acc}, True{}) + case False{}: + spine(p, Node{acc, Nil{}, Leaf{n}}, False{}) + +def t15(+d: Nat, +v: Nat) -> Nat: + match d: + case 0n: + v + case 1n+p: + Nat.add(v, Nat.add(t15(p, v), t15(p, v))) + +def big() -> Nat: + Nat.add(Nat.mul(16777215n, 16777216n), 16777215n) + +def psum(+d: Nat) -> Nat: + match d: + case 0n: + 1n + case 1n+p: + a b = psum(p) psum(p) + Nat.add(a, b) + +def beside(+n: Nat) -> Nat: + match n: + case 0n: + 0n + case 1n+p: + a b = psum(Nat.mod(n, 4n)) fib(Nat.mod(n, 9n)) + Nat.add(a, Nat.add(b, beside(p))) + +def forked(+d: Nat, +n: Nat) -> Nat: + match d: + case 0n: + fib(n) + case 1n+p: + a b = forked(p, n) fold(build(Nat.add(d, 3n), d)) + Nat.add(a, b) + +def cell(n: U32) -> Array<(U32 -> U32)>: + ALeaf{x => (x + n : U32)} + +def calls(a: Array<(U32 -> U32)>) -> U32: + match a: + case ALeaf{f}: + f(1) + case ANode{xs, ys}: + U32.add(calls(xs), calls(ys)) + +def show(+one: Nat) -> String: + String.join([ + Nat.show(fold(build(Nat.mul(10n, one), 1n))), + Nat.show(flip(build(Nat.mul(10n, one), 1n))), + Nat.show(uses(build(Nat.mul(8n, one), 3n))), + Nat.show(fib(Nat.mul(24n, one))), + Nat.show(bif(Nat.mul(24n, one))), + U32.show(ufib(Nat.mul(24n, one))), + Nat.show(third(Nat.mul(20n, one))), + Nat.show(three(Nat.mul(10n, one))), + Nat.show(size(U32, grow(Nat.mul(12n, one)))), + Nat.show(fold(spine(Nat.mul(20000n, one), Leaf{0n}, True{}))), + Nat.show(fold(spine(Nat.mul(20000n, one), Leaf{0n}, False{}))), + Nat.show(flip(spine(Nat.mul(20000n, one), Leaf{0n}, True{}))), + Nat.show(t15(Nat.mul(3n, one), Nat.div(big(), 15n))), + Nat.show(beside(Nat.mul(200n, one))), + Nat.show(forked(Nat.mul(5n, one), Nat.mul(18n, one))), + U32.show(calls(ANode{cell(41), cell(U32.from_nat(Nat.mul(6n, one)))}))], "\n") + +def main() -> IO(Unit): + do IO: + xs : List <- IO.args() + IO.print(show(List.length(&1, String, xs))) + +#|1574396 +#|1575421 +#|689529 +#|46368 +#|46368 +#|2914304144 +#|38613965 +#|59049 +#|4095 +#|200010000 +#|200010000 +#|200030000 +#|281474976710655 +#|1940 +#|454767 +#|49 diff --git a/tests/run/sum_loop_overflow.bend b/tests/run/sum_loop_overflow.bend new file mode 100644 index 000000000..4012d48f9 --- /dev/null +++ b/tests/run/sum_loop_overflow.bend @@ -0,0 +1,28 @@ +# A sum carried through two calls (sum_loop_calls) stops at the same wall as +# the recursion it replaces: fifteen equal parts of 2^48-1 over a tree of +# depth 3 land on the limit, and here the root adds one more. The loop meets +# the wall at a later add than the recursion would, with the same message. +# The depth and the extra one come from the command line's length (1 in the +# harness), which no compiler sees. +import Base + +def big() -> Nat: + Nat.add(Nat.mul(16777215n, 16777216n), 16777215n) + +def t15(+d: Nat, +v: Nat, +top: Nat) -> Nat: + match d: + case 0n: + v + case 1n+p: + Nat.add(Nat.add(v, top), Nat.add(t15(p, v, 0n), t15(p, v, 0n))) + +def run(+one: Nat) -> Nat: + t15(Nat.mul(3n, one), Nat.div(big(), 15n), one) + +def main() -> IO(Unit): + do IO: + xs : List <- IO.args() + IO.print(Nat.show(run(List.length(&1, String, xs)))) + +#|bend: a Nat past the largest immediate 2^48-1 +#|exit 1 diff --git a/tests/run/sum_loop_shapes.bend b/tests/run/sum_loop_shapes.bend new file mode 100644 index 000000000..94e9903c6 --- /dev/null +++ b/tests/run/sum_loop_shapes.bend @@ -0,0 +1,180 @@ +# A def that answers a Nat or a U32 and adds one call to itself in its tail +# runs as a loop on the C lane however the add is spelled: the call bound by +# a let first, adds inside adds, successors over an add and an add over +# successors, U32.add (which wraps: here past 2^32), and a def that also +# tail-calls a def that forks, or sums a def that recurses. The loop keeps +# the sum in a first parameter of a second def, d~acc, and the answer of +# every other arm is added to it. What must stay a recursion and answer the +# same: a bound call used twice, U32.sub (not associative), F32.add (the +# order changes the rounding: 64 ones under 1e8 are lost one at a time, and +# kept if summed first), a call behind ! and a call in a closure. An arm +# that cannot run (it holds a value of the empty type) stays as it is. Every +# count comes from the command line's length (1 in the harness), which no +# compiler sees. +import Base + +def bound(+n: Nat) -> Nat: + match n: + case 0n: + 0n + case 1n+p: + r = bound(p) + Nat.add(n, r) + +def nest(+n: Nat) -> Nat: + match n: + case 0n: + 3n + case 1n+p: + Nat.add(1n, Nat.add(Nat.mul(n, 2n), nest(p))) + +def succs(+n: Nat) -> Nat: + match n: + case 0n: + 0n + case 1n+p: + 2n+Nat.add(n, 1n+succs(p)) + +def usum(+n: Nat, +k: U32) -> U32: + match n: + case 0n: + 7 + case 1n+p: + U32.add(k, usum(p, U32.mul(k, 3))) + +def ulet(+n: Nat, +k: U32) -> U32: + match n: + case 0n: + k + case 1n+p: + r = ulet(p, U32.add(k, 1)) + U32.add(U32.add(r, k), 4000000000) + +def psum(+d: Nat) -> Nat: + match d: + case 0n: + 1n + case 1n+p: + a b = psum(p) psum(p) + Nat.add(a, b) + +def tofork(+n: Nat, +d: Nat) -> Nat: + match n: + case 0n: + psum(d) + case 1n+p: + Nat.add(n, tofork(p, d)) + +def slow(+n: Nat) -> Nat: + match n: + case 0n: + 1n + case 1n+p: + Nat.mod(Nat.mul(3n, slow(p)), 1000003n) + +def over(+n: Nat) -> Nat: + match n: + case 0n: + 0n + case 1n+p: + Nat.add(slow(Nat.mod(n, 7n)), over(p)) + +def shared(+n: Nat, +xs: List<&2, Nat>) -> Nat: + match n: + case 0n: + List.length(&2, Nat, xs) + case 1n+p: + Nat.add(List.length(&2, Nat, xs), shared(p, Con{n, xs})) + +def twice(+n: Nat) -> U32: + match n: + case 0n: + 3 + case 1n+p: + +r = twice(p) + U32.add(r, U32.add(r, 1)) + +def down(+n: Nat, +k: U32) -> U32: + match n: + case 0n: + k + case 1n+p: + U32.sub(k, down(p, U32.add(k, 3))) + +def fsum(+n: Nat, x: F32) -> F32: + match n: + case 0n: + x + case 1n+p: + F32.add(1.0, fsum(p, x)) + +def banged(+n: Nat) -> Nat: + match n: + case 0n: + 0n + case 1n+p: + Nat.add(n, banged!(p)) + +def app(f: Nat -> Nat, x: Nat) -> Nat: + f(x) + +def clo(+n: Nat) -> Nat: + match n: + case 0n: + 0n + case 1n+p: + app(y => Nat.add(y, clo(p)), n) + +type Opt is Data: + No{e: Empty} + Yes{v: Nat} + +def absurd(+n: Nat, +o: Opt) -> Nat: + match n: + case 0n: + match o: + case No{e}: + match e: + case Yes{v}: + v + case 1n+p: + Nat.add(n, absurd(p, o)) + +def show(+one: Nat) -> String: + String.join([ + Nat.show(bound(Nat.mul(1000n, one))), + Nat.show(nest(Nat.mul(1000n, one))), + Nat.show(succs(Nat.mul(1000n, one))), + U32.show(usum(Nat.mul(40n, one), 5)), + U32.show(ulet(Nat.mul(1000n, one), 9)), + Nat.show(tofork(Nat.mul(100n, one), Nat.mul(5n, one))), + Nat.show(over(Nat.mul(500n, one))), + Nat.show(shared(Nat.mul(300n, one), [7n, 8n])), + Nat.show(bound(Nat.mul(20000n, one))), + U32.show(twice(Nat.mul(40n, one))), + U32.show(down(Nat.mul(101n, one), 10)), + F32.show(fsum(Nat.mul(64n, one), 100000000.0)), + Nat.show(banged(Nat.mul(30n, one))), + Nat.show(clo(Nat.mul(300n, one))), + Nat.show(absurd(Nat.mul(1000n, one), Yes{7n}))], "\n") + +def main() -> IO(Unit): + do IO: + xs : List <- IO.args() + IO.print(show(List.length(&1, String, xs))) + +#|500500 +#|1002003 +#|503500 +#|1724892247 +#|1385956933 +#|5082 +#|77642 +#|45752 +#|200010000 +#|4294967295 +#|4294967143 +#|100000000 +#|465 +#|45150 +#|500507 From 81ca87183a59c3ca63882a6a984780f7e28bda30 Mon Sep 17 00:00:00 2001 From: Nico Abril Date: Tue, 17 Nov 2026 19:41:41 +0100 Subject: [PATCH 3/3] perf(comp): a sum loop adds no literal 0: an arm that answers 0 answers the sum as it stands acc_def turned an arm that answers 0n into Nat.add(acc, 0n), which the C lane tests against 2^48 - 1 although acc is a Nat already (and for U32 an add of 0). Such an arm now answers the sum itself. Instructions on the koru kernels with the open drafts merged (opt/integration): coins 459.0M to 429.5M, fib 399.3M to 387.9M. Of the 17 benches only histogram's C changes (two lines), same output. tests/run/sum_loop_zero.bend: one and two calls, an arm that answers another literal, a computed 0, U32, and a sum that lands on 2^48 - 1 before the arm that answers 0. comp.ts is 67,091 ttok. Co-Authored-By: Claude Fable 5.2 --- bend2/comp.ts | 4 +- tests/run/sum_loop_zero.bend | 72 ++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 tests/run/sum_loop_zero.bend diff --git a/bend2/comp.ts b/bend2/comp.ts index be8ac8107..a42ed0177 100644 --- a/bend2/comp.ts +++ b/bend2/comp.ts @@ -1154,7 +1154,9 @@ function acc_def(d: Name): void { m.args.forEach(flat); } else if (c) { cs.push(c); - } else { + } else if (!term_const(y) + || (Bend.u32_from_term(y) ?? nat_peel(y)[1]) !== 0) { + // a literal 0 adds nothing: the sum goes on as it is, untested a = Bend.Ann(Bend.App(Bend.App(Bend.Ref(op), a), Bend.Ann(x, R!)), R!); } }; diff --git a/tests/run/sum_loop_zero.bend b/tests/run/sum_loop_zero.bend new file mode 100644 index 000000000..fda5cfb58 --- /dev/null +++ b/tests/run/sum_loop_zero.bend @@ -0,0 +1,72 @@ +# An arm of a summing def that answers a literal 0 adds nothing: the sum +# goes on as it stands (C lane), with no add and no test against the Nat +# limit. One call and two calls under the add, an arm that answers another +# literal, an arm whose 0 is computed, U32.add, and a sum that lands on +# 2^48-1 before the arm that answers 0. Every count comes from the command +# line's length (1 in the harness), which no compiler sees. +import Base + +def up(+n: Nat) -> Nat: + match n: + case 0n: + 0n + case 1n+p: + Nat.add(n, up(p)) + +def fibz(+n: Nat) -> Nat: + match n: + case 0n: + 0n + case 1n+p: + match p: + case 0n: + 1n + case 1n+q: + Nat.add(fibz(p), fibz(q)) + +def five(+n: Nat) -> Nat: + match n: + case 0n: + 5n + case 1n+p: + Nat.add(n, five(p)) + +def calc(+n: Nat, +k: Nat) -> Nat: + match n: + case 0n: + Nat.sub(k, k) + case 1n+p: + Nat.add(k, calc(p, k)) + +def wrap(+n: Nat, +x: U32) -> U32: + match n: + case 0n: + 0 + case 1n+p: + U32.add(x, wrap(p, x)) + +def edge(+n: Nat, +big: Nat) -> Nat: + match n: + case 0n: + 0n + case 1n+p: + Nat.add(big, edge(p, big)) + +def main() -> IO(Unit): + do IO: + args : List <- IO.args() + +k : Nat = List.length(&1, String, args) + IO.print(Nat.show(up(Nat.mul(k, 1000n)))) + IO.print(Nat.show(fibz(Nat.add(k, 19n)))) + IO.print(Nat.show(five(Nat.mul(k, 10n)))) + IO.print(Nat.show(calc(Nat.mul(k, 7n), 6n))) + IO.print(U32.show(wrap(Nat.mul(k, 3n), 4000000000))) + # three times a third of 2^48-1, which is 5592405 * 16777217 + IO.print(Nat.show(edge(Nat.mul(k, 3n), Nat.mul(Nat.mul(k, 5592405n), 16777217n)))) + +#|500500 +#|6765 +#|60 +#|42 +#|3410065408 +#|281474976710655