Skip to content

Missed optimization (extra branch) using slice::get with enum elements with spare niches #113899

@jrose-signal

Description

@jrose-signal

The following code

#[derive(Clone, Copy)]
pub enum Outer {
    A([u8; 8]),
    B([u8; 8]),
}

pub struct Error(u8);

pub fn test(x: usize) -> Result<Outer, Error> {
    [Outer::A([10; 8]), Outer::B([20; 8])].get(x).copied().ok_or(Error(5))
}

generates the following assembly

playground::test:
	movq	%rdi, %rax
	cmpq	$1, %rsi
	ja	.LBB0_2
	leaq	(%rsi,%rsi,8), %rsi
	leaq	.L__unnamed_1(%rip), %rcx
	movzbl	(%rcx,%rsi), %edx
	cmpb	$2, %dl
	jne	.LBB0_3

.LBB0_2:
	movw	$1282, (%rax)
	retq

.LBB0_3:
	addq	%rsi, %rcx
	movq	1(%rcx), %rcx
	movb	%dl, (%rax)
	movq	%rcx, 1(%rax)
	retq

.L__unnamed_1:
	.ascii	"\000\n\n\n\n\n\n\n\n\001\024\024\024\024\024\024\024\024"

using stable (1.71.0).

But the second branch is completely superfluous; it's not possible for a load from the array to produce a None value.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.A-codegenArea: Code generationC-bugCategory: This is a bug.C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchE-needs-testCall for participation: An issue has been fixed and does not reproduce, but no test has been added.I-heavyIssue: Problems and improvements with respect to binary size of generated code.I-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