Skip to content

Missed optimization with mir-opt-level 4 #100408

Open

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

  1. Noratrieb commented on Aug 11, 2022

    @Noratrieb
    Member

    I thought that it might be UnreachablePropagation being broken here, but my fix for that pass still emits the bad assembly, so it's probably not it.

  2. tmiasko commented on Aug 12, 2022

    @tmiasko
    Contributor

    Looks like SROA drops the load range metadata (similar to what happened with !nonnull in #37945).

  3. added
    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.
    I-slowIssue: Problems and improvements with respect to performance of generated code.
    on Aug 12, 2022
  4. added
    T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.
    on Apr 5, 2023
  5. joseph-isaacs commented on Aug 31, 2026

    @joseph-isaacs
    Contributor

    Seems to be fixed in #128371

    Regression test here: https://github.com/joseph-isaacs/rust/tree/ji/issue-100408-close if required

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