Skip to content

LLVM generates branch soup for array partition point #129530

Closed as not planned
Closed as not planned
@ds84182

Description

@ds84182

I tried this code:

pub fn partition_point_short_array_n<const N: usize>(array: &[usize; N]) -> usize {
    // array.partition_point(|x| *x != 0)
    let mut i = 0;
    while i < N {
        if array[i] == 0 { break }
        i += 1;
    }
    i
}

pub fn partition_point_short_array(array: &[usize; 24]) -> usize {
    partition_point_short_array_n(array)
}

I expected to see this happen: Assembly composed of cmov and/or adox instruction. Or at least mov + je to a single exit branch.

Instead, this happened:

playground::partition_point_short_array:
	cmpq	$0, (%rdi)
	je	.LBB0_1
	cmpq	$0, 8(%rdi)
	je	.LBB0_3
	cmpq	$0, 16(%rdi)
	je	.LBB0_5
	cmpq	$0, 24(%rdi)
	je	.LBB0_7
	cmpq	$0, 32(%rdi)
	je	.LBB0_9
	cmpq	$0, 40(%rdi)
	je	.LBB0_11
	cmpq	$0, 48(%rdi)
	je	.LBB0_13
	cmpq	$0, 56(%rdi)
	je	.LBB0_15
	cmpq	$0, 64(%rdi)
	je	.LBB0_17
	cmpq	$0, 72(%rdi)
	je	.LBB0_19
	cmpq	$0, 80(%rdi)
	je	.LBB0_21
	cmpq	$0, 88(%rdi)
	je	.LBB0_23
	cmpq	$0, 96(%rdi)
	je	.LBB0_25
	cmpq	$0, 104(%rdi)
	je	.LBB0_27
	cmpq	$0, 112(%rdi)
	je	.LBB0_29
	cmpq	$0, 120(%rdi)
	je	.LBB0_31
	cmpq	$0, 128(%rdi)
	je	.LBB0_33
	cmpq	$0, 136(%rdi)
	je	.LBB0_35
	cmpq	$0, 144(%rdi)
	je	.LBB0_37
	cmpq	$0, 152(%rdi)
	je	.LBB0_39
	cmpq	$0, 160(%rdi)
	je	.LBB0_41
	cmpq	$0, 168(%rdi)
	je	.LBB0_43
	cmpq	$0, 176(%rdi)
	je	.LBB0_45
	cmpq	$1, 184(%rdi)
	movl	$24, %eax
	sbbq	$0, %rax
	retq

.LBB0_1:
	xorl	%eax, %eax
	retq

.LBB0_3:
	movl	$1, %eax
	retq

.LBB0_5:
	movl	$2, %eax
	retq

.LBB0_7:
	movl	$3, %eax
	retq

.LBB0_9:
	movl	$4, %eax
	retq

.LBB0_11:
	movl	$5, %eax
	retq

.LBB0_13:
	movl	$6, %eax
	retq

.LBB0_15:
	movl	$7, %eax
	retq

.LBB0_17:
	movl	$8, %eax
	retq

.LBB0_19:
	movl	$9, %eax
	retq

.LBB0_21:
	movl	$10, %eax
	retq

.LBB0_23:
	movl	$11, %eax
	retq

.LBB0_25:
	movl	$12, %eax
	retq

.LBB0_27:
	movl	$13, %eax
	retq

.LBB0_29:
	movl	$14, %eax
	retq

.LBB0_31:
	movl	$15, %eax
	retq

.LBB0_33:
	movl	$16, %eax
	retq

.LBB0_35:
	movl	$17, %eax
	retq

.LBB0_37:
	movl	$18, %eax
	retq

.LBB0_39:
	movl	$19, %eax
	retq

.LBB0_41:
	movl	$20, %eax
	retq

.LBB0_43:
	movl	$21, %eax
	retq

.LBB0_45:
	movl	$22, %eax
	retq

First occurs in 1.19.0 with the alternative code snippet:

#[no_mangle]
pub fn partition_point_short_array(array: &[usize; 24]) -> usize {
    let mut i = 0;
    while i < 24 {
        if array[i] == 0 { break }
        i += 1;
    }
    i
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.C-bugCategory: This is a bug.I-heavyIssue: Problems and improvements with respect to binary size of generated code.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions