2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
43 #include "ucioption.h"
49 //// Local definitions
55 enum NodeType { NonPV, PV };
57 // ThreadsManager class is used to handle all the threads related stuff in search,
58 // init, starting, parking and, the most important, launching a slave thread at a
59 // split point are what this class does. All the access to shared thread data is
60 // done through this class, so that we avoid using global variables instead.
62 class ThreadsManager {
63 /* As long as the single ThreadsManager object is defined as a global we don't
64 need to explicitly initialize to zero its data members because variables with
65 static storage duration are automatically set to zero before enter main()
71 int active_threads() const { return ActiveThreads; }
72 void set_active_threads(int newActiveThreads) { ActiveThreads = newActiveThreads; }
73 void incrementNodeCounter(int threadID) { threads[threadID].nodes++; }
74 void incrementBetaCounter(Color us, Depth d, int threadID) { threads[threadID].betaCutOffs[us] += unsigned(d); }
76 void resetNodeCounters();
77 void resetBetaCounters();
78 int64_t nodes_searched() const;
79 void get_beta_counters(Color us, int64_t& our, int64_t& their) const;
80 bool available_thread_exists(int master) const;
81 bool thread_is_available(int slave, int master) const;
82 bool thread_should_stop(int threadID) const;
83 void wake_sleeping_threads();
84 void put_threads_to_sleep();
85 void idle_loop(int threadID, SplitPoint* sp);
88 bool split(const Position& pos, SearchStack* ss, int ply, Value* alpha, const Value beta, Value* bestValue,
89 Depth depth, bool mateThreat, int* moves, MovePicker* mp, int master, bool pvNode);
95 volatile bool AllThreadsShouldExit, AllThreadsShouldSleep;
96 Thread threads[MAX_THREADS];
97 SplitPoint SplitPointStack[MAX_THREADS][ACTIVE_SPLIT_POINTS_MAX];
99 Lock MPLock, WaitLock;
101 #if !defined(_MSC_VER)
102 pthread_cond_t WaitCond;
104 HANDLE SitIdleEvent[MAX_THREADS];
110 // RootMove struct is used for moves at the root at the tree. For each
111 // root move, we store a score, a node count, and a PV (really a refutation
112 // in the case of moves which fail low).
116 RootMove() { nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL; }
118 // RootMove::operator<() is the comparison function used when
119 // sorting the moves. A move m1 is considered to be better
120 // than a move m2 if it has a higher score, or if the moves
121 // have equal score but m1 has the higher node count.
122 bool operator<(const RootMove& m) const {
124 return score != m.score ? score < m.score : theirBeta <= m.theirBeta;
129 int64_t nodes, cumulativeNodes, ourBeta, theirBeta;
130 Move pv[PLY_MAX_PLUS_2];
134 // The RootMoveList class is essentially an array of RootMove objects, with
135 // a handful of methods for accessing the data in the individual moves.
140 RootMoveList(Position& pos, Move searchMoves[]);
142 int move_count() const { return count; }
143 Move get_move(int moveNum) const { return moves[moveNum].move; }
144 Value get_move_score(int moveNum) const { return moves[moveNum].score; }
145 void set_move_score(int moveNum, Value score) { moves[moveNum].score = score; }
146 Move get_move_pv(int moveNum, int i) const { return moves[moveNum].pv[i]; }
147 int64_t get_move_cumulative_nodes(int moveNum) const { return moves[moveNum].cumulativeNodes; }
149 void set_move_nodes(int moveNum, int64_t nodes);
150 void set_beta_counters(int moveNum, int64_t our, int64_t their);
151 void set_move_pv(int moveNum, const Move pv[]);
153 void sort_multipv(int n);
156 static const int MaxRootMoves = 500;
157 RootMove moves[MaxRootMoves];
166 // Maximum depth for razoring
167 const Depth RazorDepth = 4 * OnePly;
169 // Dynamic razoring margin based on depth
170 inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
172 // Step 8. Null move search with verification search
174 // Null move margin. A null move search will not be done if the static
175 // evaluation of the position is more than NullMoveMargin below beta.
176 const Value NullMoveMargin = Value(0x200);
178 // Maximum depth for use of dynamic threat detection when null move fails low
179 const Depth ThreatDepth = 5 * OnePly;
181 // Step 9. Internal iterative deepening
183 // Minimum depth for use of internal iterative deepening
184 const Depth IIDDepth[2] = { 8 * OnePly /* non-PV */, 5 * OnePly /* PV */};
186 // At Non-PV nodes we do an internal iterative deepening search
187 // when the static evaluation is at most IIDMargin below beta.
188 const Value IIDMargin = Value(0x100);
190 // Step 11. Decide the new search depth
192 // Extensions. Configurable UCI options
193 // Array index 0 is used at non-PV nodes, index 1 at PV nodes.
194 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
195 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
197 // Minimum depth for use of singular extension
198 const Depth SingularExtensionDepth[2] = { 8 * OnePly /* non-PV */, 6 * OnePly /* PV */};
200 // If the TT move is at least SingularExtensionMargin better then the
201 // remaining ones we will extend it.
202 const Value SingularExtensionMargin = Value(0x20);
204 // Step 12. Futility pruning
206 // Futility margin for quiescence search
207 const Value FutilityMarginQS = Value(0x80);
209 // Futility lookup tables (initialized at startup) and their getter functions
210 int32_t FutilityMarginsMatrix[16][64]; // [depth][moveNumber]
211 int FutilityMoveCountArray[32]; // [depth]
213 inline Value futility_margin(Depth d, int mn) { return Value(d < 7 * OnePly ? FutilityMarginsMatrix[Max(d, 0)][Min(mn, 63)] : 2 * VALUE_INFINITE); }
214 inline int futility_move_count(Depth d) { return d < 16 * OnePly ? FutilityMoveCountArray[d] : 512; }
216 // Step 14. Reduced search
218 // Reduction lookup tables (initialized at startup) and their getter functions
219 int8_t ReductionMatrix[2][64][64]; // [pv][depth][moveNumber]
221 template <NodeType PV>
222 inline Depth reduction(Depth d, int mn) { return (Depth) ReductionMatrix[PV][Min(d / 2, 63)][Min(mn, 63)]; }
224 // Common adjustments
226 // Search depth at iteration 1
227 const Depth InitialDepth = OnePly;
229 // Easy move margin. An easy move candidate must be at least this much
230 // better than the second best move.
231 const Value EasyMoveMargin = Value(0x200);
233 // Last seconds noise filtering (LSN)
234 const bool UseLSNFiltering = true;
235 const int LSNTime = 4000; // In milliseconds
236 const Value LSNValue = value_from_centipawns(200);
237 bool loseOnTime = false;
245 // Scores and number of times the best move changed for each iteration
246 Value ValueByIteration[PLY_MAX_PLUS_2];
247 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
249 // Search window management
255 // Time managment variables
256 int SearchStartTime, MaxNodes, MaxDepth, MaxSearchTime;
257 int AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
258 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
259 bool FirstRootMove, AbortSearch, Quit, AspirationFailLow;
263 std::ofstream LogFile;
265 // Multi-threads related variables
266 Depth MinimumSplitDepth;
267 int MaxThreadsPerSplitPoint;
270 // Node counters, used only by thread[0] but try to keep in different cache
271 // lines (64 bytes each) from the heavy multi-thread read accessed variables.
273 int NodesBetweenPolls = 30000;
280 Value id_loop(const Position& pos, Move searchMoves[]);
281 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value* alphaPtr, Value* betaPtr);
283 template <NodeType PvNode>
284 Value search(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
286 template <NodeType PvNode>
287 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
289 template <NodeType PvNode>
290 void sp_search(SplitPoint* sp, int threadID);
292 template <NodeType PvNode>
293 Depth extension(const Position& pos, Move m, bool captureOrPromotion, bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous);
295 void init_node(SearchStack ss[], int ply, int threadID);
296 void update_pv(SearchStack ss[], int ply);
297 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
298 bool connected_moves(const Position& pos, Move m1, Move m2);
299 bool value_is_mate(Value value);
300 bool move_is_killer(Move m, const SearchStack& ss);
301 bool ok_to_do_nullmove(const Position& pos);
302 bool ok_to_prune(const Position& pos, Move m, Move threat);
303 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
304 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
305 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
306 void update_killers(Move m, SearchStack& ss);
307 void update_gains(const Position& pos, Move move, Value before, Value after);
309 int current_search_time();
313 void wait_for_stop_or_ponderhit();
314 void init_ss_array(SearchStack ss[]);
315 void print_pv_info(const Position& pos, SearchStack ss[], Value alpha, Value beta, Value value);
317 #if !defined(_MSC_VER)
318 void *init_thread(void *threadID);
320 DWORD WINAPI init_thread(LPVOID threadID);
330 /// init_threads(), exit_threads() and nodes_searched() are helpers to
331 /// give accessibility to some TM methods from outside of current file.
333 void init_threads() { TM.init_threads(); }
334 void exit_threads() { TM.exit_threads(); }
335 int64_t nodes_searched() { return TM.nodes_searched(); }
338 /// perft() is our utility to verify move generation is bug free. All the legal
339 /// moves up to given depth are generated and counted and the sum returned.
341 int perft(Position& pos, Depth depth)
346 MovePicker mp(pos, MOVE_NONE, depth, H);
348 // If we are at the last ply we don't need to do and undo
349 // the moves, just to count them.
350 if (depth <= OnePly) // Replace with '<' to test also qsearch
352 while (mp.get_next_move()) sum++;
356 // Loop through all legal moves
358 while ((move = mp.get_next_move()) != MOVE_NONE)
360 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
361 sum += perft(pos, depth - OnePly);
368 /// think() is the external interface to Stockfish's search, and is called when
369 /// the program receives the UCI 'go' command. It initializes various
370 /// search-related global variables, and calls root_search(). It returns false
371 /// when a quit command is received during the search.
373 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
374 int time[], int increment[], int movesToGo, int maxDepth,
375 int maxNodes, int maxTime, Move searchMoves[]) {
377 // Initialize global search variables
378 StopOnPonderhit = AbortSearch = Quit = AspirationFailLow = false;
379 MaxSearchTime = AbsoluteMaxSearchTime = ExtraSearchTime = 0;
381 TM.resetNodeCounters();
382 SearchStartTime = get_system_time();
383 ExactMaxTime = maxTime;
386 InfiniteSearch = infinite;
387 PonderSearch = ponder;
388 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
390 // Look for a book move, only during games, not tests
391 if (UseTimeManagement && get_option_value_bool("OwnBook"))
393 if (get_option_value_string("Book File") != OpeningBook.file_name())
394 OpeningBook.open(get_option_value_string("Book File"));
396 Move bookMove = OpeningBook.get_move(pos, get_option_value_bool("Best Book Move"));
397 if (bookMove != MOVE_NONE)
400 wait_for_stop_or_ponderhit();
402 cout << "bestmove " << bookMove << endl;
407 // Reset loseOnTime flag at the beginning of a new game
408 if (button_was_pressed("New Game"))
411 // Read UCI option values
412 TT.set_size(get_option_value_int("Hash"));
413 if (button_was_pressed("Clear Hash"))
416 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
417 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
418 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
419 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
420 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
421 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
422 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
423 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
424 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
425 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
426 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
427 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
429 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
430 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
431 MultiPV = get_option_value_int("MultiPV");
432 Chess960 = get_option_value_bool("UCI_Chess960");
433 UseLogFile = get_option_value_bool("Use Search Log");
436 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
438 read_weights(pos.side_to_move());
440 // Set the number of active threads
441 int newActiveThreads = get_option_value_int("Threads");
442 if (newActiveThreads != TM.active_threads())
444 TM.set_active_threads(newActiveThreads);
445 init_eval(TM.active_threads());
448 // Wake up sleeping threads
449 TM.wake_sleeping_threads();
452 int myTime = time[side_to_move];
453 int myIncrement = increment[side_to_move];
454 if (UseTimeManagement)
456 if (!movesToGo) // Sudden death time control
460 MaxSearchTime = myTime / 30 + myIncrement;
461 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
463 else // Blitz game without increment
465 MaxSearchTime = myTime / 30;
466 AbsoluteMaxSearchTime = myTime / 8;
469 else // (x moves) / (y minutes)
473 MaxSearchTime = myTime / 2;
474 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
478 MaxSearchTime = myTime / Min(movesToGo, 20);
479 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
483 if (get_option_value_bool("Ponder"))
485 MaxSearchTime += MaxSearchTime / 4;
486 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
490 // Set best NodesBetweenPolls interval to avoid lagging under
491 // heavy time pressure.
493 NodesBetweenPolls = Min(MaxNodes, 30000);
494 else if (myTime && myTime < 1000)
495 NodesBetweenPolls = 1000;
496 else if (myTime && myTime < 5000)
497 NodesBetweenPolls = 5000;
499 NodesBetweenPolls = 30000;
501 // Write search information to log file
503 LogFile << "Searching: " << pos.to_fen() << endl
504 << "infinite: " << infinite
505 << " ponder: " << ponder
506 << " time: " << myTime
507 << " increment: " << myIncrement
508 << " moves to go: " << movesToGo << endl;
510 // LSN filtering. Used only for developing purposes, disabled by default
514 // Step 2. If after last move we decided to lose on time, do it now!
515 while (SearchStartTime + myTime + 1000 > get_system_time())
519 // We're ready to start thinking. Call the iterative deepening loop function
520 Value v = id_loop(pos, searchMoves);
524 // Step 1. If this is sudden death game and our position is hopeless,
525 // decide to lose on time.
526 if ( !loseOnTime // If we already lost on time, go to step 3.
536 // Step 3. Now after stepping over the time limit, reset flag for next match.
544 TM.put_threads_to_sleep();
550 /// init_search() is called during startup. It initializes various lookup tables
554 // Init our reduction lookup tables
555 for (int i = 1; i < 64; i++) // i == depth (OnePly = 1)
556 for (int j = 1; j < 64; j++) // j == moveNumber
558 double pvRed = log(double(i)) * log(double(j)) / 3.0;
559 double nonPVRed = log(double(i)) * log(double(j)) / 1.5;
560 ReductionMatrix[PV][i][j] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(OnePly)) : 0);
561 ReductionMatrix[NonPV][i][j] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(OnePly)) : 0);
564 // Init futility margins array
565 for (int i = 0; i < 16; i++) // i == depth (OnePly = 2)
566 for (int j = 0; j < 64; j++) // j == moveNumber
568 // FIXME: test using log instead of BSR
569 FutilityMarginsMatrix[i][j] = (i < 2 ? 0 : 112 * bitScanReverse32(i * i / 2)) - 8 * j + 45;
572 // Init futility move count array
573 for (int i = 0; i < 32; i++) // i == depth (OnePly = 2)
574 FutilityMoveCountArray[i] = 3 + (1 << (3 * i / 8));
578 // SearchStack::init() initializes a search stack. Used at the beginning of a
579 // new search from the root.
580 void SearchStack::init(int ply) {
582 pv[ply] = pv[ply + 1] = MOVE_NONE;
583 currentMove = threatMove = MOVE_NONE;
584 reduction = Depth(0);
588 void SearchStack::initKillers() {
590 mateKiller = MOVE_NONE;
591 for (int i = 0; i < KILLER_MAX; i++)
592 killers[i] = MOVE_NONE;
597 // id_loop() is the main iterative deepening loop. It calls root_search
598 // repeatedly with increasing depth until the allocated thinking time has
599 // been consumed, the user stops the search, or the maximum search depth is
602 Value id_loop(const Position& pos, Move searchMoves[]) {
605 SearchStack ss[PLY_MAX_PLUS_2];
606 Move EasyMove = MOVE_NONE;
607 Value value, alpha = -VALUE_INFINITE, beta = VALUE_INFINITE;
609 // Moves to search are verified, copied, scored and sorted
610 RootMoveList rml(p, searchMoves);
612 // Handle special case of searching on a mate/stale position
613 if (rml.move_count() == 0)
616 wait_for_stop_or_ponderhit();
618 return pos.is_check() ? -VALUE_MATE : VALUE_DRAW;
621 // Print RootMoveList startup scoring to the standard output,
622 // so to output information also for iteration 1.
623 cout << "info depth " << 1
624 << "\ninfo depth " << 1
625 << " score " << value_to_string(rml.get_move_score(0))
626 << " time " << current_search_time()
627 << " nodes " << TM.nodes_searched()
629 << " pv " << rml.get_move(0) << "\n";
635 ValueByIteration[1] = rml.get_move_score(0);
638 // Is one move significantly better than others after initial scoring ?
639 if ( rml.move_count() == 1
640 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
641 EasyMove = rml.get_move(0);
643 // Iterative deepening loop
644 while (Iteration < PLY_MAX)
646 // Initialize iteration
648 BestMoveChangesByIteration[Iteration] = 0;
650 cout << "info depth " << Iteration << endl;
652 // Calculate dynamic aspiration window based on previous iterations
653 if (MultiPV == 1 && Iteration >= 6 && abs(ValueByIteration[Iteration - 1]) < VALUE_KNOWN_WIN)
655 int prevDelta1 = ValueByIteration[Iteration - 1] - ValueByIteration[Iteration - 2];
656 int prevDelta2 = ValueByIteration[Iteration - 2] - ValueByIteration[Iteration - 3];
658 AspirationDelta = Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16);
659 AspirationDelta = (AspirationDelta + 7) / 8 * 8; // Round to match grainSize
661 alpha = Max(ValueByIteration[Iteration - 1] - AspirationDelta, -VALUE_INFINITE);
662 beta = Min(ValueByIteration[Iteration - 1] + AspirationDelta, VALUE_INFINITE);
665 // Search to the current depth, rml is updated and sorted, alpha and beta could change
666 value = root_search(p, ss, rml, &alpha, &beta);
668 // Write PV to transposition table, in case the relevant entries have
669 // been overwritten during the search.
670 TT.insert_pv(p, ss[0].pv);
673 break; // Value cannot be trusted. Break out immediately!
675 //Save info about search result
676 ValueByIteration[Iteration] = value;
678 // Drop the easy move if differs from the new best move
679 if (ss[0].pv[0] != EasyMove)
680 EasyMove = MOVE_NONE;
682 if (UseTimeManagement)
685 bool stopSearch = false;
687 // Stop search early if there is only a single legal move,
688 // we search up to Iteration 6 anyway to get a proper score.
689 if (Iteration >= 6 && rml.move_count() == 1)
692 // Stop search early when the last two iterations returned a mate score
694 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
695 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
698 // Stop search early if one move seems to be much better than the others
699 int64_t nodes = TM.nodes_searched();
701 && EasyMove == ss[0].pv[0]
702 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
703 && current_search_time() > MaxSearchTime / 16)
704 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
705 && current_search_time() > MaxSearchTime / 32)))
708 // Add some extra time if the best move has changed during the last two iterations
709 if (Iteration > 5 && Iteration <= 50)
710 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
711 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
713 // Stop search if most of MaxSearchTime is consumed at the end of the
714 // iteration. We probably don't have enough time to search the first
715 // move at the next iteration anyway.
716 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
722 StopOnPonderhit = true;
728 if (MaxDepth && Iteration >= MaxDepth)
732 // If we are pondering or in infinite search, we shouldn't print the
733 // best move before we are told to do so.
734 if (!AbortSearch && (PonderSearch || InfiniteSearch))
735 wait_for_stop_or_ponderhit();
737 // Print final search statistics
738 cout << "info nodes " << TM.nodes_searched()
740 << " time " << current_search_time()
741 << " hashfull " << TT.full() << endl;
743 // Print the best move and the ponder move to the standard output
744 if (ss[0].pv[0] == MOVE_NONE)
746 ss[0].pv[0] = rml.get_move(0);
747 ss[0].pv[1] = MOVE_NONE;
750 assert(ss[0].pv[0] != MOVE_NONE);
752 cout << "bestmove " << ss[0].pv[0];
754 if (ss[0].pv[1] != MOVE_NONE)
755 cout << " ponder " << ss[0].pv[1];
762 dbg_print_mean(LogFile);
764 if (dbg_show_hit_rate)
765 dbg_print_hit_rate(LogFile);
767 LogFile << "\nNodes: " << TM.nodes_searched()
768 << "\nNodes/second: " << nps()
769 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
772 p.do_move(ss[0].pv[0], st);
773 LogFile << "\nPonder move: "
774 << move_to_san(p, ss[0].pv[1]) // Works also with MOVE_NONE
777 return rml.get_move_score(0);
781 // root_search() is the function which searches the root node. It is
782 // similar to search_pv except that it uses a different move ordering
783 // scheme, prints some information to the standard output and handles
784 // the fail low/high loops.
786 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value* alphaPtr, Value* betaPtr) {
793 Depth depth, ext, newDepth;
794 Value value, alpha, beta;
795 bool isCheck, moveIsCheck, captureOrPromotion, dangerous;
796 int researchCountFH, researchCountFL;
798 researchCountFH = researchCountFL = 0;
801 isCheck = pos.is_check();
803 // Step 1. Initialize node and poll (omitted at root, but I can see no good reason for this, FIXME)
804 // Step 2. Check for aborted search (omitted at root, because we do not initialize root node)
805 // Step 3. Mate distance pruning (omitted at root)
806 // Step 4. Transposition table lookup (omitted at root)
808 // Step 5. Evaluate the position statically
809 // At root we do this only to get reference value for child nodes
811 ss[0].eval = evaluate(pos, ei, 0);
813 ss[0].eval = VALUE_NONE; // HACK because we do not initialize root node
815 // Step 6. Razoring (omitted at root)
816 // Step 7. Static null move pruning (omitted at root)
817 // Step 8. Null move search with verification search (omitted at root)
818 // Step 9. Internal iterative deepening (omitted at root)
820 // Step extra. Fail low loop
821 // We start with small aspiration window and in case of fail low, we research
822 // with bigger window until we are not failing low anymore.
825 // Sort the moves before to (re)search
828 // Step 10. Loop through all moves in the root move list
829 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
831 // This is used by time management
832 FirstRootMove = (i == 0);
834 // Save the current node count before the move is searched
835 nodes = TM.nodes_searched();
837 // Reset beta cut-off counters
838 TM.resetBetaCounters();
840 // Pick the next root move, and print the move and the move number to
841 // the standard output.
842 move = ss[0].currentMove = rml.get_move(i);
844 if (current_search_time() >= 1000)
845 cout << "info currmove " << move
846 << " currmovenumber " << i + 1 << endl;
848 moveIsCheck = pos.move_is_check(move);
849 captureOrPromotion = pos.move_is_capture_or_promotion(move);
851 // Step 11. Decide the new search depth
852 depth = (Iteration - 2) * OnePly + InitialDepth;
853 ext = extension<PV>(pos, move, captureOrPromotion, moveIsCheck, false, false, &dangerous);
854 newDepth = depth + ext;
856 // Step 12. Futility pruning (omitted at root)
858 // Step extra. Fail high loop
859 // If move fails high, we research with bigger window until we are not failing
861 value = - VALUE_INFINITE;
865 // Step 13. Make the move
866 pos.do_move(move, st, ci, moveIsCheck);
868 // Step extra. pv search
869 // We do pv search for first moves (i < MultiPV)
870 // and for fail high research (value > alpha)
871 if (i < MultiPV || value > alpha)
873 // Aspiration window is disabled in multi-pv case
875 alpha = -VALUE_INFINITE;
877 // Full depth PV search, done on first move or after a fail high
878 value = -search<PV>(pos, ss, -beta, -alpha, newDepth, 1, false, 0);
882 // Step 14. Reduced search
883 // if the move fails high will be re-searched at full depth
884 bool doFullDepthSearch = true;
886 if ( depth >= 3 * OnePly
888 && !captureOrPromotion
889 && !move_is_castle(move))
891 ss[0].reduction = reduction<PV>(depth, i - MultiPV + 2);
894 // Reduced depth non-pv search using alpha as upperbound
895 value = -search<NonPV>(pos, ss, -(alpha+1), -alpha, newDepth-ss[0].reduction, 1, true, 0);
896 doFullDepthSearch = (value > alpha);
900 // Step 15. Full depth search
901 if (doFullDepthSearch)
903 // Full depth non-pv search using alpha as upperbound
904 ss[0].reduction = Depth(0);
905 value = -search<NonPV>(pos, ss, -(alpha+1), -alpha, newDepth, 1, true, 0);
907 // If we are above alpha then research at same depth but as PV
908 // to get a correct score or eventually a fail high above beta.
910 value = -search<PV>(pos, ss, -beta, -alpha, newDepth, 1, false, 0);
914 // Step 16. Undo move
917 // Can we exit fail high loop ?
918 if (AbortSearch || value < beta)
921 // We are failing high and going to do a research. It's important to update
922 // the score before research in case we run out of time while researching.
923 rml.set_move_score(i, value);
925 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
926 rml.set_move_pv(i, ss[0].pv);
928 // Print information to the standard output
929 print_pv_info(pos, ss, alpha, beta, value);
931 // Prepare for a research after a fail high, each time with a wider window
932 *betaPtr = beta = Min(beta + AspirationDelta * (1 << researchCountFH), VALUE_INFINITE);
935 } // End of fail high loop
937 // Finished searching the move. If AbortSearch is true, the search
938 // was aborted because the user interrupted the search or because we
939 // ran out of time. In this case, the return value of the search cannot
940 // be trusted, and we break out of the loop without updating the best
945 // Remember beta-cutoff and searched nodes counts for this move. The
946 // info is used to sort the root moves for the next iteration.
948 TM.get_beta_counters(pos.side_to_move(), our, their);
949 rml.set_beta_counters(i, our, their);
950 rml.set_move_nodes(i, TM.nodes_searched() - nodes);
952 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
953 assert(value < beta);
955 // Step 17. Check for new best move
956 if (value <= alpha && i >= MultiPV)
957 rml.set_move_score(i, -VALUE_INFINITE);
960 // PV move or new best move!
963 rml.set_move_score(i, value);
965 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
966 rml.set_move_pv(i, ss[0].pv);
970 // We record how often the best move has been changed in each
971 // iteration. This information is used for time managment: When
972 // the best move changes frequently, we allocate some more time.
974 BestMoveChangesByIteration[Iteration]++;
976 // Print information to the standard output
977 print_pv_info(pos, ss, alpha, beta, value);
979 // Raise alpha to setup proper non-pv search upper bound
986 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
988 cout << "info multipv " << j + 1
989 << " score " << value_to_string(rml.get_move_score(j))
990 << " depth " << (j <= i ? Iteration : Iteration - 1)
991 << " time " << current_search_time()
992 << " nodes " << TM.nodes_searched()
996 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
997 cout << rml.get_move_pv(j, k) << " ";
1001 alpha = rml.get_move_score(Min(i, MultiPV - 1));
1003 } // PV move or new best move
1005 assert(alpha >= *alphaPtr);
1007 AspirationFailLow = (alpha == *alphaPtr);
1009 if (AspirationFailLow && StopOnPonderhit)
1010 StopOnPonderhit = false;
1013 // Can we exit fail low loop ?
1014 if (AbortSearch || !AspirationFailLow)
1017 // Prepare for a research after a fail low, each time with a wider window
1018 *alphaPtr = alpha = Max(alpha - AspirationDelta * (1 << researchCountFL), -VALUE_INFINITE);
1023 // Sort the moves before to return
1030 // search<>() is the main search function for both PV and non-PV nodes
1032 template <NodeType PvNode>
1033 Value search(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth,
1034 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1036 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1037 assert(beta > alpha && beta <= VALUE_INFINITE);
1038 assert(PvNode || alpha == beta - 1);
1039 assert(ply >= 0 && ply < PLY_MAX);
1040 assert(threadID >= 0 && threadID < TM.active_threads());
1042 Move movesSearched[256];
1047 Depth ext, newDepth;
1048 Value bestValue, value, oldAlpha;
1049 Value refinedValue, nullValue, futilityValueScaled; // Non-PV specific
1050 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1051 bool mateThreat = false;
1053 refinedValue = bestValue = value = -VALUE_INFINITE;
1057 return qsearch<PvNode>(pos, ss, alpha, beta, Depth(0), ply, threadID);
1059 // Step 1. Initialize node and poll
1060 // Polling can abort search.
1061 init_node(ss, ply, threadID);
1063 // Step 2. Check for aborted search and immediate draw
1064 if (AbortSearch || TM.thread_should_stop(threadID))
1067 if (pos.is_draw() || ply >= PLY_MAX - 1)
1070 // Step 3. Mate distance pruning
1071 alpha = Max(value_mated_in(ply), alpha);
1072 beta = Min(value_mate_in(ply+1), beta);
1076 // Step 4. Transposition table lookup
1078 // We don't want the score of a partial search to overwrite a previous full search
1079 // TT value, so we use a different position key in case of an excluded move exists.
1080 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1082 tte = TT.retrieve(posKey);
1083 ttMove = (tte ? tte->move() : MOVE_NONE);
1085 // At PV nodes, we don't use the TT for pruning, but only for move ordering.
1086 // This is to avoid problems in the following areas:
1088 // * Repetition draw detection
1089 // * Fifty move rule detection
1090 // * Searching for a mate
1091 // * Printing of full PV line
1093 if (!PvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1095 // Refresh tte entry to avoid aging
1096 TT.store(posKey, tte->value(), tte->type(), tte->depth(), ttMove);
1098 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1099 return value_from_tt(tte->value(), ply);
1102 // Step 5. Evaluate the position statically
1103 // At PV nodes we do this only to update gain statistics
1104 isCheck = pos.is_check();
1107 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1108 ss[ply].eval = value_from_tt(tte->value(), ply);
1110 ss[ply].eval = evaluate(pos, ei, threadID);
1112 refinedValue = refine_eval(tte, ss[ply].eval, ply); // Enhance accuracy with TT value if possible
1113 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1116 // Step 6. Razoring (is omitted in PV nodes)
1118 && refinedValue < beta - razor_margin(depth)
1119 && ttMove == MOVE_NONE
1120 && ss[ply - 1].currentMove != MOVE_NULL
1121 && depth < RazorDepth
1123 && !value_is_mate(beta)
1124 && !pos.has_pawn_on_7th(pos.side_to_move()))
1126 Value rbeta = beta - razor_margin(depth);
1127 Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1129 // Logically we should return (v + razor_margin(depth)), but
1130 // surprisingly this did slightly weaker in tests.
1134 // Step 7. Static null move pruning (is omitted in PV nodes)
1135 // We're betting that the opponent doesn't have a move that will reduce
1136 // the score by more than futility_margin(depth) if we do a null move.
1139 && depth < RazorDepth
1141 && !value_is_mate(beta)
1142 && ok_to_do_nullmove(pos)
1143 && refinedValue >= beta + futility_margin(depth, 0))
1144 return refinedValue - futility_margin(depth, 0);
1146 // Step 8. Null move search with verification search (is omitted in PV nodes)
1147 // When we jump directly to qsearch() we do a null move only if static value is
1148 // at least beta. Otherwise we do a null move if static value is not more than
1149 // NullMoveMargin under beta.
1154 && !value_is_mate(beta)
1155 && ok_to_do_nullmove(pos)
1156 && refinedValue >= beta - (depth >= 4 * OnePly ? NullMoveMargin : 0))
1158 ss[ply].currentMove = MOVE_NULL;
1160 // Null move dynamic reduction based on depth
1161 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1163 // Null move dynamic reduction based on value
1164 if (refinedValue - beta > PawnValueMidgame)
1167 pos.do_null_move(st);
1169 nullValue = -search<NonPV>(pos, ss, -beta, -alpha, depth-R*OnePly, ply+1, false, threadID);
1171 pos.undo_null_move();
1173 if (nullValue >= beta)
1175 // Do not return unproven mate scores
1176 if (nullValue >= value_mate_in(PLY_MAX))
1179 if (depth < 6 * OnePly)
1182 // Do zugzwang verification search
1183 Value v = search<NonPV>(pos, ss, alpha, beta, depth-5*OnePly, ply, false, threadID);
1187 // The null move failed low, which means that we may be faced with
1188 // some kind of threat. If the previous move was reduced, check if
1189 // the move that refuted the null move was somehow connected to the
1190 // move which was reduced. If a connection is found, return a fail
1191 // low score (which will cause the reduced move to fail high in the
1192 // parent node, which will trigger a re-search with full depth).
1193 if (nullValue == value_mated_in(ply + 2))
1196 ss[ply].threatMove = ss[ply + 1].currentMove;
1197 if ( depth < ThreatDepth
1198 && ss[ply - 1].reduction
1199 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1204 // Step 9. Internal iterative deepening
1205 if ( depth >= IIDDepth[PvNode]
1206 && ttMove == MOVE_NONE
1207 && (PvNode || (!isCheck && ss[ply].eval >= beta - IIDMargin)))
1209 Depth d = (PvNode ? depth - 2 * OnePly : depth / 2);
1210 search<PvNode>(pos, ss, alpha, beta, d, ply, false, threadID);
1211 ttMove = ss[ply].pv[ply];
1212 tte = TT.retrieve(posKey);
1215 // Expensive mate threat detection (only for PV nodes)
1217 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1219 // Initialize a MovePicker object for the current position
1220 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply], (PvNode ? -VALUE_INFINITE : beta));
1223 // Step 10. Loop through moves
1224 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1225 while ( bestValue < beta
1226 && (move = mp.get_next_move()) != MOVE_NONE
1227 && !TM.thread_should_stop(threadID))
1229 assert(move_is_ok(move));
1231 if (move == excludedMove)
1234 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1235 moveIsCheck = pos.move_is_check(move, ci);
1236 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1238 // Step 11. Decide the new search depth
1239 ext = extension<PvNode>(pos, move, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1241 // Singular extension search. We extend the TT move if its value is much better than
1242 // its siblings. To verify this we do a reduced search on all the other moves but the
1243 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1244 if ( depth >= SingularExtensionDepth[PvNode]
1246 && move == tte->move()
1247 && !excludedMove // Do not allow recursive singular extension search
1249 && is_lower_bound(tte->type())
1250 && tte->depth() >= depth - 3 * OnePly)
1252 Value ttValue = value_from_tt(tte->value(), ply);
1254 if (abs(ttValue) < VALUE_KNOWN_WIN)
1256 Value b = ttValue - SingularExtensionMargin;
1257 Value v = search<NonPV>(pos, ss, b - 1, b, depth / 2, ply, false, threadID, move);
1259 if (v < ttValue - SingularExtensionMargin)
1264 newDepth = depth - OnePly + ext;
1266 // Update current move (this must be done after singular extension search)
1267 movesSearched[moveCount++] = ss[ply].currentMove = move;
1269 // Step 12. Futility pruning (is omitted in PV nodes)
1273 && !captureOrPromotion
1274 && !move_is_castle(move)
1277 // Move count based pruning
1278 if ( moveCount >= futility_move_count(depth)
1279 && ok_to_prune(pos, move, ss[ply].threatMove)
1280 && bestValue > value_mated_in(PLY_MAX))
1283 // Value based pruning
1284 Depth predictedDepth = newDepth - reduction<NonPV>(depth, moveCount); // FIXME We illogically ignore reduction condition depth >= 3*OnePly
1285 futilityValueScaled = ss[ply].eval + futility_margin(predictedDepth, moveCount)
1286 + H.gain(pos.piece_on(move_from(move)), move_to(move));
1288 if (futilityValueScaled < beta)
1290 if (futilityValueScaled > bestValue)
1291 bestValue = futilityValueScaled;
1296 // Step 13. Make the move
1297 pos.do_move(move, st, ci, moveIsCheck);
1299 // Step extra. pv search (only in PV nodes)
1300 // The first move in list is the expected PV
1301 if (PvNode && moveCount == 1)
1302 value = -search<PV>(pos, ss, -beta, -alpha, newDepth, ply+1, false, threadID);
1305 // Step 14. Reduced search
1306 // if the move fails high will be re-searched at full depth.
1307 bool doFullDepthSearch = true;
1309 if ( depth >= 3 * OnePly
1311 && !captureOrPromotion
1312 && !move_is_castle(move)
1313 && !move_is_killer(move, ss[ply]))
1315 ss[ply].reduction = reduction<PvNode>(depth, moveCount);
1316 if (ss[ply].reduction)
1318 value = -search<NonPV>(pos, ss, -(alpha+1), -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1319 doFullDepthSearch = (value > alpha);
1323 // Step 15. Full depth search
1324 if (doFullDepthSearch)
1326 ss[ply].reduction = Depth(0);
1327 value = -search<NonPV>(pos, ss, -(alpha+1), -alpha, newDepth, ply+1, true, threadID);
1329 // Step extra. pv search (only in PV nodes)
1330 // Search only for possible new PV nodes, if instead value >= beta then
1331 // parent node fails low with value <= alpha and tries another move.
1332 if (PvNode && value > alpha && value < beta)
1333 value = -search<PV>(pos, ss, -beta, -alpha, newDepth, ply+1, false, threadID);
1337 // Step 16. Undo move
1338 pos.undo_move(move);
1340 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1342 // Step 17. Check for new best move
1343 if (value > bestValue)
1348 if (PvNode && value < beta) // This guarantees that always: alpha < beta
1352 if (value == value_mate_in(ply + 1))
1353 ss[ply].mateKiller = move;
1357 // Step 18. Check for split
1358 if ( TM.active_threads() > 1
1360 && depth >= MinimumSplitDepth
1362 && TM.available_thread_exists(threadID)
1364 && !TM.thread_should_stop(threadID)
1365 && TM.split<false>(pos, ss, ply, &alpha, beta, &bestValue,
1366 depth, mateThreat, &moveCount, &mp, threadID, PvNode))
1369 // Uncomment to debug sp_search() in single thread mode
1371 if ( bestValue < beta
1375 && !TM.thread_should_stop(threadID)
1376 && TM.split<true>(pos, ss, ply, &alpha, beta, &bestValue,
1377 depth, mateThreat, &moveCount, &mp, threadID, PvNode))
1382 // Step 19. Check for mate and stalemate
1383 // All legal moves have been searched and if there are
1384 // no legal moves, it must be mate or stalemate.
1385 // If one move was excluded return fail low score.
1387 return excludedMove ? oldAlpha : (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1389 // Step 20. Update tables
1390 // If the search is not aborted, update the transposition table,
1391 // history counters, and killer moves.
1392 if (AbortSearch || TM.thread_should_stop(threadID))
1395 if (bestValue <= oldAlpha)
1396 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1398 else if (bestValue >= beta)
1400 TM.incrementBetaCounter(pos.side_to_move(), depth, threadID);
1401 move = ss[ply].pv[ply];
1402 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1403 if (!pos.move_is_capture_or_promotion(move))
1405 update_history(pos, move, depth, movesSearched, moveCount);
1406 update_killers(move, ss[ply]);
1410 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1412 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1418 // qsearch() is the quiescence search function, which is called by the main
1419 // search function when the remaining depth is zero (or, to be more precise,
1420 // less than OnePly).
1422 template <NodeType PvNode>
1423 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1424 Depth depth, int ply, int threadID) {
1426 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1427 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1428 assert(PvNode || alpha == beta - 1);
1430 assert(ply >= 0 && ply < PLY_MAX);
1431 assert(threadID >= 0 && threadID < TM.active_threads());
1436 Value staticValue, bestValue, value, futilityBase, futilityValue;
1437 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1438 const TTEntry* tte = NULL;
1440 Value oldAlpha = alpha;
1442 // Initialize, and make an early exit in case of an aborted search,
1443 // an instant draw, maximum ply reached, etc.
1444 init_node(ss, ply, threadID);
1446 // After init_node() that calls poll()
1447 if (AbortSearch || TM.thread_should_stop(threadID))
1450 if (pos.is_draw() || ply >= PLY_MAX - 1)
1453 // Transposition table lookup. At PV nodes, we don't use the TT for
1454 // pruning, but only for move ordering.
1455 tte = TT.retrieve(pos.get_key());
1456 ttMove = (tte ? tte->move() : MOVE_NONE);
1458 if (!PvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1460 assert(tte->type() != VALUE_TYPE_EVAL);
1462 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1463 return value_from_tt(tte->value(), ply);
1466 isCheck = pos.is_check();
1468 // Evaluate the position statically
1470 staticValue = -VALUE_INFINITE;
1471 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1472 staticValue = value_from_tt(tte->value(), ply);
1474 staticValue = evaluate(pos, ei, threadID);
1478 ss[ply].eval = staticValue;
1479 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1482 // Initialize "stand pat score", and return it immediately if it is
1484 bestValue = staticValue;
1486 if (bestValue >= beta)
1488 // Store the score to avoid a future costly evaluation() call
1489 if (!isCheck && !tte && ei.kingDanger[pos.side_to_move()] == 0)
1490 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1495 if (bestValue > alpha)
1498 // If we are near beta then try to get a cutoff pushing checks a bit further
1499 bool deepChecks = (depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8);
1501 // Initialize a MovePicker object for the current position, and prepare
1502 // to search the moves. Because the depth is <= 0 here, only captures,
1503 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1504 // and we are near beta) will be generated.
1505 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1507 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1508 futilityBase = staticValue + FutilityMarginQS + ei.kingDanger[pos.side_to_move()];
1510 // Loop through the moves until no moves remain or a beta cutoff occurs
1511 while ( alpha < beta
1512 && (move = mp.get_next_move()) != MOVE_NONE)
1514 assert(move_is_ok(move));
1516 moveIsCheck = pos.move_is_check(move, ci);
1518 // Update current move
1520 ss[ply].currentMove = move;
1528 && !move_is_promotion(move)
1529 && !pos.move_is_passed_pawn_push(move))
1531 futilityValue = futilityBase
1532 + pos.endgame_value_of_piece_on(move_to(move))
1533 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1535 if (futilityValue < alpha)
1537 if (futilityValue > bestValue)
1538 bestValue = futilityValue;
1543 // Detect blocking evasions that are candidate to be pruned
1544 evasionPrunable = isCheck
1545 && bestValue > value_mated_in(PLY_MAX)
1546 && !pos.move_is_capture(move)
1547 && pos.type_of_piece_on(move_from(move)) != KING
1548 && !pos.can_castle(pos.side_to_move());
1550 // Don't search moves with negative SEE values
1552 && (!isCheck || evasionPrunable)
1554 && !move_is_promotion(move)
1555 && pos.see_sign(move) < 0)
1558 // Make and search the move
1559 pos.do_move(move, st, ci, moveIsCheck);
1560 value = -qsearch<PvNode>(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1561 pos.undo_move(move);
1563 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1566 if (value > bestValue)
1577 // All legal moves have been searched. A special case: If we're in check
1578 // and no legal moves were found, it is checkmate.
1579 if (!moveCount && isCheck) // Mate!
1580 return value_mated_in(ply);
1582 // Update transposition table
1583 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1584 if (bestValue <= oldAlpha)
1586 // If bestValue isn't changed it means it is still the static evaluation
1587 // of the node, so keep this info to avoid a future evaluation() call.
1588 ValueType type = (bestValue == staticValue && !ei.kingDanger[pos.side_to_move()] ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1589 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1591 else if (bestValue >= beta)
1593 move = ss[ply].pv[ply];
1594 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1596 // Update killers only for good checking moves
1597 if (!pos.move_is_capture_or_promotion(move))
1598 update_killers(move, ss[ply]);
1601 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, d, ss[ply].pv[ply]);
1603 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1609 // sp_search() is used to search from a split point. This function is called
1610 // by each thread working at the split point. It is similar to the normal
1611 // search() function, but simpler. Because we have already probed the hash
1612 // table, done a null move search, and searched the first move before
1613 // splitting, we don't have to repeat all this work in sp_search(). We
1614 // also don't need to store anything to the hash table here: This is taken
1615 // care of after we return from the split point.
1617 template <NodeType PvNode>
1618 void sp_search(SplitPoint* sp, int threadID) {
1620 assert(threadID >= 0 && threadID < TM.active_threads());
1624 Depth ext, newDepth;
1626 Value futilityValueScaled; // NonPV specific
1627 bool isCheck, moveIsCheck, captureOrPromotion, dangerous;
1629 value = -VALUE_INFINITE;
1631 Position pos(*sp->pos);
1633 SearchStack* ss = sp->sstack[threadID];
1634 isCheck = pos.is_check();
1636 // Step 10. Loop through moves
1637 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1638 lock_grab(&(sp->lock));
1640 while ( sp->bestValue < sp->beta
1641 && !TM.thread_should_stop(threadID)
1642 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1644 moveCount = ++sp->moves;
1645 lock_release(&(sp->lock));
1647 assert(move_is_ok(move));
1649 moveIsCheck = pos.move_is_check(move, ci);
1650 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1652 // Step 11. Decide the new search depth
1653 ext = extension<PvNode>(pos, move, captureOrPromotion, moveIsCheck, false, sp->mateThreat, &dangerous);
1654 newDepth = sp->depth - OnePly + ext;
1656 // Update current move
1657 ss[sp->ply].currentMove = move;
1659 // Step 12. Futility pruning (is omitted in PV nodes)
1663 && !captureOrPromotion
1664 && !move_is_castle(move))
1666 // Move count based pruning
1667 if ( moveCount >= futility_move_count(sp->depth)
1668 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1669 && sp->bestValue > value_mated_in(PLY_MAX))
1671 lock_grab(&(sp->lock));
1675 // Value based pruning
1676 Depth predictedDepth = newDepth - reduction<NonPV>(sp->depth, moveCount);
1677 futilityValueScaled = ss[sp->ply].eval + futility_margin(predictedDepth, moveCount)
1678 + H.gain(pos.piece_on(move_from(move)), move_to(move));
1680 if (futilityValueScaled < sp->beta)
1682 lock_grab(&(sp->lock));
1684 if (futilityValueScaled > sp->bestValue)
1685 sp->bestValue = futilityValueScaled;
1690 // Step 13. Make the move
1691 pos.do_move(move, st, ci, moveIsCheck);
1693 // Step 14. Reduced search
1694 // if the move fails high will be re-searched at full depth.
1695 bool doFullDepthSearch = true;
1698 && !captureOrPromotion
1699 && !move_is_castle(move)
1700 && !move_is_killer(move, ss[sp->ply]))
1702 ss[sp->ply].reduction = reduction<PvNode>(sp->depth, moveCount);
1703 if (ss[sp->ply].reduction)
1705 Value localAlpha = sp->alpha;
1706 value = -search<NonPV>(pos, ss, -(localAlpha+1), -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1707 doFullDepthSearch = (value > localAlpha && !TM.thread_should_stop(threadID));
1711 // Step 15. Full depth search
1712 if (doFullDepthSearch)
1714 ss[sp->ply].reduction = Depth(0);
1715 Value localAlpha = sp->alpha;
1716 value = -search<NonPV>(pos, ss, -(localAlpha+1), -localAlpha, newDepth, sp->ply+1, true, threadID);
1718 if (PvNode && value > localAlpha && value < sp->beta && !TM.thread_should_stop(threadID))
1719 value = -search<PV>(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, false, threadID);
1722 // Step 16. Undo move
1723 pos.undo_move(move);
1725 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1727 // Step 17. Check for new best move
1728 lock_grab(&(sp->lock));
1730 if (value > sp->bestValue && !TM.thread_should_stop(threadID))
1732 sp->bestValue = value;
1734 if (sp->bestValue > sp->alpha)
1736 if (!PvNode || value >= sp->beta)
1737 sp->stopRequest = true;
1739 if (PvNode && value < sp->beta) // This guarantees that always: sp->alpha < sp->beta
1742 sp_update_pv(sp->parentSstack, ss, sp->ply);
1744 if (PvNode && value == value_mate_in(sp->ply + 1))
1745 ss[sp->ply].mateKiller = move;
1750 /* Here we have the lock still grabbed */
1752 sp->slaves[threadID] = 0;
1755 lock_release(&(sp->lock));
1758 // init_node() is called at the beginning of all the search functions
1759 // (search() qsearch(), and so on) and initializes the
1760 // search stack object corresponding to the current node. Once every
1761 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1762 // for user input and checks whether it is time to stop the search.
1764 void init_node(SearchStack ss[], int ply, int threadID) {
1766 assert(ply >= 0 && ply < PLY_MAX);
1767 assert(threadID >= 0 && threadID < TM.active_threads());
1769 TM.incrementNodeCounter(threadID);
1774 if (NodesSincePoll >= NodesBetweenPolls)
1781 ss[ply + 2].initKillers();
1786 // update_pv() is called whenever a search returns a value > alpha.
1787 // It updates the PV in the SearchStack object corresponding to the
1790 void update_pv(SearchStack ss[], int ply) {
1792 assert(ply >= 0 && ply < PLY_MAX);
1796 ss[ply].pv[ply] = ss[ply].currentMove;
1798 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
1799 ss[ply].pv[p] = ss[ply + 1].pv[p];
1801 ss[ply].pv[p] = MOVE_NONE;
1805 // sp_update_pv() is a variant of update_pv for use at split points. The
1806 // difference between the two functions is that sp_update_pv also updates
1807 // the PV at the parent node.
1809 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
1811 assert(ply >= 0 && ply < PLY_MAX);
1815 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1817 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
1818 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
1820 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1824 // connected_moves() tests whether two moves are 'connected' in the sense
1825 // that the first move somehow made the second move possible (for instance
1826 // if the moving piece is the same in both moves). The first move is assumed
1827 // to be the move that was made to reach the current position, while the
1828 // second move is assumed to be a move from the current position.
1830 bool connected_moves(const Position& pos, Move m1, Move m2) {
1832 Square f1, t1, f2, t2;
1835 assert(move_is_ok(m1));
1836 assert(move_is_ok(m2));
1838 if (m2 == MOVE_NONE)
1841 // Case 1: The moving piece is the same in both moves
1847 // Case 2: The destination square for m2 was vacated by m1
1853 // Case 3: Moving through the vacated square
1854 if ( piece_is_slider(pos.piece_on(f2))
1855 && bit_is_set(squares_between(f2, t2), f1))
1858 // Case 4: The destination square for m2 is defended by the moving piece in m1
1859 p = pos.piece_on(t1);
1860 if (bit_is_set(pos.attacks_from(p, t1), t2))
1863 // Case 5: Discovered check, checking piece is the piece moved in m1
1864 if ( piece_is_slider(p)
1865 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
1866 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
1868 // discovered_check_candidates() works also if the Position's side to
1869 // move is the opposite of the checking piece.
1870 Color them = opposite_color(pos.side_to_move());
1871 Bitboard dcCandidates = pos.discovered_check_candidates(them);
1873 if (bit_is_set(dcCandidates, f2))
1880 // value_is_mate() checks if the given value is a mate one
1881 // eventually compensated for the ply.
1883 bool value_is_mate(Value value) {
1885 assert(abs(value) <= VALUE_INFINITE);
1887 return value <= value_mated_in(PLY_MAX)
1888 || value >= value_mate_in(PLY_MAX);
1892 // move_is_killer() checks if the given move is among the
1893 // killer moves of that ply.
1895 bool move_is_killer(Move m, const SearchStack& ss) {
1897 const Move* k = ss.killers;
1898 for (int i = 0; i < KILLER_MAX; i++, k++)
1906 // extension() decides whether a move should be searched with normal depth,
1907 // or with extended depth. Certain classes of moves (checking moves, in
1908 // particular) are searched with bigger depth than ordinary moves and in
1909 // any case are marked as 'dangerous'. Note that also if a move is not
1910 // extended, as example because the corresponding UCI option is set to zero,
1911 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
1912 template <NodeType PvNode>
1913 Depth extension(const Position& pos, Move m, bool captureOrPromotion, bool moveIsCheck,
1914 bool singleEvasion, bool mateThreat, bool* dangerous) {
1916 assert(m != MOVE_NONE);
1918 Depth result = Depth(0);
1919 *dangerous = moveIsCheck | singleEvasion | mateThreat;
1924 result += CheckExtension[PvNode];
1927 result += SingleEvasionExtension[PvNode];
1930 result += MateThreatExtension[PvNode];
1933 if (pos.type_of_piece_on(move_from(m)) == PAWN)
1935 Color c = pos.side_to_move();
1936 if (relative_rank(c, move_to(m)) == RANK_7)
1938 result += PawnPushTo7thExtension[PvNode];
1941 if (pos.pawn_is_passed(c, move_to(m)))
1943 result += PassedPawnExtension[PvNode];
1948 if ( captureOrPromotion
1949 && pos.type_of_piece_on(move_to(m)) != PAWN
1950 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
1951 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
1952 && !move_is_promotion(m)
1955 result += PawnEndgameExtension[PvNode];
1960 && captureOrPromotion
1961 && pos.type_of_piece_on(move_to(m)) != PAWN
1962 && pos.see_sign(m) >= 0)
1968 return Min(result, OnePly);
1972 // ok_to_do_nullmove() looks at the current position and decides whether
1973 // doing a 'null move' should be allowed. In order to avoid zugzwang
1974 // problems, null moves are not allowed when the side to move has very
1975 // little material left. Currently, the test is a bit too simple: Null
1976 // moves are avoided only when the side to move has only pawns left.
1977 // It's probably a good idea to avoid null moves in at least some more
1978 // complicated endgames, e.g. KQ vs KR. FIXME
1980 bool ok_to_do_nullmove(const Position& pos) {
1982 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
1986 // ok_to_prune() tests whether it is safe to forward prune a move. Only
1987 // non-tactical moves late in the move list close to the leaves are
1988 // candidates for pruning.
1990 bool ok_to_prune(const Position& pos, Move m, Move threat) {
1992 assert(move_is_ok(m));
1993 assert(threat == MOVE_NONE || move_is_ok(threat));
1994 assert(!pos.move_is_check(m));
1995 assert(!pos.move_is_capture_or_promotion(m));
1996 assert(!pos.move_is_passed_pawn_push(m));
1998 Square mfrom, mto, tfrom, tto;
2000 // Prune if there isn't any threat move
2001 if (threat == MOVE_NONE)
2004 mfrom = move_from(m);
2006 tfrom = move_from(threat);
2007 tto = move_to(threat);
2009 // Case 1: Don't prune moves which move the threatened piece
2013 // Case 2: If the threatened piece has value less than or equal to the
2014 // value of the threatening piece, don't prune move which defend it.
2015 if ( pos.move_is_capture(threat)
2016 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2017 || pos.type_of_piece_on(tfrom) == KING)
2018 && pos.move_attacks_square(m, tto))
2021 // Case 3: If the moving piece in the threatened move is a slider, don't
2022 // prune safe moves which block its ray.
2023 if ( piece_is_slider(pos.piece_on(tfrom))
2024 && bit_is_set(squares_between(tfrom, tto), mto)
2025 && pos.see_sign(m) >= 0)
2032 // ok_to_use_TT() returns true if a transposition table score
2033 // can be used at a given point in search.
2035 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2037 Value v = value_from_tt(tte->value(), ply);
2039 return ( tte->depth() >= depth
2040 || v >= Max(value_mate_in(PLY_MAX), beta)
2041 || v < Min(value_mated_in(PLY_MAX), beta))
2043 && ( (is_lower_bound(tte->type()) && v >= beta)
2044 || (is_upper_bound(tte->type()) && v < beta));
2048 // refine_eval() returns the transposition table score if
2049 // possible otherwise falls back on static position evaluation.
2051 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2056 Value v = value_from_tt(tte->value(), ply);
2058 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2059 || (is_upper_bound(tte->type()) && v < defaultEval))
2066 // update_history() registers a good move that produced a beta-cutoff
2067 // in history and marks as failures all the other moves of that ply.
2069 void update_history(const Position& pos, Move move, Depth depth,
2070 Move movesSearched[], int moveCount) {
2074 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2076 for (int i = 0; i < moveCount - 1; i++)
2078 m = movesSearched[i];
2082 if (!pos.move_is_capture_or_promotion(m))
2083 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2088 // update_killers() add a good move that produced a beta-cutoff
2089 // among the killer moves of that ply.
2091 void update_killers(Move m, SearchStack& ss) {
2093 if (m == ss.killers[0])
2096 for (int i = KILLER_MAX - 1; i > 0; i--)
2097 ss.killers[i] = ss.killers[i - 1];
2103 // update_gains() updates the gains table of a non-capture move given
2104 // the static position evaluation before and after the move.
2106 void update_gains(const Position& pos, Move m, Value before, Value after) {
2109 && before != VALUE_NONE
2110 && after != VALUE_NONE
2111 && pos.captured_piece() == NO_PIECE_TYPE
2112 && !move_is_castle(m)
2113 && !move_is_promotion(m))
2114 H.set_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
2118 // current_search_time() returns the number of milliseconds which have passed
2119 // since the beginning of the current search.
2121 int current_search_time() {
2123 return get_system_time() - SearchStartTime;
2127 // nps() computes the current nodes/second count.
2131 int t = current_search_time();
2132 return (t > 0 ? int((TM.nodes_searched() * 1000) / t) : 0);
2136 // poll() performs two different functions: It polls for user input, and it
2137 // looks at the time consumed so far and decides if it's time to abort the
2142 static int lastInfoTime;
2143 int t = current_search_time();
2148 // We are line oriented, don't read single chars
2149 std::string command;
2151 if (!std::getline(std::cin, command))
2154 if (command == "quit")
2157 PonderSearch = false;
2161 else if (command == "stop")
2164 PonderSearch = false;
2166 else if (command == "ponderhit")
2170 // Print search information
2174 else if (lastInfoTime > t)
2175 // HACK: Must be a new search where we searched less than
2176 // NodesBetweenPolls nodes during the first second of search.
2179 else if (t - lastInfoTime >= 1000)
2186 if (dbg_show_hit_rate)
2187 dbg_print_hit_rate();
2189 cout << "info nodes " << TM.nodes_searched() << " nps " << nps()
2190 << " time " << t << " hashfull " << TT.full() << endl;
2193 // Should we stop the search?
2197 bool stillAtFirstMove = FirstRootMove
2198 && !AspirationFailLow
2199 && t > MaxSearchTime + ExtraSearchTime;
2201 bool noMoreTime = t > AbsoluteMaxSearchTime
2202 || stillAtFirstMove;
2204 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2205 || (ExactMaxTime && t >= ExactMaxTime)
2206 || (Iteration >= 3 && MaxNodes && TM.nodes_searched() >= MaxNodes))
2211 // ponderhit() is called when the program is pondering (i.e. thinking while
2212 // it's the opponent's turn to move) in order to let the engine know that
2213 // it correctly predicted the opponent's move.
2217 int t = current_search_time();
2218 PonderSearch = false;
2220 bool stillAtFirstMove = FirstRootMove
2221 && !AspirationFailLow
2222 && t > MaxSearchTime + ExtraSearchTime;
2224 bool noMoreTime = t > AbsoluteMaxSearchTime
2225 || stillAtFirstMove;
2227 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2232 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2234 void init_ss_array(SearchStack ss[]) {
2236 for (int i = 0; i < 3; i++)
2239 ss[i].initKillers();
2244 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2245 // while the program is pondering. The point is to work around a wrinkle in
2246 // the UCI protocol: When pondering, the engine is not allowed to give a
2247 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2248 // We simply wait here until one of these commands is sent, and return,
2249 // after which the bestmove and pondermove will be printed (in id_loop()).
2251 void wait_for_stop_or_ponderhit() {
2253 std::string command;
2257 if (!std::getline(std::cin, command))
2260 if (command == "quit")
2265 else if (command == "ponderhit" || command == "stop")
2271 // print_pv_info() prints to standard output and eventually to log file information on
2272 // the current PV line. It is called at each iteration or after a new pv is found.
2274 void print_pv_info(const Position& pos, SearchStack ss[], Value alpha, Value beta, Value value) {
2276 cout << "info depth " << Iteration
2277 << " score " << value_to_string(value)
2278 << ((value >= beta) ? " lowerbound" :
2279 ((value <= alpha)? " upperbound" : ""))
2280 << " time " << current_search_time()
2281 << " nodes " << TM.nodes_searched()
2285 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
2286 cout << ss[0].pv[j] << " ";
2292 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
2293 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
2295 LogFile << pretty_pv(pos, current_search_time(), Iteration,
2296 TM.nodes_searched(), value, type, ss[0].pv) << endl;
2301 // init_thread() is the function which is called when a new thread is
2302 // launched. It simply calls the idle_loop() function with the supplied
2303 // threadID. There are two versions of this function; one for POSIX
2304 // threads and one for Windows threads.
2306 #if !defined(_MSC_VER)
2308 void* init_thread(void *threadID) {
2310 TM.idle_loop(*(int*)threadID, NULL);
2316 DWORD WINAPI init_thread(LPVOID threadID) {
2318 TM.idle_loop(*(int*)threadID, NULL);
2325 /// The ThreadsManager class
2327 // resetNodeCounters(), resetBetaCounters(), searched_nodes() and
2328 // get_beta_counters() are getters/setters for the per thread
2329 // counters used to sort the moves at root.
2331 void ThreadsManager::resetNodeCounters() {
2333 for (int i = 0; i < MAX_THREADS; i++)
2334 threads[i].nodes = 0ULL;
2337 void ThreadsManager::resetBetaCounters() {
2339 for (int i = 0; i < MAX_THREADS; i++)
2340 threads[i].betaCutOffs[WHITE] = threads[i].betaCutOffs[BLACK] = 0ULL;
2343 int64_t ThreadsManager::nodes_searched() const {
2345 int64_t result = 0ULL;
2346 for (int i = 0; i < ActiveThreads; i++)
2347 result += threads[i].nodes;
2352 void ThreadsManager::get_beta_counters(Color us, int64_t& our, int64_t& their) const {
2355 for (int i = 0; i < MAX_THREADS; i++)
2357 our += threads[i].betaCutOffs[us];
2358 their += threads[i].betaCutOffs[opposite_color(us)];
2363 // idle_loop() is where the threads are parked when they have no work to do.
2364 // The parameter 'sp', if non-NULL, is a pointer to an active SplitPoint
2365 // object for which the current thread is the master.
2367 void ThreadsManager::idle_loop(int threadID, SplitPoint* sp) {
2369 assert(threadID >= 0 && threadID < MAX_THREADS);
2373 // Slave threads can exit as soon as AllThreadsShouldExit raises,
2374 // master should exit as last one.
2375 if (AllThreadsShouldExit)
2378 threads[threadID].state = THREAD_TERMINATED;
2382 // If we are not thinking, wait for a condition to be signaled
2383 // instead of wasting CPU time polling for work.
2384 while (AllThreadsShouldSleep || threadID >= ActiveThreads)
2387 assert(threadID != 0);
2388 threads[threadID].state = THREAD_SLEEPING;
2390 #if !defined(_MSC_VER)
2391 lock_grab(&WaitLock);
2392 if (AllThreadsShouldSleep || threadID >= ActiveThreads)
2393 pthread_cond_wait(&WaitCond, &WaitLock);
2394 lock_release(&WaitLock);
2396 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2400 // If thread has just woken up, mark it as available
2401 if (threads[threadID].state == THREAD_SLEEPING)
2402 threads[threadID].state = THREAD_AVAILABLE;
2404 // If this thread has been assigned work, launch a search
2405 if (threads[threadID].state == THREAD_WORKISWAITING)
2407 assert(!AllThreadsShouldExit && !AllThreadsShouldSleep);
2409 threads[threadID].state = THREAD_SEARCHING;
2411 if (threads[threadID].splitPoint->pvNode)
2412 sp_search<PV>(threads[threadID].splitPoint, threadID);
2414 sp_search<NonPV>(threads[threadID].splitPoint, threadID);
2416 assert(threads[threadID].state == THREAD_SEARCHING);
2418 threads[threadID].state = THREAD_AVAILABLE;
2421 // If this thread is the master of a split point and all threads have
2422 // finished their work at this split point, return from the idle loop.
2423 if (sp && sp->cpus == 0)
2425 // Because sp->cpus is decremented under lock protection,
2426 // be sure sp->lock has been released before to proceed.
2427 lock_grab(&(sp->lock));
2428 lock_release(&(sp->lock));
2430 assert(threads[threadID].state == THREAD_AVAILABLE);
2432 threads[threadID].state = THREAD_SEARCHING;
2439 // init_threads() is called during startup. It launches all helper threads,
2440 // and initializes the split point stack and the global locks and condition
2443 void ThreadsManager::init_threads() {
2448 #if !defined(_MSC_VER)
2449 pthread_t pthread[1];
2452 // Initialize global locks
2453 lock_init(&MPLock, NULL);
2454 lock_init(&WaitLock, NULL);
2456 #if !defined(_MSC_VER)
2457 pthread_cond_init(&WaitCond, NULL);
2459 for (i = 0; i < MAX_THREADS; i++)
2460 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
2463 // Initialize SplitPointStack locks
2464 for (i = 0; i < MAX_THREADS; i++)
2465 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2467 SplitPointStack[i][j].parent = NULL;
2468 lock_init(&(SplitPointStack[i][j].lock), NULL);
2471 // Will be set just before program exits to properly end the threads
2472 AllThreadsShouldExit = false;
2474 // Threads will be put to sleep as soon as created
2475 AllThreadsShouldSleep = true;
2477 // All threads except the main thread should be initialized to THREAD_AVAILABLE
2479 threads[0].state = THREAD_SEARCHING;
2480 for (i = 1; i < MAX_THREADS; i++)
2481 threads[i].state = THREAD_AVAILABLE;
2483 // Launch the helper threads
2484 for (i = 1; i < MAX_THREADS; i++)
2487 #if !defined(_MSC_VER)
2488 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
2490 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, NULL) != NULL);
2495 cout << "Failed to create thread number " << i << endl;
2496 Application::exit_with_failure();
2499 // Wait until the thread has finished launching and is gone to sleep
2500 while (threads[i].state != THREAD_SLEEPING) {}
2505 // exit_threads() is called when the program exits. It makes all the
2506 // helper threads exit cleanly.
2508 void ThreadsManager::exit_threads() {
2510 ActiveThreads = MAX_THREADS; // HACK
2511 AllThreadsShouldSleep = true; // HACK
2512 wake_sleeping_threads();
2514 // This makes the threads to exit idle_loop()
2515 AllThreadsShouldExit = true;
2517 // Wait for thread termination
2518 for (int i = 1; i < MAX_THREADS; i++)
2519 while (threads[i].state != THREAD_TERMINATED);
2521 // Now we can safely destroy the locks
2522 for (int i = 0; i < MAX_THREADS; i++)
2523 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2524 lock_destroy(&(SplitPointStack[i][j].lock));
2526 lock_destroy(&WaitLock);
2527 lock_destroy(&MPLock);
2531 // thread_should_stop() checks whether the thread should stop its search.
2532 // This can happen if a beta cutoff has occurred in the thread's currently
2533 // active split point, or in some ancestor of the current split point.
2535 bool ThreadsManager::thread_should_stop(int threadID) const {
2537 assert(threadID >= 0 && threadID < ActiveThreads);
2541 for (sp = threads[threadID].splitPoint; sp && !sp->stopRequest; sp = sp->parent) {}
2546 // thread_is_available() checks whether the thread with threadID "slave" is
2547 // available to help the thread with threadID "master" at a split point. An
2548 // obvious requirement is that "slave" must be idle. With more than two
2549 // threads, this is not by itself sufficient: If "slave" is the master of
2550 // some active split point, it is only available as a slave to the other
2551 // threads which are busy searching the split point at the top of "slave"'s
2552 // split point stack (the "helpful master concept" in YBWC terminology).
2554 bool ThreadsManager::thread_is_available(int slave, int master) const {
2556 assert(slave >= 0 && slave < ActiveThreads);
2557 assert(master >= 0 && master < ActiveThreads);
2558 assert(ActiveThreads > 1);
2560 if (threads[slave].state != THREAD_AVAILABLE || slave == master)
2563 // Make a local copy to be sure doesn't change under our feet
2564 int localActiveSplitPoints = threads[slave].activeSplitPoints;
2566 if (localActiveSplitPoints == 0)
2567 // No active split points means that the thread is available as
2568 // a slave for any other thread.
2571 if (ActiveThreads == 2)
2574 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2575 // that is known to be > 0, instead of threads[slave].activeSplitPoints that
2576 // could have been set to 0 by another thread leading to an out of bound access.
2577 if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
2584 // available_thread_exists() tries to find an idle thread which is available as
2585 // a slave for the thread with threadID "master".
2587 bool ThreadsManager::available_thread_exists(int master) const {
2589 assert(master >= 0 && master < ActiveThreads);
2590 assert(ActiveThreads > 1);
2592 for (int i = 0; i < ActiveThreads; i++)
2593 if (thread_is_available(i, master))
2600 // split() does the actual work of distributing the work at a node between
2601 // several threads at PV nodes. If it does not succeed in splitting the
2602 // node (because no idle threads are available, or because we have no unused
2603 // split point objects), the function immediately returns false. If
2604 // splitting is possible, a SplitPoint object is initialized with all the
2605 // data that must be copied to the helper threads (the current position and
2606 // search stack, alpha, beta, the search depth, etc.), and we tell our
2607 // helper threads that they have been assigned work. This will cause them
2608 // to instantly leave their idle loops and call sp_search_pv(). When all
2609 // threads have returned from sp_search_pv (or, equivalently, when
2610 // splitPoint->cpus becomes 0), split() returns true.
2612 template <bool Fake>
2613 bool ThreadsManager::split(const Position& p, SearchStack* sstck, int ply,
2614 Value* alpha, const Value beta, Value* bestValue,
2615 Depth depth, bool mateThreat, int* moves, MovePicker* mp, int master, bool pvNode) {
2618 assert(sstck != NULL);
2619 assert(ply >= 0 && ply < PLY_MAX);
2620 assert(*bestValue >= -VALUE_INFINITE);
2621 assert(*bestValue <= *alpha);
2622 assert(*alpha < beta);
2623 assert(beta <= VALUE_INFINITE);
2624 assert(depth > Depth(0));
2625 assert(master >= 0 && master < ActiveThreads);
2626 assert(Fake || ActiveThreads > 1);
2628 SplitPoint* splitPoint;
2632 // If no other thread is available to help us, or if we have too many
2633 // active split points, don't split.
2634 if ( (!Fake && !available_thread_exists(master))
2635 || threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
2637 lock_release(&MPLock);
2641 // Pick the next available split point object from the split point stack
2642 splitPoint = &SplitPointStack[master][threads[master].activeSplitPoints];
2644 // Initialize the split point object
2645 splitPoint->parent = threads[master].splitPoint;
2646 splitPoint->stopRequest = false;
2647 splitPoint->ply = ply;
2648 splitPoint->depth = depth;
2649 splitPoint->mateThreat = mateThreat;
2650 splitPoint->alpha = *alpha;
2651 splitPoint->beta = beta;
2652 splitPoint->pvNode = pvNode;
2653 splitPoint->bestValue = *bestValue;
2654 splitPoint->master = master;
2655 splitPoint->mp = mp;
2656 splitPoint->moves = *moves;
2657 splitPoint->cpus = 1;
2658 splitPoint->pos = &p;
2659 splitPoint->parentSstack = sstck;
2660 for (int i = 0; i < ActiveThreads; i++)
2661 splitPoint->slaves[i] = 0;
2663 threads[master].splitPoint = splitPoint;
2664 threads[master].activeSplitPoints++;
2666 // If we are here it means we are not available
2667 assert(threads[master].state != THREAD_AVAILABLE);
2669 // Allocate available threads setting state to THREAD_BOOKED
2670 for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
2671 if (!Fake && thread_is_available(i, master))
2673 threads[i].state = THREAD_BOOKED;
2674 threads[i].splitPoint = splitPoint;
2675 splitPoint->slaves[i] = 1;
2679 assert(Fake || splitPoint->cpus > 1);
2681 // We can release the lock because slave threads are already booked and master is not available
2682 lock_release(&MPLock);
2684 // Tell the threads that they have work to do. This will make them leave
2685 // their idle loop. But before copy search stack tail for each thread.
2686 for (int i = 0; i < ActiveThreads; i++)
2687 if (i == master || splitPoint->slaves[i])
2689 memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 4 * sizeof(SearchStack));
2691 assert(i == master || threads[i].state == THREAD_BOOKED);
2693 threads[i].state = THREAD_WORKISWAITING; // This makes the slave to exit from idle_loop()
2696 // Everything is set up. The master thread enters the idle loop, from
2697 // which it will instantly launch a search, because its state is
2698 // THREAD_WORKISWAITING. We send the split point as a second parameter to the
2699 // idle loop, which means that the main thread will return from the idle
2700 // loop when all threads have finished their work at this split point
2701 // (i.e. when splitPoint->cpus == 0).
2702 idle_loop(master, splitPoint);
2704 // We have returned from the idle loop, which means that all threads are
2705 // finished. Update alpha and bestValue, and return.
2708 *alpha = splitPoint->alpha;
2709 *bestValue = splitPoint->bestValue;
2710 threads[master].activeSplitPoints--;
2711 threads[master].splitPoint = splitPoint->parent;
2713 lock_release(&MPLock);
2718 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2719 // to start a new search from the root.
2721 void ThreadsManager::wake_sleeping_threads() {
2723 assert(AllThreadsShouldSleep);
2724 assert(ActiveThreads > 0);
2726 AllThreadsShouldSleep = false;
2728 if (ActiveThreads == 1)
2731 #if !defined(_MSC_VER)
2732 pthread_mutex_lock(&WaitLock);
2733 pthread_cond_broadcast(&WaitCond);
2734 pthread_mutex_unlock(&WaitLock);
2736 for (int i = 1; i < MAX_THREADS; i++)
2737 SetEvent(SitIdleEvent[i]);
2743 // put_threads_to_sleep() makes all the threads go to sleep just before
2744 // to leave think(), at the end of the search. Threads should have already
2745 // finished the job and should be idle.
2747 void ThreadsManager::put_threads_to_sleep() {
2749 assert(!AllThreadsShouldSleep);
2751 // This makes the threads to go to sleep
2752 AllThreadsShouldSleep = true;
2755 /// The RootMoveList class
2757 // RootMoveList c'tor
2759 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2761 SearchStack ss[PLY_MAX_PLUS_2];
2762 MoveStack mlist[MaxRootMoves];
2764 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2766 // Generate all legal moves
2767 MoveStack* last = generate_moves(pos, mlist);
2769 // Add each move to the moves[] array
2770 for (MoveStack* cur = mlist; cur != last; cur++)
2772 bool includeMove = includeAllMoves;
2774 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2775 includeMove = (searchMoves[k] == cur->move);
2780 // Find a quick score for the move
2782 pos.do_move(cur->move, st);
2783 moves[count].move = cur->move;
2784 moves[count].score = -qsearch<PV>(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2785 moves[count].pv[0] = cur->move;
2786 moves[count].pv[1] = MOVE_NONE;
2787 pos.undo_move(cur->move);
2794 // RootMoveList simple methods definitions
2796 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2798 moves[moveNum].nodes = nodes;
2799 moves[moveNum].cumulativeNodes += nodes;
2802 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2804 moves[moveNum].ourBeta = our;
2805 moves[moveNum].theirBeta = their;
2808 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2812 for (j = 0; pv[j] != MOVE_NONE; j++)
2813 moves[moveNum].pv[j] = pv[j];
2815 moves[moveNum].pv[j] = MOVE_NONE;
2819 // RootMoveList::sort() sorts the root move list at the beginning of a new
2822 void RootMoveList::sort() {
2824 sort_multipv(count - 1); // Sort all items
2828 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2829 // list by their scores and depths. It is used to order the different PVs
2830 // correctly in MultiPV mode.
2832 void RootMoveList::sort_multipv(int n) {
2836 for (i = 1; i <= n; i++)
2838 RootMove rm = moves[i];
2839 for (j = i; j > 0 && moves[j - 1] < rm; j--)
2840 moves[j] = moves[j - 1];