Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved halide_popcount #7225

Merged
merged 3 commits into from
Jan 25, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions src/CodeGen_C.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -152,15 +152,41 @@ inline float float_from_bits(uint32_t bits) {
}

template<typename T>
inline int halide_popcount(T a) {
inline int halide_popcount_fallback(T a) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would leave a link to the source for this algorithm for the reference (found this one https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan, for example).

int bits_set = 0;
while (a != 0) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW, ~all modern compilers should have popcount as an intrinsic -- see popcount64 in Util.cpp, maybe we should just adapt that here

bits_set += a & 1;
a >>= 1;
bits_set += 1;
// this is Brian Kernigan's bit counting algorithm
// https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan)
// removes the least significant one
a &= a - 1;
}
return bits_set;
}

template<typename T>
inline int halide_popcount(T a) {
return halide_popcount_fallback<T>(a);
}

template<>
inline int halide_popcount<uint64_t>(uint64_t a) {
#ifdef _MSC_VER
#if defined(_WIN64)
return __popcnt64(x);
#else
return __popcnt((uint32_t)(x >> 32)) + __popcnt((uint32_t)(x & 0xffffffff));
#endif
#else
#if defined(__builtin_popcountll)
static_assert(sizeof(unsigned long long) >= sizeof(uint64_t), "");
return return __builtin_popcountll(x);
#else
return halide_popcount_fallback<uint64_t>(a);
#endif
#endif
}

template<typename T>
inline int halide_count_leading_zeros(T a) {
int leading_zeros = 0;
Expand Down