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