From c55493148f53d9fa008e571c102aabd8e392e72f Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Mon, 30 Nov 2026 10:56:31 +0000 Subject: [PATCH] Share the cleanup of many live bindings across throw sites (#4686) --- .../src/backend/llvm/emit-function.ts | 17 ++ .../compiler/src/backend/llvm/emitter.test.ts | 51 ++++++ packages/compiler/src/backend/llvm/emitter.ts | 123 ++++++++++++-- .../tests/corpus/wide-binding-unwind.ts.json | 6 + tests/corpus/wide-binding-unwind.ts | 151 ++++++++++++++++++ .../corpus-costs/wide-binding-unwind.ts.json | 1 + 6 files changed, 334 insertions(+), 15 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/wide-binding-unwind.ts.json create mode 100644 tests/corpus/wide-binding-unwind.ts create mode 100644 tests/harness/corpus-costs/wide-binding-unwind.ts.json diff --git a/packages/compiler/src/backend/llvm/emit-function.ts b/packages/compiler/src/backend/llvm/emit-function.ts index cb799ca769..7d9be4e00d 100644 --- a/packages/compiler/src/backend/llvm/emit-function.ts +++ b/packages/compiler/src/backend/llvm/emit-function.ts @@ -127,6 +127,9 @@ export function emitFunction(emitter: LlEmitter, fn: IrFunction): string { emitter.frames = []; emitter.scopes = []; emitter.unwindCleanups.clear(); + emitter.unwindChainBlocks.length = 0; + emitter.unwindScopeChains.clear(); + emitter.unwindTerminators.clear(); emitter.unwindReleases.length = 0; emitter.unwindReleaseLabels.clear(); emitter.jumpTargets = []; @@ -816,6 +819,20 @@ export function emitFunction(emitter: LlEmitter, fn: IrFunction): string { emitter.releaseScope(cleanup.entries); B.terminate(cleanup.terminator); } + // The many-binding cleanup chain ends each block in the block it + // continues to; LLVM would otherwise sink the blocks' release calls into + // shared successors and choose each operand with a phi. + B.unmergedCalls = true; + for (const block of emitter.unwindChainBlocks) { + B.startBlock(block.label); + emitter.releaseScope(block.entries); + B.br(block.next); + } + B.unmergedCalls = false; + for (const [terminator, label] of emitter.unwindTerminators) { + B.startBlock(label); + B.terminate(terminator); + } if (emitter.usesLandingPads && emitter.currentUnwindAbi) B.entryAllocas.push(`${UNWIND_SLOT} = alloca { ptr, i32 }`); diff --git a/packages/compiler/src/backend/llvm/emitter.test.ts b/packages/compiler/src/backend/llvm/emitter.test.ts index 6f914385cf..49ad2b0c49 100644 --- a/packages/compiler/src/backend/llvm/emitter.test.ts +++ b/packages/compiler/src/backend/llvm/emitter.test.ts @@ -8,6 +8,7 @@ import { VOID, type IrExpr, type IrFunction, + type IrLocal, type IrModule, type IrStmt, type IrType, @@ -262,6 +263,56 @@ test("a statement's throw sites share the releases of the values it holds", () = expect(growth).toBeLessThan(3 * (stringReleases(medium!) - stringReleases(small!))); }); +/** `n` owned string bindings, each followed by a may-throw call: every call + * site sees one more live binding than the previous site, the shape of a + * factory that declares a binding between two concatenations. */ +function wideModule(n: number): IrModule { + const module = moduleFor([]); + const work = module.functions[1]!; + const locals: IrLocal[] = []; + const body: IrStmt[] = []; + for (let i = 0; i < n; i++) { + locals.push({ id: `w${i}`, name: `w${i}`, type: STRING, mutable: true }); + const owned: IrExpr = { + kind: "strConcat", + left: literal("x"), + right: literal("y"), + type: STRING, + loc, + }; + body.push({ kind: "varDecl", localId: `w${i}`, init: owned, loc }); + body.push(call()); + } + work.locals = [...work.locals, ...locals]; + // The param rebinds moduleFor appends stay: they make the parameters owned. + work.body = [...body, ...work.body]; + return module; +} + +test("throw sites with many live bindings release from a shared chain", () => { + // Few live bindings keep one cleanup block per site. + const few = workBody(emitLlvmModule(wideModule(8))); + expect(few).not.toMatch(/^exc\.release\d+:$/m); + const releases = (n: number) => stringReleases(workBody(emitLlvmModule(wideModule(n)))); + // Each site adds one binding and continues into the previous site's + // releases: the calls grow with the bindings, not with their square. + const small = releases(100); + const medium = releases(200); + const large = releases(400); + expect(medium - small).toBeGreaterThan(0); + expect(large - medium).toBeLessThan(2.5 * (medium - small)); + // Whichever statement values each site also holds add a few per site; the + // bindings alone would be one per site. The old emission wrote the whole + // live list at every site: quadratic, about 20,000 calls at 200 bindings. + expect(large).toBeLessThan(6 * 400); + // The chain keeps every release in its own block with the no-merge mark. + const blocks = [ + ...workBody(emitLlvmModule(wideModule(200))).matchAll(/^exc\.release\d+:\n((?: [^\n]*\n)+)/gm), + ]; + expect(blocks.length).toBeGreaterThan(0); + for (const block of blocks) expect(block[1]!).toMatch(/br label %exc\.(?:release|cleanup)\d+\n$/); +}); + test("detached exit defines the runtime opt-in symbol only when requested", () => { const module = moduleFor([call()]); const plain = emitLlvmModule(module); diff --git a/packages/compiler/src/backend/llvm/emitter.ts b/packages/compiler/src/backend/llvm/emitter.ts index 1667717268..b66d01dcd3 100644 --- a/packages/compiler/src/backend/llvm/emitter.ts +++ b/packages/compiler/src/backend/llvm/emitter.ts @@ -2194,11 +2194,29 @@ export class LlEmitter { /** Scope slots dominate every throw site. Share their exceptional cleanup * for identical live bindings and handlers; statement temporaries stay at * their own throw sites because their SSA values are path-dependent, - * unless a site holds many of them (unwindReleases). */ + * unless a site holds many of them (unwindReleases). A live list longer + * than UNWIND_CHAIN_MIN_VALUES bindings releases from a shared chain + * instead (unwindChainBlocks): a throw site adds only a block for the bindings + * declared since the previous site rather than one full release sequence + * per site. */ readonly unwindCleanups = new Map< string, { label: string; entries: LlScopeEntry[]; terminator: string } >(); + /** The blocks of the many-binding cleanup chain (emitUnwind), in creation + * order: each releases its bindings in order and branches to `next`. */ + readonly unwindChainBlocks: { label: string; entries: LlScopeEntry[]; next: string }[] = []; + /** A scope's chain blocks by the block they continue to: each entry + * releases the scope's first `count` bindings and then continues. A throw + * site whose scope has grown since releases only the new bindings and + * continues into the previous chain. */ + readonly unwindScopeChains = new Map< + LlScopeEntry[], + Map + >(); + /** The block ending a chain (the handler branch or the dummy return), by + * its terminator text. */ + readonly unwindTerminators = new Map(); /** The shared release blocks of throw sites that hold more than * UNWIND_CHAIN_MIN_VALUES statement values (emitUnwind), in creation * order: each releases one value and branches to `next`. */ @@ -5340,15 +5358,16 @@ export class LlEmitter { ? "ret i1 false" : "ret ptr null"; } - // Copy the entries now: later declarations extend these lexical scopes. - // Release order and the handler are part of the shared block's identity. + // Copy the scopes now: later declarations extend these lexical scopes. + // Their bindings release in releaseScope's order: each scope's bindings + // in declaration order, its arena list after them. + const liveScopes: LlScopeEntry[][] = []; const entries: LlScopeEntry[] = []; - let key = terminator; for (let i = this.scopes.length - 1; i >= scopeDepth; i--) { - for (const entry of this.scopes[i]!) { - entries.push(entry); - key += `\0${entry.slot}\0${entry.boxed ? "@scr_box_release" : releaseSym(this.shapeHost, entry.type)}`; - } + const scope = this.scopes[i]!; + liveScopes.push(scope); + for (const entry of scope) if (entry.arena !== true) entries.push(entry); + for (const entry of scope) if (entry.arena === true) entries.push(entry); } if (entries.length === 0 && !chained) { if ( @@ -5364,14 +5383,88 @@ export class LlEmitter { this.B.terminate(terminator); return; } - let cleanup = this.unwindCleanups.get(key); - if (!cleanup) { - cleanup = { label: this.B.newLabel("exc.cleanup"), entries, terminator }; - this.unwindCleanups.set(key, cleanup); + let cleanup: string; + const chainedScopes = + entries.length > UNWIND_CHAIN_MIN_VALUES && !entries.some((entry) => entry.arena === true); + if (!chainedScopes) { + // Few live bindings: one block releases them all and ends in the + // handler (or the dummy return). Release order and the handler are + // part of the block's identity. + let key = terminator; + for (const entry of entries) + key += `\0${entry.slot}\0${entry.boxed ? "@scr_box_release" : releaseSym(this.shapeHost, entry.type)}`; + let shared = this.unwindCleanups.get(key); + if (!shared) { + shared = { label: this.B.newLabel("exc.cleanup"), entries, terminator }; + this.unwindCleanups.set(key, shared); + } + cleanup = shared.label; + } else { + // Many live bindings: release from the shared chain, so a site adds + // only the bindings declared since the previous site rather than one + // full release sequence per site. + cleanup = this.unwindScopeChain(liveScopes, 0, terminator); } - // The shared blocks end in the cleanup, which is then the scope's - // releases (none for a function without bindings) and the terminator. - this.B.br(chained ? this.unwindReleaseChain(frameDepth, cleanup.label) : cleanup.label); + this.B.br(chained ? this.unwindReleaseChain(frameDepth, cleanup) : cleanup); + } + + /** The head of the shared blocks that release the live scopes from + * `depth` outward, innermost first, and then end with `terminator`. + * + * A scope's bindings live in its scope array, which only ever gains + * entries at the end, so the release of an earlier throw site is a prefix + * of a later site's. Each block releases the bindings a site added since + * the last block at that scope and continues into the previous chain; a + * function that declares a binding between every two throw sites emits + * one block per site instead of one full release sequence per site. + * Scopes with arena lists keep the single-block cleanup (emitUnwind): + * their lists drop after all the scope's bindings, which a prefix chain + * cannot order across sites. */ + private unwindScopeChain( + scopes: readonly LlScopeEntry[][], + depth: number, + terminator: string, + ): string { + const next = + depth + 1 < scopes.length + ? this.unwindScopeChain(scopes, depth + 1, terminator) + : this.unwindTerminator(terminator); + const scope = scopes[depth]!; + if (scope.length === 0) return next; + let byNext = this.unwindScopeChains.get(scope); + if (byNext === undefined) { + byNext = new Map(); + this.unwindScopeChains.set(scope, byNext); + } + let chains = byNext.get(next); + if (chains === undefined) { + chains = []; + byNext.set(next, chains); + } + let previous: { count: number; label: string } | undefined; + for (const chain of chains) + if (chain.count <= scope.length && (previous === undefined || chain.count > previous.count)) + previous = chain; + if (previous !== undefined && previous.count === scope.length) return previous.label; + const label = this.B.newLabel("exc.release"); + this.unwindChainBlocks.push({ + label, + entries: scope.slice(previous?.count ?? 0), + next: previous?.label ?? next, + }); + chains.push({ count: scope.length, label }); + return label; + } + + /** The label of the block that only ends the chain: the handler branch or + * the dummy return, shared by every chain with the same terminator. */ + private unwindTerminator(terminator: string): string { + let label = this.unwindTerminators.get(terminator); + if (label === undefined) { + label = this.B.newLabel("exc.cleanup"); + this.unwindTerminators.set(terminator, label); + } + return label; } /** The label of the shared blocks that release the statement frames from diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/wide-binding-unwind.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/wide-binding-unwind.ts.json new file mode 100644 index 0000000000..fab414ddd8 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/wide-binding-unwind.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/wide-binding-unwind.ts" + ], + "diags": [] +} diff --git a/tests/corpus/wide-binding-unwind.ts b/tests/corpus/wide-binding-unwind.ts new file mode 100644 index 0000000000..c3f2eef153 --- /dev/null +++ b/tests/corpus/wide-binding-unwind.ts @@ -0,0 +1,151 @@ +/* Unwinding a scope that holds many owned bindings: when a call in a later + * initializer throws, the shared cleanup chain releases every live binding + * exactly once. Node is the oracle for the printed values and error + * messages; the sanitized lane runs ASan and the RC audit over the same + * releases. */ +const log: string[] = []; + +function take(n: number): string { + if (n === 37 || n === 112) throw new Error("boom " + n); + log.push("v" + n); + return "v" + n; +} + +function wide(limit: number): number { + let a0 = take(limit + 0); + let a1 = take(limit + 1); + let a2 = take(limit + 2); + let a3 = take(limit + 3); + let a4 = take(limit + 4); + let a5 = take(limit + 5); + let a6 = take(limit + 6); + let a7 = take(limit + 7); + let a8 = take(limit + 8); + let a9 = take(limit + 9); + let a10 = take(limit + 10); + let a11 = take(limit + 11); + let a12 = take(limit + 12); + let a13 = take(limit + 13); + let a14 = take(limit + 14); + let a15 = take(limit + 15); + let a16 = take(limit + 16); + let a17 = take(limit + 17); + let a18 = take(limit + 18); + let a19 = take(limit + 19); + let a20 = take(limit + 20); + let a21 = take(limit + 21); + let a22 = take(limit + 22); + let a23 = take(limit + 23); + let a24 = take(limit + 24); + let a25 = take(limit + 25); + let a26 = take(limit + 26); + let a27 = take(limit + 27); + let a28 = take(limit + 28); + let a29 = take(limit + 29); + let a30 = take(limit + 30); + let a31 = take(limit + 31); + let a32 = take(limit + 32); + let a33 = take(limit + 33); + let a34 = take(limit + 34); + let a35 = take(limit + 35); + let a36 = take(limit + 36); + let a37 = take(limit + 37); + let a38 = take(limit + 38); + let a39 = take(limit + 39); + return a0.length + a39.length + (a37 === a37 ? 0 : 1) + (a38 === a38 ? 0 : 1); +} + +function handled(limit: number): number { + try { + let h0 = take(limit + 0); + let h1 = take(limit + 1); + let h2 = take(limit + 2); + let h3 = take(limit + 3); + let h4 = take(limit + 4); + let h5 = take(limit + 5); + let h6 = take(limit + 6); + let h7 = take(limit + 7); + let h8 = take(limit + 8); + let h9 = take(limit + 9); + let h10 = take(limit + 10); + let h11 = take(limit + 11); + let h12 = take(limit + 12); + let h13 = take(limit + 13); + let h14 = take(limit + 14); + let h15 = take(limit + 15); + let h16 = take(limit + 16); + let h17 = take(limit + 17); + let h18 = take(limit + 18); + let h19 = take(limit + 19); + let h20 = take(limit + 20); + let h21 = take(limit + 21); + let h22 = take(limit + 22); + let h23 = take(limit + 23); + let h24 = take(limit + 24); + let h25 = take(limit + 25); + let h26 = take(limit + 26); + let h27 = take(limit + 27); + let h28 = take(limit + 28); + let h29 = take(limit + 29); + let h30 = take(limit + 30); + let h31 = take(limit + 31); + let h32 = take(limit + 32); + let h33 = take(limit + 33); + let h34 = take(limit + 34); + let h35 = take(limit + 35); + let h36 = take(limit + 36); + let h37 = take(limit + 37); + let h38 = take(limit + 38); + let h39 = take(limit + 39); + return h0.length + h39.length + (h37 === h37 ? 0 : 1) + (h38 === h38 ? 0 : 1); + } catch (e) { + return -(e as Error).message.length; + } +} + +function nested(limit: number): number { + let outer = take(limit + 0); + if (outer.length > 1) { + let inner0 = take(limit + 37); + let inner1 = take(limit + 1); + return outer.length + inner0.length + inner1.length; + } + return outer.length; +} + +function withFinally(limit: number): string { + let head = take(limit + 0); + try { + const body = take(limit + 112); + return head + ":" + body; + } finally { + log.push("finally"); + } +} + +console.log("wide ok", wide(200)); +try { + console.log("wide threw", wide(0)); +} catch (e) { + console.log("wide threw", (e as Error).message); +} +console.log("log", log.join(",")); +log.length = 0; +console.log("handled", handled(200), handled(0), handled(100)); +console.log("log", log.join(",")); +log.length = 0; +console.log("nested ok", nested(200)); +try { + console.log("nested threw", nested(0)); +} catch (e) { + console.log("nested threw", (e as Error).message); +} +console.log("log", log.join(",")); +log.length = 0; +try { + withFinally(0); +} catch (e) { + console.log("finally threw", (e as Error).message); +} +console.log("finally ok", withFinally(200)); +console.log("log", log.join(",")); diff --git a/tests/harness/corpus-costs/wide-binding-unwind.ts.json b/tests/harness/corpus-costs/wide-binding-unwind.ts.json new file mode 100644 index 0000000000..614770a44b --- /dev/null +++ b/tests/harness/corpus-costs/wide-binding-unwind.ts.json @@ -0,0 +1 @@ +{ "plain": 2100, "san": 28600 }