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