[libc-commits] [libc] [libc][__support][bit] Switch popcount to Brian Kernighan’s Algorithm (PR #95625)

Ryan Beltran via libc-commits libc-commits at lists.llvm.org
Fri Jun 14 17:00:58 PDT 2024


https://github.com/rpbeltran created https://github.com/llvm/llvm-project/pull/95625

This swaps the algorithm used for popcount to Brian Kernighan’s Algorithm[1] when __builtin_popcount is not available.

The while loop runs once per set bit instead of once per digit as before which is slightly better on average.

[1] https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan

>From 234694de863e1e4f650847c11ab3e0ca0a98258d Mon Sep 17 00:00:00 2001
From: Ryan Beltran <ryanbeltran at chromium.org>
Date: Fri, 14 Jun 2024 22:31:07 +0000
Subject: [PATCH] =?UTF-8?q?[libc][=5F=5Fsupport][bit]=20Switch=20popcount?=
 =?UTF-8?q?=20to=20Brian=20Kernighan=E2=80=99s=20Algorithm?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

This swaps the algorithm used for popcount to Brian Kernighan’s
Algorithm[1] when __builtin_popcount is not available.

The while loop runs once per set bit instead of once per digit as before
which is slightly better on average.

[1] https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
---
 libc/src/__support/CPP/bit.h | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/libc/src/__support/CPP/bit.h b/libc/src/__support/CPP/bit.h
index 8a8951a18bfa1..4aea066d26ab0 100644
--- a/libc/src/__support/CPP/bit.h
+++ b/libc/src/__support/CPP/bit.h
@@ -271,9 +271,10 @@ template <typename T>
 [[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<cpp::is_unsigned_v<T>, int>
 popcount(T value) {
   int count = 0;
-  for (int i = 0; i != cpp::numeric_limits<T>::digits; ++i)
-    if ((value >> i) & 0x1)
-      ++count;
+  while (value) {
+    value &= value - 1;
+    ++count;
+  }
   return count;
 }
 #define ADD_SPECIALIZATION(TYPE, BUILTIN)                                      \



More information about the libc-commits mailing list