Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using if-else to match cmp::Ordering is better than match #86391

Closed
fee1-dead opened this issue Jun 17, 2021 · 2 comments
Closed

Using if-else to match cmp::Ordering is better than match #86391

fee1-dead opened this issue Jun 17, 2021 · 2 comments
Labels
A-codegen Area: Code generation C-enhancement Category: An issue proposing an enhancement or a PR with one.

Comments

@fee1-dead
Copy link
Member

Godbolt

Consider the following snippet:

#[inline(never)]
fn if_else(cmp: Ordering) -> u32 {
    let mut x = 0;
    if cmp == Less {
        x += black_box(1);
    } else if cmp == Greater {
        x += black_box(2);
    } else {
        x += black_box(3);
    }
    x
}

#[inline(never)]
fn matching(cmp: Ordering) -> u32 {
    let mut x = 0;
    match cmp {
        Less => {
            x += black_box(1);
        }
        Greater => {
            x += black_box(2);
        }
        _ => {
            x += black_box(3);
        }
    }
    x
}

This is part of if_else:

example::if_else:
        sub     rsp, 12
        cmp     dil, 1
        je      .LBB0_5
        cmp     dil, -1
        jne     .LBB0_4

...and this is part of matching:

example::matching:
        sub     rsp, 12
        cmp     dil, -1
        je      .LBB1_3
        movsx   rax, dil
        cmp     rax, 1
        jne     .LBB1_2

I think these two should generate the same code, but currently using match gives one extra instruction.

@rustbot label A-codegen C-enhancement

@rustbot rustbot added A-codegen Area: Code generation C-enhancement Category: An issue proposing an enhancement or a PR with one. labels Jun 17, 2021
@leonardo-m
Copy link

See also Issue #86354

@dotdash
Copy link
Contributor

dotdash commented Jun 24, 2022

This seems to have been fixed in the meantime, the Godbolt link shows that two comparisons are switched, but the extra instruction is gone,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-codegen Area: Code generation C-enhancement Category: An issue proposing an enhancement or a PR with one.
Projects
None yet
Development

No branches or pull requests

5 participants