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