Skip to content

Redundant bounds check #121259

@EgorBo

Description

@EgorBo

The following snippet produces a redundant bounds check:

void Test(ReadOnlySpan<char> name)
{
    int length = name.Length;
    if (length == 0)
    {
        return;
    }
    if (length == 1)
    {
        if (name[0] == ':')
        {
            return;
        }
    }
    else if (name[0] == ':' && name[1] != ':')
    {
        return;
    }
}

Codegen:

; Method Program:Test(System.ReadOnlySpan`1[char]):this (FullOpts)
       sub      rsp, 40
       mov      rax, bword ptr [rdx]
       mov      ecx, dword ptr [rdx+0x08]
       test     ecx, ecx
       je       SHORT G_M56625_IG05
       cmp      ecx, 1
       je       SHORT G_M56625_IG04
       cmp      word  ptr [rax], 58
       jne      SHORT G_M56625_IG05
       cmp      ecx, 1
       jbe      SHORT G_M56625_IG06
       jmp      SHORT G_M56625_IG05
G_M56625_IG04:
       cmp      word  ptr [rax], ax
G_M56625_IG05:
       add      rsp, 40
       ret      
G_M56625_IG06:
       call     CORINFO_HELP_RNGCHKFAIL
       int3     
; Total bytes of code: 46

It's actually a simplified version of:

if (name is [] or [':'] or [':', not ':', ..])
{
}

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMIreduce-unsafe

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions