Skip to content

fix(optimization): recover inline-const for exports whose writers are tree-shaken - #9992

Merged
IWANABETHATGUY merged 5 commits into
rolldown:mainfrom
linyiru:fix/9698-inlineconst-multi-entry
Nov 15, 2026
Merged

IWANABETHATGUY merged 5 commits into
rolldown:mainfrom
linyiru:fix/9698-inlineconst-multi-entry

Conversation

@linyiru

@linyiru linyiru commented Jun 27, 2026

Copy link
Copy Markdown
Contributor

Summary

Fixes #9698. When optimization.inlineConst is on and there is more than one entry, a top level export let X = <literal> whose only writes live in code that gets tree-shaken away is not recognized as constant. Guards like if (X) survive and drag in otherwise dead code. With a single entry it already works, so the output ended up depending on how chunks were split.

Minimal repro (the issue's pattern):

// flag.js
export let custom_render = false;
export function enable_custom_render() { custom_render = true; }

// index.js (entry)
import { custom_render } from "./flag.js";
import { mount as mount_client } from "./main-client.js";
export function mount(...args) {
  if (custom_render) return mount_client(...args);
  throw new Error("can't use on the server");
}

// another.js (entry)
import { custom_render } from "./flag.js";
console.log(custom_render);

// custom-render.js (not an entry, not imported anywhere, so dead)
import { enable_custom_render } from "./flag.js";
enable_custom_render();

enable_custom_render is the only writer of custom_render and it is never reached, so custom_render is always false. Rollup drops the guarded code. Rolldown kept it once flag.js became a shared chunk.

Root cause

inline-const (cross_module_optimization) runs before tree-shaking (include_statements). It decides const eligibility from IsNotReassigned, which is computed syntactically at scan time and counts the write inside enable_custom_render even though that function is dead. With one entry the whole graph is hoisted into one chunk and the in-chunk minifier folds the value, which hid the problem. With two entries flag.js is a separate shared chunk and only inline-const could fold across the boundary, but it had already refused.

Fix

After tree-shaking, re-derive const-ness from real liveness:

  • During scan, record for each top level symbol which statements write it (reassigned_stmt_map), and keep literal lets that were dropped from the const map only because they are syntactically mutated (mutated_constant_candidates).
  • After include_statements, a candidate becomes constant when every statement that writes it was excluded by tree-shaking. In ESM all writes to an exported binding live in its own module, so this is decided locally without cross module analysis.
  • Newly found constants are added to the constant map and folded by re-running inline-const and tree-shaking (a small fixpoint). If nothing is recovered the loop exits immediately, so builds without dead writer constants are unaffected.

Safety:

  • Only ESM bindings are recovered. CommonJS exports are written through exports.x = ... member expressions which this path does not track, so they are never treated as candidates.
  • A candidate is recovered only when its captured writers are non-empty and all excluded. If a symbol is marked mutated but we captured no writer (a write form the scan does not record), it stays conservative and is left alone.
  • It only does extra work when inline-const is enabled and a candidate actually exists, so default and disabled builds pay nothing.

Test plan

  • New fixture crates/rolldown/tests/rolldown/optimization/inline_const/issue_9698_multi_entry_dead_writer reproduces the issue with two entries and inlineConst. The snapshot shows the guard removed (mount becomes just the throw) and console.log(false) in the other entry.
  • cargo test -p rolldown passes and no existing snapshots changed.
  • Node tests for bundling, optimization, tree-shaking, plugins, and sourcemaps pass.
  • Verified through the public API that with inlineConst off the guard is kept (no behavior change), and with the default or an explicit inlineConst the guard is removed.

AI disclosure

This change was developed with the help of an AI coding assistant. I reviewed, tested, and validated all of it and I take responsibility for the result.

@codspeed

codspeed Bot commented Jun 27, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

1 warning

⚠️ 4 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 7 untouched benchmarks
⏩ 10 skipped benchmarks1


Comparing linyiru:fix/9698-inlineconst-multi-entry (4ece737) with main (b932fa3)2

Open in CodSpeed

Footnotes

  1. 10 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

  2. No successful run was found on main (1daf59f) during the generation of this report, so b932fa3 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@hyfdev hyfdev assigned hyfdev and IWANABETHATGUY and unassigned hyfdev Nov 11, 2026
@IWANABETHATGUY
IWANABETHATGUY force-pushed the fix/9698-inlineconst-multi-entry branch from 21289c4 to 4ec1855 Compare November 12, 2026 10:27
@netlify

netlify Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for rolldown-rs ready!

Name Link
🔨 Latest commit 4ece737
🔍 Latest deploy log https://app.netlify.com/projects/rolldown-rs/deploys/6af9d25acc486fa438ea1b59
😎 Deploy Preview https://deploy-preview-9992--rolldown-rs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@IWANABETHATGUY

Copy link
Copy Markdown
Member

I rebased this onto main and pushed 4ec1855 on top of your commit.

On current main, the recovery loop after include_statements doesn't fit well. It reruns only cross_module_optimization and include_statements, so the passes in between (prune_constant_branches and others) never see a recovered constant. It also runs tree shaking again in each round.

The new commit decides the constant once, before cross_module_optimization. An exported let becomes a constant when all its writes are inside functions that no importer, statement with side effects, or property write can reach. Then every later pass reads the same constant map.

It also drops var from the candidates, because the var candidates skipped the checks that main has for var (redeclaration, eval, read before declaration). Your issue_9698_multi_entry_dead_writer fixture stays.

linyiru and others added 3 commits November 12, 2026 17:08
… tree-shaken

An exported `let X = <literal>` whose only writes live in code that is
later tree-shaken is effectively constant, but inline-const runs before
tree-shaking and treats X as reassigned (the IsNotReassigned flag is
syntactic, computed at scan time). With multiple entries X's module
becomes a shared chunk, the in-chunk minifier can no longer fold it, and
guards like `if (X)` survive and keep otherwise dead code.

After tree-shaking, re-derive const-ness from real liveness: a candidate
`let` (literal init, dropped from the const map because it is
syntactically mutated) becomes constant when every statement that writes
it was excluded. In ESM all writes to an exported binding live in its own
module, so this is decidable locally. Recovered constants are folded by
re-running inline-const and tree-shaking. It is a no-op when inline-const
is disabled, so normal builds pay nothing.

Closes rolldown#9698
…ant passes

The scanner keeps each exported `let` whose writes are all inside functions. A link pass
before `cross_module_optimization` makes it a constant when no importer, statement with side
effects or property write can reach a writer, so all constant passes see one constant map.
Each importer is read one time.
@linyiru
linyiru force-pushed the fix/9698-inlineconst-multi-entry branch from 4ec1855 to 860b5d4 Compare November 12, 2026 23:08
@IWANABETHATGUY
IWANABETHATGUY enabled auto-merge (squash) November 15, 2026 15:40
@IWANABETHATGUY
IWANABETHATGUY merged commit ef4d3fe into rolldown:main Nov 15, 2026
35 checks passed
@rolldown-guard rolldown-guard Bot mentioned this pull request Nov 18, 2026
shulaoda added a commit that referenced this pull request Nov 18, 2026
## [1.3.3] - 2026-11-18

### 🚀 Features

- rolldown_plugin_chunk_import_map: add `include` option (#11750) by @shulaoda
- show plugin timings as a table (#11726) by @shulaoda
- inline-common-chunks: inline chunks that `import()` also loads (#11656) by @hyfdev

### 🐛 Bug Fixes

- binding: don't crash WASI calls made after `close()` (#11783) by @hyfdev
- reset plugin module options when modules are fetched again (#11456) by @Vladimir-Pirotskiy
- prevent UMD dependencies from using host AMD loaders (#10648) by @rohit-jsfreaky
- binding: count builds that overlap in the plugin timings report (#11775) by @IWANABETHATGUY
- new-url: decode percent-encoded paths in `new URL()` (#11419) by @theRizwan
- new-url: emit the asset when a plugin loads a `new URL()` target as code (#11418) by @theRizwan
- hmr: don't treat modules in unloaded chunks as already run (#11772) by @hyfdev
- binding: keep only the latest build's handle in `BindingBundler` (#11769) by @shulaoda
- plugin: propagate onLog hook errors to fail the build (#9907) by @jaehafe
- rolldown_plugin_vite_resolve: clear the resolver cache on update watch events (#11666) by @lazerg
- print the `url` of plugin errors and warnings (#11744) by @lazerg
- dev: recover from a rebuild that fails in `buildEnd` (#11713) by @hyfdev
- inline-const: do not inline an exported `var` read early through an import cycle (#11751) by @hyfdev
- cjs: keep a CommonJS entry's `module.exports` in CJS output (#11752) by @hyfdev
- keep internal chunk exports out of dynamic import namespaces (#11737) by @IWANABETHATGUY
- deconflict: keep block function and class names when a catch/var binding is renamed (#11743) by @hyfdev
- keep data URL modules in execution order with `chunkModulesOrder: 'module-id'` (#11735) by @shulaoda
- stop special-casing module ids that start with `rolldown:` (#11731) by @shulaoda
- inline-const: do not inline a `var` read early inside a function (#11673) by @hyfdev
- tla: ignore top-level await in tree-shaken statements (#11724) by @hyfdev
- cli: correct the help text of `--polyfillRequire`, `--makeAbsoluteExternalsRelative` and `--format` (#11725) by @shulaoda
- code-splitting: keep the source order of external imports (#11687) by @danielroe
- preserve-modules: create chunks in execution order (#11705) by @hyfdev
- join the option path in a validation warning with dots (#11723) by @shulaoda
- rolldown_plugin_vite_reporter: cut the progress line at a character boundary (#11721) by @shulaoda
- dev: keep preserved-JSX handling when a rebuild adds the first JSX module (#11707) by @hyfdev
- plugin: reject `this.load()` in `buildStart` (#11720) by @hyfdev
- keep dynamic entry as the facade of its `codeSplitting` group chunk (#11507) by @danielroe
- order entry chunks by their first-executed module (#11506) by @danielroe
- reject an unknown `output.esModule` string (#11719) by @shulaoda
- jsx: error instead of panicking when a preserved JSX tag imports a non-identifier name (#11706) by @hyfdev
- optimization: recover inline-const for exports whose writers are tree-shaken (#9992) by @linyiru
- perf-kit: read `index.html` as the browser does when detecting the entry (#11668) by @IWANABETHATGUY
- sourcemap: resolve relative sources of plugin maps against the module (#11691) by @BoussonKarel
- keep_names: don't emit class static blocks for targets without them (#11497) by @thelastbackspace
- inline-common-chunks: avoid an entry facade when a lazy chunk loads one of its modules (#11689) by @hyfdev
- inline-const: do not inline a constant used as a JSX element name (#11678) by @shulaoda
- reject a `moduleSideEffects` rule without `test` and `external` (#11684) by @shulaoda
- code-splitting: retry `avoidRedundantChunkLoads` moves that an unmoved atom blocked (#11659) by @Tom4ikss
- json: preserve lone UTF-16 surrogates (#11677) by @shuvroroy
- initialize an entry's re-exported modules in source order (#11548) by @Aschenbath
- support function replacers in `MagicString.replace`/`replaceAll` (#11624) by @btea
- inline-const: treat `pass: 0` as disabled (#11663) by @shulaoda
- release the old name when a deduplicated asset re-picks a shorter one (#11664) by @olivier-thatch
- honor `output.exports` for non-entry modules under `preserveModules` (#11218) by @Marve10s
- do not treat `require` passed as a call argument as a `require()` call (#11660) by @shulaoda
- include sourcemap comments in chunk hashes (#11547) by @shuvroroy
- deps: update rustix to 1.1.6 to fix musl builds on ppc64le and s390x (#11665) by @WhyNotHugo
- allow plugins to be garbage collected after `bundle.close()` (#11467) by @IWANABETHATGUY

### 🚜 Refactor

- remove `BindingHookJsLoadOutput` and use `BindingHookLoadOutput` (#11746) by @sapphi-red
- dev: enable `skipCommonRuntimeInjection` by default and remove the option (#11776) by @sapphi-red
- simplify `BindingSourcemap` with `#napi(transparent)` (#11745) by @sapphi-red
- remove unused and constant parameters (#11758) by @shulaoda
- remove the unused `block_on_spawn_all` and the `async-scoped` dependency (#11754) by @shulaoda
- remove fields that are never read (#11757) by @shulaoda
- use the public sourcemap lookup cursor (#11580) by @Dunqing
- remove unused types, methods and trait impls (#11742) by @shulaoda
- make `InstantiatedChunk` Ecma-only and drop the `Generator` trait (#11730) by @shulaoda
- remove the unused `InstantiationKind::None` variant (#11728) by @shulaoda

### 📚 Documentation

- linking: remove the stale `Module::CssModule` mention (#11729) by @shulaoda
- magic-string: recommend `'boundary'` over `hires: true` (#11652) by @IWANABETHATGUY
- readme: remove the DeepWiki badge (#11722) by @hyfdev

### ⚡ Performance

- sourcemap: avoid a source map copy when plugins return maps (#11764) by @anonrig
- keep `g`/`d` regex flags on the fast matcher (#11762) by @anonrig
- minify: minify each chunk as soon as its renderChunk hooks return (#11703) by @Boshen
- free each module's AST as soon as it is printed (#11733) by @Boshen
- code-splitting: compute already-loaded atoms without per-importer clones (#11700) by @Boshen
- bitset: visit only set bits in `index_of_one` and vectorize `union` (#11699) by @Boshen
- manual-code-splitting: skip modules already in the group (#11698) by @Boshen
- binding: compress embedded oxc runtime helpers (#10751) by @Boshen
- avoid per-chunk hash sets when hashing transitive chunk dependencies (#11681) by @Boshen
- collect cross-chunk declared symbols without a shared AppendOnlyVec (#11682) by @Boshen
- shrink sourcemap JSON buffers before retaining them as assets (#11407) by @h-a-n-a
- read output chunk and asset metadata lazily in output hooks (#11683) by @Boshen
- plugin: avoid promises for synchronous hooks (#11674) by @Boshen
- skip sourcemap generation in `RenderedModule::code()` (#11654) by @camc314

### 🧪 Testing

- dev: run the in-flight `ensureLatestBuildOutput` close test with the WASI binding (#11785) by @shulaoda
- json: ensure transform generates empty sourcemap (#11747) by @sapphi-red
- render-chunk: stop pinning the renderChunk call order (#11759) by @hyfdev
- render-chunk: check only the guaranteed renderChunk call order (#11755) by @hyfdev
- sourcemap: build the expected source path from separate segments (#11749) by @hyfdev
- fix the flaky normalized options memory check on WASI (#11738) by @hyfdev

### ⚙️ Miscellaneous Tasks

- deps: update rust crate oxc_index to v5.0.1 (#11761) by @renovate[bot]
- deps: update dependency vite-plus to v1.7.0 (#11748) by @renovate[bot]
- deps: update rollup submodule for tests to v4.68.4 (#11740) by @rolldown-guard[bot]
- deps: update test262 submodule for tests (#11741) by @rolldown-guard[bot]
- deps: upgrade oxc to 0.159.0 (#11736) by @camc314
- wasi: remove the Node Test retry (#11732) by @shulaoda
- bump .node-version to 24.22.3 (#11717) by @shulaoda
- deps: update dependency ws to v8.23.0 (#11718) by @renovate[bot]
- deps: update rust crates (#11715) by @renovate[bot]
- deps: update npm packages (#11714) by @renovate[bot]
- deps: update github actions (#11716) by @renovate[bot]
- exclude compressed oxc runtime helpers from EOL normalization (#11704) by @hyfdev
- deps: update dependency rolldown-plugin-dts to v0.30.2 (#11711) by @renovate[bot]
- deps: update crate-ci/typos action to v1.52.2 (#11701) by @renovate[bot]
- deps: update dependency rolldown-plugin-dts to v0.30.1 (#11686) by @renovate[bot]
- deps: update rust to v1.100.0 (#11685) by @Boshen
- deps: update crate-ci/typos action to v1.52.1 (#11679) by @renovate[bot]

### ❤️ New Contributors

* @Vladimir-Pirotskiy made their first contribution in [#11456](#11456)
* @rohit-jsfreaky made their first contribution in [#10648](#10648)
* @BoussonKarel made their first contribution in [#11691](#11691)
* @thelastbackspace made their first contribution in [#11497](#11497)
* @Tom4ikss made their first contribution in [#11659](#11659)
* @Aschenbath made their first contribution in [#11548](#11548)
* @olivier-thatch made their first contribution in [#11664](#11664)
* @Marve10s made their first contribution in [#11218](#11218)
* @WhyNotHugo made their first contribution in [#11665](#11665)

Co-authored-by: shulaoda <[email protected]>
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.

[Bug]: treeshake away never changing variables read from multiple entries

3 participants