Is it at all possible to direct any C++ compiler to do this?
Probably not directly - it's a quality-of-implementation issue.
Both Clang and GCC (for the recent versions tested), do this with the standard -O3
flag. Actually, they even do it with -O1
and -O2
... you have to disable optimization completely for them to emit the call to ExpensiveFunction
.
A quick attempt with x64 MSVC 19.24 shows it will optimize out the call as well, at least with /O2
.
MSVC command-line options are listed here.
GCC command-line options are in the manual, optimization-specific ones are here.
In general you can see what several different compilers do to the same code simultaneously with Matt Godbolt's compiler explorer, like so.
Note that this is only testing your sample code - if ExpensiveFunction
has observable side-effects, the optimizer will be unable to remove it.
Edit so it turns out that ExpensiveFunction
does have observable side-effects.
I recognize that an optimization that removes the call to ExpensiveFunction may be a destructive optimization,
There is no such thing as a "destructive optimization". Optimization is something that improves the non-functional characteristics of your program (typically performance or size) without changing the functional characteristics, which are specifically defined as the visible side-effects.
Let's consider your title, corrected to match the body of the question:
Are there C++ compiler options that allow aggressive removal of all function calls and passed in arguments to functions with non-empty bodies?
If the compiler is free to speed up your code by throwing away things that take time even if they have an externally-observable effect, life becomes very simple: it can just replace every program with
int main() {}
and call it a "destructive optimization". This is a correct solution to your corrected title, right?
... but I feel that this should be possible without converting print into a macro that will be compiled out in the most optimized configuration.
You can alternatively make the body of ExpensiveFunction
conditional, if for example it is really debug output whose observable side-effect you want to disable in some builds
int ExpensiveFunction() {
#ifndef DEBUG
// Do expensive calculation
// ...
std::cout << "You shouldn't see this!" << std::endl;
#endif
return 42;
}
But disabling code that has observable side-effects must always be under your manual control, unless you're happy with my extra-reductive whole-program optimization above.