Clang 23 misses a simple loop optimisation
Clang 23 misses a seemingly simple optimisation opportunity1. This is a reminder not to rely on the Sufficiently Smart Compiler. For performance-critical code, check your assembly.
In the code below, scale_sum implements
and scale_sum_2 implements
where b = scale and a[i] = foos[i].
auto scale_sum(unsigned const scale,
unsigned const * const foos,
unsigned const n) noexcept -> unsigned {
unsigned sum{0};
for (unsigned i{0}; i < n; ++i) {
sum += scale * foos[i];
}
return sum;
}
auto scale_sum_2(unsigned const scale,
unsigned const * const foos,
unsigned const n) noexcept -> unsigned {
unsigned sum{0};
for (unsigned i{0}; i < n; ++i) {
sum += foos[i];
}
return sum * scale;
}
With unsigned integers, the transformation is valid even with overflow.
The assembly for the inner loop of each function is given below.
Clang emits vpmulld instructions within scale_sumβs loop rather than factoring out the multiplication as in scale_sum_2.
Enabling AVX-512 made no difference to this optimisation.
; scale_sum
vpmulld zmm5, zmm0, zmmword ptr [rsi + r8]
vpmulld zmm6, zmm0, zmmword ptr [rsi + r8 + 64]
vpaddd zmm1, zmm5, zmm1
vpaddd zmm2, zmm6, zmm2
vpmulld zmm5, zmm0, zmmword ptr [rsi + r8 + 128]
vpaddd zmm3, zmm5, zmm3
vpmulld zmm5, zmm0, zmmword ptr [rsi + r8 + 192]
vpaddd zmm4, zmm5, zmm4
; scale_sum_2
vpaddd zmm0, zmm0, zmmword ptr [rsi + r8]
vpaddd zmm1, zmm1, zmmword ptr [rsi + r8 + 64]
vpaddd zmm2, zmm2, zmmword ptr [rsi + r8 + 128]
vpaddd zmm3, zmm3, zmmword ptr [rsi + r8 + 192]
-
I previously posted this on Redditβs /r/cppΒ ↩