rust-lang / rust-lang/rust

match generates more branch instructions

Open
#122,726 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

I tried this code:

fn foo(a: Option<i32>, b: Option<i32>) -> i32 {
  match (a, b) {
    (None, None) => 0,
    (Some(a), Some(b)) => a + b,
    (Some(a), _) => a,
    _ => 1,
  }
}z

The generated assembly code:

foo:
        xor     eax, eax
        test    edi, edi
        je      .LBB0_1
        cmp     edx, 1
        cmove   eax, ecx
        add     eax, esi
        ret
.LBB0_1:
        test    edx, edx
        setne   al
        ret

godbolt: https://rust.godbolt.org/z/7dGEccqcW.

We can get less code with alive2 validation:

tgt:                                    # @tgt
        test    edx, edx
        cmove   ecx, edx
        lea     eax, [rcx + rsi]
        test    edi, edi
        cmove   eax, edx
        ret

godbolt (llc): https://llvm.godbolt.org/z/331WYovKG

Meta

rustc --version --verbose:

rustc 1.78.0-nightly (3cbb93223 2024-03-13)
binary: rustc
commit-hash: 3cbb93223f33024db464a4df27a13c7cce870173
commit-date: 2024-03-13
host: x86_64-unknown-linux-gnu
release: 1.78.0-nightly
LLVM version: 18.1.0

@rustbot modify labels: +C-optimization +A-codegen +A-LLVM +I-slow

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.

Research direction

The report names no repository file or test; start by compiling the supplied Rust reproducer and comparing its assembly with the linked Godbolt and Alive2 results. Done means identifying and addressing the codegen or LLVM path responsible for the extra branch instructions, with regression coverage for this match pattern.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers, performance
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.