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