Skip to content

JIT doesn't eliminate bounds checks sometimes #11623

@EgorBo

Description

@EgorBo

During dotnet/coreclr#21336 I noticed that JIT doesn't eliminate bounds checks in some cases despite the (uint) pattern, e.g.:

public void WriteBytes(Span<byte> destination)
{
    if ((uint)destination.Length >= 5)
    {
        destination[0] = 1;
        destination[1] = 2;
        destination[2] = 3;
        destination[3] = 4;
        destination[4] = 5;
    }
}

Output:

WriteBytes(System.Span`1)
  | cmp     edx,0
  | jbe     00007ffd`190b6d11
  | mov     byte ptr [rax],1
  | cmp     edx,1
  | jbe     00007ffd`190b6d11
  | mov     byte ptr [rax+1],2
  | cmp     edx,2
  | jbe     00007ffd`190b6d11
  | mov     byte ptr [rax+2],3
  | cmp     edx,3
  | jbe     00007ffd`190b6d11
  | mov     byte ptr [rax+3],4
  | cmp     edx,4
  | jbe     00007ffd`190b6d11
  | mov     byte ptr [rax+4],5
  | add     rsp,28h

but if I change the condition a bit - it might help:
if ((uint)destination.Length >= 5) - remain
if ((uint)destination.Length > 4) - eliminated!
if ((uint)destination.Length == 5) - eliminated!
if (5 <= (uint)destination.Length) - remain

Is it a known issue/feature-request?

TieredJit is disabled
.NET Core 3.0.0-preview-27122-01 (CoreCLR 4.6.27121.03, CoreFX 4.7.18.57103), 64bit RyuJIT

category:cq
theme:range-check
skill-level:intermediate
cost:small

Metadata

Metadata

Assignees

No one assigned

    Labels

    JitUntriagedCLR JIT issues needing additional triagearea-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMIoptimization

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions