Skip to content

Rust fails to optimize away useless unwrap check #57166

Open
@upsuper

Description

@upsuper

See the following code:

pub struct ListNode {
    next: Option<Box<ListNode>>
}

pub fn foo(mut head: Box<ListNode>) -> Box<ListNode> {
    let mut cur = &mut head;
    while let Some(next) = std::mem::replace(&mut cur.next, None) {
        cur.next = Some(next);
        cur = cur.next.as_mut().unwrap();
    }
    head
}

Apparently the unwrap should never panic given the assignment in the previous line. However, based on the assembly output, that check isn't optimized away.

(The while let statement seems to be generating useless function calls for drop as well, btw.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.C-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.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions