Skip to content

Redundant bound checks around span.Slice(span.Length - CNS) #127486

@EgorBo

Description

@EgorBo

Found in #127485

int Test(ReadOnlySpan<byte> span)
{
    if (span.Length >= sizeof(int))
        return BinaryPrimitives.ReadInt32BigEndian(span.Slice(span.Length - sizeof(int)));
    return -1;
}

Currently emits:

; Method Bench:Test(System.ReadOnlySpan`1[byte]):int:this (FullOpts)
G_M27777_IG01:  ;; offset=0x0000
       sub      rsp, 40
						;; size=4 bbWeight=1 PerfScore 0.25

G_M27777_IG02:  ;; offset=0x0004
       mov      rcx, bword ptr [rdx]
       mov      edx, dword ptr [rdx+0x08]
       cmp      edx, 4
       jge      SHORT G_M27777_IG05
						;; size=11 bbWeight=1 PerfScore 5.25

G_M27777_IG03:  ;; offset=0x000F
       mov      eax, -1
						;; size=5 bbWeight=0.50 PerfScore 0.12

G_M27777_IG04:  ;; offset=0x0014
       add      rsp, 40
       ret      
						;; size=5 bbWeight=0.50 PerfScore 0.62

G_M27777_IG05:  ;; offset=0x0019
       lea      eax, [rdx-0x04]
       cmp      eax, edx
       ja       SHORT G_M27777_IG07
       mov      r8d, eax
       add      rcx, r8
       sub      edx, eax
       cmp      edx, 4
       jl       SHORT G_M27777_IG08
       movbe    eax, dword ptr [rcx]
						;; size=24 bbWeight=0.50 PerfScore 2.88

G_M27777_IG06:  ;; offset=0x0031
       add      rsp, 40
       ret      
						;; size=5 bbWeight=0.50 PerfScore 0.62

G_M27777_IG07:  ;; offset=0x0036
       call     [System.ThrowHelper:ThrowArgumentOutOfRangeException()]
       int3     
						;; size=7 bbWeight=0 PerfScore 0.00

G_M27777_IG08:  ;; offset=0x003D
       mov      ecx, 40
       call     [System.ThrowHelper:ThrowArgumentOutOfRangeException(int)]
       int3     
						;; size=12 bbWeight=0 PerfScore 0.00
; Total bytes of code: 73

Metadata

Metadata

Assignees

Labels

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

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions