views:

64

answers:

2

I am trying to use CL 16.0 for x64 (VS 2010) to produce some readable 64-bit ASM code for an example, but CL insists on preallocating a ton of stack space (28h bytes), with the following line:

sub rsp, 40 ; 00000028H (actual value depends on number of local vars of course)

Question is, how can I disable this behavior? It is difficult to explain to the class and I like to show them clean, explicable code... My assumption is that "sub rsp, XXX" should allocate the exact space required by the local variables in the function.

Surely it doesn't need that extra space. On x86, this behavior seems to be controlled by the edit-and-continue switches (/Zi vs. /ZI), but these don't have any effect in the x64 case. Any idea how to make x64 CL only allocate as much stack as it actually needs?

Thanks in advance!

+2  A: 

It'd be easier if you showed the source code that produced this, but 40 bytes is not that much for a 64-bit machine. That's only five longs or pointers. Another thing to take into account is alignment for local variables - the compiler probably pads them for optimal access.

Edit:

Hmm, this is indeed a bit puzzling. Running this through GCC doesn't result is such stack grab. My suspicion is that this is compiler-specific exception handling prolog requirement (do you see some weird-looking labels before and after the stack allocation in the generated code?).

Here are couple of MSDN links you might find useful:

I don't have a Windows box to test, but try /favor:??? and see if cranking the optimization level up a bit eliminates this. It's a leaf function after all.

Also, comments formatting on SO sucks, put the code into the question itself.

Nikolai N Fetissov
+1 for alignment. Isn't stack allocation on x64 aligned to 16 bytes?
codekaizen
Gladly, but it's amazingly trivial: int testfunc(void) { int a = 0; return a; }Which compiles into the following: sub rsp,18h mov dword ptr [rsp],0 mov eax,dword ptr [rsp] add rsp,18h ret Even if we account for 16-byte alignment, this seems like too much, no?
ldoogy
A: 

Probably it will help.

Article. The reasons why 64-bit programs require more stack memory.

Andrey Karpov