Skip to content

Commit d4876dc

Browse files
committed
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>
1 parent 3249777 commit d4876dc

8 files changed

Lines changed: 67 additions & 70 deletions

File tree

src/Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ endif
222222
CXXFLAGS = -g -Wall -Wcast-qual -ansi -fno-exceptions -fno-rtti $(EXTRACXXFLAGS)
223223

224224
ifeq ($(comp),gcc)
225-
CXXFLAGS += -Wno-long-long -Wextra
225+
CXXFLAGS += -pedantic -Wno-long-long -Wextra
226226
endif
227227

228228
ifeq ($(comp),icc)

src/bitboard.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,7 @@ namespace {
404404
}
405405

406406
for (Bitboard b = 0ULL; b < 256ULL; b++)
407-
BitCount8Bit[b] = (uint8_t)count_1s(b);
407+
BitCount8Bit[b] = (uint8_t)count_1s<CNT32>(b);
408408
}
409409

410410
int remove_bit_8(int i) { return ((i & ~15) >> 1) | (i & 7); }
@@ -494,7 +494,7 @@ namespace {
494494
Bitboard index_to_bitboard(int index, Bitboard mask) {
495495

496496
Bitboard result = 0ULL;
497-
int bits = count_1s(mask);
497+
int bits = count_1s<CNT32>(mask);
498498

499499
for (int i = 0; i < bits; i++)
500500
{

src/bitcount.h

Lines changed: 41 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -24,44 +24,40 @@
2424

2525
#include "types.h"
2626

27-
// Select type of intrinsic bit count instruction to use, see
28-
// README.txt on how to pgo compile with POPCNT support.
29-
#if !defined(USE_POPCNT)
30-
#define POPCNT_INTRINSIC(x) 0
31-
#elif defined(_MSC_VER)
32-
#define POPCNT_INTRINSIC(x) (int)__popcnt64(x)
33-
#elif defined(__GNUC__)
34-
35-
#define POPCNT_INTRINSIC(x) ({ \
36-
unsigned long __ret; \
37-
__asm__("popcnt %1, %0" : "=r" (__ret) : "r" (x)); \
38-
__ret; })
39-
40-
#endif
27+
enum BitCountType {
28+
CNT64,
29+
CNT64_MAX15,
30+
CNT32,
31+
CNT32_MAX15,
32+
CNT_POPCNT
33+
};
4134

42-
43-
/// Software implementation of bit count functions
44-
45-
#if defined(IS_64BIT)
46-
47-
inline int count_1s(Bitboard b) {
35+
/// count_1s() counts the number of nonzero bits in a bitboard.
36+
/// We have different optimized versions according if platform
37+
/// is 32 or 64 bits, and to the maximum number of nonzero bits.
38+
/// We also support hardware popcnt instruction. See Readme.txt
39+
/// on how to pgo compile with popcnt support.
40+
template<BitCountType> inline int count_1s(Bitboard);
41+
42+
template<>
43+
inline int count_1s<CNT64>(Bitboard b) {
4844
b -= ((b>>1) & 0x5555555555555555ULL);
4945
b = ((b>>2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
5046
b = ((b>>4) + b) & 0x0F0F0F0F0F0F0F0FULL;
5147
b *= 0x0101010101010101ULL;
5248
return int(b >> 56);
5349
}
5450

55-
inline int count_1s_max_15(Bitboard b) {
51+
template<>
52+
inline int count_1s<CNT64_MAX15>(Bitboard b) {
5653
b -= (b>>1) & 0x5555555555555555ULL;
5754
b = ((b>>2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
5855
b *= 0x1111111111111111ULL;
5956
return int(b >> 60);
6057
}
6158

62-
#else // if !defined(IS_64BIT)
63-
64-
inline int count_1s(Bitboard b) {
59+
template<>
60+
inline int count_1s<CNT32>(Bitboard b) {
6561
unsigned w = unsigned(b >> 32), v = unsigned(b);
6662
v -= (v >> 1) & 0x55555555; // 0-2 in 2 bits
6763
w -= (w >> 1) & 0x55555555;
@@ -73,7 +69,8 @@ inline int count_1s(Bitboard b) {
7369
return int(v >> 24);
7470
}
7571

76-
inline int count_1s_max_15(Bitboard b) {
72+
template<>
73+
inline int count_1s<CNT32_MAX15>(Bitboard b) {
7774
unsigned w = unsigned(b >> 32), v = unsigned(b);
7875
v -= (v >> 1) & 0x55555555; // 0-2 in 2 bits
7976
w -= (w >> 1) & 0x55555555;
@@ -84,27 +81,21 @@ inline int count_1s_max_15(Bitboard b) {
8481
return int(v >> 28);
8582
}
8683

87-
#endif // BITCOUNT
88-
89-
90-
/// count_1s() counts the number of nonzero bits in a bitboard.
91-
/// If template parameter is true an intrinsic is called, otherwise
92-
/// we fallback on a software implementation.
93-
94-
template<bool UseIntrinsic>
95-
inline int count_1s(Bitboard b) {
96-
97-
return UseIntrinsic ? POPCNT_INTRINSIC(b) : count_1s(b);
98-
}
99-
100-
template<bool UseIntrinsic>
101-
inline int count_1s_max_15(Bitboard b) {
102-
103-
return UseIntrinsic ? POPCNT_INTRINSIC(b) : count_1s_max_15(b);
84+
template<>
85+
inline int count_1s<CNT_POPCNT>(Bitboard b) {
86+
#if !defined(USE_POPCNT)
87+
return int(b != 0); // Avoid 'b not used' warning
88+
#elif defined(_MSC_VER)
89+
return __popcnt64(b);
90+
#elif defined(__GNUC__)
91+
unsigned long ret;
92+
__asm__("popcnt %1, %0" : "=r" (ret) : "r" (b));
93+
return ret;
94+
#endif
10495
}
10596

10697

107-
// Detect hardware POPCNT support
98+
/// cpu_has_popcnt() detects support for popcnt instruction at runtime
10899
inline bool cpu_has_popcnt() {
109100

110101
int CPUInfo[4] = {-1};
@@ -113,22 +104,22 @@ inline bool cpu_has_popcnt() {
113104
}
114105

115106

116-
// Global constant initialized at startup that is set to true if
117-
// CPU on which application runs supports POPCNT intrinsic. Unless
118-
// USE_POPCNT is not defined.
107+
/// CpuHasPOPCNT is a global constant initialized at startup that
108+
/// is set to true if CPU on which application runs supports popcnt
109+
/// hardware instruction. Unless USE_POPCNT is not defined.
119110
#if defined(USE_POPCNT)
120111
const bool CpuHasPOPCNT = cpu_has_popcnt();
121112
#else
122113
const bool CpuHasPOPCNT = false;
123114
#endif
124115

125116

126-
// Global constant used to print info about the use of 64 optimized
127-
// functions to verify that a 64 bit compile has been correctly built.
117+
/// CpuIs64Bit is a global constant initialized at compile time that
118+
/// is set to true if CPU on which application runs is a 64 bits.
128119
#if defined(IS_64BIT)
129-
const bool CpuHas64BitPath = true;
120+
const bool CpuIs64Bit = true;
130121
#else
131-
const bool CpuHas64BitPath = false;
122+
const bool CpuIs64Bit = false;
132123
#endif
133124

134125
#endif // !defined(BITCOUNT_H_INCLUDED)

src/endgame.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -357,7 +357,7 @@ Value EvaluationFunction<KBBKN>::apply(const Position& pos) const {
357357
result += Value(square_distance(bksq, nsq) * 32);
358358

359359
// Bonus for restricting the knight's mobility
360-
result += Value((8 - count_1s_max_15(pos.attacks_from<KNIGHT>(nsq))) * 8);
360+
result += Value((8 - count_1s<CNT32_MAX15>(pos.attacks_from<KNIGHT>(nsq))) * 8);
361361

362362
return strongerSide == pos.side_to_move() ? result : -result;
363363
}

src/evaluate.cpp

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,7 @@ namespace {
439439
template<Color Us, bool HasPopCnt>
440440
void init_eval_info(const Position& pos, EvalInfo& ei) {
441441

442+
const BitCountType Max15 = HasPopCnt ? CNT_POPCNT : CpuIs64Bit ? CNT64_MAX15 : CNT32_MAX15;
442443
const Color Them = (Us == WHITE ? BLACK : WHITE);
443444

444445
Bitboard b = ei.attackedBy[Them][KING] = pos.attacks_from<KING>(pos.king_square(Them));
@@ -448,7 +449,7 @@ namespace {
448449
if (ei.updateKingTables[Us])
449450
{
450451
b &= ei.attackedBy[Us][PAWN];
451-
ei.kingAttackersCount[Us] = b ? count_1s_max_15<HasPopCnt>(b) / 2 : EmptyBoardBB;
452+
ei.kingAttackersCount[Us] = b ? count_1s<Max15>(b) / 2 : EmptyBoardBB;
452453
ei.kingAdjacentZoneAttacksCount[Us] = ei.kingAttackersWeight[Us] = EmptyBoardBB;
453454
}
454455
}
@@ -491,6 +492,8 @@ namespace {
491492
File f;
492493
Score bonus = SCORE_ZERO;
493494

495+
const BitCountType Full = HasPopCnt ? CNT_POPCNT : CpuIs64Bit ? CNT64 : CNT32;
496+
const BitCountType Max15 = HasPopCnt ? CNT_POPCNT : CpuIs64Bit ? CNT64_MAX15 : CNT32_MAX15;
494497
const Color Them = (Us == WHITE ? BLACK : WHITE);
495498
const Square* ptr = pos.piece_list_begin(Us, Piece);
496499

@@ -518,12 +521,12 @@ namespace {
518521
ei.kingAttackersWeight[Us] += KingAttackWeights[Piece];
519522
Bitboard bb = (b & ei.attackedBy[Them][KING]);
520523
if (bb)
521-
ei.kingAdjacentZoneAttacksCount[Us] += count_1s_max_15<HasPopCnt>(bb);
524+
ei.kingAdjacentZoneAttacksCount[Us] += count_1s<Max15>(bb);
522525
}
523526

524527
// Mobility
525-
mob = (Piece != QUEEN ? count_1s_max_15<HasPopCnt>(b & mobilityArea)
526-
: count_1s<HasPopCnt>(b & mobilityArea));
528+
mob = (Piece != QUEEN ? count_1s<Max15>(b & mobilityArea)
529+
: count_1s<Full >(b & mobilityArea));
527530

528531
mobility += MobilityBonus[Piece][mob];
529532

@@ -652,6 +655,7 @@ namespace {
652655
template<Color Us, bool HasPopCnt>
653656
Score evaluate_king(const Position& pos, EvalInfo& ei, Value& margin) {
654657

658+
const BitCountType Max15 = HasPopCnt ? CNT_POPCNT : CpuIs64Bit ? CNT64_MAX15 : CNT32_MAX15;
655659
const Color Them = (Us == WHITE ? BLACK : WHITE);
656660

657661
Bitboard undefended, b, b1, b2, safe;
@@ -680,7 +684,7 @@ namespace {
680684
// attacked and undefended squares around our king, the square of the
681685
// king, and the quality of the pawn shelter.
682686
attackUnits = Min(25, (ei.kingAttackersCount[Them] * ei.kingAttackersWeight[Them]) / 2)
683-
+ 3 * (ei.kingAdjacentZoneAttacksCount[Them] + count_1s_max_15<HasPopCnt>(undefended))
687+
+ 3 * (ei.kingAdjacentZoneAttacksCount[Them] + count_1s<Max15>(undefended))
684688
+ InitKingDanger[relative_square(Us, ksq)]
685689
- mg_value(ei.pi->king_shelter<Us>(pos, ksq)) / 32;
686690

@@ -694,7 +698,7 @@ namespace {
694698
| ei.attackedBy[Them][BISHOP] | ei.attackedBy[Them][ROOK]);
695699
if (b)
696700
attackUnits += QueenContactCheckBonus
697-
* count_1s_max_15<HasPopCnt>(b)
701+
* count_1s<Max15>(b)
698702
* (Them == pos.side_to_move() ? 2 : 1);
699703
}
700704

@@ -712,7 +716,7 @@ namespace {
712716
| ei.attackedBy[Them][BISHOP] | ei.attackedBy[Them][QUEEN]);
713717
if (b)
714718
attackUnits += RookContactCheckBonus
715-
* count_1s_max_15<HasPopCnt>(b)
719+
* count_1s<Max15>(b)
716720
* (Them == pos.side_to_move() ? 2 : 1);
717721
}
718722

@@ -725,22 +729,22 @@ namespace {
725729
// Enemy queen safe checks
726730
b = (b1 | b2) & ei.attackedBy[Them][QUEEN];
727731
if (b)
728-
attackUnits += QueenCheckBonus * count_1s_max_15<HasPopCnt>(b);
732+
attackUnits += QueenCheckBonus * count_1s<Max15>(b);
729733

730734
// Enemy rooks safe checks
731735
b = b1 & ei.attackedBy[Them][ROOK];
732736
if (b)
733-
attackUnits += RookCheckBonus * count_1s_max_15<HasPopCnt>(b);
737+
attackUnits += RookCheckBonus * count_1s<Max15>(b);
734738

735739
// Enemy bishops safe checks
736740
b = b2 & ei.attackedBy[Them][BISHOP];
737741
if (b)
738-
attackUnits += BishopCheckBonus * count_1s_max_15<HasPopCnt>(b);
742+
attackUnits += BishopCheckBonus * count_1s<Max15>(b);
739743

740744
// Enemy knights safe checks
741745
b = pos.attacks_from<KNIGHT>(ksq) & ei.attackedBy[Them][KNIGHT] & safe;
742746
if (b)
743-
attackUnits += KnightCheckBonus * count_1s_max_15<HasPopCnt>(b);
747+
attackUnits += KnightCheckBonus * count_1s<Max15>(b);
744748

745749
// To index KingDangerTable[] attackUnits must be in [0, 99] range
746750
attackUnits = Min(99, Max(0, attackUnits));
@@ -865,6 +869,7 @@ namespace {
865869
template<Color Us, bool HasPopCnt>
866870
int evaluate_space(const Position& pos, EvalInfo& ei) {
867871

872+
const BitCountType Max15 = HasPopCnt ? CNT_POPCNT : CpuIs64Bit ? CNT64_MAX15 : CNT32_MAX15;
868873
const Color Them = (Us == WHITE ? BLACK : WHITE);
869874

870875
// Find the safe squares for our pieces inside the area defined by
@@ -880,7 +885,7 @@ namespace {
880885
behind |= (Us == WHITE ? behind >> 8 : behind << 8);
881886
behind |= (Us == WHITE ? behind >> 16 : behind << 16);
882887

883-
return count_1s_max_15<HasPopCnt>(safe) + count_1s_max_15<HasPopCnt>(behind & safe);
888+
return count_1s<Max15>(safe) + count_1s<Max15>(behind & safe);
884889
}
885890

886891

src/misc.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ void dbg_print_mean(ofstream& logFile) {
146146

147147
const string engine_name() {
148148

149-
const string cpu64(CpuHas64BitPath ? " 64bit" : "");
149+
const string cpu64(CpuIs64Bit ? " 64bit" : "");
150150

151151
if (!EngineVersion.empty())
152152
return AppName + " " + EngineVersion + cpu64;

src/pawns.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
147147
Rank r;
148148
bool passed, isolated, doubled, opposed, chain, backward, candidate;
149149
Score value = SCORE_ZERO;
150+
const BitCountType Max15 = CpuIs64Bit ? CNT64_MAX15 : CNT32_MAX15;
150151
const Square* ptr = pos.piece_list_begin(Us, PAWN);
151152

152153
// Initialize halfOpenFiles[]
@@ -206,7 +207,7 @@ Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
206207
// Test for candidate passed pawn
207208
candidate = !(opposed | passed)
208209
&& (b = attack_span_mask(opposite_color(Us), s + pawn_push(Us)) & ourPawns) != EmptyBoardBB
209-
&& count_1s_max_15(b) >= count_1s_max_15(attack_span_mask(Us, s) & theirPawns);
210+
&& count_1s<Max15>(b) >= count_1s<Max15>(attack_span_mask(Us, s) & theirPawns);
210211

211212
// In order to prevent doubled passed pawns from receiving a too big
212213
// bonus, only the frontmost passed pawn on each file is considered as

src/position.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1917,7 +1917,7 @@ bool Position::is_ok(int* failedStep) const {
19171917

19181918
// Is there more than 2 checkers?
19191919
if (failedStep) (*failedStep)++;
1920-
if (debugCheckerCount && count_1s(st->checkersBB) > 2)
1920+
if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
19211921
return false;
19221922

19231923
// Bitboards OK?
@@ -1986,7 +1986,7 @@ bool Position::is_ok(int* failedStep) const {
19861986
if (debugPieceCounts)
19871987
for (Color c = WHITE; c <= BLACK; c++)
19881988
for (PieceType pt = PAWN; pt <= KING; pt++)
1989-
if (pieceCount[c][pt] != count_1s(pieces(pt, c)))
1989+
if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
19901990
return false;
19911991

19921992
if (failedStep) (*failedStep)++;

0 commit comments

Comments
 (0)