Does a c/c++ compiler optimize constant divisions by power-of-two value into shifts?
c, c++, gcc, optimization
Solution
Even with `g++ -O0` (yes, `-O0`!), this happens. Your function compiles down to:
_Z3divm:
.LFB952:
pushq %rbp
.LCFI0:
movq %rsp, %rbp
.LCFI1:
movq %rdi, -24(%rbp)
movq $64, -8(%rbp)
movq -24(%rbp), %rax
shrq $6, %rax
leave
ret
Note the `shrq $6`, which is a right shift by 6 places.
With `-O1`, the unnecessary junk is removed:
_Z3divm:
.LFB1023:
movq %rdi, %rax
shrq $6, %rax
ret
Results on g++ 4.3.3, x64.
Problem
Question says it all. Does anyone know if the following... ``` size_t div(size_t value) { const size_t x = 64; return value / x; } ``` ...is optimized into? ``` size_t div(size_t value) { return value >> 6; } ``` Do compilers do this? (My interest lies in GCC). Are there situations where it does and others where it doesn't? I would really like to know, because every time I write a division that could be optimized like this I spend some mental energy wondering about whether precious nothings of a second is wasted doing a division where a shift would suffice.