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