1
0
Fork 0
mirror of https://github.com/sockspls/badfish synced 2025-04-30 00:33:09 +00:00

Rewrite bit counting functions

Get rid of macros and use templates instead,
this is safer and allows us fix the warning:

ISO C++ forbids braced-groups within expressions

That broke compilation with -pedantic flag under
gcc and POPCNT enabled.

No functional and no performance change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
This commit is contained in:
Marco Costalba 2010-10-04 11:45:04 +02:00
parent 3249777cdb
commit d4876dc963
8 changed files with 66 additions and 69 deletions

View file

@ -222,7 +222,7 @@ endif
CXXFLAGS = -g -Wall -Wcast-qual -ansi -fno-exceptions -fno-rtti $(EXTRACXXFLAGS) CXXFLAGS = -g -Wall -Wcast-qual -ansi -fno-exceptions -fno-rtti $(EXTRACXXFLAGS)
ifeq ($(comp),gcc) ifeq ($(comp),gcc)
CXXFLAGS += -Wno-long-long -Wextra CXXFLAGS += -pedantic -Wno-long-long -Wextra
endif endif
ifeq ($(comp),icc) ifeq ($(comp),icc)

View file

@ -404,7 +404,7 @@ namespace {
} }
for (Bitboard b = 0ULL; b < 256ULL; b++) for (Bitboard b = 0ULL; b < 256ULL; b++)
BitCount8Bit[b] = (uint8_t)count_1s(b); BitCount8Bit[b] = (uint8_t)count_1s<CNT32>(b);
} }
int remove_bit_8(int i) { return ((i & ~15) >> 1) | (i & 7); } int remove_bit_8(int i) { return ((i & ~15) >> 1) | (i & 7); }
@ -494,7 +494,7 @@ namespace {
Bitboard index_to_bitboard(int index, Bitboard mask) { Bitboard index_to_bitboard(int index, Bitboard mask) {
Bitboard result = 0ULL; Bitboard result = 0ULL;
int bits = count_1s(mask); int bits = count_1s<CNT32>(mask);
for (int i = 0; i < bits; i++) for (int i = 0; i < bits; i++)
{ {

View file

@ -24,27 +24,23 @@
#include "types.h" #include "types.h"
// Select type of intrinsic bit count instruction to use, see enum BitCountType {
// README.txt on how to pgo compile with POPCNT support. CNT64,
#if !defined(USE_POPCNT) CNT64_MAX15,
#define POPCNT_INTRINSIC(x) 0 CNT32,
#elif defined(_MSC_VER) CNT32_MAX15,
#define POPCNT_INTRINSIC(x) (int)__popcnt64(x) CNT_POPCNT
#elif defined(__GNUC__) };
#define POPCNT_INTRINSIC(x) ({ \ /// count_1s() counts the number of nonzero bits in a bitboard.
unsigned long __ret; \ /// We have different optimized versions according if platform
__asm__("popcnt %1, %0" : "=r" (__ret) : "r" (x)); \ /// is 32 or 64 bits, and to the maximum number of nonzero bits.
__ret; }) /// We also support hardware popcnt instruction. See Readme.txt
/// on how to pgo compile with popcnt support.
template<BitCountType> inline int count_1s(Bitboard);
#endif template<>
inline int count_1s<CNT64>(Bitboard b) {
/// Software implementation of bit count functions
#if defined(IS_64BIT)
inline int count_1s(Bitboard b) {
b -= ((b>>1) & 0x5555555555555555ULL); b -= ((b>>1) & 0x5555555555555555ULL);
b = ((b>>2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL); b = ((b>>2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
b = ((b>>4) + b) & 0x0F0F0F0F0F0F0F0FULL; b = ((b>>4) + b) & 0x0F0F0F0F0F0F0F0FULL;
@ -52,16 +48,16 @@ inline int count_1s(Bitboard b) {
return int(b >> 56); return int(b >> 56);
} }
inline int count_1s_max_15(Bitboard b) { template<>
inline int count_1s<CNT64_MAX15>(Bitboard b) {
b -= (b>>1) & 0x5555555555555555ULL; b -= (b>>1) & 0x5555555555555555ULL;
b = ((b>>2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL); b = ((b>>2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
b *= 0x1111111111111111ULL; b *= 0x1111111111111111ULL;
return int(b >> 60); return int(b >> 60);
} }
#else // if !defined(IS_64BIT) template<>
inline int count_1s<CNT32>(Bitboard b) {
inline int count_1s(Bitboard b) {
unsigned w = unsigned(b >> 32), v = unsigned(b); unsigned w = unsigned(b >> 32), v = unsigned(b);
v -= (v >> 1) & 0x55555555; // 0-2 in 2 bits v -= (v >> 1) & 0x55555555; // 0-2 in 2 bits
w -= (w >> 1) & 0x55555555; w -= (w >> 1) & 0x55555555;
@ -73,7 +69,8 @@ inline int count_1s(Bitboard b) {
return int(v >> 24); return int(v >> 24);
} }
inline int count_1s_max_15(Bitboard b) { template<>
inline int count_1s<CNT32_MAX15>(Bitboard b) {
unsigned w = unsigned(b >> 32), v = unsigned(b); unsigned w = unsigned(b >> 32), v = unsigned(b);
v -= (v >> 1) & 0x55555555; // 0-2 in 2 bits v -= (v >> 1) & 0x55555555; // 0-2 in 2 bits
w -= (w >> 1) & 0x55555555; w -= (w >> 1) & 0x55555555;
@ -84,27 +81,21 @@ inline int count_1s_max_15(Bitboard b) {
return int(v >> 28); return int(v >> 28);
} }
#endif // BITCOUNT template<>
inline int count_1s<CNT_POPCNT>(Bitboard b) {
#if !defined(USE_POPCNT)
/// count_1s() counts the number of nonzero bits in a bitboard. return int(b != 0); // Avoid 'b not used' warning
/// If template parameter is true an intrinsic is called, otherwise #elif defined(_MSC_VER)
/// we fallback on a software implementation. return __popcnt64(b);
#elif defined(__GNUC__)
template<bool UseIntrinsic> unsigned long ret;
inline int count_1s(Bitboard b) { __asm__("popcnt %1, %0" : "=r" (ret) : "r" (b));
return ret;
return UseIntrinsic ? POPCNT_INTRINSIC(b) : count_1s(b); #endif
}
template<bool UseIntrinsic>
inline int count_1s_max_15(Bitboard b) {
return UseIntrinsic ? POPCNT_INTRINSIC(b) : count_1s_max_15(b);
} }
// Detect hardware POPCNT support /// cpu_has_popcnt() detects support for popcnt instruction at runtime
inline bool cpu_has_popcnt() { inline bool cpu_has_popcnt() {
int CPUInfo[4] = {-1}; int CPUInfo[4] = {-1};
@ -113,9 +104,9 @@ inline bool cpu_has_popcnt() {
} }
// Global constant initialized at startup that is set to true if /// CpuHasPOPCNT is a global constant initialized at startup that
// CPU on which application runs supports POPCNT intrinsic. Unless /// is set to true if CPU on which application runs supports popcnt
// USE_POPCNT is not defined. /// hardware instruction. Unless USE_POPCNT is not defined.
#if defined(USE_POPCNT) #if defined(USE_POPCNT)
const bool CpuHasPOPCNT = cpu_has_popcnt(); const bool CpuHasPOPCNT = cpu_has_popcnt();
#else #else
@ -123,12 +114,12 @@ const bool CpuHasPOPCNT = false;
#endif #endif
// Global constant used to print info about the use of 64 optimized /// CpuIs64Bit is a global constant initialized at compile time that
// functions to verify that a 64 bit compile has been correctly built. /// is set to true if CPU on which application runs is a 64 bits.
#if defined(IS_64BIT) #if defined(IS_64BIT)
const bool CpuHas64BitPath = true; const bool CpuIs64Bit = true;
#else #else
const bool CpuHas64BitPath = false; const bool CpuIs64Bit = false;
#endif #endif
#endif // !defined(BITCOUNT_H_INCLUDED) #endif // !defined(BITCOUNT_H_INCLUDED)

View file

@ -357,7 +357,7 @@ Value EvaluationFunction<KBBKN>::apply(const Position& pos) const {
result += Value(square_distance(bksq, nsq) * 32); result += Value(square_distance(bksq, nsq) * 32);
// Bonus for restricting the knight's mobility // Bonus for restricting the knight's mobility
result += Value((8 - count_1s_max_15(pos.attacks_from<KNIGHT>(nsq))) * 8); result += Value((8 - count_1s<CNT32_MAX15>(pos.attacks_from<KNIGHT>(nsq))) * 8);
return strongerSide == pos.side_to_move() ? result : -result; return strongerSide == pos.side_to_move() ? result : -result;
} }

View file

@ -439,6 +439,7 @@ namespace {
template<Color Us, bool HasPopCnt> template<Color Us, bool HasPopCnt>
void init_eval_info(const Position& pos, EvalInfo& ei) { void init_eval_info(const Position& pos, EvalInfo& ei) {
const BitCountType Max15 = HasPopCnt ? CNT_POPCNT : CpuIs64Bit ? CNT64_MAX15 : CNT32_MAX15;
const Color Them = (Us == WHITE ? BLACK : WHITE); const Color Them = (Us == WHITE ? BLACK : WHITE);
Bitboard b = ei.attackedBy[Them][KING] = pos.attacks_from<KING>(pos.king_square(Them)); Bitboard b = ei.attackedBy[Them][KING] = pos.attacks_from<KING>(pos.king_square(Them));
@ -448,7 +449,7 @@ namespace {
if (ei.updateKingTables[Us]) if (ei.updateKingTables[Us])
{ {
b &= ei.attackedBy[Us][PAWN]; b &= ei.attackedBy[Us][PAWN];
ei.kingAttackersCount[Us] = b ? count_1s_max_15<HasPopCnt>(b) / 2 : EmptyBoardBB; ei.kingAttackersCount[Us] = b ? count_1s<Max15>(b) / 2 : EmptyBoardBB;
ei.kingAdjacentZoneAttacksCount[Us] = ei.kingAttackersWeight[Us] = EmptyBoardBB; ei.kingAdjacentZoneAttacksCount[Us] = ei.kingAttackersWeight[Us] = EmptyBoardBB;
} }
} }
@ -491,6 +492,8 @@ namespace {
File f; File f;
Score bonus = SCORE_ZERO; Score bonus = SCORE_ZERO;
const BitCountType Full = HasPopCnt ? CNT_POPCNT : CpuIs64Bit ? CNT64 : CNT32;
const BitCountType Max15 = HasPopCnt ? CNT_POPCNT : CpuIs64Bit ? CNT64_MAX15 : CNT32_MAX15;
const Color Them = (Us == WHITE ? BLACK : WHITE); const Color Them = (Us == WHITE ? BLACK : WHITE);
const Square* ptr = pos.piece_list_begin(Us, Piece); const Square* ptr = pos.piece_list_begin(Us, Piece);
@ -518,12 +521,12 @@ namespace {
ei.kingAttackersWeight[Us] += KingAttackWeights[Piece]; ei.kingAttackersWeight[Us] += KingAttackWeights[Piece];
Bitboard bb = (b & ei.attackedBy[Them][KING]); Bitboard bb = (b & ei.attackedBy[Them][KING]);
if (bb) if (bb)
ei.kingAdjacentZoneAttacksCount[Us] += count_1s_max_15<HasPopCnt>(bb); ei.kingAdjacentZoneAttacksCount[Us] += count_1s<Max15>(bb);
} }
// Mobility // Mobility
mob = (Piece != QUEEN ? count_1s_max_15<HasPopCnt>(b & mobilityArea) mob = (Piece != QUEEN ? count_1s<Max15>(b & mobilityArea)
: count_1s<HasPopCnt>(b & mobilityArea)); : count_1s<Full >(b & mobilityArea));
mobility += MobilityBonus[Piece][mob]; mobility += MobilityBonus[Piece][mob];
@ -652,6 +655,7 @@ namespace {
template<Color Us, bool HasPopCnt> template<Color Us, bool HasPopCnt>
Score evaluate_king(const Position& pos, EvalInfo& ei, Value& margin) { Score evaluate_king(const Position& pos, EvalInfo& ei, Value& margin) {
const BitCountType Max15 = HasPopCnt ? CNT_POPCNT : CpuIs64Bit ? CNT64_MAX15 : CNT32_MAX15;
const Color Them = (Us == WHITE ? BLACK : WHITE); const Color Them = (Us == WHITE ? BLACK : WHITE);
Bitboard undefended, b, b1, b2, safe; Bitboard undefended, b, b1, b2, safe;
@ -680,7 +684,7 @@ namespace {
// attacked and undefended squares around our king, the square of the // attacked and undefended squares around our king, the square of the
// king, and the quality of the pawn shelter. // king, and the quality of the pawn shelter.
attackUnits = Min(25, (ei.kingAttackersCount[Them] * ei.kingAttackersWeight[Them]) / 2) attackUnits = Min(25, (ei.kingAttackersCount[Them] * ei.kingAttackersWeight[Them]) / 2)
+ 3 * (ei.kingAdjacentZoneAttacksCount[Them] + count_1s_max_15<HasPopCnt>(undefended)) + 3 * (ei.kingAdjacentZoneAttacksCount[Them] + count_1s<Max15>(undefended))
+ InitKingDanger[relative_square(Us, ksq)] + InitKingDanger[relative_square(Us, ksq)]
- mg_value(ei.pi->king_shelter<Us>(pos, ksq)) / 32; - mg_value(ei.pi->king_shelter<Us>(pos, ksq)) / 32;
@ -694,7 +698,7 @@ namespace {
| ei.attackedBy[Them][BISHOP] | ei.attackedBy[Them][ROOK]); | ei.attackedBy[Them][BISHOP] | ei.attackedBy[Them][ROOK]);
if (b) if (b)
attackUnits += QueenContactCheckBonus attackUnits += QueenContactCheckBonus
* count_1s_max_15<HasPopCnt>(b) * count_1s<Max15>(b)
* (Them == pos.side_to_move() ? 2 : 1); * (Them == pos.side_to_move() ? 2 : 1);
} }
@ -712,7 +716,7 @@ namespace {
| ei.attackedBy[Them][BISHOP] | ei.attackedBy[Them][QUEEN]); | ei.attackedBy[Them][BISHOP] | ei.attackedBy[Them][QUEEN]);
if (b) if (b)
attackUnits += RookContactCheckBonus attackUnits += RookContactCheckBonus
* count_1s_max_15<HasPopCnt>(b) * count_1s<Max15>(b)
* (Them == pos.side_to_move() ? 2 : 1); * (Them == pos.side_to_move() ? 2 : 1);
} }
@ -725,22 +729,22 @@ namespace {
// Enemy queen safe checks // Enemy queen safe checks
b = (b1 | b2) & ei.attackedBy[Them][QUEEN]; b = (b1 | b2) & ei.attackedBy[Them][QUEEN];
if (b) if (b)
attackUnits += QueenCheckBonus * count_1s_max_15<HasPopCnt>(b); attackUnits += QueenCheckBonus * count_1s<Max15>(b);
// Enemy rooks safe checks // Enemy rooks safe checks
b = b1 & ei.attackedBy[Them][ROOK]; b = b1 & ei.attackedBy[Them][ROOK];
if (b) if (b)
attackUnits += RookCheckBonus * count_1s_max_15<HasPopCnt>(b); attackUnits += RookCheckBonus * count_1s<Max15>(b);
// Enemy bishops safe checks // Enemy bishops safe checks
b = b2 & ei.attackedBy[Them][BISHOP]; b = b2 & ei.attackedBy[Them][BISHOP];
if (b) if (b)
attackUnits += BishopCheckBonus * count_1s_max_15<HasPopCnt>(b); attackUnits += BishopCheckBonus * count_1s<Max15>(b);
// Enemy knights safe checks // Enemy knights safe checks
b = pos.attacks_from<KNIGHT>(ksq) & ei.attackedBy[Them][KNIGHT] & safe; b = pos.attacks_from<KNIGHT>(ksq) & ei.attackedBy[Them][KNIGHT] & safe;
if (b) if (b)
attackUnits += KnightCheckBonus * count_1s_max_15<HasPopCnt>(b); attackUnits += KnightCheckBonus * count_1s<Max15>(b);
// To index KingDangerTable[] attackUnits must be in [0, 99] range // To index KingDangerTable[] attackUnits must be in [0, 99] range
attackUnits = Min(99, Max(0, attackUnits)); attackUnits = Min(99, Max(0, attackUnits));
@ -865,6 +869,7 @@ namespace {
template<Color Us, bool HasPopCnt> template<Color Us, bool HasPopCnt>
int evaluate_space(const Position& pos, EvalInfo& ei) { int evaluate_space(const Position& pos, EvalInfo& ei) {
const BitCountType Max15 = HasPopCnt ? CNT_POPCNT : CpuIs64Bit ? CNT64_MAX15 : CNT32_MAX15;
const Color Them = (Us == WHITE ? BLACK : WHITE); const Color Them = (Us == WHITE ? BLACK : WHITE);
// Find the safe squares for our pieces inside the area defined by // Find the safe squares for our pieces inside the area defined by
@ -880,7 +885,7 @@ namespace {
behind |= (Us == WHITE ? behind >> 8 : behind << 8); behind |= (Us == WHITE ? behind >> 8 : behind << 8);
behind |= (Us == WHITE ? behind >> 16 : behind << 16); behind |= (Us == WHITE ? behind >> 16 : behind << 16);
return count_1s_max_15<HasPopCnt>(safe) + count_1s_max_15<HasPopCnt>(behind & safe); return count_1s<Max15>(safe) + count_1s<Max15>(behind & safe);
} }

View file

@ -146,7 +146,7 @@ void dbg_print_mean(ofstream& logFile) {
const string engine_name() { const string engine_name() {
const string cpu64(CpuHas64BitPath ? " 64bit" : ""); const string cpu64(CpuIs64Bit ? " 64bit" : "");
if (!EngineVersion.empty()) if (!EngineVersion.empty())
return AppName + " " + EngineVersion + cpu64; return AppName + " " + EngineVersion + cpu64;

View file

@ -147,6 +147,7 @@ Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
Rank r; Rank r;
bool passed, isolated, doubled, opposed, chain, backward, candidate; bool passed, isolated, doubled, opposed, chain, backward, candidate;
Score value = SCORE_ZERO; Score value = SCORE_ZERO;
const BitCountType Max15 = CpuIs64Bit ? CNT64_MAX15 : CNT32_MAX15;
const Square* ptr = pos.piece_list_begin(Us, PAWN); const Square* ptr = pos.piece_list_begin(Us, PAWN);
// Initialize halfOpenFiles[] // Initialize halfOpenFiles[]
@ -206,7 +207,7 @@ Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
// Test for candidate passed pawn // Test for candidate passed pawn
candidate = !(opposed | passed) candidate = !(opposed | passed)
&& (b = attack_span_mask(opposite_color(Us), s + pawn_push(Us)) & ourPawns) != EmptyBoardBB && (b = attack_span_mask(opposite_color(Us), s + pawn_push(Us)) & ourPawns) != EmptyBoardBB
&& count_1s_max_15(b) >= count_1s_max_15(attack_span_mask(Us, s) & theirPawns); && count_1s<Max15>(b) >= count_1s<Max15>(attack_span_mask(Us, s) & theirPawns);
// In order to prevent doubled passed pawns from receiving a too big // In order to prevent doubled passed pawns from receiving a too big
// bonus, only the frontmost passed pawn on each file is considered as // bonus, only the frontmost passed pawn on each file is considered as

View file

@ -1917,7 +1917,7 @@ bool Position::is_ok(int* failedStep) const {
// Is there more than 2 checkers? // Is there more than 2 checkers?
if (failedStep) (*failedStep)++; if (failedStep) (*failedStep)++;
if (debugCheckerCount && count_1s(st->checkersBB) > 2) if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
return false; return false;
// Bitboards OK? // Bitboards OK?
@ -1986,7 +1986,7 @@ bool Position::is_ok(int* failedStep) const {
if (debugPieceCounts) if (debugPieceCounts)
for (Color c = WHITE; c <= BLACK; c++) for (Color c = WHITE; c <= BLACK; c++)
for (PieceType pt = PAWN; pt <= KING; pt++) for (PieceType pt = PAWN; pt <= KING; pt++)
if (pieceCount[c][pt] != count_1s(pieces(pt, c))) if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
return false; return false;
if (failedStep) (*failedStep)++; if (failedStep) (*failedStep)++;