Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are there so many different calling conventions?

Historically, why does it seem like just about everyone and their kid brother defined their own calling conventions? You've got C, C++, Windows, Pascal, Fortran, Fastcall and probably a zillion others I didn't think to mention. Shouldn't one convention be the most efficient for the vast majority of use cases? Is there ever any good reason to prefer one over the other?

like image 565
dsimcha Avatar asked Aug 06 '10 22:08

dsimcha


People also ask

Why do we have calling conventions?

A calling convention governs how functions on a particular architecture and operating system interact. This includes rules about includes how function arguments are placed, where return values go, what registers functions may use, how they may allocate local variables, and so forth.

What are the different calling conventions?

Microsoft x64 calling convention That means RCX, RDX, R8, R9 for integer, struct or pointer arguments (in that order), and XMM0, XMM1, XMM2, XMM3 for floating point arguments. Additional arguments are pushed onto the stack (right to left). Integer return values (similar to x86) are returned in RAX if 64 bits or less.

How many prevalent calling conventions do exist?

There are three major calling conventions that are used with the C language on 32-bit x86 processors: STDCALL, CDECL, and FASTCALL.

What is the default calling convention?

__cdecl is the default calling convention for C and C++ programs. Because the stack is cleaned up by the caller, it can do vararg functions. The __cdecl calling convention creates larger executables than __stdcall, because it requires each function call to include stack cleanup code.


2 Answers

The calling conventions you mention were designed over the course of decades for different languages and different hardware. They all had different goals. cdecl supported variable arguments for printf. stdcall resulted in smaller code gen, but no variable arguments. Fastcall could greatly speed up the performance of simple functions with only one or two arguments on older machines (but is rarely a speed up today.)

Note than when x64 was introduced, on Windows at least, it was designed to have a single calling convention.

Raymond Chen wrote a great series on the history of calling conventions, you can start here.

like image 197
Michael Avatar answered Oct 21 '22 05:10

Michael


Because historically everyone and their kid brother did define their own calling conventions. They were all created for different purposes and thus driven by different performance needs. For instance, C++ favours optimisations for passing the this parameter.

like image 31
Marcelo Cantos Avatar answered Oct 21 '22 03:10

Marcelo Cantos