mirror of
https://github.com/oxc-project/oxc.git
synced 2026-11-04 10:29:58 +00:00
feat(minifier): remove unreachable code after terminating statements (#24441)
Folding a define-replaced branch can leave `if (true) { ... return fn; }` as a bare block: the lexical declaration inside pins the block (flattening it could collide with sibling bindings), and the statements after it survived even though the block always returns. rolldown's per-module tree-shake hits this shape and ships the dead branch (rolldown/rolldown#10184).
`minimize_statements` only flagged dead control flow on direct jump statements, each arm setting the flag by hand. The driver now flips the flag whenever the statement it just emitted never completes normally: a direct jump, a block ending in a jump, an if/else where both branches jump, or a try where every path jumps. That single check subsumes the per-arm writes, so the `&mut bool` threaded through the return/throw handlers is gone. The removal reuses the existing dead-zone machinery, so `var` hoisting and kept function declarations behave as before, and both DCE and full-minify modes are covered.
A minimized dead zone keeps hoisting survivors after the jump — `function` declarations and the initializer-less `var` stub KeepVar re-emits — so the block predicate skips those from the back instead of testing only the literal last statement; nothing after an aborting statement ever runs, so they cannot change how the block completes.
The helper is conservative on purpose: labeled statements never count (`a: { break a; }` completes normally), and loops and switches are left to their specific folds. Terser removes the same tails; esbuild keeps them. The leftover `{ ... }` block wrapper is also kept — flattening a block whose lexical declarations may collide with siblings is a separate rewrite, and terser and esbuild keep the braces too.
## Example
`__SSR__` defined to `true` (rolldown treeshake, `minify: false`):
```js
export function test1() {
if (true) {
const fn = () => console.log("ssr");
fn.stop = fn;
return fn;
}
const fn = () => console.log("client");
fn.stop = fn;
return fn;
}
```
Before, the unreachable client tail stayed in the output. After:
```js
export function test1() {
{
const fn = () => console.log("ssr");
fn.stop = fn;
return fn;
}
}
```
Verified with the minifier unit suite, test262/babel minifier conformance (no changes), DCE `--twice` idempotency, and `just minsize` (antd gzip 455.51 kB -> 455.50 kB, iteration counts unchanged).
Fixes rolldown/rolldown#10184.
Implemented with AI assistance (Claude Code); design, review, and verification driven by the author per the repo AI-usage policy.
This commit is contained in:
1 parent
8b1f6a286d
commit
616bfa24df
5 files changed
+159
-34
No files matched your search
@@ -74,18 +74,18 @@ impl<'a> PeepholeOptimizations {
|
||||
}
|
||||
continue; // drop: `stmt` is intentionally not pushed into `stmts`.
|
||||
}
|
||||
if Self::minimize_statement(
|
||||
stmt,
|
||||
i,
|
||||
&mut old_stmts,
|
||||
stmts,
|
||||
&mut is_control_flow_dead,
|
||||
ctx,
|
||||
)
|
||||
.is_break()
|
||||
{
|
||||
if Self::minimize_statement(stmt, i, &mut old_stmts, stmts, ctx).is_break() {
|
||||
break;
|
||||
}
|
||||
// A statement that never completes normally — a direct jump, a
|
||||
// kept block ending in a jump, an if/else or try/catch where
|
||||
// every branch jumps — makes the rest of the list unreachable.
|
||||
// https://github.com/rolldown/rolldown/issues/10184
|
||||
if !is_control_flow_dead
|
||||
&& stmts.last().is_some_and(Self::statement_never_completes_normally)
|
||||
{
|
||||
is_control_flow_dead = true;
|
||||
}
|
||||
}
|
||||
if let Some(stmt) = keep_var.get_variable_declaration_statement(&ctx.ast) {
|
||||
match Self::remove_unused_variable_declaration(stmt, ctx) {
|
||||
@@ -364,22 +364,10 @@ impl<'a> PeepholeOptimizations {
|
||||
i: usize,
|
||||
stmts: &mut ArenaVec<'a, Statement<'a>>,
|
||||
result: &mut ArenaVec<'a, Statement<'a>>,
|
||||
is_control_flow_dead: &mut bool,
|
||||
|
||||
ctx: &mut TraverseCtx<'a>,
|
||||
) -> ControlFlow<()> {
|
||||
match stmt {
|
||||
Statement::EmptyStatement(_) => (),
|
||||
Statement::BreakStatement(s) => {
|
||||
// Local `&mut bool` flag, not an AST slot.
|
||||
*is_control_flow_dead = true;
|
||||
result.push(Statement::BreakStatement(s));
|
||||
}
|
||||
Statement::ContinueStatement(s) => {
|
||||
// Local `&mut bool` flag, not an AST slot.
|
||||
*is_control_flow_dead = true;
|
||||
result.push(Statement::ContinueStatement(s));
|
||||
}
|
||||
Statement::VariableDeclaration(var_decl) => {
|
||||
Self::handle_variable_declaration(var_decl, result, ctx);
|
||||
}
|
||||
@@ -395,10 +383,10 @@ impl<'a> PeepholeOptimizations {
|
||||
}
|
||||
}
|
||||
Statement::ReturnStatement(ret_stmt) => {
|
||||
Self::handle_return_statement(ret_stmt, result, is_control_flow_dead, ctx);
|
||||
Self::handle_return_statement(ret_stmt, result, ctx);
|
||||
}
|
||||
Statement::ThrowStatement(throw_stmt) => {
|
||||
Self::handle_throw_statement(throw_stmt, result, is_control_flow_dead, ctx);
|
||||
Self::handle_throw_statement(throw_stmt, result, ctx);
|
||||
}
|
||||
Statement::ForStatement(for_stmt) => {
|
||||
Self::handle_for_statement(for_stmt, result, ctx);
|
||||
@@ -445,6 +433,65 @@ impl<'a> PeepholeOptimizations {
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether control never falls through to the statement after this one in
|
||||
/// the same statement list (terser's `aborts`).
|
||||
///
|
||||
/// Any abrupt completion qualifies, whatever its target: a `break` or
|
||||
/// `continue` transfers control past the end of the enclosing statement
|
||||
/// list, never to the next statement in it.
|
||||
///
|
||||
/// Conservative on purpose:
|
||||
/// - A labeled statement completes normally when its body breaks out of
|
||||
/// its own label (`a: { break a; }`), so it never counts.
|
||||
/// - Loops and switches count as completing normally; `while (true)`
|
||||
/// without `break` is handled by loop-specific folds instead.
|
||||
fn statement_never_completes_normally(stmt: &Statement<'a>) -> bool {
|
||||
match stmt {
|
||||
Statement::ReturnStatement(_)
|
||||
| Statement::ThrowStatement(_)
|
||||
| Statement::BreakStatement(_)
|
||||
| Statement::ContinueStatement(_) => true,
|
||||
Statement::BlockStatement(block) => Self::block_never_completes_normally(block),
|
||||
Statement::IfStatement(if_stmt) => {
|
||||
if_stmt.alternate.as_ref().is_some_and(Self::statement_never_completes_normally)
|
||||
&& Self::statement_never_completes_normally(&if_stmt.consequent)
|
||||
}
|
||||
Statement::TryStatement(try_stmt) => {
|
||||
// A finalizer that aborts overrides however the other
|
||||
// blocks complete. Otherwise the try block must abort, and
|
||||
// so must the catch block when present (an exception
|
||||
// thrown before the try block's jump lands there).
|
||||
try_stmt.finalizer.as_ref().is_some_and(|f| Self::block_never_completes_normally(f))
|
||||
|| (Self::block_never_completes_normally(&try_stmt.block)
|
||||
&& try_stmt
|
||||
.handler
|
||||
.as_ref()
|
||||
.is_none_or(|h| Self::block_never_completes_normally(&h.body)))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn block_never_completes_normally(block: &BlockStatement<'a>) -> bool {
|
||||
// A minimized dead zone keeps only hoisting survivors after the jump:
|
||||
// `function` declarations and the initializer-less `var` stub
|
||||
// re-emitted by `KeepVar`. Their bindings initialize at scope entry
|
||||
// and nothing after an aborting statement ever runs, so skip them
|
||||
// from the back before testing how the block completes.
|
||||
block
|
||||
.body
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|stmt| match stmt {
|
||||
Statement::FunctionDeclaration(_) => false,
|
||||
Statement::VariableDeclaration(decl) => {
|
||||
!(decl.kind.is_var() && decl.declarations.iter().all(|d| d.init.is_none()))
|
||||
}
|
||||
_ => true,
|
||||
})
|
||||
.is_some_and(Self::statement_never_completes_normally)
|
||||
}
|
||||
|
||||
/// For variable declarations:
|
||||
/// * merge with the previous variable declarator if their kinds are the same
|
||||
/// * remove the variable declarator if it is unused
|
||||
@@ -885,7 +932,6 @@ impl<'a> PeepholeOptimizations {
|
||||
fn handle_return_statement(
|
||||
mut ret_stmt: ArenaBox<'a, ReturnStatement<'a>>,
|
||||
result: &mut ArenaVec<'a, Statement<'a>>,
|
||||
is_control_flow_dead: &mut bool,
|
||||
|
||||
ctx: &mut TraverseCtx<'a>,
|
||||
) {
|
||||
@@ -916,8 +962,6 @@ impl<'a> PeepholeOptimizations {
|
||||
ctx.drop_expression(&old);
|
||||
}
|
||||
result.push(Statement::ReturnStatement(ret_stmt));
|
||||
// Local `&mut bool` flag, not an AST slot.
|
||||
*is_control_flow_dead = true;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -931,14 +975,11 @@ impl<'a> PeepholeOptimizations {
|
||||
result.pop();
|
||||
}
|
||||
result.push(Statement::ReturnStatement(ret_stmt));
|
||||
// Local `&mut bool` flag, not an AST slot.
|
||||
*is_control_flow_dead = true;
|
||||
}
|
||||
|
||||
fn handle_throw_statement(
|
||||
mut throw_stmt: ArenaBox<'a, ThrowStatement<'a>>,
|
||||
result: &mut ArenaVec<'a, Statement<'a>>,
|
||||
is_control_flow_dead: &mut bool,
|
||||
|
||||
ctx: &mut TraverseCtx<'a>,
|
||||
) {
|
||||
@@ -959,8 +1000,6 @@ impl<'a> PeepholeOptimizations {
|
||||
ctx.drop_statement(&dropped);
|
||||
}
|
||||
result.push(Statement::ThrowStatement(throw_stmt));
|
||||
// Local `&mut bool` flag, not an AST slot.
|
||||
*is_control_flow_dead = true;
|
||||
}
|
||||
|
||||
fn handle_for_statement(
|
||||
|
||||
@@ -711,3 +711,63 @@ fn dce_keeps_write_only_property_assignments() {
|
||||
"(function() {\n\tvar r = require(\"react\");\n\tvar o = function(e, t) {\n\t\treturn r.create(e, t);\n\t};\n\to.displayName = \"X\";\n})();",
|
||||
);
|
||||
}
|
||||
|
||||
// A statement that never completes normally (a kept block ending in a jump,
|
||||
// an if/else or try/catch where every branch jumps) makes everything after it
|
||||
// in the same statement list unreachable. The kept-block shape is what
|
||||
// `define`-driven branch folding leaves behind: `if (true) { ... return fn; }`
|
||||
// folds to a block that is pinned by its lexical declaration.
|
||||
#[test]
|
||||
fn dce_remove_unreachable_after_terminating_statement() {
|
||||
// https://github.com/rolldown/rolldown/issues/10184
|
||||
test(
|
||||
"export function f() {\n\tif (true) {\n\t\tconst fn = () => 1;\n\t\tfn.stop = fn;\n\t\treturn fn;\n\t}\n\tconst fn = () => 2;\n\tfn.stop = fn;\n\treturn fn;\n}",
|
||||
"export function f() {\n\t{\n\t\tconst fn = () => 1;\n\t\tfn.stop = fn;\n\t\treturn fn;\n\t}\n}",
|
||||
);
|
||||
// Both branches of an if/else terminate.
|
||||
test(
|
||||
"export function f(c) { if (c) { return 1; } else { return 2; } foo(); }",
|
||||
"export function f(c) { if (c) return 1; else return 2; }",
|
||||
);
|
||||
// Both blocks of a try/catch terminate.
|
||||
test(
|
||||
"export function f() { try { return g(); } catch { return h(); } i(); }",
|
||||
"export function f() { try { return g(); } catch { return h(); } }",
|
||||
);
|
||||
// A `var` in the unreachable tail hoists; unreferenced, the re-emitted
|
||||
// declaration is then dropped as unused.
|
||||
test(
|
||||
"export function f() {\n\tif (true) {\n\t\tconst a = 1;\n\t\tuse(a);\n\t\treturn a;\n\t}\n\tvar x = g();\n}",
|
||||
"export function f() {\n\t{\n\t\tconst a = 1;\n\t\tuse(a);\n\t\treturn a;\n\t}\n}",
|
||||
);
|
||||
// A `var` in the unreachable tail referenced from live code keeps its
|
||||
// binding (only the unreachable initializer goes).
|
||||
test(
|
||||
"export function f() {\n\tuse(() => x);\n\tif (true) {\n\t\tconst a = 1;\n\t\tuse(a);\n\t\treturn a;\n\t}\n\tvar x = g();\n}",
|
||||
"export function f() {\n\tuse(() => x);\n\t{\n\t\tconst a = 1;\n\t\tuse(a);\n\t\treturn a;\n\t}\n\tvar x;\n}",
|
||||
);
|
||||
// Function declarations in the unreachable tail hoist and stay.
|
||||
test_same(
|
||||
"export function f() {\n\t{\n\t\tconst a = g();\n\t\tuse(a);\n\t\treturn a;\n\t}\n\tfunction g() {\n\t\treturn 2;\n\t}\n}",
|
||||
);
|
||||
// Negative: the block can complete normally, so the tail stays.
|
||||
test_same(
|
||||
"export function f(c) {\n\t{\n\t\tlet a = g();\n\t\tif (c) return a;\n\t}\n\treturn foo();\n}",
|
||||
);
|
||||
// Hoisting survivors trailing the jump inside the block — a kept
|
||||
// `function` declaration or a `var` stub re-emitted by `KeepVar` — don't
|
||||
// hide that the block terminates.
|
||||
test(
|
||||
"export function f() {\n\t{\n\t\tconst a = g();\n\t\ta.x = a;\n\t\treturn a;\n\t\tfunction g() {\n\t\t\treturn {};\n\t\t}\n\t}\n\ttail();\n}",
|
||||
"export function f() {\n\t{\n\t\tconst a = g();\n\t\ta.x = a;\n\t\treturn a;\n\t\tfunction g() {\n\t\t\treturn {};\n\t\t}\n\t}\n}",
|
||||
);
|
||||
test(
|
||||
"export function f() {\n\tuse(() => x);\n\t{\n\t\tlet a = g();\n\t\tuse(a);\n\t\treturn a;\n\t\tvar x = h();\n\t}\n\ttail();\n}",
|
||||
"export function f() {\n\tuse(() => x);\n\t{\n\t\tlet a = g();\n\t\tuse(a);\n\t\treturn a;\n\t\tvar x;\n\t}\n}",
|
||||
);
|
||||
// Negative: skipping the hoisting survivors must land on a statement
|
||||
// that really terminates — `if` without `else` doesn't.
|
||||
test_same(
|
||||
"export function f(c) {\n\t{\n\t\tif (c) return g();\n\t\tfunction g() {\n\t\t\treturn 1;\n\t\t}\n\t}\n\treturn tail();\n}",
|
||||
);
|
||||
}
|
||||
@@ -182,6 +182,32 @@ fn remove_unreachable() {
|
||||
// after `return` is preserved under `unused: Keep`.
|
||||
test("function f() { return; var a }", "function f() { return; var a }");
|
||||
test_unused("(function () { return; var a })()", "");
|
||||
|
||||
// https://github.com/rolldown/rolldown/issues/10184
|
||||
// A statement that never completes normally also terminates the list:
|
||||
// a block pinned by its lexical declaration, or a try/catch where both
|
||||
// blocks jump.
|
||||
test(
|
||||
"function f() { { const a = g(); a.x = a; return a; } h(); }",
|
||||
"function f() { { let a = g(); return a.x = a, a; } }",
|
||||
);
|
||||
test(
|
||||
"function f() { try { return g(); } catch { return h(); } i(); }",
|
||||
"function f() { try { return g(); } catch { return h(); } }",
|
||||
);
|
||||
// Negative: the block can complete normally, so the tail stays.
|
||||
test_same("function f(c) { { let a = g(); if (c) return a; } return foo(); }");
|
||||
// Hoisting survivors trailing the jump inside the block — a kept
|
||||
// `function` declaration or a `var` stub re-emitted by `KeepVar` — don't
|
||||
// hide that the block terminates.
|
||||
test(
|
||||
"function f() { { const a = g(); a.x = a; return a; function g() { return {} } } h(); }",
|
||||
"function f() { { let a = g(); return a.x = a, a; function g() { return {} } } }",
|
||||
);
|
||||
test(
|
||||
"function f() { use(() => x); { let a = g(); use(a); return a; var x = h(); } tail(); }",
|
||||
"function f() { use(() => x); { let a = g(); return use(a), a; var x; } }",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -21,7 +21,7 @@ Original | minified | minified | gzip | gzip | Iterations | Fi
|
||||
|
||||
3.20 MB | 1.00 MB | 1.01 MB | 322.59 kB | 331.56 kB | 2 | echarts.js
|
||||
|
||||
6.69 MB | 2.13 MB | 2.31 MB | 455.51 kB | 488.28 kB | 5 | antd.js
|
||||
6.69 MB | 2.13 MB | 2.31 MB | 455.50 kB | 488.28 kB | 5 | antd.js
|
||||
|
||||
10.95 MB | 3.33 MB | 3.49 MB | 853.05 kB | 915.50 kB | 4 | typescript.js
|
||||
|
||||
@@ -8,7 +8,7 @@ RadixUIAdoptionSection.jsx | 2.52 kB || 21 | 0 |
|
||||
|
||||
pdf.mjs | 567.30 kB || 2469 | 205 || 47471 | 7742
|
||||
|
||||
antd.js | 6.69 MB || 1044 | 56 || 372637 | 76751
|
||||
antd.js | 6.69 MB || 1044 | 56 || 372632 | 76745
|
||||
|
||||
binder.ts | 193.08 kB || 33 | 1 || 7076 | 824
|
||||
|
||||
|
||||
Reference in new issue
Block a user