<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/75155>75155</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
Missing optimization: fold `max(b, a + 1) - a` to `b - a` when `a < b`
</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/iQ4tYx
### Description:
```c
long src(long a, long b) {
if(a < b){
return max(b, a + 1) - a;
}else{
return 0;
}
}
```
can be folded to:
```c
long tgt(long a, long b) {
if(a < b){
return b - a;
}else{
return 0;
}
}
```
Similarly, it also applies to other cases like `a >b`, `min(b, a + 1)` and so on.
### Real-world motivation
This snippet of IR is derived from [redis/src/db.c@readGetKeys](https://github.com/redis/redis/blob/c85a9b7896b9727709b71fed414bf8a117436d71/src/db.c#L2899C14-L2899C14) (after O3 pipeline).
The example above is a reduced version. If you're interested in the original suboptimal IR and optimal IR, see also:https://godbolt.org/z/YaEYnedYW
**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/eJy0VMFu4zYQ_Rr6MohBUbIoHXRI4nWx6BZFtwXaHElxZE1DkQJJOcl-fUE53sTtbnuqQZgccPw8j_PmqRjp6BA7trtju_1GLWn0ofvjfnzZaG9eultLJxQwB-8HVt7CmNIcWXnLxIGJg1pvt9aepq0PRyYOPTJx-MLEgX6p0sMz43vGb1-_RXlesMfYB5oTeZeh3ufU_Lz6c2y9O0IMPRPNelRM3MN60ky0wOTdOQ8AgAYmGgWsvF8v3-4CpiU4mNQzE43OCAqYuIMiQ9yAYuU7FCb3aCNeIefPKwh_S2Zy_1r018Ol-nPYKwcaYfDWoIHk37h-i2U6pv9k-V2K10Xq_5PVrzSRVcG-5CIpgbLRg5pnSxghefBpxAC9ihjB0i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