Repository navigation
Conversation
c987b2b to
38fd9ac
Compare
16b2cc9 to
30c820c
Compare
|
There was an error when running Please check that your changes are working as intended. |
cba7f5b to
31b25f9
Compare
There was a problem hiding this comment.
Pull request overview
This PR updates the Yul optimizer’s UnusedStoreEliminator pipeline to avoid incorrect mstore removals when the input is not in pseudo-SSA form (notably when function parameters are involved), and adds targeted optimizer tests for the “no SSA transform” scenario described in #16458.
Changes:
- Extend
SSAValueTrackerto treat unassigned function parameters as valid SSA roots when checking SSA-ness transitively through dependencies. - Filter the knowledge-base SSA input used by
UnusedStoreEliminatorto only include expressions that are in SSA form together with their dependencies. - Add a dedicated
unusedStoreEliminatorNoSsaTransformtest step and new Yul tests that exercise the problematic cases.
Reviewed changes
Copilot reviewed 9 out of 9 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
libyul/optimiser/SSAValueTracker.h |
Adds an SSA-with-dependencies query API and tracks function parameters. |
libyul/optimiser/SSAValueTracker.cpp |
Implements dependency-based SSA checking and parameter tracking during AST walk. |
libyul/optimiser/UnusedStoreEliminator.cpp |
Builds the SSA value map using only SSA-safe expressions (with SSA-safe dependencies). |
test/libyul/YulOptimizerTestCommon.cpp |
Adds a new optimizer test step that runs UnusedStoreEliminator without SSATransform. |
test/libyul/yulOptimizerTests/unusedStoreEliminatorNoSsaTransform/mstore_location_reassigned.yul |
New regression test covering non-SSA reassignment affecting mstore location. |
test/libyul/yulOptimizerTests/unusedStoreEliminatorNoSsaTransform/function_parameter_as_mstore_location_unrelated.yul |
New test where parameter-derived store location should be removable (non-overlapping). |
test/libyul/yulOptimizerTests/unusedStoreEliminatorNoSsaTransform/function_parameter_as_mstore_location_covering.yul |
New test where parameter-derived store location must be kept (overlapping return). |
test/libyul/yulOptimizerTests/unusedStoreEliminatorNoSsaTransform/function_parameter_reassinged_as_mstore_location_unrelated.yul |
New test intended to cover reassigned-parameter non-overlap scenario. |
test/libyul/yulOptimizerTests/unusedStoreEliminatorNoSsaTransform/function_parameter_reassinged_as_mstore_location_covering.yul |
New test covering reassigned-parameter overlapping scenario. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
9cf23ac to
7d014ec
Compare
| else | ||
| { | ||
| solAssert(std::holds_alternative<Literal>(*_expression), "Impossible expression type"); | ||
| return true; | ||
| } |
There was a problem hiding this comment.
| else | |
| { | |
| solAssert(std::holds_alternative<Literal>(*_expression), "Impossible expression type"); | |
| return true; | |
| } | |
| solAssert(std::holds_alternative<Literal>(*_expression), "Impossible expression type"); | |
| return true; |
There was a problem hiding this comment.
i don't think the suggestion works
| // let a := add(arg, 1) | ||
| // let b := arg | ||
| // let outLen := 32 | ||
| // mstore(a, 0xAA) |
There was a problem hiding this comment.
This worked before the fix as well, since you're not reassigning arg?
There was a problem hiding this comment.
Yes, but I added function parameters set to the SSAValueTracker, because I need to know them if they are not reassigned and if not they properly close the closed set. This is just a simple test of this.
3ef065c to
df081a5
Compare
bbdfc8c to
b871cd5
Compare
There was a problem hiding this comment.
Please remember that this will need a buglist entry.
Without it the PR is not really finished so it should still be a draft.
There was a problem hiding this comment.
bug list updated. How about the blogpost link? I changed it to draft for now.
There was a problem hiding this comment.
You can leave it unfilled until we know when we're releasing this. URLs are predictable, based on date and title (which should match the bug ID) so we could create one already, but if we do it now, we can easily forget to update the date and we'll end up with a broken link. So for now I'd put in something that clearly looks like a placeholder.
There was a problem hiding this comment.
I used X/Y/Z placeholder for now as it was done in prev cases.
b871cd5 to
8f69008
Compare
8f69008 to
87e9ec9
Compare
d4d524f to
98e3dcf
Compare
|
I removed local benchmarks result and added benchmarks from the benchmark machine. |
Summary:Per-benchmark distribution of the regressionΔ% (target vs baseline) across the 48 benchmarks in each pipeline:
Worst regressionsIR pipeline, cpu_time
evmasm pipeline, cpu_time
DetailsBenchmark results |
| auto cacheIt = m_isSSACache.find(_expression); | ||
| if (cacheIt != m_isSSACache.end()) | ||
| return cacheIt->second; |
There was a problem hiding this comment.
| auto cacheIt = m_isSSACache.find(_expression); | |
| if (cacheIt != m_isSSACache.end()) | |
| return cacheIt->second; | |
| std::optional<bool> cachedSSAStatus = valueOrDefault(m_isSSACache, _expression, std::nullopt); | |
| if (cachedSSAStatus.has_value()) | |
| return *cachedSSAStatus; |
There was a problem hiding this comment.
In that case one could even write
if (std::optional<bool> cachedSSAStatus = valueOrDefault(m_isSSACache, _expression, std::nullopt))
...There was a problem hiding this comment.
Did you check on gcc? This does not compile on clang:
/Users/rodia/projects/solidity/libsolutil/CommonData.h:282:51: error: incompatible operand types ('const std::nullopt_t' and 'bool')
282 | std::is_reference_v<decltype((it == _map.end()) ? std::forward<ValueType>(_defaultValue) : it->second)>,
| ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~
/Users/rodia/projects/solidity/libyul/optimiser/SSAValueTracker.cpp:69:46: note: in instantiation of function template specialization 'solidity::util::valueOrDefault<boost::unordered::unordered_flat_map<const std::variant<solidity::yul::FunctionCall, solidity::yul::Identifier, solidity::yul::Literal> *, bool, std::hash<const std::variant<solidity::yul::FunctionCall, solidity::yul::Identifier, solidity::yul::Literal> *>> &, const std::variant<solidity::yul::FunctionCall, solidity::yul::Identifier, solidity::yul::Literal> *, const std::nullopt_t &, void *>' requested here
69 | std::optional<bool> cachedSSAStatus = util::valueOrDefault(m_isSSACache, _expression, std::nullopt);
There was a problem hiding this comment.
Same error on gcc. Did you have something different in mind?
| for (auto const& param: _funDef.parameters) | ||
| { | ||
| solAssert(!m_values.contains(param.name), "Source needs to be disambiguated."); | ||
| m_values[param.name] = nullptr; |
There was a problem hiding this comment.
This design seems unnecessarily error-prone to me. We might have been better off with disallowing nullptr in setValue() and having two separate methods for marking as "unset" and "known to be zero". Then the code would also be self-explanatory without extra comments.
I'd not change this in this PR but we should consider refactoring it after the fix.
98e3dcf to
997d88d
Compare
| return true; | ||
|
|
||
| // Check cache first | ||
| if (auto const cacheIt = m_isSSACache.find(_expression); cacheIt != m_isSSACache.end()) |
There was a problem hiding this comment.
| if (auto const cacheIt = m_isSSACache.find(_expression); cacheIt != m_isSSACache.end()) | |
| if ( | |
| auto const cacheIt = m_isSSACache.find(_expression); | |
| cacheIt != m_isSSACache.end() | |
| ) |
I'd still much prefer the valueOrDefault() version (or even the original) to this. Those declaration ifs are unreadable to me.
There was a problem hiding this comment.
Not sure how you want to make it compiles. The only solution I was able to find is:
if (std::optional<bool> cachedSSAStatus = util::valueOrDefault(m_isSSACache, _expression, std::optional<bool>{}, util::allow_copy))
return *cachedSSAStatus;
which to be honest looks like shit or rust :)
There was a problem hiding this comment.
Ah, ok, I see the problem. I guess the fact that we want the default to have a different type than the map values (optional<bool> rather than bool) is breaking things. We'd need a new variant specifically for optional like we have with valueOrNullptr() for pointers. Too bad, but not something to solve in this PR. I expected this to be a straightforward suggestion.
Anyway, those ifs are an abomination. Please reformat it as suggested or revert to the original.
cameel
left a comment
There was a problem hiding this comment.
Here are some final remarks from reviewing the tests. Some of them actually seem ineffective because they use constructs that would prevent the store from being eliminated even before the fix. It would be easier to see that if the addition of new tests and the expectation update were not in the same commit.
Also, it seems that the addition of parameter tracking in SSAValueTracker has more visible effects and should be treated as its own change.
There was a problem hiding this comment.
Not something to do here, but just wanted to say that we need this kind of test often enough that we should probably just add a new test case that prints out evmasm output. Or add an option to do so in Yul tests.
| x := add(x, 32) | ||
| let b := x | ||
| let outLen := 32 | ||
| mstore(a, 0xAA) |
There was a problem hiding this comment.
This needs a comment saying that the point of the test is to make sure this mstore survives. In the context of this PR it may be obvious, but not necessarily later, when you see it in isolation. We should make it easy to tell if the test is still correct when updating expectations in bulk.
There was a problem hiding this comment.
Also, that would be easier to verify in Yul output. Why is optimized Yul output enough in yul_optimizer_unused_store_eliminator_without_ssa_transform but not here? Or is it simply that it's much longer?
There was a problem hiding this comment.
Do you mean --ir-optimized? If so, I’m not sure if it always has semantically the same output. For example when generating yul using --ir-optimized the inline assembly code gets wrapped int a function, but for --asm it’s directly in the sub_0: assembly { block.
There was a problem hiding this comment.
It should be semantically equivalent enough, in the sense that the mstore() should not just randomly disappear, regardless of how the code is embedded. So if the bug is fixed, the effects should be visible in --ir-optimized.
| x := calldataload(32) | ||
| let a := add(x, 32) | ||
| let b := x | ||
| let outLen := 32 | ||
| mstore(a, 0xAA) |
There was a problem hiding this comment.
It would be helpful to have a short comment in each test indicating whether a removal is expected or not.
| x := calldataload(32) | |
| let a := add(x, 32) | |
| let b := x | |
| let outLen := 32 | |
| mstore(a, 0xAA) | |
| x := calldataload(32) // Reassignment; breaks tracking of dependent variables | |
| let a := add(x, 32) | |
| let b := x | |
| let outLen := 32 | |
| mstore(a, 0xAA) // Unused, no overlap with [b, b+outLen] |
| function g() -> r1, r2 | ||
| { | ||
| r1 := calldataload(0) | ||
| r2 := calldataload(32) |
There was a problem hiding this comment.
I think you meant this?
| r2 := calldataload(32) | |
| r2 := add(calldataload(0), 32) |
Otherwise this is a case where we would not be able to remove the mstore even without the multi-assignment. calldataload(0) and calldataload(32) are completely independent and can be anything. It's basically [X, Y) vs [X+32, X+64) situation. These have to be treated as an overlap because an Y that would make it overlap exists.
There was a problem hiding this comment.
OK, but it does not change anything. The USE analyses only current function body and additionally SSAValueTracker never adds multi-variable declaration to the tracked values.
There was a problem hiding this comment.
The test is pointless if the mstore() can't be removed. You're saying that it's pointless anyway because there's one more factor that prevents removal?
This sounds like we can't really create an effective test for this case.
| sstore(arg, value) | ||
| arg := add(arg, 1) | ||
| let value1 := add(value, 1) | ||
| sstore(arg, value1) |
There was a problem hiding this comment.
The assignment of arg is not the only reason this cannot be eliminated. arg and arg+1 are distinct slots so the first sstore is not redundant.
Same in indirect() below.
There was a problem hiding this comment.
Can you also add this case for LoopInvariantCodeMotion?
{
let x := calldataload(0)
let b := x
for { let i := 1 } iszero(eq(i, 10)) { i := add(i, 1) } {
let inv := add(b, 42)
x := add(x, 32)
}
}This is the equivalent of the same case that causes the bug in UnusedStoreEliminator, i.e. code that has SSA variables whose value depends on non-SSA variables.
For a moment I thought that we may have the same bug in LoopInvariantCodeMotion, because it also depends on SSAValueTracker's checking whether a variable is SSA and our fix only adjusts UnusedStoreEliminator. Turns out it's safe because the bug only results in the tracked value being wrong, not in non-SSA variables being misdetected and LoopInvariantCodeMotion does not care about the value - only that it does not change in the loop. In the example above b has the SSA property even though x, which it depends on does not. This means that moving inv before the loop is safe.
|
Changes related to function parameters tracking separated to #16959. |
There was a problem hiding this comment.
🔵 Needs a closer look
It changes core optimizer soundness logic in a way that can affect compilation correctness across many patterns, so it warrants final human review despite the added regression tests.
Review details
- Files reviewed: 30/30 changed files
- Comments generated: 0 new
- Review effort level: Lite
blishko
left a comment
There was a problem hiding this comment.
I am a bit worried that we are treating the symptom and not the underlying cause of this issue.
The underlying problem to me seems to be the use of KnowledgeBase in its "SSA" mode by UnusedStoreEliminator.
As you have correctly noticed, "SSA" mode works correctly only if any of a value's dependencies are never re-assigned.
It seems to me a better fix would be to use the "non-SSA" mode of the KnowledgeBase, rather then discarding all values then have non-SSA dependency.
With the fix, we are losing some valid optimizations, which is a bit unfortunate.
| function f(arg) | ||
| { | ||
| let b := arg | ||
| arg := add(arg, 32) | ||
| let outLen := 32 | ||
| mstore(arg, 0xAA) | ||
| return(b, outLen) | ||
| } | ||
| } | ||
|
|
||
| // ---- | ||
| // step: unusedStoreEliminatorNoSsaTransform | ||
| // | ||
| // { | ||
| // function f(arg) | ||
| // { | ||
| // let b := arg | ||
| // arg := add(arg, 32) | ||
| // let outLen := 32 | ||
| // mstore(arg, 0xAA) | ||
| // return(b, outLen) | ||
| // } |
There was a problem hiding this comment.
In this case, it would be OK (and desirable) to actually eliminate the mstore, no?
| let x := calldataload(0) | ||
| x := calldataload(32) // Reassignment; breaks tracking of dependent variables | ||
| let a := add(x, 32) | ||
| let b := x | ||
| let outLen := 32 | ||
| mstore(a, 0xAA) // Unused, no overlap with [b, b+outLen] | ||
| return(b, outLen) | ||
| } | ||
| // ---- | ||
| // step: unusedStoreEliminatorNoSsaTransform | ||
| // | ||
| // { | ||
| // let x := calldataload(0) | ||
| // x := calldataload(32) | ||
| // let a := add(x, 32) | ||
| // let b := x | ||
| // let outLen := 32 | ||
| // mstore(a, 0xAA) | ||
| // return(b, outLen) |
There was a problem hiding this comment.
In this case, it would be OK (and desirable) to actually eliminate the mstore, no?
Expectations reflect behavior before the isSSAWithDependencies fix (but after function-parameter tracking, which now lands first): USE still incorrectly removes a handful of stores here. The next commit updates these same expectations to show what the fix changes. Co-authored-by: Nikola Matić <nikola.matic@ethereum.org>
Updates the expectations added in the previous commit: USE no longer incorrectly removes stores whose location can't be proven safe once a dependency has been reassigned outside of SSA form. Co-Authored-By: Nikola Matić <nikola.matic@ethereum.org>
|
We decided to merge this as it is, but I made additional analysis in the context of the new, better implementation of the knowledge base which was pushed recently. As a result I prepared an alternative solution which also resolves the issue with the loop-carried dependency reported by the team and also recently by a couple of independent ppl. The solution can be found here. It’s a draft because I haven’t updated the change log and the bug list yet. |
SSAValueTrackerimplementation has changed to support also variables which are functions parameters. Previous implementation omitted function parameters because they do not have default value.SSAValueTrackersupported only variables which are initialised, directly in the code or by default value. Functions return variables are set to0, but function parameters have values passed by the caller. Additional set is added to store function parameters which are not assigned in the function body. This change allowed to implement function which filters out variables which (with their dependencies) are not in SSA form. It's needed to properly define a set which serves as an input to the knowledge base.
Fixes: #16458
Depends on: #16959