Windless avoid division by zero

Let's say I have a piece of code in lines

double test(double value, double denom) {
  return (denom == 0 ? 0 : value/denom);
}

      

which is compiled for:

    movapd  %xmm0, %xmm2
    xorpd   %xmm0, %xmm0
    ucomisd %xmm0, %xmm1
    jnp .L8
.L5:
    movapd  %xmm2, %xmm0
    divsd   %xmm1, %xmm0
    ret
    .p2align 4,,10
    .p2align 3
.L8:
    jne .L5
    rep
    ret

      

Is there some neat way to mess up branching? It's about X86-64. For example, PPC has a select command, is there an equivalent in ISA X86-64?

+3


source to share


2 answers


Assuming you've disabled exceptions, it's easy to mask the result:



xorpd %xmm2, %xmm2
cmpneqsd %xmm1, %xmm2
divsd %xmm1, %xmm0
andpd %xmm2, %xmm0
ret

      

+4


source


The branch prediction engine is very good these days.

If you don't actually have zero divisors with some non-zero frequency, the branch predictor will figure out that jnp doesn't branch statistically and just crashes without losing performance.



Have you measured this and have seen any loss in performance compared to no benchmark?

+1


source







All Articles