Skip to content

[JIT] Redundant Span<> bounds check not elided for fields in ref structs #10645

@Zhentar

Description

@Zhentar

From my review of various issues around bounds checks, the length check here should be sufficient to elide the span's bounds check:

private readonly ReadOnlySpan<int> _colStarts;
public int? TryParseInt(int col)
{
	if ((uint)col < (uint)_colStarts.Length)
	{
		var parseSpan = _span.Slice(_colStarts[col]);

		Utf8Parser.TryParse(parseSpan, out int result, out _);
		return result;
	}

	return null;
}

(Full code available here: https://gist.github.com/Zhentar/6464a6190c0007d83c95634d1a9889ed )

But it is still present in the jitted code, with the latest nightly (CoreCLR 4.6.26709.01, CoreFX 4.6.26606.05), 64bit RyuJIT

DelimitedFileParser.StrictFileParser+SpanLineParser.TryParseInt(Int32)
	push    rdi
	push    rsi
	sub     rsp,58h
	mov     rsi,rcx
	lea     rdi,[rsp+28h]
	mov     ecx,0Ch
	xor     eax,eax
	rep     stos dword ptr [rdi]
	mov     rcx,rsi
;				if ((uint)col < (uint)_colStarts.Length)
;				^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	cmp     dword ptr [rcx],ecx
	lea     r8,[rcx+10h]
	cmp     edx,dword ptr [r8+8]
	jae     M04_L00
;					var parseSpan = _span.Slice(_colStarts[col]);
;					^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	mov     r8,rcx
	cmp     dword ptr [r8],r8d
	add     r8,10h
	cmp     edx,dword ptr [r8+8]
	jae     M04_L02
	mov     r8,qword ptr [r8]
	movsxd  rdx,edx
	mov     edx,dword ptr [r8+rdx*4]
	mov     r8d,dword ptr [rcx+8]
	cmp     edx,r8d
	ja      M04_L01
	mov     rcx,qword ptr [rcx]
	sub     r8d,edx
	movsxd  rdx,edx
	add     rcx,rdx```

category:cq
theme:bounds-checks
skill-level:expert
cost:medium
impact:medium

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMIenhancementProduct code improvement that does NOT require public API changes/additions

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions