rust-lang / rust-lang/rust

Missed Optimization when Matching on Complete Unicode Character Ranges with an Unreachable Arm

Open
#123,927 1 comment 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Hello, I've noticed a bug with rustc:

#[inline(never)]
pub fn with_unreachable(c: char) -> bool {
    match c {
        ('\0'..='\u{d7ff}') => true,
        ('\u{e000}'..='\u{10ffff}') => true,
        _ => false
    }
}

#[inline(never)]
pub fn without_unreachable(c: char) -> bool {
    match c {
        ('\0'..='\u{d7ff}') => true,
        ('\u{e000}'..='\u{10ffff}') => true,
    }
}

which outputs:

example::with_unreachable::hd01eb55f04576fdc:
  cmp edi, 55296
  setb cl
  add edi, -57344
  cmp edi, 1056768
  setb al
  or al, cl
  ret

example::without_unreachable::h31c5b4f665ccfd93:
  mov al, 1
  ret

Gives a compiler warning telling us that _ => false is unreachable, but it seems that the optimiser isn't privy to this? We'd expect without_unreachable and with_unreachable to give the same assembly output.

Meta

The above is built with rustc 1.77.0 and flags -C debuginfo=1 --emit asm -Cllvm-args=--x86-asm-syntax=intel --crate-type rlib --color=always --edition 2021 -C opt-level=3

A link to the godbolt snippet: https://godbolt.org/z/hf7jje83W

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 by reproducing the two functions with the listed rustc 1.77.0 flags and compare their emitted assembly, using the linked Godbolt snippet as a reference. Trace the compiler optimization path responsible for matching complete Unicode ranges, then add or update a regression test showing that the unreachable-arm version produces the same optimized result as the version without that arm.

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
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.