Skip to content

if Result::is_ok() followed immediately by Result::unwrap() fails to optimize out the second err check #85771

Description

@TheBlueMatt

In the following trivial example, LLVM fails to optimize the unwrap() away. While its somewhat contrived in the sense that a match or if let should be preferred, more complicated logic ends up with similar blocks eventually.

pub fn print_if_some(arg: Result<u64, u32>) {
    if arg.is_ok() {
        let v = arg.unwrap();
        if v == 42 {
            println!("{}", v);
        }
        return;
    }
}

Godbolt link for the same is https://godbolt.org/z/xrT1GfG7e you can see the test and jne for panic'ing.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-codegenArea: Code generationC-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-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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions