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

    <tr>
        <th>Summary</th>
        <td>
            [LICM] LICM miscompiles IR (introduces UB) when constant folding
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            miscompilation,
            loopoptim
      </td>
    </tr>

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

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

<pre>
    LICM transforms the following IR:
```llvm
target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128-ni:1-p2:32:8:8:32-ni:2"
target triple = "x86_64-unknown-linux-gnu"

define void @test(i32 %a) {
entry:
  br label %loop

loop:                              ; preds = %loop, %entry
  %val = phi i32 [ 1, %loop ], [ 0, %entry ]
  %0 = or i32 %val, %a
  %1 = mul nuw i32 %0, 65536
  %sext = mul nsw i32 %1, -9
  %2 = call i32 null(i32 %sext)
  br label %loop
}
```
into
```llvm
define void @test(i32 %a) {
entry:
  br label %loop

loop: ; preds = %loop, %entry
  %val = phi i32 [ 1, %loop ], [ 0, %entry ]
  %0 = or i32 %val, %a
  %1 = mul nuw i32 %0, -589824
  %2 = call i32 null(i32 %1)
  br label %loop
}
```

Which is not equivalent. It needs to drop `nuw` flag on mul, since now %1 might be overflowing (suppose it was value close to 2^16 - 1 before).

Godbolt: https://godbolt.org/z/Wh9G8nsrr
Alive2: https://alive2.llvm.org/ce/z/admTj4
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJzUVc-vozYQ_mvMZUSEB0zgwCF5aVZPai_bVnusHDDgrbGpbZL3-tdXNry87Fb9oUo9bJQ4nvE3n2f8GYY7JwctREPYkbBTwhc_Gtt0XEvFJ5VcTPfafP_89AN4y7XrjZ0c-FFAb5QyN6kHeP5I8gPJTiQ7kDJbv0pdp9XluR2Eh457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