]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
[PATCH v3] match.pd: popcount(X & -X) -> -X != 0 [PR102486]
authorDaniel Barboza <daniel.barboza@oss.qualcomm.com>
Wed, 7 Jan 2026 14:17:26 +0000 (07:17 -0700)
committerJeff Law <jeffrey.law@oss.qualcomm.com>
Wed, 7 Jan 2026 14:20:22 +0000 (07:20 -0700)
The initial idea of this optimization was to reduce it to "X != 0",
checking for either X being an unsigned or a truncating conversion.
Then we discussed reducing it to "(X & -X) != 0" instead. This form
would avoid the potential trapping problems (like -ftrapv) that might
happen in case X is not an unsigned type.

Then, as suggested by Roger Sayle in bugzilla, we could reduce to just
"-X != 0". Keeping the negated value in the pattern preserves any trapping
or UBs to be handled by other match.pd patterns that are more able to do
the conversion to "X != 0" when applicable. This would also spare us from
a TYPE_UNSIGNED check.

PR tree-optimization/102486

gcc/ChangeLog:

* match.pd (`popcount (X & -X) -> -X != 0`): New pattern.

gcc/testsuite/ChangeLog:

* gcc.dg/tree-ssa/pr102486.c: New test.

Signed-off-by: Daniel Barboza <daniel.barboza@oss.qualcomm.com>
gcc/match.pd
gcc/testsuite/gcc.dg/tree-ssa/pr102486.c [new file with mode: 0644]

index 7753b258fc23f6e4cf7d3c95f3e597465cafc687..f73f66d19a9a5d57bfea940debedc129652a4201 100644 (file)
@@ -10616,6 +10616,20 @@ DEFINE_INT_AND_FLOAT_ROUND_FN (RINT)
              (popcount:s @1))
       (popcount (log2 @0 @1)))))
 
+/* popcount (X & -X) is -X != 0.  */
+(simplify
+  (POPCOUNT (convert?@2 (bit_and:c @0 (negate@1 @0))))
+    (with { tree type0 = TREE_TYPE (@0);
+           tree type2 = TREE_TYPE (@2); }
+      (if (INTEGRAL_TYPE_P (type0)
+          && TYPE_PRECISION (type2) <= TYPE_PRECISION (type0))
+       /* Use an explicit bool conversion to avoid errors when the
+          POPCOUNT result is assigned to a type (e.g. int) that
+          will generate a "bogus comparison result type" error.  */
+       (convert:type
+         (ne:boolean_type_node
+           (convert:type2 @1) { build_zero_cst (type2); })))))
+
 #if GIMPLE
 /* popcount(zext(X)) == popcount(X).  */
 (simplify
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/pr102486.c b/gcc/testsuite/gcc.dg/tree-ssa/pr102486.c
new file mode 100644 (file)
index 0000000..aa454d9
--- /dev/null
@@ -0,0 +1,14 @@
+/* { dg-do compile } */
+/* { dg-options "-O1 -fdump-tree-optimized" } */
+
+int f (unsigned y)
+{
+  return __builtin_popcount (y & -y);
+}
+
+int f2 (int y)
+{
+  return __builtin_popcount (y & -y);
+}
+
+/* { dg-final { scan-tree-dump-times "popcount" 0 "optimized" } } */