Skip to content

[StackIR] Support control flow input parameters - #9300

Merged
tlively merged 8 commits into
mainfrom
stack-ir-param-types
Nov 19, 2026
Merged

tlively merged 8 commits into
mainfrom
stack-ir-param-types

Conversation

@tlively

@tlively tlively commented Oct 23, 2026

Copy link
Copy Markdown
Member

Add a params field to StackInst on control-flow begin instructions (BlockBegin, IfBegin, LoopBegin, TryBegin, and TryTableBegin), and update ModuleUtils::collectHeapTypeInfo, BinaryInstWriter, WasmBinaryWriter, PrintSExpression, and StackIROptimizer to register, emit, print, and account for control-flow input parameter signatures.

The optimizer does not yet use the input parameters, so add gtests that artificially test printing and binary writing for now. These tests will be replaced with normal lit tests in future commits that start using the block parameters in the optimizer.

Using control flow input parameters in Stack IR will ultimately improve code size by up to 1.2% geomean across many interesting Wasm modules, depending on what other optimizations run first.

Add a params field to StackInst on control-flow begin instructions (BlockBegin, IfBegin, LoopBegin, TryBegin, and TryTableBegin), and update ModuleUtils::collectHeapTypeInfo, BinaryInstWriter, WasmBinaryWriter, PrintSExpression, and StackIROptimizer to register, emit, print, and account for control-flow input parameter signatures.

The optimizer does not yet use the input parameters, so add gtests that artificially test printing and binary writing for now. These tests will be replaced with normal lit tests in future commits that start using the block parameters in the optimizer.

Using control flow input parameters in Stack IR will ultimately improve code size by up to 1.2% geomean across many interesting Wasm modules, depending on what other optimizations run first.
@tlively
tlively requested a review from a team as a code owner October 23, 2026 17:30
@tlively
tlively requested review from kripken and stevenfontanella and removed request for a team October 23, 2026 17:30

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces support for control-flow block input parameters within StackIR, binary writing, and printing. It updates the type collection and optimization processes to account for these parameters, and adjusts the StackIR optimizer to handle control flow instructions that consume stack values. Additionally, comprehensive unit tests are added to verify these changes. The review feedback suggests a safer way to manage the state of parameter types during expression visitation by saving and restoring the previous parameter state, which prevents potential bugs from nested or recursive visits.

Comment thread src/wasm-stack.h
Comment on lines +108 to 118
void visit(Expression* curr, Type params = Type::none) {
if (func) {
parent.trackExpressionStart(curr, func);
}
currParams = params;
OverriddenVisitor<BinaryInstWriter>::visit(curr);
currParams = Type::none;
if (func) {
parent.trackExpressionEnd(curr, func);
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To prevent potential bugs from nested or recursive visit calls, it is safer to save and restore the previous value of currParams using a local variable rather than unconditionally resetting it to Type::none at the end of the method.

Suggested change
void visit(Expression* curr, Type params = Type::none) {
if (func) {
parent.trackExpressionStart(curr, func);
}
currParams = params;
OverriddenVisitor<BinaryInstWriter>::visit(curr);
currParams = Type::none;
if (func) {
parent.trackExpressionEnd(curr, func);
}
}
void visit(Expression* curr, Type params = Type::none) {
if (func) {
parent.trackExpressionStart(curr, func);
}
auto oldParams = currParams;
currParams = params;
OverriddenVisitor<BinaryInstWriter>::visit(curr);
currParams = oldParams;
if (func) {
parent.trackExpressionEnd(curr, func);
}
}

@kripken

kripken commented Oct 23, 2026

Copy link
Copy Markdown
Member
  1. How does using input parameters affect our roundtrip sizes? I mean, does re-parsing it back in cause problems?
  2. How complex are those optimizations that are planned for later? Would be good to get an idea if that is worth the 1.2% benefit.

@tlively

tlively commented Oct 23, 2026 •

Copy link
Copy Markdown
Member Author
  1. Parsing the binary will introduce scratch locals to replace the control flow inputs. These will mostly be identical to the locals that were optimized out to produce the control flow inputs in the first place. The only difference I can think of is that when the control flow parameter is passed through multiple nested control flow instructions, the parser will generate a separate scratch local for each one. This will easily be fixed up by SimplifyLocals, but we could also potentially optimize this in IRBuilder.
  2. This is the first in a stack of 5 PRs. The others will be:
    1. Thread stack values into block params - updates heap2stack to add control flow params (-0.63% size geomean)
    2. Thread stack values into one-armed ifs - optimizes ifs (very small benefit)
    3. Thread induction locals into loop params - optimizes loops (teeny tiny benefit)
    4. Prune and coalesce locals after StackIR - removes locals from the function header when StackIR has optimized them out (-0.57% size geomean)

If you'd prefer, we can drop the if and loop optimizations.

@kripken

kripken commented Oct 26, 2026

Copy link
Copy Markdown
Member

but we could also potentially optimize this in IRBuilder.

Do we do anything like that atm in IRBuilder, or is this a new type of optimization there? How complex will it be?

I do think we should avoid roundtripping getting worse (which is annoying and also bad for reduction).

Prune and coalesce locals after StackIR - removes locals from the function header when StackIR has optimized them out (-0.57% size geomean)

This is independent, I think, of input params? Definitely useful!

@tlively

tlively commented Oct 26, 2026

Copy link
Copy Markdown
Member Author

but we could also potentially optimize this in IRBuilder.

Do we do anything like that atm in IRBuilder, or is this a new type of optimization there? How complex will it be?

This shouldn't be any more complex than many other things already happening in IRBuilder. I imagine it will be similar to what you are currently doing to support pops nested in unnamed blocks. I can implement and land this first to prevent even temporary round-trip regressions.

Prune and coalesce locals after StackIR - removes locals from the function header when StackIR has optimized them out (-0.57% size geomean)

This is independent, I think, of input params? Definitely useful!

Yes, this is independent. Using input parameters just means there are a few more locals that can be optimized out this way.

@tlively

tlively commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

@kripken, all the preliminary IRBuilder changes have landed, so this should be ready for another look.

@kripken

kripken commented Nov 18, 2026

Copy link
Copy Markdown
Member

Did the landings so far prevent round-trip regressions as we hoped? If so, is there a test that verifies that?

@tlively

tlively commented Nov 18, 2026

Copy link
Copy Markdown
Member Author

Did the landings so far prevent round-trip regressions as we hoped? If so, is there a test that verifies that?

Yes! They work quite well. The tests will be in the next PR, since this one doesn't actually start emitting block parameters yet.

Comment thread src/ir/module-utils.cpp
// Whether StackIR is available for the function being scanned, in which case
// control flow signatures have already been collected from StackIR and should
// not be collected again from the Binaryen IR control flow nodes.
bool hasStackIR;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am having trouble understanding the model here. StackIR has never been read outside of wasm-stack-opts.cpp. In this new approach, it is..? Is this new design documented somewhere?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In particular, Stack IR can get out of sync etc., and is thrown out in various circumstances, and it isn't clear to me how all that works in a world where Stack IR is read during the main pipeline.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stack IR is still not read during the main pipeline. It is newly passed here, but only from Print.cpp and wasm-binary.cpp, which already had access to Stack IR.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But this is used in collectHeapTypeInfo which is used from many places during the main pipeline?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, but all those places pass the default nullptr for the ModuleStackIR* argument.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, now I see, thanks.

@kripken kripken left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, now I am starting to get the general idea here. Nice approach, to use Stack IR in this way! Some more comments as I am still reading.

Comment thread src/ir/module-utils.cpp Outdated
Comment on lines +422 to +424
// Whether StackIR is available for the function being scanned, in which case
// control flow signatures have already been collected from StackIR and should
// not be collected again from the Binaryen IR control flow nodes.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should perhaps replace "whether StackIR is available" with "whether StackIR is available and should be used" because it is possible that during the main pipeline we have StackIR, but are not using it. And add "It is only safe to use StackIR during binary generation, not the main optimization pipeline (as it may get stale)"

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since #6568, Function and Module do not store StackIR at all; ModuleStackIR is only constructed transiently inside WasmBinaryWriter::prepare() and PrintSExpression::generateStackIR() and destroyed immediately afterward, so there is no persistent StackIR that could go stale. Tweaked this comment slightly to 'Whether StackIR is being used...' and documented the stackIR precondition on collectHeapTypeInfo in src/ir/module-utils.h.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh thanks, I forgot that refactor...

Comment thread src/ir/module-utils.cpp Outdated
}
void visitTryTable(TryTable* curr) {
info.noteControlFlow(Signature(Type::none, curr->type));
if (!hasStackIR) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we do this repetitive operation inside noteControlFlow or a trampoline on the path to it? That would avoid duplication and make us safe when we add new control flow structures later.

If that doesn't work, can we assert inside noteControlFlow that !hasStackIR?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can't do this check (whether as an assertion or not) inside noteControlFlow because noteControlFlow is used both from the non-StackIR paths here and also from the new StackIR path below. I've factored this into a maybeNoteControlFlow helper, though.

Comment thread src/ir/module-utils.cpp Outdated
inst->op == StackInst::IfBegin ||
inst->op == StackInst::LoopBegin ||
inst->op == StackInst::TryBegin ||
inst->op == StackInst::TryTableBegin) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we can add a helper isControlFlowBegin to avoid hardcoding this list here?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Comment thread src/ir/module-utils.h
TypeInclusion inclusion = TypeInclusion::AllTypes,
VisibilityHandling visibility = VisibilityHandling::NoVisibility);
VisibilityHandling visibility = VisibilityHandling::NoVisibility,
const ModuleStackIR* stackIR = nullptr);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a comment on the meaning of the new param here, which I think is less obvious than the prior ones. In particular when it is safe to pass it in, is important at the API level.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

@kripken kripken left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great, thanks! Sorry for my confusion before but I think this PR is now in a really nice and clear place.

@tlively
tlively enabled auto-merge (squash) November 19, 2026 19:05
@tlively
tlively merged commit 489f708 into main Nov 19, 2026
18 checks passed
@tlively
tlively deleted the stack-ir-param-types branch November 19, 2026 19:18
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.

2 participants