Skip to content

Missed optimization with mir-opt-level 4 #100408

Description

@leonardo-m

This code with an inner immediately invoked lambda function:

use std::num::NonZeroI32;

pub fn foo(x: NonZeroI32) -> i32 {
	(|x: &NonZeroI32| 33 / x.get())(&x)
}

Compiled using:

rustc 1.65.0-nightly (f03ce3096 2022-08-08)
binary: rustc
commit-hash: f03ce30962cf1b2a5158667eabae8bf6e8d1cb03
commit-date: 2022-08-08
host: x86_64-unknown-linux-gnu
release: 1.65.0-nightly
LLVM version: 14.0.6

With arguments:

--edition 2021 -C opt-level=3 -Z mir-opt-level=3

Gives a nice asm:

foo:
        mov     eax, 33
        xor     edx, edx
        idiv    edi
        ret

But cranking opt up to the 4th level:

--edition 2021 -C opt-level=3 -Z mir-opt-level=4

Gives an asm similar to not using the lambda function at all:

foo:
        test    edi, edi
        je      .LBB0_2
        mov     eax, 33
        xor     edx, edx
        idiv    edi
        ret
.LBB0_2:
        push    rax
        lea     rdi, [rip + str.0]
        lea     rdx, [rip + .L__unnamed_1]
        mov     esi, 25
        call    qword ptr [rip + core::panicking::panic@GOTPCREL]
        ud2

(Inspired by: https://old.reddit.com/r/rust/comments/wkw55b/help_matching_c_codegen_for_a_small_function/ijr7o5x/ ).

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