]> git.sesse.net Git - stockfish/blob - src/search.cpp
73050bdf12534065495807d016753debd2e8ca3b
[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   Threads.set_size(Options["Threads"]);
311
312   // Set best timer interval to avoid lagging under time pressure. Timer is
313   // used to check for remaining available thinking time.
314   if (Limits.use_time_management())
315       Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 16, TimerResolution)));
316   else
317       Threads.set_timer(100);
318
319   // We're ready to start searching. Call the iterative deepening loop function
320   id_loop(pos);
321
322   // Stop timer and send all the slaves to sleep, if not already sleeping
323   Threads.set_timer(0);
324   Threads.set_size(1);
325
326   if (Options["Use Search Log"])
327   {
328       int e = elapsed_time();
329
330       Log log(Options["Search Log Filename"]);
331       log << "Nodes: "          << pos.nodes_searched()
332           << "\nNodes/second: " << (e > 0 ? pos.nodes_searched() * 1000 / e : 0)
333           << "\nBest move: "    << move_to_san(pos, RootMoves[0].pv[0]);
334
335       StateInfo st;
336       pos.do_move(RootMoves[0].pv[0], st);
337       log << "\nPonder move: " << move_to_san(pos, RootMoves[0].pv[1]) << endl;
338       pos.undo_move(RootMoves[0].pv[0]);
339   }
340
341 finalize:
342
343   // When we reach max depth we arrive here even without Signals.stop is raised,
344   // but if we are pondering or in infinite search, we shouldn't print the best
345   // move before we are told to do so.
346   if (!Signals.stop && (Limits.ponder || Limits.infinite))
347       Threads[pos.thread()].wait_for_stop_or_ponderhit();
348
349   // Best move could be MOVE_NONE when searching on a stalemate position
350   cout << "bestmove " << move_to_uci(RootMoves[0].pv[0], Chess960)
351        << " ponder "  << move_to_uci(RootMoves[0].pv[1], Chess960) << endl;
352 }
353
354
355 namespace {
356
357   // id_loop() is the main iterative deepening loop. It calls search() repeatedly
358   // with increasing depth until the allocated thinking time has been consumed,
359   // user stops the search, or the maximum search depth is reached.
360
361   void id_loop(Position& pos) {
362
363     Stack ss[MAX_PLY_PLUS_2];
364     int depth, prevBestMoveChanges;
365     Value bestValue, alpha, beta, delta;
366     bool bestMoveNeverChanged = true;
367     Move skillBest = MOVE_NONE;
368
369     memset(ss, 0, 4 * sizeof(Stack));
370     depth = BestMoveChanges = 0;
371     bestValue = delta = -VALUE_INFINITE;
372     ss->currentMove = MOVE_NULL; // Hack to skip update gains
373
374     // Iterative deepening loop until requested to stop or target depth reached
375     while (!Signals.stop && ++depth <= MAX_PLY && (!Limits.maxDepth || depth <= Limits.maxDepth))
376     {
377         // Save last iteration's scores before first PV line is searched and all
378         // the move scores but the (new) PV are set to -VALUE_INFINITE.
379         for (size_t i = 0; i < RootMoves.size(); i++)
380             RootMoves[i].prevScore = RootMoves[i].score;
381
382         prevBestMoveChanges = BestMoveChanges;
383         BestMoveChanges = 0;
384
385         // MultiPV loop. We perform a full root search for each PV line
386         for (PVIdx = 0; PVIdx < std::min(MultiPV, RootMoves.size()); PVIdx++)
387         {
388             // Set aspiration window default width
389             if (depth >= 5 && abs(RootMoves[PVIdx].prevScore) < VALUE_KNOWN_WIN)
390             {
391                 delta = Value(16);
392                 alpha = RootMoves[PVIdx].prevScore - delta;
393                 beta  = RootMoves[PVIdx].prevScore + delta;
394             }
395             else
396             {
397                 alpha = -VALUE_INFINITE;
398                 beta  =  VALUE_INFINITE;
399             }
400
401             // Start with a small aspiration window and, in case of fail high/low,
402             // research with bigger window until not failing high/low anymore.
403             do {
404                 // Search starts from ss+1 to allow referencing (ss-1). This is
405                 // needed by update gains and ss copy when splitting at Root.
406                 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
407
408                 // Bring to front the best move. It is critical that sorting is
409                 // done with a stable algorithm because all the values but the first
410                 // and eventually the new best one are set to -VALUE_INFINITE and
411                 // we want to keep the same order for all the moves but the new
412                 // PV that goes to the front. Note that in case of MultiPV search
413                 // the already searched PV lines are preserved.
414                 sort<RootMove>(RootMoves.begin() + PVIdx, RootMoves.end());
415
416                 // In case we have found an exact score and we are going to leave
417                 // the fail high/low loop then reorder the PV moves, otherwise
418                 // leave the last PV move in its position so to be searched again.
419                 // Of course this is needed only in MultiPV search.
420                 if (PVIdx && bestValue > alpha && bestValue < beta)
421                     sort<RootMove>(RootMoves.begin(), RootMoves.begin() + PVIdx);
422
423                 // Write PV back to transposition table in case the relevant
424                 // entries have been overwritten during the search.
425                 for (size_t i = 0; i <= PVIdx; i++)
426                     RootMoves[i].insert_pv_in_tt(pos);
427
428                 // If search has been stopped exit the aspiration window loop.
429                 // Sorting and writing PV back to TT is safe becuase RootMoves
430                 // is still valid, although refers to previous iteration.
431                 if (Signals.stop)
432                     break;
433
434                 // Send full PV info to GUI if we are going to leave the loop or
435                 // if we have a fail high/low and we are deep in the search.
436                 if ((bestValue > alpha && bestValue < beta) || elapsed_time() > 2000)
437                     pv_info_to_uci(pos, depth, alpha, beta);
438
439                 // In case of failing high/low increase aspiration window and
440                 // research, otherwise exit the fail high/low loop.
441                 if (bestValue >= beta)
442                 {
443                     beta += delta;
444                     delta += delta / 2;
445                 }
446                 else if (bestValue <= alpha)
447                 {
448                     Signals.failedLowAtRoot = true;
449                     Signals.stopOnPonderhit = false;
450
451                     alpha -= delta;
452                     delta += delta / 2;
453                 }
454                 else
455                     break;
456
457                 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
458
459             } while (abs(bestValue) < VALUE_KNOWN_WIN);
460         }
461
462         // Skills: Do we need to pick now the best move ?
463         if (SkillLevelEnabled && depth == 1 + SkillLevel)
464             skillBest = do_skill_level();
465
466         if (!Signals.stop && Options["Use Search Log"])
467              pv_info_to_log(pos, depth, bestValue, elapsed_time(), &RootMoves[0].pv[0]);
468
469         // Filter out startup noise when monitoring best move stability
470         if (depth > 2 && BestMoveChanges)
471             bestMoveNeverChanged = false;
472
473         // Do we have time for the next iteration? Can we stop searching now?
474         if (!Signals.stop && !Signals.stopOnPonderhit && Limits.use_time_management())
475         {
476             bool stop = false; // Local variable, not the volatile Signals.stop
477
478             // Take in account some extra time if the best move has changed
479             if (depth > 4 && depth < 50)
480                 TimeMgr.pv_instability(BestMoveChanges, prevBestMoveChanges);
481
482             // Stop search if most of available time is already consumed. We
483             // probably don't have enough time to search the first move at the
484             // next iteration anyway.
485             if (elapsed_time() > (TimeMgr.available_time() * 62) / 100)
486                 stop = true;
487
488             // Stop search early if one move seems to be much better than others
489             if (    depth >= 12
490                 && !stop
491                 && (   (bestMoveNeverChanged &&  pos.captured_piece_type())
492                     || elapsed_time() > (TimeMgr.available_time() * 40) / 100))
493             {
494                 Value rBeta = bestValue - EasyMoveMargin;
495                 (ss+1)->excludedMove = RootMoves[0].pv[0];
496                 (ss+1)->skipNullMove = true;
497                 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth - 3) * ONE_PLY);
498                 (ss+1)->skipNullMove = false;
499                 (ss+1)->excludedMove = MOVE_NONE;
500
501                 if (v < rBeta)
502                     stop = true;
503             }
504
505             if (stop)
506             {
507                 // If we are allowed to ponder do not stop the search now but
508                 // keep pondering until GUI sends "ponderhit" or "stop".
509                 if (Limits.ponder)
510                     Signals.stopOnPonderhit = true;
511                 else
512                     Signals.stop = true;
513             }
514         }
515     }
516
517     // When using skills swap best PV line with the sub-optimal one
518     if (SkillLevelEnabled)
519     {
520         if (skillBest == MOVE_NONE) // Still unassigned ?
521             skillBest = do_skill_level();
522
523         std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), skillBest));
524     }
525   }
526
527
528   // search<>() is the main search function for both PV and non-PV nodes and for
529   // normal and SplitPoint nodes. When called just after a split point the search
530   // is simpler because we have already probed the hash table, done a null move
531   // search, and searched the first move before splitting, we don't have to repeat
532   // all this work again. We also don't need to store anything to the hash table
533   // here: This is taken care of after we return from the split point.
534
535   template <NodeType NT>
536   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
537
538     const bool PvNode   = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
539     const bool SpNode   = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
540     const bool RootNode = (NT == Root || NT == SplitPointRoot);
541
542     assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
543     assert((alpha == beta - 1) || PvNode);
544     assert(depth > DEPTH_ZERO);
545     assert(pos.thread() >= 0 && pos.thread() < Threads.size());
546
547     Move movesSearched[MAX_MOVES];
548     StateInfo st;
549     const TTEntry *tte;
550     Key posKey;
551     Move ttMove, move, excludedMove, threatMove;
552     Depth ext, newDepth;
553     Bound bt;
554     Value bestValue, value, oldAlpha;
555     Value refinedValue, nullValue, futilityBase, futilityValue;
556     bool isPvMove, inCheck, singularExtensionNode, givesCheck;
557     bool captureOrPromotion, dangerous, doFullDepthSearch;
558     int moveCount = 0, playedMoveCount = 0;
559     Thread& thread = Threads[pos.thread()];
560     SplitPoint* sp = NULL;
561
562     refinedValue = bestValue = value = -VALUE_INFINITE;
563     oldAlpha = alpha;
564     inCheck = pos.in_check();
565     ss->ply = (ss-1)->ply + 1;
566
567     // Used to send selDepth info to GUI
568     if (PvNode && thread.maxPly < ss->ply)
569         thread.maxPly = ss->ply;
570
571     // Step 1. Initialize node
572     if (SpNode)
573     {
574         tte = NULL;
575         ttMove = excludedMove = MOVE_NONE;
576         sp = ss->sp;
577         threatMove = sp->threatMove;
578         bestValue = sp->bestValue;
579         moveCount = sp->moveCount; // Lock must be held here
580
581         assert(bestValue > -VALUE_INFINITE && moveCount > 0);
582
583         goto split_point_start;
584     }
585     else
586     {
587         ss->currentMove = ss->bestMove = threatMove = (ss+1)->excludedMove = MOVE_NONE;
588         (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
589         (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
590
591     }
592
593     // Step 2. Check for aborted search and immediate draw
594     // Enforce node limit here. FIXME: This only works with 1 search thread.
595     if (Limits.maxNodes && pos.nodes_searched() >= Limits.maxNodes)
596         Signals.stop = true;
597
598     if ((   Signals.stop
599          || pos.is_draw<false>()
600          || ss->ply > MAX_PLY) && !RootNode)
601         return VALUE_DRAW;
602
603     // Step 3. Mate distance pruning. Even if we mate at the next move our score
604     // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
605     // a shorter mate was found upward in the tree then there is no need to search
606     // further, we will never beat current alpha. Same logic but with reversed signs
607     // applies also in the opposite condition of being mated instead of giving mate,
608     // in this case return a fail-high score.
609     if (!RootNode)
610     {
611         alpha = std::max(mated_in(ss->ply), alpha);
612         beta = std::min(mate_in(ss->ply+1), beta);
613         if (alpha >= beta)
614             return alpha;
615     }
616
617     // Step 4. Transposition table lookup
618     // We don't want the score of a partial search to overwrite a previous full search
619     // TT value, so we use a different position key in case of an excluded move.
620     excludedMove = ss->excludedMove;
621     posKey = excludedMove ? pos.exclusion_key() : pos.key();
622     tte = TT.probe(posKey);
623     ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
624
625     // At PV nodes we check for exact scores, while at non-PV nodes we check for
626     // a fail high/low. Biggest advantage at probing at PV nodes is to have a
627     // smooth experience in analysis mode. We don't probe at Root nodes otherwise
628     // we should also update RootMoveList to avoid bogus output.
629     if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == BOUND_EXACT
630                                     : can_return_tt(tte, depth, beta, ss->ply)))
631     {
632         TT.refresh(tte);
633         ss->bestMove = move = ttMove; // Can be MOVE_NONE
634         value = value_from_tt(tte->value(), ss->ply);
635
636         if (   value >= beta
637             && move
638             && !pos.is_capture_or_promotion(move)
639             && move != ss->killers[0])
640         {
641             ss->killers[1] = ss->killers[0];
642             ss->killers[0] = move;
643         }
644         return value;
645     }
646
647     // Step 5. Evaluate the position statically and update parent's gain statistics
648     if (inCheck)
649         ss->eval = ss->evalMargin = VALUE_NONE;
650     else if (tte)
651     {
652         assert(tte->static_value() != VALUE_NONE);
653
654         ss->eval = tte->static_value();
655         ss->evalMargin = tte->static_value_margin();
656         refinedValue = refine_eval(tte, ss->eval, ss->ply);
657     }
658     else
659     {
660         refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
661         TT.store(posKey, VALUE_NONE, BOUND_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
662     }
663
664     // Update gain for the parent non-capture move given the static position
665     // evaluation before and after the move.
666     if (   (move = (ss-1)->currentMove) != MOVE_NULL
667         && (ss-1)->eval != VALUE_NONE
668         && ss->eval != VALUE_NONE
669         && !pos.captured_piece_type()
670         && !is_special(move))
671     {
672         Square to = to_sq(move);
673         H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
674     }
675
676     // Step 6. Razoring (is omitted in PV nodes)
677     if (   !PvNode
678         &&  depth < RazorDepth
679         && !inCheck
680         &&  refinedValue + razor_margin(depth) < beta
681         &&  ttMove == MOVE_NONE
682         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
683         && !pos.has_pawn_on_7th(pos.side_to_move()))
684     {
685         Value rbeta = beta - razor_margin(depth);
686         Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
687         if (v < rbeta)
688             // Logically we should return (v + razor_margin(depth)), but
689             // surprisingly this did slightly weaker in tests.
690             return v;
691     }
692
693     // Step 7. Static null move pruning (is omitted in PV nodes)
694     // We're betting that the opponent doesn't have a move that will reduce
695     // the score by more than futility_margin(depth) if we do a null move.
696     if (   !PvNode
697         && !ss->skipNullMove
698         &&  depth < RazorDepth
699         && !inCheck
700         &&  refinedValue - futility_margin(depth, 0) >= beta
701         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
702         &&  pos.non_pawn_material(pos.side_to_move()))
703         return refinedValue - futility_margin(depth, 0);
704
705     // Step 8. Null move search with verification search (is omitted in PV nodes)
706     if (   !PvNode
707         && !ss->skipNullMove
708         &&  depth > ONE_PLY
709         && !inCheck
710         &&  refinedValue >= beta
711         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
712         &&  pos.non_pawn_material(pos.side_to_move()))
713     {
714         ss->currentMove = MOVE_NULL;
715
716         // Null move dynamic reduction based on depth
717         int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);
718
719         // Null move dynamic reduction based on value
720         if (refinedValue - PawnValueMidgame > beta)
721             R++;
722
723         pos.do_null_move<true>(st);
724         (ss+1)->skipNullMove = true;
725         nullValue = depth-R*ONE_PLY < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
726                                               : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY);
727         (ss+1)->skipNullMove = false;
728         pos.do_null_move<false>(st);
729
730         if (nullValue >= beta)
731         {
732             // Do not return unproven mate scores
733             if (nullValue >= VALUE_MATE_IN_MAX_PLY)
734                 nullValue = beta;
735
736             if (depth < 6 * ONE_PLY)
737                 return nullValue;
738
739             // Do verification search at high depths
740             ss->skipNullMove = true;
741             Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY);
742             ss->skipNullMove = false;
743
744             if (v >= beta)
745                 return nullValue;
746         }
747         else
748         {
749             // The null move failed low, which means that we may be faced with
750             // some kind of threat. If the previous move was reduced, check if
751             // the move that refuted the null move was somehow connected to the
752             // move which was reduced. If a connection is found, return a fail
753             // low score (which will cause the reduced move to fail high in the
754             // parent node, which will trigger a re-search with full depth).
755             threatMove = (ss+1)->bestMove;
756
757             if (   depth < ThreatDepth
758                 && (ss-1)->reduction
759                 && threatMove != MOVE_NONE
760                 && connected_moves(pos, (ss-1)->currentMove, threatMove))
761                 return beta - 1;
762         }
763     }
764
765     // Step 9. ProbCut (is omitted in PV nodes)
766     // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
767     // and a reduced search returns a value much above beta, we can (almost) safely
768     // prune the previous move.
769     if (   !PvNode
770         &&  depth >= RazorDepth + ONE_PLY
771         && !inCheck
772         && !ss->skipNullMove
773         &&  excludedMove == MOVE_NONE
774         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY)
775     {
776         Value rbeta = beta + 200;
777         Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
778
779         assert(rdepth >= ONE_PLY);
780         assert((ss-1)->currentMove != MOVE_NONE);
781
782         MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
783         CheckInfo ci(pos);
784
785         while ((move = mp.next_move()) != MOVE_NONE)
786             if (pos.pl_move_is_legal(move, ci.pinned))
787             {
788                 ss->currentMove = move;
789                 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
790                 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
791                 pos.undo_move(move);
792                 if (value >= rbeta)
793                     return value;
794             }
795     }
796
797     // Step 10. Internal iterative deepening
798     if (   depth >= IIDDepth[PvNode]
799         && ttMove == MOVE_NONE
800         && (PvNode || (!inCheck && ss->eval + IIDMargin >= beta)))
801     {
802         Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
803
804         ss->skipNullMove = true;
805         search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
806         ss->skipNullMove = false;
807
808         tte = TT.probe(posKey);
809         ttMove = tte ? tte->move() : MOVE_NONE;
810     }
811
812 split_point_start: // At split points actual search starts from here
813
814     MovePickerExt<SpNode> mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
815     CheckInfo ci(pos);
816     ss->bestMove = MOVE_NONE;
817     futilityBase = ss->eval + ss->evalMargin;
818     singularExtensionNode =   !RootNode
819                            && !SpNode
820                            && depth >= SingularExtensionDepth[PvNode]
821                            && ttMove != MOVE_NONE
822                            && !excludedMove // Recursive singular search is not allowed
823                            && (tte->type() & BOUND_LOWER)
824                            && tte->depth() >= depth - 3 * ONE_PLY;
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 > 3 * 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 Signals.stop 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
1061               if (value >= beta)
1062                   sp->cutoff = true;
1063           }
1064       }
1065
1066       // Step 19. Check for split
1067       if (   !SpNode
1068           && depth >= Threads.min_split_depth()
1069           && bestValue < beta
1070           && Threads.available_slave_exists(pos.thread())
1071           && !Signals.stop
1072           && !thread.cutoff_occurred())
1073           bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, depth,
1074                                                threatMove, moveCount, &mp, NT);
1075     }
1076
1077     // Step 20. Check for mate and stalemate
1078     // All legal moves have been searched and if there are no legal moves, it
1079     // must be mate or stalemate. Note that we can have a false positive in
1080     // case of Signals.stop or thread.cutoff_occurred() are set, but this is
1081     // harmless because return value is discarded anyhow in the parent nodes.
1082     // If we are in a singular extension search then return a fail low score.
1083     if (!moveCount)
1084         return excludedMove ? oldAlpha : inCheck ? mated_in(ss->ply) : VALUE_DRAW;
1085
1086     // If we have pruned all the moves without searching return a fail-low score
1087     if (bestValue == -VALUE_INFINITE)
1088     {
1089         assert(!playedMoveCount);
1090
1091         bestValue = alpha;
1092     }
1093
1094     // Step 21. Update tables
1095     // Update transposition table entry, killers and history
1096     if (!SpNode && !Signals.stop && !thread.cutoff_occurred())
1097     {
1098         move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1099         bt   = bestValue <= oldAlpha ? BOUND_UPPER
1100              : bestValue >= beta ? BOUND_LOWER : BOUND_EXACT;
1101
1102         TT.store(posKey, value_to_tt(bestValue, ss->ply), bt, depth, move, ss->eval, ss->evalMargin);
1103
1104         // Update killers and history for non capture cut-off moves
1105         if (    bestValue >= beta
1106             && !pos.is_capture_or_promotion(move)
1107             && !inCheck)
1108         {
1109             if (move != ss->killers[0])
1110             {
1111                 ss->killers[1] = ss->killers[0];
1112                 ss->killers[0] = move;
1113             }
1114
1115             // Increase history value of the cut-off move
1116             Value bonus = Value(int(depth) * int(depth));
1117             H.add(pos.piece_moved(move), to_sq(move), bonus);
1118
1119             // Decrease history of all the other played non-capture moves
1120             for (int i = 0; i < playedMoveCount - 1; i++)
1121             {
1122                 Move m = movesSearched[i];
1123                 H.add(pos.piece_moved(m), to_sq(m), -bonus);
1124             }
1125         }
1126     }
1127
1128     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1129
1130     return bestValue;
1131   }
1132
1133
1134   // qsearch() is the quiescence search function, which is called by the main
1135   // search function when the remaining depth is zero (or, to be more precise,
1136   // less than ONE_PLY).
1137
1138   template <NodeType NT>
1139   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1140
1141     const bool PvNode = (NT == PV);
1142
1143     assert(NT == PV || NT == NonPV);
1144     assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1145     assert((alpha == beta - 1) || PvNode);
1146     assert(depth <= DEPTH_ZERO);
1147     assert(pos.thread() >= 0 && pos.thread() < Threads.size());
1148
1149     StateInfo st;
1150     Move ttMove, move;
1151     Value bestValue, value, evalMargin, futilityValue, futilityBase;
1152     bool inCheck, enoughMaterial, givesCheck, evasionPrunable;
1153     const TTEntry* tte;
1154     Depth ttDepth;
1155     Bound bt;
1156     Value oldAlpha = alpha;
1157
1158     ss->bestMove = ss->currentMove = MOVE_NONE;
1159     ss->ply = (ss-1)->ply + 1;
1160
1161     // Check for an instant draw or maximum ply reached
1162     if (pos.is_draw<true>() || ss->ply > MAX_PLY)
1163         return VALUE_DRAW;
1164
1165     // Decide whether or not to include checks, this fixes also the type of
1166     // TT entry depth that we are going to use. Note that in qsearch we use
1167     // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1168     inCheck = pos.in_check();
1169     ttDepth = (inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1170
1171     // Transposition table lookup. At PV nodes, we don't use the TT for
1172     // pruning, but only for move ordering.
1173     tte = TT.probe(pos.key());
1174     ttMove = (tte ? tte->move() : MOVE_NONE);
1175
1176     if (!PvNode && tte && can_return_tt(tte, ttDepth, beta, ss->ply))
1177     {
1178         ss->bestMove = ttMove; // Can be MOVE_NONE
1179         return value_from_tt(tte->value(), ss->ply);
1180     }
1181
1182     // Evaluate the position statically
1183     if (inCheck)
1184     {
1185         bestValue = futilityBase = -VALUE_INFINITE;
1186         ss->eval = evalMargin = VALUE_NONE;
1187         enoughMaterial = false;
1188     }
1189     else
1190     {
1191         if (tte)
1192         {
1193             assert(tte->static_value() != VALUE_NONE);
1194
1195             evalMargin = tte->static_value_margin();
1196             ss->eval = bestValue = tte->static_value();
1197         }
1198         else
1199             ss->eval = bestValue = evaluate(pos, evalMargin);
1200
1201         // Stand pat. Return immediately if static value is at least beta
1202         if (bestValue >= beta)
1203         {
1204             if (!tte)
1205                 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), BOUND_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1206
1207             return bestValue;
1208         }
1209
1210         if (PvNode && bestValue > alpha)
1211             alpha = bestValue;
1212
1213         futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1214         enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1215     }
1216
1217     // Initialize a MovePicker object for the current position, and prepare
1218     // to search the moves. Because the depth is <= 0 here, only captures,
1219     // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1220     // be generated.
1221     MovePicker mp(pos, ttMove, depth, H, to_sq((ss-1)->currentMove));
1222     CheckInfo ci(pos);
1223
1224     // Loop through the moves until no moves remain or a beta cutoff occurs
1225     while (   bestValue < beta
1226            && (move = mp.next_move()) != MOVE_NONE)
1227     {
1228       assert(is_ok(move));
1229
1230       givesCheck = pos.move_gives_check(move, ci);
1231
1232       // Futility pruning
1233       if (   !PvNode
1234           && !inCheck
1235           && !givesCheck
1236           &&  move != ttMove
1237           &&  enoughMaterial
1238           && !is_promotion(move)
1239           && !pos.is_passed_pawn_push(move))
1240       {
1241           futilityValue =  futilityBase
1242                          + PieceValueEndgame[pos.piece_on(to_sq(move))]
1243                          + (is_enpassant(move) ? PawnValueEndgame : VALUE_ZERO);
1244
1245           if (futilityValue < beta)
1246           {
1247               if (futilityValue > bestValue)
1248                   bestValue = futilityValue;
1249
1250               continue;
1251           }
1252
1253           // Prune moves with negative or equal SEE
1254           if (   futilityBase < beta
1255               && depth < DEPTH_ZERO
1256               && pos.see(move) <= 0)
1257               continue;
1258       }
1259
1260       // Detect non-capture evasions that are candidate to be pruned
1261       evasionPrunable =   !PvNode
1262                        && inCheck
1263                        && bestValue > VALUE_MATED_IN_MAX_PLY
1264                        && !pos.is_capture(move)
1265                        && !pos.can_castle(pos.side_to_move());
1266
1267       // Don't search moves with negative SEE values
1268       if (   !PvNode
1269           && (!inCheck || evasionPrunable)
1270           &&  move != ttMove
1271           && !is_promotion(move)
1272           &&  pos.see_sign(move) < 0)
1273           continue;
1274
1275       // Don't search useless checks
1276       if (   !PvNode
1277           && !inCheck
1278           &&  givesCheck
1279           &&  move != ttMove
1280           && !pos.is_capture_or_promotion(move)
1281           &&  ss->eval + PawnValueMidgame / 4 < beta
1282           && !check_is_dangerous(pos, move, futilityBase, beta, &bestValue))
1283           continue;
1284
1285       // Check for legality only before to do the move
1286       if (!pos.pl_move_is_legal(move, ci.pinned))
1287           continue;
1288
1289       ss->currentMove = move;
1290
1291       // Make and search the move
1292       pos.do_move(move, st, ci, givesCheck);
1293       value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1294       pos.undo_move(move);
1295
1296       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1297
1298       // New best move?
1299       if (value > bestValue)
1300       {
1301           bestValue = value;
1302           ss->bestMove = move;
1303
1304           if (   PvNode
1305               && value > alpha
1306               && value < beta) // We want always alpha < beta
1307               alpha = value;
1308        }
1309     }
1310
1311     // All legal moves have been searched. A special case: If we're in check
1312     // and no legal moves were found, it is checkmate.
1313     if (inCheck && bestValue == -VALUE_INFINITE)
1314         return mated_in(ss->ply); // Plies to mate from the root
1315
1316     // Update transposition table
1317     move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1318     bt   = bestValue <= oldAlpha ? BOUND_UPPER
1319          : bestValue >= beta ? BOUND_LOWER : BOUND_EXACT;
1320
1321     TT.store(pos.key(), value_to_tt(bestValue, ss->ply), bt, ttDepth, move, ss->eval, evalMargin);
1322
1323     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1324
1325     return bestValue;
1326   }
1327
1328
1329   // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1330   // bestValue is updated only when returning false because in that case move
1331   // will be pruned.
1332
1333   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bestValue)
1334   {
1335     Bitboard b, occ, oldAtt, newAtt, kingAtt;
1336     Square from, to, ksq, victimSq;
1337     Piece pc;
1338     Color them;
1339     Value futilityValue, bv = *bestValue;
1340
1341     from = from_sq(move);
1342     to = to_sq(move);
1343     them = ~pos.side_to_move();
1344     ksq = pos.king_square(them);
1345     kingAtt = pos.attacks_from<KING>(ksq);
1346     pc = pos.piece_on(from);
1347
1348     occ = pos.occupied_squares() & ~(1ULL << from) & ~(1ULL << ksq);
1349     oldAtt = pos.attacks_from(pc, from, occ);
1350     newAtt = pos.attacks_from(pc,   to, occ);
1351
1352     // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1353     b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1354
1355     if (!(b && (b & (b - 1))))
1356         return true;
1357
1358     // Rule 2. Queen contact check is very dangerous
1359     if (type_of(pc) == QUEEN && (kingAtt & to))
1360         return true;
1361
1362     // Rule 3. Creating new double threats with checks
1363     b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1364
1365     while (b)
1366     {
1367         victimSq = pop_1st_bit(&b);
1368         futilityValue = futilityBase + PieceValueEndgame[pos.piece_on(victimSq)];
1369
1370         // Note that here we generate illegal "double move"!
1371         if (   futilityValue >= beta
1372             && pos.see_sign(make_move(from, victimSq)) >= 0)
1373             return true;
1374
1375         if (futilityValue > bv)
1376             bv = futilityValue;
1377     }
1378
1379     // Update bestValue only if check is not dangerous (because we will prune the move)
1380     *bestValue = bv;
1381     return false;
1382   }
1383
1384
1385   // connected_moves() tests whether two moves are 'connected' in the sense
1386   // that the first move somehow made the second move possible (for instance
1387   // if the moving piece is the same in both moves). The first move is assumed
1388   // to be the move that was made to reach the current position, while the
1389   // second move is assumed to be a move from the current position.
1390
1391   bool connected_moves(const Position& pos, Move m1, Move m2) {
1392
1393     Square f1, t1, f2, t2;
1394     Piece p1, p2;
1395     Square ksq;
1396
1397     assert(is_ok(m1));
1398     assert(is_ok(m2));
1399
1400     // Case 1: The moving piece is the same in both moves
1401     f2 = from_sq(m2);
1402     t1 = to_sq(m1);
1403     if (f2 == t1)
1404         return true;
1405
1406     // Case 2: The destination square for m2 was vacated by m1
1407     t2 = to_sq(m2);
1408     f1 = from_sq(m1);
1409     if (t2 == f1)
1410         return true;
1411
1412     // Case 3: Moving through the vacated square
1413     p2 = pos.piece_on(f2);
1414     if (piece_is_slider(p2) && (squares_between(f2, t2) & f1))
1415       return true;
1416
1417     // Case 4: The destination square for m2 is defended by the moving piece in m1
1418     p1 = pos.piece_on(t1);
1419     if (pos.attacks_from(p1, t1) & t2)
1420         return true;
1421
1422     // Case 5: Discovered check, checking piece is the piece moved in m1
1423     ksq = pos.king_square(pos.side_to_move());
1424     if (piece_is_slider(p1) && (squares_between(t1, ksq) & f2))
1425     {
1426         Bitboard occ = pos.occupied_squares();
1427         occ ^= f2;
1428         if (pos.attacks_from(p1, t1, occ) & ksq)
1429             return true;
1430     }
1431     return false;
1432   }
1433
1434
1435   // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1436   // "plies to mate from the current position". Non-mate scores are unchanged.
1437   // The function is called before storing a value to the transposition table.
1438
1439   Value value_to_tt(Value v, int ply) {
1440
1441     if (v >= VALUE_MATE_IN_MAX_PLY)
1442       return v + ply;
1443
1444     if (v <= VALUE_MATED_IN_MAX_PLY)
1445       return v - ply;
1446
1447     return v;
1448   }
1449
1450
1451   // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
1452   // from the transposition table (where refers to the plies to mate/be mated
1453   // from current position) to "plies to mate/be mated from the root".
1454
1455   Value value_from_tt(Value v, int ply) {
1456
1457     if (v >= VALUE_MATE_IN_MAX_PLY)
1458       return v - ply;
1459
1460     if (v <= VALUE_MATED_IN_MAX_PLY)
1461       return v + ply;
1462
1463     return v;
1464   }
1465
1466
1467   // connected_threat() tests whether it is safe to forward prune a move or if
1468   // is somehow connected to the threat move returned by null search.
1469
1470   bool connected_threat(const Position& pos, Move m, Move threat) {
1471
1472     assert(is_ok(m));
1473     assert(is_ok(threat));
1474     assert(!pos.is_capture_or_promotion(m));
1475     assert(!pos.is_passed_pawn_push(m));
1476
1477     Square mfrom, mto, tfrom, tto;
1478
1479     mfrom = from_sq(m);
1480     mto = to_sq(m);
1481     tfrom = from_sq(threat);
1482     tto = to_sq(threat);
1483
1484     // Case 1: Don't prune moves which move the threatened piece
1485     if (mfrom == tto)
1486         return true;
1487
1488     // Case 2: If the threatened piece has value less than or equal to the
1489     // value of the threatening piece, don't prune moves which defend it.
1490     if (   pos.is_capture(threat)
1491         && (   PieceValueMidgame[pos.piece_on(tfrom)] >= PieceValueMidgame[pos.piece_on(tto)]
1492             || type_of(pos.piece_on(tfrom)) == KING)
1493         && pos.move_attacks_square(m, tto))
1494         return true;
1495
1496     // Case 3: If the moving piece in the threatened move is a slider, don't
1497     // prune safe moves which block its ray.
1498     if (    piece_is_slider(pos.piece_on(tfrom))
1499         && (squares_between(tfrom, tto) & mto)
1500         &&  pos.see_sign(m) >= 0)
1501         return true;
1502
1503     return false;
1504   }
1505
1506
1507   // can_return_tt() returns true if a transposition table score can be used to
1508   // cut-off at a given point in search.
1509
1510   bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply) {
1511
1512     Value v = value_from_tt(tte->value(), ply);
1513
1514     return   (   tte->depth() >= depth
1515               || v >= std::max(VALUE_MATE_IN_MAX_PLY, beta)
1516               || v < std::min(VALUE_MATED_IN_MAX_PLY, beta))
1517
1518           && (   ((tte->type() & BOUND_LOWER) && v >= beta)
1519               || ((tte->type() & BOUND_UPPER) && v < beta));
1520   }
1521
1522
1523   // refine_eval() returns the transposition table score if possible, otherwise
1524   // falls back on static position evaluation.
1525
1526   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1527
1528       assert(tte);
1529
1530       Value v = value_from_tt(tte->value(), ply);
1531
1532       if (   ((tte->type() & BOUND_LOWER) && v >= defaultEval)
1533           || ((tte->type() & BOUND_UPPER) && v < defaultEval))
1534           return v;
1535
1536       return defaultEval;
1537   }
1538
1539
1540   // current_search_time() returns the number of milliseconds which have passed
1541   // since the beginning of the current search.
1542
1543   int elapsed_time(bool reset) {
1544
1545     static int searchStartTime;
1546
1547     if (reset)
1548         searchStartTime = system_time();
1549
1550     return system_time() - searchStartTime;
1551   }
1552
1553
1554   // score_to_uci() converts a value to a string suitable for use with the UCI
1555   // protocol specifications:
1556   //
1557   // cp <x>     The score from the engine's point of view in centipawns.
1558   // mate <y>   Mate in y moves, not plies. If the engine is getting mated
1559   //            use negative values for y.
1560
1561   string score_to_uci(Value v, Value alpha, Value beta) {
1562
1563     std::stringstream s;
1564
1565     if (abs(v) < VALUE_MATE_IN_MAX_PLY)
1566         s << "cp " << v * 100 / int(PawnValueMidgame);
1567     else
1568         s << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
1569
1570     s << (v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");
1571
1572     return s.str();
1573   }
1574
1575
1576   // pv_info_to_uci() sends search info to GUI. UCI protocol requires to send all
1577   // the PV lines also if are still to be searched and so refer to the previous
1578   // search score.
1579
1580   void pv_info_to_uci(const Position& pos, int depth, Value alpha, Value beta) {
1581
1582     int t = elapsed_time();
1583     int selDepth = 0;
1584
1585     for (int i = 0; i < Threads.size(); i++)
1586         if (Threads[i].maxPly > selDepth)
1587             selDepth = Threads[i].maxPly;
1588
1589     for (size_t i = 0; i < std::min(UCIMultiPV, RootMoves.size()); i++)
1590     {
1591         bool updated = (i <= PVIdx);
1592
1593         if (depth == 1 && !updated)
1594             continue;
1595
1596         int d = (updated ? depth : depth - 1);
1597         Value v = (updated ? RootMoves[i].score : RootMoves[i].prevScore);
1598         std::stringstream s;
1599
1600         for (int j = 0; RootMoves[i].pv[j] != MOVE_NONE; j++)
1601             s <<  " " << move_to_uci(RootMoves[i].pv[j], Chess960);
1602
1603         cout << "info depth " << d
1604              << " seldepth " << selDepth
1605              << " score " << (i == PVIdx ? score_to_uci(v, alpha, beta) : score_to_uci(v))
1606              << " nodes " << pos.nodes_searched()
1607              << " nps " << (t > 0 ? pos.nodes_searched() * 1000 / t : 0)
1608              << " time " << t
1609              << " multipv " << i + 1
1610              << " pv" << s.str() << endl;
1611     }
1612   }
1613
1614
1615   // pv_info_to_log() writes human-readable search information to the log file
1616   // (which is created when the UCI parameter "Use Search Log" is "true"). It
1617   // uses the two below helpers to pretty format time and score respectively.
1618
1619   string time_to_string(int millisecs) {
1620
1621     const int MSecMinute = 1000 * 60;
1622     const int MSecHour   = 1000 * 60 * 60;
1623
1624     int hours = millisecs / MSecHour;
1625     int minutes =  (millisecs % MSecHour) / MSecMinute;
1626     int seconds = ((millisecs % MSecHour) % MSecMinute) / 1000;
1627
1628     std::stringstream s;
1629
1630     if (hours)
1631         s << hours << ':';
1632
1633     s << std::setfill('0') << std::setw(2) << minutes << ':'
1634                            << std::setw(2) << seconds;
1635     return s.str();
1636   }
1637
1638   string score_to_string(Value v) {
1639
1640     std::stringstream s;
1641
1642     if (v >= VALUE_MATE_IN_MAX_PLY)
1643         s << "#" << (VALUE_MATE - v + 1) / 2;
1644     else if (v <= VALUE_MATED_IN_MAX_PLY)
1645         s << "-#" << (VALUE_MATE + v) / 2;
1646     else
1647         s << std::setprecision(2) << std::fixed << std::showpos
1648           << float(v) / PawnValueMidgame;
1649
1650     return s.str();
1651   }
1652
1653   void pv_info_to_log(Position& pos, int depth, Value value, int time, Move pv[]) {
1654
1655     const int64_t K = 1000;
1656     const int64_t M = 1000000;
1657
1658     StateInfo state[MAX_PLY_PLUS_2], *st = state;
1659     Move* m = pv;
1660     string san, padding;
1661     size_t length;
1662     std::stringstream s;
1663
1664     s << std::setw(2) << depth
1665       << std::setw(8) << score_to_string(value)
1666       << std::setw(8) << time_to_string(time);
1667
1668     if (pos.nodes_searched() < M)
1669         s << std::setw(8) << pos.nodes_searched() / 1 << "  ";
1670
1671     else if (pos.nodes_searched() < K * M)
1672         s << std::setw(7) << pos.nodes_searched() / K << "K  ";
1673
1674     else
1675         s << std::setw(7) << pos.nodes_searched() / M << "M  ";
1676
1677     padding = string(s.str().length(), ' ');
1678     length = padding.length();
1679
1680     while (*m != MOVE_NONE)
1681     {
1682         san = move_to_san(pos, *m);
1683
1684         if (length + san.length() > 80)
1685         {
1686             s << "\n" + padding;
1687             length = padding.length();
1688         }
1689
1690         s << san << ' ';
1691         length += san.length() + 1;
1692
1693         pos.do_move(*m++, *st++);
1694     }
1695
1696     while (m != pv)
1697         pos.undo_move(*--m);
1698
1699     Log l(Options["Search Log Filename"]);
1700     l << s.str() << endl;
1701   }
1702
1703
1704   // When playing with strength handicap choose best move among the MultiPV set
1705   // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1706
1707   Move do_skill_level() {
1708
1709     assert(MultiPV > 1);
1710
1711     static RKISS rk;
1712
1713     // PRNG sequence should be not deterministic
1714     for (int i = abs(system_time() % 50); i > 0; i--)
1715         rk.rand<unsigned>();
1716
1717     // RootMoves are already sorted by score in descending order
1718     size_t size = std::min(MultiPV, RootMoves.size());
1719     int variance = std::min(RootMoves[0].score - RootMoves[size - 1].score, PawnValueMidgame);
1720     int weakness = 120 - 2 * SkillLevel;
1721     int max_s = -VALUE_INFINITE;
1722     Move best = MOVE_NONE;
1723
1724     // Choose best move. For each move score we add two terms both dependent on
1725     // weakness, one deterministic and bigger for weaker moves, and one random,
1726     // then we choose the move with the resulting highest score.
1727     for (size_t i = 0; i < size; i++)
1728     {
1729         int s = RootMoves[i].score;
1730
1731         // Don't allow crazy blunders even at very low skills
1732         if (i > 0 && RootMoves[i-1].score > s + EasyMoveMargin)
1733             break;
1734
1735         // This is our magic formula
1736         s += (  weakness * int(RootMoves[0].score - s)
1737               + variance * (rk.rand<unsigned>() % weakness)) / 128;
1738
1739         if (s > max_s)
1740         {
1741             max_s = s;
1742             best = RootMoves[i].pv[0];
1743         }
1744     }
1745     return best;
1746   }
1747
1748 } // namespace
1749
1750
1751 /// RootMove::extract_pv_from_tt() builds a PV by adding moves from the TT table.
1752 /// We consider also failing high nodes and not only BOUND_EXACT nodes so to
1753 /// allow to always have a ponder move even when we fail high at root, and a
1754 /// long PV to print that is important for position analysis.
1755
1756 void RootMove::extract_pv_from_tt(Position& pos) {
1757
1758   StateInfo state[MAX_PLY_PLUS_2], *st = state;
1759   TTEntry* tte;
1760   int ply = 1;
1761   Move m = pv[0];
1762
1763   assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1764
1765   pv.clear();
1766   pv.push_back(m);
1767   pos.do_move(m, *st++);
1768
1769   while (   (tte = TT.probe(pos.key())) != NULL
1770          && (m = tte->move()) != MOVE_NONE // Local copy, TT entry could change
1771          && pos.is_pseudo_legal(m)
1772          && pos.pl_move_is_legal(m, pos.pinned_pieces())
1773          && ply < MAX_PLY
1774          && (!pos.is_draw<false>() || ply < 2))
1775   {
1776       pv.push_back(m);
1777       pos.do_move(m, *st++);
1778       ply++;
1779   }
1780   pv.push_back(MOVE_NONE);
1781
1782   do pos.undo_move(pv[--ply]); while (ply);
1783 }
1784
1785
1786 /// RootMove::insert_pv_in_tt() is called at the end of a search iteration, and
1787 /// inserts the PV back into the TT. This makes sure the old PV moves are searched
1788 /// first, even if the old TT entries have been overwritten.
1789
1790 void RootMove::insert_pv_in_tt(Position& pos) {
1791
1792   StateInfo state[MAX_PLY_PLUS_2], *st = state;
1793   TTEntry* tte;
1794   Key k;
1795   Value v, m = VALUE_NONE;
1796   int ply = 0;
1797
1798   assert(pv[ply] != MOVE_NONE && pos.is_pseudo_legal(pv[ply]));
1799
1800   do {
1801       k = pos.key();
1802       tte = TT.probe(k);
1803
1804       // Don't overwrite existing correct entries
1805       if (!tte || tte->move() != pv[ply])
1806       {
1807           v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1808           TT.store(k, VALUE_NONE, BOUND_NONE, DEPTH_NONE, pv[ply], v, m);
1809       }
1810       pos.do_move(pv[ply], *st++);
1811
1812   } while (pv[++ply] != MOVE_NONE);
1813
1814   do pos.undo_move(pv[--ply]); while (ply);
1815 }
1816
1817
1818 /// Thread::idle_loop() is where the thread is parked when it has no work to do.
1819 /// The parameter 'master_sp', if non-NULL, is a pointer to an active SplitPoint
1820 /// object for which the thread is the master.
1821
1822 void Thread::idle_loop(SplitPoint* sp_master) {
1823
1824   // If this thread is the master of a split point and all slaves have
1825   // finished their work at this split point, return from the idle loop.
1826   while (!sp_master || sp_master->slavesMask)
1827   {
1828       // If we are not searching, wait for a condition to be signaled
1829       // instead of wasting CPU time polling for work.
1830       while (   do_sleep
1831              || do_exit
1832              || (!is_searching && Threads.use_sleeping_threads()))
1833       {
1834           if (do_exit)
1835           {
1836               assert(!sp_master);
1837               return;
1838           }
1839
1840           // Grab the lock to avoid races with Thread::wake_up()
1841           lock_grab(sleepLock);
1842
1843           // If we are master and all slaves have finished don't go to sleep
1844           if (sp_master && !sp_master->slavesMask)
1845           {
1846               lock_release(sleepLock);
1847               break;
1848           }
1849
1850           // Do sleep after retesting sleep conditions under lock protection, in
1851           // particular we need to avoid a deadlock in case a master thread has,
1852           // in the meanwhile, allocated us and sent the wake_up() call before we
1853           // had the chance to grab the lock.
1854           if (do_sleep || !is_searching)
1855               cond_wait(sleepCond, sleepLock);
1856
1857           lock_release(sleepLock);
1858       }
1859
1860       // If this thread has been assigned work, launch a search
1861       if (is_searching)
1862       {
1863           assert(!do_sleep && !do_exit);
1864
1865           lock_grab(Threads.splitLock);
1866
1867           assert(is_searching);
1868           SplitPoint* sp = curSplitPoint;
1869
1870           lock_release(Threads.splitLock);
1871
1872           Stack ss[MAX_PLY_PLUS_2];
1873           Position pos(*sp->pos, threadID);
1874           int master = sp->master;
1875
1876           memcpy(ss, sp->ss - 1, 4 * sizeof(Stack));
1877           (ss+1)->sp = sp;
1878
1879           lock_grab(sp->lock);
1880
1881           if (sp->nodeType == Root)
1882               search<SplitPointRoot>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1883           else if (sp->nodeType == PV)
1884               search<SplitPointPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1885           else if (sp->nodeType == NonPV)
1886               search<SplitPointNonPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1887           else
1888               assert(false);
1889
1890           assert(is_searching);
1891
1892           is_searching = false;
1893           sp->slavesMask &= ~(1ULL << threadID);
1894           sp->nodes += pos.nodes_searched();
1895
1896           // After releasing the lock we cannot access anymore any SplitPoint
1897           // related data in a reliably way becuase it could have been released
1898           // under our feet by the sp master.
1899           lock_release(sp->lock);
1900
1901           // Wake up master thread so to allow it to return from the idle loop in
1902           // case we are the last slave of the split point.
1903           if (   Threads.use_sleeping_threads()
1904               && threadID != master
1905               && !Threads[master].is_searching)
1906               Threads[master].wake_up();
1907       }
1908   }
1909   // In helpful master concept a master can help only a sub-tree of its split
1910   // point, and because here is all finished is not possible master is booked.
1911   assert(!is_searching);
1912 }
1913
1914
1915 /// check_time() is called by the timer thread when the timer triggers. It is
1916 /// used to print debug info and, more important, to detect when we are out of
1917 /// available time and so stop the search.
1918
1919 void check_time() {
1920
1921   static int lastInfoTime;
1922   int e = elapsed_time();
1923
1924   if (system_time() - lastInfoTime >= 1000 || !lastInfoTime)
1925   {
1926       lastInfoTime = system_time();
1927       dbg_print();
1928   }
1929
1930   if (Limits.ponder)
1931       return;
1932
1933   bool stillAtFirstMove =    Signals.firstRootMove
1934                          && !Signals.failedLowAtRoot
1935                          &&  e > TimeMgr.available_time();
1936
1937   bool noMoreTime =   e > TimeMgr.maximum_time() - 2 * TimerResolution
1938                    || stillAtFirstMove;
1939
1940   if (   (Limits.use_time_management() && noMoreTime)
1941       || (Limits.maxTime && e >= Limits.maxTime))
1942       Signals.stop = true;
1943 }