-// Select type of intrinsic bit count instruction to use
-
-#if defined(_MSC_VER) && defined(_WIN64) // Microsoft compiler
-
-#include <intrin.h>
-
-inline bool cpu_has_popcnt() {
-
- int CPUInfo[4] = {-1};
- __cpuid(CPUInfo, 0x00000001);
- return (CPUInfo[2] >> 23) & 1;
-}
-
-#define POPCNT_INTRINSIC(x) __popcnt64(x)
-
-#elif defined(__INTEL_COMPILER) && (defined(__x86_64) || defined(_M_X64)) // Intel compiler
-
-#include <nmmintrin.h>
-
-inline bool cpu_has_popcnt() {
-
- int CPUInfo[4] = {-1};
- __cpuid(CPUInfo, 0x00000001);
- return (CPUInfo[2] >> 23) & 1;
-}
-
-#define POPCNT_INTRINSIC(x) _mm_popcnt_u64(x)
-
-#else // Safe fallback for unsupported compilers
-
-inline bool cpu_has_popcnt() { return false; }
-
-#define POPCNT_INTRINSIC(x) count_1s(x)
-
-#endif // cpu_has_popcnt() selection
-
-
-/// Software implementation of bit count functions
-
-#if defined(IS_64BIT)
-
-inline int count_1s(Bitboard b) {
- b -= ((b>>1) & 0x5555555555555555ULL);
- b = ((b>>2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
- b = ((b>>4) + b) & 0x0F0F0F0F0F0F0F0FULL;
- b *= 0x0101010101010101ULL;
- return int(b >> 56);
+enum BitCountType {
+ CNT_64,
+ CNT_64_MAX15,
+ CNT_32,
+ CNT_32_MAX15,
+ CNT_HW_POPCNT
+};
+
+/// Determine at compile time the best popcount<> specialization according if
+/// platform is 32 or 64 bits, to the maximum number of nonzero bits to count
+/// and if hardware popcnt instruction is available.
+const BitCountType Full = HasPopCnt ? CNT_HW_POPCNT : Is64Bit ? CNT_64 : CNT_32;
+const BitCountType Max15 = HasPopCnt ? CNT_HW_POPCNT : Is64Bit ? CNT_64_MAX15 : CNT_32_MAX15;
+
+
+/// popcount() counts the number of nonzero bits in a bitboard
+template<BitCountType> inline int popcount(Bitboard);
+
+template<>
+inline int popcount<CNT_64>(Bitboard b) {
+ b -= (b >> 1) & 0x5555555555555555ULL;
+ b = ((b >> 2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
+ b = ((b >> 4) + b) & 0x0F0F0F0F0F0F0F0FULL;
+ return (b * 0x0101010101010101ULL) >> 56;