Skip to content

Inefficient Match Statement Optimization for Unit-Only Enums with Fixed Offsets #129131

Open

Description

Description:
The match statement in the provided Rust code generates a jump table with -O3 optimizations, despite the fact that the discriminant values for the enum variants have a fixed offset from their target characters. This results in suboptimal code generation when a more efficient approach is possible.

Reproduction:

use std::fmt::{Display, Formatter};

#[derive(Copy, Clone)]
enum Letter {
    A,
    B,
    C,
}

impl Display for Letter {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let letter = match self {
            Letter::A => 'a',
            Letter::B => 'b',
            Letter::C => 'c',
        };
        write!(f, "{}", letter)
    }
}

Expected Behavior:
Since each discriminant value of the Letter enum is exactly 97 units away from the corresponding target characters in the match statement, the compiler should ideally optimize this code to use a direct calculation rather than generating a jump table.

Example of Hand-Optimized Code:

use std::fmt::{Display, Formatter};

#[derive(Copy, Clone)]
enum Letter {
    A,
    B,
    C,
}

impl Display for Letter {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let letter = ((*self as u8) + 97) as char;
        write!(f, "{}", letter)
    }
}

Compiler Explorer Links:

Additional Notes:
Although manual optimization achieves the desired performance, automatic optimization by the compiler is preferred to ensure both efficiency and maintainability of the code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.A-codegenArea: Code generationA-patternsRelating to patterns and pattern matchingC-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.llvm-fixed-upstreamIssue expected to be fixed by the next major LLVM upgrade, or backported fixes

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions