<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/54692>54692</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
[clang] Missed optimization: Bitwise & generates worse code than && for booleans
</td>
</tr>
<tr>
<th>Labels</th>
<td>
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
AMS21
</td>
</tr>
</table>
<pre>
Given the following source code: [godbolt link](https://godbolt.org/z/Kvc8fTxMh)
```cpp
bool is_ctrl_1(const char c) { return (c >= 0 && c <= 31) | (c == 127); }
bool is_ctrl_2(const char c) { return (c >= 0 & c <= 31) | (c == 127); }
bool is_ctrl_3(const char c) { return (c >= 0 & c <= 31) || (c == 127); }
```
compiling with `-O3`. We we the following assembly:
```asm
is_ctrl_1(char): # @is_ctrl_1(char)
cmp dil, 32
setb cl
cmp dil, 127
sete al
or al, cl
ret
is_ctrl_2(char): # @is_ctrl_2(char)
mov eax, edi
not al
shr al, 7
cmp dil, 32
setl cl
and cl, al
cmp dil, 127
sete al
or al, cl
ret
is_ctrl_3(char): # @is_ctrl_3(char)
mov eax, edi
not al
shr al, 7
cmp dil, 32
setl cl
and cl, al
cmp dil, 127
sete al
or al, cl
ret
```
As you can see `is_ctrl_2` and `is_ctrl_3` generates more assembly which is not optimal and could be the same as `is_ctrl_1`. GCC does generate the exact same assembly for all 3 functions.
Note using `||` instead of `|` in `is_ctrl_1` doesn't change the generated code.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJztVktv2zAM_jX2hWggS3EeBx_y2HoYuh02YMdBluRYm2IFlpy0_fWj5HhNgnRbu2GnGYoVkSL5kVI-prTyobjVe9WArxVU1hh70M0GnO1aoUBYqRK2gCRfbqwsrfFgdPMtydcJndXe7xxqE_oWx1E_su0GV4_4ebcXs-rT_V2d0HlC1glZHN8T0g-x2_WS0loD2n0RvjVfMnQtbOM8iJq3INAakukSWuW7toGghYS9SdgaCK4mOCBIVkHCsn77ati3DtKMTgMGtkTN-hTKWWD6wsB_Jyr786i_E3io-SkOYbc7bcJxH7SvAbU3Hxi-R_BZwUFdXAnunNqW5iGc-LXT5G7bS84OEnOKWBbw7JNQBsmYXDOL_oZ9YruLs9QmoStg9FztlC_jNvNTs1CcSzsVZn5hZ9t-5tHs0isez3m29HXZ0uey3dp9nBW_D_GV1Of6xvoB3nk6dXsCe_rSEpprJeSNhKMcrS4j_qMCs9cVmP0v8C8KfJUbFg4ebAeCN-heBW54urETEgGfyAJrwEY1quVeOSxtq37wBRxqLWrku1hRu_N6y010IGxnJJQ90Ti-DTanXrPIRberFUiLXgf_cbu658IPRsdAFSbMjQEGVdcIr5FVR3027y2adS7QWMgzUmaArJF3FZdgq0EehZcgYvwmodNI0s2mhzDgkbFNjlJZMDlnc5567Y0qsGcKg5uxWcKdRoyyT14_8gAt3OGl9gftVKT1p-odbOv61otheDP0uJBd6ByKNy7tWlNc9F-k8K4cIafjwpj9MN3sWvtVCY9LBNEph1_y8WRO07rgMsvGZJarfDqXks2rPKumM17mc0J4TqvU8FIZF1LBLFJdUEIpGZMMn2lGRqRSOeETkZPxhE_YDH92asu1GYXA4Z9A2hYRQ9ltHCqNdt49KfHg9KZRavDPO1_btljcfaRZGsEWEel37mdVBQ">