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

via libc-commits libc-commits at lists.llvm.org
Fri Jun 14 19:56:20 PDT 2024


Author: Ryan Beltran
Date: 2024-06-14T19:56:15-07:00
New Revision: 6f5dfbd73a2867019d52be546a89d4fb4224b83d

URL: https://github.com/llvm/llvm-project/commit/6f5dfbd73a2867019d52be546a89d4fb4224b83d
DIFF: https://github.com/llvm/llvm-project/commit/6f5dfbd73a2867019d52be546a89d4fb4224b83d.diff

LOG: [libc][__support][bit] Switch popcount to Brian Kernighan’s Algorithm (#95625)

Added: 
    

Modified: 
    libc/src/__support/CPP/bit.h

Removed: 
    


################################################################################
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