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