Skip to content

Commit

Permalink
Use popcount intrinsics
Browse files Browse the repository at this point in the history
  • Loading branch information
kunalspathak committed May 8, 2023
1 parent 40e49f9 commit 0b3da21
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 27 deletions.
2 changes: 1 addition & 1 deletion src/coreclr/jit/compiler.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ inline bool genMaxOneBit(T value)
template <typename T>
inline bool genExactlyOneBit(T value)
{
return ((value != 0) && genMaxOneBit(value));
return BitOperations::PopCount(value) == 1;
}

/*****************************************************************************
Expand Down
39 changes: 13 additions & 26 deletions src/coreclr/jit/utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2788,19 +2788,11 @@ uint32_t BitOperations::Log2(uint64_t value)
uint32_t BitOperations::PopCount(uint32_t value)
{
#if defined(_MSC_VER)
// Inspired by the Stanford Bit Twiddling Hacks by Sean Eron Anderson:
// http://graphics.stanford.edu/~seander/bithacks.html

const uint32_t c1 = 0x55555555u;
const uint32_t c2 = 0x33333333u;
const uint32_t c3 = 0x0F0F0F0Fu;
const uint32_t c4 = 0x01010101u;

value -= (value >> 1) & c1;
value = (value & c2) + ((value >> 2) & c2);
value = (((value + (value >> 4)) & c3) * c4) >> 24;

return value;
#ifdef HOST_ARM64
return _CountOneBits(value);
#else
return __popcnt(value);
#endif
#else
int32_t result = __builtin_popcount(value);
return static_cast<uint32_t>(result);
Expand All @@ -2819,19 +2811,14 @@ uint32_t BitOperations::PopCount(uint32_t value)
uint32_t BitOperations::PopCount(uint64_t value)
{
#if defined(_MSC_VER)
// Inspired by the Stanford Bit Twiddling Hacks by Sean Eron Anderson:
// http://graphics.stanford.edu/~seander/bithacks.html

const uint64_t c1 = 0x5555555555555555ull;
const uint64_t c2 = 0x3333333333333333ull;
const uint64_t c3 = 0x0F0F0F0F0F0F0F0Full;
const uint64_t c4 = 0x0101010101010101ull;

value -= (value >> 1) & c1;
value = (value & c2) + ((value >> 2) & c2);
value = (((value + (value >> 4)) & c3) * c4) >> 56;

return static_cast<uint32_t>(value);
#ifdef HOST_ARM64
return _CountOneBits64(value);
#elif defined(HOST_64BIT)
int64_t result = __popcnt64(value);
return static_cast<uint32_t>(result);
#else
return __popcnt(value >> 32);
#endif
#else
int32_t result = __builtin_popcountll(value);
return static_cast<uint32_t>(result);
Expand Down

0 comments on commit 0b3da21

Please sign in to comment.