diff --git a/include/helpers.hpp b/include/helpers.hpp index e12d350e..84b39b23 100644 --- a/include/helpers.hpp +++ b/include/helpers.hpp @@ -40,53 +40,6 @@ static inline void unreachable_() { #define assume assert #endif -// Ideally we'd use `std::bit_width`, but it has insufficient compiler support -#ifdef __GNUC__ // GCC or compatible - #define ctz __builtin_ctz - #define clz __builtin_clz - -#elif defined(_MSC_VER) - #include - #pragma intrinsic(_BitScanReverse, _BitScanForward) - -static inline int ctz(unsigned int x) { - assume(x != 0); - unsigned long count; - _BitScanForward(&count, x); - return count; -} - -static inline int clz(unsigned int x) { - assume(x != 0); - unsigned long count; - _BitScanReverse(&count, x); - return 31 - count; -} - -#else - #include - -static inline int ctz(unsigned int x) { - assume(x != 0); - int count = 0; - while (!(x & 1)) { - x >>= 1; - ++count; - } - return count; -} - -static inline int clz(unsigned int x) { - assume(x != 0); - int count = 0; - while (x <= UINT_MAX / 2) { - x <<= 1; - ++count; - } - return count; -} -#endif - // Macros for stringification #define STR(x) #x #define EXPAND_AND_STR(x) STR(x) diff --git a/src/fix/fix.cpp b/src/fix/fix.cpp index d447f3fe..3304735c 100644 --- a/src/fix/fix.cpp +++ b/src/fix/fix.cpp @@ -5,6 +5,7 @@ #include "fix/fix.hpp" #include +#include #include #include #include @@ -305,14 +306,9 @@ static void assume(rom0Len == sizeof(rom0)); } assume(nbBanks >= 2); - // Alter number of banks to reflect required value - // x&(x-1) is zero iff x is a power of 2, or 0; we know for sure it's non-zero, - // so this is true (non-zero) when we don't have a power of 2 - if (nbBanks & (nbBanks - 1)) { - nbBanks = 1 << (CHAR_BIT * sizeof(nbBanks) - clz(nbBanks)); - } + nbBanks = std::bit_ceil(nbBanks); // Write final ROM size - rom0[0x148] = ctz(nbBanks / 2); + rom0[0x148] = std::countr_zero(nbBanks / 2); // Alter global checksum based on how many bytes will be added (not counting ROM0) globalSum += options.padValue * ((nbBanks - 1) * BANK_SIZE - totalRomxLen); } diff --git a/src/opmath.cpp b/src/opmath.cpp index b3cfa8e2..0b183931 100644 --- a/src/opmath.cpp +++ b/src/opmath.cpp @@ -4,9 +4,10 @@ #include "opmath.hpp" +#include #include -#include "helpers.hpp" // assume, clz, ctz +#include "helpers.hpp" // assume // Signed overflow is UB, so these compute with unsigned arithmetic, which wraps around. // Casting back is OK because the types implement two's complement behavior. @@ -135,9 +136,9 @@ int32_t op_low(int32_t value) { } int32_t op_bitwidth(int32_t value) { - return value != 0 ? 32 - clz(static_cast(value)) : 0; + return std::bit_width(static_cast(value)); } int32_t op_tzcount(int32_t value) { - return value != 0 ? ctz(static_cast(value)) : 32; + return std::countr_zero(static_cast(value)); }