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

    <tr>
        <th>Summary</th>
        <td>
            [SimplifyCFG] SimplifyCFG does not eliminate the UB branch after inlining
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            llvm:optimizations,
            missed-optimization
      </td>
    </tr>

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

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

<pre>
    I tried the following IR:

```
define internal ptr @bar(ptr %arg, i1 %arg1) {
bb:
  br i1 %arg1, label %bb4, label %bb2

bb2:
  %i = load ptr, ptr %arg, align 8
  %i3 = getelementptr inbounds i8, ptr %i, i64 1
  store ptr %i3, ptr %arg, align 8
  br label %bb4

bb4:
  %i5 = phi ptr [ %i, %bb2 ], [ null, %bb ]
  ret ptr %i5
}

define i32 @foo(ptr %arg, i1 %arg1) {
bb:
  %i = call ptr @bar(ptr %arg, i1 %arg1)
  %i2 = icmp ne ptr %i, null
  call void @llvm.assume(i1 %i2)
  %i3 = load i32, ptr %i, align 4
  ret i32 %i3
}

declare void @llvm.assume(i1)
```

We can eliminate the branch, but it doesn't. To my surprise, re-executing the output once simplifycfg eliminates this branch: https://llvm.godbolt.org/z/85zKbMdxe.

I've noticed that the user order is different after inlining and reading the text IR.

The `passingValueIsAlwaysUndefined` only considers the first user:
https://github.com/llvm/llvm-project/blob/92f4001906a18fca29929a333e61fdd662a9b0bd/llvm/lib/Transforms/Utils/SimplifyCFG.cpp#L7567-L7577

Of course there are many ways to solve this problem, for example:

1. Handle all users
2. Choose an instruction that `passingValueIsAlwaysUndefined` can handle (I'd go with this one first.)
3. Support `assume(%p == null)`

But my biggest concern here is **whether the user order needs to be consistent**. I don't like it when an optimization happens randomly.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJycVl2PqzYT_jXOzWgRmK9wkYvNR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