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-2012 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/>.
37 #include "ucioption.h"
41 volatile SignalsType Signals;
43 std::vector<RootMove> RootMoves;
44 Position RootPosition;
45 Time::point SearchTime;
46 StateStackPtr SetupStates;
51 using namespace Search;
55 // Set to true to force running with one thread. Used for debugging
56 const bool FakeSplit = false;
58 // This is the minimum interval in msec between two check_time() calls
59 const int TimerResolution = 5;
61 // Different node types, used as template parameter
62 enum NodeType { Root, PV, NonPV, SplitPointRoot, SplitPointPV, SplitPointNonPV };
64 // Lookup table to check if a Piece is a slider and its access function
65 const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
66 inline bool piece_is_slider(Piece p) { return Slidings[p]; }
68 // Dynamic razoring margin based on depth
69 inline Value razor_margin(Depth d) { return Value(512 + 16 * int(d)); }
71 // Futility lookup tables (initialized at startup) and their access functions
72 Value FutilityMargins[16][64]; // [depth][moveNumber]
73 int FutilityMoveCounts[32]; // [depth]
75 inline Value futility_margin(Depth d, int mn) {
77 return d < 7 * ONE_PLY ? FutilityMargins[std::max(int(d), 1)][std::min(mn, 63)]
81 // Reduction lookup tables (initialized at startup) and their access function
82 int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
84 template <bool PvNode> inline Depth reduction(Depth d, int mn) {
86 return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
89 size_t MultiPV, UCIMultiPV, PVIdx;
93 bool SkillLevelEnabled, Chess960;
96 template <NodeType NT>
97 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
99 template <NodeType NT>
100 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
102 void id_loop(Position& pos);
103 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta);
104 bool connected_moves(const Position& pos, Move m1, Move m2);
105 Value value_to_tt(Value v, int ply);
106 Value value_from_tt(Value v, int ply);
107 bool connected_threat(const Position& pos, Move m, Move threat);
108 Value refine_eval(const TTEntry* tte, Value ttValue, Value defaultEval);
109 Move do_skill_level();
110 string uci_pv(const Position& pos, int depth, Value alpha, Value beta);
115 /// Search::init() is called during startup to initialize various lookup tables
117 void Search::init() {
119 int d; // depth (ONE_PLY == 2)
120 int hd; // half depth (ONE_PLY == 1)
123 // Init reductions array
124 for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
126 double pvRed = log(double(hd)) * log(double(mc)) / 3.0;
127 double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
128 Reductions[1][hd][mc] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(ONE_PLY)) : 0);
129 Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
132 // Init futility margins array
133 for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
134 FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
136 // Init futility move count array
137 for (d = 0; d < 32; d++)
138 FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
142 /// Search::perft() is our utility to verify move generation. All the leaf nodes
143 /// up to the given depth are generated and counted and the sum returned.
145 size_t Search::perft(Position& pos, Depth depth) {
147 // At the last ply just return the number of legal moves (leaf nodes)
148 if (depth == ONE_PLY)
149 return MoveList<LEGAL>(pos).size();
155 for (MoveList<LEGAL> ml(pos); !ml.end(); ++ml)
157 pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
158 cnt += perft(pos, depth - ONE_PLY);
159 pos.undo_move(ml.move());
166 /// Search::think() is the external interface to Stockfish's search, and is
167 /// called by the main thread when the program receives the UCI 'go' command. It
168 /// searches from RootPosition and at the end prints the "bestmove" to output.
170 void Search::think() {
172 static PolyglotBook book; // Defined static to initialize the PRNG only once
174 Position& pos = RootPosition;
175 Chess960 = pos.is_chess960();
176 Eval::RootColor = pos.side_to_move();
177 int scaledCF = Eval::ContemptFactor * MaterialTable::game_phase(pos) / PHASE_MIDGAME;
178 Eval::ValueDraw[ Eval::RootColor] = VALUE_DRAW - Value(scaledCF);
179 Eval::ValueDraw[~Eval::RootColor] = VALUE_DRAW + Value(scaledCF);
180 TimeMgr.init(Limits, pos.startpos_ply_counter(), pos.side_to_move());
184 if (RootMoves.empty())
186 sync_cout << "info depth 0 score "
187 << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW) << sync_endl;
189 RootMoves.push_back(MOVE_NONE);
193 if (Options["OwnBook"] && !Limits.infinite)
195 Move bookMove = book.probe(pos, Options["Book File"], Options["Best Book Move"]);
197 if (bookMove && std::count(RootMoves.begin(), RootMoves.end(), bookMove))
199 std::swap(RootMoves[0], *std::find(RootMoves.begin(), RootMoves.end(), bookMove));
204 UCIMultiPV = Options["MultiPV"];
205 SkillLevel = Options["Skill Level"];
207 // Do we have to play with skill handicap? In this case enable MultiPV that
208 // we will use behind the scenes to retrieve a set of possible moves.
209 SkillLevelEnabled = (SkillLevel < 20);
210 MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, (size_t)4) : UCIMultiPV);
212 if (Options["Use Search Log"])
214 Log log(Options["Search Log Filename"]);
215 log << "\nSearching: " << pos.to_fen()
216 << "\ninfinite: " << Limits.infinite
217 << " ponder: " << Limits.ponder
218 << " time: " << Limits.time[pos.side_to_move()]
219 << " increment: " << Limits.inc[pos.side_to_move()]
220 << " moves to go: " << Limits.movestogo
226 // Set best timer interval to avoid lagging under time pressure. Timer is
227 // used to check for remaining available thinking time.
228 if (Limits.use_time_management())
229 Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 16, TimerResolution)));
230 else if (Limits.nodes)
231 Threads.set_timer(2 * TimerResolution);
233 Threads.set_timer(100);
235 // We're ready to start searching. Call the iterative deepening loop function
238 Threads.set_timer(0); // Stop timer
241 if (Options["Use Search Log"])
243 Time::point elapsed = Time::now() - SearchTime + 1;
245 Log log(Options["Search Log Filename"]);
246 log << "Nodes: " << pos.nodes_searched()
247 << "\nNodes/second: " << pos.nodes_searched() * 1000 / elapsed
248 << "\nBest move: " << move_to_san(pos, RootMoves[0].pv[0]);
251 pos.do_move(RootMoves[0].pv[0], st);
252 log << "\nPonder move: " << move_to_san(pos, RootMoves[0].pv[1]) << std::endl;
253 pos.undo_move(RootMoves[0].pv[0]);
258 // When we reach max depth we arrive here even without Signals.stop is raised,
259 // but if we are pondering or in infinite search, we shouldn't print the best
260 // move before we are told to do so.
261 if (!Signals.stop && (Limits.ponder || Limits.infinite))
262 pos.this_thread()->wait_for_stop_or_ponderhit();
264 // Best move could be MOVE_NONE when searching on a stalemate position
265 sync_cout << "bestmove " << move_to_uci(RootMoves[0].pv[0], Chess960)
266 << " ponder " << move_to_uci(RootMoves[0].pv[1], Chess960) << sync_endl;
272 // id_loop() is the main iterative deepening loop. It calls search() repeatedly
273 // with increasing depth until the allocated thinking time has been consumed,
274 // user stops the search, or the maximum search depth is reached.
276 void id_loop(Position& pos) {
278 Stack ss[MAX_PLY_PLUS_2];
279 int depth, prevBestMoveChanges;
280 Value bestValue, alpha, beta, delta;
281 bool bestMoveNeverChanged = true;
282 Move skillBest = MOVE_NONE;
284 memset(ss, 0, 4 * sizeof(Stack));
285 depth = BestMoveChanges = 0;
286 bestValue = delta = -VALUE_INFINITE;
287 ss->currentMove = MOVE_NULL; // Hack to skip update gains
289 // Iterative deepening loop until requested to stop or target depth reached
290 while (!Signals.stop && ++depth <= MAX_PLY && (!Limits.depth || depth <= Limits.depth))
292 // Save last iteration's scores before first PV line is searched and all
293 // the move scores but the (new) PV are set to -VALUE_INFINITE.
294 for (size_t i = 0; i < RootMoves.size(); i++)
295 RootMoves[i].prevScore = RootMoves[i].score;
297 prevBestMoveChanges = BestMoveChanges;
300 // MultiPV loop. We perform a full root search for each PV line
301 for (PVIdx = 0; PVIdx < std::min(MultiPV, RootMoves.size()); PVIdx++)
303 // Set aspiration window default width
304 if (depth >= 5 && abs(RootMoves[PVIdx].prevScore) < VALUE_KNOWN_WIN)
307 alpha = RootMoves[PVIdx].prevScore - delta;
308 beta = RootMoves[PVIdx].prevScore + delta;
312 alpha = -VALUE_INFINITE;
313 beta = VALUE_INFINITE;
316 // Start with a small aspiration window and, in case of fail high/low,
317 // research with bigger window until not failing high/low anymore.
320 // Search starts from ss+1 to allow referencing (ss-1). This is
321 // needed by update gains and ss copy when splitting at Root.
322 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
324 // Bring to front the best move. It is critical that sorting is
325 // done with a stable algorithm because all the values but the first
326 // and eventually the new best one are set to -VALUE_INFINITE and
327 // we want to keep the same order for all the moves but the new
328 // PV that goes to the front. Note that in case of MultiPV search
329 // the already searched PV lines are preserved.
330 sort<RootMove>(RootMoves.begin() + PVIdx, RootMoves.end());
332 // In case we have found an exact score and we are going to leave
333 // the fail high/low loop then reorder the PV moves, otherwise
334 // leave the last PV move in its position so to be searched again.
335 // Of course this is needed only in MultiPV search.
336 if (PVIdx && bestValue > alpha && bestValue < beta)
337 sort<RootMove>(RootMoves.begin(), RootMoves.begin() + PVIdx);
339 // Write PV back to transposition table in case the relevant
340 // entries have been overwritten during the search.
341 for (size_t i = 0; i <= PVIdx; i++)
342 RootMoves[i].insert_pv_in_tt(pos);
344 // If search has been stopped exit the aspiration window loop.
345 // Sorting and writing PV back to TT is safe becuase RootMoves
346 // is still valid, although refers to previous iteration.
350 // Send full PV info to GUI if we are going to leave the loop or
351 // if we have a fail high/low and we are deep in the search.
352 if ((bestValue > alpha && bestValue < beta) || Time::now() - SearchTime > 2000)
353 sync_cout << uci_pv(pos, depth, alpha, beta) << sync_endl;
355 // In case of failing high/low increase aspiration window and
356 // research, otherwise exit the fail high/low loop.
357 if (bestValue >= beta)
362 else if (bestValue <= alpha)
364 Signals.failedLowAtRoot = true;
365 Signals.stopOnPonderhit = false;
373 // Search with full window in case we have a win/mate score
374 if (abs(bestValue) >= VALUE_KNOWN_WIN)
376 alpha = -VALUE_INFINITE;
377 beta = VALUE_INFINITE;
380 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
384 // Skills: Do we need to pick now the best move ?
385 if (SkillLevelEnabled && depth == 1 + SkillLevel)
386 skillBest = do_skill_level();
388 if (!Signals.stop && Options["Use Search Log"])
390 Log log(Options["Search Log Filename"]);
391 log << pretty_pv(pos, depth, bestValue, Time::now() - SearchTime, &RootMoves[0].pv[0])
395 // Filter out startup noise when monitoring best move stability
396 if (depth > 2 && BestMoveChanges)
397 bestMoveNeverChanged = false;
399 // Do we have time for the next iteration? Can we stop searching now?
400 if (!Signals.stop && !Signals.stopOnPonderhit && Limits.use_time_management())
402 bool stop = false; // Local variable, not the volatile Signals.stop
404 // Take in account some extra time if the best move has changed
405 if (depth > 4 && depth < 50)
406 TimeMgr.pv_instability(BestMoveChanges, prevBestMoveChanges);
408 // Stop search if most of available time is already consumed. We
409 // probably don't have enough time to search the first move at the
410 // next iteration anyway.
411 if (Time::now() - SearchTime > (TimeMgr.available_time() * 62) / 100)
414 // Stop search early if one move seems to be much better than others
417 && ( (bestMoveNeverChanged && pos.captured_piece_type())
418 || Time::now() - SearchTime > (TimeMgr.available_time() * 40) / 100))
420 Value rBeta = bestValue - 2 * PawnValueMg;
421 (ss+1)->excludedMove = RootMoves[0].pv[0];
422 (ss+1)->skipNullMove = true;
423 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth - 3) * ONE_PLY);
424 (ss+1)->skipNullMove = false;
425 (ss+1)->excludedMove = MOVE_NONE;
433 // If we are allowed to ponder do not stop the search now but
434 // keep pondering until GUI sends "ponderhit" or "stop".
436 Signals.stopOnPonderhit = true;
443 // When using skills swap best PV line with the sub-optimal one
444 if (SkillLevelEnabled)
446 if (skillBest == MOVE_NONE) // Still unassigned ?
447 skillBest = do_skill_level();
449 std::swap(RootMoves[0], *std::find(RootMoves.begin(), RootMoves.end(), skillBest));
454 // search<>() is the main search function for both PV and non-PV nodes and for
455 // normal and SplitPoint nodes. When called just after a split point the search
456 // is simpler because we have already probed the hash table, done a null move
457 // search, and searched the first move before splitting, we don't have to repeat
458 // all this work again. We also don't need to store anything to the hash table
459 // here: This is taken care of after we return from the split point.
461 template <NodeType NT>
462 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
464 const bool PvNode = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
465 const bool SpNode = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
466 const bool RootNode = (NT == Root || NT == SplitPointRoot);
468 assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
469 assert(PvNode || (alpha == beta - 1));
470 assert(depth > DEPTH_ZERO);
472 Move movesSearched[64];
477 Move ttMove, move, excludedMove, bestMove, threatMove;
479 Value bestValue, value, ttValue;
480 Value refinedValue, nullValue, futilityValue;
481 bool inCheck, givesCheck, pvMove, singularExtensionNode;
482 bool captureOrPromotion, dangerous, doFullDepthSearch;
483 int moveCount, playedMoveCount;
485 // Step 1. Initialize node
486 Thread* thisThread = pos.this_thread();
487 moveCount = playedMoveCount = 0;
488 inCheck = pos.in_check();
493 bestMove = sp->bestMove;
494 threatMove = sp->threatMove;
495 bestValue = sp->bestValue;
497 ttMove = excludedMove = MOVE_NONE;
498 ttValue = VALUE_NONE;
500 assert(sp->bestValue > -VALUE_INFINITE && sp->moveCount > 0);
502 goto split_point_start;
505 bestValue = -VALUE_INFINITE;
506 ss->currentMove = threatMove = (ss+1)->excludedMove = bestMove = MOVE_NONE;
507 ss->ply = (ss-1)->ply + 1;
508 (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
509 (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
511 // Used to send selDepth info to GUI
512 if (PvNode && thisThread->maxPly < ss->ply)
513 thisThread->maxPly = ss->ply;
517 // Step 2. Check for aborted search and immediate draw
518 if (Signals.stop || pos.is_draw<false>() || ss->ply > MAX_PLY)
519 return Eval::ValueDraw[pos.side_to_move()];
521 // Step 3. Mate distance pruning. Even if we mate at the next move our score
522 // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
523 // a shorter mate was found upward in the tree then there is no need to search
524 // further, we will never beat current alpha. Same logic but with reversed signs
525 // applies also in the opposite condition of being mated instead of giving mate,
526 // in this case return a fail-high score.
527 alpha = std::max(mated_in(ss->ply), alpha);
528 beta = std::min(mate_in(ss->ply+1), beta);
533 // Step 4. Transposition table lookup
534 // We don't want the score of a partial search to overwrite a previous full search
535 // TT value, so we use a different position key in case of an excluded move.
536 excludedMove = ss->excludedMove;
537 posKey = excludedMove ? pos.exclusion_key() : pos.key();
538 tte = TT.probe(posKey);
539 ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
540 ttValue = tte ? value_from_tt(tte->value(), ss->ply) : VALUE_NONE;
542 // At PV nodes we check for exact scores, while at non-PV nodes we check for
543 // a fail high/low. Biggest advantage at probing at PV nodes is to have a
544 // smooth experience in analysis mode. We don't probe at Root nodes otherwise
545 // we should also update RootMoveList to avoid bogus output.
547 && tte && tte->depth() >= depth
548 && ( PvNode ? tte->type() == BOUND_EXACT
549 : ttValue >= beta ? (tte->type() & BOUND_LOWER)
550 : (tte->type() & BOUND_UPPER)))
553 ss->currentMove = ttMove; // Can be MOVE_NONE
557 && !pos.is_capture_or_promotion(ttMove)
558 && ttMove != ss->killers[0])
560 ss->killers[1] = ss->killers[0];
561 ss->killers[0] = ttMove;
566 // Step 5. Evaluate the position statically and update parent's gain statistics
568 ss->eval = ss->evalMargin = refinedValue = VALUE_NONE;
571 assert(tte->static_value() != VALUE_NONE);
573 ss->eval = tte->static_value();
574 ss->evalMargin = tte->static_value_margin();
575 refinedValue = refine_eval(tte, ttValue, ss->eval);
579 refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
580 TT.store(posKey, VALUE_NONE, BOUND_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
583 // Update gain for the parent non-capture move given the static position
584 // evaluation before and after the move.
585 if ( (move = (ss-1)->currentMove) != MOVE_NULL
586 && (ss-1)->eval != VALUE_NONE
587 && ss->eval != VALUE_NONE
588 && !pos.captured_piece_type()
589 && type_of(move) == NORMAL)
591 Square to = to_sq(move);
592 H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
595 // Step 6. Razoring (is omitted in PV nodes)
597 && depth < 4 * ONE_PLY
599 && refinedValue + razor_margin(depth) < beta
600 && ttMove == MOVE_NONE
601 && abs(beta) < VALUE_MATE_IN_MAX_PLY
602 && !pos.pawn_on_7th(pos.side_to_move()))
604 Value rbeta = beta - razor_margin(depth);
605 Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
607 // Logically we should return (v + razor_margin(depth)), but
608 // surprisingly this did slightly weaker in tests.
612 // Step 7. Static null move pruning (is omitted in PV nodes)
613 // We're betting that the opponent doesn't have a move that will reduce
614 // the score by more than futility_margin(depth) if we do a null move.
617 && depth < 4 * ONE_PLY
619 && refinedValue - FutilityMargins[depth][0] >= beta
620 && abs(beta) < VALUE_MATE_IN_MAX_PLY
621 && pos.non_pawn_material(pos.side_to_move()))
622 return refinedValue - FutilityMargins[depth][0];
624 // Step 8. Null move search with verification search (is omitted in PV nodes)
629 && refinedValue >= beta
630 && abs(beta) < VALUE_MATE_IN_MAX_PLY
631 && pos.non_pawn_material(pos.side_to_move()))
633 ss->currentMove = MOVE_NULL;
635 // Null move dynamic reduction based on depth
636 Depth R = 3 * ONE_PLY + depth / 4;
638 // Null move dynamic reduction based on value
639 if (refinedValue - PawnValueMg > beta)
642 pos.do_null_move<true>(st);
643 (ss+1)->skipNullMove = true;
644 nullValue = depth-R < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
645 : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R);
646 (ss+1)->skipNullMove = false;
647 pos.do_null_move<false>(st);
649 if (nullValue >= beta)
651 // Do not return unproven mate scores
652 if (nullValue >= VALUE_MATE_IN_MAX_PLY)
655 if (depth < 6 * ONE_PLY)
658 // Do verification search at high depths
659 ss->skipNullMove = true;
660 Value v = search<NonPV>(pos, ss, alpha, beta, depth-R);
661 ss->skipNullMove = false;
668 // The null move failed low, which means that we may be faced with
669 // some kind of threat. If the previous move was reduced, check if
670 // the move that refuted the null move was somehow connected to the
671 // move which was reduced. If a connection is found, return a fail
672 // low score (which will cause the reduced move to fail high in the
673 // parent node, which will trigger a re-search with full depth).
674 threatMove = (ss+1)->currentMove;
676 if ( depth < 5 * ONE_PLY
678 && threatMove != MOVE_NONE
679 && connected_moves(pos, (ss-1)->currentMove, threatMove))
684 // Step 9. ProbCut (is omitted in PV nodes)
685 // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
686 // and a reduced search returns a value much above beta, we can (almost) safely
687 // prune the previous move.
689 && depth >= 5 * ONE_PLY
692 && excludedMove == MOVE_NONE
693 && abs(beta) < VALUE_MATE_IN_MAX_PLY)
695 Value rbeta = beta + 200;
696 Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
698 assert(rdepth >= ONE_PLY);
699 assert((ss-1)->currentMove != MOVE_NONE);
700 assert((ss-1)->currentMove != MOVE_NULL);
702 MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
705 while ((move = mp.next_move<false>()) != MOVE_NONE)
706 if (pos.pl_move_is_legal(move, ci.pinned))
708 ss->currentMove = move;
709 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
710 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
717 // Step 10. Internal iterative deepening
718 if ( depth >= (PvNode ? 5 * ONE_PLY : 8 * ONE_PLY)
719 && ttMove == MOVE_NONE
720 && (PvNode || (!inCheck && ss->eval + Value(256) >= beta)))
722 Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
724 ss->skipNullMove = true;
725 search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
726 ss->skipNullMove = false;
728 tte = TT.probe(posKey);
729 ttMove = tte ? tte->move() : MOVE_NONE;
732 split_point_start: // At split points actual search starts from here
734 MovePicker mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
736 value = bestValue; // Workaround a bogus 'uninitialized' warning under gcc
737 singularExtensionNode = !RootNode
739 && depth >= (PvNode ? 6 * ONE_PLY : 8 * ONE_PLY)
740 && ttMove != MOVE_NONE
741 && !excludedMove // Recursive singular search is not allowed
742 && (tte->type() & BOUND_LOWER)
743 && tte->depth() >= depth - 3 * ONE_PLY;
745 // Step 11. Loop through moves
746 // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
747 while ((move = mp.next_move<SpNode>()) != MOVE_NONE)
751 if (move == excludedMove)
754 // At root obey the "searchmoves" option and skip moves not listed in Root
755 // Move List, as a consequence any illegal move is also skipped. In MultiPV
756 // mode we also skip PV moves which have been already searched.
757 if (RootNode && !std::count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
762 // Shared counter cannot be decremented later if move turns out to be illegal
763 if (!pos.pl_move_is_legal(move, ci.pinned))
766 moveCount = ++sp->moveCount;
774 Signals.firstRootMove = (moveCount == 1);
776 if (thisThread == Threads.main_thread() && Time::now() - SearchTime > 2000)
777 sync_cout << "info depth " << depth / ONE_PLY
778 << " currmove " << move_to_uci(move, Chess960)
779 << " currmovenumber " << moveCount + PVIdx << sync_endl;
783 captureOrPromotion = pos.is_capture_or_promotion(move);
784 givesCheck = pos.move_gives_check(move, ci);
785 dangerous = givesCheck
786 || pos.is_passed_pawn_push(move)
787 || type_of(move) == CASTLE
788 || ( captureOrPromotion // Entering a pawn endgame?
789 && type_of(pos.piece_on(to_sq(move))) != PAWN
790 && type_of(move) == NORMAL
791 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
792 - PieceValue[Mg][pos.piece_on(to_sq(move))] == VALUE_ZERO));
794 // Step 12. Extend checks and, in PV nodes, also dangerous moves
795 if (PvNode && dangerous)
798 else if (givesCheck && pos.see_sign(move) >= 0)
801 // Singular extension search. If all moves but one fail low on a search of
802 // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
803 // is singular and should be extended. To verify this we do a reduced search
804 // on all the other moves but the ttMove, if result is lower than ttValue minus
805 // a margin then we extend ttMove.
806 if ( singularExtensionNode
809 && pos.pl_move_is_legal(move, ci.pinned)
810 && abs(ttValue) < VALUE_KNOWN_WIN)
812 Value rBeta = ttValue - int(depth);
813 ss->excludedMove = move;
814 ss->skipNullMove = true;
815 value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
816 ss->skipNullMove = false;
817 ss->excludedMove = MOVE_NONE;
820 ext = rBeta >= beta ? ONE_PLY + ONE_PLY / 2 : ONE_PLY;
823 // Update current move (this must be done after singular extension search)
824 newDepth = depth - ONE_PLY + ext;
826 // Step 13. Futility pruning (is omitted in PV nodes)
828 && !captureOrPromotion
832 && (bestValue > VALUE_MATED_IN_MAX_PLY || ( bestValue == -VALUE_INFINITE
833 && alpha > VALUE_MATED_IN_MAX_PLY)))
835 // Move count based pruning
836 if ( depth < 16 * ONE_PLY
837 && moveCount >= FutilityMoveCounts[depth]
838 && (!threatMove || !connected_threat(pos, move, threatMove)))
846 // Value based pruning
847 // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
848 // but fixing this made program slightly weaker.
849 Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
850 futilityValue = ss->eval + ss->evalMargin + futility_margin(predictedDepth, moveCount)
851 + H.gain(pos.piece_moved(move), to_sq(move));
853 if (futilityValue < beta)
861 // Prune moves with negative SEE at low depths
862 if ( predictedDepth < 2 * ONE_PLY
863 && pos.see_sign(move) < 0)
872 // Check for legality only before to do the move
873 if (!pos.pl_move_is_legal(move, ci.pinned))
879 pvMove = PvNode ? moveCount == 1 : false;
880 ss->currentMove = move;
881 if (!SpNode && !captureOrPromotion && playedMoveCount < 64)
882 movesSearched[playedMoveCount++] = move;
884 // Step 14. Make the move
885 pos.do_move(move, st, ci, givesCheck);
887 // Step 15. Reduced depth search (LMR). If the move fails high will be
888 // re-searched at full depth.
889 if ( depth > 3 * ONE_PLY
891 && !captureOrPromotion
893 && ss->killers[0] != move
894 && ss->killers[1] != move)
896 ss->reduction = reduction<PvNode>(depth, moveCount);
897 Depth d = std::max(newDepth - ss->reduction, ONE_PLY);
898 alpha = SpNode ? sp->alpha : alpha;
900 value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
902 doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
903 ss->reduction = DEPTH_ZERO;
906 doFullDepthSearch = !pvMove;
908 // Step 16. Full depth search, when LMR is skipped or fails high
909 if (doFullDepthSearch)
911 alpha = SpNode ? sp->alpha : alpha;
912 value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
913 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
916 // Only for PV nodes do a full PV search on the first move or after a fail
917 // high, in the latter case search only if value < beta, otherwise let the
918 // parent node to fail low with value <= alpha and to try another move.
919 if (PvNode && (pvMove || (value > alpha && (RootNode || value < beta))))
920 value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
921 : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
923 // Step 17. Undo move
926 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
928 // Step 18. Check for new best move
932 bestValue = sp->bestValue;
936 // Finished searching the move. If Signals.stop is true, the search
937 // was aborted because the user interrupted the search or because we
938 // ran out of time. In this case, the return value of the search cannot
939 // be trusted, and we don't update the best move and/or PV.
940 if (Signals.stop || thisThread->cutoff_occurred())
945 RootMove& rm = *std::find(RootMoves.begin(), RootMoves.end(), move);
947 // PV move or new best move ?
948 if (pvMove || value > alpha)
951 rm.extract_pv_from_tt(pos);
953 // We record how often the best move has been changed in each
954 // iteration. This information is used for time management: When
955 // the best move changes frequently, we allocate some more time.
956 if (!pvMove && MultiPV == 1)
960 // All other moves but the PV are set to the lowest value, this
961 // is not a problem when sorting becuase sort is stable and move
962 // position in the list is preserved, just the PV is pushed up.
963 rm.score = -VALUE_INFINITE;
966 if (value > bestValue)
969 if (SpNode) sp->bestValue = value;
974 if (SpNode) sp->bestMove = move;
976 if (PvNode && value < beta)
978 alpha = value; // Update alpha here! Always alpha < beta
979 if (SpNode) sp->alpha = value;
983 if (SpNode) sp->cutoff = true;
989 // Step 19. Check for splitting the search
991 && depth >= Threads.min_split_depth()
993 && Threads.available_slave_exists(thisThread))
995 bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, &bestMove,
996 depth, threatMove, moveCount, mp, NT);
1004 // Step 20. Check for mate and stalemate
1005 // All legal moves have been searched and if there are no legal moves, it
1006 // must be mate or stalemate. Note that we can have a false positive in
1007 // case of Signals.stop or thread.cutoff_occurred() are set, but this is
1008 // harmless because return value is discarded anyhow in the parent nodes.
1009 // If we are in a singular extension search then return a fail low score.
1010 // A split node has at least one move, the one tried before to be splitted.
1012 return excludedMove ? alpha : inCheck ? mated_in(ss->ply) : VALUE_DRAW;
1014 // If we have pruned all the moves without searching return a fail-low score
1015 if (bestValue == -VALUE_INFINITE)
1017 assert(!playedMoveCount);
1022 if (bestValue >= beta) // Failed high
1024 TT.store(posKey, value_to_tt(bestValue, ss->ply), BOUND_LOWER, depth,
1025 bestMove, ss->eval, ss->evalMargin);
1027 if (!pos.is_capture_or_promotion(bestMove) && !inCheck)
1029 if (bestMove != ss->killers[0])
1031 ss->killers[1] = ss->killers[0];
1032 ss->killers[0] = bestMove;
1035 // Increase history value of the cut-off move
1036 Value bonus = Value(int(depth) * int(depth));
1037 H.add(pos.piece_moved(bestMove), to_sq(bestMove), bonus);
1039 // Decrease history of all the other played non-capture moves
1040 for (int i = 0; i < playedMoveCount - 1; i++)
1042 Move m = movesSearched[i];
1043 H.add(pos.piece_moved(m), to_sq(m), -bonus);
1047 else // Failed low or PV search
1048 TT.store(posKey, value_to_tt(bestValue, ss->ply),
1049 PvNode && bestMove != MOVE_NONE ? BOUND_EXACT : BOUND_UPPER,
1050 depth, bestMove, ss->eval, ss->evalMargin);
1052 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1058 // qsearch() is the quiescence search function, which is called by the main
1059 // search function when the remaining depth is zero (or, to be more precise,
1060 // less than ONE_PLY).
1062 template <NodeType NT>
1063 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1065 const bool PvNode = (NT == PV);
1067 assert(NT == PV || NT == NonPV);
1068 assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1069 assert(PvNode || (alpha == beta - 1));
1070 assert(depth <= DEPTH_ZERO);
1075 Move ttMove, move, bestMove;
1076 Value bestValue, value, ttValue, futilityValue, futilityBase;
1077 bool inCheck, givesCheck, enoughMaterial, evasionPrunable;
1080 inCheck = pos.in_check();
1081 ss->currentMove = bestMove = MOVE_NONE;
1082 ss->ply = (ss-1)->ply + 1;
1084 // Check for an instant draw or maximum ply reached
1085 if (pos.is_draw<true>() || ss->ply > MAX_PLY)
1086 return Eval::ValueDraw[pos.side_to_move()];
1088 // Transposition table lookup. At PV nodes, we don't use the TT for
1089 // pruning, but only for move ordering.
1091 tte = TT.probe(posKey);
1092 ttMove = tte ? tte->move() : MOVE_NONE;
1093 ttValue = tte ? value_from_tt(tte->value(),ss->ply) : VALUE_NONE;
1095 // Decide whether or not to include checks, this fixes also the type of
1096 // TT entry depth that we are going to use. Note that in qsearch we use
1097 // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1098 ttDepth = inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS;
1100 if ( tte && tte->depth() >= ttDepth
1101 && ( PvNode ? tte->type() == BOUND_EXACT
1102 : ttValue >= beta ? (tte->type() & BOUND_LOWER)
1103 : (tte->type() & BOUND_UPPER)))
1105 ss->currentMove = ttMove; // Can be MOVE_NONE
1109 // Evaluate the position statically
1112 ss->eval = ss->evalMargin = VALUE_NONE;
1113 bestValue = futilityBase = -VALUE_INFINITE;
1114 enoughMaterial = false;
1120 assert(tte->static_value() != VALUE_NONE);
1122 ss->eval = bestValue = tte->static_value();
1123 ss->evalMargin = tte->static_value_margin();
1126 ss->eval = bestValue = evaluate(pos, ss->evalMargin);
1128 // Stand pat. Return immediately if static value is at least beta
1129 if (bestValue >= beta)
1132 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), BOUND_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
1137 if (PvNode && bestValue > alpha)
1140 futilityBase = ss->eval + ss->evalMargin + Value(128);
1141 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMg;
1144 // Initialize a MovePicker object for the current position, and prepare
1145 // to search the moves. Because the depth is <= 0 here, only captures,
1146 // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1148 MovePicker mp(pos, ttMove, depth, H, to_sq((ss-1)->currentMove));
1151 // Loop through the moves until no moves remain or a beta cutoff occurs
1152 while ((move = mp.next_move<false>()) != MOVE_NONE)
1154 assert(is_ok(move));
1156 givesCheck = pos.move_gives_check(move, ci);
1164 && type_of(move) != PROMOTION
1165 && !pos.is_passed_pawn_push(move))
1167 futilityValue = futilityBase
1168 + PieceValue[Eg][pos.piece_on(to_sq(move))]
1169 + (type_of(move) == ENPASSANT ? PawnValueEg : VALUE_ZERO);
1171 if (futilityValue < beta)
1173 if (futilityValue > bestValue)
1174 bestValue = futilityValue;
1179 // Prune moves with negative or equal SEE
1180 if ( futilityBase < beta
1181 && depth < DEPTH_ZERO
1182 && pos.see(move) <= 0)
1186 // Detect non-capture evasions that are candidate to be pruned
1187 evasionPrunable = !PvNode
1189 && bestValue > VALUE_MATED_IN_MAX_PLY
1190 && !pos.is_capture(move)
1191 && !pos.can_castle(pos.side_to_move());
1193 // Don't search moves with negative SEE values
1195 && (!inCheck || evasionPrunable)
1197 && type_of(move) != PROMOTION
1198 && pos.see_sign(move) < 0)
1201 // Don't search useless checks
1206 && !pos.is_capture_or_promotion(move)
1207 && ss->eval + PawnValueMg / 4 < beta
1208 && !check_is_dangerous(pos, move, futilityBase, beta))
1211 // Check for legality only before to do the move
1212 if (!pos.pl_move_is_legal(move, ci.pinned))
1215 ss->currentMove = move;
1217 // Make and search the move
1218 pos.do_move(move, st, ci, givesCheck);
1219 value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth - ONE_PLY);
1220 pos.undo_move(move);
1222 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1224 // Check for new best move
1225 if (value > bestValue)
1231 if (PvNode && value < beta) // Update alpha here! Always alpha < beta
1238 TT.store(posKey, value_to_tt(value, ss->ply), BOUND_LOWER,
1239 ttDepth, move, ss->eval, ss->evalMargin);
1247 // All legal moves have been searched. A special case: If we're in check
1248 // and no legal moves were found, it is checkmate.
1249 if (inCheck && bestValue == -VALUE_INFINITE)
1250 return mated_in(ss->ply); // Plies to mate from the root
1252 TT.store(posKey, value_to_tt(bestValue, ss->ply),
1253 PvNode && bestMove != MOVE_NONE ? BOUND_EXACT : BOUND_UPPER,
1254 ttDepth, bestMove, ss->eval, ss->evalMargin);
1256 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1262 // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1263 // bestValue is updated only when returning false because in that case move
1266 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta)
1268 Bitboard b, occ, oldAtt, newAtt, kingAtt;
1269 Square from, to, ksq;
1273 from = from_sq(move);
1275 them = ~pos.side_to_move();
1276 ksq = pos.king_square(them);
1277 kingAtt = pos.attacks_from<KING>(ksq);
1278 pc = pos.piece_moved(move);
1280 occ = pos.pieces() ^ from ^ ksq;
1281 oldAtt = pos.attacks_from(pc, from, occ);
1282 newAtt = pos.attacks_from(pc, to, occ);
1284 // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1285 b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1287 if (!more_than_one(b))
1290 // Rule 2. Queen contact check is very dangerous
1291 if (type_of(pc) == QUEEN && (kingAtt & to))
1294 // Rule 3. Creating new double threats with checks
1295 b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1298 // Note that here we generate illegal "double move"!
1299 if (futilityBase + PieceValue[Eg][pos.piece_on(pop_lsb(&b))] >= beta)
1307 // connected_moves() tests whether two moves are 'connected' in the sense
1308 // that the first move somehow made the second move possible (for instance
1309 // if the moving piece is the same in both moves). The first move is assumed
1310 // to be the move that was made to reach the current position, while the
1311 // second move is assumed to be a move from the current position.
1313 bool connected_moves(const Position& pos, Move m1, Move m2) {
1315 Square f1, t1, f2, t2;
1322 // Case 1: The moving piece is the same in both moves
1328 // Case 2: The destination square for m2 was vacated by m1
1334 // Case 3: Moving through the vacated square
1335 p2 = pos.piece_on(f2);
1336 if (piece_is_slider(p2) && (between_bb(f2, t2) & f1))
1339 // Case 4: The destination square for m2 is defended by the moving piece in m1
1340 p1 = pos.piece_on(t1);
1341 if (pos.attacks_from(p1, t1) & t2)
1344 // Case 5: Discovered check, checking piece is the piece moved in m1
1345 ksq = pos.king_square(pos.side_to_move());
1346 if ( piece_is_slider(p1)
1347 && (between_bb(t1, ksq) & f2)
1348 && (pos.attacks_from(p1, t1, pos.pieces() ^ f2) & ksq))
1355 // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1356 // "plies to mate from the current position". Non-mate scores are unchanged.
1357 // The function is called before storing a value to the transposition table.
1359 Value value_to_tt(Value v, int ply) {
1361 if (v >= VALUE_MATE_IN_MAX_PLY)
1364 if (v <= VALUE_MATED_IN_MAX_PLY)
1371 // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
1372 // from the transposition table (where refers to the plies to mate/be mated
1373 // from current position) to "plies to mate/be mated from the root".
1375 Value value_from_tt(Value v, int ply) {
1377 if (v >= VALUE_MATE_IN_MAX_PLY)
1380 if (v <= VALUE_MATED_IN_MAX_PLY)
1387 // connected_threat() tests whether it is safe to forward prune a move or if
1388 // is somehow connected to the threat move returned by null search.
1390 bool connected_threat(const Position& pos, Move m, Move threat) {
1393 assert(is_ok(threat));
1394 assert(!pos.is_capture_or_promotion(m));
1395 assert(!pos.is_passed_pawn_push(m));
1397 Square mfrom, mto, tfrom, tto;
1401 tfrom = from_sq(threat);
1402 tto = to_sq(threat);
1404 // Case 1: Don't prune moves which move the threatened piece
1408 // Case 2: If the threatened piece has value less than or equal to the
1409 // value of the threatening piece, don't prune moves which defend it.
1410 if ( pos.is_capture(threat)
1411 && ( PieceValue[Mg][pos.piece_on(tfrom)] >= PieceValue[Mg][pos.piece_on(tto)]
1412 || type_of(pos.piece_on(tfrom)) == KING)
1413 && pos.move_attacks_square(m, tto))
1416 // Case 3: If the moving piece in the threatened move is a slider, don't
1417 // prune safe moves which block its ray.
1418 if ( piece_is_slider(pos.piece_on(tfrom))
1419 && (between_bb(tfrom, tto) & mto)
1420 && pos.see_sign(m) >= 0)
1427 // refine_eval() returns the transposition table score if possible, otherwise
1428 // falls back on static position evaluation.
1430 Value refine_eval(const TTEntry* tte, Value v, Value defaultEval) {
1434 if ( ((tte->type() & BOUND_LOWER) && v >= defaultEval)
1435 || ((tte->type() & BOUND_UPPER) && v < defaultEval))
1442 // When playing with strength handicap choose best move among the MultiPV set
1443 // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1445 Move do_skill_level() {
1447 assert(MultiPV > 1);
1451 // PRNG sequence should be not deterministic
1452 for (int i = Time::now() % 50; i > 0; i--)
1453 rk.rand<unsigned>();
1455 // RootMoves are already sorted by score in descending order
1456 size_t size = std::min(MultiPV, RootMoves.size());
1457 int variance = std::min(RootMoves[0].score - RootMoves[size - 1].score, PawnValueMg);
1458 int weakness = 120 - 2 * SkillLevel;
1459 int max_s = -VALUE_INFINITE;
1460 Move best = MOVE_NONE;
1462 // Choose best move. For each move score we add two terms both dependent on
1463 // weakness, one deterministic and bigger for weaker moves, and one random,
1464 // then we choose the move with the resulting highest score.
1465 for (size_t i = 0; i < size; i++)
1467 int s = RootMoves[i].score;
1469 // Don't allow crazy blunders even at very low skills
1470 if (i > 0 && RootMoves[i-1].score > s + 2 * PawnValueMg)
1473 // This is our magic formula
1474 s += ( weakness * int(RootMoves[0].score - s)
1475 + variance * (rk.rand<unsigned>() % weakness)) / 128;
1480 best = RootMoves[i].pv[0];
1487 // uci_pv() formats PV information according to UCI protocol. UCI requires
1488 // to send all the PV lines also if are still to be searched and so refer to
1489 // the previous search score.
1491 string uci_pv(const Position& pos, int depth, Value alpha, Value beta) {
1493 std::stringstream s;
1494 Time::point elaspsed = Time::now() - SearchTime + 1;
1497 for (size_t i = 0; i < Threads.size(); i++)
1498 if (Threads[i].maxPly > selDepth)
1499 selDepth = Threads[i].maxPly;
1501 for (size_t i = 0; i < std::min(UCIMultiPV, RootMoves.size()); i++)
1503 bool updated = (i <= PVIdx);
1505 if (depth == 1 && !updated)
1508 int d = (updated ? depth : depth - 1);
1509 Value v = (updated ? RootMoves[i].score : RootMoves[i].prevScore);
1511 if (s.rdbuf()->in_avail())
1514 s << "info depth " << d
1515 << " seldepth " << selDepth
1516 << " score " << (i == PVIdx ? score_to_uci(v, alpha, beta) : score_to_uci(v))
1517 << " nodes " << pos.nodes_searched()
1518 << " nps " << pos.nodes_searched() * 1000 / elaspsed
1519 << " time " << elaspsed
1520 << " multipv " << i + 1
1523 for (size_t j = 0; RootMoves[i].pv[j] != MOVE_NONE; j++)
1524 s << " " << move_to_uci(RootMoves[i].pv[j], Chess960);
1533 /// RootMove::extract_pv_from_tt() builds a PV by adding moves from the TT table.
1534 /// We consider also failing high nodes and not only BOUND_EXACT nodes so to
1535 /// allow to always have a ponder move even when we fail high at root, and a
1536 /// long PV to print that is important for position analysis.
1538 void RootMove::extract_pv_from_tt(Position& pos) {
1540 StateInfo state[MAX_PLY_PLUS_2], *st = state;
1545 assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1549 pos.do_move(m, *st++);
1551 while ( (tte = TT.probe(pos.key())) != NULL
1552 && (m = tte->move()) != MOVE_NONE // Local copy, TT entry could change
1553 && pos.is_pseudo_legal(m)
1554 && pos.pl_move_is_legal(m, pos.pinned_pieces())
1556 && (!pos.is_draw<false>() || ply < 2))
1559 pos.do_move(m, *st++);
1562 pv.push_back(MOVE_NONE);
1564 do pos.undo_move(pv[--ply]); while (ply);
1568 /// RootMove::insert_pv_in_tt() is called at the end of a search iteration, and
1569 /// inserts the PV back into the TT. This makes sure the old PV moves are searched
1570 /// first, even if the old TT entries have been overwritten.
1572 void RootMove::insert_pv_in_tt(Position& pos) {
1574 StateInfo state[MAX_PLY_PLUS_2], *st = state;
1577 Value v, m = VALUE_NONE;
1580 assert(pv[ply] != MOVE_NONE && pos.is_pseudo_legal(pv[ply]));
1586 // Don't overwrite existing correct entries
1587 if (!tte || tte->move() != pv[ply])
1589 v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1590 TT.store(k, VALUE_NONE, BOUND_NONE, DEPTH_NONE, pv[ply], v, m);
1592 pos.do_move(pv[ply], *st++);
1594 } while (pv[++ply] != MOVE_NONE);
1596 do pos.undo_move(pv[--ply]); while (ply);
1600 /// Thread::idle_loop() is where the thread is parked when it has no work to do
1602 void Thread::idle_loop() {
1604 // Pointer 'sp_master', if non-NULL, points to the active SplitPoint
1605 // object for which the thread is the master.
1606 const SplitPoint* sp_master = splitPointsCnt ? curSplitPoint : NULL;
1608 assert(!sp_master || (sp_master->master == this && is_searching));
1610 // If this thread is the master of a split point and all slaves have
1611 // finished their work at this split point, return from the idle loop.
1612 while (!sp_master || sp_master->slavesMask)
1614 // If we are not searching, wait for a condition to be signaled
1615 // instead of wasting CPU time polling for work.
1618 || (!is_searching && Threads.use_sleeping_threads()))
1626 // Grab the lock to avoid races with Thread::wake_up()
1629 // If we are master and all slaves have finished don't go to sleep
1630 if (sp_master && !sp_master->slavesMask)
1636 // Do sleep after retesting sleep conditions under lock protection, in
1637 // particular we need to avoid a deadlock in case a master thread has,
1638 // in the meanwhile, allocated us and sent the wake_up() call before we
1639 // had the chance to grab the lock.
1640 if (do_sleep || !is_searching)
1641 sleepCondition.wait(mutex);
1646 // If this thread has been assigned work, launch a search
1649 assert(!do_sleep && !do_exit);
1651 Threads.mutex.lock();
1653 assert(is_searching);
1654 SplitPoint* sp = curSplitPoint;
1656 Threads.mutex.unlock();
1658 Stack ss[MAX_PLY_PLUS_2];
1659 Position pos(*sp->pos, this);
1661 memcpy(ss, sp->ss - 1, 4 * sizeof(Stack));
1666 assert(sp->activePositions[idx] == NULL);
1668 sp->activePositions[idx] = &pos;
1670 if (sp->nodeType == Root)
1671 search<SplitPointRoot>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1672 else if (sp->nodeType == PV)
1673 search<SplitPointPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1674 else if (sp->nodeType == NonPV)
1675 search<SplitPointNonPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1679 assert(is_searching);
1681 is_searching = false;
1682 sp->activePositions[idx] = NULL;
1683 sp->slavesMask &= ~(1ULL << idx);
1684 sp->nodes += pos.nodes_searched();
1686 // Wake up master thread so to allow it to return from the idle loop in
1687 // case we are the last slave of the split point.
1688 if ( Threads.use_sleeping_threads()
1689 && this != sp->master
1692 assert(!sp->master->is_searching);
1693 sp->master->wake_up();
1696 // After releasing the lock we cannot access anymore any SplitPoint
1697 // related data in a safe way becuase it could have been released under
1698 // our feet by the sp master. Also accessing other Thread objects is
1699 // unsafe because if we are exiting there is a chance are already freed.
1706 /// check_time() is called by the timer thread when the timer triggers. It is
1707 /// used to print debug info and, more important, to detect when we are out of
1708 /// available time and so stop the search.
1712 static Time::point lastInfoTime = Time::now();
1713 int64_t nodes = 0; // Workaround silly 'uninitialized' gcc warning
1715 if (Time::now() - lastInfoTime >= 1000)
1717 lastInfoTime = Time::now();
1726 Threads.mutex.lock();
1728 nodes = RootPosition.nodes_searched();
1730 // Loop across all split points and sum accumulated SplitPoint nodes plus
1731 // all the currently active slaves positions.
1732 for (size_t i = 0; i < Threads.size(); i++)
1733 for (int j = 0; j < Threads[i].splitPointsCnt; j++)
1735 SplitPoint& sp = Threads[i].splitPoints[j];
1740 Bitboard sm = sp.slavesMask;
1743 Position* pos = sp.activePositions[pop_lsb(&sm)];
1744 nodes += pos ? pos->nodes_searched() : 0;
1750 Threads.mutex.unlock();
1753 Time::point elapsed = Time::now() - SearchTime;
1754 bool stillAtFirstMove = Signals.firstRootMove
1755 && !Signals.failedLowAtRoot
1756 && elapsed > TimeMgr.available_time();
1758 bool noMoreTime = elapsed > TimeMgr.maximum_time() - 2 * TimerResolution
1759 || stillAtFirstMove;
1761 if ( (Limits.use_time_management() && noMoreTime)
1762 || (Limits.movetime && elapsed >= Limits.movetime)
1763 || (Limits.nodes && nodes >= Limits.nodes))
1764 Signals.stop = true;