<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/60546>60546</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
Simplify `urem` to `icmp+select` in `(x + 1) % n`
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
scottmcm
</td>
</tr>
</table>
<pre>
(Inspired by someone doing `self.write_index = (self.write_index + 1) % self.container.len();` in a circular buffer.)
If `x < n` (such as because it was just used to index an array of that length), then there's no need to modulo in `(x + 1) % n`, since there's only one case where the modulo does anything, and thus we could detect that case instead.
Alive2 proof: <https://alive2.llvm.org/ce/z/UNmz9j>
```llvm
define i64 @src(i64 noundef %x, i64 noundef %n) noundef {
%start:
%_3 = icmp ult i64 noundef %x, noundef %n
assume i1 %_3
%_6 = add nuw i64 noundef %x, 1
%0 = urem i64 %_6, noundef %n
ret i64 %0
}
; =>
define i64 @tgt(i64 noundef %x, i64 noundef %n) noundef {
%start:
%_3 = icmp ult i64 noundef %x, noundef %n
assume i1 %_3
%_6 = add nuw i64 noundef %x, 1
%w = icmp eq i64 %_6, noundef %n
%0 = select i1 %w, i64 0, i64 %_6
ret i64 %0
}
; Transformation seems to be correct!
```
Repro in opt: <https://llvm.godbolt.org/z/5vP7T8fE7>
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJzcVE1v4zYQ_TX0ZbAGTX1ZBx3iJAb2UhTt9rygyJHEgCJdfsTr_fXFSE7WSTdozwsYMjmceTPzyDcyRjM6xI5VB1Y9bGROkw9dVD6lWc2b3utLx8T-s4snE1BDf4HoZ_QOQXvjRmA1j2iH7TmYhF-N0_gNWPEATOz_bRcH2DHRAhMVLKfKuySNw7C16JjYM9Gy4sBqDsaBBGWCylYG6PMwYNjSMX9g_G79fh4oPeW7B0dBlDSrCWSEHpXMEcEkOMsITzkmyBE1JA9rNdKBDEFewA-QJpnAohvTRDnEPaQJHX0CMtFEcB4crtGz19kSCCVnYv-uL7dY7yEap_AGwTt7AeJNyYhwJjudvsBpjxGku6TJuJHipdOQphzhjKB8tho0JlRprXUBMS4mlHp7y8mdNc8o4BS8H1hxR9xMKZ0iK-6YODJxlIvD1trneevDyMRRIRPH70wc__pt_t4-seLxFpDaWX4UsZo0DsYhmLoEVvIYFBN72jifncaBaPhGLbyzOaLodd8crviiikmGRAUuBiDfr8XyioyaT5Bteg-1wL-BvobKGPOMYHYryC1ivSBKrcHl808BdzfufPHOAee1TwL4KGnA9OLEr001D9dFcSCgV07fUpfG9AtSd_6RH__-b_ZeyY5o6X2vBZxfWOAvixXk_1H-JUgXBx9mmYx3EBHnSNrtSUshoEpM7N6979tH_weewiJxf0o_VdEin9Hr3tt0lREpqHr-vfmyHx4bVjxudFfotmjlBrtd3VR1We6KdjN1spFDXTa83jdc1djK3dDzvapUKUVT83ZjOsFFwQWvOS_Frt2iVFWj2moo64IXWLGS4yyNfVXxxsSYsat5VdYbK3u0cRnpQjg8w3LIhKAJHzqK-dTnMbKSWxNT_IGSTLLY_WnmkzXDheYbCYAma_K0oztl4rBe1HVKfzgENznY7i1ro0lT7rfKz1cKr3-fTsE_LZdyXGqNTByXXv4JAAD__xAA74s">