From be0056a7023d8ee56be34ad45a247a9cdee72c19 Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Thu, 3 Dec 2026 11:39:38 +0000 Subject: [PATCH] Inline small closures called from sibling closures (#4808) --- native/llvm-codegen/src/partition.cpp | 8 +++ .../src/backend/llvm/closure-inlining.test.ts | 51 +++++++++++++++++++ .../src/backend/llvm/emit-function.ts | 13 +++++ 3 files changed, 72 insertions(+) create mode 100644 packages/compiler/src/backend/llvm/closure-inlining.test.ts diff --git a/native/llvm-codegen/src/partition.cpp b/native/llvm-codegen/src/partition.cpp index 31413591e8..26fb42a45d 100644 --- a/native/llvm-codegen/src/partition.cpp +++ b/native/llvm-codegen/src/partition.cpp @@ -829,6 +829,14 @@ std::optional partitionProgramText(StringRef Text, (S.Kind == SymbolKind::Function ? std::binary_search(S.Calls.begin(), S.Calls.end(), Ref) : S.Constant)); + } else if (S.Kind == SymbolKind::Function && Symbols[Ref].Kind == SymbolKind::Function && + Symbols[Ref].Header.contains("alwaysinline") && + std::binary_search(S.Calls.begin(), S.Calls.end(), Ref)) { + // A later caller's direct call makes an always-inlined definition a + // candidate of the partition it already follows: a factory takes the + // closure body's address, and the sibling closure that calls it is + // the one that can inline it. + MayFollow[Ref] = 1; } else { Referrer[Ref] = Shared; } diff --git a/packages/compiler/src/backend/llvm/closure-inlining.test.ts b/packages/compiler/src/backend/llvm/closure-inlining.test.ts new file mode 100644 index 0000000000..74d7c8634a --- /dev/null +++ b/packages/compiler/src/backend/llvm/closure-inlining.test.ts @@ -0,0 +1,51 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "vitest"; +import { compile, deserializeModule } from "../../index.js"; +import { emitLlvmModule } from "./emitter.js"; + +async function llvmFor(source: string): Promise { + const dir = await mkdtemp(join(tmpdir(), "scriptc-closure-inlining-")); + try { + const entry = join(dir, "main.ts"), + output = join(dir, "main.ir.json"); + await writeFile(entry, source); + const result = await compile(entry, { outDir: dir, outPath: output, outputKind: "ir" }); + if (!result.ok) + throw new Error(result.diagnostics.map((item) => `${item.code}: ${item.message}`).join("\n")); + return emitLlvmModule(deserializeModule(await readFile(output, "utf8"))); + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + +test("a small lifted closure body is marked alwaysinline", async () => { + const ir = await llvmFor(` +function make() { + let n = 0 + function inc() { + n = n + 1 + } + inc() + return inc +} +make()() +`); + expect(ir).toMatch(/define internal \S+ @sc_\S+\(ptr %sc_env[^\n]*alwaysinline #0 \{/); +}); + +test("a lifted closure body above the inline size keeps the cost model's decision", async () => { + const body = Array.from({ length: 140 }, () => " n = n + 1").join("\n"); + const ir = await llvmFor(` +function make() { + let n = 0 + function big() { +${body} + } + return big +} +make()() +`); + expect(ir).not.toMatch(/define internal \S+ @sc_\S+\(ptr %sc_env[^\n]*alwaysinline #0 \{/); +}); diff --git a/packages/compiler/src/backend/llvm/emit-function.ts b/packages/compiler/src/backend/llvm/emit-function.ts index 7d9be4e00d..6352a29976 100644 --- a/packages/compiler/src/backend/llvm/emit-function.ts +++ b/packages/compiler/src/backend/llvm/emit-function.ts @@ -893,6 +893,19 @@ export function emitFunction(emitter: LlEmitter, fn: IrFunction): string { // the function had before the version existed. else if (versionedFunctions(emitter).has(fn.name)) attrs = `noinline ${attrs}`; if (fn.name.startsWith(RESULT_ENTRY_PREFIX)) attrs = `inlinehint ${attrs}`; + // A small closure body is inlined at every direct sibling call: the + // address the factory stores keeps the partitioner from following it + // otherwise, and the call is the only dispatch a known callee pays. + if ( + !unoptimized && + emitter.debug === null && + !attrs.includes("noinline") && + fn.captures !== undefined && + !fn.async && + !fn.generator && + (emitter.nodeIndex.nodeCount(fn) ?? Infinity) <= 120 + ) + attrs = `alwaysinline ${attrs}`; if (unoptimized && attrs === FN_ATTRS) attrs = `noinline optnone ${attrs}`; const debug = emitter.debugScope === null ? "" : ` !dbg ${emitter.debugScope}`; const symbol = borrowed ? mangleBorrowedFunction(fn.name) : mangleFunction(fn.name);