Skip to content

Commit 449e7a4

Browse files
authored
Fix CountLeadingZeroes on MSVC (WebAssembly#3028)
We just had the logic there wrong - MSVC's intrinsic returns the bit index, not the number of leading zeros. That's identical when scanning forward but not in reverse... Fixes WebAssembly#2942
1 parent e89b401 commit 449e7a4

1 file changed

Lines changed: 5 additions & 2 deletions

File tree

src/support/bits.cpp

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,10 @@ template<> int CountLeadingZeroes<uint32_t>(uint32_t v) {
116116
#elif defined(_MSC_VER)
117117
unsigned long count;
118118
_BitScanReverse(&count, v);
119-
return (int)count;
119+
// BitScanReverse gives the bit position (0 for the LSB, then 1, etc.) of the
120+
// first bit that is 1, when looking from the MSB. To count leading zeros, we
121+
// need to adjust that.
122+
return 31 - int(count);
120123
#else
121124
// See Stanford bithacks, find the log base 2 of an N-bit integer in
122125
// O(lg(N)) operations with multiply and lookup:
@@ -142,7 +145,7 @@ template<> int CountLeadingZeroes<uint64_t>(uint64_t v) {
142145
#elif defined(_MSC_VER) && defined(_M_X64)
143146
unsigned long count;
144147
_BitScanReverse64(&count, v);
145-
return (int)count;
148+
return 63 - int(count);
146149
#else
147150
return v >> 32 ? CountLeadingZeroes((uint32_t)(v >> 32))
148151
: 32 + CountLeadingZeroes((uint32_t)v);

0 commit comments

Comments
 (0)