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