]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
Improve do_store_flag for single bit comparison against 0
authorAndrew Pinski <apinski@marvell.com>
Thu, 18 May 2023 21:38:55 +0000 (21:38 +0000)
committerAndrew Pinski <apinski@marvell.com>
Sun, 4 Jun 2023 20:48:32 +0000 (20:48 +0000)
While working something else, I noticed we could improve
the following function code generation:
```
unsigned f(unsigned t)
{
  if (t & ~(1<<30)) __builtin_unreachable();
  return t != 0;
}
```
Right know we just emit a comparison against 0 instead
of just a shift right by 30.
There is code in do_store_flag which already optimizes
`(t & 1<<30) != 0` to `(t >> 30) & 1` (using bit extraction if available).
This patch extends it to handle the case where we know t has a nonzero
of just one bit set.

Changes from v1:
* v2: Updated for the bit extraction improvements.

OK? Bootstrapped and tested on x86_64-linux-gnu with no regressions.

gcc/ChangeLog:

* expr.cc (do_store_flag): Extend the one bit checking case
to handle the case where we don't have an and but rather still
one bit is known to be non-zero.

gcc/expr.cc

index 56b51876f80449f25295e67715440a281425d78d..6027e7ffca5af915059143de556760e5de9d1c90 100644 (file)
@@ -13162,16 +13162,31 @@ do_store_flag (sepops ops, rtx target, machine_mode mode)
       && integer_zerop (arg1)
       && (TYPE_PRECISION (ops->type) != 1 || TYPE_UNSIGNED (ops->type)))
     {
-      gimple *srcstmt = get_def_for_expr (arg0, BIT_AND_EXPR);
-      if (srcstmt
-         && integer_pow2p (gimple_assign_rhs2 (srcstmt)))
+      wide_int nz = tree_nonzero_bits (arg0);
+
+      if (wi::popcount (nz) == 1)
        {
+         tree op0;
+         int bitnum;
+         gimple *srcstmt = get_def_for_expr (arg0, BIT_AND_EXPR);
+         /* If the defining statement was (x & POW2), then remove the and
+            as we are going to add it back. */
+         if (srcstmt
+             && integer_pow2p (gimple_assign_rhs2 (srcstmt)))
+           {
+             op0 = gimple_assign_rhs1 (srcstmt);
+             bitnum = tree_log2 (gimple_assign_rhs2 (srcstmt));
+           }
+         else
+           {
+             op0 = arg0;
+             bitnum = wi::exact_log2 (nz);
+           }
          enum tree_code tcode = code == NE ? NE_EXPR : EQ_EXPR;
-         int bitnum = tree_log2 (gimple_assign_rhs2 (srcstmt));
 
          type = lang_hooks.types.type_for_mode (mode, unsignedp);
          return expand_single_bit_test (loc, tcode,
-                                        gimple_assign_rhs1 (srcstmt),
+                                        op0,
                                         bitnum, type, target, mode);
        }
     }