Quite Incredible Optimization
I was nicely surprised today when I tried to compile the following test function with the -g3 optimization flag.
int f(int a) { bool b(true); b &= a; return b ? 5 : 255; }
The result makes use of advance arithmetic to compute the 5 or 255 out of the 0 or 1 defined by the result define in b. As expected, though, if a is not 0 or 1, the result may not be what you'd otherwise expect.
0: 83 e7 01 and $0x1,%edi 3: 83 ff 01 cmp $0x1,%edi 6: 19 c0 sbb %eax,%eax 8: 25 fa 00 00 00 and $0xfa,%eax d: 83 c0 05 add $0x5,%eax 10: c3 retq
As you can see, only bit 0 of the input (%edi) is kept for the computation. The function may need to be rewritten with:
b = b && a;
- Alexis Wilke's blog
- Login to post comments
Syndicate