Skip to content

JIT: don't fold Bnd - X using facts about a loop-varying bound - #137956

Open
AndyAyersMS wants to merge 10 commits into
dotnet:mainfrom
AndyAyersMS:jit-phi-range-137674
Open

AndyAyersMS wants to merge 10 commits into
dotnet:mainfrom
AndyAyersMS:jit-phi-range-137674

Conversation

@AndyAyersMS

@AndyAyersMS AndyAyersMS commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

GetBoundMinusXRange folds compares like span.Length - i < 0 by finding a range for i relative to the bound. To do that it walks i's SSA definitions around the loop. If the bound can change from one iteration to the next, that walk can erroneously relate i to 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

  • First try to bound i using only facts that hold at the compare: live assertions, plus what i's value number implies (e.g. a length is never negative). This reuses GetRangeFromAssertions, with a new overload that takes a preferred bound.
  • Fall back to the SSA walk only when the bound is invariant in every loop whose header PHI i can reach. The new optIsBoundInvariantInLoopsOf checks each such loop with optVNIsLoopInvariant.
  • Bail out to assertion-only reasoning if the method has irreducible cycles, since those are not natural loops.
  • Assertion prop runs after RBO and CSE. By then m_loops has 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:
    • ValueNumStore records those loops.
    • BlockToNaturalLoopMap is now keyed by bbID rather than bbPostorderNum, 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".
    • Since JIT: rebuild SSA and VN after RBO jump threading #137972, jump threading rebuilds DFS, loops, SSA and VN. The remaining flow changes after VN only remove edges, so the VN-time loops can only over-approximate the current loops.
    • Blocks created after VN, and unknown loop indices, are treated as loop variant, and assert in checked builds.

Testing

  • Runtime_137674 covers 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).
  • Egor's vectorized Sum example compiles to the same code as on main, with no bounds checks.
  • SuperPMI asmdiffs, windows x64, all collections, vs main (9899e0b): no replay failures, about 500 contexts with diffs, net roughly -6.5 KB. Regressions I looked at are methods where the bound does vary across iterations (e.g. FileSystemName.EscapeExpression, which re-slices its span each iteration); many involve checked-CoreLib Debug.Asserts. Not all regressions were inspected.
  • Throughput vs main: within ±0.02% in every collection.

Resolves #137674

Note

This change and PR description were prepared with GitHub Copilot.

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
@github-actions github-actions Bot added the area-CodeGen-coreclr CLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI label Nov 20, 2026
@azure-pipelines

Copy link
Copy Markdown
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.

@AndyAyersMS
AndyAyersMS requested a balanced review from Copilot November 20, 2026 00:02
@AndyAyersMS

Copy link
Copy Markdown
Member Author

@EgorBo ptal
fyi @dotnet/jit-contrib

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 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

@EgorBo

EgorBo commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

@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;
}

@AndyAyersMS

Copy link
Copy Markdown
Member Author

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.

AndyAyersMS and others added 2 commits November 20, 2026 07:47
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
@AndyAyersMS

AndyAyersMS commented Nov 23, 2026 •

Copy link
Copy Markdown
Member Author

@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.

@AndyAyersMS
AndyAyersMS requested review from EgorBo and a balanced review from Copilot November 24, 2026 01:43

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Loop-carried array-length bounds can still bypass the guard, allowing a previous iteration’s length to incorrectly fold the negative-subtraction check.

1 open issue

Review effort: Balanced

Comment thread src/coreclr/jit/assertionprop.cpp Resolved
@EgorBo

EgorBo commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

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

bndVN is ARR_LENGTH(phi) in the first case and a load through a memory phi in the second, so IsPhiDef(bndVN) is false and the slow SSA walk still runs. So the Copilot comment on this line is valid.

Making the check transitive (any phi, memory phi or MemOpaque reachable from bndVN) isn't enough. It fixes both cases but regresses the Sum example from my earlier comment: on win-x64 the span is an implicit byref, so its length load counts as variant and the span.Length - i >= 0 / >= 4 checks come back. It looks like the real condition is "bndVN is invariant in the loop whose phi cycle the walk crosses", and that probably belongs in RangeCheck's phi handling, not only in GetBoundMinusXRange.

Smaller things:

  • The phi path rebuilds what GetRangeFromAssertions already does (type range, never-negative lower limit, MergeEdgeAssertions). Reusing it, with a preferred-bound overload if needed, would avoid making MergeEdgeAssertions public.

With the current PR, Sum (from #137956 (comment)) has no bounds checks, so that part looks good.

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
@AndyAyersMS

Copy link
Copy Markdown
Member Author

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 m_loops is cleared post-RBO).

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 fgMorphTree)... I believe this is the case, but there's nothing guaranteeing this.

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.

AndyAyersMS and others added 4 commits November 25, 2026 09:35
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
@AndyAyersMS

Copy link
Copy Markdown
Member Author

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.

@AndyAyersMS AndyAyersMS changed the title JIT: avoid treating phi bounds as loop invariant JIT: don't fold Bnd - X using facts about a loop-varying bound Nov 27, 2026
@AndyAyersMS
AndyAyersMS requested a balanced review from Copilot November 27, 2026 17:19

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 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

Comment thread src/coreclr/jit/assertionprop.cpp Resolved
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
@AndyAyersMS

AndyAyersMS commented Nov 28, 2026 •

Copy link
Copy Markdown
Member Author

@EgorBo take another look...

diffs

@EgorBo

EgorBo commented Nov 30, 2026

Copy link
Copy Markdown
Member

The (uint)X > (uint)Bnd path in optAssertionPropGlobal_RelOp has the same problem. It still does the slow SSA walk with op2VN as the preferred bound and doesn't check invariance. This returns 5 instead of 105 with both main and this PR (checked JIT, win-x64):

[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

Span.Slice takes the same path. Replacing the if with try { sum += span.Slice(i).Length; } catch (ArgumentOutOfRangeException) { sum += 100; } returns 0 instead of 101 on main. With this PR it hits Assertion failed. length >= 0 in checked CoreLib.

As a quick check, I added optIsBoundInvariantInLoopsOf(op1VN, op2VN) to that condition, and both cases then returned the expected values. It's probably better to handle it like GetBoundMinusXRange: try assertions first, then do the SSA walk only when the bound is invariant. Could you add both cases to Runtime_137674?

Minor:

  • The new GetRangeFromAssertions overload only adds the MergeEdgeAssertions step. An optional preferredBoundVN parameter on the existing overload might be simpler.
  • A short comment in optIsBoundInvariantInLoopsOf would help. It should say that its VN walk must cover every phi the RangeCheck SSA walk can reach, since the fix depends on that.

@EgorBo

EgorBo commented Nov 30, 2026

Copy link
Copy Markdown
Member

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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-CodeGen-coreclr CLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

JIT: (bug) Assertion prop folds span.Length - i < 0 to false when span is reassigned in a loop

3 participants