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