diff options
author | Alon Zakai <alonzakai@gmail.com> | 2015-12-24 09:38:26 -0800 |
---|---|---|
committer | Alon Zakai <alonzakai@gmail.com> | 2015-12-24 09:38:26 -0800 |
commit | 207af0d877d195cf22540c00ebe8607c9ef41316 (patch) | |
tree | 0257161a58014b1eeb244900741fbb7151c9a7f6 /src/bits.h | |
parent | 35df36e4c18498c72bd8345d99e27856582d9054 (diff) | |
parent | f2773d476c835fcc95e4e67d775736affa224552 (diff) | |
download | binaryen-207af0d877d195cf22540c00ebe8607c9ef41316.tar.gz binaryen-207af0d877d195cf22540c00ebe8607c9ef41316.tar.bz2 binaryen-207af0d877d195cf22540c00ebe8607c9ef41316.zip |
Merge branch 'simplify-bits'
Diffstat (limited to 'src/bits.h')
-rw-r--r-- | src/bits.h | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/src/bits.h b/src/bits.h index 98bb96a4f..98ae5c4b7 100644 --- a/src/bits.h +++ b/src/bits.h @@ -17,6 +17,8 @@ #ifndef wasm_bits_h #define wasm_bits_h +#include <type_traits> + /* * Portable bit functions. * @@ -37,6 +39,18 @@ template<typename T> inline T BitReverse(T /* v */); template<typename T> inline int CountTrailingZeroes(T /* v */); template<typename T> inline int CountLeadingZeroes(T /* v */); +// Convenience signed -> unsigned. It usually doesn't make much sense to use bit +// functions on signed types. +template <typename T> inline int PopCount(T v) { + return PopCount(typename std::make_unsigned<T>::type(v)); +} +template <typename T> inline int CountTrailingZeroes(T v) { + return CountTrailingZeroes(typename std::make_unsigned<T>::type(v)); +} +template <typename T> inline int CountLeadingZeroes(T v) { + return CountLeadingZeroes(typename std::make_unsigned<T>::type(v)); +} + // Implementations for the above templates. template<> inline int PopCount<uint8_t>(uint8_t v) { @@ -84,6 +98,11 @@ template<> inline int CountTrailingZeroes<uint32_t>(uint32_t v) { 32; } +template<> inline int CountTrailingZeroes<uint64_t>(uint64_t v) { + return (uint32_t)v ? CountTrailingZeroes<uint32_t>(v) + : 32 + CountTrailingZeroes<uint32_t>(v >> 32); +} + template<> inline int CountLeadingZeroes<uint32_t>(uint32_t v) { // See Stanford bithacks, find the log base 2 of an N-bit integer in // O(lg(N)) operations with multiply and lookup: @@ -102,6 +121,11 @@ template<> inline int CountLeadingZeroes<uint32_t>(uint32_t v) { 32; } +template<> inline int CountLeadingZeroes<uint64_t>(uint64_t v) { + return v >> 32 ? CountLeadingZeroes<uint32_t>(v >> 32) + : 32 + CountLeadingZeroes<uint32_t>(v); +} + } // namespace wasm #endif // wasm_bits_h |