rust-lang / rust-lang/rust

assert_eq! of trivially-equal enums with 2 non-empty variants is not optimized out

Open
#139,733 6 comments 0 reactions 1 assignee View on GitHub

@dianqk is already working on this.

Since Apr 29, 2025.

A-LLVM C-optimization I-slow T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

https://godbolt.org/z/Wrq4EdvrP

This program should be optimized to an empty main, but it isn't:

#[derive(PartialEq)]
enum Foo {
    Bar(u8, u8),
    #[allow(dead_code)]
    Baz(u8),
}

impl std::fmt::Debug for Foo {
    #[inline]
    fn fmt(&self, _f: &mut std::fmt::Formatter) -> std::fmt::Result {
        Ok(())
    }
}

pub fn main() {
    let a = Foo::Bar(1, 2);
    let b = Foo::Bar(1, 2);
    assert_eq!(a, b);
}

Note that if the assert is changed to just a panic that doesn't try to format a and b, the comparison does get optimized out. And also, if the Baz is a unit variant we will get the expected optimization but only with -Cdebuginfo=0.

rustc 1.85.0-nightly (d117b7f21 2024-12-31)
binary: rustc
commit-hash: d117b7f211835282b3b177dc64245fff0327c04c
commit-date: 2024-12-31
host: x86_64-unknown-linux-gnu
release: 1.85.0-nightly
LLVM version: 19.1.6

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.