Skip to content

[ER] A harder case of missed array bound test elision #85660

@leonardo-m

Description

@leonardo-m

Another common case where LLVM doesn't infer the safety of the array access:

fn copy_to_front_evens(arr: &mut [u32; 100]) {
    let mut pos = 0; // Tortoise
    for i in 0 .. arr.len() { // Hare
        if arr[i] % 2 == 1 {
            arr[pos] = arr[i];
            pos += 1;
        }
    }
}

Compiled with -O it performs a bound test in arr[pos]:

copy_to_front_evens:
	pushq	%rax
	movq	%rdi, %rax
	movl	$1, %ecx
	xorl	%edi, %edi
	jmp	.LBB0_1

.LBB0_7:
	addq	$2, %rcx
	cmpq	$101, %rcx
	je	.LBB0_8

.LBB0_1:
	movl	-4(%rax,%rcx,4), %edx
	testb	$1, %dl
	je	.LBB0_4
	cmpq	$99, %rdi
	ja	.LBB0_9
	movl	%edx, (%rax,%rdi,4)
	addq	$1, %rdi

.LBB0_4:
	movl	(%rax,%rcx,4), %edx
	testb	$1, %dl
	je	.LBB0_7
	cmpq	$99, %rdi
	ja	.LBB0_9
	movl	%edx, (%rax,%rdi,4)
	addq	$1, %rdi
	jmp	.LBB0_7

.LBB0_8:
	popq	%rax
	retq

.LBB0_9:
	leaq	.L__unnamed_1(%rip), %rdx
	movl	$100, %esi
	callq	*core::panicking::panic_bounds_check@GOTPCREL(%rip)
	ud2

I don't know if a back-end like LLVM is supposed to infer complex situations as this one. Perhaps this is the job of explicit code annotations of pre/post-conditions, loop (in)variants, etc.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchI-slowIssue: Problems and improvements with respect to performance of generated code.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions