Repository navigation
JIT: don't fold Bnd - X using facts about a loop-varying bound - #137956
AndyAyersMS wants to merge 10 commits into
Conversation
A loop-carried phi can change each iteration, leading range analysis to fold comparisons incorrectly. Avoid the bound-minus-index fold for phi bounds, and add a regression test. Resolves dotnet#137674 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 6f34605e-ac72-4292-9874-90760d4f0337
|
Azure Pipelines: Successfully started running 5 pipeline(s). 10 pipeline(s) were filtered out due to trigger conditions. There may be pipelines that require an authorized user to comment /azp run to run. |
|
@EgorBo ptal |
There was a problem hiding this comment.
🟢 Approval recommended
No active review issues were reported for the phi-bound range-analysis change and its regression test.
No open issues 🎉
What changed in this PR
This PR addresses incorrect JIT comparison folding when a loop-carried phi bound changes between iterations.
Changes:
- Conservatively skips the specialized bound-minus-index range analysis for phi bounds, while leaving other folding paths available.
- Adds a regression test that replaces a span during iteration and verifies the correct result of
105.
| File | Description |
|---|---|
src/tests/JIT/Regression_ro_2/Runtime_137674.cs |
Adds coverage for a span length that changes between loop iterations. |
src/coreclr/jit/assertionprop.cpp |
Returns an unknown range for phi bounds in the specialized subtraction analysis. |
Review effort: Balanced
|
@AndyAyersMS that is quite a lot of regressions - are we sure all of them a correctness issues? I fear this might break the optimized bound checks that I am relying on to remove unsafe code, e.g. can you check that this PR doesn't introduce bound checks in public static int Sum(ReadOnlySpan<int> span)
{
Vector128<int> vSum = default;
// Main loop
int i;
for (i = 0; i < span.Length - Vector128<int>.Count; i += Vector128<int>.Count)
vSum += Vector128.Create(span[i..]);
// Horizontal sum
int sum = Vector128.Sum(vSum);
// Trailing elements
for (; i < span.Length; i++)
sum += span[i];
return sum;
} |
|
Yeah, agree. More than I expectedl I only was looking at an SPMI subset before. We can be a bit more aggressive, let me see if that reduces some of the regressions. |
When the bound is a loop-carried phi, derive the index range from assertions live at the subtraction, plus never-negative facts. Fall back to the SSA walk only if the phi is defined outside the index loop. This removes most of the codegen churn from the earlier fix. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 6f34605e-ac72-4292-9874-90760d4f0337
For loop-carried bounds, derive the index range only from facts valid at that point rather than walking its SSA cycle. This keeps the dotnet#137674 fix while reducing the implementation and accepting a small increase in checked-build codegen diffs. Resolves dotnet#137674 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 6f34605e-ac72-4292-9874-90760d4f0337
|
@EgorBo last two commits should regain most of the optimizations. There is more we could do beyond this, eg looking at the loop variance of the phi defs. Your example above was optimized in both the original PR and with the new changes. |
|
The fix doesn't cover bounds that are derived from a loop-carried value instead of being a phi themselves. With this PR's checked JIT these two variants still return 5 instead of 105: [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
static int TestArr(int[] span, int[] repl)
{
int i = 0, sum = 0;
while (true)
{
if (span.Length - i < 0) sum += 100;
if (i >= span.Length) return sum;
sum += span[i];
i++;
span = repl;
}
}
static int[] s_arr, s_repl;
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
static int TestStatic()
{
int i = 0, sum = 0;
while (true)
{
int[] a = s_arr;
if (a.Length - i < 0) sum += 100;
if (i >= a.Length) return sum;
sum += a[i];
i++;
s_arr = s_repl;
}
}
// TestArr(new int[] { 5 }, new int[0]) == 105
// s_arr = new int[] { 5 }; s_repl = new int[0]; TestStatic() == 105
Making the check transitive (any phi, memory phi or Smaller things:
With the current PR, |
The previous fix only guarded bounds that are themselves phis, so a bound derived from a loop-carried value (eg the length of a loop-carried array, or a static reloaded each iteration) could still be related to the wrong iteration's value. Use current assertions first, and only walk X's SSA defs when the bound is invariant in every loop whose header phi X can reach. Reuse GetRangeFromAssertions with a preferred bound for the assertion-only path. Add array and static field cases to the regression test. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 6f34605e-ac72-4292-9874-90760d4f0337
|
I think this maybe should wait for #137972 -- if we want to reason about loops during AP we need to be confident flow alterations made between VN and AP's loop examination don't cause us to make bad deductions. With #137972, we can be (mostly*) confident that all that has happened is that edges have been removed, so the loop structure VN saw is a conservative approximation of the loops that remain (in particular it at worst overstates which blocks are loop headers), and we can query VN's own cached loop data (since the canonical Without #137972, jump threading complicates the flow and we can't be confident that we know which blocks are loop headers (and even if we rebuilt loops, VN's loop invariance will be based on a possibly different loop structure). (*mostly) because we also need to ensure no new blocks are created or edges re-routed (say via One other possible gotcha is that the loop structure doesn't represent all forms of recurrence, so we may also need to consider irreducible flow. I need to think about that more. |
Irreducible cycles are not natural loops, so the loop invariance check could not see them and allowed the SSA walk for bounds that change across their iterations. Bail out to assertion-only reasoning when the VN loop structure has improper headers, and add irreducible span and array cases to the test. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 6f34605e-ac72-4292-9874-90760d4f0337
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 6f34605e-ac72-4292-9874-90760d4f0337
Assertion prop consults the loops computed for value numbering after RBO and CSE. CSE's incremental SSA may recompute the DFS and renumber blocks, and the block to loop map and loop membership queries were keyed by bbPostorderNum, so renumbered blocks looked like they were outside every loop and loop-variant bounds could be treated as invariant. Key BlockToNaturalLoopMap by bbID and answer membership by walking parent loops. Record the VN loops in ValueNumStore, and treat blocks created after VN or unknown loop indices as loop variant, with asserts. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 6f34605e-ac72-4292-9874-90760d4f0337
|
In this latest sequence of commits, we now will use the VN based loop structure to check the loop-variance of VNs. This loop structure is potentially stale but should be conservatively correct (the only troublemaker currently was jump threading, and we now rebuild VN after that), and we assert that at least no new blocks are queried and handle them conservatively in release. Also that the VN map and loops were created by the most recent VN pass. We also bail if there were irreducible loops and I added test cases showing that this is necessary. For stability the block to loop map must now be keyed off of bbID instead of dfs numbers, since later phases may rerun dfs. |
There was a problem hiding this comment.
🟡 Changes recommended
The assertion-propagation walk treats raw loop indices as value numbers, allowing MemOpaque(UnknownLoop) to cause out-of-bounds VN access and crash compilation.
1 open issue
1 resolved since last review
Review effort: Balanced
MemOpaque's argument and MapStore's 4th argument are loop indices, not value numbers, so treating them as VNs in the bound invariance walk could index past the VN store (eg for UnknownLoop). Skip them, as optVNIsLoopInvariant does. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 6f34605e-ac72-4292-9874-90760d4f0337
|
The [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
static int Test(ReadOnlySpan<int> span, ReadOnlySpan<int> repl)
{
int i = 0, sum = 0;
while (true)
{
if ((uint)i > (uint)span.Length) sum += 100;
if (i >= span.Length) return sum;
sum += span[i];
i++;
span = repl;
}
}
// Test(new int[] { 5 }, new int[0]) == 105
As a quick check, I added Minor:
|
|
btw, other than non-covered case and the nits, i'm fine with this change - up to you how to handle the non-covered scenario, could be a follow up or in this PR |

GetBoundMinusXRangefolds compares likespan.Length - i < 0by finding a range forirelative to the bound. To do that it walksi's SSA definitions around the loop. If the bound can change from one iteration to the next, that walk can erroneously relateito a previous iteration's bound. The compare is then folded incorrectly (#137674).Earlier versions of this PR only guarded bounds whose value number is itself a PHI: first by skipping the fold, then by relying only on assertions. The first approach caused a lot of codegen churn, and both missed bounds that are derived from loop-carried values. Examples include the length of an array local that is reassigned in the loop, and a static that is reloaded each iteration. Both were pointed out in review.
Changes
iusing only facts that hold at the compare: live assertions, plus whati's value number implies (e.g. a length is never negative). This reusesGetRangeFromAssertions, with a new overload that takes a preferred bound.ican reach. The newoptIsBoundInvariantInLoopsOfchecks each such loop withoptVNIsLoopInvariant.m_loopshas been cleared, and the DFS may have been recomputed (for example by incremental SSA in CSE). So these queries use the loops computed by the most recent value numbering, which are also the loops that memory and opaque VNs are tagged with:ValueNumStorerecords those loops.BlockToNaturalLoopMapis now keyed bybbIDrather thanbbPostorderNum, and membership is answered by walking parent loops. This keeps lookups correct when blocks have been renumbered. Before this change, a renumbered block would read as "not in any loop".Testing
Runtime_137674covers the span, array-parameter, static-field, and irreducible-cycle variants. It fails with the original JIT and passes with this change.Regression_ro_2: 525 passed, 0 failed, 7 skipped (test assembly built before merging current main, so tests added by main since then were not included).Sumexample compiles to the same code as on main, with no bounds checks.FileSystemName.EscapeExpression, which re-slices its span each iteration); many involve checked-CoreLibDebug.Asserts. Not all regressions were inspected.Resolves #137674
Note
This change and PR description were prepared with GitHub Copilot.