On Wed, 16 Nov 2016, Michael Matz wrote:

Hi,

On Wed, 16 Nov 2016, Marc Glisse wrote:

The first sentence about ORing the sign bit sounds strange (except for a
sign-magnitude representation). With 2's complement, INT_MIN is -2^31, the
divisors are the 2^k and -(2^k). -2 * 2^30 yields INT_MIN, but your test
misses -2 as a possible divisor. On the other hand, 0b100...001 (aka
-INT_MAX)
is not a divisor of INT_MIN but your test says the reverse.

Yeah, but it handled the testcase ;)  So I guess the easiest would be
to check integer_pow2p (abs (TREE_OPERAND (t, 0)) then, thus
wi::popcount (wi::abs (TREE_OPERAND (t, 0))) == 1?

Looks good to me, thanks.

An integer X is a power of two if and only if
 X & -X == 0  (&& X != 0 if you want to exclude zero)
which also nicely handles positive and negative numbers at the same time.
No need for popcounts or abs.

There are bit tricks to test for powers of 2, but X & -X == 0 doesn't quite work (X & -X == X is closer, but needs a tweak for negative numbers). We could use
wi::pow2_p (wi::abs (TREE_OPERAND (t, 0)))
adding a new function pow2_p so it remains readable and we reduce the risk of using the wrong bit trick...

--
Marc Glisse

Reply via email to