Do C compilers optimize the execution stack in case of successive function calls?

LOSnel Source

I have a basic question about call stack behavior. I would like to know how the system manage the call stack memory when a function is called at the end of an other function.

For example:

void FunctionOne(void)
{
    [...] // Various code operations
    FunctionTwo();
}


void FunctionTwo(void)
{
    [...] // Various code operation
    FunctionThree();
}


void FunctionThree(void)
{
    [...] // Various code operation
    FunctionFour();
    [...] // Various code operation
}

Does the call stack memory is cleaned when the execution jumps from FunctionOne() to FunctionTwo() because there is no instruction after the call of FunctionTwo()?

Is the stack memory keeping the entire level of execution when it goes from FunctionTwo() to FunctionThree()?

Or maybe I'm wrong since the beginning about how the call stack works and its purpose?

Thanks for your help.

cembeddedcompiler-optimizationcallstack

Answers

answered 5 days ago chqrlie #1

Indeed the calls to functionTwo() from functionOne() and to functionThree() from functionTwo() could be generated as jumps after some specific adjustments to account for the arguments and local variables of the caller (what you can stack cleanup). This is called tail call optimization. They could also be generated inline, the code of the called function becoming part of the calling function.

Whether the C compiler performs tail call optimisation, inline generation or some more advanced trick is a quality of implementation issue. Doing so may improve code speed, and reduce stack usage, but make debugging more difficult as the call stack may be confusing to trace.

The Standard imposes no requirements regarding this, the compiler must generate code as if the calls take place normally.

answered 5 days ago X12koni #2

Should be like this photo: memory stack

comments powered by Disqus