https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87655
Bug ID: 87655
Summary: `i = i % constant` for static local `i` is not
optimized
Product: gcc
Version: 9.0
Status: UNCONFIRMED
Keywords: missed-optimization
Severity: normal
Priority: P3
Component: middle-end
Assignee: unassigned at gcc dot gnu.org
Reporter: antoshkka at gmail dot com
Target Milestone: ---
Consider the following example:
unsigned next_trivial() {
static int i = 0;
auto ret = i;
++i;
i = i % 10;
return ret;
}
For that example a very suboptimal assembly with multiplication, many registers
usage and multiple instructions is generated.
However, the above example could be rewritten in the following way:
unsigned next_trivial_optim() {
static int i = 0;
auto ret = i;
++i;
if (i == 10) { i = 0; }
return ret;
}
For the above code snippet a very short and clear assembly is produced, without
any multiplications and unnecessary instructions:
mov eax, DWORD PTR next_trivial_optim()::i[rip]
mov ecx, 0
lea edx, [rax+1]
cmp eax, 9
cmove edx, ecx
mov DWORD PTR next_trivial_optim()::i[rip], edx
ret
Please, add an optimization to do that transformation.