1. 程式人生 > >64位與32位系統中函式呼叫中暫存器使用規則

64位與32位系統中函式呼叫中暫存器使用規則

32位系統:

Calling Conventions

The x86 architecture has several different calling conventions. Fortunately, they all follow the same register preservation and function return rules:

  • Functions must preserve all registers, except for eax, ecx, and edx, which can be changed across a function call, and esp
    , which must be updated according to the calling convention.
  • The eax register receives function return values if the result is 32 bits or smaller. If the result is 64 bits, then the result is stored in the edx:eax pair.

The following is a list of calling conventions used on the x86 architecture:

  • Win32 (__stdcall
    )

    Function parameters are passed on the stack, pushed right to left, and the callee cleans the stack.

  • Native C++ method call (also known as thiscall)

    Function parameters are passed on the stack, pushed right to left, the "this" pointer is passed in the ecx register, and the callee cleans the stack.

  • COM (__stdcall for C++ method calls)

    Function parameters are passed on the stack, pushed right to left, then the "this" pointer is pushed on the stack, and then the function is called. The callee cleans the stack.

  • __fastcall

    The first two DWORD-or-smaller arguments are passed in the ecx and edx registers. The remaining parameters are passed on the stack, pushed right to left. The callee cleans the stack.

  • __cdecl

  • Function parameters are passed on the stack, pushed right to left, and the caller cleans the stack. The __cdecl calling convention is used for all functions with variable-length parameters.

    Calling Conventions 64位系統:

    Unlike the x86, the C/C++ compiler only supports one calling convention on x64. This calling convention takes advantage of the increased number of registers available on x64:

    • The first four integer or pointer parameters are passed in the rcx, rdx, r8, and r9 registers.
    • The first four floating-point parameters are passed in the first four SSE registers, xmm0-xmm3.
    • The caller reserves space on the stack for arguments passed in registers. The called function can use this space to spill the contents of registers to the stack.
    • Any additional arguments are passed on the stack.
    • An integer or pointer return value is returned in the rax register, while a floating-point return value is returned in xmm0.
    • rax, rcx, rdx, r8-r11 are volatile.
    • rbx, rbp, rdi, rsi, r12-r15 are nonvolatile.

    The calling convention for C++ is very similar: the this pointer is passed as an implicit first parameter. The next three parameters are passed in registers, while the rest are passed on the stack.