Skip to content

Bounds checks: multiple monotonically increasing counters (within bounds) #116238

Open

Description

@EgorBo

A popular loop pattern when there are two (or more) monotonically increasing counters, unfortunately, JIT doesn't optimize bounds checks for them.

public int DecodeBytes_safe(Span<byte> buffer)
{
    int j = 0;
    for (int i = 0; i < buffer.Length; i++)
    {
        // e.g. under some condition
        buffer[j++] = 0;
    }
    return j;
}

Current codegen:

; Method Progam:DecodeBytes_safe(System.Span`1[ubyte]):int:this (FullOpts)
G_M20838_IG01:  ;; offset=0x0000
       sub      rsp, 40
G_M20838_IG02:  ;; offset=0x0004
       mov      rax, bword ptr [rdx]
       mov      ecx, dword ptr [rdx+0x08]
       xor      edx, edx
       test     ecx, ecx
       jg       SHORT G_M20838_IG06
G_M20838_IG03:  ;; offset=0x0010
       mov      r10d, edx
G_M20838_IG04:  ;; offset=0x0013
       mov      eax, r10d
G_M20838_IG05:  ;; offset=0x0016
       add      rsp, 40
       ret      
G_M20838_IG06:  ;; offset=0x001B
       mov      r8d, ecx
       align    [2 bytes for IG07]
G_M20838_IG07:  ;; offset=0x0020
       lea      r10d, [rdx+0x01]
       cmp      edx, ecx
       jae      SHORT G_M20838_IG09
       mov      edx, edx
       mov      byte  ptr [rax+rdx], 0
       dec      r8d
       je       SHORT G_M20838_IG04
G_M20838_IG08:  ;; offset=0x0033
       mov      edx, r10d
       jmp      SHORT G_M20838_IG07
G_M20838_IG09:  ;; offset=0x0038
       call     CORINFO_HELP_RNGCHKFAIL
       int3     
; Total bytes of code: 62

Activity

  1. added
    untriaged
    on Jun 3, 2025
  2. added
    area-CodeGen-coreclr
    on Jun 3, 2025
  3. added this to the Future milestone on Jun 3, 2025
  4. added and removed
    untriaged
    on Jun 3, 2025
  5. dotnet-policy-service commented on Jun 3, 2025

    @dotnet-policy-service
    Contributor

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

  6. jakobbotsch commented on Jun 3, 2025

    @jakobbotsch
    Member

    That's something that a bounds checks elimination pass based on SCEVs would be able to handle.

  7. EgorBo commented on Jun 3, 2025

    @EgorBo
    MemberAuthor

    That's something that a bounds checks elimination pass based on SCEVs would be able to handle.

    Yeah I was about to ping you about it

  8. changed the title [-]Bounds checks: multiple monotonically increasing counters (withing bounds)[/-] [+]Bounds checks: multiple monotonically increasing counters (within bounds)[/+] on Jun 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-CodeGen-coreclrreduce-unsafe

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions