Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
official-stockfish
GitHub Repository: official-stockfish/Stockfish
Path: blob/master/src/bitboard.h
626 views
1
/*
2
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
Copyright (C) 2004-2026 The Stockfish developers (see AUTHORS file)
4
5
Stockfish is free software: you can redistribute it and/or modify
6
it under the terms of the GNU General Public License as published by
7
the Free Software Foundation, either version 3 of the License, or
8
(at your option) any later version.
9
10
Stockfish is distributed in the hope that it will be useful,
11
but WITHOUT ANY WARRANTY; without even the implied warranty of
12
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
GNU General Public License for more details.
14
15
You should have received a copy of the GNU General Public License
16
along with this program. If not, see <http://www.gnu.org/licenses/>.
17
*/
18
19
#ifndef BITBOARD_H_INCLUDED
20
#define BITBOARD_H_INCLUDED
21
22
#include <algorithm>
23
#include <cassert>
24
#include <cmath>
25
#include <cstring>
26
#include <cstdint>
27
#include <cstdlib>
28
#include <string>
29
#include <initializer_list>
30
#include <array>
31
32
#include "types.h"
33
34
namespace Stockfish {
35
36
namespace Bitboards {
37
38
void init();
39
std::string pretty(Bitboard b);
40
41
} // namespace Stockfish::Bitboards
42
43
constexpr Bitboard FileABB = 0x0101010101010101ULL;
44
constexpr Bitboard FileBBB = FileABB << 1;
45
constexpr Bitboard FileCBB = FileABB << 2;
46
constexpr Bitboard FileDBB = FileABB << 3;
47
constexpr Bitboard FileEBB = FileABB << 4;
48
constexpr Bitboard FileFBB = FileABB << 5;
49
constexpr Bitboard FileGBB = FileABB << 6;
50
constexpr Bitboard FileHBB = FileABB << 7;
51
52
constexpr Bitboard Rank1BB = 0xFF;
53
constexpr Bitboard Rank2BB = Rank1BB << (8 * 1);
54
constexpr Bitboard Rank3BB = Rank1BB << (8 * 2);
55
constexpr Bitboard Rank4BB = Rank1BB << (8 * 3);
56
constexpr Bitboard Rank5BB = Rank1BB << (8 * 4);
57
constexpr Bitboard Rank6BB = Rank1BB << (8 * 5);
58
constexpr Bitboard Rank7BB = Rank1BB << (8 * 6);
59
constexpr Bitboard Rank8BB = Rank1BB << (8 * 7);
60
61
extern uint8_t PopCnt16[1 << 16];
62
extern uint8_t SquareDistance[SQUARE_NB][SQUARE_NB];
63
64
extern Bitboard BetweenBB[SQUARE_NB][SQUARE_NB];
65
extern Bitboard LineBB[SQUARE_NB][SQUARE_NB];
66
extern Bitboard RayPassBB[SQUARE_NB][SQUARE_NB];
67
68
// Magic holds all magic bitboards relevant data for a single square
69
struct Magic {
70
Bitboard mask;
71
Bitboard* attacks;
72
#ifndef USE_PEXT
73
Bitboard magic;
74
unsigned shift;
75
#endif
76
77
// Compute the attack's index using the 'magic bitboards' approach
78
unsigned index(Bitboard occupied) const {
79
80
#ifdef USE_PEXT
81
return unsigned(pext(occupied, mask));
82
#else
83
if (Is64Bit)
84
return unsigned(((occupied & mask) * magic) >> shift);
85
86
unsigned lo = unsigned(occupied) & unsigned(mask);
87
unsigned hi = unsigned(occupied >> 32) & unsigned(mask >> 32);
88
return (lo * unsigned(magic) ^ hi * unsigned(magic >> 32)) >> shift;
89
#endif
90
}
91
92
Bitboard attacks_bb(Bitboard occupied) const { return attacks[index(occupied)]; }
93
};
94
95
extern Magic Magics[SQUARE_NB][2];
96
97
constexpr Bitboard square_bb(Square s) {
98
assert(is_ok(s));
99
return (1ULL << s);
100
}
101
102
103
// Overloads of bitwise operators between a Bitboard and a Square for testing
104
// whether a given bit is set in a bitboard, and for setting and clearing bits.
105
106
constexpr Bitboard operator&(Bitboard b, Square s) { return b & square_bb(s); }
107
constexpr Bitboard operator|(Bitboard b, Square s) { return b | square_bb(s); }
108
constexpr Bitboard operator^(Bitboard b, Square s) { return b ^ square_bb(s); }
109
constexpr Bitboard& operator|=(Bitboard& b, Square s) { return b |= square_bb(s); }
110
constexpr Bitboard& operator^=(Bitboard& b, Square s) { return b ^= square_bb(s); }
111
112
constexpr Bitboard operator&(Square s, Bitboard b) { return b & s; }
113
constexpr Bitboard operator|(Square s, Bitboard b) { return b | s; }
114
constexpr Bitboard operator^(Square s, Bitboard b) { return b ^ s; }
115
116
constexpr Bitboard operator|(Square s1, Square s2) { return square_bb(s1) | s2; }
117
118
constexpr bool more_than_one(Bitboard b) { return b & (b - 1); }
119
120
121
// rank_bb() and file_bb() return a bitboard representing all the squares on
122
// the given file or rank.
123
124
constexpr Bitboard rank_bb(Rank r) { return Rank1BB << (8 * r); }
125
126
constexpr Bitboard rank_bb(Square s) { return rank_bb(rank_of(s)); }
127
128
constexpr Bitboard file_bb(File f) { return FileABB << f; }
129
130
constexpr Bitboard file_bb(Square s) { return file_bb(file_of(s)); }
131
132
133
// Moves a bitboard one or two steps as specified by the direction D
134
template<Direction D>
135
constexpr Bitboard shift(Bitboard b) {
136
return D == NORTH ? b << 8
137
: D == SOUTH ? b >> 8
138
: D == NORTH + NORTH ? b << 16
139
: D == SOUTH + SOUTH ? b >> 16
140
: D == EAST ? (b & ~FileHBB) << 1
141
: D == WEST ? (b & ~FileABB) >> 1
142
: D == NORTH_EAST ? (b & ~FileHBB) << 9
143
: D == NORTH_WEST ? (b & ~FileABB) << 7
144
: D == SOUTH_EAST ? (b & ~FileHBB) >> 7
145
: D == SOUTH_WEST ? (b & ~FileABB) >> 9
146
: 0;
147
}
148
149
150
// Returns the squares attacked by pawns of the given color
151
// from the squares in the given bitboard.
152
template<Color C>
153
constexpr Bitboard pawn_attacks_bb(Bitboard b) {
154
return C == WHITE ? shift<NORTH_WEST>(b) | shift<NORTH_EAST>(b)
155
: shift<SOUTH_WEST>(b) | shift<SOUTH_EAST>(b);
156
}
157
158
159
// Returns a bitboard representing an entire line (from board edge
160
// to board edge) that intersects the two given squares. If the given squares
161
// are not on a same file/rank/diagonal, the function returns 0. For instance,
162
// line_bb(SQ_C4, SQ_F7) will return a bitboard with the A2-G8 diagonal.
163
inline Bitboard line_bb(Square s1, Square s2) {
164
165
assert(is_ok(s1) && is_ok(s2));
166
return LineBB[s1][s2];
167
}
168
169
170
// Returns a bitboard representing the squares in the semi-open
171
// segment between the squares s1 and s2 (excluding s1 but including s2). If the
172
// given squares are not on a same file/rank/diagonal, it returns s2. For instance,
173
// between_bb(SQ_C4, SQ_F7) will return a bitboard with squares D5, E6 and F7, but
174
// between_bb(SQ_E6, SQ_F8) will return a bitboard with the square F8. This trick
175
// allows to generate non-king evasion moves faster: the defending piece must either
176
// interpose itself to cover the check or capture the checking piece.
177
inline Bitboard between_bb(Square s1, Square s2) {
178
179
assert(is_ok(s1) && is_ok(s2));
180
return BetweenBB[s1][s2];
181
}
182
183
// distance() functions return the distance between x and y, defined as the
184
// number of steps for a king in x to reach y.
185
186
template<typename T1 = Square>
187
inline int distance(Square x, Square y);
188
189
template<>
190
inline int distance<File>(Square x, Square y) {
191
return std::abs(file_of(x) - file_of(y));
192
}
193
194
template<>
195
inline int distance<Rank>(Square x, Square y) {
196
return std::abs(rank_of(x) - rank_of(y));
197
}
198
199
template<>
200
inline int distance<Square>(Square x, Square y) {
201
return SquareDistance[x][y];
202
}
203
204
inline int edge_distance(File f) { return std::min(f, File(FILE_H - f)); }
205
206
207
constexpr int constexpr_popcount(Bitboard b) {
208
b = b - ((b >> 1) & 0x5555555555555555ULL);
209
b = (b & 0x3333333333333333ULL) + ((b >> 2) & 0x3333333333333333ULL);
210
b = (b + (b >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
211
return static_cast<int>((b * 0x0101010101010101ULL) >> 56);
212
}
213
214
// Counts the number of non-zero bits in a bitboard.
215
inline int popcount(Bitboard b) {
216
217
#ifndef USE_POPCNT
218
219
std::uint16_t indices[4];
220
std::memcpy(indices, &b, sizeof(b));
221
return PopCnt16[indices[0]] + PopCnt16[indices[1]] + PopCnt16[indices[2]]
222
+ PopCnt16[indices[3]];
223
224
#elif defined(_MSC_VER)
225
226
return int(_mm_popcnt_u64(b));
227
228
#else // Assumed gcc or compatible compiler
229
230
return __builtin_popcountll(b);
231
232
#endif
233
}
234
235
// Returns the least significant bit in a non-zero bitboard.
236
inline Square lsb(Bitboard b) {
237
assert(b);
238
239
#if defined(__GNUC__) // GCC, Clang, ICX
240
241
return Square(__builtin_ctzll(b));
242
243
#elif defined(_MSC_VER)
244
#ifdef _WIN64 // MSVC, WIN64
245
246
unsigned long idx;
247
_BitScanForward64(&idx, b);
248
return Square(idx);
249
250
#else // MSVC, WIN32
251
unsigned long idx;
252
253
if (b & 0xffffffff)
254
{
255
_BitScanForward(&idx, int32_t(b));
256
return Square(idx);
257
}
258
else
259
{
260
_BitScanForward(&idx, int32_t(b >> 32));
261
return Square(idx + 32);
262
}
263
#endif
264
#else // Compiler is neither GCC nor MSVC compatible
265
#error "Compiler not supported."
266
#endif
267
}
268
269
// Returns the most significant bit in a non-zero bitboard.
270
inline Square msb(Bitboard b) {
271
assert(b);
272
273
#if defined(__GNUC__) // GCC, Clang, ICX
274
275
return Square(63 ^ __builtin_clzll(b));
276
277
#elif defined(_MSC_VER)
278
#ifdef _WIN64 // MSVC, WIN64
279
280
unsigned long idx;
281
_BitScanReverse64(&idx, b);
282
return Square(idx);
283
284
#else // MSVC, WIN32
285
286
unsigned long idx;
287
288
if (b >> 32)
289
{
290
_BitScanReverse(&idx, int32_t(b >> 32));
291
return Square(idx + 32);
292
}
293
else
294
{
295
_BitScanReverse(&idx, int32_t(b));
296
return Square(idx);
297
}
298
#endif
299
#else // Compiler is neither GCC nor MSVC compatible
300
#error "Compiler not supported."
301
#endif
302
}
303
304
// Returns the bitboard of the least significant
305
// square of a non-zero bitboard. It is equivalent to square_bb(lsb(bb)).
306
inline Bitboard least_significant_square_bb(Bitboard b) {
307
assert(b);
308
return b & -b;
309
}
310
311
// Finds and clears the least significant bit in a non-zero bitboard.
312
inline Square pop_lsb(Bitboard& b) {
313
assert(b);
314
const Square s = lsb(b);
315
b &= b - 1;
316
return s;
317
}
318
319
namespace Bitboards {
320
// Returns the bitboard of target square for the given step
321
// from the given square. If the step is off the board, returns empty bitboard.
322
constexpr Bitboard safe_destination(Square s, int step) {
323
constexpr auto abs = [](int v) { return v < 0 ? -v : v; };
324
Square to = Square(s + step);
325
return is_ok(to) && abs(file_of(s) - file_of(to)) <= 2 ? square_bb(to) : Bitboard(0);
326
}
327
328
constexpr Bitboard sliding_attack(PieceType pt, Square sq, Bitboard occupied) {
329
Bitboard attacks = 0;
330
Direction RookDirections[4] = {NORTH, SOUTH, EAST, WEST};
331
Direction BishopDirections[4] = {NORTH_EAST, SOUTH_EAST, SOUTH_WEST, NORTH_WEST};
332
333
for (Direction d : (pt == ROOK ? RookDirections : BishopDirections))
334
{
335
Square s = sq;
336
while (safe_destination(s, d))
337
{
338
attacks |= (s += d);
339
if (occupied & s)
340
{
341
break;
342
}
343
}
344
}
345
346
return attacks;
347
}
348
349
constexpr Bitboard knight_attack(Square sq) {
350
Bitboard b = {};
351
for (int step : {-17, -15, -10, -6, 6, 10, 15, 17})
352
b |= safe_destination(sq, step);
353
return b;
354
}
355
356
constexpr Bitboard king_attack(Square sq) {
357
Bitboard b = {};
358
for (int step : {-9, -8, -7, -1, 1, 7, 8, 9})
359
b |= safe_destination(sq, step);
360
return b;
361
}
362
363
constexpr Bitboard pseudo_attacks(PieceType pt, Square sq) {
364
switch (pt)
365
{
366
case PieceType::ROOK :
367
case PieceType::BISHOP :
368
return sliding_attack(pt, sq, 0);
369
case PieceType::QUEEN :
370
return sliding_attack(PieceType::ROOK, sq, 0) | sliding_attack(PieceType::BISHOP, sq, 0);
371
case PieceType::KNIGHT :
372
return knight_attack(sq);
373
case PieceType::KING :
374
return king_attack(sq);
375
default :
376
assert(false);
377
return 0;
378
}
379
}
380
381
}
382
383
inline constexpr auto PseudoAttacks = []() constexpr {
384
std::array<std::array<Bitboard, SQUARE_NB>, PIECE_TYPE_NB> attacks{};
385
386
for (Square s1 = SQ_A1; s1 <= SQ_H8; ++s1)
387
{
388
attacks[WHITE][s1] = pawn_attacks_bb<WHITE>(square_bb(s1));
389
attacks[BLACK][s1] = pawn_attacks_bb<BLACK>(square_bb(s1));
390
391
attacks[KING][s1] = Bitboards::pseudo_attacks(KING, s1);
392
attacks[KNIGHT][s1] = Bitboards::pseudo_attacks(KNIGHT, s1);
393
attacks[QUEEN][s1] = attacks[BISHOP][s1] = Bitboards::pseudo_attacks(BISHOP, s1);
394
attacks[QUEEN][s1] |= attacks[ROOK][s1] = Bitboards::pseudo_attacks(ROOK, s1);
395
}
396
397
return attacks;
398
}();
399
400
401
// Returns the pseudo attacks of the given piece type
402
// assuming an empty board.
403
template<PieceType Pt>
404
inline Bitboard attacks_bb(Square s, Color c = COLOR_NB) {
405
406
assert((Pt != PAWN || c < COLOR_NB) && (is_ok(s)));
407
return Pt == PAWN ? PseudoAttacks[c][s] : PseudoAttacks[Pt][s];
408
}
409
410
411
// Returns the attacks by the given piece
412
// assuming the board is occupied according to the passed Bitboard.
413
// Sliding piece attacks do not continue passed an occupied square.
414
template<PieceType Pt>
415
inline Bitboard attacks_bb(Square s, Bitboard occupied) {
416
417
assert((Pt != PAWN) && (is_ok(s)));
418
419
switch (Pt)
420
{
421
case BISHOP :
422
case ROOK :
423
return Magics[s][Pt - BISHOP].attacks_bb(occupied);
424
case QUEEN :
425
return attacks_bb<BISHOP>(s, occupied) | attacks_bb<ROOK>(s, occupied);
426
default :
427
return PseudoAttacks[Pt][s];
428
}
429
}
430
431
// Returns the attacks by the given piece
432
// assuming the board is occupied according to the passed Bitboard.
433
// Sliding piece attacks do not continue passed an occupied square.
434
inline Bitboard attacks_bb(PieceType pt, Square s, Bitboard occupied) {
435
436
assert((pt != PAWN) && (is_ok(s)));
437
438
switch (pt)
439
{
440
case BISHOP :
441
return attacks_bb<BISHOP>(s, occupied);
442
case ROOK :
443
return attacks_bb<ROOK>(s, occupied);
444
case QUEEN :
445
return attacks_bb<BISHOP>(s, occupied) | attacks_bb<ROOK>(s, occupied);
446
default :
447
return PseudoAttacks[pt][s];
448
}
449
}
450
451
inline Bitboard attacks_bb(Piece pc, Square s) {
452
if (type_of(pc) == PAWN)
453
return PseudoAttacks[color_of(pc)][s];
454
455
return PseudoAttacks[type_of(pc)][s];
456
}
457
458
459
inline Bitboard attacks_bb(Piece pc, Square s, Bitboard occupied) {
460
if (type_of(pc) == PAWN)
461
return PseudoAttacks[color_of(pc)][s];
462
463
return attacks_bb(type_of(pc), s, occupied);
464
}
465
466
} // namespace Stockfish
467
468
#endif // #ifndef BITBOARD_H_INCLUDED
469
470