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

    <tr>
        <th>Summary</th>
        <td>
            Failure to remove mask from shift amounts in unrolled loop
        </td>
    </tr>

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

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

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

<pre>
    This code generates unnecessary `and` instructions on the shift amounts when the loop is unrolled

```
#include <stddef.h>

void foo(unsigned *a, size_t n, unsigned x) {
  #pragma unroll(8)
  for (size_t i = 0; i != n; ++i)
    a[i] = x << (i & 31);
}
```

The computeKnownBits in the middle end is able to prove that some bits of the unrolled induction variable are 0 and that causes InstCombine to change the AND mask from 31, to 24, 25, 26, 27, etc.

SelectionDAG's computeKnownBits and AssertZExt nodes are unable to get the same known zero bits that InstCombine saw due to the phi recurrence. This prevents SelectionDAG from converting the AND mask back to 31 to remove it during instruction selection.

https://godbolt.org/z/cfGd7rWfz

cc: @nikic @RKSimon @efriedma-quic @goldsteinn 
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJxsVN2O4zYPfRrmhpjAluK_C1_kZ7P4sMB30V2gQG8KWaJtdWzJleTM7Dx9ITnTybQFAoayeJhzTmgK7_VgiFooTlBcdmINo3VtsMtCTu46q362P0btUVpFOJAhJwJ5XI0hSd4L9xOhzIRRUGaojQ9ulUFb49EaDCOhH3UfUMx2NcHjy0jb48naBXVs5Ow0kYLsAtnxHsvs_tmOjGsjp1URAj_7oBT1-xH4l0fMzWqFvbXA6tUkTQqBHQWwM3r9Rr8HNDH_-_IVWINQnTY4IjC-ODHM4k4JWF0Da96ve-sQWH1vpRH4BTPgp5iyPJ5MPAE7ATvpByCigOKkobgkzGvUAPwcm0VoiTyP1fxOBKrLf5uQ4o-RUNp5WQN9M_bFnHTwqDdHZ63UREhGRV9FNxEGi4uzN8IwioDezoRdRNg-Id69R23U9q_hTTidoMIRZiiM2rBSrJ48_s_4cLZzp01qLkdhBkq9jv-_4Cz8M_bOzknTOVawQ0xYkWKZYhUjBbl_FPadJkoMLsevwCr_b5WRytF7cuG3L68BjVXkE8vVvGsdKGwjJ2bC54jEN3J205xkPPL34gXVmoARtIwaHcnVOTKS9pimfnF0ozi3j_w2idKaG7mgzfBZfyfkc-zJ8xgdzdF_HVCtLtY-vCLo35t-smIMYfHAj8CuwK6DVZ2dwt66Adj1DdhV9l9V5X7t3x5BUgI_Ihwyo5-1jMkv377r2ZqYUu80qVk8_blud4OdlA-kjcGdarlqeCN21OZlU5WH5lDWu7Ft8owXKu8aSTIryy5XBcursmuKospEzXe6ZRnjeZbXeZVXh2Jf85wVZV3zui6LjMr4y7PQ036abnMUsNPer9SWzaEud5PoaPJp7zAWK4Af45IZyABjcRe5Nj5-6tbBwyGbtA_-o1XQYaL2KvS0Onpw-mMGPy8ebT7GPe6e3eqm9h9W6zCu3V7aGdg1Mdq-nhZn_yAZgF2TAA_smjT8FQAA__9h3qmu">