rust-lang / rust-lang/rust

Missed Optimization: Inefficient Handling of Mutable Reference in Simple Conditional Assignment

Open
#124,346 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

The following example shows how LLVM isn't able to optimize trivial branches when dealing with &mut pointers, while it can with owned values. I'd expect both functions to override current_len with 0 without needing to branch.

#[no_mangle]
pub fn unoptimized(current_len: &mut u32) {
    if *current_len != 0 {
        *current_len = 0;
    }
}

#[no_mangle]
pub fn optimized(mut current_len: u32) -> u32 {
    if current_len != 0 {
        current_len = 0;
    }
    current_len
}
unoptimized:
        cmp     dword ptr [rdi], 0
        je      .LBB0_2
        mov     dword ptr [rdi], 0
.LBB0_2:
        ret

optimized:
        xor     eax, eax
        ret
define void @unoptimized(ptr noalias nocapture noundef align 4 dereferenceable(4) %current_len) unnamed_addr {
start:
  %_2 = load i32, ptr %current_len, align 4
  %0 = icmp eq i32 %_2, 0
  br i1 %0, label %bb3, label %bb1

bb1:
  store i32 0, ptr %current_len, align 4
  br label %bb3

bb3:
  ret void
}

define noundef i32 @optimized(i32 noundef %0) unnamed_addr {
start:
  ret i32 0
}

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

Start with the Rust reproducer in the issue and compare the generated assembly and LLVM IR for the mutable-reference and owned-value functions. Investigate the compiler code-generation or optimization path responsible for this difference. Done means the mutable-reference case avoids the unnecessary conditional branch while preserving the shown behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
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.