<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/82414>82414</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
[InstCombine] Missed optimization : fold `X > C2 ? X + C1 : C2 + C1` to `max(X, C2) + C1`
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
XChy
</td>
</tr>
</table>
<pre>
Alive2 proof: https://alive2.llvm.org/ce/z/ERjNs4
### Motivating example
```llvm
define i32 @src(i32 %x) {
%add = add nsw i32 %x, 16
%cmp = icmp sgt i32 %x, 1008
%s = select i1 %cmp, i32 %add, i32 1024
ret i32 %s
}
```
can be folded to:
```llvm
define i32 @tgt(i32 %x) {
%smax = call i32 @llvm.smax.i32(i32 %x, i32 1008)
%add = add nuw nsw i32 %smax, 16
ret i32 %add
}
```
LLVM does well when `C1` or `C2` is not constant, but when both are constants, LLVM missed it. Though this example doesn't show better codegen, I think it's a better canonicalization.
### Real-world motivation
This snippet of IR is derived from [protobuf/generated_message_tctable_lite.cc](https://github.com/dtcxzyw/llvm-opt-benchmark/blob/main/bench/protobuf/original/generated_message_tctable_lite.cc.ll@_ZN6google8protobuf13RepeatedFieldIiE14GrowNoAnnotateEii) after O3 pipeline (original IR is from [llvm-opt-benchmark](https://github.com/dtcxzyw/llvm-opt-benchmark)).
Original IR is too big to attach here, email me to get it please.
**Let me know if you can confirm that it's an optimization opportunity, thanks.**
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJykVV1r4zoQ_TXKy9Bgy47jPOShTepLoe1CWS7lvhTZmtjayhojTZq2v_4i52OTZe-ylwWTWJozI53jo5EKwbQOcSlmN2K2nqgtd-SXz6vuY1KT_lheW_OGEgZPtBHZNXTMQxDZtZCVkJUao1Nr3_op-VbIqkEhq08hq9unb48hF8laJNeHX5ntH3ggNm-KjWsB31U_WIQLYJH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