Search code examples
c++ccompiler-constructioncompilationfunction-call

Why does VS2013 compile a function-call into two instructions instead of one?


Here is a simple program:

void func()
{
    printf("hello");
}

int main()
{
    printf("%p",func);
    func();
    return 0;
}

Stepping over the line printf("%p",func), I get 00F811AE printed on the console.

Disassembling the line func(), gives me call _func (0F811AEh) - so far so good.

But disassembling the contents of func, the first instruction appears at address 00F813C0.

So I "went to see" what's on address 00F811AE, and there I found jmp func (0F813C0h).

To summarize this, it appears that the function-call is compiled as two instructions:

call _func (0F811AEh)
jmp   func (0F813C0h)

Why does the VS2013 compiler use two instructions instead of just one?

It appears that a single jmp would do the the job. I am asking even this because I have a feeling that the other compilers do it in a similar manner (depending on the underlying HW architecture of course).

Thanks


Solution

  • Learn about "thunking": http://en.wikipedia.org/wiki/Thunk

    One benefit with "thunking" in your example is that the rest of your code will always call func, but any function performing the same role could be injected into the call at address 0x00F811AE.

    Try making func a static one and find out if anything changes.