Now to the topic at hand. I was disassembling some code the other day (just using objdump, nothing fancy) and I noticed a weird pattern emitted by GCC.
billm@plums:~$ objdump -d /bin/ls | less ... 8049ba9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi ...
This pattern appears all over the place (though sometimes with other registers subsituted for edi). Mostly I’ve noticed it in between functions (after one returns and before the next begins) but it also appears within function bodies.
What does this instruction do? The weirdo syntax makes it particularly difficult to determine. Apparently %eiz is a pseudo-register that just evaluates to zero at all times (like r0 on MIPS). I decoded the same instruction using an older version of objdump, and it instead gave the more normal result “lea 0×0(%edi),%edi”. I think the binutils people must pull a lot of all-nighters to make their crazy AT&T syntax even more inscrutable with each new version. Why can’t we just use Intel syntax? It seems way more intuitive to me.
Returning to the problem at hand, the instruction “lea 0×0(%edi),%edi” still doesn’t make much sense. Why would you ever want to load the effective address of [edi] into edi? This is semantically equivalent to “mov edi, edi”, or, more simply, to a NOP.
I eventually found a mailing list post by binutils guru Ian Lance Taylor that reveals the answer. Sometimes GCC inserts NOP instructions into the code stream to ensure proper alignment and stuff like that. The NOP instruction takes one byte, so you would think that you could just add as many as needed. But according to Ian Lance Taylor, it’s faster for the chip to execute one long instruction than many short instructions. So rather than inserting seven NOP instructions, they instead use one bizarro LEA, which uses up seven bytes and is semantically equivalent to a NOP.
I must admit to being a bit confused still. Most of the time, these semantic NOPs are not executed so you might as well use regular NOPs. Occasionally, the LEAs do occur in places where they might be executed, but in those cases I don’t always understand why a NOP is needed. Sometimes the next instruction after the NOP is a branch target, and so I can understand that the compiler might want the CPU to start loading those instructions on a cache line boundary if possible. But sometimes the instruction after the NOP is not a branch target. In that case, why is there a random NOP in the instruction stream? It just seems wasteful of cache. Perhaps someone can enlighten me.
Anyway, wasn’t that interesting?