-1

I'm generating assembly for simple programs in order to get a better understanding, and I'm seeing an instruction I don't understand.

Here's a simple program I use:

int main() {
    int i = 1;
    int j = 2;
    int k = i + j;
    return 0;
}

Generating with clang main.c -o main.asm -S -O0, I get this for my main:

    main:
    .cfi_startproc
# %bb.0:
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register %rbp
    xorl    %eax, %eax
    movl    $0, -4(%rbp)
    movl    $1, -8(%rbp)
    movl    $2, -12(%rbp)
    movl    -8(%rbp), %ecx
    addl    -12(%rbp), %ecx
    movl    %ecx, -16(%rbp)
    popq    %rbp
    .cfi_def_cfa %rsp, 8
    retq

Most I get, except the movl $0, -4(%rsp), which is right before both variables initialization. Compiling with -g or with other means of adding annotations does not provide any clues as to what this is doing.

What's even more puzzling to me is that assembly generated with the same options with GCC does not show this instruction, while the rest is sensibly the same assembly.

I've documented myself notably through this article and this shows that at %rbp-4 there should be "local variable 1" which does not seem to be the case here.

What is this doing then, and what am I missing?

JBL
  • 12,588
  • 4
  • 53
  • 84
  • 3
    Duplicate (in C++ guise)? https://stackoverflow.com/questions/49300094/unoptimized-clang-code-generates-unneeded-movl-0-4rbp-in-a-trivial-mai – pmg Sep 21 '21 at 15:42
  • @pmg Oh, indeed, I didn't stumble on it. Thanks! – JBL Sep 21 '21 at 15:58

1 Answers1

1

The only real code here is

main:                                   # @main
        xorl    %eax, %eax
        retq

or if you want to force the stack frame:

main:                                   # @main
        pushq   %rbp
        movq    %rsp, %rbp
        xorl    %eax, %eax
        popq    %rbp
        retq

As your program has no observable behaviour

The rest is because you do not optimize the code.

0___________
  • 60,014
  • 4
  • 34
  • 74