Does a c/c++ compiler optimize constant divisions by power-of-two value into shifts?

后端 未结 4 604
清歌不尽
清歌不尽 2020-11-30 05:49

Question says it all. Does anyone know if the following...

size_t div(size_t value) {
    const size_t x = 64;
    return value / x;
}

...i

4条回答
  •  时光说笑
    2020-11-30 06:06

    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.

提交回复
热议问题