Why doesn't the Rust optimizer remove those useless instructions (tested on Godbolt Compiler Explorer)?

Viewed 1662

I wanted to take a look at the assembly output for a tiny Rust function:

pub fn double(n: u8) -> u8 {
    n + n
}

I used the Godbolt Compiler Explorer to generate and view the assembly (with the -O flag, of course). It shows this output:

example::double:
    push    rbp
    mov     rbp, rsp
    add     dil, dil
    mov     eax, edi
    pop     rbp
    ret

Now I'm a bit confused, as there are a few instructions that doesn't seem to do anything useful: push rbp, mov rbp, rsp and pop rbp. From what I understand, I would think that executing these three instructions alone doesn't have any side effects. So why doesn't the Rust optimizer remove those useless instructions?


For comparisons, I also tested a C++ version:

unsigned char doubleN(unsigned char n) {
    return n + n;
}

Assembly output (with -O flag):

doubleN(unsigned char): # @doubleN(unsigned char)
    add dil, dil
    mov eax, edi
    ret

And in fact, here those "useless" instructions from above are missing, as I would expect from an optimized output.

1 Answers
Related