https://gcc.gnu.org/bugzilla/show_bug.cgi?id=124680
Bug ID: 124680
Summary: Missed optimization: Fold `x / (1<<C) - (x % (1<<C) <
0)` to `x >> C`
Product: gcc
Version: 15.2.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: tree-optimization
Assignee: unassigned at gcc dot gnu.org
Reporter: Explorer09 at gmail dot com
Target Milestone: ---
```c
int func1(int x) {
int quo = x / 256 - (x % 256 < 0);
return quo;
}
int func2(int x) {
int rem = (int)((unsigned int)x % 256);
int quo = (x - rem) / 256;
return quo;
}
```
Compiler Explorer link:
https://godbolt.org/z/67EoErjG1
GCC can optimize func2 in the example above to an arithmetic right shift, but
it missed on the func1 example. (Clang is able to optimize both.)
```assembly
func2:
movl %edi, %eax
sarl $8, %eax
ret
```
This pattern is "perform a division, but round the quotient towards negative
infinity". When the divisor is a power of 2, it can be optimized into an
arithmetic right shift. It's more portable than the ">>" operator in C, since
the C standard says that the ">>" operator on a negative integer has an
implementation-defined behavior.
(This issue is split from bug 124675. In bug 124675 I mentioned this pattern as
"func4" and "func5". Since the issue with optimizing devision and modulo are
different, it's worth splitting the report into two.)