<html>
<head>
<base href="https://bugs.llvm.org/">
</head>
<body><table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Bug ID</th>
<td><a class="bz_bug_link
bz_status_NEW "
title="NEW - [x86-64] missed optimization: can use the zero flag which is set by BSR"
href="https://bugs.llvm.org/show_bug.cgi?id=40090">40090</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>[x86-64] missed optimization: can use the zero flag which is set by BSR
</td>
</tr>
<tr>
<th>Product</th>
<td>new-bugs
</td>
</tr>
<tr>
<th>Version</th>
<td>trunk
</td>
</tr>
<tr>
<th>Hardware</th>
<td>PC
</td>
</tr>
<tr>
<th>OS</th>
<td>All
</td>
</tr>
<tr>
<th>Status</th>
<td>NEW
</td>
</tr>
<tr>
<th>Severity</th>
<td>enhancement
</td>
</tr>
<tr>
<th>Priority</th>
<td>P
</td>
</tr>
<tr>
<th>Component</th>
<td>new bugs
</td>
</tr>
<tr>
<th>Assignee</th>
<td>unassignedbugs@nondot.org
</td>
</tr>
<tr>
<th>Reporter</th>
<td>arthur.j.odwyer@gmail.com
</td>
</tr>
<tr>
<th>CC</th>
<td>htmldeveloper@gmail.com, llvm-bugs@lists.llvm.org
</td>
</tr></table>
<p>
<div>
<pre>I was trying to trick Clang into generating optimal code for a 128-bit "count
leading zeros" function. I started with the most naive version:
using u128 = __uint128_t;
using u64 = uint64_t;
int countleadingzerosA(u128 x)
{
return (x >> 64) ? __builtin_clzll(u64(x >> 64)) + 64
: __builtin_clzll(u64(x));
}
testq %rsi, %rsi
je .LBB1_2
bsrq %rsi, %rax
xorl $63, %eax
orl $64, %eax
retq
.LBB1_2:
bsrq %rdi, %rax
xorl $63, %eax
retq
By examining the generated code (-O3), I was able to produce this version:
int countleadingzerosB(u128 x)
{
int lo = 63 - __builtin_clzll(u64(x)) + 64;
int hi = 63 - __builtin_clzll(u64(x >> 64));
return 63 - ((x >> 64) ? hi : lo);
}
bsrq %rdi, %rax
xorl $64, %eax
bsrq %rsi, %rcx
testq %rsi, %rsi
cmovel %eax, %ecx
movl $63, %eax
subl %ecx, %eax
retq
I believe there are two missed optimizations here that MIGHT be relatively
straightforward to implement.
Number 1: According to <a href="https://www.felixcloutier.com/x86/BSR.html">https://www.felixcloutier.com/x86/BSR.html</a> the
instruction `bsrq %rsi, %rcx` sets ZF in exactly the same way as `testq %rsi,
%rsi`, so the `testq` instruction is redundant.
Number 2: If dataflow can remember that the value in %rax is in the range
[0..63], then it should be able to apply the same SUB-to-XOR strength reduction
that it did in countleadingzerosA: we can replace the final two instructions
with `xorl $63, %ecx; movl %ecx, %eax` and then the `movl` can be eliminated by
register allocation.
I can easily work around number 2 by just doing `return 63 ^ ...` instead of
`return 63 - ...`; I was just surprised that the compiler would do SUB-to-XOR
in some places but then seemingly miss it in others.</pre>
</div>
</p>
<hr>
<span>You are receiving this mail because:</span>
<ul>
<li>You are on the CC list for the bug.</li>
</ul>
</body>
</html>