Skip to content

Front-end, emitter and build sweep: Laravel lowering 128 s -> 25 s, staged IR -42%, peak RSS -30%, bin/build 12 -> 1.5 min - #510

Merged
blacktrs merged 18 commits into
mainfrom
perf/front-end-sweep
Oct 28, 2026
Merged

blacktrs merged 18 commits into
mainfrom
perf/front-end-sweep

Conversation

@blacktrs

Copy link
Copy Markdown
Contributor

What

A compile-time and memory sweep of the front end, the emitter and the build of the compiler itself, found by profiling a Laravel application (4 652 files, 132 k functions) and examples/symfony-app. Every fix removes a linear scan inside a loop, an avoidable copy of a multi-hundred-MB string, or a block of IR that every later phase has to write, split and parse.

Laravel, -O 0, up to the assembly step (numbers are from my runs on a loaded machine, ±10%):

before after this PR
LowerFromAst 128 s ~25 s
InferTypes (one full run) 48-72 s 8-36 s
Monomorphize 99 s ~20 s
EmitLlvm ~147 s ~107 s
staged IR 4.44 GB 2.56 GB (-42%)
compiler peak RSS 6.5 GB 4.5 GB
bin/build (compiler self-build) ~12 min, ~7.7 GB tree peak ~1.5 min, ~4 GB

Changes, by area

Lowering / inference (time)

  • LowerFromAst::canonFunctionName rebuilt its case-insensitive function index on every declared function (O(N²), 99 s on Laravel): the index is now updated on declare.
  • variadicMethodParams and LowerReify::findFunctionDef walked every class / function per name: indexed once.
  • InferTypes::scanCtorPropContainers walked all functions per class (5.5 billion steps) and anyDeclarerFn copied every function name per method: both indexed once per run.

Emitter (time)

  • emitDynFnCall filtered 130 k signatures per dynamic-call site, three times: candidate sets are shared per arity.
  • classCensusIndex memoized; irIsClosed scans with PCRE instead of a per-byte loop.
  • HoistAllocas::runFast slices a function body instead of walking lines (about 2x on the in-memory path) and searches only inside the body; SplitModule collects @symbol references per body with one PCRE pass (88 s -> 69 s).

IR size

  • A dynamic-method site $o->$m(...$pack) handed every by-ref / variadic name to inline arms over the caller's argument nodes, once per late-static-binding copy of the forwarder (Laravel's Facade::__callStatic: 268 names x 46 copies). A single spread of a cell-element pack now shares the helper: -1.3 GB.
  • new $cls(...) and closure literals are hoisted out of a dynamic-method site so it takes the shared dispatch (a 28 MB function in Eloquent): -243 MB.
  • print_r / var_export property lines are one call instead of an inlined concatenation; backtrace push/pop are alwaysinline helper calls instead of two blocks per call site (symfony-app IR -10%).

Memory

  • The class-descriptor / reflection part of a staged preamble (237 MB on Laravel) is spooled to a file with the linkonce_odr rewrite applied, instead of being copied up through four string concatenations: -0.5 GB peak.
  • bin/build keeps the compiler's automatic cycle collector (peak 6.5 -> 4.7 GB for +4.7% time) and splits the compiler's own module (see below).

Build

  • bin/build split the compiler's module by default. One serial clang -O2 over ~200 MB of IR took ~10 min and ~7.7 GB. Measured on the same commit, symfony-app front end + emit, six interleaved runs per variant, both MANTICORE_AUTO_GC=0: the split costs the compiler itself +4.5% (62.9 s vs 65.7 s wall, 62.6 s vs 65.4 s CPU). Emitted IR is identical. MANTICORE_AUTO_SPLIT=0 / MANTICORE_AUTO_GC=0 restore the old build.
  • build sweeps /tmp/manticore_buildobj_<pid>.* left by dead builders (killed builds left 4 GB each; 50 GB accumulated in a day).

Verification

  • Emitted IR is unchanged by the pure speed/memory fixes: examples/symfony-app staged IR is byte-identical before and after (cmp, sha 3a9458c1...); Laravel's staged IR has the same byte count.
  • The IR-size changes alter IR by design; their behaviour is covered by new cases dyn_method_new_dyn_arg, dyn_method_spread_forward, dyn_method_arm_helpers (outputs from php).
  • Built from the pinned bootstrap release (rm bin/manticore; bin/build, stage0 0.17.0 -> generation 1 -> generation 2): green.
  • tests/aot/run.sh -k subsets, all green: hello, dyn (121), closure, backtrace, exception, generator, spread, reflect, print_r, var_export, serialize, static, callable; tests/cli and tests/parser green.
  • examples/symfony-app built with the result: / 200, 404, 20 requests; APP_ENV=dev with a cold var/ (previously crashing) serves 200/404.

Not run: the full AOT suite, tools/difftest.sh, tools/selfhost_fixpoint.sh, the Linux gate. Laravel itself does not run yet, so its numbers are compile-side only.

Notes for review

  • Some fixes of the same kind are not here because they build on unpushed commits of the Laravel branch (scoped rescans in InferTypes, EscapeSummaries pooling). They follow once those land.
  • A rejected attempt, for the record: moving each dyn-method name arm into its own shared helper left the IR size unchanged (arms differ per receiver type); reverted before this PR.

…lare (O(N^2) rebuild per synthesized function; Laravel lowering 128 s -> 29 s)
…canning every function per class/method (Laravel InferTypes 50 s -> 8-17 s per full run)
…y holder name to the shared helper (Laravel IR 4.20 -> 2.89 GB)
…two blocks per call site (symfony-app IR -10%)
…or by default

The compiler's pass-1 build was one serial `clang -O2` over ~200 MB of IR: ~10 min and
a ~7.7 GB peak (the middle end plateaus near 2.8 GB, the backend ramps past 7 GB). Auto-split
(19 parts) takes ~1.5 min at ~4 GB. Measured on the same commit, symfony-app front+emit, 6
interleaved runs per variant: the split costs the compiler itself +4.5% (62.9 s vs 65.7 s wall,
62.6 s vs 65.4 s CPU). The emitted IR is identical either way.

The compiler was also built without its automatic cycle collector. On Laravel (-O 0, compiler
process only) the collector takes the peak RSS from 6.5 GB to 4.7 GB (after the parse step 667 MB
to 155 MB) for +4.7% time (340 s to 356 s).

Both are now the default; MANTICORE_AUTO_SPLIT=0 and MANTICORE_AUTO_GC=0 restore the old build.
…ly (29 s -> 0.3 s on Laravel's extra helpers); phase timing lines for the end of emit
…eamble to a file instead of passing 237 MB up through four string concatenations (Laravel peak RSS 5.0 -> 4.5 GB)
@blacktrs blacktrs changed the title Front-end, emitter and build sweep: Laravel compile 3x faster, staged IR -42%, peak RSS -30% Front-end, emitter and build sweep: Laravel lowering 128 s -> 25 s, staged IR -42%, peak RSS -30%, bin/build 12 -> 1.5 min Oct 28, 2026
@blacktrs

Copy link
Copy Markdown
Contributor Author

@claude please review

@claude

claude Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Claude finished @blacktrs's task in 1m 31s —— View job


Review of #510: front-end, emitter and build sweep

I read the full diff and the surrounding code for the riskiest paths. I did not build or run anything, so this is a code read only. The changes are mostly sound: each indexing fix keeps the old semantics, and the identical symfony-app IR is good evidence for the pure-speed ones. These are the points I'd look at, most important first.

1. findFunctionDef still walks the whole list on every miss (LowerReify.php:~850)

  • $pos is -1 for any name not in the index, so control falls through to the "stale slot" foreach over $module->functions.
  • The main caller, chainMethodFn (LowerReify.php:505), probes Class__method up the parent chain. Most of those probes miss, so the O(N) scan per miss may survive in exactly the hot path this change targets.
  • I'd fall back to the walk only when $pos >= 0 and functions[$pos]->name !== $name. A miss on an index that was extended to the current count can return null directly.
  • The one caveat is the "edited in place" case the comment mentions. If functions can be removed or replaced at the same count, track that with a stamp rather than walking on every miss.

2. The dynfNameableSigs() and dynfSymsMemo caches reset whenever count($this->sigs->returnType) changes

  • EmitLlvm.php:843 writes to sigs->returnType per function, and lazily minted thunks and closures may add entries during emission.
  • If dynfThunk, dynfTwinThunk or similar register sigs, the count changes between sites. That would rebuild the 130 k-entry filtered list and drop the memo at every site, which brings the quadratic back. Please confirm with a counter, or invalidate explicitly where sigs are mutated.
  • Related: the filter is applied twice, once in dynfNameableSigs() and again by the unchanged if (!$this->dynfNameable($cname)) continue; inside each loop. That is harmless but redundant.

3. Preamble spooling (EmitLlvm.php, EmitLlvmRuntime.php)

  • The marker \x1eMCSPOOL:<path>\x1e travels through emitPreamble() and linkonceRuntime() as text.
    • It only works if nothing in between inspects or transforms the preamble. Today the streaming branch just writes it out, but this is fragile.
    • If any later caller of emitPreamble() doesn't go through writeSpooledPreamble, the marker lands in the IR. Consider asserting that $preamble contains no \x1e when $spooled is false.
  • The spool files (<streamIrPath>.preN) leak if an exception is thrown between creation and writeSpooledPreamble. The new /tmp/manticore_buildobj_* sweep covers only the default /tmp location and only on the next non--keep build.
  • spoolPreamble assumes the surrounding text ends in \n when the spool starts ($leadingNl = true). It is probably true, but nothing enforces it.
  • The private bool $preambleSpoolOn block was inserted between the linkonceRuntime doc comment and its method (EmitLlvm.php:~1470). The doc comment now documents the new properties instead of linkonceRuntime. Please move the new block above that comment.

4. runFast vs run

  • It is documented as "same output for well-formed IR", and I traced the slicing logic without finding a divergence. That claim is now load-bearing, since runFile (≤ 64 MB) and all the in-memory call sites switched to it.
  • A fuzz or differential check of run against runFast over the existing .ll corpus (or just the staged IR of a few examples) would turn the claim into evidence. The PR only shows byte-identity for symfony-app.
  • Nit: the end-of-function search loop re-calls strpos("\n}") per candidate. That is fine for normal IR, but a function containing many } lines at column 0 (for example inside metadata or string constants) will iterate more.

5. bin/build and build_compile_module stale-dir sweep (Main.php:~3250)

  • kill -0 "$p" fails with EPERM for a live process owned by another user, so that builder's dir is treated as dead and removed. In practice the rm would also fail on a foreign-owned dir, but a shared /tmp with same-user containers or PID namespaces can mis-detect liveness. A pid reused by an unrelated process also keeps a stale dir alive, which is the safe direction.
  • Consider checking ownership (-O "$f") and/or age (find -mmin +N) before deleting. Also use a PID-and-start-time check, or at least skip entries modified in the last few minutes.
  • This sweep runs on every build that isn't -keep, including user builds, so a failed sweep should never be fatal. As written, system() ignores the result, which is fine.

6. anyDeclarerFn rewrite

  • It is equivalent to VivifyRefArgs::firstDeclarer (first __ split, table order). It now returns '' for an unknown method instead of calling firstDeclarer each time, which matches. Good.
  • anyDeclarerBuilt is reset in InferTypes per run, but fnByName is not reset in the same place I checked. Please make sure nothing mutates fnByName mid-run, or the memo would go stale where the old one didn't (the old memo was per method, built lazily).

7. variadicMethodParams index

  • The semantics match the old rule: a method name is null if any declaration is non-variadic or the counts disagree.
  • Invalidation: variadicIdxBuilt = false is set at the two places variadicMethodParamsCache is reset. Is the old variadicMethodParamsCache still read or written anywhere? If not, delete the now-dead property to avoid confusion.

8. irIsClosed via PCRE

  • It matches the old logic, including %aN not matching. preg_match_all('/%r[0-9]+/') on a multi-MB function body builds a large match array. That is probably still much faster than the PHP loop, but peak memory per call scales with the number of %r tokens. This is worth a glance if it is called on very large bodies.
  • Per AGENTS.md, /u isn't used, so non-UTF-8 bytes are fine.

9. Dyn-method spread sharing (EmitLlvmObjects.php:~5790)

  • Setting $needsNodes = false when $pack !== null && $argc === 1 && $packElem === null assumes every holder, by-ref and variadic included, can take its args from the pack. The new tests (dyn_method_spread_forward, dyn_method_arm_helpers) cover by-ref and variadic names reached via a spread forwarder. I'd still want one case where the spread receiver is a by-ref parameter taking an array element, to pin down the write-back semantics.
  • Adding KIND_NEW_DYN_OBJ and KIND_CLOSURE to the hoist predicate (EmitLlvmObjects.php:5165) looks right: both can have side effects and must be evaluated once.

10. Process and docs

  • The PR says the full AOT suite, difftest, selfhost_fixpoint and the Linux gate were not run. This touches HoistAllocas, the emitter, and bin/build defaults (split on, GC on), so I'd hold the merge for at least the full AOT suite and the Linux gate. Per AGENTS.md the Linux gate is mandatory for runtime-adjacent changes. The fixpoint check matters most here because the compiler is now built split by default.
  • bin/build changes the shipping default (split, GC on). The "+4.5% compiler runtime" figure comes from 6 runs per variant; that is fine, but it is a real trade-off for every user of the compiler. Say so in the release notes.
  • The Stats::line('IR: …') additions in EmitLlvm.php look like leftover profiling. They are cheap and gated, but consider dropping them or keeping only the ones you'll want later.

Tests: the three new cases are good. Their .out files should be regenerated and compared with php -d xdebug.mode=off as a final step, as your notes say.

Bottom line: I found no correctness bug I could prove from the diff. Items 1 and 2 are the ones most likely to quietly undo the speedups. Item 3 (marker and cleanup fragility) and the missing full-suite and gate runs are what I'd resolve before merging.
· branch perf/front-end-sweep

…ship, runFast differential tool

- LowerReify::findFunctionDef: a name the index does not hold is not in the list (the index covers every
  entry up to the current count); chainMethodFn probes Class__method up the parent chain and most probes
  miss, so a miss must not fall back to the linear walk. Only a slot that no longer holds its name walks.
- EmitLlvm: a failed build no longer leaves preamble spool files behind (dropPreambleSpools), and the
  assumption that a spool starts a line is checked when the marker is expanded instead of assumed;
  linkonceRuntime's doc comment is back above its method.
- Main: the stale-builder sweep only touches entries owned by the current user.
- LowerFromAst: drop the now-unused variadicMethodParamsCache.
- tools/hoist_diff.php: differential check of HoistAllocas::runFast against run() over real IR and a
  scrambled copy of it (153 variants, 127 011 allocas moved, no mismatch).
- Repro tests/aot/repro/wrong/spread_byref_array_writeback (#511): a by-ref parameter reached through a
  spread of an array passed by reference does not write back; the same on main, found while checking the
  dynamic-method spread path.
@blacktrs

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Point by point, with what I checked and what I changed (pushed as ea7ea876):

  1. findFunctionDef misses — right, that was a real hole: chainMethodFn probes mostly miss, and a miss fell through to the walk. Fixed: a name the index does not hold is null; only a slot that no longer holds its name walks. I grepped Lower*.php for in-place edits / removals of $module->functions and found none (only addFunction). Staged IR of examples/symfony-app is byte-identical before and after the fix (same app dir, same sha); lowering went 9.3 s -> 8.6 s there.
  2. dynfNameableSigs / dynfSymsMemo invalidation — the count-based key does not thrash: the only write to sigs->returnType is EmitLlvm.php:843, in the setup loop that runs before the emission loop; thunks and closures do not register sigs. I argued this from the code and did not add a counter; the emit phase did drop from ~147 s to ~107 s on Laravel. The duplicate dynfNameable filter in the loops is intentional (kept so the loops' behaviour does not depend on the cache).
  3. Spooling — doc comment moved back above linkonceRuntime; spool files are removed if the build throws between creation and use (dropPreambleSpools); "the spool starts a line" is now checked when the marker is expanded and throws otherwise. A marker cannot reach a non-spooled path: spooling is switched on only around emitPreamble() for a staged module without frame pointers, and any spool implies the spooled write path.
  4. runFast vs run — added tools/hoist_diff.php (differential over real IR plus a scrambled copy with the allocas dropped at random places and a variable-sized one). Over the repo's dump-llvm-mir output: 153 variants, 127 011 allocas moved, no mismatch. On the nit: LLVM string constants escape newlines, so a column-0 } only ends a function.
  5. Stale-dir sweep — added an ownership check (-O). I did not add an age check: leftovers of a dead builder are garbage at any age, and a reused pid keeps a stale dir alive, which is the safe direction.
  6. anyDeclarerFn — fnByName is assigned only in InferTypes::run() (reset and filled at the start), so nothing mutates it mid-run.
  7. variadicMethodParamsCache — dead after the index; removed.
  8. irIsClosed — match arrays are bounded by one function body's %r tokens; the old loop built the same $used map.
  9. By-ref write-back through a spread — I wrote the case and it is a pre-existing divergence, not something this PR introduces: function f(array &$args) { return $o->inc(...$args); } does not write back, with or without a dynamic name, on current main too (php: 11 11, manticore: 11 10). Filed as A by-ref parameter reached through a spread of an array passed by reference does not write back #511 with a repro under tests/aot/repro/wrong/. The new tests cover by-value forwarders and by-ref/variadic holders.
  10. Process — agreed. The full AOT suite runs in the CI shards; difftest, the self-host fixpoint and the Linux gate I have not run, and the merge should wait for them. The split/collector defaults deserve a line in the release notes. The Stats::line additions are gated by MANTICORE_STATS; I kept them because they produced the numbers in the description.

session_start() rolls session.gc_probability / gc_divisor (1/100 by default) and calls the handler's
gc() on a hit. The test pins the handler protocol, which has no gc, so one run in a few hundred printed
an extra `gc(1440);` (8 of 3000 local runs; failed once on linux-alpine-arm64 in CI). Set
session.gc_probability to 0 in the test, as php's own session tests do; 0 of 3000 runs now differ.
@blacktrs

Copy link
Copy Markdown
Contributor Author

The session_user_handler failure on alpine-arm64 (4/4) is a flaky test that exists on main, not something this PR changes: session_start() rolls session.gc_probability / gc_divisor (1/100) and calls the user handler's gc() on a hit, so a run occasionally prints an extra gc(1440); (the CI diff shows exactly that line). Locally 8 of 3000 runs of the old test differ, 0 of 3000 after ini_set('session.gc_probability', '0'). Pushed as a separate commit that only touches the test (session_user_handler.php; expected output unchanged and equal to php's).

…f one

The probe reads the peak RSS, which moves in whole pages for reasons that are not a leak; a single
40 000-call batch occasionally crossed the 200 KB budget on one CI job (viaArr printed `leak`) while the
identical code on every other target stayed flat. A real per-call leak grows every batch, so the function
is now flat if any of three consecutive batches stays within the budget. A deliberately leaking variant
still prints `leak`.
@blacktrs

Copy link
Copy Markdown
Contributor Author

return_ref_boxed_local_no_leak (viaArr leak on one job) is also a flake and not caused by this PR: the program's IR is byte-identical between a compiler built from main and this branch (same module size, same user functions), and 0 of 300 local runs print leak with either compiler. The probe reads peak RSS against a 200 KB budget over a single 40 000-call batch, and the test's own comment notes the peak moves in whole pages. Pushed a test-only commit that measures up to three batches (a real leak grows every batch; a page jump does not repeat); a deliberately leaking variant still prints leak.

@blacktrs
blacktrs merged commit 3b44bde into main Oct 28, 2026
44 checks passed
@blacktrs
blacktrs deleted the perf/front-end-sweep branch October 28, 2026 12:52
@blacktrs
blacktrs restored the perf/front-end-sweep branch October 28, 2026 12:52
@blacktrs
blacktrs deleted the perf/front-end-sweep branch October 28, 2026 12:52
@blacktrs
blacktrs restored the perf/front-end-sweep branch October 28, 2026 12: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.

1 participant