https://gcc.gnu.org/bugzilla/show_bug.cgi?id=124912
Bug ID: 124912
Summary: Failure to canonicalize common ctz idioms
Product: gcc
Version: 16.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: tree-optimization
Assignee: unassigned at gcc dot gnu.org
Reporter: [email protected]
Target Milestone: ---
A similar case to Bug 124630
The difference is that Clang generates the correct output in this example,
while GCC does not (in the original bug, both produce incorrect assembly).
Compiled with: -O2 -march=rv64gcb
int builtin_popcount(unsigned x) {
if (x != 0)
return __builtin_popcount((x & -x) - 1);
return 32;
}
GCC assembly:
builtin_popcount:
bne a0,zero,.L5
li a0,32
ret
.L5:
negw a5,a0
and a0,a5,a0
addiw a0,a0,-1
cpopw a0,a0
ret
Clang assembly:
builtin_popcount:
ctzw a0, a0
ret
On Godbolt (https://godbolt.org/z/ffndfKE7o), there is a similar case for
__builtin_clz with the same issue.
There is also an example (ntz2) from Hacker’s Delight 2nd Edition where we have
similar problem.
int ntz2(unsigned x) {
int n=0;
x = ~x & (x - 1);
while (x != 0) {
n = n + 1;
x = x >> 1;
}
return n;
}
GCC assembly:
ntz2:
addiw a5,a0,-1
andn a0,a5,a0
beq a0,zero,.L11
clzw a0,a0
li a5,32
subw a0,a5,a0
.L11:
ret
Clang assembly:
ntz2:
ctzw a0, a0
ret