On Friday, 24 April 2015 at 06:29:55 UTC, deadalnix wrote:
On Thursday, 23 April 2015 at 10:23:57 UTC, Andrea Fontana wrote:
On Thursday, 23 April 2015 at 10:08:24 UTC, John Colvin wrote:
asm.dlang.org

and d.godbolt.org

This isn't a D-specific question though, so gcc.godbolt.org would allow you to test a wider range of backends.

I was wondering if compilers can optimize this:

uint foo3(uint a)
{
 return a*!(a/5);
}

That actually gives the same results.

That is cool ! However, careful, division can stall the pipeline.

I'm not an assembly expert but it seems that some compilers (using godbolt, asm.dlang.org) optimize it as:

return a*(a<=4)

gcc:

foo3(unsigned int):
        xor     eax, eax
        cmp     edi, 4
        setbe   al
        imul    eax, edi
        ret


gdc:

uint foo2(uint a)
{
  return a*(a<5);
}

uint foo3(uint a)
{
  return a*!(a/5);
}

uint example.foo2(uint):
        xorl    %eax, %eax
        cmpl    $4, %edi
        setbe   %al
        imull   %edi, %eax
        ret
uint example.foo3(uint):
        movl    %edi, %eax
        movl    $-858993459, %edx
        mull    %edx
        xorl    %eax, %eax
        shrl    $2, %edx
        testl   %edx, %edx
        sete    %al
        imull   %edi, %eax
        ret

Reply via email to