Why does gcc generate redundant build code?

I wanted to see how some C / C ++ functions were translated into an assembly, and I created the following file:

struct foo {
    int x;
    char y[0];
};

char *bar(struct foo *f)
{
    return f->y;
}

Then I compiled this with gcc -S(and also tried with g++ -S), but when I looked at the build code, I was disappointed to find a trivial redundancy in the bar function that I considered gccfor optimization:

_bar:
Leh_func_begin1:
        pushq   %rbp
Ltmp0:
        movq    %rsp, %rbp
Ltmp1:
        movq    %rdi, -8(%rbp)
        movq    -8(%rbp), %rax
        movabsq $4, %rcx
        addq    %rcx, %rax
        movq    %rax, -24(%rbp)
        movq    -24(%rbp), %rax
        movq    %rax, -16(%rbp)
        movq    -16(%rbp), %rax
        popq    %rbp
        ret
Leh_func_end1:

By the way, the lines

        movq    %rax, -24(%rbp)
        movq    -24(%rbp), %rax
        movq    %rax, -16(%rbp)
        movq    -16(%rbp), %rax

seem pointless. Is there any reason why gcc (and possibly other compilers) cannot / will not optimize this?

+5
source share
2 answers

I thought gcc should be able to optimize.

From the gcc manual :

- .

, , . -O3, gcc 4.4.6 :

bar:
.LFB0:
        .cfi_startproc
        leaq    4(%rdi), %rax
        ret
        .cfi_endproc

. .

+11

, , , , , .

, gcc -O -S

peephole. , , , ( ) - , .

, , GCC, Clang 32- , - 64-, 32- .

+8

All Articles