From: Aldy Hernandez Date: Mon, 7 Nov 2022 07:40:12 +0000 (+0100) Subject: [range-op] Restrict division by power of 2 optimization to positive numbers. X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=3bff15c1c9fb3eb0bb042717e072476ec2d6d88c;p=platform%2Fupstream%2Fgcc.git [range-op] Restrict division by power of 2 optimization to positive numbers. The problem here is that we are transforming a division by a power of 2 into a right shift, and using this to shift the maybe nonzero bits. This gives the wrong result when the number being divided is negative. In the testcase we are dividing this by 8: [irange] int [-256, -255] NONZERO 0xffffff01 and coming up with: [irange] int [-32, -31] NONZERO 0xffffffe0 The maybe nonzero bits are wrong as -31 has the LSB set (0xffffffe1) whereas the bitmask says the lower 4 bits are off. PR tree-optimization/107541 gcc/ChangeLog: * range-op.cc (operator_div::fold_range): Restrict power of 2 optimization to positive numbers. gcc/testsuite/ChangeLog: * gcc.dg/tree-ssa/pr107541.c: New test. --- diff --git a/gcc/range-op.cc b/gcc/range-op.cc index 5e94c3d..2b5db0c 100644 --- a/gcc/range-op.cc +++ b/gcc/range-op.cc @@ -1953,7 +1953,9 @@ operator_div::fold_range (irange &r, tree type, return true; tree t; - if (rh.singleton_p (&t)) + if (code == TRUNC_DIV_EXPR + && rh.singleton_p (&t) + && !wi::neg_p (lh.lower_bound ())) { wide_int wi = wi::to_wide (t); int shift = wi::exact_log2 (wi); diff --git a/gcc/testsuite/gcc.dg/tree-ssa/pr107541.c b/gcc/testsuite/gcc.dg/tree-ssa/pr107541.c new file mode 100644 index 0000000..4751421 --- /dev/null +++ b/gcc/testsuite/gcc.dg/tree-ssa/pr107541.c @@ -0,0 +1,16 @@ +// { dg-do run } +// { dg-options "-O1" } + +unsigned char a = 1; +char b, e; +long c; +short d; +int main() { + a = ~(1 && a); + c = ~((~a / 8 | -2) & 11007578330939886389LLU); + e = -c; + d = ~c / e; + if (d < 2000) + __builtin_abort(); + return 0; +}