C++11 attribute [[gnu::flatten]] doesn't inline all functions recursively (but g++ does)
Here is a code snippet. When compiled with G++ -O3, the x() and y() functions are inlined into the z() function. When compiled with Clang++ 15, the z() function is not flattened. Under GCC the attribute applies recursive to all functions called by z(). Since the attribute is called [[gnu::flatten]] I'd expect Clang++ to do the same thing that GCC does.
extern float foo (float f);
// generate lots of code
template<int T>
inline float
x (float f)
{
if constexpr (T > 0)
{
return foo (x<T - 1> (f));
}
else
{
return 0;
}
}
inline float
y (float f)
{
f += x<100> (f);
return f;
}
[[gnu::flatten]]
float z ()
{
y (0);
}
Here is a Godbolt link: https://godbolt.org/z/zdn7z1zfn
The generated code for z() looks like this for Clang++ 15
z(): # @z()
push rax
xorps xmm0, xmm0
call float x<99>(float)
call foo(float)@PLT
[...]
As you can see, the z() function here calls the x<99> function, where I'd expect it to inline it.
This is a known issue
https://groups.google.com/g/llvm-dev/c/gGRCEi9g4ac/m/sEKFTnTGAwAJ
- the test case has some undefined behaviours on the function
[[gnu::flatten]]
float z ()
{
y (0);
}
the function do not have a return on end of function.
in the llvm InlineCost.cpp ,https://github.com/llvm/llvm-project/blob/main/llvm/lib/Analysis/InlineCost.cpp#L2021
bool CallAnalyzer::allowSizeGrowth(CallBase &Call) {
.....
if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
if (isa<UnreachableInst>(II->getNormalDest()->getTerminator()))
return false;
} else if (isa<UnreachableInst>(Call.getParent()->getTerminator()))
return false;
and in the function https://github.com/llvm/llvm-project/blob/main/llvm/lib/Analysis/InlineCost.cpp#L2078
void InlineCostCallAnalyzer::updateThreshold(CallBase &Call, Function &Callee) {
// If no size growth is allowed for this inlining, set Threshold to 0.
if (!allowSizeGrowth(Call)) {
Threshold = 0;
return;
}
it will set the Threshold to zero if the caller function which has UnreachableInst as Terminator .
that is means if a caller has UnreachableInst as Terminator, all the callee in the function can not be inline.
you need to add a return statement for the function, for example: return y (0);
- using -Rpass-missed=inline in the compile line to get the inline cost , and then you will find that after add
-mllvm --inline-threshold=500into command line, you will get all the functions to be inline.