0

I'm looking at the disassembler output of an XCode C file and I get the following:

enter image description here

Showing that:

int a=2;

Translates into this:

    0x100000f88 <+8>:  movl   $0x0, -0x4(%rbp)
->  0x100000f8f <+15>: movl   $0x2, -0x8(%rbp)

Now I get (I think?) the point of this in that it's clearing the higher four bytes and then moving the number 2 into the lower four bytes so it looks like:

--------------- 0
       0
--------------- -1
       0
--------------- -2
       0
--------------- -3
       0
--------------- -4
       0
--------------- -5
       0
--------------- -6
       0
--------------- -7
       2
--------------- -8

But why does it do that and not just movq $2, -8(%rbp) ? Finally, why does it do a subq $0x10 instead of subq $0x8 on the line above? I've never seen offsets of ten used before? (<-- Answering my own second question, I see the x in there now, so it's an offset of 16 not 10)


By the way, this is on a mac Mojave 10.14.6 using XCode for debugging -- is there a particular tag I should put into the question, or is x86 and assembly enough?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
samuelbrody1249
  • 4,379
  • 1
  • 15
  • 58
  • Are you familiar with the requirement for [stack alignment](https://stackoverflow.com/questions/49391001/why-does-the-x86-64-amd64-system-v-abi-mandate-a-16-byte-stack-alignment)? That's likely the reason for the 16 byte subtraction (though can't tell for sure without seeing the rest of the prologue). – Nate Eldredge Jan 09 '21 at 06:20
  • From what you've shown of the code, the `movl $0, -0x4(%rbp)` seems to be completely redundant, since that value is never read back. Are you compiling without optimizations? Yes, you must be, no optimizing compiler would store an immediate constant in memory and then load it right back into a register. So the answer is probably no deeper than "non-optimizing compilers produce dumb code because nobody told them to be smart". – Nate Eldredge Jan 09 '21 at 06:21
  • @NateEldredge no optimizations (intentionally) of course. Regarding the `16` -- yes I updated the question, I misread that as a decimal instead of as hex (two quads). – samuelbrody1249 Jan 09 '21 at 06:24
  • You told clang not to optimize, so it didn't do store-merging between the tmp return value (see linked duplicate) and your 4-byte `int a` initializer. Of course with optimization enabled it wouldn't be storing/reloading a zero to the stack in the first place. XCode's highlighting is basically wrong, the store of `0` has nothing to do with `int a=2`, more like the opening brace of `main`, @Nate – Peter Cordes Jan 09 '21 at 06:42
  • Appropriate tags for this question would be `assembly x86-64 clang` or maybe LLVM - because you're asking why clang specifically chose the instructions it did. (xcode along with clang or LLVM can work to indicate Apple clang instead of mainline clang) – Peter Cordes Jan 09 '21 at 06:42

0 Answers0