Skip to content

Commit e069c63

Browse files
committed
Add rv_popcount() for efficient population count operations
Introduce the rv_popcount() function to compute the population count (number of set bits) in a 32-bit integer. This function is a prerequisite for implementing the cpop instruction in the RISC-V Zbb extension.
1 parent 340d093 commit e069c63

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/common.h

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,26 @@ static inline int rv_ctz(uint32_t v)
109109
}
110110
#endif
111111

112+
#if defined(__GNUC__) || defined(__clang__)
113+
static inline int rv_popcount(uint32_t v)
114+
{
115+
/* https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html */
116+
117+
return __builtin_popcount(v);
118+
}
119+
#else /* generic implementation */
120+
static inline int rv_popcount(uint32_t v)
121+
{
122+
/* https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
123+
*/
124+
125+
v -= (v >> 1) & 0x55555555;
126+
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
127+
v = (v + (v >> 4)) & 0x0f0f0f0f;
128+
return (v * 0x01010101) >> 24;
129+
}
130+
#endif
131+
112132
/*
113133
* Integer log base 2
114134
*

0 commit comments

Comments
 (0)