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