Jul 28, 2012

Posted by | 0 Comments

Calling Convention – Part III (__fastcall)

Calling Convention – Part III (__fastcall)

Make sure you have read “Calling Convention – Part I” & “Calling Convention – Part II” of this article.

Fast calling convention ( __fastcall )

Fast calling convention indicates that the first two arguments should be placed in registers (ECX & EDX) and rest are pushed on stack. This reduces the cost of a function call, because operations with registers are faster than with the stack.

We can explicitly declare a function to use the __fastcall convention as shown:

int __fastcall Add( int nValue1, int nValue2 );

The main characteristics of __fastcall calling convention are:

  1. The first two function arguments that require 32 bits or less are placed into registers ECX and EDX. The rest of them are pushed on the stack from right to left.
  2. Arguments are popped from the stack by the called function.

Function Name Decoration For fastcall

Function name is decorated by by prefixing a ‘@’ character and postfixing a ‘@’ and number of bytes of stack space required by the arguments at end of the function name.

@[email protected] //@ added before & after function name and number of bytes space required on stack

Note: Microsoft have reserved the right to change the registers for passing the arguments in future compiler versions.

Here goes an example:

; // put the arguments in the registers EDX and ECX
mov         edx,3
mov         ecx,2
; // call the function
call @[email protected]
; // copy the return value from EAX to a local variable (int nResult)
mov DWORD PTR [nResult], eax

The called function is shown below:

; // function prolog
push ebp
mov ebp, esp
push ebx
push esi
push edi
; // return nValue1 + nValue2;
mov eax, DWORD PTR [nValue1]
add eax, DWORD PTR [nValue2]
; // function epilog
pop ebx
pop esi
pop edi
mov esp, ebp
pop ebp
;//Stack cleanup and return
ret 8

Conclusion

Advantage

Advantage of __fastcall calling convention is that it attempts to put arguments in registers, rather than on the stack, thus making function calls faster.

Disadvantage

Disadvantage of __fastcall calling convention is that functions with variable number of arguments (like printf())  can’t use __fastcall. Instead they must use __cdecl, because it is the only calling convention who knows the number of arguments in each function call; therefore only the caller can perform the stack cleanup.

Final Part: Cont. Calling Convention – Part IV

Read More