[clang++] Loop vectorization not happening in outlined lambda function
void foo(int *A, int *B, int *C, int *D, int len) {
auto func = [&] () {
for (int i =0; i < len; i++)
A[i] = B[i] * C[i] + D[i];
};
func();
}
$ clang++ lambda.cpp -O3 -c -S -emit-llvm -fno-unroll-loops -fno-inline
The issue is lambda is outlined into another function due to which variable "len" is loaded inside the loop. Loop bounds are not determined due to this load (compiler might be expecting alias to the load instruction).
The original problem is in Geekbench 6.1 src/geekbench/ml/backend/cpu/depthwise_convolution_2d.cpp Line no: 402. The reason for adding "-fno-unroll-loops -fno-inline" in the above code is that for smaller functions, lambda is inlined and there is no problem in vectorization. In Geekbench, inlining doesn't happen for lambda, but outlined, and hence fails to vectorize. A good performance gain is expected in Geekbench if vectorization happens for this loop.
@llvm/issue-subscribers-clang-codegen
Author: None (kavitha-natarajan)
$ clang++ lambda.cpp -O3 -c -S -emit-llvm -fno-unroll-loops -fno-inline
The issue is lambda is outlined into another function due to which variable "len" is loaded inside the loop. Loop bounds are not determined due to this load (compiler might be expecting alias to the load instruction).
The original problem is in Geekbench 6.1 src/geekbench/ml/backend/cpu/depthwise_convolution_2d.cpp Line no: 402. The reason for adding "-fno-unroll-loops -fno-inline" in the above code is that for smaller functions, lambda is inlined and there is no problem in vectorization. In Geekbench, inlining doesn't happen for lambda, but outlined, and hence fails to vectorize. A good performance gain is expected in Geekbench if vectorization happens for this loop.
@llvm/issue-subscribers-clang-frontend
Author: None (kavitha-natarajan)
$ clang++ lambda.cpp -O3 -c -S -emit-llvm -fno-unroll-loops -fno-inline
The issue is lambda is outlined into another function due to which variable "len" is loaded inside the loop. Loop bounds are not determined due to this load (compiler might be expecting alias to the load instruction).
The original problem is in Geekbench 6.1 src/geekbench/ml/backend/cpu/depthwise_convolution_2d.cpp Line no: 402. The reason for adding "-fno-unroll-loops -fno-inline" in the above code is that for smaller functions, lambda is inlined and there is no problem in vectorization. In Geekbench, inlining doesn't happen for lambda, but outlined, and hence fails to vectorize. A good performance gain is expected in Geekbench if vectorization happens for this loop.
See https://github.com/llvm/llvm-project/issues/112060 also.
I think clang-codegen is a good tag. Alias analysis is partly to blame, but I'd prefer clang lowers lambda more appropriately like just mark them const somehow. Currently the object passed to lambda fails to transmit the information that int len is a constant.
Feel free to remove it if you think otherwise.
@llvm/issue-subscribers-clang-codegen
Author: None (kavitha-natarajan)
$ clang++ lambda.cpp -O3 -c -S -emit-llvm -fno-unroll-loops -fno-inline
The issue is lambda is outlined into another function due to which variable "len" is loaded inside the loop. Loop bounds are not determined due to this load (compiler might be expecting alias to the load instruction).
The original problem is in Geekbench 6.1 src/geekbench/ml/backend/cpu/depthwise_convolution_2d.cpp Line no: 402. The reason for adding "-fno-unroll-loops -fno-inline" in the above code is that for smaller functions, lambda is inlined and there is no problem in vectorization. In Geekbench, inlining doesn't happen for lambda, but outlined, and hence fails to vectorize. A good performance gain is expected in Geekbench if vectorization happens for this loop.
cc: @zygoloid is there a way we can make the int len a const while generating llvm ir for this lambda in clang codegen?
I think determining that the captured int len value is constant is too complex to do in the frontend. We're not really set up to do that kind of analysis. Maybe once we have ClangIR -- I think there's a fairly broad class of lambda optimizations we could do once we have a mutable high-level IR that's amenable to analyses.
Is a source change acceptable? Changing the capture default from [&] to [=] might help a bit, but not enough to infer the store to A[i] doesn't alias len, so that probably won't help enough. Changing the loop to for (int i =0, L = len; i < L; i++) should allow vectorization.
Could we split the loop into an &A[i] <= &len and a &A[i] > &len case, and virtualize the two pieces? That should be correct even without a noalias assumption.
How important is it that we optimize this well despite a key part of the optimizer (the inliner) being turned off?
I think determining that the captured
int lenvalue is constant is too complex to do in the frontend. We're not really set up to do that kind of analysis.
A related issue https://github.com/llvm/llvm-project/issues/112060 is quite similar, lambda replaced with a class. Not sure if we can optimize that one in the current framework.
Maybe once we have ClangIR -- I think there's a fairly broad class of lambda optimizations we could do once we have a mutable high-level IR that's amenable to analyses.
Nice, looking forward to it.
Is a source change acceptable? Changing the capture default from
[&]to[=]might help a bit, but not enough to infer the store toA[i]doesn't aliaslen, so that probably won't help enough. Changing the loop tofor (int i =0, L = len; i < L; i++)should allow vectorization.
Not sure if source code is possible as it is coming from a benchmark.
Could we split the loop into an
&A[i] <= &lenand a&A[i] > &lencase, and virtualize the two pieces? That should be correct even without a noalias assumption.
Yeah, we were thinking of one of two approaches. a) if clang could modify the code in a way that makes int len as constant, that would be ideal. Given that is not the case we'll add a runtime check (approach 2).
How important is it that we optimize this well despite a key part of the optimizer (the inliner) being turned off?
We'd like the optimization to happen under standard optimization flags like -O3. maybe supplying another flag is fine as long as it doesn't regress remaining benchmarks. Thanks.
In geekbench, the loop bound is already declared as const only. However, when it is passed to the outlined function, it is stored as a pointer within an anonymous structure and pass the structure as argument to the outlined function. It does not propagate the information that it is a const. If clang can preserve it as const or attach noalias attribute to such const scalar, LICM can take care of hoisting it out.
Will it be possible to add lifetime markers (at clang level) for the created object? That should help disambiguate alias sets.
void foo(int *A, int *B, int *C, int *D, int len) {
// func_object_lifetime_start
auto func = [&] () {
for (int i =0; i < len; i++)
A[i] = B[i] * C[i] + D[i];
};
func();
// Func_object_lifetime_end
}
Given lifetime markers, in llvm it should be possible to analyze that A, B, C, D and len never alias with the this pointer.
Just saw that removing '-fno-inline' vectorizes it. Why are we not enabling inline? https://godbolt.org/z/KPrd1GW7s
Given lifetime markers, in llvm it should be possible to analyze that A, B, C, D and len never alias with the
thispointer.
We already emit lifetime markers for func in foo. But the problem is that the lambda is lowered as:
struct lambda {
int **A, **B, **C, **D, *len;
void operator()() const {
for (int i =0; i < len; i++)
A[i] = B[i] * C[i] + D[i];
}
};
void foo(int *A, int *B, int *C, int *D, int len) {
auto func = lambda{&A, &B, &C, &D, &len};
func();
}
and because inlining has been turned off, you'd need some pretty fancy interprocedural analysis to take the knowledge that, in foo, A can't point to len and turn that into knowledge that, in the lambda::operator() function, *this->A can't point to the same thing that this->len points to. Lifetime markers in foo probably aren't incredibly helpful here.
(For what it's worth, I'm a little surprised you can vectorize this anyway, at least without a runtime check -- B, C, and D could alias A. And if we're doing a runtime check for those, shouldn't we also be able to do one for len?)
Just saw that removing '-fno-inline' vectorizes it. Why are we not enabling inline? https://godbolt.org/z/KPrd1GW7s
It gets inlined in this smaller testcase. '-fno-inline' is added to reproduce the geekbench scenario. In case of lambda function, it gets outlined in geekbench.
(For what it's worth, I'm a little surprised you can vectorize this anyway, at least without a runtime check -- B, C, and D could alias A.
Compiler does insert a runtime check with inlining enabled. https://godbolt.org/z/x6Y3dPPW4
And if we're doing a runtime check for those, shouldn't we also be able to do one for len?)
Yeah so that's our next step. I believe with -fno-inline, because len isn't loop-invariant, the compiler doesn't bother moving forward.
The inability to recognize len as a constant inhibits the compiler's ability to perform optimizations such as vectorization, affecting performance.
Proposal: The proposal is to use the restrict keyword for pointer parameters in the foo function
// Just check which ever fits "__restrict__" or "restrict" depends on the C/C ++ compiler you are using.
// vectorized loop (vectorization width: 4, interleaved count: 1) [-Rpass=loop-vectorize]
// void foo(int *__restrict__ A, int *__restrict__ B, int *__restrict__ C, int *__restrict__ D, int len) {
void foo(int *restrict A, int *restrict B, int *restrict C, int *restrict D, int len) {
auto func = [&] () {
for (int i = 0; i < len; i++)
A[i] = B[i] * C[i] + D[i];
};
func();
}
Reduction in Aliasing: The restrict keyword informs the compiler that pointers are not aliasing. This known memory non-overlap allows for more aggressive optimizations.
Performance Improvements: By reducing aliasing assumptions, the compiler can perform optimizations like vectorization even when the lambda function is outlined.
Minimal Code Change: This change requires a simple addition of qualifiers and doesn't necessitate rewriting or restructuring the entire function logic.
Thank you.
Proposal: The proposal is to use the restrict keyword for pointer parameters in the foo function
If the programmer can add __restrict that would make it a bit easier to fix. Even with __restrict, the vectorization didn't happen (https://godbolt.org/z/WcEcjzzb1) but that should be less difficult to handle.
Proposal: The proposal is to use the restrict keyword for pointer parameters in the foo function
If the programmer can add __restrict that would make it a bit easier to fix. Even with __restrict, the vectorization didn't happen (https://godbolt.org/z/WcEcjzzb1) but that should be less difficult to handle.
For "Even with __restrict, the vectorization didn't happen" depends upon the loop and placing inside the function.
&
but that should be less difficult to handle
Yes, here you go.
Explanation:
case 1
The loop is encapsulated within a lambda function. While lambda functions can capture variables and simplify code, they introduce extra levels of abstraction.
Lambda functions, especially those capturing by reference ([&]), are turned into functors (objects with operator() defined) by the compiler. The outlined nature of lambdas is/can sometimes prevent the compiler from fully optimizing the loop within, especially with aggressive inline disabling.
// -O3 -fno-inline -g0 -fno-unroll-loops -Rpass=vectorize
// -O3 -g0 -fno-unroll-loops -Rpass=vectorize ==> it will work as there is no inline flag, i.e. vectorization.
// no vectorisation Compiler returned: 0
void foo(int *__restrict__ A, int *__restrict__ B, int *__restrict__ C, int *__restrict__ D, int len) {
auto func = [&] () {
for (int i = 0; i < len; i++)
A[i] = B[i] * C[i] + D[i];
};
func();
}
case 2
Since the loop is directly within the foo function, the compiler is allowed to see the iteration space and loop structure, so you get the vectorization.
// -O3 -fno-inline -g0 -fno-unroll-loops -Rpass=vectorize
// vectorisation <source>:34:5: remark: vectorized loop (vectorization width: 4, interleaved count: 1) [-Rpass=loop-vectorize]
//34 | for (int i = 0; i < len; i++) {
// | ^
//Compiler returned: 0
void foo(int *__restrict__ A, int *__restrict__ B, int *__restrict__ C, int *__restrict__ D, int len) {
//auto func = [&] () {
for (int i = 0; i < len; i++)
A[i] = B[i] * C[i] + D[i];
//func();
}
I hope the explanation is useful.
Could you provide a detailed explanation of the context and the specific area within the LLVM project where your code is being used ?
Thank you