Reputation: 215
Me again.
I'm having a lot of "add esp, 4" in my program and I'm trying to reduce its size. Is there any smaller instruction that can replace "add esp, 4" ?
Upvotes: 5
Views: 3775
Reputation: 51944
pop edx
Or any other integer register you don't mind destroying.
This is what modern compilers actually do (clang and sometimes gcc) because it's often optimal for performance as well as code-size on modern CPUs.
An add esp,4
after a call
would force the CPU's stack engine to insert a stack-sync uop before doing the actual add
. If you otherwise don't modify use ESP directly except with stack instructions (e.g. as part of an addressing mode) before the next push/pop/call/ret, then you saved a uop by using pop
.
That cache line of stack memory is going to be hot in cache (making the load cheap) if any other stack instructions ran recently.
Upvotes: 6
Reputation: 11
If you are aligning stack after a call, the better way to do this is using RETN X
, where X
is the number of bytes to add on ESP
...
PUSH EAX
CALL EBX (in this func, you use RETN 4)
<<here the stack is already aligned>>
Or, use POPFD =x
Upvotes: 1
Reputation: 137960
popfd
will add 4 to esp
in just one byte, with the side effect of randomizing your flags. It might be slow to execute; I don't know.
Of course it would help to see code or know what your requirements really are.
Upvotes: 0
Reputation: 106317
A better question might be: "why do you have so many add esp, 4
instructions, and what can you do to have less of them?" It's somewhat unusual to be doing lots of small increments to the stack pointer like this.
Are you moving things to/from the stack at the same time? Could you use push
/pop
instead?
Alternatively, do you really need to update the stack pointer so frequently, or could you get away with moving it once at the beginning of a block of code to make some space on the stack, then restoring it once at the end of the routine?
What are you really trying to do?
Upvotes: 5
Reputation: 84835
Sorry if this will sound trivial... but if you manage to reorder your code so that several add esp, 4
instructions are consecutive, you can of course simplify them to e.g.:
add esp, 8
or even:
add esp, 12
Just make sure that moved instructions don't reference esp
or the stack; or if they do reference something on the stack, they do only via the ebp
register.
Upvotes: 4
Reputation: 19985
One way to do it if you have multiple function calls:
sub esp, 4
mov 0(esp), param
call ...
...
mov 0(esp), param2
call ...
...
add esp, 4
That is, reuse the stack allocated for the first parameter over several function calls.
Upvotes: 2
Reputation: 25022
If you're managing a stack(I assume you are), you can use push eax
and pop eax
to add values to the stack and maintain the esp
. You can also use instructions such as pusha/popa
to push/pop all GPRs on/off the stack and pushf/popf
to push/pop the EFLAGS registers on/off the stack.
Upvotes: 0