]> git.sesse.net Git - stockfish/blob - src/search.cpp
Don't allow LMR to fall in qsearch
[stockfish] / src / search.cpp
1 /*
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
5
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.
10
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.
15
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/>.
18 */
19
20 #include <algorithm>
21 #include <cassert>
22 #include <cmath>
23 #include <cstring>
24 #include <iomanip>
25 #include <iostream>
26 #include <sstream>
27
28 #include "book.h"
29 #include "evaluate.h"
30 #include "history.h"
31 #include "misc.h"
32 #include "movegen.h"
33 #include "movepick.h"
34 #include "search.h"
35 #include "timeman.h"
36 #include "thread.h"
37 #include "tt.h"
38 #include "ucioption.h"
39
40 namespace Search {
41
42   volatile SignalsType Signals;
43   LimitsType Limits;
44   std::vector<RootMove> RootMoves;
45   Position RootPosition;
46 }
47
48 using std::string;
49 using std::cout;
50 using std::endl;
51 using namespace Search;
52
53 namespace {
54
55   // Set to true to force running with one thread. Used for debugging
56   const bool FakeSplit = false;
57
58   // Different node types, used as template parameter
59   enum NodeType { Root, PV, NonPV, SplitPointRoot, SplitPointPV, SplitPointNonPV };
60
61   // Lookup table to check if a Piece is a slider and its access function
62   const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
63   inline bool piece_is_slider(Piece p) { return Slidings[p]; }
64
65   // Maximum depth for razoring
66   const Depth RazorDepth = 4 * ONE_PLY;
67
68   // Dynamic razoring margin based on depth
69   inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
70
71   // Maximum depth for use of dynamic threat detection when null move fails low
72   const Depth ThreatDepth = 5 * ONE_PLY;
73
74   // Minimum depth for use of internal iterative deepening
75   const Depth IIDDepth[] = { 8 * ONE_PLY, 5 * ONE_PLY };
76
77   // At Non-PV nodes we do an internal iterative deepening search
78   // when the static evaluation is bigger then beta - IIDMargin.
79   const Value IIDMargin = Value(0x100);
80
81   // Minimum depth for use of singular extension
82   const Depth SingularExtensionDepth[] = { 8 * ONE_PLY, 6 * ONE_PLY };
83
84   // Futility margin for quiescence search
85   const Value FutilityMarginQS = Value(0x80);
86
87   // Futility lookup tables (initialized at startup) and their access functions
88   Value FutilityMargins[16][64]; // [depth][moveNumber]
89   int FutilityMoveCounts[32];    // [depth]
90
91   inline Value futility_margin(Depth d, int mn) {
92
93     return d < 7 * ONE_PLY ? FutilityMargins[std::max(int(d), 1)][std::min(mn, 63)]
94                            : 2 * VALUE_INFINITE;
95   }
96
97   inline int futility_move_count(Depth d) {
98
99     return d < 16 * ONE_PLY ? FutilityMoveCounts[d] : MAX_MOVES;
100   }
101
102   // Reduction lookup tables (initialized at startup) and their access function
103   int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
104
105   template <bool PvNode> inline Depth reduction(Depth d, int mn) {
106
107     return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
108   }
109
110   // Easy move margin. An easy move candidate must be at least this much better
111   // than the second best move.
112   const Value EasyMoveMargin = Value(0x150);
113
114   // This is the minimum interval in msec between two check_time() calls
115   const int TimerResolution = 5;
116
117
118   size_t MultiPV, UCIMultiPV, PVIdx;
119   TimeManager TimeMgr;
120   int BestMoveChanges;
121   int SkillLevel;
122   bool SkillLevelEnabled, Chess960;
123   History H;
124
125
126   template <NodeType NT>
127   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
128
129   template <NodeType NT>
130   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
131
132   void id_loop(Position& pos);
133   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bValue);
134   bool connected_moves(const Position& pos, Move m1, Move m2);
135   Value value_to_tt(Value v, int ply);
136   Value value_from_tt(Value v, int ply);
137   bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply);
138   bool connected_threat(const Position& pos, Move m, Move threat);
139   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
140   Move do_skill_level();
141   int elapsed_time(bool reset = false);
142   string score_to_uci(Value v, Value alpha = -VALUE_INFINITE, Value beta = VALUE_INFINITE);
143   void pv_info_to_log(Position& pos, int depth, Value score, int time, Move pv[]);
144   void pv_info_to_uci(const Position& pos, int depth, Value alpha, Value beta);
145
146   // MovePickerExt class template extends MovePicker and allows to choose at
147   // compile time the proper moves source according to the type of node. In the
148   // default case we simply create and use a standard MovePicker object.
149   template<bool SpNode> struct MovePickerExt : public MovePicker {
150
151     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
152                   : MovePicker(p, ttm, d, h, ss, b) {}
153   };
154
155   // In case of a SpNode we use split point's shared MovePicker object as moves source
156   template<> struct MovePickerExt<true> : public MovePicker {
157
158     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
159                   : MovePicker(p, ttm, d, h, ss, b), mp(ss->sp->mp) {}
160
161     Move next_move() { return mp->next_move(); }
162     MovePicker* mp;
163   };
164
165   // is_dangerous() checks whether a move belongs to some classes of known
166   // 'dangerous' moves so that we avoid to prune it.
167   FORCE_INLINE bool is_dangerous(const Position& pos, Move m, bool captureOrPromotion) {
168
169     // Test for a pawn pushed to 7th or a passed pawn move
170     if (type_of(pos.piece_moved(m)) == PAWN)
171     {
172         Color c = pos.side_to_move();
173         if (   relative_rank(c, to_sq(m)) == RANK_7
174             || pos.pawn_is_passed(c, to_sq(m)))
175             return true;
176     }
177
178     // Test for a capture that triggers a pawn endgame
179     if (   captureOrPromotion
180         && type_of(pos.piece_on(to_sq(m))) != PAWN
181         && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
182             - PieceValueMidgame[pos.piece_on(to_sq(m))] == VALUE_ZERO)
183         && !is_special(m))
184         return true;
185
186     return false;
187   }
188
189 } // namespace
190
191
192 /// Search::init() is called during startup to initialize various lookup tables
193
194 void Search::init() {
195
196   int d;  // depth (ONE_PLY == 2)
197   int hd; // half depth (ONE_PLY == 1)
198   int mc; // moveCount
199
200   // Init reductions array
201   for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
202   {
203       double    pvRed = log(double(hd)) * log(double(mc)) / 3.0;
204       double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
205       Reductions[1][hd][mc] = (int8_t) (   pvRed >= 1.0 ? floor(   pvRed * int(ONE_PLY)) : 0);
206       Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
207   }
208
209   // Init futility margins array
210   for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
211       FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
212
213   // Init futility move count array
214   for (d = 0; d < 32; d++)
215       FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
216 }
217
218
219 /// Search::perft() is our utility to verify move generation. All the leaf nodes
220 /// up to the given depth are generated and counted and the sum returned.
221
222 int64_t Search::perft(Position& pos, Depth depth) {
223
224   StateInfo st;
225   int64_t cnt = 0;
226
227   MoveList<MV_LEGAL> ml(pos);
228
229   // At the last ply just return the number of moves (leaf nodes)
230   if (depth == ONE_PLY)
231       return ml.size();
232
233   CheckInfo ci(pos);
234   for ( ; !ml.end(); ++ml)
235   {
236       pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
237       cnt += perft(pos, depth - ONE_PLY);
238       pos.undo_move(ml.move());
239   }
240   return cnt;
241 }
242
243
244 /// Search::think() is the external interface to Stockfish's search, and is
245 /// called by the main thread when the program receives the UCI 'go' command. It
246 /// searches from RootPosition and at the end prints the "bestmove" to output.
247
248 void Search::think() {
249
250   static Book book; // Defined static to initialize the PRNG only once
251
252   Position& pos = RootPosition;
253   Chess960 = pos.is_chess960();
254   elapsed_time(true);
255   TimeMgr.init(Limits, pos.startpos_ply_counter());
256   TT.new_search();
257   H.clear();
258
259   if (RootMoves.empty())
260   {
261       cout << "info depth 0 score "
262            << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW) << endl;
263
264       RootMoves.push_back(MOVE_NONE);
265       goto finalize;
266   }
267
268   if (Options["OwnBook"])
269   {
270       Move bookMove = book.probe(pos, Options["Book File"], Options["Best Book Move"]);
271
272       if (bookMove && count(RootMoves.begin(), RootMoves.end(), bookMove))
273       {
274           std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), bookMove));
275           goto finalize;
276       }
277   }
278
279   // Read UCI options: GUI could change UCI parameters during the game
280   read_evaluation_uci_options(pos.side_to_move());
281   Threads.read_uci_options();
282
283   TT.set_size(Options["Hash"]);
284   if (Options["Clear Hash"])
285   {
286       Options["Clear Hash"] = false;
287       TT.clear();
288   }
289
290   UCIMultiPV = Options["MultiPV"];
291   SkillLevel = Options["Skill Level"];
292
293   // Do we have to play with skill handicap? In this case enable MultiPV that
294   // we will use behind the scenes to retrieve a set of possible moves.
295   SkillLevelEnabled = (SkillLevel < 20);
296   MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, (size_t)4) : UCIMultiPV);
297
298   if (Options["Use Search Log"])
299   {
300       Log log(Options["Search Log Filename"]);
301       log << "\nSearching: "  << pos.to_fen()
302           << "\ninfinite: "   << Limits.infinite
303           << " ponder: "      << Limits.ponder
304           << " time: "        << Limits.time
305           << " increment: "   << Limits.increment
306           << " moves to go: " << Limits.movesToGo
307           << endl;
308   }
309
310   for (int i = 0; i < Threads.size(); i++)
311   {
312       Threads[i].maxPly = 0;
313       Threads[i].wake_up();
314   }
315
316   // Set best timer interval to avoid lagging under time pressure. Timer is
317   // used to check for remaining available thinking time.
318   if (Limits.use_time_management())
319       Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 16, TimerResolution)));
320   else
321       Threads.set_timer(100);
322
323   // We're ready to start searching. Call the iterative deepening loop function
324   id_loop(pos);
325
326   // Stop timer and send all the slaves to sleep, if not already sleeping
327   Threads.set_timer(0);
328   Threads.set_size(1);
329
330   if (Options["Use Search Log"])
331   {
332       int e = elapsed_time();
333
334       Log log(Options["Search Log Filename"]);
335       log << "Nodes: "          << pos.nodes_searched()
336           << "\nNodes/second: " << (e > 0 ? pos.nodes_searched() * 1000 / e : 0)
337           << "\nBest move: "    << move_to_san(pos, RootMoves[0].pv[0]);
338
339       StateInfo st;
340       pos.do_move(RootMoves[0].pv[0], st);
341       log << "\nPonder move: " << move_to_san(pos, RootMoves[0].pv[1]) << endl;
342       pos.undo_move(RootMoves[0].pv[0]);
343   }
344
345 finalize:
346
347   // When we reach max depth we arrive here even without Signals.stop is raised,
348   // but if we are pondering or in infinite search, we shouldn't print the best
349   // move before we are told to do so.
350   if (!Signals.stop && (Limits.ponder || Limits.infinite))
351       Threads.wait_for_stop_or_ponderhit();
352
353   // Best move could be MOVE_NONE when searching on a stalemate position
354   cout << "bestmove " << move_to_uci(RootMoves[0].pv[0], Chess960)
355        << " ponder "  << move_to_uci(RootMoves[0].pv[1], Chess960) << endl;
356 }
357
358
359 namespace {
360
361   // id_loop() is the main iterative deepening loop. It calls search() repeatedly
362   // with increasing depth until the allocated thinking time has been consumed,
363   // user stops the search, or the maximum search depth is reached.
364
365   void id_loop(Position& pos) {
366
367     Stack ss[MAX_PLY_PLUS_2];
368     int depth, prevBestMoveChanges;
369     Value bestValue, alpha, beta, delta;
370     bool bestMoveNeverChanged = true;
371     Move skillBest = MOVE_NONE;
372
373     memset(ss, 0, 4 * sizeof(Stack));
374     depth = BestMoveChanges = 0;
375     bestValue = delta = -VALUE_INFINITE;
376     ss->currentMove = MOVE_NULL; // Hack to skip update gains
377
378     // Iterative deepening loop until requested to stop or target depth reached
379     while (!Signals.stop && ++depth <= MAX_PLY && (!Limits.maxDepth || depth <= Limits.maxDepth))
380     {
381         // Save last iteration's scores before first PV line is searched and all
382         // the move scores but the (new) PV are set to -VALUE_INFINITE.
383         for (size_t i = 0; i < RootMoves.size(); i++)
384             RootMoves[i].prevScore = RootMoves[i].score;
385
386         prevBestMoveChanges = BestMoveChanges;
387         BestMoveChanges = 0;
388
389         // MultiPV loop. We perform a full root search for each PV line
390         for (PVIdx = 0; PVIdx < std::min(MultiPV, RootMoves.size()); PVIdx++)
391         {
392             // Set aspiration window default width
393             if (depth >= 5 && abs(RootMoves[PVIdx].prevScore) < VALUE_KNOWN_WIN)
394             {
395                 delta = Value(16);
396                 alpha = RootMoves[PVIdx].prevScore - delta;
397                 beta  = RootMoves[PVIdx].prevScore + delta;
398             }
399             else
400             {
401                 alpha = -VALUE_INFINITE;
402                 beta  =  VALUE_INFINITE;
403             }
404
405             // Start with a small aspiration window and, in case of fail high/low,
406             // research with bigger window until not failing high/low anymore.
407             do {
408                 // Search starts from ss+1 to allow referencing (ss-1). This is
409                 // needed by update gains and ss copy when splitting at Root.
410                 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
411
412                 // Bring to front the best move. It is critical that sorting is
413                 // done with a stable algorithm because all the values but the first
414                 // and eventually the new best one are set to -VALUE_INFINITE and
415                 // we want to keep the same order for all the moves but the new
416                 // PV that goes to the front. Note that in case of MultiPV search
417                 // the already searched PV lines are preserved.
418                 sort<RootMove>(RootMoves.begin() + PVIdx, RootMoves.end());
419
420                 // In case we have found an exact score and we are going to leave
421                 // the fail high/low loop then reorder the PV moves, otherwise
422                 // leave the last PV move in its position so to be searched again.
423                 // Of course this is needed only in MultiPV search.
424                 if (PVIdx && bestValue > alpha && bestValue < beta)
425                     sort<RootMove>(RootMoves.begin(), RootMoves.begin() + PVIdx);
426
427                 // Write PV back to transposition table in case the relevant
428                 // entries have been overwritten during the search.
429                 for (size_t i = 0; i <= PVIdx; i++)
430                     RootMoves[i].insert_pv_in_tt(pos);
431
432                 // If search has been stopped exit the aspiration window loop.
433                 // Sorting and writing PV back to TT is safe becuase RootMoves
434                 // is still valid, although refers to previous iteration.
435                 if (Signals.stop)
436                     break;
437
438                 // Send full PV info to GUI if we are going to leave the loop or
439                 // if we have a fail high/low and we are deep in the search.
440                 if ((bestValue > alpha && bestValue < beta) || elapsed_time() > 2000)
441                     pv_info_to_uci(pos, depth, alpha, beta);
442
443                 // In case of failing high/low increase aspiration window and
444                 // research, otherwise exit the fail high/low loop.
445                 if (bestValue >= beta)
446                 {
447                     beta += delta;
448                     delta += delta / 2;
449                 }
450                 else if (bestValue <= alpha)
451                 {
452                     Signals.failedLowAtRoot = true;
453                     Signals.stopOnPonderhit = false;
454
455                     alpha -= delta;
456                     delta += delta / 2;
457                 }
458                 else
459                     break;
460
461                 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
462
463             } while (abs(bestValue) < VALUE_KNOWN_WIN);
464         }
465
466         // Skills: Do we need to pick now the best move ?
467         if (SkillLevelEnabled && depth == 1 + SkillLevel)
468             skillBest = do_skill_level();
469
470         if (Options["Use Search Log"])
471              pv_info_to_log(pos, depth, bestValue, elapsed_time(), &RootMoves[0].pv[0]);
472
473         // Filter out startup noise when monitoring best move stability
474         if (depth > 2 && BestMoveChanges)
475             bestMoveNeverChanged = false;
476
477         // Do we have time for the next iteration? Can we stop searching now?
478         if (!Signals.stop && !Signals.stopOnPonderhit && Limits.use_time_management())
479         {
480             bool stop = false; // Local variable, not the volatile Signals.stop
481
482             // Take in account some extra time if the best move has changed
483             if (depth > 4 && depth < 50)
484                 TimeMgr.pv_instability(BestMoveChanges, prevBestMoveChanges);
485
486             // Stop search if most of available time is already consumed. We
487             // probably don't have enough time to search the first move at the
488             // next iteration anyway.
489             if (elapsed_time() > (TimeMgr.available_time() * 62) / 100)
490                 stop = true;
491
492             // Stop search early if one move seems to be much better than others
493             if (    depth >= 12
494                 && !stop
495                 && (   (bestMoveNeverChanged &&  pos.captured_piece_type())
496                     || elapsed_time() > (TimeMgr.available_time() * 40) / 100))
497             {
498                 Value rBeta = bestValue - EasyMoveMargin;
499                 (ss+1)->excludedMove = RootMoves[0].pv[0];
500                 (ss+1)->skipNullMove = true;
501                 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth - 3) * ONE_PLY);
502                 (ss+1)->skipNullMove = false;
503                 (ss+1)->excludedMove = MOVE_NONE;
504
505                 if (v < rBeta)
506                     stop = true;
507             }
508
509             if (stop)
510             {
511                 // If we are allowed to ponder do not stop the search now but
512                 // keep pondering until GUI sends "ponderhit" or "stop".
513                 if (Limits.ponder)
514                     Signals.stopOnPonderhit = true;
515                 else
516                     Signals.stop = true;
517             }
518         }
519     }
520
521     // When using skills swap best PV line with the sub-optimal one
522     if (SkillLevelEnabled)
523     {
524         if (skillBest == MOVE_NONE) // Still unassigned ?
525             skillBest = do_skill_level();
526
527         std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), skillBest));
528     }
529   }
530
531
532   // search<>() is the main search function for both PV and non-PV nodes and for
533   // normal and SplitPoint nodes. When called just after a split point the search
534   // is simpler because we have already probed the hash table, done a null move
535   // search, and searched the first move before splitting, we don't have to repeat
536   // all this work again. We also don't need to store anything to the hash table
537   // here: This is taken care of after we return from the split point.
538
539   template <NodeType NT>
540   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
541
542     const bool PvNode   = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
543     const bool SpNode   = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
544     const bool RootNode = (NT == Root || NT == SplitPointRoot);
545
546     assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
547     assert(PvNode == (alpha != beta - 1));
548     assert(depth > DEPTH_ZERO);
549     assert(pos.thread() >= 0 && pos.thread() < Threads.size());
550
551     Move movesSearched[MAX_MOVES];
552     StateInfo st;
553     const TTEntry *tte;
554     Key posKey;
555     Move ttMove, move, excludedMove, threatMove;
556     Depth ext, newDepth;
557     ValueType vt;
558     Value bestValue, value, oldAlpha;
559     Value refinedValue, nullValue, futilityBase, futilityValue;
560     bool isPvMove, inCheck, singularExtensionNode, givesCheck;
561     bool captureOrPromotion, dangerous, doFullDepthSearch;
562     int moveCount = 0, playedMoveCount = 0;
563     Thread& thread = Threads[pos.thread()];
564     SplitPoint* sp = NULL;
565
566     refinedValue = bestValue = value = -VALUE_INFINITE;
567     oldAlpha = alpha;
568     inCheck = pos.in_check();
569     ss->ply = (ss-1)->ply + 1;
570
571     // Used to send selDepth info to GUI
572     if (PvNode && thread.maxPly < ss->ply)
573         thread.maxPly = ss->ply;
574
575     // Step 1. Initialize node
576     if (!SpNode)
577     {
578         ss->currentMove = ss->bestMove = threatMove = (ss+1)->excludedMove = MOVE_NONE;
579         (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
580         (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
581     }
582     else
583     {
584         sp = ss->sp;
585         tte = NULL;
586         ttMove = excludedMove = MOVE_NONE;
587         threatMove = sp->threatMove;
588         goto split_point_start;
589     }
590
591     // Step 2. Check for aborted search and immediate draw
592     if ((   Signals.stop
593          || pos.is_draw<false>()
594          || ss->ply > MAX_PLY) && !RootNode)
595         return VALUE_DRAW;
596
597     // Step 3. Mate distance pruning. Even if we mate at the next move our score
598     // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
599     // a shorter mate was found upward in the tree then there is no need to search
600     // further, we will never beat current alpha. Same logic but with reversed signs
601     // applies also in the opposite condition of being mated instead of giving mate,
602     // in this case return a fail-high score.
603     if (!RootNode)
604     {
605         alpha = std::max(mated_in(ss->ply), alpha);
606         beta = std::min(mate_in(ss->ply+1), beta);
607         if (alpha >= beta)
608             return alpha;
609     }
610
611     // Step 4. Transposition table lookup
612     // We don't want the score of a partial search to overwrite a previous full search
613     // TT value, so we use a different position key in case of an excluded move.
614     excludedMove = ss->excludedMove;
615     posKey = excludedMove ? pos.exclusion_key() : pos.key();
616     tte = TT.probe(posKey);
617     ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
618
619     // At PV nodes we check for exact scores, while at non-PV nodes we check for
620     // a fail high/low. Biggest advantage at probing at PV nodes is to have a
621     // smooth experience in analysis mode. We don't probe at Root nodes otherwise
622     // we should also update RootMoveList to avoid bogus output.
623     if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == VALUE_TYPE_EXACT
624                                     : can_return_tt(tte, depth, beta, ss->ply)))
625     {
626         TT.refresh(tte);
627         ss->bestMove = move = ttMove; // Can be MOVE_NONE
628         value = value_from_tt(tte->value(), ss->ply);
629
630         if (   value >= beta
631             && move
632             && !pos.is_capture_or_promotion(move)
633             && move != ss->killers[0])
634         {
635             ss->killers[1] = ss->killers[0];
636             ss->killers[0] = move;
637         }
638         return value;
639     }
640
641     // Step 5. Evaluate the position statically and update parent's gain statistics
642     if (inCheck)
643         ss->eval = ss->evalMargin = VALUE_NONE;
644     else if (tte)
645     {
646         assert(tte->static_value() != VALUE_NONE);
647
648         ss->eval = tte->static_value();
649         ss->evalMargin = tte->static_value_margin();
650         refinedValue = refine_eval(tte, ss->eval, ss->ply);
651     }
652     else
653     {
654         refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
655         TT.store(posKey, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
656     }
657
658     // Update gain for the parent non-capture move given the static position
659     // evaluation before and after the move.
660     if (   (move = (ss-1)->currentMove) != MOVE_NULL
661         && (ss-1)->eval != VALUE_NONE
662         && ss->eval != VALUE_NONE
663         && !pos.captured_piece_type()
664         && !is_special(move))
665     {
666         Square to = to_sq(move);
667         H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
668     }
669
670     // Step 6. Razoring (is omitted in PV nodes)
671     if (   !PvNode
672         &&  depth < RazorDepth
673         && !inCheck
674         &&  refinedValue + razor_margin(depth) < beta
675         &&  ttMove == MOVE_NONE
676         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
677         && !pos.has_pawn_on_7th(pos.side_to_move()))
678     {
679         Value rbeta = beta - razor_margin(depth);
680         Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
681         if (v < rbeta)
682             // Logically we should return (v + razor_margin(depth)), but
683             // surprisingly this did slightly weaker in tests.
684             return v;
685     }
686
687     // Step 7. Static null move pruning (is omitted in PV nodes)
688     // We're betting that the opponent doesn't have a move that will reduce
689     // the score by more than futility_margin(depth) if we do a null move.
690     if (   !PvNode
691         && !ss->skipNullMove
692         &&  depth < RazorDepth
693         && !inCheck
694         &&  refinedValue - futility_margin(depth, 0) >= beta
695         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
696         &&  pos.non_pawn_material(pos.side_to_move()))
697         return refinedValue - futility_margin(depth, 0);
698
699     // Step 8. Null move search with verification search (is omitted in PV nodes)
700     if (   !PvNode
701         && !ss->skipNullMove
702         &&  depth > ONE_PLY
703         && !inCheck
704         &&  refinedValue >= beta
705         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
706         &&  pos.non_pawn_material(pos.side_to_move()))
707     {
708         ss->currentMove = MOVE_NULL;
709
710         // Null move dynamic reduction based on depth
711         int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);
712
713         // Null move dynamic reduction based on value
714         if (refinedValue - PawnValueMidgame > beta)
715             R++;
716
717         pos.do_null_move<true>(st);
718         (ss+1)->skipNullMove = true;
719         nullValue = depth-R*ONE_PLY < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
720                                               : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY);
721         (ss+1)->skipNullMove = false;
722         pos.do_null_move<false>(st);
723
724         if (nullValue >= beta)
725         {
726             // Do not return unproven mate scores
727             if (nullValue >= VALUE_MATE_IN_MAX_PLY)
728                 nullValue = beta;
729
730             if (depth < 6 * ONE_PLY)
731                 return nullValue;
732
733             // Do verification search at high depths
734             ss->skipNullMove = true;
735             Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY);
736             ss->skipNullMove = false;
737
738             if (v >= beta)
739                 return nullValue;
740         }
741         else
742         {
743             // The null move failed low, which means that we may be faced with
744             // some kind of threat. If the previous move was reduced, check if
745             // the move that refuted the null move was somehow connected to the
746             // move which was reduced. If a connection is found, return a fail
747             // low score (which will cause the reduced move to fail high in the
748             // parent node, which will trigger a re-search with full depth).
749             threatMove = (ss+1)->bestMove;
750
751             if (   depth < ThreatDepth
752                 && (ss-1)->reduction
753                 && threatMove != MOVE_NONE
754                 && connected_moves(pos, (ss-1)->currentMove, threatMove))
755                 return beta - 1;
756         }
757     }
758
759     // Step 9. ProbCut (is omitted in PV nodes)
760     // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
761     // and a reduced search returns a value much above beta, we can (almost) safely
762     // prune the previous move.
763     if (   !PvNode
764         &&  depth >= RazorDepth + ONE_PLY
765         && !inCheck
766         && !ss->skipNullMove
767         &&  excludedMove == MOVE_NONE
768         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY)
769     {
770         Value rbeta = beta + 200;
771         Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
772
773         assert(rdepth >= ONE_PLY);
774
775         MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
776         CheckInfo ci(pos);
777
778         while ((move = mp.next_move()) != MOVE_NONE)
779             if (pos.pl_move_is_legal(move, ci.pinned))
780             {
781                 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
782                 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
783                 pos.undo_move(move);
784                 if (value >= rbeta)
785                     return value;
786             }
787     }
788
789     // Step 10. Internal iterative deepening
790     if (   depth >= IIDDepth[PvNode]
791         && ttMove == MOVE_NONE
792         && (PvNode || (!inCheck && ss->eval + IIDMargin >= beta)))
793     {
794         Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
795
796         ss->skipNullMove = true;
797         search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
798         ss->skipNullMove = false;
799
800         tte = TT.probe(posKey);
801         ttMove = tte ? tte->move() : MOVE_NONE;
802     }
803
804 split_point_start: // At split points actual search starts from here
805
806     MovePickerExt<SpNode> mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
807     CheckInfo ci(pos);
808     ss->bestMove = MOVE_NONE;
809     futilityBase = ss->eval + ss->evalMargin;
810     singularExtensionNode =   !RootNode
811                            && !SpNode
812                            && depth >= SingularExtensionDepth[PvNode]
813                            && ttMove != MOVE_NONE
814                            && !excludedMove // Recursive singular search is not allowed
815                            && (tte->type() & VALUE_TYPE_LOWER)
816                            && tte->depth() >= depth - 3 * ONE_PLY;
817     if (SpNode)
818     {
819         lock_grab(&(sp->lock));
820         bestValue = sp->bestValue;
821         moveCount = sp->moveCount;
822
823         assert(bestValue > -VALUE_INFINITE && moveCount > 0);
824     }
825
826     // Step 11. Loop through moves
827     // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
828     while (   bestValue < beta
829            && (move = mp.next_move()) != MOVE_NONE
830            && !thread.cutoff_occurred()
831            && !Signals.stop)
832     {
833       assert(is_ok(move));
834
835       if (move == excludedMove)
836           continue;
837
838       // At root obey the "searchmoves" option and skip moves not listed in Root
839       // Move List, as a consequence any illegal move is also skipped. In MultiPV
840       // mode we also skip PV moves which have been already searched.
841       if (RootNode && !count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
842           continue;
843
844       // At PV and SpNode nodes we want all moves to be legal since the beginning
845       if ((PvNode || SpNode) && !pos.pl_move_is_legal(move, ci.pinned))
846           continue;
847
848       if (SpNode)
849       {
850           moveCount = ++sp->moveCount;
851           lock_release(&(sp->lock));
852       }
853       else
854           moveCount++;
855
856       if (RootNode)
857       {
858           Signals.firstRootMove = (moveCount == 1);
859
860           if (pos.thread() == 0 && elapsed_time() > 2000)
861               cout << "info depth " << depth / ONE_PLY
862                    << " currmove " << move_to_uci(move, Chess960)
863                    << " currmovenumber " << moveCount + PVIdx << endl;
864       }
865
866       isPvMove = (PvNode && moveCount <= 1);
867       captureOrPromotion = pos.is_capture_or_promotion(move);
868       givesCheck = pos.move_gives_check(move, ci);
869       dangerous = givesCheck || is_dangerous(pos, move, captureOrPromotion);
870       ext = DEPTH_ZERO;
871
872       // Step 12. Extend checks and, in PV nodes, also dangerous moves
873       if (PvNode && dangerous)
874           ext = ONE_PLY;
875
876       else if (givesCheck && pos.see_sign(move) >= 0)
877           ext = PvNode ? ONE_PLY : ONE_PLY / 2;
878
879       // Singular extension search. If all moves but one fail low on a search of
880       // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
881       // is singular and should be extended. To verify this we do a reduced search
882       // on all the other moves but the ttMove, if result is lower than ttValue minus
883       // a margin then we extend ttMove.
884       if (   singularExtensionNode
885           && !ext
886           && move == ttMove
887           && pos.pl_move_is_legal(move, ci.pinned))
888       {
889           Value ttValue = value_from_tt(tte->value(), ss->ply);
890
891           if (abs(ttValue) < VALUE_KNOWN_WIN)
892           {
893               Value rBeta = ttValue - int(depth);
894               ss->excludedMove = move;
895               ss->skipNullMove = true;
896               value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
897               ss->skipNullMove = false;
898               ss->excludedMove = MOVE_NONE;
899               ss->bestMove = MOVE_NONE;
900               if (value < rBeta)
901                   ext = ONE_PLY;
902           }
903       }
904
905       // Update current move (this must be done after singular extension search)
906       newDepth = depth - ONE_PLY + ext;
907
908       // Step 13. Futility pruning (is omitted in PV nodes)
909       if (   !PvNode
910           && !captureOrPromotion
911           && !inCheck
912           && !dangerous
913           &&  move != ttMove
914           && !is_castle(move)
915           && (bestValue > VALUE_MATED_IN_MAX_PLY || bestValue == -VALUE_INFINITE))
916       {
917           // Move count based pruning
918           if (   moveCount >= futility_move_count(depth)
919               && (!threatMove || !connected_threat(pos, move, threatMove)))
920           {
921               if (SpNode)
922                   lock_grab(&(sp->lock));
923
924               continue;
925           }
926
927           // Value based pruning
928           // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
929           // but fixing this made program slightly weaker.
930           Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
931           futilityValue =  futilityBase + futility_margin(predictedDepth, moveCount)
932                          + H.gain(pos.piece_moved(move), to_sq(move));
933
934           if (futilityValue < beta)
935           {
936               if (SpNode)
937                   lock_grab(&(sp->lock));
938
939               continue;
940           }
941
942           // Prune moves with negative SEE at low depths
943           if (   predictedDepth < 2 * ONE_PLY
944               && pos.see_sign(move) < 0)
945           {
946               if (SpNode)
947                   lock_grab(&(sp->lock));
948
949               continue;
950           }
951       }
952
953       // Check for legality only before to do the move
954       if (!pos.pl_move_is_legal(move, ci.pinned))
955       {
956           moveCount--;
957           continue;
958       }
959
960       ss->currentMove = move;
961       if (!SpNode && !captureOrPromotion)
962           movesSearched[playedMoveCount++] = move;
963
964       // Step 14. Make the move
965       pos.do_move(move, st, ci, givesCheck);
966
967       // Step 15. Reduced depth search (LMR). If the move fails high will be
968       // re-searched at full depth.
969       if (   depth > 4 * ONE_PLY
970           && !isPvMove
971           && !captureOrPromotion
972           && !dangerous
973           && !is_castle(move)
974           &&  ss->killers[0] != move
975           &&  ss->killers[1] != move)
976       {
977           ss->reduction = reduction<PvNode>(depth, moveCount);
978           Depth d = std::max(newDepth - ss->reduction, ONE_PLY);
979           alpha = SpNode ? sp->alpha : alpha;
980
981           value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
982
983           doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
984           ss->reduction = DEPTH_ZERO;
985       }
986       else
987           doFullDepthSearch = !isPvMove;
988
989       // Step 16. Full depth search, when LMR is skipped or fails high
990       if (doFullDepthSearch)
991       {
992           alpha = SpNode ? sp->alpha : alpha;
993           value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
994                                      : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
995       }
996
997       // Only for PV nodes do a full PV search on the first move or after a fail
998       // high, in the latter case search only if value < beta, otherwise let the
999       // parent node to fail low with value <= alpha and to try another move.
1000       if (PvNode && (isPvMove || (value > alpha && (RootNode || value < beta))))
1001           value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
1002                                      : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
1003
1004       // Step 17. Undo move
1005       pos.undo_move(move);
1006
1007       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1008
1009       // Step 18. Check for new best move
1010       if (SpNode)
1011       {
1012           lock_grab(&(sp->lock));
1013           bestValue = sp->bestValue;
1014           alpha = sp->alpha;
1015       }
1016
1017       // Finished searching the move. If StopRequest is true, the search
1018       // was aborted because the user interrupted the search or because we
1019       // ran out of time. In this case, the return value of the search cannot
1020       // be trusted, and we don't update the best move and/or PV.
1021       if (RootNode && !Signals.stop)
1022       {
1023           RootMove& rm = *find(RootMoves.begin(), RootMoves.end(), move);
1024
1025           // PV move or new best move ?
1026           if (isPvMove || value > alpha)
1027           {
1028               rm.score = value;
1029               rm.extract_pv_from_tt(pos);
1030
1031               // We record how often the best move has been changed in each
1032               // iteration. This information is used for time management: When
1033               // the best move changes frequently, we allocate some more time.
1034               if (!isPvMove && MultiPV == 1)
1035                   BestMoveChanges++;
1036           }
1037           else
1038               // All other moves but the PV are set to the lowest value, this
1039               // is not a problem when sorting becuase sort is stable and move
1040               // position in the list is preserved, just the PV is pushed up.
1041               rm.score = -VALUE_INFINITE;
1042
1043       }
1044
1045       if (value > bestValue)
1046       {
1047           bestValue = value;
1048           ss->bestMove = move;
1049
1050           if (   PvNode
1051               && value > alpha
1052               && value < beta) // We want always alpha < beta
1053               alpha = value;
1054
1055           if (SpNode && !thread.cutoff_occurred())
1056           {
1057               sp->bestValue = value;
1058               sp->ss->bestMove = move;
1059               sp->alpha = alpha;
1060               sp->is_betaCutoff = (value >= beta);
1061           }
1062       }
1063
1064       // Step 19. Check for split
1065       if (   !SpNode
1066           && depth >= Threads.min_split_depth()
1067           && bestValue < beta
1068           && Threads.available_slave_exists(pos.thread())
1069           && !Signals.stop
1070           && !thread.cutoff_occurred())
1071           bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, depth,
1072                                                threatMove, moveCount, &mp, NT);
1073     }
1074
1075     // Step 20. Check for mate and stalemate
1076     // All legal moves have been searched and if there are no legal moves, it
1077     // must be mate or stalemate. Note that we can have a false positive in
1078     // case of StopRequest or thread.cutoff_occurred() are set, but this is
1079     // harmless because return value is discarded anyhow in the parent nodes.
1080     // If we are in a singular extension search then return a fail low score.
1081     if (!moveCount)
1082         return excludedMove ? oldAlpha : inCheck ? mated_in(ss->ply) : VALUE_DRAW;
1083
1084     // If we have pruned all the moves without searching return a fail-low score
1085     if (bestValue == -VALUE_INFINITE)
1086     {
1087         assert(!playedMoveCount);
1088
1089         bestValue = alpha;
1090     }
1091
1092     // Step 21. Update tables
1093     // Update transposition table entry, killers and history
1094     if (!SpNode && !Signals.stop && !thread.cutoff_occurred())
1095     {
1096         move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1097         vt   = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1098              : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1099
1100         TT.store(posKey, value_to_tt(bestValue, ss->ply), vt, depth, move, ss->eval, ss->evalMargin);
1101
1102         // Update killers and history for non capture cut-off moves
1103         if (    bestValue >= beta
1104             && !pos.is_capture_or_promotion(move)
1105             && !inCheck)
1106         {
1107             if (move != ss->killers[0])
1108             {
1109                 ss->killers[1] = ss->killers[0];
1110                 ss->killers[0] = move;
1111             }
1112
1113             // Increase history value of the cut-off move
1114             Value bonus = Value(int(depth) * int(depth));
1115             H.add(pos.piece_moved(move), to_sq(move), bonus);
1116
1117             // Decrease history of all the other played non-capture moves
1118             for (int i = 0; i < playedMoveCount - 1; i++)
1119             {
1120                 Move m = movesSearched[i];
1121                 H.add(pos.piece_moved(m), to_sq(m), -bonus);
1122             }
1123         }
1124     }
1125
1126     if (SpNode)
1127     {
1128         // Here we have the lock still grabbed
1129         sp->is_slave[pos.thread()] = false;
1130         sp->nodes += pos.nodes_searched();
1131         lock_release(&(sp->lock));
1132     }
1133
1134     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1135
1136     return bestValue;
1137   }
1138
1139
1140   // qsearch() is the quiescence search function, which is called by the main
1141   // search function when the remaining depth is zero (or, to be more precise,
1142   // less than ONE_PLY).
1143
1144   template <NodeType NT>
1145   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1146
1147     const bool PvNode = (NT == PV);
1148
1149     assert(NT == PV || NT == NonPV);
1150     assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1151     assert(PvNode == (alpha != beta - 1));
1152     assert(depth <= DEPTH_ZERO);
1153     assert(pos.thread() >= 0 && pos.thread() < Threads.size());
1154
1155     StateInfo st;
1156     Move ttMove, move;
1157     Value bestValue, value, evalMargin, futilityValue, futilityBase;
1158     bool inCheck, enoughMaterial, givesCheck, evasionPrunable;
1159     const TTEntry* tte;
1160     Depth ttDepth;
1161     ValueType vt;
1162     Value oldAlpha = alpha;
1163
1164     ss->bestMove = ss->currentMove = MOVE_NONE;
1165     ss->ply = (ss-1)->ply + 1;
1166
1167     // Check for an instant draw or maximum ply reached
1168     if (pos.is_draw<true>() || ss->ply > MAX_PLY)
1169         return VALUE_DRAW;
1170
1171     // Decide whether or not to include checks, this fixes also the type of
1172     // TT entry depth that we are going to use. Note that in qsearch we use
1173     // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1174     inCheck = pos.in_check();
1175     ttDepth = (inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1176
1177     // Transposition table lookup. At PV nodes, we don't use the TT for
1178     // pruning, but only for move ordering.
1179     tte = TT.probe(pos.key());
1180     ttMove = (tte ? tte->move() : MOVE_NONE);
1181
1182     if (!PvNode && tte && can_return_tt(tte, ttDepth, beta, ss->ply))
1183     {
1184         ss->bestMove = ttMove; // Can be MOVE_NONE
1185         return value_from_tt(tte->value(), ss->ply);
1186     }
1187
1188     // Evaluate the position statically
1189     if (inCheck)
1190     {
1191         bestValue = futilityBase = -VALUE_INFINITE;
1192         ss->eval = evalMargin = VALUE_NONE;
1193         enoughMaterial = false;
1194     }
1195     else
1196     {
1197         if (tte)
1198         {
1199             assert(tte->static_value() != VALUE_NONE);
1200
1201             evalMargin = tte->static_value_margin();
1202             ss->eval = bestValue = tte->static_value();
1203         }
1204         else
1205             ss->eval = bestValue = evaluate(pos, evalMargin);
1206
1207         // Stand pat. Return immediately if static value is at least beta
1208         if (bestValue >= beta)
1209         {
1210             if (!tte)
1211                 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), VALUE_TYPE_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1212
1213             return bestValue;
1214         }
1215
1216         if (PvNode && bestValue > alpha)
1217             alpha = bestValue;
1218
1219         futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1220         enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1221     }
1222
1223     // Initialize a MovePicker object for the current position, and prepare
1224     // to search the moves. Because the depth is <= 0 here, only captures,
1225     // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1226     // be generated.
1227     MovePicker mp(pos, ttMove, depth, H, to_sq((ss-1)->currentMove));
1228     CheckInfo ci(pos);
1229
1230     // Loop through the moves until no moves remain or a beta cutoff occurs
1231     while (   bestValue < beta
1232            && (move = mp.next_move()) != MOVE_NONE)
1233     {
1234       assert(is_ok(move));
1235
1236       givesCheck = pos.move_gives_check(move, ci);
1237
1238       // Futility pruning
1239       if (   !PvNode
1240           && !inCheck
1241           && !givesCheck
1242           &&  move != ttMove
1243           &&  enoughMaterial
1244           && !is_promotion(move)
1245           && !pos.is_passed_pawn_push(move))
1246       {
1247           futilityValue =  futilityBase
1248                          + PieceValueEndgame[pos.piece_on(to_sq(move))]
1249                          + (is_enpassant(move) ? PawnValueEndgame : VALUE_ZERO);
1250
1251           if (futilityValue < beta)
1252           {
1253               if (futilityValue > bestValue)
1254                   bestValue = futilityValue;
1255
1256               continue;
1257           }
1258
1259           // Prune moves with negative or equal SEE
1260           if (   futilityBase < beta
1261               && depth < DEPTH_ZERO
1262               && pos.see(move) <= 0)
1263               continue;
1264       }
1265
1266       // Detect non-capture evasions that are candidate to be pruned
1267       evasionPrunable =   !PvNode
1268                        && inCheck
1269                        && bestValue > VALUE_MATED_IN_MAX_PLY
1270                        && !pos.is_capture(move)
1271                        && !pos.can_castle(pos.side_to_move());
1272
1273       // Don't search moves with negative SEE values
1274       if (   !PvNode
1275           && (!inCheck || evasionPrunable)
1276           &&  move != ttMove
1277           && !is_promotion(move)
1278           &&  pos.see_sign(move) < 0)
1279           continue;
1280
1281       // Don't search useless checks
1282       if (   !PvNode
1283           && !inCheck
1284           &&  givesCheck
1285           &&  move != ttMove
1286           && !pos.is_capture_or_promotion(move)
1287           &&  ss->eval + PawnValueMidgame / 4 < beta
1288           && !check_is_dangerous(pos, move, futilityBase, beta, &bestValue))
1289       {
1290           if (ss->eval + PawnValueMidgame / 4 > bestValue)
1291               bestValue = ss->eval + PawnValueMidgame / 4;
1292
1293           continue;
1294       }
1295
1296       // Check for legality only before to do the move
1297       if (!pos.pl_move_is_legal(move, ci.pinned))
1298           continue;
1299
1300       ss->currentMove = move;
1301
1302       // Make and search the move
1303       pos.do_move(move, st, ci, givesCheck);
1304       value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1305       pos.undo_move(move);
1306
1307       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1308
1309       // New best move?
1310       if (value > bestValue)
1311       {
1312           bestValue = value;
1313           ss->bestMove = move;
1314
1315           if (   PvNode
1316               && value > alpha
1317               && value < beta) // We want always alpha < beta
1318               alpha = value;
1319        }
1320     }
1321
1322     // All legal moves have been searched. A special case: If we're in check
1323     // and no legal moves were found, it is checkmate.
1324     if (inCheck && bestValue == -VALUE_INFINITE)
1325         return mated_in(ss->ply); // Plies to mate from the root
1326
1327     // Update transposition table
1328     move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1329     vt   = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1330          : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1331
1332     TT.store(pos.key(), value_to_tt(bestValue, ss->ply), vt, ttDepth, move, ss->eval, evalMargin);
1333
1334     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1335
1336     return bestValue;
1337   }
1338
1339
1340   // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1341   // bestValue is updated only when returning false because in that case move
1342   // will be pruned.
1343
1344   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bestValue)
1345   {
1346     Bitboard b, occ, oldAtt, newAtt, kingAtt;
1347     Square from, to, ksq, victimSq;
1348     Piece pc;
1349     Color them;
1350     Value futilityValue, bv = *bestValue;
1351
1352     from = from_sq(move);
1353     to = to_sq(move);
1354     them = ~pos.side_to_move();
1355     ksq = pos.king_square(them);
1356     kingAtt = pos.attacks_from<KING>(ksq);
1357     pc = pos.piece_on(from);
1358
1359     occ = pos.occupied_squares() & ~(1ULL << from) & ~(1ULL << ksq);
1360     oldAtt = pos.attacks_from(pc, from, occ);
1361     newAtt = pos.attacks_from(pc,   to, occ);
1362
1363     // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1364     b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1365
1366     if (!(b && (b & (b - 1))))
1367         return true;
1368
1369     // Rule 2. Queen contact check is very dangerous
1370     if (   type_of(pc) == QUEEN
1371         && bit_is_set(kingAtt, to))
1372         return true;
1373
1374     // Rule 3. Creating new double threats with checks
1375     b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1376
1377     while (b)
1378     {
1379         victimSq = pop_1st_bit(&b);
1380         futilityValue = futilityBase + PieceValueEndgame[pos.piece_on(victimSq)];
1381
1382         // Note that here we generate illegal "double move"!
1383         if (   futilityValue >= beta
1384             && pos.see_sign(make_move(from, victimSq)) >= 0)
1385             return true;
1386
1387         if (futilityValue > bv)
1388             bv = futilityValue;
1389     }
1390
1391     // Update bestValue only if check is not dangerous (because we will prune the move)
1392     *bestValue = bv;
1393     return false;
1394   }
1395
1396
1397   // connected_moves() tests whether two moves are 'connected' in the sense
1398   // that the first move somehow made the second move possible (for instance
1399   // if the moving piece is the same in both moves). The first move is assumed
1400   // to be the move that was made to reach the current position, while the
1401   // second move is assumed to be a move from the current position.
1402
1403   bool connected_moves(const Position& pos, Move m1, Move m2) {
1404
1405     Square f1, t1, f2, t2;
1406     Piece p1, p2;
1407     Square ksq;
1408
1409     assert(is_ok(m1));
1410     assert(is_ok(m2));
1411
1412     // Case 1: The moving piece is the same in both moves
1413     f2 = from_sq(m2);
1414     t1 = to_sq(m1);
1415     if (f2 == t1)
1416         return true;
1417
1418     // Case 2: The destination square for m2 was vacated by m1
1419     t2 = to_sq(m2);
1420     f1 = from_sq(m1);
1421     if (t2 == f1)
1422         return true;
1423
1424     // Case 3: Moving through the vacated square
1425     p2 = pos.piece_on(f2);
1426     if (   piece_is_slider(p2)
1427         && bit_is_set(squares_between(f2, t2), f1))
1428       return true;
1429
1430     // Case 4: The destination square for m2 is defended by the moving piece in m1
1431     p1 = pos.piece_on(t1);
1432     if (bit_is_set(pos.attacks_from(p1, t1), t2))
1433         return true;
1434
1435     // Case 5: Discovered check, checking piece is the piece moved in m1
1436     ksq = pos.king_square(pos.side_to_move());
1437     if (    piece_is_slider(p1)
1438         &&  bit_is_set(squares_between(t1, ksq), f2))
1439     {
1440         Bitboard occ = pos.occupied_squares();
1441         clear_bit(&occ, f2);
1442         if (bit_is_set(pos.attacks_from(p1, t1, occ), ksq))
1443             return true;
1444     }
1445     return false;
1446   }
1447
1448
1449   // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1450   // "plies to mate from the current position". Non-mate scores are unchanged.
1451   // The function is called before storing a value to the transposition table.
1452
1453   Value value_to_tt(Value v, int ply) {
1454
1455     if (v >= VALUE_MATE_IN_MAX_PLY)
1456       return v + ply;
1457
1458     if (v <= VALUE_MATED_IN_MAX_PLY)
1459       return v - ply;
1460
1461     return v;
1462   }
1463
1464
1465   // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
1466   // from the transposition table (where refers to the plies to mate/be mated
1467   // from current position) to "plies to mate/be mated from the root".
1468
1469   Value value_from_tt(Value v, int ply) {
1470
1471     if (v >= VALUE_MATE_IN_MAX_PLY)
1472       return v - ply;
1473
1474     if (v <= VALUE_MATED_IN_MAX_PLY)
1475       return v + ply;
1476
1477     return v;
1478   }
1479
1480
1481   // connected_threat() tests whether it is safe to forward prune a move or if
1482   // is somehow connected to the threat move returned by null search.
1483
1484   bool connected_threat(const Position& pos, Move m, Move threat) {
1485
1486     assert(is_ok(m));
1487     assert(is_ok(threat));
1488     assert(!pos.is_capture_or_promotion(m));
1489     assert(!pos.is_passed_pawn_push(m));
1490
1491     Square mfrom, mto, tfrom, tto;
1492
1493     mfrom = from_sq(m);
1494     mto = to_sq(m);
1495     tfrom = from_sq(threat);
1496     tto = to_sq(threat);
1497
1498     // Case 1: Don't prune moves which move the threatened piece
1499     if (mfrom == tto)
1500         return true;
1501
1502     // Case 2: If the threatened piece has value less than or equal to the
1503     // value of the threatening piece, don't prune moves which defend it.
1504     if (   pos.is_capture(threat)
1505         && (   PieceValueMidgame[pos.piece_on(tfrom)] >= PieceValueMidgame[pos.piece_on(tto)]
1506             || type_of(pos.piece_on(tfrom)) == KING)
1507         && pos.move_attacks_square(m, tto))
1508         return true;
1509
1510     // Case 3: If the moving piece in the threatened move is a slider, don't
1511     // prune safe moves which block its ray.
1512     if (   piece_is_slider(pos.piece_on(tfrom))
1513         && bit_is_set(squares_between(tfrom, tto), mto)
1514         && pos.see_sign(m) >= 0)
1515         return true;
1516
1517     return false;
1518   }
1519
1520
1521   // can_return_tt() returns true if a transposition table score can be used to
1522   // cut-off at a given point in search.
1523
1524   bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply) {
1525
1526     Value v = value_from_tt(tte->value(), ply);
1527
1528     return   (   tte->depth() >= depth
1529               || v >= std::max(VALUE_MATE_IN_MAX_PLY, beta)
1530               || v < std::min(VALUE_MATED_IN_MAX_PLY, beta))
1531
1532           && (   ((tte->type() & VALUE_TYPE_LOWER) && v >= beta)
1533               || ((tte->type() & VALUE_TYPE_UPPER) && v < beta));
1534   }
1535
1536
1537   // refine_eval() returns the transposition table score if possible, otherwise
1538   // falls back on static position evaluation.
1539
1540   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1541
1542       assert(tte);
1543
1544       Value v = value_from_tt(tte->value(), ply);
1545
1546       if (   ((tte->type() & VALUE_TYPE_LOWER) && v >= defaultEval)
1547           || ((tte->type() & VALUE_TYPE_UPPER) && v < defaultEval))
1548           return v;
1549
1550       return defaultEval;
1551   }
1552
1553
1554   // current_search_time() returns the number of milliseconds which have passed
1555   // since the beginning of the current search.
1556
1557   int elapsed_time(bool reset) {
1558
1559     static int searchStartTime;
1560
1561     if (reset)
1562         searchStartTime = system_time();
1563
1564     return system_time() - searchStartTime;
1565   }
1566
1567
1568   // score_to_uci() converts a value to a string suitable for use with the UCI
1569   // protocol specifications:
1570   //
1571   // cp <x>     The score from the engine's point of view in centipawns.
1572   // mate <y>   Mate in y moves, not plies. If the engine is getting mated
1573   //            use negative values for y.
1574
1575   string score_to_uci(Value v, Value alpha, Value beta) {
1576
1577     std::stringstream s;
1578
1579     if (abs(v) < VALUE_MATE_IN_MAX_PLY)
1580         s << "cp " << v * 100 / int(PawnValueMidgame);
1581     else
1582         s << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
1583
1584     s << (v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");
1585
1586     return s.str();
1587   }
1588
1589
1590   // pv_info_to_uci() sends search info to GUI. UCI protocol requires to send all
1591   // the PV lines also if are still to be searched and so refer to the previous
1592   // search score.
1593
1594   void pv_info_to_uci(const Position& pos, int depth, Value alpha, Value beta) {
1595
1596     int t = elapsed_time();
1597     int selDepth = 0;
1598
1599     for (int i = 0; i < Threads.size(); i++)
1600         if (Threads[i].maxPly > selDepth)
1601             selDepth = Threads[i].maxPly;
1602
1603     for (size_t i = 0; i < std::min(UCIMultiPV, RootMoves.size()); i++)
1604     {
1605         bool updated = (i <= PVIdx);
1606
1607         if (depth == 1 && !updated)
1608             continue;
1609
1610         int d = (updated ? depth : depth - 1);
1611         Value v = (updated ? RootMoves[i].score : RootMoves[i].prevScore);
1612         std::stringstream s;
1613
1614         for (int j = 0; RootMoves[i].pv[j] != MOVE_NONE; j++)
1615             s <<  " " << move_to_uci(RootMoves[i].pv[j], Chess960);
1616
1617         cout << "info depth " << d
1618              << " seldepth " << selDepth
1619              << " score " << (i == PVIdx ? score_to_uci(v, alpha, beta) : score_to_uci(v))
1620              << " nodes " << pos.nodes_searched()
1621              << " nps " << (t > 0 ? pos.nodes_searched() * 1000 / t : 0)
1622              << " time " << t
1623              << " multipv " << i + 1
1624              << " pv" << s.str() << endl;
1625     }
1626   }
1627
1628
1629   // pv_info_to_log() writes human-readable search information to the log file
1630   // (which is created when the UCI parameter "Use Search Log" is "true"). It
1631   // uses the two below helpers to pretty format time and score respectively.
1632
1633   string time_to_string(int millisecs) {
1634
1635     const int MSecMinute = 1000 * 60;
1636     const int MSecHour   = 1000 * 60 * 60;
1637
1638     int hours = millisecs / MSecHour;
1639     int minutes =  (millisecs % MSecHour) / MSecMinute;
1640     int seconds = ((millisecs % MSecHour) % MSecMinute) / 1000;
1641
1642     std::stringstream s;
1643
1644     if (hours)
1645         s << hours << ':';
1646
1647     s << std::setfill('0') << std::setw(2) << minutes << ':'
1648                            << std::setw(2) << seconds;
1649     return s.str();
1650   }
1651
1652   string score_to_string(Value v) {
1653
1654     std::stringstream s;
1655
1656     if (v >= VALUE_MATE_IN_MAX_PLY)
1657         s << "#" << (VALUE_MATE - v + 1) / 2;
1658     else if (v <= VALUE_MATED_IN_MAX_PLY)
1659         s << "-#" << (VALUE_MATE + v) / 2;
1660     else
1661         s << std::setprecision(2) << std::fixed << std::showpos
1662           << float(v) / PawnValueMidgame;
1663
1664     return s.str();
1665   }
1666
1667   void pv_info_to_log(Position& pos, int depth, Value value, int time, Move pv[]) {
1668
1669     const int64_t K = 1000;
1670     const int64_t M = 1000000;
1671
1672     StateInfo state[MAX_PLY_PLUS_2], *st = state;
1673     Move* m = pv;
1674     string san, padding;
1675     size_t length;
1676     std::stringstream s;
1677
1678     s << std::setw(2) << depth
1679       << std::setw(8) << score_to_string(value)
1680       << std::setw(8) << time_to_string(time);
1681
1682     if (pos.nodes_searched() < M)
1683         s << std::setw(8) << pos.nodes_searched() / 1 << "  ";
1684
1685     else if (pos.nodes_searched() < K * M)
1686         s << std::setw(7) << pos.nodes_searched() / K << "K  ";
1687
1688     else
1689         s << std::setw(7) << pos.nodes_searched() / M << "M  ";
1690
1691     padding = string(s.str().length(), ' ');
1692     length = padding.length();
1693
1694     while (*m != MOVE_NONE)
1695     {
1696         san = move_to_san(pos, *m);
1697
1698         if (length + san.length() > 80)
1699         {
1700             s << "\n" + padding;
1701             length = padding.length();
1702         }
1703
1704         s << san << ' ';
1705         length += san.length() + 1;
1706
1707         pos.do_move(*m++, *st++);
1708     }
1709
1710     while (m != pv)
1711         pos.undo_move(*--m);
1712
1713     Log l(Options["Search Log Filename"]);
1714     l << s.str() << endl;
1715   }
1716
1717
1718   // When playing with strength handicap choose best move among the MultiPV set
1719   // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1720
1721   Move do_skill_level() {
1722
1723     assert(MultiPV > 1);
1724
1725     static RKISS rk;
1726
1727     // PRNG sequence should be not deterministic
1728     for (int i = abs(system_time() % 50); i > 0; i--)
1729         rk.rand<unsigned>();
1730
1731     // RootMoves are already sorted by score in descending order
1732     size_t size = std::min(MultiPV, RootMoves.size());
1733     int variance = std::min(RootMoves[0].score - RootMoves[size - 1].score, PawnValueMidgame);
1734     int weakness = 120 - 2 * SkillLevel;
1735     int max_s = -VALUE_INFINITE;
1736     Move best = MOVE_NONE;
1737
1738     // Choose best move. For each move score we add two terms both dependent on
1739     // weakness, one deterministic and bigger for weaker moves, and one random,
1740     // then we choose the move with the resulting highest score.
1741     for (size_t i = 0; i < size; i++)
1742     {
1743         int s = RootMoves[i].score;
1744
1745         // Don't allow crazy blunders even at very low skills
1746         if (i > 0 && RootMoves[i-1].score > s + EasyMoveMargin)
1747             break;
1748
1749         // This is our magic formula
1750         s += (  weakness * int(RootMoves[0].score - s)
1751               + variance * (rk.rand<unsigned>() % weakness)) / 128;
1752
1753         if (s > max_s)
1754         {
1755             max_s = s;
1756             best = RootMoves[i].pv[0];
1757         }
1758     }
1759     return best;
1760   }
1761
1762 } // namespace
1763
1764
1765 /// RootMove::extract_pv_from_tt() builds a PV by adding moves from the TT table.
1766 /// We consider also failing high nodes and not only VALUE_TYPE_EXACT nodes so
1767 /// to allow to always have a ponder move even when we fail high at root, and
1768 /// a long PV to print that is important for position analysis.
1769
1770 void RootMove::extract_pv_from_tt(Position& pos) {
1771
1772   StateInfo state[MAX_PLY_PLUS_2], *st = state;
1773   TTEntry* tte;
1774   int ply = 1;
1775   Move m = pv[0];
1776
1777   assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1778
1779   pv.clear();
1780   pv.push_back(m);
1781   pos.do_move(m, *st++);
1782
1783   while (   (tte = TT.probe(pos.key())) != NULL
1784          && tte->move() != MOVE_NONE
1785          && pos.is_pseudo_legal(tte->move())
1786          && pos.pl_move_is_legal(tte->move(), pos.pinned_pieces())
1787          && ply < MAX_PLY
1788          && (!pos.is_draw<false>() || ply < 2))
1789   {
1790       pv.push_back(tte->move());
1791       pos.do_move(tte->move(), *st++);
1792       ply++;
1793   }
1794   pv.push_back(MOVE_NONE);
1795
1796   do pos.undo_move(pv[--ply]); while (ply);
1797 }
1798
1799
1800 /// RootMove::insert_pv_in_tt() is called at the end of a search iteration, and
1801 /// inserts the PV back into the TT. This makes sure the old PV moves are searched
1802 /// first, even if the old TT entries have been overwritten.
1803
1804 void RootMove::insert_pv_in_tt(Position& pos) {
1805
1806   StateInfo state[MAX_PLY_PLUS_2], *st = state;
1807   TTEntry* tte;
1808   Key k;
1809   Value v, m = VALUE_NONE;
1810   int ply = 0;
1811
1812   assert(pv[ply] != MOVE_NONE && pos.is_pseudo_legal(pv[ply]));
1813
1814   do {
1815       k = pos.key();
1816       tte = TT.probe(k);
1817
1818       // Don't overwrite existing correct entries
1819       if (!tte || tte->move() != pv[ply])
1820       {
1821           v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1822           TT.store(k, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, pv[ply], v, m);
1823       }
1824       pos.do_move(pv[ply], *st++);
1825
1826   } while (pv[++ply] != MOVE_NONE);
1827
1828   do pos.undo_move(pv[--ply]); while (ply);
1829 }
1830
1831
1832 /// Thread::idle_loop() is where the thread is parked when it has no work to do.
1833 /// The parameter 'sp', if non-NULL, is a pointer to an active SplitPoint object
1834 /// for which the thread is the master.
1835
1836 void Thread::idle_loop(SplitPoint* sp) {
1837
1838   while (true)
1839   {
1840       // If we are not searching, wait for a condition to be signaled
1841       // instead of wasting CPU time polling for work.
1842       while (   do_sleep
1843              || do_terminate
1844              || (Threads.use_sleeping_threads() && !is_searching))
1845       {
1846           assert((!sp && threadID) || Threads.use_sleeping_threads());
1847
1848           if (do_terminate)
1849           {
1850               assert(!sp);
1851               return;
1852           }
1853
1854           // Grab the lock to avoid races with Thread::wake_up()
1855           lock_grab(&sleepLock);
1856
1857           // If we are master and all slaves have finished don't go to sleep
1858           if (sp && Threads.split_point_finished(sp))
1859           {
1860               lock_release(&sleepLock);
1861               break;
1862           }
1863
1864           // Do sleep after retesting sleep conditions under lock protection, in
1865           // particular we need to avoid a deadlock in case a master thread has,
1866           // in the meanwhile, allocated us and sent the wake_up() call before we
1867           // had the chance to grab the lock.
1868           if (do_sleep || !is_searching)
1869               cond_wait(&sleepCond, &sleepLock);
1870
1871           lock_release(&sleepLock);
1872       }
1873
1874       // If this thread has been assigned work, launch a search
1875       if (is_searching)
1876       {
1877           assert(!do_terminate);
1878
1879           // Copy split point position and search stack and call search()
1880           Stack ss[MAX_PLY_PLUS_2];
1881           SplitPoint* tsp = splitPoint;
1882           Position pos(*tsp->pos, threadID);
1883
1884           memcpy(ss, tsp->ss - 1, 4 * sizeof(Stack));
1885           (ss+1)->sp = tsp;
1886
1887           if (tsp->nodeType == Root)
1888               search<SplitPointRoot>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
1889           else if (tsp->nodeType == PV)
1890               search<SplitPointPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
1891           else if (tsp->nodeType == NonPV)
1892               search<SplitPointNonPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
1893           else
1894               assert(false);
1895
1896           assert(is_searching);
1897
1898           is_searching = false;
1899
1900           // Wake up master thread so to allow it to return from the idle loop in
1901           // case we are the last slave of the split point.
1902           if (   Threads.use_sleeping_threads()
1903               && threadID != tsp->master
1904               && !Threads[tsp->master].is_searching)
1905               Threads[tsp->master].wake_up();
1906       }
1907
1908       // If this thread is the master of a split point and all slaves have
1909       // finished their work at this split point, return from the idle loop.
1910       if (sp && Threads.split_point_finished(sp))
1911       {
1912           // Because sp->is_slave[] is reset under lock protection,
1913           // be sure sp->lock has been released before to return.
1914           lock_grab(&(sp->lock));
1915           lock_release(&(sp->lock));
1916           return;
1917       }
1918   }
1919 }
1920
1921
1922 /// check_time() is called by the timer thread when the timer triggers. It is
1923 /// used to print debug info and, more important, to detect when we are out of
1924 /// available time and so stop the search.
1925
1926 void check_time() {
1927
1928   static int lastInfoTime;
1929   int e = elapsed_time();
1930
1931   if (system_time() - lastInfoTime >= 1000 || !lastInfoTime)
1932   {
1933       lastInfoTime = system_time();
1934       dbg_print();
1935   }
1936
1937   if (Limits.ponder)
1938       return;
1939
1940   bool stillAtFirstMove =    Signals.firstRootMove
1941                          && !Signals.failedLowAtRoot
1942                          &&  e > TimeMgr.available_time();
1943
1944   bool noMoreTime =   e > TimeMgr.maximum_time() - 2 * TimerResolution
1945                    || stillAtFirstMove;
1946
1947   if (   (Limits.use_time_management() && noMoreTime)
1948       || (Limits.maxTime && e >= Limits.maxTime)
1949          /* missing nodes limit */ ) // FIXME
1950       Signals.stop = true;
1951 }