How many machine instructions are needed for a function call in C?
I'd like to know how ma开发者_如何学JAVAny instructions are needed for a function call in a C program compiled with gcc for x86 platforms from start to finish.
- Write some code.
- Compile it.
- Look at the disassembly.
- Count the instructions.
The answer will vary as you vary the number and type of parameters, calling conventions etc.
That is a really tricky question that's hard to answer and it may vary.
First of all in the caller it is needed to pass the parameters, depending on the type this will vary, in most cases you will have a push instruction for each parameter.
Then, in the called procedure the first instructions will be to do the allocation for local variables. This is usually done in 3 operations:
PUSH EBP
MOV EBP, ESP
SUB ESP, xxx
You will have the assembly code of the function after that.
Following the code but before the return, the ebp and esp will be restored:
MOV ESP, EBP
POP EBP
Lastly, you will have a ret instruction that depending on the calling convention will dealocate the parameters of the stack or it will leave that to the caller. You can determine this if the RET is with a number as parameter or if the parameter is 0, respectively. In case the parameter is 0 you will have POP instructions in the caller after the CALL instruction.
I would expect at least one
CALL Function
unless it is inlined, of course.
If you use -mno-accumulate-outgoing-args
and -Os
(or -mpreferred-stack-boundary=2
, or 3 on 64-bit), then the overhead is exactly one push
per argument word-sized argument, one call
, and one add
to adjust the stack pointer after return.
Without -mno-accumulate-outgoing-args
and with default 16-byte stack alignment, gcc generates code that's roughly the same speed but roughly five times larger for function calls, for no good reason.
精彩评论