2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2023 The Stockfish developers (see AUTHORS file)
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.
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.
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/>.
22 #if _WIN32_WINNT < 0x0601
24 #define _WIN32_WINNT 0x0601 // Force to include needed API prototypes
32 // The needed Windows API for processor groups could be missed from old Windows
33 // versions, so instead of calling them directly (forcing the linker to resolve
34 // the calls at compile time), try to load them at runtime. To do this we need
35 // first to define the corresponding function pointers.
37 using fun1_t = bool (*)(LOGICAL_PROCESSOR_RELATIONSHIP,
38 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX,
40 using fun2_t = bool (*)(USHORT, PGROUP_AFFINITY);
41 using fun3_t = bool (*)(HANDLE, CONST GROUP_AFFINITY*, PGROUP_AFFINITY);
42 using fun4_t = bool (*)(USHORT, PGROUP_AFFINITY, USHORT, PUSHORT);
43 using fun5_t = WORD (*)();
44 using fun6_t = bool (*)(HANDLE, DWORD, PHANDLE);
45 using fun7_t = bool (*)(LPCSTR, LPCSTR, PLUID);
46 using fun8_t = bool (*)(HANDLE, BOOL, PTOKEN_PRIVILEGES, DWORD, PTOKEN_PRIVILEGES, PDWORD);
58 #include <string_view>
62 #if defined(__linux__) && !defined(__ANDROID__)
66 #if defined(__APPLE__) || defined(__ANDROID__) || defined(__OpenBSD__) \
67 || (defined(__GLIBCXX__) && !defined(_GLIBCXX_HAVE_ALIGNED_ALLOC) && !defined(_WIN32)) \
69 #define POSIXALIGNEDALLOC
77 // Version number or dev.
78 constexpr std::string_view version = "dev";
80 // Our fancy logging facility. The trick here is to replace cin.rdbuf() and
81 // cout.rdbuf() with two Tie objects that tie cin and cout to a file stream. We
82 // can toggle the logging of std::cout and std:cin at runtime whilst preserving
83 // usual I/O functionality, all without changing a single line of code!
84 // Idea from http://groups.google.com/group/comp.lang.c++/msg/1d941c0f26ea0d81
86 struct Tie: public std::streambuf { // MSVC requires split streambuf for cin and cout
88 Tie(std::streambuf* b, std::streambuf* l) :
92 int sync() override { return logBuf->pubsync(), buf->pubsync(); }
93 int overflow(int c) override { return log(buf->sputc(char(c)), "<< "); }
94 int underflow() override { return buf->sgetc(); }
95 int uflow() override { return log(buf->sbumpc(), ">> "); }
97 std::streambuf *buf, *logBuf;
99 int log(int c, const char* prefix) {
101 static int last = '\n'; // Single log file
104 logBuf->sputn(prefix, 3);
106 return last = logBuf->sputc(char(c));
113 in(std::cin.rdbuf(), file.rdbuf()),
114 out(std::cout.rdbuf(), file.rdbuf()) {}
115 ~Logger() { start(""); }
121 static void start(const std::string& fname) {
125 if (l.file.is_open())
127 std::cout.rdbuf(l.out.buf);
128 std::cin.rdbuf(l.in.buf);
134 l.file.open(fname, std::ifstream::out);
136 if (!l.file.is_open())
138 std::cerr << "Unable to open debug log file " << fname << std::endl;
142 std::cin.rdbuf(&l.in);
143 std::cout.rdbuf(&l.out);
151 // Returns the full name of the current Stockfish version.
152 // For local dev compiles we try to append the commit sha and commit date
153 // from git if that fails only the local compilation date is set and "nogit" is specified:
154 // Stockfish dev-YYYYMMDD-SHA
156 // Stockfish dev-YYYYMMDD-nogit
158 // For releases (non-dev builds) we only include the version number:
160 std::string engine_info(bool to_uci) {
161 std::stringstream ss;
162 ss << "Stockfish " << version << std::setfill('0');
164 if constexpr (version == "dev")
168 ss << stringify(GIT_DATE);
170 constexpr std::string_view months("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec");
171 std::string month, day, year;
172 std::stringstream date(__DATE__); // From compiler, format is "Sep 21 2008"
174 date >> month >> day >> year;
175 ss << year << std::setw(2) << std::setfill('0') << (1 + months.find(month) / 4)
176 << std::setw(2) << std::setfill('0') << day;
182 ss << stringify(GIT_SHA);
188 ss << (to_uci ? "\nid author " : " by ") << "the Stockfish developers (see AUTHORS file)";
194 // Returns a string trying to describe the compiler we use
195 std::string compiler_info() {
197 #define make_version_string(major, minor, patch) \
198 stringify(major) "." stringify(minor) "." stringify(patch)
200 // Predefined macros hell:
202 // __GNUC__ Compiler is GCC, Clang or ICX
203 // __clang__ Compiler is Clang or ICX
204 // __INTEL_LLVM_COMPILER Compiler is ICX
205 // _MSC_VER Compiler is MSVC
206 // _WIN32 Building on Windows (any)
207 // _WIN64 Building on Windows 64 bit
209 std::string compiler = "\nCompiled by : ";
211 #if defined(__INTEL_LLVM_COMPILER)
213 compiler += stringify(__INTEL_LLVM_COMPILER);
214 #elif defined(__clang__)
215 compiler += "clang++ ";
216 compiler += make_version_string(__clang_major__, __clang_minor__, __clang_patchlevel__);
219 compiler += "(version ";
220 compiler += stringify(_MSC_FULL_VER) "." stringify(_MSC_BUILD);
222 #elif defined(__e2k__) && defined(__LCC__)
223 #define dot_ver2(n) \
224 compiler += char('.'); \
225 compiler += char('0' + (n) / 10); \
226 compiler += char('0' + (n) % 10);
228 compiler += "MCST LCC ";
229 compiler += "(version ";
230 compiler += std::to_string(__LCC__ / 100);
231 dot_ver2(__LCC__ % 100) dot_ver2(__LCC_MINOR__) compiler += ")";
233 compiler += "g++ (GNUC) ";
234 compiler += make_version_string(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
236 compiler += "Unknown compiler ";
237 compiler += "(unknown version)";
240 #if defined(__APPLE__)
241 compiler += " on Apple";
242 #elif defined(__CYGWIN__)
243 compiler += " on Cygwin";
244 #elif defined(__MINGW64__)
245 compiler += " on MinGW64";
246 #elif defined(__MINGW32__)
247 compiler += " on MinGW32";
248 #elif defined(__ANDROID__)
249 compiler += " on Android";
250 #elif defined(__linux__)
251 compiler += " on Linux";
252 #elif defined(_WIN64)
253 compiler += " on Microsoft Windows 64-bit";
254 #elif defined(_WIN32)
255 compiler += " on Microsoft Windows 32-bit";
257 compiler += " on unknown system";
260 compiler += "\nCompilation architecture : ";
262 compiler += stringify(ARCH);
264 compiler += "(undefined architecture)";
267 compiler += "\nCompilation settings : ";
268 compiler += (Is64Bit ? "64bit" : "32bit");
269 #if defined(USE_VNNI)
272 #if defined(USE_AVX512)
273 compiler += " AVX512";
275 compiler += (HasPext ? " BMI2" : "");
276 #if defined(USE_AVX2)
279 #if defined(USE_SSE41)
280 compiler += " SSE41";
282 #if defined(USE_SSSE3)
283 compiler += " SSSE3";
285 #if defined(USE_SSE2)
288 compiler += (HasPopCnt ? " POPCNT" : "");
289 #if defined(USE_NEON_DOTPROD)
290 compiler += " NEON_DOTPROD";
291 #elif defined(USE_NEON)
296 compiler += " DEBUG";
299 compiler += "\nCompiler __VERSION__ macro : ";
301 compiler += __VERSION__;
303 compiler += "(undefined macro)";
312 // Debug functions used mainly to collect run-time statistics
313 constexpr int MaxDebugSlots = 32;
319 std::atomic<int64_t> data[N] = {0};
321 constexpr inline std::atomic<int64_t>& operator[](int index) { return data[index]; }
324 DebugInfo<2> hit[MaxDebugSlots];
325 DebugInfo<2> mean[MaxDebugSlots];
326 DebugInfo<3> stdev[MaxDebugSlots];
327 DebugInfo<6> correl[MaxDebugSlots];
331 void dbg_hit_on(bool cond, int slot) {
338 void dbg_mean_of(int64_t value, int slot) {
341 mean[slot][1] += value;
344 void dbg_stdev_of(int64_t value, int slot) {
347 stdev[slot][1] += value;
348 stdev[slot][2] += value * value;
351 void dbg_correl_of(int64_t value1, int64_t value2, int slot) {
354 correl[slot][1] += value1;
355 correl[slot][2] += value1 * value1;
356 correl[slot][3] += value2;
357 correl[slot][4] += value2 * value2;
358 correl[slot][5] += value1 * value2;
364 auto E = [&n](int64_t x) { return double(x) / n; };
365 auto sqr = [](double x) { return x * x; };
367 for (int i = 0; i < MaxDebugSlots; ++i)
369 std::cerr << "Hit #" << i << ": Total " << n << " Hits " << hit[i][1]
370 << " Hit Rate (%) " << 100.0 * E(hit[i][1]) << std::endl;
372 for (int i = 0; i < MaxDebugSlots; ++i)
373 if ((n = mean[i][0]))
375 std::cerr << "Mean #" << i << ": Total " << n << " Mean " << E(mean[i][1]) << std::endl;
378 for (int i = 0; i < MaxDebugSlots; ++i)
379 if ((n = stdev[i][0]))
381 double r = sqrt(E(stdev[i][2]) - sqr(E(stdev[i][1])));
382 std::cerr << "Stdev #" << i << ": Total " << n << " Stdev " << r << std::endl;
385 for (int i = 0; i < MaxDebugSlots; ++i)
386 if ((n = correl[i][0]))
388 double r = (E(correl[i][5]) - E(correl[i][1]) * E(correl[i][3]))
389 / (sqrt(E(correl[i][2]) - sqr(E(correl[i][1])))
390 * sqrt(E(correl[i][4]) - sqr(E(correl[i][3]))));
391 std::cerr << "Correl. #" << i << ": Total " << n << " Coefficient " << r << std::endl;
396 // Used to serialize access to std::cout
397 // to avoid multiple threads writing at the same time.
398 std::ostream& operator<<(std::ostream& os, SyncCout sc) {
412 // Trampoline helper to avoid moving Logger to misc.h
413 void start_logger(const std::string& fname) { Logger::start(fname); }
418 void prefetch(void*) {}
422 void prefetch(void* addr) {
424 #if defined(_MSC_VER)
425 _mm_prefetch((char*) addr, _MM_HINT_T0);
427 __builtin_prefetch(addr);
434 // Wrapper for systems where the c++17 implementation
435 // does not guarantee the availability of aligned_alloc(). Memory allocated with
436 // std_aligned_alloc() must be freed with std_aligned_free().
437 void* std_aligned_alloc(size_t alignment, size_t size) {
439 #if defined(POSIXALIGNEDALLOC)
441 return posix_memalign(&mem, alignment, size) ? nullptr : mem;
442 #elif defined(_WIN32) && !defined(_M_ARM) && !defined(_M_ARM64)
443 return _mm_malloc(size, alignment);
444 #elif defined(_WIN32)
445 return _aligned_malloc(size, alignment);
447 return std::aligned_alloc(alignment, size);
451 void std_aligned_free(void* ptr) {
453 #if defined(POSIXALIGNEDALLOC)
455 #elif defined(_WIN32) && !defined(_M_ARM) && !defined(_M_ARM64)
457 #elif defined(_WIN32)
464 // aligned_large_pages_alloc() will return suitably aligned memory, if possible using large pages.
468 static void* aligned_large_pages_alloc_windows([[maybe_unused]] size_t allocSize) {
474 HANDLE hProcessToken{};
478 const size_t largePageSize = GetLargePageMinimum();
482 // Dynamically link OpenProcessToken, LookupPrivilegeValue and AdjustTokenPrivileges
484 HMODULE hAdvapi32 = GetModuleHandle(TEXT("advapi32.dll"));
487 hAdvapi32 = LoadLibrary(TEXT("advapi32.dll"));
489 auto fun6 = fun6_t((void (*)()) GetProcAddress(hAdvapi32, "OpenProcessToken"));
492 auto fun7 = fun7_t((void (*)()) GetProcAddress(hAdvapi32, "LookupPrivilegeValueA"));
495 auto fun8 = fun8_t((void (*)()) GetProcAddress(hAdvapi32, "AdjustTokenPrivileges"));
499 // We need SeLockMemoryPrivilege, so try to enable it for the process
500 if (!fun6( // OpenProcessToken()
501 GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hProcessToken))
504 if (fun7( // LookupPrivilegeValue(nullptr, SE_LOCK_MEMORY_NAME, &luid)
505 nullptr, "SeLockMemoryPrivilege", &luid))
507 TOKEN_PRIVILEGES tp{};
508 TOKEN_PRIVILEGES prevTp{};
511 tp.PrivilegeCount = 1;
512 tp.Privileges[0].Luid = luid;
513 tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
515 // Try to enable SeLockMemoryPrivilege. Note that even if AdjustTokenPrivileges() succeeds,
516 // we still need to query GetLastError() to ensure that the privileges were actually obtained.
517 if (fun8( // AdjustTokenPrivileges()
518 hProcessToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &prevTp, &prevTpLen)
519 && GetLastError() == ERROR_SUCCESS)
521 // Round up size to full pages and allocate
522 allocSize = (allocSize + largePageSize - 1) & ~size_t(largePageSize - 1);
523 mem = VirtualAlloc(nullptr, allocSize, MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES,
526 // Privilege no longer needed, restore previous state
527 fun8( // AdjustTokenPrivileges ()
528 hProcessToken, FALSE, &prevTp, 0, nullptr, nullptr);
532 CloseHandle(hProcessToken);
539 void* aligned_large_pages_alloc(size_t allocSize) {
541 // Try to allocate large pages
542 void* mem = aligned_large_pages_alloc_windows(allocSize);
544 // Fall back to regular, page-aligned, allocation if necessary
546 mem = VirtualAlloc(nullptr, allocSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
553 void* aligned_large_pages_alloc(size_t allocSize) {
555 #if defined(__linux__)
556 constexpr size_t alignment = 2 * 1024 * 1024; // assumed 2MB page size
558 constexpr size_t alignment = 4096; // assumed small page size
561 // Round up to multiples of alignment
562 size_t size = ((allocSize + alignment - 1) / alignment) * alignment;
563 void* mem = std_aligned_alloc(alignment, size);
564 #if defined(MADV_HUGEPAGE)
565 madvise(mem, size, MADV_HUGEPAGE);
573 // aligned_large_pages_free() will free the previously allocated ttmem
577 void aligned_large_pages_free(void* mem) {
579 if (mem && !VirtualFree(mem, 0, MEM_RELEASE))
581 DWORD err = GetLastError();
582 std::cerr << "Failed to free large page memory. Error code: 0x" << std::hex << err
583 << std::dec << std::endl;
590 void aligned_large_pages_free(void* mem) { std_aligned_free(mem); }
595 namespace WinProcGroup {
599 void bindThisThread(size_t) {}
603 // Retrieves logical processor information using Windows-specific
604 // API and returns the best node id for the thread with index idx. Original
605 // code from Texel by Peter Ă–sterlund.
606 static int best_node(size_t idx) {
611 DWORD returnLength = 0;
612 DWORD byteOffset = 0;
614 // Early exit if the needed API is not available at runtime
615 HMODULE k32 = GetModuleHandle(TEXT("Kernel32.dll"));
616 auto fun1 = (fun1_t) (void (*)()) GetProcAddress(k32, "GetLogicalProcessorInformationEx");
620 // First call to GetLogicalProcessorInformationEx() to get returnLength.
621 // We expect the call to fail due to null buffer.
622 if (fun1(RelationAll, nullptr, &returnLength))
625 // Once we know returnLength, allocate the buffer
626 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer, *ptr;
627 ptr = buffer = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) malloc(returnLength);
629 // Second call to GetLogicalProcessorInformationEx(), now we expect to succeed
630 if (!fun1(RelationAll, buffer, &returnLength))
636 while (byteOffset < returnLength)
638 if (ptr->Relationship == RelationNumaNode)
641 else if (ptr->Relationship == RelationProcessorCore)
644 threads += (ptr->Processor.Flags == LTP_PC_SMT) ? 2 : 1;
648 byteOffset += ptr->Size;
649 ptr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) (((char*) ptr) + ptr->Size);
654 std::vector<int> groups;
656 // Run as many threads as possible on the same node until the core limit is
657 // reached, then move on to filling the next node.
658 for (int n = 0; n < nodes; n++)
659 for (int i = 0; i < cores / nodes; i++)
662 // In case a core has more than one logical processor (we assume 2) and we
663 // still have threads to allocate, spread them evenly across available nodes.
664 for (int t = 0; t < threads - cores; t++)
665 groups.push_back(t % nodes);
667 // If we still have more threads than the total number of logical processors
668 // then return -1 and let the OS to decide what to do.
669 return idx < groups.size() ? groups[idx] : -1;
673 // Sets the group affinity of the current thread
674 void bindThisThread(size_t idx) {
676 // Use only local variables to be thread-safe
677 int node = best_node(idx);
682 // Early exit if the needed API are not available at runtime
683 HMODULE k32 = GetModuleHandle(TEXT("Kernel32.dll"));
684 auto fun2 = fun2_t((void (*)()) GetProcAddress(k32, "GetNumaNodeProcessorMaskEx"));
685 auto fun3 = fun3_t((void (*)()) GetProcAddress(k32, "SetThreadGroupAffinity"));
686 auto fun4 = fun4_t((void (*)()) GetProcAddress(k32, "GetNumaNodeProcessorMask2"));
687 auto fun5 = fun5_t((void (*)()) GetProcAddress(k32, "GetMaximumProcessorGroupCount"));
694 GROUP_AFFINITY affinity;
695 if (fun2(node, &affinity)) // GetNumaNodeProcessorMaskEx
696 fun3(GetCurrentThread(), &affinity, nullptr); // SetThreadGroupAffinity
700 // If a numa node has more than one processor group, we assume they are
701 // sized equal and we spread threads evenly across the groups.
702 USHORT elements, returnedElements;
703 elements = fun5(); // GetMaximumProcessorGroupCount
704 GROUP_AFFINITY* affinity = (GROUP_AFFINITY*) malloc(elements * sizeof(GROUP_AFFINITY));
705 if (fun4(node, affinity, elements, &returnedElements)) // GetNumaNodeProcessorMask2
706 fun3(GetCurrentThread(), &affinity[idx % returnedElements],
707 nullptr); // SetThreadGroupAffinity
714 } // namespace WinProcGroup
718 #define GETCWD _getcwd
721 #define GETCWD getcwd
724 namespace CommandLine {
726 std::string argv0; // path+name of the executable binary, as given by argv[0]
727 std::string binaryDirectory; // path of the executable directory
728 std::string workingDirectory; // path of the working directory
730 void init([[maybe_unused]] int argc, char* argv[]) {
731 std::string pathSeparator;
733 // Extract the path+name of the executable binary
737 pathSeparator = "\\";
739 // Under windows argv[0] may not have the extension. Also _get_pgmptr() had
740 // issues in some Windows 10 versions, so check returned values carefully.
741 char* pgmptr = nullptr;
742 if (!_get_pgmptr(&pgmptr) && pgmptr != nullptr && *pgmptr)
749 // Extract the working directory
750 workingDirectory = "";
752 char* cwd = GETCWD(buff, 40000);
754 workingDirectory = cwd;
756 // Extract the binary directory path from argv0
757 binaryDirectory = argv0;
758 size_t pos = binaryDirectory.find_last_of("\\/");
759 if (pos == std::string::npos)
760 binaryDirectory = "." + pathSeparator;
762 binaryDirectory.resize(pos + 1);
764 // Pattern replacement: "./" at the start of path is replaced by the working directory
765 if (binaryDirectory.find("." + pathSeparator) == 0)
766 binaryDirectory.replace(0, 1, workingDirectory);
770 } // namespace CommandLine
772 } // namespace Stockfish