Skip to content

Suboptimal code generation for array Element by Element replace/overwrite (Uneeded stores) #150325

@Keith-Cancel

Description

@Keith-Cancel

I noticed that the code generation on something I was working on was less than ideal. I was able to distill it down to some very simple examples here on compiler explorer: Compiler Explorer

I would expect the output to be similar to either test4() or test5() for the functions test1(), test2(), and test3().

For example here is test3():

fn test3(mut a: [u32; 3], b: &[u32; 3]) -> [u32;3] {
    *a.get_mut(0).unwrap() = b[0];
    *a.get_mut(1).unwrap() = b[1];
    *a.get_mut(2).unwrap() = b[2];
    return a;
}

The generated assembly is:

test3:
    mov rax, rdi
    mov rcx, qword ptr [rdx]
    mov qword ptr [rsi], rcx
    mov edx, dword ptr [rdx + 8]
    mov dword ptr [rsi + 8], edx
    mov dword ptr [rdi + 8], edx
    mov qword ptr [rdi], rcx
    ret

Where as if we look at test4() we can see that we can get rid of the spurious stores, by adding let mut a = a; What is interesting is this does nothing when using the index operator [], if you look at what I have on compiler explorer test2().

fn test4(mut a: [u32; 3], b: &[u32; 3]) -> [u32;3] {
    let mut a = a;
    *a.get_mut(0).unwrap() = b[0];
    *a.get_mut(1).unwrap() = b[1];
    *a.get_mut(2).unwrap() = b[2];
    return a;
}

The generated assembly for test4()

test4:
    mov rax, rdi
    mov ecx, dword ptr [rdx + 8]
    mov rdx, qword ptr [rdx]
    mov qword ptr [rdi], rdx
    mov dword ptr [rdi + 8], ecx
    ret

@rustbot label A-LLVM
@rustbot label C-optimization
@rustbot label A-codegen

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.A-codegenArea: Code generationC-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchneeds-triageThis issue may need triage. Remove it if it has been sufficiently triaged.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions