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

    <tr>
        <th>Summary</th>
        <td>
            [IndVars] Incorrect comparison folding
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            new issue
      </td>
    </tr>

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

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

<pre>
    In the following test (https://llvm.godbolt.org/z/rT64Yb1K6), `-indvars` currently folds `%cmp2` to `false`:
```
declare void @use(i1)

define void @test(ptr %arr) {
entry:
  br label %loop.header

loop.header:
  %iv = phi i64 [ %iv.inc, %loop.latch ], [ 0, %entry ]
  %prev = phi i32 [ %v, %loop.latch ], [ 0, %entry ]
  %ptr = getelementptr inbounds i32, ptr %arr, i64 %iv
  %v = load i32, ptr %ptr
  %cmp1 = icmp sgt i32 %v, 0
  br i1 %cmp1, label %if, label %loop.latch

if:
  %cmp2 = icmp slt i32 %prev, 0
  call void @use(i1 %cmp2)
  br label %loop.latch

loop.latch:
  %iv.inc = add nuw nsw i64 %iv, 1
  %cmp = icmp ult i64 %iv.inc, 16
  br i1 %cmp, label %loop.header, label %exit

exit:
  ret void
}
```
This is incorrect: While we have a guard that `%v > 0`, the value of `%v` in the `%prev` phi comes from the previous iteration, so the used context is incorrect.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJydVE1vnDAQ_TVwsYLAfGz2wCHJNlLUa9SqR4MHcOu1kW12k_76jg3ssklOlUCYmec3zzPjaTR_r18UcQOQTkupz0L1xIF1JKL3g3OjjfKHiD7jI-XpmPSaN1q6RJseTX_xNa9V8avJvlcR3Uf0iURVeicUPzFjcUnayRhQTr57fm69O6Jlexyp9zrtDR2TFrwDQ6WHKH3w6_kJvxxayQyQkxacREU6IZrei8xHnPELrBPqivKnQNjoDJ6lZMYgnES7xxmMmsz7JSAhjSGSNSA9Vmo9JgMwDmbLvzVfNyJenEiUH8g4CCKqgkTl42xNhGpDShZKyVw7oPsQjIhKF28QExxX0tHAhjanK-3p_xl9JpCwBwcSjgjxFqEaPSmsDMbwm7f5eprP48-y4ZllSc34hz342cCwxllAClwR27v5FMsJ0k3iRbbivedSBtHd_F4PvC0Kgm5q4TtrE1Veovp83gRumZSfWmqluLTWF53xScPG-qEvfAcENYxzoqYzUfa8ySnKyW61X6VPXvqKXDspq75K2-c0LV26tcObcFvR4f8q14ALyVggu8OXN_F1ENgo-KhW471uPQP5OQgJ5AxkYCcgjPQTMxxHCnPLbfcN840EFlTkZ82JyQmI7laAnwViHkOzJVQLjb75W30ESzqjjwHgXUJPKMKBYU5o5VmtDk6sI8cNysGbuxGaxLzO-T7fs9gJJ6HG2_Ki-A8_psoDeVlxPtrIjLBahYmF8zCejKxvZ2Ev3DA1CWKXwbh87kajf_u00Gdh7QQWF2VFCxoPdV6WabqvihSA74HTomR5VXC-ayooedfGoVTWC4soVYCN4ilwjQJjUdOU0rSiuyzNyrxM2qbIc4B7_DDImw6bGI5MyCTMaZzPsamDpGbqLTqlsM5encxa0SsIefD8bHKDNrUSf0Qbh8B1EP4PLTzKYw">