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

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

    <tr>
      <th>Labels</th>
      <td>
            llvm:instcombine,
            missed-optimization
      </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 blsr_human_readable(unsigned X) {
  return X ? 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 = xor i32 %4, -1
  %6 = and i32 %5, %0
  %7 = select i1 %2, i32 0, i32 %6

  f3 0f bc cf tzcnt  %edi,%ecx
  89 f8                      mov    %edi,%eax
 0f b3 c8                   btr    %ecx,%eax
  85 ff test   %edi,%edi
  0f 44 c7                   cmove %edi,%eax
```

We could transform this into:

```
unsigned blsr_optimal(unsigned X) {
  return X & (X - 1);
  // %2 = add i32 %0, -1
  // %3 = and i32 %2, %0
  //
  // c4 e2 78 f3 cf blsr   %edi,%eax
}
```

Proof: https://alive2.llvm.org/ce/z/zpNB-G
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJykVE2P8jYX_TU3mytQco2TsMiCj5dX3bSVqqrPbuQ4DrjjxNR2pjMs-tsrm8mUoXRUqQgck5xz7kfOtfBeH0elGuBb4PtMTOFkXfMsLlMQz-KknQgia2331uzscNZGAdtAvod8Xsv8_Xv9SwegA0ojxiMufOiA7SXQFmhLOS4G4eQJ2N4_vxnxrHDxA808pkdppk4hsF2rA7D_3YaZxpRnh63x7uk0DWJ8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