How does an optimizing c++ compiler determine when a stack slot of a function(part of stack frame of a function) is no longer needed by that function, so it can reuse its memory? .
By stack slot I mean a part of stack frame of a function, not necessarily a whole stack frame of a function and an example to clarify the matter is, suppose we have a function that has six integer variables defined in its scope, when it's time to use sixth variable in the function, fifth variable's become useless so compiler can use same memory block for fifth and sixth variables.
any information on this subject is appreciated.

6 Years
Discussion Span
Last Post by Garrett2011

Optimization by the compiler is always a nebulous matter because it is really up to the compiler to do the optimizations it deems necessary or not.

One solution is to use scopes within your functions (I mean "{ ..code.. }" just like that). This way the compiler can more easily determine at what point things become useless and can better piece together the smaller stack frames within the function. There is a general guideline in C++ (and in newer revisions of C), which says that you should try and reduce the scope (or life-time) of your variables to the bare minimum, as much as possible without making the code to messy. So, of course, the old C-style way of putting all variable declarations at the start of the function should be avoided altogether.

As far as how intelligent the compiler is at doing this DU-chain optimization.. it depends on the compiler (very highly as a matter fact). This compiler-intelligence is a reason why the intel compiler, for example, can sometimes produce executable code that is 2 or 3 times faster than any other compiler.


Typically it doesn't, unless you force it to. For example:

> g++44 -Wall -std=c++98 -pedantic -Werror -fomit-frame-pointer -fstrict-aliasing -fconserve-stack  -fno-defer-pop

The frame of a function is transient, and the memory is reclaimed as soon as the function returns. It could also cause most debuggers to stumble.



> g++44 -Wall -std=c++98 -pedantic -Werror -fomit-frame-pointer -fstrict-aliasing -fconserve-stack  -fno-defer-pop

what are those, compiler options?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.