solidity
solidity copied to clipboard
Add Peephole Optimization for Function Selector Guard
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:
FunctionSelectorGuard -
Restriction: pattern applies only immediately after
Tag -
Unit 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
| Category | Before | After | Savings |
|---|---|---|---|
| Bytes in guard | 5 | 4 | -1 byte |
| Deployment gas | – | – | ~200 gas |
| Execution gas | 11 gas | 8 gas | 3 gas theoretical / 2 gas observed |