3

I have seen an assembly code which subtracts from the stack pointer before calling a function without any particular reason. The space subtracted is left empty and not used:

sub    esp, 8    ; stack align
push   dword y
push   dword [x]
call   foo
add    esp, 16
mov    [x], eax

The writer of the code added the comment 'stack align', but I don't know what is meant by 'stack align' nor how does the command sub esp, 8 help achieving it.

Any ideas?

Ori Popowski
  • 10,432
  • 15
  • 57
  • 79
  • 1
    See http://stackoverflow.com/questions/612443/why-does-the-mac-abi-require-16-byte-stack-alignment-for-x86-32 – Nikolai Fetissov Jun 04 '12 at 16:09
  • The answer says "SSE require their memory operands to be aligned to 16-byte boundaries". But this program doesn't use any of the instructions introduced in SSE. So what's the motivation to align the stack in 16 bytes? Is there another reason to do so beside the SSE requirements? – Ori Popowski Jun 04 '12 at 16:44
  • 1
    Even without using SSE instructions, it's a good idea to 16-byte align your code and data. The memory/cache logic and instruction prefetch all benefit since they can guarantee that the memory request will be satisfied with a single read. This makes sense since the memory interface of modern Intel chips is 64-bits wide and dual channel (16 bytes). – BitBank Jun 04 '12 at 17:01

1 Answers1

3

If your stack pointer is aligned to a cache line when a function is entered, execution of the functions is likely to place less stress on the cache.

So, a compiler system can be organized to insist that functions are entered with the SP aligned on a cache line, and the compiler, knowing how much stack has been used at each call site, how much it takes to re-align the SP before it makes the call.

That would explain your example. I haven't seen many compilers actually do this, since the stack itself tends to grow/shrink by modest distances and overall doesn't put much demand on the cache by virtue of reusing that local storage again and again.

Another use is allocating space for the callee to work in, or to return a result bigger than what fits in a register. A compiler wouldn't write a comment like that, so some person likely did this. Maybe he knew what he was doing; maybe he didn't. If the called function doesn't need this space, then its just a wasted instruction.

Ira Baxter
  • 93,541
  • 22
  • 172
  • 341