<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/60799>60799</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            Simplify "X ? 1U << std::countr_zero(X) : 0" to "X & -X"
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            llvm:instcombine
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          kazutakahirata
      </td>
    </tr>
</table>

<pre>
    Compile:

```
// clang -std=c++20 -march=skylake -O2
#include <bit>

unsigned blsi_human_readable(unsigned X) {
  return X ? 1U << std::countr_zero(X) : 0;
}
```

I get:

```
  %2 = icmp eq i32 %0, 0
  %3 = tail call i32 @llvm.cttz.i32(i32 %0, i1 false) #3, !range !5
  %4 = shl nuw i32 1, %3
  %5 = select i1 %2, i32 0, i32 %4

  f3 0f bc c7 tzcnt  %edi,%eax
  b9 01 00 00 00             mov $0x1,%ecx
  c4 e2 79 f7 c1             shlx   %eax,%ecx,%eax
  0f 42 c7 cmovb  %edi,%eax
```

We could transform this into:

```
unsigned blsi_optimal(unsigned X) {
  return X & -X;
  // %2 = sub i32 0, %0
  // %3 = and i32 %2, %0
  //
  // c4 e2 78 f3 df             blsi   %edi,%eax
}
```

Proof: https://alive2.llvm.org/ce/z/C2eFaF
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyUVF9vuzYU_TSXl6tE5pq_DzykyZD2tEnTtL5Vxpjg1eAMm67Np58MSZr-1lZbhIiBc879d2zhnD6OSlWQPkB6iMTseztVz-I8e_Esej0JL6LGtm_V3g4nbRTwHbADsOs9Y5drfaQaqEZpxHjEjfMt8IMEegB6IIabQUyyB35wz29GPCvc_EJXHtejNHOrEPi-0R74T_dh5nHJs8XGOP3Uz4MYnyYlWtEYBVTcPj8ClQj5w8pCnJSfpxEfEXiN8e9BHPgel8R2wHfSzqOfns5qskDFyuY7ZMAvEpAfPi90uf-MR-W_7wgiUEoI_IBaDidUf6HmFF4yoD3eo_iC8kIblMKYFZcwY16GrfT-vNWcgIp7uo6xE8apJXHiPLwDiicxHlVYpHfyySLveoPj_PciHq_wlN-h0hWljJI-yIfsl0ickF0XQe2-ZsSOI-uwkShz9Gc5-kVMtRpoHxbi9YpsSmQxMna57n-DfUGghL3GF5a8sWSCijAvsctRxh9YrjevuIYTr-_EH-OyDhMK6cnBvjRfpPfplP9QKO1sWvSTGF1npwF9rx3q0dvvh__Rtvbk9SDMf_MrZbh5vNkwpLvsrJuZ3Ny8z2Sxw7-Aq5_E2F5nRp9jf2BeWl2Embbdh1aHMvCr1n27U36drO3C1uq9P7nQtSWYMPpF0XaxuJ2OQLVUQPUZqN6TqkUdtRVvS16KSFVxlmcpL3hZRH2VdXmXZo1ibdu0iWKJLLKubETD4yYtUxHpihhxRnHGSpbxYpslCUvzLivilhQrS0iYGoQ2t-iRdm5WVcbysoyMaJRxy7lIFBDAd3p0Xtqh0aMConBeTlX4tGnmows7VTvv3uW89kZVv-nhZHT3hkD0_88hIvT2Ql0tQRTNk6k-9vGofT83W2kHoHrJdv3bnCb7p5IeqF6Kc0D1Ut8_AQAA____ApXr">