0

I am reading about x64 Assembly through this online textbook. It takes the following C function:

int adder2(int a) {
    return a + 2;
}

And shows how it is compiled into x64 Assembly:

push %rbp
mov %rsp,%rbp
mov %edi,-0x4(%rbp)
mov -0x4(%rbp),%eax
add $0x2,%eax
pop %rbp
retq

I understand that push %rbp pushes the adder2 function onto the call stack, pop %rbp pops it from the call stack, and retq returns control to the function that had called adder2. I also get that add $0x2, %eax adds 2 to a, and the result is what will be returned.

However, why are there three lines that call the mov command? There is only one variable (a), so why are there so many registers? There is no clear line-by-line connection between the C and Assembly code.

Michael Petch
  • 46,082
  • 8
  • 107
  • 198
K Man
  • 602
  • 2
  • 9
  • 21
  • 2
    This is caused by the inefficiencies produced when compiling without optimizations. You are seeing unnecessary loads and stores to the stack. Try `gcc` with option `-O2` or `-O3` – Michael Petch Jan 10 '23 at 01:17
  • 4
    Indeed, in general there is no line-by-line connection. In this case the code shown is compiled without optimization so it does a bunch of useless stuff. _"push %rbp pushes the adder2 function onto the call stack"_ no it does nothing like that. It pushes the `rbp` register to the stack, not the function (whatever that even means). Also the code creates `a` as a local variable on the stack and writes the argument that got passed in `%edi` there only to reload it immediately. An optimized version would be `lea 2(%edi), %eax; ret`. – Jester Jan 10 '23 at 01:18
  • 1
    C code hides many essentials from us. There's no C language concept of the call stack or stack frame, which necessarily have manifestation in assembly/machine code, and, C allows logical variables while machine code has physical storage. The only direct correspondence is the add instruction; the rest is stuff necessary but hidden by C. – Erik Eidt Jan 10 '23 at 05:16
  • 1
    For larger functions that accomplish things more complicated than just adding 2, these "extra actions" are allocating space for the function's local variables. C does this out of habit if you don't have optimizations on. With `-O2` or `-O3` you wouldn't even see this function at all, C would just add the 2 inline. – puppydrum64 Jan 10 '23 at 13:19

0 Answers0