Tag Archives: tangent

Off on a Tangent: Calling Conventions

There are many things that we take for granted when using a computer: the operating system, hard ware drivers, and graphical interfaces. By learning about these tools, it gives a new awareness into how much work it takes to get even a simple system working. Computer programmers also take advantage of a number of software components: compiler, linker, operating system, memory management functions and debuggers. There is quite a bit of behind the scenes that goes on even in a simple program like:

int foo(int a, int b) {
return a + b;
}
int main() {
return foo(3, 4);
}

Still has many layers underneath the obvious, the one I want to mention briefly today is the calling conventions. I was curious what happens when you call a function, and looking on wikipedia, I found an article that very nicely shows how many possible things could happen.

Normally in with gcc, when you call a function, the generated code pushes the arguments to the function onto the stack in reverse order, that is, last argument first, and then pushes the address of the next instruction to execute and jumps to the function. That function then can access the arguments and put it’s return value in EAX and jump back to the pushed instruction address. The caller must then clear the stack and use the EAX return value.

However, a way to optimize your code with gcc is the -mregparm=N command, which will put the N < 4 first arguments in registers EAX, EDX, and ECX respectively and push the rest onto the stack. This is much quicker since it requires less memory access. However, you must make sure to compile all your code this way, otherwise you’ll have some strange interactions when the conventions are mixed.

Peace and chow,

Ranok