Skip to content

Neighboring-ret code size optimization missed on x86-64 #113431

@ChaiTRex

Description

@ChaiTRex

I tried this code:

pub fn a(xs: &[u8], i: usize) -> Option<u32> {
    xs
        .get(i..=i + 2)
        .map(|three_bytes| {
            let mut result = [0; 4];
            result[1..4].copy_from_slice(three_bytes);
            u32::from_ne_bytes(result)
        })
}

I expected to see this happen: No ret instruction followed immediately by a ret instruction.

Instead, this happened: A ret instruction was followed immediately by a ret instruction. From cargo asm code_size::a:

code_size::a:
 lea     r8, [rdx, +, 2]
 xor     eax, eax
 cmp     r8, -1
 je      .LBB0_1
 mov     rcx, rdx
 cmp     rcx, -4
 ja      .LBB0_5
 cmp     r8, rsi
 jae     .LBB0_5
 movzx   edx, byte, ptr, [rdi, +, rcx, +, 2]
 movzx   eax, word, ptr, [rdi, +, rcx]
 shl     eax, 8
 shl     edx, 24
 or      edx, eax
 mov     eax, 1
.LBB0_5:
 ret
.LBB0_1:
 ret

Labels LBB0_1 and LBB0_5 and their rets can be combined to reduce code size.

Meta

rustc --version --verbose:

rustc 1.70.0 (90c541806 2023-05-31)
binary: rustc
commit-hash: 90c541806f23a127002de5b4038be731ba1458ca
commit-date: 2023-05-31
host: x86_64-unknown-linux-gnu
release: 1.70.0
LLVM version: 16.0.2
rustc 1.71.0-beta.4 (dbf31f17d 2023-06-24)
binary: rustc
commit-hash: dbf31f17d020475885f50fb7d5fc15ff239843d8
commit-date: 2023-06-24
host: x86_64-unknown-linux-gnu
release: 1.71.0-beta.4
LLVM version: 16.0.5
rustc 1.72.0-nightly (85bf07972 2023-07-06)
binary: rustc
commit-hash: 85bf07972a1041b9e25393b803d0e006bec3eaaf
commit-date: 2023-07-06
host: x86_64-unknown-linux-gnu
release: 1.72.0-nightly
LLVM version: 16.0.5

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.C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing such

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions