[PATCH] middle-end: If supported, use __builtin_bitreverse64 on reflect_hwi. [PR126625]

Kael Andrew Franco <[email protected]> Thu, 6 Aug 2026 06:22:56 -0400
Newsgroups gmane.comp.gcc.patches
Message-ID <CACAb0qfKrUtWoRDGKS7V__mWw2ga3KS-qC0YQCO8Kkx+FKi7hg@mail.gmail.com>
From f3df22990341e3ff247160509c41e8b123aff0bd Mon Sep 17 00:00:00 2001
From: Kael Andrew Alonzo Franco <[email protected]>
Date: Wed, 5 Aug 2026 12:50:20 -0400
Subject: [PATCH] middle-end: If supported, use __builtin_bitreverse64
on reflect_hwi. [PR126625]

reflect_hwi uses a naive for loop approach to emulate __builtin_bitreverse64 ().
This is slow compared to using __builtin_bitreverse64 () plus bitshift.
This is useful for bootstrapping GCC since r17-523.
Also add assert on BITWIDTH <= 64.

Bootstrapped and regtested on x86_64-pc-linux-gnu.

	PR middle-end/126625

gcc/ChangeLog:

	* hwint.cc (reflect_hwi): If supported, use __builtin_bitreverse64.

Signed-off-by: Kael Andrew Franco <[email protected]>
---
 gcc/hwint.cc | 19 ++++++++++++++++++-
 1 file changed, 18 insertions(+), 1 deletion(-)

diff --git a/gcc/hwint.cc b/gcc/hwint.cc
index f3b3e7b8408..e87956ed3f5 100644
--- a/gcc/hwint.cc
+++ b/gcc/hwint.cc
@@ -189,12 +189,27 @@ least_common_multiple (HOST_WIDE_INT a, HOST_WIDE_INT b)
   return mul_hwi (abs_hwi (a) / gcd (a, b), abs_hwi (b));
 }

-/* Reflect (reverse) the bits of a given VALUE within a specified BITWIDTH.  */
+#ifdef __has_builtin
+#if __has_builtin(__builtin_bitreverse64)
+#define HAS_BITREVERSE64
+#endif
+#endif
+
+/* Reflect (reverse) the bits of a given VALUE within a specified
BITWIDTH <= 64.  */

 unsigned HOST_WIDE_INT
 reflect_hwi (unsigned HOST_WIDE_INT value, unsigned bitwidth)
 {
+  if (bitwidth == 0)
+    return 0;
+
+  gcc_checking_assert (bitwidth <= 64);
+
+#ifdef HAS_BITREVERSE64
+  return __builtin_bitreverse64 (value) >> (64 - bitwidth);
+#else
   unsigned HOST_WIDE_INT reflected_value = 0;
+
   /* Loop through each bit in the specified BITWIDTH.  */
   for (size_t i = 0; i < bitwidth; i++)
     {
@@ -204,5 +219,7 @@ reflect_hwi (unsigned HOST_WIDE_INT value,
unsigned bitwidth)
       reflected_value |= (value & 1);
       value >>= 1;
     }
+
   return reflected_value;
+#endif
 }
-- 
2.55.0