https://gcc.gnu.org/bugzilla/show_bug.cgi?id=129194
Bug ID: 129194
Summary: Missed optimization for x - (16*y - y): associativity
could be used to hide latency
Product: gcc
Version: 16.2.0
URL: https://godbolt.org/noscript/z/rK4Poa5Ef
Status: UNCONFIRMED
Keywords: missed-optimization
Severity: normal
Priority: P3
Component: tree-optimization
Assignee: unassigned at gcc dot gnu.org
Reporter: sparks05 at proton dot me
Target Milestone: ---
Host: x86_64
Target: x86_64
Possibly related:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128737 associative arithmetic can
be done in parallel with four or more operands
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69943 expressions with multiple
associative operators don't always create instruction-level parallelism
unsigned long mod15(unsigned long x) { return x % 15; }
compiles (x86_64 -O3 -fomit-frame-pointer,
https://godbolt.org/noscript/z/4cT8EPTzz) to
mod15(unsigned long):
movabsq $-8608480567731124087, %rax
mulq %rdi
movq %rdx, %rax
shrq $3, %rax
movq %rax, %rdx
salq $4, %rdx
subq %rax, %rdx
movq %rdi, %rax
subq %rdx, %rax
ret
which is the same as any of of
unsigned long y = x / 15; return x - 15*y;
unsigned long y = x / 15; return x - (16*y - y);
If I tweak the source to
unsigned long y = x / 15; return x + (-(16*y) + y);
I get the somewhat nicer code (-2 instructions)
mod15(unsigned long):
movabsq $-8608480567731124087, %rax
mulq %rdi
shrq $3, %rdx
movq %rdx, %rax
salq $4, %rax
subq %rax, %rdx
leaq (%rdx,%rdi), %rax
ret
But if I feed GCC (https://godbolt.org/noscript/z/rK4Poa5Ef)
unsigned long y = x / 15; return x - 16*y + y;
I get the *much* nicer code (-3 instructions):
mod15(unsigned long):
movabsq $-8608480567731124087, %rax
mulq %rdi
shrq $3, %rdx
leaq (%rdi,%rdx), %rax
salq $4, %rdx
subq %rdx, %rax
ret
In modern wide OOO processors, moves are done in the renamer and consume
almost no resources, so they're an I-cache annoyance but not a big deal.
However, it's the latency which annoys me. 16*y is obviously only available
a cycle after y, and x is available ab initio, so summing the latter
first and *then* subtracting the shift result saves a cycle of latency.
*This*, I care about.
Thank you for the diligent efforts!