-
Notifications
You must be signed in to change notification settings - Fork 6.3k
Add Peephole Optimization for Function Selector Guard #16315
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: develop
Are you sure you want to change the base?
Add Peephole Optimization for Function Selector Guard #16315
Conversation
strictly should be boolean
with unit test
with unit test removed unneeded comments
with unit test
with unit tests
focus on source level no inline assembly
|
Thank you for your contribution to the Solidity compiler! A team member will follow up shortly. If you haven't read our contributing guidelines and our review checklist before, please do it now, this makes the reviewing process and accepting your contribution smoother. If you have any questions or need our help, feel free to post them in the PR or talk to us directly on the #solidity-dev channel on Matrix. |
…to philippecyberian/peepholes
Summary
This PR introduces a new peephole optimization that simplifies and reduces the bytecode for Solidity’s function selector guard emitted in the dispatcher of every contract.
The standard guard:
is replaced with its shorter logically equivalent form:
This optimization is safe, local, and formally verified.
Motivation
The function selector guard exists in essentially every Solidity contract.
This PR saves:
1 byte of deployed runtime code (≈ 200 gas)
2 gas per external call (based on execution measured via
evmone)Eliminates
ISZEROand avoids one stack element.The optimization applies only when the canonical dispatcher pattern is recognized and the pattern appears immediately after a
Tag. This ensures no interference with ABI decoding, length checks, or string/memory operations.Formal Equivalence
The replacement is proven equivalent by demonstrating:
An SMT formulation in Z3 confirms no counterexamples exist:
A formal proof sketch (stack transformer equivalence and algebraic equivalence) is included in the Issue:
👉[GitHub Issue #16316]
Changes Included
New peephole optimization:
FunctionSelectorGuardRestriction: pattern applies only immediately after
TagUnit test verifying:
rewrite occurs in valid canonical case
rewrite is suppressed when pattern is incomplete or misplaced
Measurements demonstrating bytecode and gas savings
Gas & Size Savings Summary
Request for Review
I would appreciate review focus on:
Pattern matching constraints (only following
Tag)Interaction with future dispatcher variants or EOF changes
Placement order within the peephole optimizer list
Any additional edge cases to include in testing
This PR is intended to be minimal, safe, and consistent with existing peephole optimizations.