r/programming • u/DataBaeBee • Sep 14 '26
How GCC Eliminates Unnecessary Integer Division
https://leetarxiv.substack.com/p/how-gcc-eliminates-unnecessary-integer
251
Upvotes
r/programming • u/DataBaeBee • Sep 14 '26
View all comments
Show parent comment
17
u/ack_error Sep 15 '26
They're different ranges.
The quoted IMUL range is for throughput vs. latency. An IMUL will take 3 cycles from start to finish, but if you have non-dependent multiplies you can start an IMUL every cycle. This is not hard to hit, a simple loop processing elements in an array independently can hit 1 multiply/cycle. These timings are independent of the values being multiplied.
The IDIV range is because the end-to-end latency of IDIV can actually change depending on the values, often because the divider has some early outs. This means that the same loop with an IDIV in it can run faster or slower when different values are processed.
That being said, I checked the timings on Skylake and it turns out that you're not likely to see this variation in C, because it's a very specific boundary. IDIV is not a 64-bit / 64-bit division, it's actually a 128-bit / 64-bit division. What seems to happen is that the Skylake CPU has an optimization to run the IDIV faster if the upper 64 bits of the dividend are zero and it can do a 64-bit / 64-bit division instead; within that the values don't seem to matter. Standard C and C++ don't expose a 128-bit integer type so the full division will generally only be hit with intrinisics or a compiler-specific int128 type.