Bounds checks: multiple monotonically increasing counters (within bounds)

Open
#116,238 3 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
30/100
Issue type
Feature
Clarity
Needs clarification
Activity status
Stale
Tech stack
csharp

Research direction

Start with the DecodeBytes_safe sample and compare its current generated assembly with the bounds-check behavior described in the issue. Investigate the JIT area responsible for optimizing multiple monotonically increasing counters; done means the generated loop no longer retains the unnecessary bounds check while preserving the required range-check failure behavior.

Written by the indexing model from the issue text.

Description

area-CodeGen-coreclr reduce-unsafe

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

Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from dotnet/runtime

All issues in dotnet/runtime

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.