[OT] compiler optimisations

John Colvin via Digitalmars-d digitalmars-d at puremagic.com
Thu Apr 23 01:33:52 PDT 2015


Why can no compiler I try optimise this toy example as I would 
expect?

// uncomment if using a C compiler
// typedef unsigned int uint;
uint foo(uint a)
{
   if (a < 5)
     return (a * 3) / 3;
   else
     return 0;
}

So, I would expect the compiler to be able to see that it is 
equivalent to

uint foo(uint a)
{
   return (a < 5) ? a : 0;
}

But apparently not a single modern compiler I tried can do this 
optimisation, unless it's hidden in some obscure flag I'm not 
aware of.

An even more striking example can be found if you replace the / 
with %, where the result of the function is then unconditionally 
zero, but every compiler i tried still spat out multiplication 
instructions.

Is there a good reason for this, or is it just " * and / aren't 
always inverses, so never mind all the cases where they are"?

Now I know that this seems like a unrealistic example, but when 
you're in complicated meta-programming situations code like this 
can and will appear.


More information about the Digitalmars-d mailing list