]> git.sesse.net Git - stockfish/blob - src/syzygy/tbprobe.cpp
Make casting styles consistent
[stockfish] / src / syzygy / tbprobe.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2023 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 #include "tbprobe.h"
20
21 #include <sys/stat.h>
22 #include <algorithm>
23 #include <atomic>
24 #include <cassert>
25 #include <cstdint>
26 #include <cstdlib>
27 #include <cstring>
28 #include <deque>
29 #include <fstream>
30 #include <initializer_list>
31 #include <iostream>
32 #include <mutex>
33 #include <sstream>
34 #include <string_view>
35 #include <type_traits>
36 #include <utility>
37 #include <vector>
38
39 #include "../bitboard.h"
40 #include "../misc.h"
41 #include "../movegen.h"
42 #include "../position.h"
43 #include "../search.h"
44 #include "../types.h"
45 #include "../uci.h"
46
47 #ifndef _WIN32
48 #include <fcntl.h>
49 #include <sys/mman.h>
50 #include <unistd.h>
51 #else
52 #define WIN32_LEAN_AND_MEAN
53 #ifndef NOMINMAX
54 #  define NOMINMAX // Disable macros min() and max()
55 #endif
56 #include <windows.h>
57 #endif
58
59 using namespace Stockfish::Tablebases;
60
61 int Stockfish::Tablebases::MaxCardinality;
62
63 namespace Stockfish {
64
65 namespace {
66
67 constexpr int TBPIECES = 7; // Max number of supported pieces
68 constexpr int MAX_DTZ = 1 << 18; // Max DTZ supported, large enough to deal with the syzygy TB limit.
69
70 enum { BigEndian, LittleEndian };
71 enum TBType { WDL, DTZ }; // Used as template parameter
72
73 // Each table has a set of flags: all of them refer to DTZ tables, the last one to WDL tables
74 enum TBFlag { STM = 1, Mapped = 2, WinPlies = 4, LossPlies = 8, Wide = 16, SingleValue = 128 };
75
76 inline WDLScore operator-(WDLScore d) { return WDLScore(-int(d)); }
77 inline Square operator^(Square s, int i) { return Square(int(s) ^ i); }
78
79 constexpr std::string_view PieceToChar = " PNBRQK  pnbrqk";
80
81 int MapPawns[SQUARE_NB];
82 int MapB1H1H7[SQUARE_NB];
83 int MapA1D1D4[SQUARE_NB];
84 int MapKK[10][SQUARE_NB]; // [MapA1D1D4][SQUARE_NB]
85
86 int Binomial[6][SQUARE_NB];    // [k][n] k elements from a set of n elements
87 int LeadPawnIdx[6][SQUARE_NB]; // [leadPawnsCnt][SQUARE_NB]
88 int LeadPawnsSize[6][4];       // [leadPawnsCnt][FILE_A..FILE_D]
89
90 // Comparison function to sort leading pawns in ascending MapPawns[] order
91 bool pawns_comp(Square i, Square j) { return MapPawns[i] < MapPawns[j]; }
92 int off_A1H8(Square sq) { return int(rank_of(sq)) - file_of(sq); }
93
94 constexpr Value WDL_to_value[] = {
95    -VALUE_MATE + MAX_PLY + 1,
96     VALUE_DRAW - 2,
97     VALUE_DRAW,
98     VALUE_DRAW + 2,
99     VALUE_MATE - MAX_PLY - 1
100 };
101
102 template<typename T, int Half = sizeof(T) / 2, int End = sizeof(T) - 1>
103 inline void swap_endian(T& x)
104 {
105     static_assert(std::is_unsigned<T>::value, "Argument of swap_endian not unsigned");
106
107     uint8_t tmp, *c = (uint8_t*)&x;
108     for (int i = 0; i < Half; ++i)
109         tmp = c[i], c[i] = c[End - i], c[End - i] = tmp;
110 }
111 template<> inline void swap_endian<uint8_t>(uint8_t&) {}
112
113 template<typename T, int LE> T number(void* addr)
114 {
115     T v;
116
117     if (uintptr_t(addr) & (alignof(T) - 1)) // Unaligned pointer (very rare)
118         std::memcpy(&v, addr, sizeof(T));
119     else
120         v = *((T*)addr);
121
122     if (LE != IsLittleEndian)
123         swap_endian(v);
124     return v;
125 }
126
127 // DTZ tables don't store valid scores for moves that reset the rule50 counter
128 // like captures and pawn moves but we can easily recover the correct dtz of the
129 // previous move if we know the position's WDL score.
130 int dtz_before_zeroing(WDLScore wdl) {
131     return wdl == WDLWin         ?  1   :
132            wdl == WDLCursedWin   ?  101 :
133            wdl == WDLBlessedLoss ? -101 :
134            wdl == WDLLoss        ? -1   : 0;
135 }
136
137 // Return the sign of a number (-1, 0, 1)
138 template <typename T> int sign_of(T val) {
139     return (T(0) < val) - (val < T(0));
140 }
141
142 // Numbers in little endian used by sparseIndex[] to point into blockLength[]
143 struct SparseEntry {
144     char block[4];   // Number of block
145     char offset[2];  // Offset within the block
146 };
147
148 static_assert(sizeof(SparseEntry) == 6, "SparseEntry must be 6 bytes");
149
150 using Sym = uint16_t; // Huffman symbol
151
152 struct LR {
153     enum Side { Left, Right };
154
155     uint8_t lr[3]; // The first 12 bits is the left-hand symbol, the second 12
156                    // bits is the right-hand symbol. If symbol has length 1,
157                    // then the left-hand symbol is the stored value.
158     template<Side S>
159     Sym get() {
160         return S == Left  ? ((lr[1] & 0xF) << 8) | lr[0] :
161                S == Right ?  (lr[2] << 4) | (lr[1] >> 4) : (assert(false), Sym(-1));
162     }
163 };
164
165 static_assert(sizeof(LR) == 3, "LR tree entry must be 3 bytes");
166
167 // Tablebases data layout is structured as following:
168 //
169 //  TBFile:   memory maps/unmaps the physical .rtbw and .rtbz files
170 //  TBTable:  one object for each file with corresponding indexing information
171 //  TBTables: has ownership of TBTable objects, keeping a list and a hash
172
173 // class TBFile memory maps/unmaps the single .rtbw and .rtbz files. Files are
174 // memory mapped for best performance. Files are mapped at first access: at init
175 // time only existence of the file is checked.
176 class TBFile : public std::ifstream {
177
178     std::string fname;
179
180 public:
181     // Look for and open the file among the Paths directories where the .rtbw
182     // and .rtbz files can be found. Multiple directories are separated by ";"
183     // on Windows and by ":" on Unix-based operating systems.
184     //
185     // Example:
186     // C:\tb\wdl345;C:\tb\wdl6;D:\tb\dtz345;D:\tb\dtz6
187     static std::string Paths;
188
189     TBFile(const std::string& f) {
190
191 #ifndef _WIN32
192         constexpr char SepChar = ':';
193 #else
194         constexpr char SepChar = ';';
195 #endif
196         std::stringstream ss(Paths);
197         std::string path;
198
199         while (std::getline(ss, path, SepChar))
200         {
201             fname = path + "/" + f;
202             std::ifstream::open(fname);
203             if (is_open())
204                 return;
205         }
206     }
207
208     // Memory map the file and check it.
209     uint8_t* map(void** baseAddress, uint64_t* mapping, TBType type) {
210         if (is_open())
211             close(); // Need to re-open to get native file descriptor
212
213 #ifndef _WIN32
214         struct stat statbuf;
215         int fd = ::open(fname.c_str(), O_RDONLY);
216
217         if (fd == -1)
218             return *baseAddress = nullptr, nullptr;
219
220         fstat(fd, &statbuf);
221
222         if (statbuf.st_size % 64 != 16)
223         {
224             std::cerr << "Corrupt tablebase file " << fname << std::endl;
225             exit(EXIT_FAILURE);
226         }
227
228         *mapping = statbuf.st_size;
229         *baseAddress = mmap(nullptr, statbuf.st_size, PROT_READ, MAP_SHARED, fd, 0);
230 #if defined(MADV_RANDOM)
231         madvise(*baseAddress, statbuf.st_size, MADV_RANDOM);
232 #endif
233         ::close(fd);
234
235         if (*baseAddress == MAP_FAILED)
236         {
237             std::cerr << "Could not mmap() " << fname << std::endl;
238             exit(EXIT_FAILURE);
239         }
240 #else
241         // Note FILE_FLAG_RANDOM_ACCESS is only a hint to Windows and as such may get ignored.
242         HANDLE fd = CreateFileA(fname.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr,
243                                OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, nullptr);
244
245         if (fd == INVALID_HANDLE_VALUE)
246             return *baseAddress = nullptr, nullptr;
247
248         DWORD size_high;
249         DWORD size_low = GetFileSize(fd, &size_high);
250
251         if (size_low % 64 != 16)
252         {
253             std::cerr << "Corrupt tablebase file " << fname << std::endl;
254             exit(EXIT_FAILURE);
255         }
256
257         HANDLE mmap = CreateFileMapping(fd, nullptr, PAGE_READONLY, size_high, size_low, nullptr);
258         CloseHandle(fd);
259
260         if (!mmap)
261         {
262             std::cerr << "CreateFileMapping() failed" << std::endl;
263             exit(EXIT_FAILURE);
264         }
265
266         *mapping = uint64_t(mmap);
267         *baseAddress = MapViewOfFile(mmap, FILE_MAP_READ, 0, 0, 0);
268
269         if (!*baseAddress)
270         {
271             std::cerr << "MapViewOfFile() failed, name = " << fname
272                       << ", error = " << GetLastError() << std::endl;
273             exit(EXIT_FAILURE);
274         }
275 #endif
276         uint8_t* data = (uint8_t*)*baseAddress;
277
278         constexpr uint8_t Magics[][4] = { { 0xD7, 0x66, 0x0C, 0xA5 },
279                                           { 0x71, 0xE8, 0x23, 0x5D } };
280
281         if (memcmp(data, Magics[type == WDL], 4))
282         {
283             std::cerr << "Corrupted table in file " << fname << std::endl;
284             unmap(*baseAddress, *mapping);
285             return *baseAddress = nullptr, nullptr;
286         }
287
288         return data + 4; // Skip Magics's header
289     }
290
291     static void unmap(void* baseAddress, uint64_t mapping) {
292
293 #ifndef _WIN32
294         munmap(baseAddress, mapping);
295 #else
296         UnmapViewOfFile(baseAddress);
297         CloseHandle((HANDLE)mapping);
298 #endif
299     }
300 };
301
302 std::string TBFile::Paths;
303
304 // struct PairsData contains low level indexing information to access TB data.
305 // There are 8, 4 or 2 PairsData records for each TBTable, according to type of
306 // table and if positions have pawns or not. It is populated at first access.
307 struct PairsData {
308     uint8_t flags;                 // Table flags, see enum TBFlag
309     uint8_t maxSymLen;             // Maximum length in bits of the Huffman symbols
310     uint8_t minSymLen;             // Minimum length in bits of the Huffman symbols
311     uint32_t blocksNum;            // Number of blocks in the TB file
312     size_t sizeofBlock;            // Block size in bytes
313     size_t span;                   // About every span values there is a SparseIndex[] entry
314     Sym* lowestSym;                // lowestSym[l] is the symbol of length l with the lowest value
315     LR* btree;                     // btree[sym] stores the left and right symbols that expand sym
316     uint16_t* blockLength;         // Number of stored positions (minus one) for each block: 1..65536
317     uint32_t blockLengthSize;      // Size of blockLength[] table: padded so it's bigger than blocksNum
318     SparseEntry* sparseIndex;      // Partial indices into blockLength[]
319     size_t sparseIndexSize;        // Size of SparseIndex[] table
320     uint8_t* data;                 // Start of Huffman compressed data
321     std::vector<uint64_t> base64;  // base64[l - min_sym_len] is the 64bit-padded lowest symbol of length l
322     std::vector<uint8_t> symlen;   // Number of values (-1) represented by a given Huffman symbol: 1..256
323     Piece pieces[TBPIECES];        // Position pieces: the order of pieces defines the groups
324     uint64_t groupIdx[TBPIECES+1]; // Start index used for the encoding of the group's pieces
325     int groupLen[TBPIECES+1];      // Number of pieces in a given group: KRKN -> (3, 1)
326     uint16_t map_idx[4];           // WDLWin, WDLLoss, WDLCursedWin, WDLBlessedLoss (used in DTZ)
327 };
328
329 // struct TBTable contains indexing information to access the corresponding TBFile.
330 // There are 2 types of TBTable, corresponding to a WDL or a DTZ file. TBTable
331 // is populated at init time but the nested PairsData records are populated at
332 // first access, when the corresponding file is memory mapped.
333 template<TBType Type>
334 struct TBTable {
335     using Ret = typename std::conditional<Type == WDL, WDLScore, int>::type;
336
337     static constexpr int Sides = Type == WDL ? 2 : 1;
338
339     std::atomic_bool ready;
340     void* baseAddress;
341     uint8_t* map;
342     uint64_t mapping;
343     Key key;
344     Key key2;
345     int pieceCount;
346     bool hasPawns;
347     bool hasUniquePieces;
348     uint8_t pawnCount[2]; // [Lead color / other color]
349     PairsData items[Sides][4]; // [wtm / btm][FILE_A..FILE_D or 0]
350
351     PairsData* get(int stm, int f) {
352         return &items[stm % Sides][hasPawns ? f : 0];
353     }
354
355     TBTable() : ready(false), baseAddress(nullptr) {}
356     explicit TBTable(const std::string& code);
357     explicit TBTable(const TBTable<WDL>& wdl);
358
359     ~TBTable() {
360         if (baseAddress)
361             TBFile::unmap(baseAddress, mapping);
362     }
363 };
364
365 template<>
366 TBTable<WDL>::TBTable(const std::string& code) : TBTable() {
367
368     StateInfo st;
369     Position pos;
370
371     key = pos.set(code, WHITE, &st).material_key();
372     pieceCount = pos.count<ALL_PIECES>();
373     hasPawns = pos.pieces(PAWN);
374
375     hasUniquePieces = false;
376     for (Color c : { WHITE, BLACK })
377         for (PieceType pt = PAWN; pt < KING; ++pt)
378             if (popcount(pos.pieces(c, pt)) == 1)
379                 hasUniquePieces = true;
380
381     // Set the leading color. In case both sides have pawns the leading color
382     // is the side with less pawns because this leads to better compression.
383     bool c =   !pos.count<PAWN>(BLACK)
384             || (   pos.count<PAWN>(WHITE)
385                 && pos.count<PAWN>(BLACK) >= pos.count<PAWN>(WHITE));
386
387     pawnCount[0] = pos.count<PAWN>(c ? WHITE : BLACK);
388     pawnCount[1] = pos.count<PAWN>(c ? BLACK : WHITE);
389
390     key2 = pos.set(code, BLACK, &st).material_key();
391 }
392
393 template<>
394 TBTable<DTZ>::TBTable(const TBTable<WDL>& wdl) : TBTable() {
395
396     // Use the corresponding WDL table to avoid recalculating all from scratch
397     key = wdl.key;
398     key2 = wdl.key2;
399     pieceCount = wdl.pieceCount;
400     hasPawns = wdl.hasPawns;
401     hasUniquePieces = wdl.hasUniquePieces;
402     pawnCount[0] = wdl.pawnCount[0];
403     pawnCount[1] = wdl.pawnCount[1];
404 }
405
406 // class TBTables creates and keeps ownership of the TBTable objects, one for
407 // each TB file found. It supports a fast, hash based, table lookup. Populated
408 // at init time, accessed at probe time.
409 class TBTables {
410
411     struct Entry
412     {
413         Key key;
414         TBTable<WDL>* wdl;
415         TBTable<DTZ>* dtz;
416
417         template <TBType Type>
418         TBTable<Type>* get() const {
419             return (TBTable<Type>*)(Type == WDL ? (void*)wdl : (void*)dtz);
420         }
421     };
422
423     static constexpr int Size = 1 << 12; // 4K table, indexed by key's 12 lsb
424     static constexpr int Overflow = 1;  // Number of elements allowed to map to the last bucket
425
426     Entry hashTable[Size + Overflow];
427
428     std::deque<TBTable<WDL>> wdlTable;
429     std::deque<TBTable<DTZ>> dtzTable;
430
431     void insert(Key key, TBTable<WDL>* wdl, TBTable<DTZ>* dtz) {
432         uint32_t homeBucket = uint32_t(key) & (Size - 1);
433         Entry entry{ key, wdl, dtz };
434
435         // Ensure last element is empty to avoid overflow when looking up
436         for (uint32_t bucket = homeBucket; bucket < Size + Overflow - 1; ++bucket) {
437             Key otherKey = hashTable[bucket].key;
438             if (otherKey == key || !hashTable[bucket].get<WDL>()) {
439                 hashTable[bucket] = entry;
440                 return;
441             }
442
443             // Robin Hood hashing: If we've probed for longer than this element,
444             // insert here and search for a new spot for the other element instead.
445             uint32_t otherHomeBucket = uint32_t(otherKey) & (Size - 1);
446             if (otherHomeBucket > homeBucket) {
447                 std::swap(entry, hashTable[bucket]);
448                 key = otherKey;
449                 homeBucket = otherHomeBucket;
450             }
451         }
452         std::cerr << "TB hash table size too low!" << std::endl;
453         exit(EXIT_FAILURE);
454     }
455
456 public:
457     template<TBType Type>
458     TBTable<Type>* get(Key key) {
459         for (const Entry* entry = &hashTable[uint32_t(key) & (Size - 1)]; ; ++entry) {
460             if (entry->key == key || !entry->get<Type>())
461                 return entry->get<Type>();
462         }
463     }
464
465     void clear() {
466         memset(hashTable, 0, sizeof(hashTable));
467         wdlTable.clear();
468         dtzTable.clear();
469     }
470     size_t size() const { return wdlTable.size(); }
471     void add(const std::vector<PieceType>& pieces);
472 };
473
474 TBTables TBTables;
475
476 // If the corresponding file exists two new objects TBTable<WDL> and TBTable<DTZ>
477 // are created and added to the lists and hash table. Called at init time.
478 void TBTables::add(const std::vector<PieceType>& pieces) {
479
480     std::string code;
481
482     for (PieceType pt : pieces)
483         code += PieceToChar[pt];
484
485     TBFile file(code.insert(code.find('K', 1), "v") + ".rtbw"); // KRK -> KRvK
486
487     if (!file.is_open()) // Only WDL file is checked
488         return;
489
490     file.close();
491
492     MaxCardinality = std::max(int(pieces.size()), MaxCardinality);
493
494     wdlTable.emplace_back(code);
495     dtzTable.emplace_back(wdlTable.back());
496
497     // Insert into the hash keys for both colors: KRvK with KR white and black
498     insert(wdlTable.back().key , &wdlTable.back(), &dtzTable.back());
499     insert(wdlTable.back().key2, &wdlTable.back(), &dtzTable.back());
500 }
501
502 // TB tables are compressed with canonical Huffman code. The compressed data is divided into
503 // blocks of size d->sizeofBlock, and each block stores a variable number of symbols.
504 // Each symbol represents either a WDL or a (remapped) DTZ value, or a pair of other symbols
505 // (recursively). If you keep expanding the symbols in a block, you end up with up to 65536
506 // WDL or DTZ values. Each symbol represents up to 256 values and will correspond after
507 // Huffman coding to at least 1 bit. So a block of 32 bytes corresponds to at most
508 // 32 x 8 x 256 = 65536 values. This maximum is only reached for tables that consist mostly
509 // of draws or mostly of wins, but such tables are actually quite common. In principle, the
510 // blocks in WDL tables are 64 bytes long (and will be aligned on cache lines). But for
511 // mostly-draw or mostly-win tables this can leave many 64-byte blocks only half-filled, so
512 // in such cases blocks are 32 bytes long. The blocks of DTZ tables are up to 1024 bytes long.
513 // The generator picks the size that leads to the smallest table. The "book" of symbols and
514 // Huffman codes is the same for all blocks in the table. A non-symmetric pawnless TB file
515 // will have one table for wtm and one for btm, a TB file with pawns will have tables per
516 // file a,b,c,d also in this case one set for wtm and one for btm.
517 int decompress_pairs(PairsData* d, uint64_t idx) {
518
519     // Special case where all table positions store the same value
520     if (d->flags & TBFlag::SingleValue)
521         return d->minSymLen;
522
523     // First we need to locate the right block that stores the value at index "idx".
524     // Because each block n stores blockLength[n] + 1 values, the index i of the block
525     // that contains the value at position idx is:
526     //
527     //                    for (i = -1, sum = 0; sum <= idx; i++)
528     //                        sum += blockLength[i + 1] + 1;
529     //
530     // This can be slow, so we use SparseIndex[] populated with a set of SparseEntry that
531     // point to known indices into blockLength[]. Namely SparseIndex[k] is a SparseEntry
532     // that stores the blockLength[] index and the offset within that block of the value
533     // with index I(k), where:
534     //
535     //       I(k) = k * d->span + d->span / 2      (1)
536
537     // First step is to get the 'k' of the I(k) nearest to our idx, using definition (1)
538     uint32_t k = uint32_t(idx / d->span);
539
540     // Then we read the corresponding SparseIndex[] entry
541     uint32_t block = number<uint32_t, LittleEndian>(&d->sparseIndex[k].block);
542     int offset     = number<uint16_t, LittleEndian>(&d->sparseIndex[k].offset);
543
544     // Now compute the difference idx - I(k). From definition of k we know that
545     //
546     //       idx = k * d->span + idx % d->span    (2)
547     //
548     // So from (1) and (2) we can compute idx - I(K):
549     int diff = idx % d->span - d->span / 2;
550
551     // Sum the above to offset to find the offset corresponding to our idx
552     offset += diff;
553
554     // Move to previous/next block, until we reach the correct block that contains idx,
555     // that is when 0 <= offset <= d->blockLength[block]
556     while (offset < 0)
557         offset += d->blockLength[--block] + 1;
558
559     while (offset > d->blockLength[block])
560         offset -= d->blockLength[block++] + 1;
561
562     // Finally, we find the start address of our block of canonical Huffman symbols
563     uint32_t* ptr = (uint32_t*)(d->data + (uint64_t(block) * d->sizeofBlock));
564
565     // Read the first 64 bits in our block, this is a (truncated) sequence of
566     // unknown number of symbols of unknown length but we know the first one
567     // is at the beginning of this 64 bits sequence.
568     uint64_t buf64 = number<uint64_t, BigEndian>(ptr); ptr += 2;
569     int buf64Size = 64;
570     Sym sym;
571
572     while (true)
573     {
574         int len = 0; // This is the symbol length - d->min_sym_len
575
576         // Now get the symbol length. For any symbol s64 of length l right-padded
577         // to 64 bits we know that d->base64[l-1] >= s64 >= d->base64[l] so we
578         // can find the symbol length iterating through base64[].
579         while (buf64 < d->base64[len])
580             ++len;
581
582         // All the symbols of a given length are consecutive integers (numerical
583         // sequence property), so we can compute the offset of our symbol of
584         // length len, stored at the beginning of buf64.
585         sym = Sym((buf64 - d->base64[len]) >> (64 - len - d->minSymLen));
586
587         // Now add the value of the lowest symbol of length len to get our symbol
588         sym += number<Sym, LittleEndian>(&d->lowestSym[len]);
589
590         // If our offset is within the number of values represented by symbol sym
591         // we are done...
592         if (offset < d->symlen[sym] + 1)
593             break;
594
595         // ...otherwise update the offset and continue to iterate
596         offset -= d->symlen[sym] + 1;
597         len += d->minSymLen; // Get the real length
598         buf64 <<= len;       // Consume the just processed symbol
599         buf64Size -= len;
600
601         if (buf64Size <= 32) { // Refill the buffer
602             buf64Size += 32;
603             buf64 |= uint64_t(number<uint32_t, BigEndian>(ptr++)) << (64 - buf64Size);
604         }
605     }
606
607     // Ok, now we have our symbol that expands into d->symlen[sym] + 1 symbols.
608     // We binary-search for our value recursively expanding into the left and
609     // right child symbols until we reach a leaf node where symlen[sym] + 1 == 1
610     // that will store the value we need.
611     while (d->symlen[sym])
612     {
613         Sym left = d->btree[sym].get<LR::Left>();
614
615         // If a symbol contains 36 sub-symbols (d->symlen[sym] + 1 = 36) and
616         // expands in a pair (d->symlen[left] = 23, d->symlen[right] = 11), then
617         // we know that, for instance the ten-th value (offset = 10) will be on
618         // the left side because in Recursive Pairing child symbols are adjacent.
619         if (offset < d->symlen[left] + 1)
620             sym = left;
621         else {
622             offset -= d->symlen[left] + 1;
623             sym = d->btree[sym].get<LR::Right>();
624         }
625     }
626
627     return d->btree[sym].get<LR::Left>();
628 }
629
630 bool check_dtz_stm(TBTable<WDL>*, int, File) { return true; }
631
632 bool check_dtz_stm(TBTable<DTZ>* entry, int stm, File f) {
633
634     auto flags = entry->get(stm, f)->flags;
635     return   (flags & TBFlag::STM) == stm
636           || ((entry->key == entry->key2) && !entry->hasPawns);
637 }
638
639 // DTZ scores are sorted by frequency of occurrence and then assigned the
640 // values 0, 1, 2, ... in order of decreasing frequency. This is done for each
641 // of the four WDLScore values. The mapping information necessary to reconstruct
642 // the original values is stored in the TB file and read during map[] init.
643 WDLScore map_score(TBTable<WDL>*, File, int value, WDLScore) { return WDLScore(value - 2); }
644
645 int map_score(TBTable<DTZ>* entry, File f, int value, WDLScore wdl) {
646
647     constexpr int WDLMap[] = { 1, 3, 0, 2, 0 };
648
649     auto flags = entry->get(0, f)->flags;
650
651     uint8_t* map = entry->map;
652     uint16_t* idx = entry->get(0, f)->map_idx;
653     if (flags & TBFlag::Mapped) {
654         if (flags & TBFlag::Wide)
655             value = ((uint16_t *)map)[idx[WDLMap[wdl + 2]] + value];
656         else
657             value = map[idx[WDLMap[wdl + 2]] + value];
658     }
659
660     // DTZ tables store distance to zero in number of moves or plies. We
661     // want to return plies, so we have convert to plies when needed.
662     if (   (wdl == WDLWin  && !(flags & TBFlag::WinPlies))
663         || (wdl == WDLLoss && !(flags & TBFlag::LossPlies))
664         ||  wdl == WDLCursedWin
665         ||  wdl == WDLBlessedLoss)
666         value *= 2;
667
668     return value + 1;
669 }
670
671 // Compute a unique index out of a position and use it to probe the TB file. To
672 // encode k pieces of same type and color, first sort the pieces by square in
673 // ascending order s1 <= s2 <= ... <= sk then compute the unique index as:
674 //
675 //      idx = Binomial[1][s1] + Binomial[2][s2] + ... + Binomial[k][sk]
676 //
677 template<typename T, typename Ret = typename T::Ret>
678 Ret do_probe_table(const Position& pos, T* entry, WDLScore wdl, ProbeState* result) {
679
680     Square squares[TBPIECES];
681     Piece pieces[TBPIECES];
682     uint64_t idx;
683     int next = 0, size = 0, leadPawnsCnt = 0;
684     PairsData* d;
685     Bitboard b, leadPawns = 0;
686     File tbFile = FILE_A;
687
688     // A given TB entry like KRK has associated two material keys: KRvk and Kvkr.
689     // If both sides have the same pieces keys are equal. In this case TB tables
690     // only store the 'white to move' case, so if the position to lookup has black
691     // to move, we need to switch the color and flip the squares before to lookup.
692     bool symmetricBlackToMove = (entry->key == entry->key2 && pos.side_to_move());
693
694     // TB files are calculated for white as stronger side. For instance we have
695     // KRvK, not KvKR. A position where stronger side is white will have its
696     // material key == entry->key, otherwise we have to switch the color and
697     // flip the squares before to lookup.
698     bool blackStronger = (pos.material_key() != entry->key);
699
700     int flipColor   = (symmetricBlackToMove || blackStronger) * 8;
701     int flipSquares = (symmetricBlackToMove || blackStronger) * 56;
702     int stm         = (symmetricBlackToMove || blackStronger) ^ pos.side_to_move();
703
704     // For pawns, TB files store 4 separate tables according if leading pawn is on
705     // file a, b, c or d after reordering. The leading pawn is the one with maximum
706     // MapPawns[] value, that is the one most toward the edges and with lowest rank.
707     if (entry->hasPawns) {
708
709         // In all the 4 tables, pawns are at the beginning of the piece sequence and
710         // their color is the reference one. So we just pick the first one.
711         Piece pc = Piece(entry->get(0, 0)->pieces[0] ^ flipColor);
712
713         assert(type_of(pc) == PAWN);
714
715         leadPawns = b = pos.pieces(color_of(pc), PAWN);
716         do
717             squares[size++] = pop_lsb(b) ^ flipSquares;
718         while (b);
719
720         leadPawnsCnt = size;
721
722         std::swap(squares[0], *std::max_element(squares, squares + leadPawnsCnt, pawns_comp));
723
724         tbFile = File(edge_distance(file_of(squares[0])));
725     }
726
727     // DTZ tables are one-sided, i.e. they store positions only for white to
728     // move or only for black to move, so check for side to move to be stm,
729     // early exit otherwise.
730     if (!check_dtz_stm(entry, stm, tbFile))
731         return *result = CHANGE_STM, Ret();
732
733     // Now we are ready to get all the position pieces (but the lead pawns) and
734     // directly map them to the correct color and square.
735     b = pos.pieces() ^ leadPawns;
736     do {
737         Square s = pop_lsb(b);
738         squares[size] = s ^ flipSquares;
739         pieces[size++] = Piece(pos.piece_on(s) ^ flipColor);
740     } while (b);
741
742     assert(size >= 2);
743
744     d = entry->get(stm, tbFile);
745
746     // Then we reorder the pieces to have the same sequence as the one stored
747     // in pieces[i]: the sequence that ensures the best compression.
748     for (int i = leadPawnsCnt; i < size - 1; ++i)
749         for (int j = i + 1; j < size; ++j)
750             if (d->pieces[i] == pieces[j])
751             {
752                 std::swap(pieces[i], pieces[j]);
753                 std::swap(squares[i], squares[j]);
754                 break;
755             }
756
757     // Now we map again the squares so that the square of the lead piece is in
758     // the triangle A1-D1-D4.
759     if (file_of(squares[0]) > FILE_D)
760         for (int i = 0; i < size; ++i)
761             squares[i] = flip_file(squares[i]);
762
763     // Encode leading pawns starting with the one with minimum MapPawns[] and
764     // proceeding in ascending order.
765     if (entry->hasPawns) {
766         idx = LeadPawnIdx[leadPawnsCnt][squares[0]];
767
768         std::stable_sort(squares + 1, squares + leadPawnsCnt, pawns_comp);
769
770         for (int i = 1; i < leadPawnsCnt; ++i)
771             idx += Binomial[i][MapPawns[squares[i]]];
772
773         goto encode_remaining; // With pawns we have finished special treatments
774     }
775
776     // In positions without pawns, we further flip the squares to ensure leading
777     // piece is below RANK_5.
778     if (rank_of(squares[0]) > RANK_4)
779         for (int i = 0; i < size; ++i)
780             squares[i] = flip_rank(squares[i]);
781
782     // Look for the first piece of the leading group not on the A1-D4 diagonal
783     // and ensure it is mapped below the diagonal.
784     for (int i = 0; i < d->groupLen[0]; ++i) {
785         if (!off_A1H8(squares[i]))
786             continue;
787
788         if (off_A1H8(squares[i]) > 0) // A1-H8 diagonal flip: SQ_A3 -> SQ_C1
789             for (int j = i; j < size; ++j)
790                 squares[j] = Square(((squares[j] >> 3) | (squares[j] << 3)) & 63);
791         break;
792     }
793
794     // Encode the leading group.
795     //
796     // Suppose we have KRvK. Let's say the pieces are on square numbers wK, wR
797     // and bK (each 0...63). The simplest way to map this position to an index
798     // is like this:
799     //
800     //   index = wK * 64 * 64 + wR * 64 + bK;
801     //
802     // But this way the TB is going to have 64*64*64 = 262144 positions, with
803     // lots of positions being equivalent (because they are mirrors of each
804     // other) and lots of positions being invalid (two pieces on one square,
805     // adjacent kings, etc.).
806     // Usually the first step is to take the wK and bK together. There are just
807     // 462 ways legal and not-mirrored ways to place the wK and bK on the board.
808     // Once we have placed the wK and bK, there are 62 squares left for the wR
809     // Mapping its square from 0..63 to available squares 0..61 can be done like:
810     //
811     //   wR -= (wR > wK) + (wR > bK);
812     //
813     // In words: if wR "comes later" than wK, we deduct 1, and the same if wR
814     // "comes later" than bK. In case of two same pieces like KRRvK we want to
815     // place the two Rs "together". If we have 62 squares left, we can place two
816     // Rs "together" in 62 * 61 / 2 ways (we divide by 2 because rooks can be
817     // swapped and still get the same position.)
818     //
819     // In case we have at least 3 unique pieces (included kings) we encode them
820     // together.
821     if (entry->hasUniquePieces) {
822
823         int adjust1 =  squares[1] > squares[0];
824         int adjust2 = (squares[2] > squares[0]) + (squares[2] > squares[1]);
825
826         // First piece is below a1-h8 diagonal. MapA1D1D4[] maps the b1-d1-d3
827         // triangle to 0...5. There are 63 squares for second piece and and 62
828         // (mapped to 0...61) for the third.
829         if (off_A1H8(squares[0]))
830             idx = (   MapA1D1D4[squares[0]]  * 63
831                    + (squares[1] - adjust1)) * 62
832                    +  squares[2] - adjust2;
833
834         // First piece is on a1-h8 diagonal, second below: map this occurrence to
835         // 6 to differentiate from the above case, rank_of() maps a1-d4 diagonal
836         // to 0...3 and finally MapB1H1H7[] maps the b1-h1-h7 triangle to 0..27.
837         else if (off_A1H8(squares[1]))
838             idx = (  6 * 63 + rank_of(squares[0]) * 28
839                    + MapB1H1H7[squares[1]])       * 62
840                    + squares[2] - adjust2;
841
842         // First two pieces are on a1-h8 diagonal, third below
843         else if (off_A1H8(squares[2]))
844             idx =  6 * 63 * 62 + 4 * 28 * 62
845                  +  rank_of(squares[0])        * 7 * 28
846                  + (rank_of(squares[1]) - adjust1) * 28
847                  +  MapB1H1H7[squares[2]];
848
849         // All 3 pieces on the diagonal a1-h8
850         else
851             idx = 6 * 63 * 62 + 4 * 28 * 62 + 4 * 7 * 28
852                  +  rank_of(squares[0])         * 7 * 6
853                  + (rank_of(squares[1]) - adjust1)  * 6
854                  + (rank_of(squares[2]) - adjust2);
855     } else
856         // We don't have at least 3 unique pieces, like in KRRvKBB, just map
857         // the kings.
858         idx = MapKK[MapA1D1D4[squares[0]]][squares[1]];
859
860 encode_remaining:
861     idx *= d->groupIdx[0];
862     Square* groupSq = squares + d->groupLen[0];
863
864     // Encode remaining pawns then pieces according to square, in ascending order
865     bool remainingPawns = entry->hasPawns && entry->pawnCount[1];
866
867     while (d->groupLen[++next])
868     {
869         std::stable_sort(groupSq, groupSq + d->groupLen[next]);
870         uint64_t n = 0;
871
872         // Map down a square if "comes later" than a square in the previous
873         // groups (similar to what done earlier for leading group pieces).
874         for (int i = 0; i < d->groupLen[next]; ++i)
875         {
876             auto f = [&](Square s) { return groupSq[i] > s; };
877             auto adjust = std::count_if(squares, groupSq, f);
878             n += Binomial[i + 1][groupSq[i] - adjust - 8 * remainingPawns];
879         }
880
881         remainingPawns = false;
882         idx += n * d->groupIdx[next];
883         groupSq += d->groupLen[next];
884     }
885
886     // Now that we have the index, decompress the pair and get the score
887     return map_score(entry, tbFile, decompress_pairs(d, idx), wdl);
888 }
889
890 // Group together pieces that will be encoded together. The general rule is that
891 // a group contains pieces of same type and color. The exception is the leading
892 // group that, in case of positions without pawns, can be formed by 3 different
893 // pieces (default) or by the king pair when there is not a unique piece apart
894 // from the kings. When there are pawns, pawns are always first in pieces[].
895 //
896 // As example KRKN -> KRK + N, KNNK -> KK + NN, KPPKP -> P + PP + K + K
897 //
898 // The actual grouping depends on the TB generator and can be inferred from the
899 // sequence of pieces in piece[] array.
900 template<typename T>
901 void set_groups(T& e, PairsData* d, int order[], File f) {
902
903     int n = 0, firstLen = e.hasPawns ? 0 : e.hasUniquePieces ? 3 : 2;
904     d->groupLen[n] = 1;
905
906     // Number of pieces per group is stored in groupLen[], for instance in KRKN
907     // the encoder will default on '111', so groupLen[] will be (3, 1).
908     for (int i = 1; i < e.pieceCount; ++i)
909         if (--firstLen > 0 || d->pieces[i] == d->pieces[i - 1])
910             d->groupLen[n]++;
911         else
912             d->groupLen[++n] = 1;
913
914     d->groupLen[++n] = 0; // Zero-terminated
915
916     // The sequence in pieces[] defines the groups, but not the order in which
917     // they are encoded. If the pieces in a group g can be combined on the board
918     // in N(g) different ways, then the position encoding will be of the form:
919     //
920     //           g1 * N(g2) * N(g3) + g2 * N(g3) + g3
921     //
922     // This ensures unique encoding for the whole position. The order of the
923     // groups is a per-table parameter and could not follow the canonical leading
924     // pawns/pieces -> remaining pawns -> remaining pieces. In particular the
925     // first group is at order[0] position and the remaining pawns, when present,
926     // are at order[1] position.
927     bool pp = e.hasPawns && e.pawnCount[1]; // Pawns on both sides
928     int next = pp ? 2 : 1;
929     int freeSquares = 64 - d->groupLen[0] - (pp ? d->groupLen[1] : 0);
930     uint64_t idx = 1;
931
932     for (int k = 0; next < n || k == order[0] || k == order[1]; ++k)
933         if (k == order[0]) // Leading pawns or pieces
934         {
935             d->groupIdx[0] = idx;
936             idx *=         e.hasPawns ? LeadPawnsSize[d->groupLen[0]][f]
937                   : e.hasUniquePieces ? 31332 : 462;
938         }
939         else if (k == order[1]) // Remaining pawns
940         {
941             d->groupIdx[1] = idx;
942             idx *= Binomial[d->groupLen[1]][48 - d->groupLen[0]];
943         }
944         else // Remaining pieces
945         {
946             d->groupIdx[next] = idx;
947             idx *= Binomial[d->groupLen[next]][freeSquares];
948             freeSquares -= d->groupLen[next++];
949         }
950
951     d->groupIdx[n] = idx;
952 }
953
954 // In Recursive Pairing each symbol represents a pair of children symbols. So
955 // read d->btree[] symbols data and expand each one in his left and right child
956 // symbol until reaching the leafs that represent the symbol value.
957 uint8_t set_symlen(PairsData* d, Sym s, std::vector<bool>& visited) {
958
959     visited[s] = true; // We can set it now because tree is acyclic
960     Sym sr = d->btree[s].get<LR::Right>();
961
962     if (sr == 0xFFF)
963         return 0;
964
965     Sym sl = d->btree[s].get<LR::Left>();
966
967     if (!visited[sl])
968         d->symlen[sl] = set_symlen(d, sl, visited);
969
970     if (!visited[sr])
971         d->symlen[sr] = set_symlen(d, sr, visited);
972
973     return d->symlen[sl] + d->symlen[sr] + 1;
974 }
975
976 uint8_t* set_sizes(PairsData* d, uint8_t* data) {
977
978     d->flags = *data++;
979
980     if (d->flags & TBFlag::SingleValue) {
981         d->blocksNum = d->blockLengthSize = 0;
982         d->span = d->sparseIndexSize = 0; // Broken MSVC zero-init
983         d->minSymLen = *data++; // Here we store the single value
984         return data;
985     }
986
987     // groupLen[] is a zero-terminated list of group lengths, the last groupIdx[]
988     // element stores the biggest index that is the tb size.
989     uint64_t tbSize = d->groupIdx[std::find(d->groupLen, d->groupLen + 7, 0) - d->groupLen];
990
991     d->sizeofBlock = 1ULL << *data++;
992     d->span = 1ULL << *data++;
993     d->sparseIndexSize = size_t((tbSize + d->span - 1) / d->span); // Round up
994     auto padding = number<uint8_t, LittleEndian>(data++);
995     d->blocksNum = number<uint32_t, LittleEndian>(data); data += sizeof(uint32_t);
996     d->blockLengthSize = d->blocksNum + padding; // Padded to ensure SparseIndex[]
997                                                  // does not point out of range.
998     d->maxSymLen = *data++;
999     d->minSymLen = *data++;
1000     d->lowestSym = (Sym*)data;
1001     d->base64.resize(d->maxSymLen - d->minSymLen + 1);
1002
1003     // See https://en.wikipedia.org/wiki/Huffman_coding
1004     // The canonical code is ordered such that longer symbols (in terms of
1005     // the number of bits of their Huffman code) have lower numeric value,
1006     // so that d->lowestSym[i] >= d->lowestSym[i+1] (when read as LittleEndian).
1007     // Starting from this we compute a base64[] table indexed by symbol length
1008     // and containing 64 bit values so that d->base64[i] >= d->base64[i+1].
1009
1010     // Implementation note: we first cast the unsigned size_t "base64.size()"
1011     // to a signed int "base64_size" variable and then we are able to subtract 2,
1012     // avoiding unsigned overflow warnings.
1013
1014     int base64_size = static_cast<int>(d->base64.size());
1015     for (int i = base64_size - 2; i >= 0; --i) {
1016         d->base64[i] = (d->base64[i + 1] + number<Sym, LittleEndian>(&d->lowestSym[i])
1017                                          - number<Sym, LittleEndian>(&d->lowestSym[i + 1])) / 2;
1018
1019         assert(d->base64[i] * 2 >= d->base64[i+1]);
1020     }
1021
1022     // Now left-shift by an amount so that d->base64[i] gets shifted 1 bit more
1023     // than d->base64[i+1] and given the above assert condition, we ensure that
1024     // d->base64[i] >= d->base64[i+1]. Moreover for any symbol s64 of length i
1025     // and right-padded to 64 bits holds d->base64[i-1] >= s64 >= d->base64[i].
1026     for (int i = 0; i < base64_size; ++i)
1027         d->base64[i] <<= 64 - i - d->minSymLen; // Right-padding to 64 bits
1028
1029     data += base64_size * sizeof(Sym);
1030     d->symlen.resize(number<uint16_t, LittleEndian>(data)); data += sizeof(uint16_t);
1031     d->btree = (LR*)data;
1032
1033     // The compression scheme used is "Recursive Pairing", that replaces the most
1034     // frequent adjacent pair of symbols in the source message by a new symbol,
1035     // reevaluating the frequencies of all of the symbol pairs with respect to
1036     // the extended alphabet, and then repeating the process.
1037     // See https://web.archive.org/web/20201106232444/http://www.larsson.dogma.net/dcc99.pdf
1038     std::vector<bool> visited(d->symlen.size());
1039
1040     for (Sym sym = 0; sym < d->symlen.size(); ++sym)
1041         if (!visited[sym])
1042             d->symlen[sym] = set_symlen(d, sym, visited);
1043
1044     return data + d->symlen.size() * sizeof(LR) + (d->symlen.size() & 1);
1045 }
1046
1047 uint8_t* set_dtz_map(TBTable<WDL>&, uint8_t* data, File) { return data; }
1048
1049 uint8_t* set_dtz_map(TBTable<DTZ>& e, uint8_t* data, File maxFile) {
1050
1051     e.map = data;
1052
1053     for (File f = FILE_A; f <= maxFile; ++f) {
1054         auto flags = e.get(0, f)->flags;
1055         if (flags & TBFlag::Mapped) {
1056             if (flags & TBFlag::Wide) {
1057                 data += uintptr_t(data) & 1;  // Word alignment, we may have a mixed table
1058                 for (int i = 0; i < 4; ++i) { // Sequence like 3,x,x,x,1,x,0,2,x,x
1059                     e.get(0, f)->map_idx[i] = uint16_t((uint16_t*)data - (uint16_t*)e.map + 1);
1060                     data += 2 * number<uint16_t, LittleEndian>(data) + 2;
1061                 }
1062             }
1063             else {
1064                 for (int i = 0; i < 4; ++i) {
1065                     e.get(0, f)->map_idx[i] = uint16_t(data - e.map + 1);
1066                     data += *data + 1;
1067                 }
1068             }
1069         }
1070     }
1071
1072     return data += uintptr_t(data) & 1; // Word alignment
1073 }
1074
1075 // Populate entry's PairsData records with data from the just memory mapped file.
1076 // Called at first access.
1077 template<typename T>
1078 void set(T& e, uint8_t* data) {
1079
1080     PairsData* d;
1081
1082     enum { Split = 1, HasPawns = 2 };
1083
1084     assert(e.hasPawns        == bool(*data & HasPawns));
1085     assert((e.key != e.key2) == bool(*data & Split));
1086
1087     data++; // First byte stores flags
1088
1089     const int sides = T::Sides == 2 && (e.key != e.key2) ? 2 : 1;
1090     const File maxFile = e.hasPawns ? FILE_D : FILE_A;
1091
1092     bool pp = e.hasPawns && e.pawnCount[1]; // Pawns on both sides
1093
1094     assert(!pp || e.pawnCount[0]);
1095
1096     for (File f = FILE_A; f <= maxFile; ++f) {
1097
1098         for (int i = 0; i < sides; i++)
1099             *e.get(i, f) = PairsData();
1100
1101         int order[][2] = { { *data & 0xF, pp ? *(data + 1) & 0xF : 0xF },
1102                            { *data >>  4, pp ? *(data + 1) >>  4 : 0xF } };
1103         data += 1 + pp;
1104
1105         for (int k = 0; k < e.pieceCount; ++k, ++data)
1106             for (int i = 0; i < sides; i++)
1107                 e.get(i, f)->pieces[k] = Piece(i ? *data >>  4 : *data & 0xF);
1108
1109         for (int i = 0; i < sides; ++i)
1110             set_groups(e, e.get(i, f), order[i], f);
1111     }
1112
1113     data += uintptr_t(data) & 1; // Word alignment
1114
1115     for (File f = FILE_A; f <= maxFile; ++f)
1116         for (int i = 0; i < sides; i++)
1117             data = set_sizes(e.get(i, f), data);
1118
1119     data = set_dtz_map(e, data, maxFile);
1120
1121     for (File f = FILE_A; f <= maxFile; ++f)
1122         for (int i = 0; i < sides; i++) {
1123             (d = e.get(i, f))->sparseIndex = (SparseEntry*)data;
1124             data += d->sparseIndexSize * sizeof(SparseEntry);
1125         }
1126
1127     for (File f = FILE_A; f <= maxFile; ++f)
1128         for (int i = 0; i < sides; i++) {
1129             (d = e.get(i, f))->blockLength = (uint16_t*)data;
1130             data += d->blockLengthSize * sizeof(uint16_t);
1131         }
1132
1133     for (File f = FILE_A; f <= maxFile; ++f)
1134         for (int i = 0; i < sides; i++) {
1135             data = (uint8_t*)((uintptr_t(data) + 0x3F) & ~0x3F); // 64 byte alignment
1136             (d = e.get(i, f))->data = data;
1137             data += d->blocksNum * d->sizeofBlock;
1138         }
1139 }
1140
1141 // If the TB file corresponding to the given position is already memory mapped
1142 // then return its base address, otherwise try to memory map and init it. Called
1143 // at every probe, memory map and init only at first access. Function is thread
1144 // safe and can be called concurrently.
1145 template<TBType Type>
1146 void* mapped(TBTable<Type>& e, const Position& pos) {
1147
1148     static std::mutex mutex;
1149
1150     // Use 'acquire' to avoid a thread reading 'ready' == true while
1151     // another is still working. (compiler reordering may cause this).
1152     if (e.ready.load(std::memory_order_acquire))
1153         return e.baseAddress; // Could be nullptr if file does not exist
1154
1155     std::scoped_lock<std::mutex> lk(mutex);
1156
1157     if (e.ready.load(std::memory_order_relaxed)) // Recheck under lock
1158         return e.baseAddress;
1159
1160     // Pieces strings in decreasing order for each color, like ("KPP","KR")
1161     std::string fname, w, b;
1162     for (PieceType pt = KING; pt >= PAWN; --pt) {
1163         w += std::string(popcount(pos.pieces(WHITE, pt)), PieceToChar[pt]);
1164         b += std::string(popcount(pos.pieces(BLACK, pt)), PieceToChar[pt]);
1165     }
1166
1167     fname =  (e.key == pos.material_key() ? w + 'v' + b : b + 'v' + w)
1168            + (Type == WDL ? ".rtbw" : ".rtbz");
1169
1170     uint8_t* data = TBFile(fname).map(&e.baseAddress, &e.mapping, Type);
1171
1172     if (data)
1173         set(e, data);
1174
1175     e.ready.store(true, std::memory_order_release);
1176     return e.baseAddress;
1177 }
1178
1179 template<TBType Type, typename Ret = typename TBTable<Type>::Ret>
1180 Ret probe_table(const Position& pos, ProbeState* result, WDLScore wdl = WDLDraw) {
1181
1182     if (pos.count<ALL_PIECES>() == 2) // KvK
1183         return Ret(WDLDraw);
1184
1185     TBTable<Type>* entry = TBTables.get<Type>(pos.material_key());
1186
1187     if (!entry || !mapped(*entry, pos))
1188         return *result = FAIL, Ret();
1189
1190     return do_probe_table(pos, entry, wdl, result);
1191 }
1192
1193 // For a position where the side to move has a winning capture it is not necessary
1194 // to store a winning value so the generator treats such positions as "don't cares"
1195 // and tries to assign to it a value that improves the compression ratio. Similarly,
1196 // if the side to move has a drawing capture, then the position is at least drawn.
1197 // If the position is won, then the TB needs to store a win value. But if the
1198 // position is drawn, the TB may store a loss value if that is better for compression.
1199 // All of this means that during probing, the engine must look at captures and probe
1200 // their results and must probe the position itself. The "best" result of these
1201 // probes is the correct result for the position.
1202 // DTZ tables do not store values when a following move is a zeroing winning move
1203 // (winning capture or winning pawn move). Also DTZ store wrong values for positions
1204 // where the best move is an ep-move (even if losing). So in all these cases set
1205 // the state to ZEROING_BEST_MOVE.
1206 template<bool CheckZeroingMoves>
1207 WDLScore search(Position& pos, ProbeState* result) {
1208
1209     WDLScore value, bestValue = WDLLoss;
1210     StateInfo st;
1211
1212     auto moveList = MoveList<LEGAL>(pos);
1213     size_t totalCount = moveList.size(), moveCount = 0;
1214
1215     for (const Move move : moveList)
1216     {
1217         if (   !pos.capture(move)
1218             && (!CheckZeroingMoves || type_of(pos.moved_piece(move)) != PAWN))
1219             continue;
1220
1221         moveCount++;
1222
1223         pos.do_move(move, st);
1224         value = -search<false>(pos, result);
1225         pos.undo_move(move);
1226
1227         if (*result == FAIL)
1228             return WDLDraw;
1229
1230         if (value > bestValue)
1231         {
1232             bestValue = value;
1233
1234             if (value >= WDLWin)
1235             {
1236                 *result = ZEROING_BEST_MOVE; // Winning DTZ-zeroing move
1237                 return value;
1238             }
1239         }
1240     }
1241
1242     // In case we have already searched all the legal moves we don't have to probe
1243     // the TB because the stored score could be wrong. For instance TB tables
1244     // do not contain information on position with ep rights, so in this case
1245     // the result of probe_wdl_table is wrong. Also in case of only capture
1246     // moves, for instance here 4K3/4q3/6p1/2k5/6p1/8/8/8 w - - 0 7, we have to
1247     // return with ZEROING_BEST_MOVE set.
1248     bool noMoreMoves = (moveCount && moveCount == totalCount);
1249
1250     if (noMoreMoves)
1251         value = bestValue;
1252     else
1253     {
1254         value = probe_table<WDL>(pos, result);
1255
1256         if (*result == FAIL)
1257             return WDLDraw;
1258     }
1259
1260     // DTZ stores a "don't care" value if bestValue is a win
1261     if (bestValue >= value)
1262         return *result = (   bestValue > WDLDraw
1263                           || noMoreMoves ? ZEROING_BEST_MOVE : OK), bestValue;
1264
1265     return *result = OK, value;
1266 }
1267
1268 } // namespace
1269
1270
1271 /// Tablebases::init() is called at startup and after every change to
1272 /// "SyzygyPath" UCI option to (re)create the various tables. It is not thread
1273 /// safe, nor it needs to be.
1274 void Tablebases::init(const std::string& paths) {
1275
1276     TBTables.clear();
1277     MaxCardinality = 0;
1278     TBFile::Paths = paths;
1279
1280     if (paths.empty() || paths == "<empty>")
1281         return;
1282
1283     // MapB1H1H7[] encodes a square below a1-h8 diagonal to 0..27
1284     int code = 0;
1285     for (Square s = SQ_A1; s <= SQ_H8; ++s)
1286         if (off_A1H8(s) < 0)
1287             MapB1H1H7[s] = code++;
1288
1289     // MapA1D1D4[] encodes a square in the a1-d1-d4 triangle to 0..9
1290     std::vector<Square> diagonal;
1291     code = 0;
1292     for (Square s = SQ_A1; s <= SQ_D4; ++s)
1293         if (off_A1H8(s) < 0 && file_of(s) <= FILE_D)
1294             MapA1D1D4[s] = code++;
1295
1296         else if (!off_A1H8(s) && file_of(s) <= FILE_D)
1297             diagonal.push_back(s);
1298
1299     // Diagonal squares are encoded as last ones
1300     for (auto s : diagonal)
1301         MapA1D1D4[s] = code++;
1302
1303     // MapKK[] encodes all the 462 possible legal positions of two kings where
1304     // the first is in the a1-d1-d4 triangle. If the first king is on the a1-d4
1305     // diagonal, the other one shall not to be above the a1-h8 diagonal.
1306     std::vector<std::pair<int, Square>> bothOnDiagonal;
1307     code = 0;
1308     for (int idx = 0; idx < 10; idx++)
1309         for (Square s1 = SQ_A1; s1 <= SQ_D4; ++s1)
1310             if (MapA1D1D4[s1] == idx && (idx || s1 == SQ_B1)) // SQ_B1 is mapped to 0
1311             {
1312                 for (Square s2 = SQ_A1; s2 <= SQ_H8; ++s2)
1313                     if ((PseudoAttacks[KING][s1] | s1) & s2)
1314                         continue; // Illegal position
1315
1316                     else if (!off_A1H8(s1) && off_A1H8(s2) > 0)
1317                         continue; // First on diagonal, second above
1318
1319                     else if (!off_A1H8(s1) && !off_A1H8(s2))
1320                         bothOnDiagonal.emplace_back(idx, s2);
1321
1322                     else
1323                         MapKK[idx][s2] = code++;
1324             }
1325
1326     // Legal positions with both kings on diagonal are encoded as last ones
1327     for (auto p : bothOnDiagonal)
1328         MapKK[p.first][p.second] = code++;
1329
1330     // Binomial[] stores the Binomial Coefficients using Pascal rule. There
1331     // are Binomial[k][n] ways to choose k elements from a set of n elements.
1332     Binomial[0][0] = 1;
1333
1334     for (int n = 1; n < 64; n++) // Squares
1335         for (int k = 0; k < 6 && k <= n; ++k) // Pieces
1336             Binomial[k][n] =  (k > 0 ? Binomial[k - 1][n - 1] : 0)
1337                             + (k < n ? Binomial[k    ][n - 1] : 0);
1338
1339     // MapPawns[s] encodes squares a2-h7 to 0..47. This is the number of possible
1340     // available squares when the leading one is in 's'. Moreover the pawn with
1341     // highest MapPawns[] is the leading pawn, the one nearest the edge and,
1342     // among pawns with same file, the one with lowest rank.
1343     int availableSquares = 47; // Available squares when lead pawn is in a2
1344
1345     // Init the tables for the encoding of leading pawns group: with 7-men TB we
1346     // can have up to 5 leading pawns (KPPPPPK).
1347     for (int leadPawnsCnt = 1; leadPawnsCnt <= 5; ++leadPawnsCnt)
1348         for (File f = FILE_A; f <= FILE_D; ++f)
1349         {
1350             // Restart the index at every file because TB table is split
1351             // by file, so we can reuse the same index for different files.
1352             int idx = 0;
1353
1354             // Sum all possible combinations for a given file, starting with
1355             // the leading pawn on rank 2 and increasing the rank.
1356             for (Rank r = RANK_2; r <= RANK_7; ++r)
1357             {
1358                 Square sq = make_square(f, r);
1359
1360                 // Compute MapPawns[] at first pass.
1361                 // If sq is the leading pawn square, any other pawn cannot be
1362                 // below or more toward the edge of sq. There are 47 available
1363                 // squares when sq = a2 and reduced by 2 for any rank increase
1364                 // due to mirroring: sq == a3 -> no a2, h2, so MapPawns[a3] = 45
1365                 if (leadPawnsCnt == 1)
1366                 {
1367                     MapPawns[sq] = availableSquares--;
1368                     MapPawns[flip_file(sq)] = availableSquares--;
1369                 }
1370                 LeadPawnIdx[leadPawnsCnt][sq] = idx;
1371                 idx += Binomial[leadPawnsCnt - 1][MapPawns[sq]];
1372             }
1373             // After a file is traversed, store the cumulated per-file index
1374             LeadPawnsSize[leadPawnsCnt][f] = idx;
1375         }
1376
1377     // Add entries in TB tables if the corresponding ".rtbw" file exists
1378     for (PieceType p1 = PAWN; p1 < KING; ++p1) {
1379         TBTables.add({KING, p1, KING});
1380
1381         for (PieceType p2 = PAWN; p2 <= p1; ++p2) {
1382             TBTables.add({KING, p1, p2, KING});
1383             TBTables.add({KING, p1, KING, p2});
1384
1385             for (PieceType p3 = PAWN; p3 < KING; ++p3)
1386                 TBTables.add({KING, p1, p2, KING, p3});
1387
1388             for (PieceType p3 = PAWN; p3 <= p2; ++p3) {
1389                 TBTables.add({KING, p1, p2, p3, KING});
1390
1391                 for (PieceType p4 = PAWN; p4 <= p3; ++p4) {
1392                     TBTables.add({KING, p1, p2, p3, p4, KING});
1393
1394                     for (PieceType p5 = PAWN; p5 <= p4; ++p5)
1395                         TBTables.add({KING, p1, p2, p3, p4, p5, KING});
1396
1397                     for (PieceType p5 = PAWN; p5 < KING; ++p5)
1398                         TBTables.add({KING, p1, p2, p3, p4, KING, p5});
1399                 }
1400
1401                 for (PieceType p4 = PAWN; p4 < KING; ++p4) {
1402                     TBTables.add({KING, p1, p2, p3, KING, p4});
1403
1404                     for (PieceType p5 = PAWN; p5 <= p4; ++p5)
1405                         TBTables.add({KING, p1, p2, p3, KING, p4, p5});
1406                 }
1407             }
1408
1409             for (PieceType p3 = PAWN; p3 <= p1; ++p3)
1410                 for (PieceType p4 = PAWN; p4 <= (p1 == p3 ? p2 : p3); ++p4)
1411                     TBTables.add({KING, p1, p2, KING, p3, p4});
1412         }
1413     }
1414
1415     sync_cout << "info string Found " << TBTables.size() << " tablebases" << sync_endl;
1416 }
1417
1418 // Probe the WDL table for a particular position.
1419 // If *result != FAIL, the probe was successful.
1420 // The return value is from the point of view of the side to move:
1421 // -2 : loss
1422 // -1 : loss, but draw under 50-move rule
1423 //  0 : draw
1424 //  1 : win, but draw under 50-move rule
1425 //  2 : win
1426 WDLScore Tablebases::probe_wdl(Position& pos, ProbeState* result) {
1427
1428     *result = OK;
1429     return search<false>(pos, result);
1430 }
1431
1432 // Probe the DTZ table for a particular position.
1433 // If *result != FAIL, the probe was successful.
1434 // The return value is from the point of view of the side to move:
1435 //         n < -100 : loss, but draw under 50-move rule
1436 // -100 <= n < -1   : loss in n ply (assuming 50-move counter == 0)
1437 //        -1        : loss, the side to move is mated
1438 //         0        : draw
1439 //     1 < n <= 100 : win in n ply (assuming 50-move counter == 0)
1440 //   100 < n        : win, but draw under 50-move rule
1441 //
1442 // The return value n can be off by 1: a return value -n can mean a loss
1443 // in n+1 ply and a return value +n can mean a win in n+1 ply. This
1444 // cannot happen for tables with positions exactly on the "edge" of
1445 // the 50-move rule.
1446 //
1447 // This implies that if dtz > 0 is returned, the position is certainly
1448 // a win if dtz + 50-move-counter <= 99. Care must be taken that the engine
1449 // picks moves that preserve dtz + 50-move-counter <= 99.
1450 //
1451 // If n = 100 immediately after a capture or pawn move, then the position
1452 // is also certainly a win, and during the whole phase until the next
1453 // capture or pawn move, the inequality to be preserved is
1454 // dtz + 50-move-counter <= 100.
1455 //
1456 // In short, if a move is available resulting in dtz + 50-move-counter <= 99,
1457 // then do not accept moves leading to dtz + 50-move-counter == 100.
1458 int Tablebases::probe_dtz(Position& pos, ProbeState* result) {
1459
1460     *result = OK;
1461     WDLScore wdl = search<true>(pos, result);
1462
1463     if (*result == FAIL || wdl == WDLDraw) // DTZ tables don't store draws
1464         return 0;
1465
1466     // DTZ stores a 'don't care' value in this case, or even a plain wrong
1467     // one as in case the best move is a losing ep, so it cannot be probed.
1468     if (*result == ZEROING_BEST_MOVE)
1469         return dtz_before_zeroing(wdl);
1470
1471     int dtz = probe_table<DTZ>(pos, result, wdl);
1472
1473     if (*result == FAIL)
1474         return 0;
1475
1476     if (*result != CHANGE_STM)
1477         return (dtz + 100 * (wdl == WDLBlessedLoss || wdl == WDLCursedWin)) * sign_of(wdl);
1478
1479     // DTZ stores results for the other side, so we need to do a 1-ply search and
1480     // find the winning move that minimizes DTZ.
1481     StateInfo st;
1482     int minDTZ = 0xFFFF;
1483
1484     for (const Move move : MoveList<LEGAL>(pos))
1485     {
1486         bool zeroing = pos.capture(move) || type_of(pos.moved_piece(move)) == PAWN;
1487
1488         pos.do_move(move, st);
1489
1490         // For zeroing moves we want the dtz of the move _before_ doing it,
1491         // otherwise we will get the dtz of the next move sequence. Search the
1492         // position after the move to get the score sign (because even in a
1493         // winning position we could make a losing capture or going for a draw).
1494         dtz = zeroing ? -dtz_before_zeroing(search<false>(pos, result))
1495                       : -probe_dtz(pos, result);
1496
1497         // If the move mates, force minDTZ to 1
1498         if (dtz == 1 && pos.checkers() && MoveList<LEGAL>(pos).size() == 0)
1499             minDTZ = 1;
1500
1501         // Convert result from 1-ply search. Zeroing moves are already accounted
1502         // by dtz_before_zeroing() that returns the DTZ of the previous move.
1503         if (!zeroing)
1504             dtz += sign_of(dtz);
1505
1506         // Skip the draws and if we are winning only pick positive dtz
1507         if (dtz < minDTZ && sign_of(dtz) == sign_of(wdl))
1508             minDTZ = dtz;
1509
1510         pos.undo_move(move);
1511
1512         if (*result == FAIL)
1513             return 0;
1514     }
1515
1516     // When there are no legal moves, the position is mate: we return -1
1517     return minDTZ == 0xFFFF ? -1 : minDTZ;
1518 }
1519
1520
1521 // Use the DTZ tables to rank root moves.
1522 //
1523 // A return value false indicates that not all probes were successful.
1524 bool Tablebases::root_probe(Position& pos, Search::RootMoves& rootMoves) {
1525
1526     ProbeState result = OK;
1527     StateInfo st;
1528
1529     // Obtain 50-move counter for the root position
1530     int cnt50 = pos.rule50_count();
1531
1532     // Check whether a position was repeated since the last zeroing move.
1533     bool rep = pos.has_repeated();
1534
1535     int dtz, bound = Options["Syzygy50MoveRule"] ? (MAX_DTZ - 100) : 1;
1536
1537     // Probe and rank each move
1538     for (auto& m : rootMoves)
1539     {
1540         pos.do_move(m.pv[0], st);
1541
1542         // Calculate dtz for the current move counting from the root position
1543         if (pos.rule50_count() == 0)
1544         {
1545             // In case of a zeroing move, dtz is one of -101/-1/0/1/101
1546             WDLScore wdl = -probe_wdl(pos, &result);
1547             dtz = dtz_before_zeroing(wdl);
1548         }
1549         else if (pos.is_draw(1))
1550         {
1551             // In case a root move leads to a draw by repetition or
1552             // 50-move rule, we set dtz to zero. Note: since we are
1553             // only 1 ply from the root, this must be a true 3-fold
1554             // repetition inside the game history.
1555             dtz = 0;
1556         }
1557         else
1558         {
1559             // Otherwise, take dtz for the new position and correct by 1 ply
1560             dtz = -probe_dtz(pos, &result);
1561             dtz =  dtz > 0 ? dtz + 1
1562                  : dtz < 0 ? dtz - 1 : dtz;
1563         }
1564
1565         // Make sure that a mating move is assigned a dtz value of 1
1566         if (   pos.checkers()
1567             && dtz == 2
1568             && MoveList<LEGAL>(pos).size() == 0)
1569             dtz = 1;
1570
1571         pos.undo_move(m.pv[0]);
1572
1573         if (result == FAIL)
1574             return false;
1575
1576         // Better moves are ranked higher. Certain wins are ranked equally.
1577         // Losing moves are ranked equally unless a 50-move draw is in sight.
1578         int r =  dtz > 0 ? (dtz + cnt50 <= 99 && !rep ? MAX_DTZ : MAX_DTZ - (dtz + cnt50))
1579                : dtz < 0 ? (-dtz * 2 + cnt50 < 100 ? -MAX_DTZ : -MAX_DTZ + (-dtz + cnt50))
1580                : 0;
1581         m.tbRank = r;
1582
1583         // Determine the score to be displayed for this move. Assign at least
1584         // 1 cp to cursed wins and let it grow to 49 cp as the positions gets
1585         // closer to a real win.
1586         m.tbScore =  r >= bound ? VALUE_MATE - MAX_PLY - 1
1587                    : r >  0     ? Value((std::max( 3, r - (MAX_DTZ - 200)) * int(PawnValue)) / 200)
1588                    : r == 0     ? VALUE_DRAW
1589                    : r > -bound ? Value((std::min(-3, r + (MAX_DTZ - 200)) * int(PawnValue)) / 200)
1590                    :             -VALUE_MATE + MAX_PLY + 1;
1591     }
1592
1593     return true;
1594 }
1595
1596
1597 // Use the WDL tables to rank root moves.
1598 // This is a fallback for the case that some or all DTZ tables are missing.
1599 //
1600 // A return value false indicates that not all probes were successful.
1601 bool Tablebases::root_probe_wdl(Position& pos, Search::RootMoves& rootMoves) {
1602
1603     static const int WDL_to_rank[] = { -MAX_DTZ, -MAX_DTZ + 101, 0, MAX_DTZ - 101, MAX_DTZ };
1604
1605     ProbeState result = OK;
1606     StateInfo st;
1607     WDLScore wdl;
1608
1609     bool rule50 = Options["Syzygy50MoveRule"];
1610
1611     // Probe and rank each move
1612     for (auto& m : rootMoves)
1613     {
1614         pos.do_move(m.pv[0], st);
1615
1616         if (pos.is_draw(1))
1617             wdl = WDLDraw;
1618         else
1619             wdl = -probe_wdl(pos, &result);
1620
1621         pos.undo_move(m.pv[0]);
1622
1623         if (result == FAIL)
1624             return false;
1625
1626         m.tbRank = WDL_to_rank[wdl + 2];
1627
1628         if (!rule50)
1629             wdl =  wdl > WDLDraw ? WDLWin
1630                  : wdl < WDLDraw ? WDLLoss : WDLDraw;
1631         m.tbScore = WDL_to_value[wdl + 2];
1632     }
1633
1634     return true;
1635 }
1636
1637 } // namespace Stockfish