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