Skip to content

JIT can't elide span.Slice range checks after a manual check #112953

Closed

Description

@MihaZupan

https://godbolt.org/z/hjqc5rodx

For a case like this:

public static ReadOnlySpan<char> Test(ReadOnlySpan<char> span, int offset)
{
    if ((uint)offset < (uint)span.Length)
    {
        return span.Slice(offset + 1);
    }
    
    return span;
}

public ReadOnlySpan<T> Slice(int start)
{
if ((uint)start > (uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException();
return new ReadOnlySpan<T>(ref Unsafe.Add(ref _reference, (nint)(uint)start /* force zero-extension */), _length - start);
}

The JIT isn't removing the if ((uint)start > (uint)_length) check.

You can hit that in IndexOf + slice loops, e.g.

int count = 0;
int pos;
while ((uint)(pos = span.IndexOf(c)) < (uint)span.Length)
{
    count++;
    span = span.Slice(pos + 1);
}

Activity

  1. added
    area-CodeGen-coreclr
    on Feb 26, 2025
  2. added
    untriaged
    on Feb 26, 2025
  3. dotnet-policy-service commented on Feb 26, 2025

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
    See info in area-owners.md if you want to be subscribed.

  4. self-assigned this
    on Feb 26, 2025
  5. added this to the Future milestone on Feb 26, 2025
  6. removed
    untriaged
    on Feb 26, 2025
  7. EgorBo commented on Feb 26, 2025

    @EgorBo
    Member

    Hopefully, should be handled by the PRs I'm currently working on (e.g. #112907 + #112824 + more changes)

  8. added
    in-pr
    on Feb 28, 2025
  9. tannergooding commented on Apr 28, 2025

    @tannergooding
    Member

    @EgorBo can this be closed now?

  10. EgorBo commented on May 2, 2025

    @EgorBo
    Member

    @EgorBo can this be closed now?

    Nope, still needs work

  11. modified the milestones: Future, 11.0.0 on May 12, 2026
  12. modified the milestones: 11.0.0, 12.0.0 on Jul 30, 2026
  13. added a commit that references this issue on Oct 29, 2026
    aa1a3d6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclrin-pr

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions