]> git.sesse.net Git - stockfish/blob - src/search.cpp
fb9bc17a26232b1d27853cb65e69a0691c07cd72
[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-2014 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 "evaluate.h"
28 #include "movegen.h"
29 #include "movepick.h"
30 #include "rkiss.h"
31 #include "search.h"
32 #include "timeman.h"
33 #include "thread.h"
34 #include "tt.h"
35 #include "uci.h"
36 #include "syzygy/tbprobe.h"
37
38 namespace Search {
39
40   volatile SignalsType Signals;
41   LimitsType Limits;
42   std::vector<RootMove> RootMoves;
43   Position RootPos;
44   Time::point SearchTime;
45   StateStackPtr SetupStates;
46   int TBCardinality;
47   uint64_t TBHits;
48   bool RootInTB;
49   bool TB50MoveRule;
50   Depth TBProbeDepth;
51   Value TBScore;
52 }
53
54 using std::string;
55 using Eval::evaluate;
56 using namespace Search;
57
58 namespace {
59
60   // Different node types, used as template parameter
61   enum NodeType { Root, PV, NonPV };
62
63   // Dynamic razoring margin based on depth
64   inline Value razor_margin(Depth d) { return Value(512 + 32 * d); }
65
66   // Futility lookup tables (initialized at startup) and their access functions
67   int FutilityMoveCounts[2][16]; // [improving][depth]
68
69   inline Value futility_margin(Depth d) {
70     return Value(200 * d);
71   }
72
73   // Reduction lookup tables (initialized at startup) and their access function
74   int8_t Reductions[2][2][64][64]; // [pv][improving][depth][moveNumber]
75
76   template <bool PvNode> inline Depth reduction(bool i, Depth d, int mn) {
77     return (Depth) Reductions[PvNode][i][std::min(int(d), 63)][std::min(mn, 63)];
78   }
79
80   size_t PVIdx;
81   TimeManager TimeMgr;
82   double BestMoveChanges;
83   Value DrawValue[COLOR_NB];
84   HistoryStats History;
85   GainsStats Gains;
86   MovesStats Countermoves, Followupmoves;
87
88   template <NodeType NT, bool SpNode>
89   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth, bool cutNode);
90
91   template <NodeType NT, bool InCheck>
92   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
93
94   void id_loop(Position& pos);
95   Value value_to_tt(Value v, int ply);
96   Value value_from_tt(Value v, int ply);
97   void update_pv(Move* pv, Move move, Move* childPv);
98   void update_stats(const Position& pos, Stack* ss, Move move, Depth depth, Move* quiets, int quietsCnt);
99   string uci_pv(const Position& pos, Depth depth, Value alpha, Value beta);
100
101   struct Skill {
102     Skill(int l, size_t rootSize) : level(l),
103                                     candidates(l < 20 ? std::min(4, (int)rootSize) : 0),
104                                     best(MOVE_NONE) {}
105    ~Skill() {
106       if (candidates) // Swap best PV line with the sub-optimal one
107           std::swap(RootMoves[0], *std::find(RootMoves.begin(),
108                     RootMoves.end(), best ? best : pick_move()));
109     }
110
111     size_t candidates_size() const { return candidates; }
112     bool time_to_pick(Depth depth) const { return depth / ONE_PLY == 1 + level; }
113     Move pick_move();
114
115     int level;
116     size_t candidates;
117     Move best;
118   };
119
120 } // namespace
121
122
123 /// Search::init() is called during startup to initialize various lookup tables
124
125 void Search::init() {
126
127   // Init reductions array
128   for (int d = 1; d < 64; ++d)
129       for (int mc = 1; mc < 64; ++mc)
130       {
131           double    pvRed = 0.00 + log(double(d)) * log(double(mc)) / 3.00;
132           double nonPVRed = 0.33 + log(double(d)) * log(double(mc)) / 2.25;
133
134           Reductions[1][1][d][mc] = int8_t(   pvRed >= 1.0 ?    pvRed + 0.5: 0);
135           Reductions[0][1][d][mc] = int8_t(nonPVRed >= 1.0 ? nonPVRed + 0.5: 0);
136
137           Reductions[1][0][d][mc] = Reductions[1][1][d][mc];
138           Reductions[0][0][d][mc] = Reductions[0][1][d][mc];
139
140           // Increase reduction when eval is not improving
141           if (Reductions[0][0][d][mc] >= 2)
142               Reductions[0][0][d][mc] += 1;
143       }
144
145   // Init futility move count array
146   for (int d = 0; d < 16; ++d)
147   {
148       FutilityMoveCounts[0][d] = int(2.4 + 0.773 * pow(d + 0.00, 1.8));
149       FutilityMoveCounts[1][d] = int(2.9 + 1.045 * pow(d + 0.49, 1.8));
150   }
151 }
152
153
154 /// Search::perft() is our utility to verify move generation. All the leaf nodes
155 /// up to the given depth are generated and counted and the sum returned.
156 template<bool Root>
157 uint64_t Search::perft(Position& pos, Depth depth) {
158
159   StateInfo st;
160   uint64_t cnt, nodes = 0;
161   CheckInfo ci(pos);
162   const bool leaf = (depth == 2 * ONE_PLY);
163
164   for (MoveList<LEGAL> it(pos); *it; ++it)
165   {
166       if (Root && depth <= ONE_PLY)
167           cnt = 1, nodes++;
168       else
169       {
170           pos.do_move(*it, st, ci, pos.gives_check(*it, ci));
171           cnt = leaf ? MoveList<LEGAL>(pos).size() : perft<false>(pos, depth - ONE_PLY);
172           nodes += cnt;
173           pos.undo_move(*it);
174       }
175       if (Root)
176           sync_cout << UCI::format_move(*it, pos.is_chess960()) << ": " << cnt << sync_endl;
177   }
178   return nodes;
179 }
180
181 template uint64_t Search::perft<true>(Position& pos, Depth depth);
182
183
184 /// Search::think() is the external interface to Stockfish's search, and is
185 /// called by the main thread when the program receives the UCI 'go' command. It
186 /// searches from RootPos and at the end prints the "bestmove" to output.
187
188 void Search::think() {
189
190   TimeMgr.init(Limits, RootPos.game_ply(), RootPos.side_to_move());
191   TBHits = TBCardinality = 0;
192   RootInTB = false;
193
194   int cf = Options["Contempt"] * PawnValueEg / 100; // From centipawns
195   DrawValue[ RootPos.side_to_move()] = VALUE_DRAW - Value(cf);
196   DrawValue[~RootPos.side_to_move()] = VALUE_DRAW + Value(cf);
197
198   if (RootMoves.empty())
199   {
200       RootMoves.push_back(MOVE_NONE);
201       sync_cout << "info depth 0 score "
202                 << UCI::format_value(RootPos.checkers() ? -VALUE_MATE : VALUE_DRAW)
203                 << sync_endl;
204   }
205   else
206   {
207       // Check Tablebases at root
208       int piecesCnt = RootPos.total_piece_count();
209       TBCardinality = Options["SyzygyProbeLimit"];
210       TBProbeDepth = Options["SyzygyProbeDepth"] * ONE_PLY;
211       if (TBCardinality > Tablebases::TBLargest)
212       {
213           TBCardinality = Tablebases::TBLargest;
214           TBProbeDepth = 0 * ONE_PLY;
215       }
216       TB50MoveRule = Options["Syzygy50MoveRule"];
217
218       if (piecesCnt <= TBCardinality)
219       {
220           TBHits = RootMoves.size();
221
222           // If the current root position is in the tablebases then RootMoves
223           // contains only moves that preserve the draw or win.
224           RootInTB = Tablebases::root_probe(RootPos, TBScore);
225
226           if (RootInTB)
227           {
228               TBCardinality = 0; // Do not probe tablebases during the search
229
230               // It might be a good idea to mangle the hash key (xor it
231               // with a fixed value) in order to "clear" the hash table of
232               // the results of previous probes. However, that would have to
233               // be done from within the Position class, so we skip it for now.
234
235               // Optional: decrease target time.
236           }
237           else // If DTZ tables are missing, use WDL tables as a fallback
238           {
239               // Filter out moves that do not preserve a draw or win
240               RootInTB = Tablebases::root_probe_wdl(RootPos, TBScore);
241
242               // Only probe during search if winning
243               if (TBScore <= VALUE_DRAW)
244                   TBCardinality = 0;
245           }
246
247           if (!RootInTB)
248           {
249               TBHits = 0;
250           }
251           else if (!TB50MoveRule)
252           {
253               TBScore = TBScore > VALUE_DRAW ? VALUE_MATE - MAX_PLY - 1
254                       : TBScore < VALUE_DRAW ? -VALUE_MATE + MAX_PLY + 1
255                       : TBScore;
256           }
257       }
258
259       for (size_t i = 0; i < Threads.size(); ++i)
260           Threads[i]->maxPly = 0;
261
262       Threads.timer->run = true;
263       Threads.timer->notify_one(); // Wake up the recurring timer
264
265       id_loop(RootPos); // Let's start searching !
266
267       Threads.timer->run = false;
268   }
269
270   // When we reach the maximum depth, we can arrive here without a raise of
271   // Signals.stop. However, if we are pondering or in an infinite search,
272   // the UCI protocol states that we shouldn't print the best move before the
273   // GUI sends a "stop" or "ponderhit" command. We therefore simply wait here
274   // until the GUI sends one of those commands (which also raises Signals.stop).
275   if (!Signals.stop && (Limits.ponder || Limits.infinite))
276   {
277       Signals.stopOnPonderhit = true;
278       RootPos.this_thread()->wait_for(Signals.stop);
279   }
280
281   sync_cout << "bestmove " << UCI::format_move(RootMoves[0].pv[0], RootPos.is_chess960());
282
283   if (RootMoves[0].pv.size() > 1)
284       std::cout << " ponder " << UCI::format_move(RootMoves[0].pv[1], RootPos.is_chess960());
285
286   std::cout << sync_endl;
287 }
288
289
290 namespace {
291
292   // id_loop() is the main iterative deepening loop. It calls search() repeatedly
293   // with increasing depth until the allocated thinking time has been consumed,
294   // user stops the search, or the maximum search depth is reached.
295
296   void id_loop(Position& pos) {
297
298     Stack stack[MAX_PLY+4], *ss = stack+2; // To allow referencing (ss-2) and (ss+2)
299     Depth depth;
300     Value bestValue, alpha, beta, delta;
301
302     std::memset(ss-2, 0, 5 * sizeof(Stack));
303
304     depth = DEPTH_ZERO;
305     BestMoveChanges = 0;
306     bestValue = delta = alpha = -VALUE_INFINITE;
307     beta = VALUE_INFINITE;
308
309     TT.new_search();
310     History.clear();
311     Gains.clear();
312     Countermoves.clear();
313     Followupmoves.clear();
314
315     size_t multiPV = Options["MultiPV"];
316     Skill skill(Options["Skill Level"], RootMoves.size());
317
318     // Do we have to play with skill handicap? In this case enable MultiPV search
319     // that we will use behind the scenes to retrieve a set of possible moves.
320     multiPV = std::max(multiPV, skill.candidates_size());
321
322     // Iterative deepening loop until requested to stop or target depth reached
323     while (++depth < DEPTH_MAX && !Signals.stop && (!Limits.depth || depth <= Limits.depth))
324     {
325         // Age out PV variability metric
326         BestMoveChanges *= 0.5;
327
328         // Save the last iteration's scores before first PV line is searched and
329         // all the move scores except the (new) PV are set to -VALUE_INFINITE.
330         for (size_t i = 0; i < RootMoves.size(); ++i)
331             RootMoves[i].prevScore = RootMoves[i].score;
332
333         // MultiPV loop. We perform a full root search for each PV line
334         for (PVIdx = 0; PVIdx < std::min(multiPV, RootMoves.size()) && !Signals.stop; ++PVIdx)
335         {
336             // Reset aspiration window starting size
337             if (depth >= 5 * ONE_PLY)
338             {
339                 delta = Value(16);
340                 alpha = std::max(RootMoves[PVIdx].prevScore - delta,-VALUE_INFINITE);
341                 beta  = std::min(RootMoves[PVIdx].prevScore + delta, VALUE_INFINITE);
342             }
343
344             // Start with a small aspiration window and, in the case of a fail
345             // high/low, re-search with a bigger window until we're not failing
346             // high/low anymore.
347             while (true)
348             {
349                 bestValue = search<Root, false>(pos, ss, alpha, beta, depth, false);
350
351                 // Bring the best move to the front. It is critical that sorting
352                 // is done with a stable algorithm because all the values but the
353                 // first and eventually the new best one are set to -VALUE_INFINITE
354                 // and we want to keep the same order for all the moves except the
355                 // new PV that goes to the front. Note that in case of MultiPV
356                 // search the already searched PV lines are preserved.
357                 std::stable_sort(RootMoves.begin() + PVIdx, RootMoves.end());
358
359                 // Write PV back to transposition table in case the relevant
360                 // entries have been overwritten during the search.
361                 for (size_t i = 0; i <= PVIdx; ++i)
362                     RootMoves[i].insert_pv_in_tt(pos);
363
364                 // If search has been stopped break immediately. Sorting and
365                 // writing PV back to TT is safe because RootMoves is still
366                 // valid, although it refers to previous iteration.
367                 if (Signals.stop)
368                     break;
369
370                 // When failing high/low give some update (without cluttering
371                 // the UI) before a re-search.
372                 if (  (bestValue <= alpha || bestValue >= beta)
373                     && Time::now() - SearchTime > 3000)
374                     sync_cout << uci_pv(pos, depth, alpha, beta) << sync_endl;
375
376                 // In case of failing low/high increase aspiration window and
377                 // re-search, otherwise exit the loop.
378                 if (bestValue <= alpha)
379                 {
380                     beta = (alpha + beta) / 2;
381                     alpha = std::max(bestValue - delta, -VALUE_INFINITE);
382
383                     Signals.failedLowAtRoot = true;
384                     Signals.stopOnPonderhit = false;
385                 }
386                 else if (bestValue >= beta)
387                 {
388                     alpha = (alpha + beta) / 2;
389                     beta = std::min(bestValue + delta, VALUE_INFINITE);
390                 }
391                 else
392                     break;
393
394                 delta += delta / 2;
395
396                 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
397             }
398
399             // Sort the PV lines searched so far and update the GUI
400             std::stable_sort(RootMoves.begin(), RootMoves.begin() + PVIdx + 1);
401
402             if (Signals.stop)
403                 sync_cout << "info nodes " << RootPos.nodes_searched()
404                           << " time " << Time::now() - SearchTime << sync_endl;
405
406             else if (   PVIdx + 1 == std::min(multiPV, RootMoves.size())
407                      || Time::now() - SearchTime > 3000)
408                 sync_cout << uci_pv(pos, depth, alpha, beta) << sync_endl;
409         }
410
411         // If skill levels are enabled and time is up, pick a sub-optimal best move
412         if (skill.candidates_size() && skill.time_to_pick(depth))
413             skill.pick_move();
414
415         // Have we found a "mate in x"?
416         if (   Limits.mate
417             && bestValue >= VALUE_MATE_IN_MAX_PLY
418             && VALUE_MATE - bestValue <= 2 * Limits.mate)
419             Signals.stop = true;
420
421         // Do we have time for the next iteration? Can we stop searching now?
422         if (Limits.use_time_management() && !Signals.stop && !Signals.stopOnPonderhit)
423         {
424             // Take some extra time if the best move has changed
425             if (depth > 4 * ONE_PLY && multiPV == 1)
426                 TimeMgr.pv_instability(BestMoveChanges);
427
428             // Stop the search if only one legal move is available or all
429             // of the available time has been used.
430             if (   RootMoves.size() == 1
431                 || Time::now() - SearchTime > TimeMgr.available_time())
432             {
433                 // If we are allowed to ponder do not stop the search now but
434                 // keep pondering until the GUI sends "ponderhit" or "stop".
435                 if (Limits.ponder)
436                     Signals.stopOnPonderhit = true;
437                 else
438                     Signals.stop = true;
439             }
440         }
441     }
442   }
443
444
445   // search<>() is the main search function for both PV and non-PV nodes and for
446   // normal and SplitPoint nodes. When called just after a split point the search
447   // is simpler because we have already probed the hash table, done a null move
448   // search, and searched the first move before splitting, so we don't have to
449   // repeat all this work again. We also don't need to store anything to the hash
450   // table here: This is taken care of after we return from the split point.
451
452   template <NodeType NT, bool SpNode>
453   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth, bool cutNode) {
454
455     const bool RootNode = NT == Root;
456     const bool PvNode   = NT == PV || NT == Root;
457
458     assert(-VALUE_INFINITE <= alpha && alpha < beta && beta <= VALUE_INFINITE);
459     assert(PvNode || (alpha == beta - 1));
460     assert(depth > DEPTH_ZERO);
461
462     Move pv[MAX_PLY+1], quietsSearched[64];
463     StateInfo st;
464     const TTEntry *tte;
465     SplitPoint* splitPoint;
466     Key posKey;
467     Move ttMove, move, excludedMove, bestMove;
468     Depth ext, newDepth, predictedDepth;
469     Value bestValue, value, ttValue, eval, nullValue, futilityValue;
470     bool inCheck, givesCheck, singularExtensionNode, improving;
471     bool captureOrPromotion, dangerous, doFullDepthSearch;
472     int moveCount, quietCount;
473
474     // Step 1. Initialize node
475     Thread* thisThread = pos.this_thread();
476     inCheck = pos.checkers();
477
478     if (SpNode)
479     {
480         splitPoint = ss->splitPoint;
481         bestMove   = splitPoint->bestMove;
482         bestValue  = splitPoint->bestValue;
483         tte = NULL;
484         ttMove = excludedMove = MOVE_NONE;
485         ttValue = VALUE_NONE;
486
487         assert(splitPoint->bestValue > -VALUE_INFINITE && splitPoint->moveCount > 0);
488
489         goto moves_loop;
490     }
491
492     moveCount = quietCount = 0;
493     bestValue = -VALUE_INFINITE;
494     ss->ply = (ss-1)->ply + 1;
495
496     // Used to send selDepth info to GUI
497     if (PvNode && thisThread->maxPly < ss->ply)
498         thisThread->maxPly = ss->ply;
499
500     if (!RootNode)
501     {
502         // Step 2. Check for aborted search and immediate draw
503         if (Signals.stop || pos.is_draw() || ss->ply >= MAX_PLY)
504             return ss->ply >= MAX_PLY && !inCheck ? evaluate(pos) : DrawValue[pos.side_to_move()];
505
506         // Step 3. Mate distance pruning. Even if we mate at the next move our score
507         // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
508         // a shorter mate was found upward in the tree then there is no need to search
509         // because we will never beat the current alpha. Same logic but with reversed
510         // signs applies also in the opposite condition of being mated instead of giving
511         // mate. In this case return a fail-high score.
512         alpha = std::max(mated_in(ss->ply), alpha);
513         beta = std::min(mate_in(ss->ply+1), beta);
514         if (alpha >= beta)
515             return alpha;
516     }
517
518     assert(0 <= ss->ply && ss->ply < MAX_PLY);
519
520     ss->currentMove = ss->ttMove = (ss+1)->excludedMove = bestMove = MOVE_NONE;
521     (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
522     (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
523
524     // Step 4. Transposition table lookup
525     // We don't want the score of a partial search to overwrite a previous full search
526     // TT value, so we use a different position key in case of an excluded move.
527     excludedMove = ss->excludedMove;
528     posKey = excludedMove ? pos.exclusion_key() : pos.key();
529     tte = TT.probe(posKey);
530     ss->ttMove = ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
531     ttValue = tte ? value_from_tt(tte->value(), ss->ply) : VALUE_NONE;
532
533     // At non-PV nodes we check for a fail high/low. We don't probe at PV nodes
534     if (  !PvNode
535         && tte
536         && tte->depth() >= depth
537         && ttValue != VALUE_NONE // Only in case of TT access race
538         && (ttValue >= beta ? (tte->bound() & BOUND_LOWER)
539                             : (tte->bound() & BOUND_UPPER)))
540     {
541         ss->currentMove = ttMove; // Can be MOVE_NONE
542
543         // If ttMove is quiet, update killers, history, counter move and followup move on TT hit
544         if (ttValue >= beta && ttMove && !pos.capture_or_promotion(ttMove) && !inCheck)
545             update_stats(pos, ss, ttMove, depth, NULL, 0);
546
547         return ttValue;
548     }
549
550     // Step 4a. Tablebase probe
551     if (   !RootNode
552         && pos.total_piece_count() <= TBCardinality
553         && ( pos.total_piece_count() < TBCardinality || depth >= TBProbeDepth )
554         && pos.rule50_count() == 0)
555     {
556         int found, v = Tablebases::probe_wdl(pos, &found);
557
558         if (found)
559         {
560             TBHits++;
561
562             if (TB50MoveRule) {
563                 value = v < -1 ? -VALUE_MATE + MAX_PLY + ss->ply
564                       : v >  1 ?  VALUE_MATE - MAX_PLY - ss->ply
565                       : VALUE_DRAW + 2 * v;
566             }
567             else
568             {
569                 value = v < 0 ? -VALUE_MATE + MAX_PLY + ss->ply
570                       : v > 0 ?  VALUE_MATE - MAX_PLY - ss->ply
571                       : VALUE_DRAW;
572             }
573
574             TT.store(posKey, value_to_tt(value, ss->ply), BOUND_EXACT,
575                      std::min(DEPTH_MAX - ONE_PLY, depth + 6 * ONE_PLY), MOVE_NONE, VALUE_NONE);
576
577             return value;
578         }
579     }
580
581     // Step 5. Evaluate the position statically and update parent's gain statistics
582     if (inCheck)
583     {
584         ss->staticEval = eval = VALUE_NONE;
585         goto moves_loop;
586     }
587
588     else if (tte)
589     {
590         // Never assume anything on values stored in TT
591         if ((ss->staticEval = eval = tte->eval_value()) == VALUE_NONE)
592             eval = ss->staticEval = evaluate(pos);
593
594         // Can ttValue be used as a better position evaluation?
595         if (ttValue != VALUE_NONE)
596             if (tte->bound() & (ttValue > eval ? BOUND_LOWER : BOUND_UPPER))
597                 eval = ttValue;
598     }
599     else
600     {
601         eval = ss->staticEval =
602         (ss-1)->currentMove != MOVE_NULL ? evaluate(pos) : -(ss-1)->staticEval + 2 * Eval::Tempo;
603
604         TT.store(posKey, VALUE_NONE, BOUND_NONE, DEPTH_NONE, MOVE_NONE, ss->staticEval);
605     }
606
607     if (   !pos.captured_piece_type()
608         &&  ss->staticEval != VALUE_NONE
609         && (ss-1)->staticEval != VALUE_NONE
610         && (move = (ss-1)->currentMove) != MOVE_NULL
611         &&  move != MOVE_NONE
612         &&  type_of(move) == NORMAL)
613     {
614         Square to = to_sq(move);
615         Gains.update(pos.piece_on(to), to, -(ss-1)->staticEval - ss->staticEval);
616     }
617
618     // Step 6. Razoring (skipped when in check)
619     if (   !PvNode
620         &&  depth < 4 * ONE_PLY
621         &&  eval + razor_margin(depth) <= alpha
622         &&  ttMove == MOVE_NONE
623         && !pos.pawn_on_7th(pos.side_to_move()))
624     {
625         if (   depth <= ONE_PLY
626             && eval + razor_margin(3 * ONE_PLY) <= alpha)
627             return qsearch<NonPV, false>(pos, ss, alpha, beta, DEPTH_ZERO);
628
629         Value ralpha = alpha - razor_margin(depth);
630         Value v = qsearch<NonPV, false>(pos, ss, ralpha, ralpha+1, DEPTH_ZERO);
631         if (v <= ralpha)
632             return v;
633     }
634
635     // Step 7. Futility pruning: child node (skipped when in check)
636     if (   !PvNode
637         && !ss->skipNullMove
638         &&  depth < 7 * ONE_PLY
639         &&  eval - futility_margin(depth) >= beta
640         &&  eval < VALUE_KNOWN_WIN  // Do not return unproven wins
641         &&  pos.non_pawn_material(pos.side_to_move()))
642         return eval - futility_margin(depth);
643
644     // Step 8. Null move search with verification search (is omitted in PV nodes)
645     if (   !PvNode
646         && !ss->skipNullMove
647         &&  depth >= 2 * ONE_PLY
648         &&  eval >= beta
649         &&  pos.non_pawn_material(pos.side_to_move()))
650     {
651         ss->currentMove = MOVE_NULL;
652
653         assert(eval - beta >= 0);
654
655         // Null move dynamic reduction based on depth and value
656         Depth R = (3 + depth / 4 + std::min((eval - beta) / PawnValueMg, 3)) * ONE_PLY;
657
658         pos.do_null_move(st);
659         (ss+1)->skipNullMove = true;
660         nullValue = depth-R < ONE_PLY ? -qsearch<NonPV, false>(pos, ss+1, -beta, -beta+1, DEPTH_ZERO)
661                                       : - search<NonPV, false>(pos, ss+1, -beta, -beta+1, depth-R, !cutNode);
662         (ss+1)->skipNullMove = false;
663         pos.undo_null_move();
664
665         if (nullValue >= beta)
666         {
667             // Do not return unproven mate scores
668             if (nullValue >= VALUE_MATE_IN_MAX_PLY)
669                 nullValue = beta;
670
671             if (depth < 12 * ONE_PLY && abs(beta) < VALUE_KNOWN_WIN)
672                 return nullValue;
673
674             // Do verification search at high depths
675             ss->skipNullMove = true;
676             Value v = depth-R < ONE_PLY ? qsearch<NonPV, false>(pos, ss, beta-1, beta, DEPTH_ZERO)
677                                         :  search<NonPV, false>(pos, ss, beta-1, beta, depth-R, false);
678             ss->skipNullMove = false;
679
680             if (v >= beta)
681                 return nullValue;
682         }
683     }
684
685     // Step 9. ProbCut (skipped when in check)
686     // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
687     // and a reduced search returns a value much above beta, we can (almost) safely
688     // prune the previous move.
689     if (   !PvNode
690         &&  depth >= 5 * ONE_PLY
691         && !ss->skipNullMove
692         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY)
693     {
694         Value rbeta = std::min(beta + 200, VALUE_INFINITE);
695         Depth rdepth = depth - 4 * ONE_PLY;
696
697         assert(rdepth >= ONE_PLY);
698         assert((ss-1)->currentMove != MOVE_NONE);
699         assert((ss-1)->currentMove != MOVE_NULL);
700
701         MovePicker mp(pos, ttMove, History, pos.captured_piece_type());
702         CheckInfo ci(pos);
703
704         while ((move = mp.next_move<false>()) != MOVE_NONE)
705             if (pos.legal(move, ci.pinned))
706             {
707                 ss->currentMove = move;
708                 pos.do_move(move, st, ci, pos.gives_check(move, ci));
709                 value = -search<NonPV, false>(pos, ss+1, -rbeta, -rbeta+1, rdepth, !cutNode);
710                 pos.undo_move(move);
711                 if (value >= rbeta)
712                     return value;
713             }
714     }
715
716     // Step 10. Internal iterative deepening (skipped when in check)
717     if (    depth >= (PvNode ? 5 * ONE_PLY : 8 * ONE_PLY)
718         && !ttMove
719         && (PvNode || ss->staticEval + 256 >= beta))
720     {
721         Depth d = 2 * (depth - 2 * ONE_PLY) - (PvNode ? DEPTH_ZERO : depth / 2);
722         ss->skipNullMove = true;
723         search<PvNode ? PV : NonPV, false>(pos, ss, alpha, beta, d / 2, true);
724         ss->skipNullMove = false;
725
726         tte = TT.probe(posKey);
727         ttMove = tte ? tte->move() : MOVE_NONE;
728     }
729
730 moves_loop: // When in check and at SpNode search starts from here
731
732     Square prevMoveSq = to_sq((ss-1)->currentMove);
733     Move countermoves[] = { Countermoves[pos.piece_on(prevMoveSq)][prevMoveSq].first,
734                             Countermoves[pos.piece_on(prevMoveSq)][prevMoveSq].second };
735
736     Square prevOwnMoveSq = to_sq((ss-2)->currentMove);
737     Move followupmoves[] = { Followupmoves[pos.piece_on(prevOwnMoveSq)][prevOwnMoveSq].first,
738                              Followupmoves[pos.piece_on(prevOwnMoveSq)][prevOwnMoveSq].second };
739
740     MovePicker mp(pos, ttMove, depth, History, countermoves, followupmoves, ss);
741     CheckInfo ci(pos);
742     value = bestValue; // Workaround a bogus 'uninitialized' warning under gcc
743     improving =   ss->staticEval >= (ss-2)->staticEval
744                || ss->staticEval == VALUE_NONE
745                ||(ss-2)->staticEval == VALUE_NONE;
746
747     singularExtensionNode =   !RootNode
748                            && !SpNode
749                            &&  depth >= 8 * ONE_PLY
750                            &&  ttMove != MOVE_NONE
751                        /*  &&  ttValue != VALUE_NONE Already implicit in the next condition */
752                            &&  abs(ttValue) < VALUE_KNOWN_WIN
753                            && !excludedMove // Recursive singular search is not allowed
754                            && (tte->bound() & BOUND_LOWER)
755                            &&  tte->depth() >= depth - 3 * ONE_PLY;
756
757     // Step 11. Loop through moves
758     // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
759     while ((move = mp.next_move<SpNode>()) != MOVE_NONE)
760     {
761       assert(is_ok(move));
762
763       if (move == excludedMove)
764           continue;
765
766       // At root obey the "searchmoves" option and skip moves not listed in Root
767       // Move List. As a consequence any illegal move is also skipped. In MultiPV
768       // mode we also skip PV moves which have been already searched.
769       if (RootNode && !std::count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
770           continue;
771
772       if (SpNode)
773       {
774           // Shared counter cannot be decremented later if the move turns out to be illegal
775           if (!pos.legal(move, ci.pinned))
776               continue;
777
778           moveCount = ++splitPoint->moveCount;
779           splitPoint->mutex.unlock();
780       }
781       else
782           ++moveCount;
783
784       if (RootNode)
785       {
786           Signals.firstRootMove = (moveCount == 1);
787
788           if (thisThread == Threads.main() && Time::now() - SearchTime > 3000)
789               sync_cout << "info depth " << depth / ONE_PLY
790                         << " currmove " << UCI::format_move(move, pos.is_chess960())
791                         << " currmovenumber " << moveCount + PVIdx << sync_endl;
792       }
793
794       if (PvNode)
795           (ss+1)->pv = NULL;
796
797       ext = DEPTH_ZERO;
798       captureOrPromotion = pos.capture_or_promotion(move);
799
800       givesCheck =  type_of(move) == NORMAL && !ci.dcCandidates
801                   ? ci.checkSq[type_of(pos.piece_on(from_sq(move)))] & to_sq(move)
802                   : pos.gives_check(move, ci);
803
804       dangerous =   givesCheck
805                  || type_of(move) != NORMAL
806                  || pos.advanced_pawn_push(move);
807
808       // Step 12. Extend checks
809       if (givesCheck && pos.see_sign(move) >= VALUE_ZERO)
810           ext = ONE_PLY;
811
812       // Singular extension search. If all moves but one fail low on a search of
813       // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
814       // is singular and should be extended. To verify this we do a reduced search
815       // on all the other moves but the ttMove and if the result is lower than
816       // ttValue minus a margin then we extend the ttMove.
817       if (    singularExtensionNode
818           &&  move == ttMove
819           && !ext
820           &&  pos.legal(move, ci.pinned))
821       {
822           Value rBeta = ttValue - 2 * depth / ONE_PLY;
823           ss->excludedMove = move;
824           ss->skipNullMove = true;
825           value = search<NonPV, false>(pos, ss, rBeta - 1, rBeta, depth / 2, cutNode);
826           ss->skipNullMove = false;
827           ss->excludedMove = MOVE_NONE;
828
829           if (value < rBeta)
830               ext = ONE_PLY;
831       }
832
833       // Update the current move (this must be done after singular extension search)
834       newDepth = depth - ONE_PLY + ext;
835
836       // Step 13. Pruning at shallow depth (exclude PV nodes)
837       if (   !PvNode
838           && !captureOrPromotion
839           && !inCheck
840           && !dangerous
841           &&  bestValue > VALUE_MATED_IN_MAX_PLY)
842       {
843           // Move count based pruning
844           if (   depth < 16 * ONE_PLY
845               && moveCount >= FutilityMoveCounts[improving][depth])
846           {
847               if (SpNode)
848                   splitPoint->mutex.lock();
849
850               continue;
851           }
852
853           predictedDepth = newDepth - reduction<PvNode>(improving, depth, moveCount);
854
855           // Futility pruning: parent node
856           if (predictedDepth < 7 * ONE_PLY)
857           {
858               futilityValue =  ss->staticEval + futility_margin(predictedDepth)
859                              + 128 + Gains[pos.moved_piece(move)][to_sq(move)];
860
861               if (futilityValue <= alpha)
862               {
863                   bestValue = std::max(bestValue, futilityValue);
864
865                   if (SpNode)
866                   {
867                       splitPoint->mutex.lock();
868                       if (bestValue > splitPoint->bestValue)
869                           splitPoint->bestValue = bestValue;
870                   }
871                   continue;
872               }
873           }
874
875           // Prune moves with negative SEE at low depths
876           if (predictedDepth < 4 * ONE_PLY && pos.see_sign(move) < VALUE_ZERO)
877           {
878               if (SpNode)
879                   splitPoint->mutex.lock();
880
881               continue;
882           }
883       }
884
885       // Speculative prefetch as early as possible
886       prefetch((char*)TT.first_entry(pos.key_after(move)));
887
888       // Check for legality just before making the move
889       if (!RootNode && !SpNode && !pos.legal(move, ci.pinned))
890       {
891           moveCount--;
892           continue;
893       }
894
895       ss->currentMove = move;
896       if (!SpNode && !captureOrPromotion && quietCount < 64)
897           quietsSearched[quietCount++] = move;
898
899       // Step 14. Make the move
900       pos.do_move(move, st, ci, givesCheck);
901
902       // Step 15. Reduced depth search (LMR). If the move fails high it will be
903       // re-searched at full depth.
904       if (    depth >= 3 * ONE_PLY
905           &&  moveCount > 1
906           && !captureOrPromotion
907           &&  move != ss->killers[0]
908           &&  move != ss->killers[1])
909       {
910           ss->reduction = reduction<PvNode>(improving, depth, moveCount);
911
912           if (   (!PvNode && cutNode)
913               ||  History[pos.piece_on(to_sq(move))][to_sq(move)] < 0)
914               ss->reduction += ONE_PLY;
915
916           if (move == countermoves[0] || move == countermoves[1])
917               ss->reduction = std::max(DEPTH_ZERO, ss->reduction - ONE_PLY);
918
919           // Decrease reduction for moves that escape a capture
920           if (   ss->reduction
921               && type_of(move) == NORMAL
922               && type_of(pos.piece_on(to_sq(move))) != PAWN
923               && pos.see(make_move(to_sq(move), from_sq(move))) < 0)
924               ss->reduction = std::max(DEPTH_ZERO, ss->reduction - ONE_PLY);
925
926           Depth d = std::max(newDepth - ss->reduction, ONE_PLY);
927           if (SpNode)
928               alpha = splitPoint->alpha;
929
930           value = -search<NonPV, false>(pos, ss+1, -(alpha+1), -alpha, d, true);
931
932           // Re-search at intermediate depth if reduction is very high
933           if (value > alpha && ss->reduction >= 4 * ONE_PLY)
934           {
935               Depth d2 = std::max(newDepth - 2 * ONE_PLY, ONE_PLY);
936               value = -search<NonPV, false>(pos, ss+1, -(alpha+1), -alpha, d2, true);
937           }
938
939           doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
940           ss->reduction = DEPTH_ZERO;
941       }
942       else
943           doFullDepthSearch = !PvNode || moveCount > 1;
944
945       // Step 16. Full depth search, when LMR is skipped or fails high
946       if (doFullDepthSearch)
947       {
948           if (SpNode)
949               alpha = splitPoint->alpha;
950
951           value = newDepth <   ONE_PLY ?
952                             givesCheck ? -qsearch<NonPV,  true>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
953                                        : -qsearch<NonPV, false>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
954                                        : - search<NonPV, false>(pos, ss+1, -(alpha+1), -alpha, newDepth, !cutNode);
955       }
956
957       // For PV nodes only, do a full PV search on the first move or after a fail
958       // high (in the latter case search only if value < beta), otherwise let the
959       // parent node fail low with value <= alpha and to try another move.
960       if (PvNode && (moveCount == 1 || (value > alpha && (RootNode || value < beta))))
961       {
962           (ss+1)->pv = pv;
963           (ss+1)->pv[0] = MOVE_NONE;
964
965           value = newDepth <   ONE_PLY ?
966                             givesCheck ? -qsearch<PV,  true>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
967                                        : -qsearch<PV, false>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
968                                        : - search<PV, false>(pos, ss+1, -beta, -alpha, newDepth, false);
969       }
970
971       // Step 17. Undo move
972       pos.undo_move(move);
973
974       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
975
976       // Step 18. Check for new best move
977       if (SpNode)
978       {
979           splitPoint->mutex.lock();
980           bestValue = splitPoint->bestValue;
981           alpha = splitPoint->alpha;
982       }
983
984       // Finished searching the move. If a stop or a cutoff occurred, the return
985       // value of the search cannot be trusted, and we return immediately without
986       // updating best move, PV and TT.
987       if (Signals.stop || thisThread->cutoff_occurred())
988           return VALUE_ZERO;
989
990       if (RootNode)
991       {
992           RootMove& rm = *std::find(RootMoves.begin(), RootMoves.end(), move);
993
994           // PV move or new best move ?
995           if (moveCount == 1 || value > alpha)
996           {
997               rm.score = value;
998               rm.pv.resize(1);
999
1000               assert((ss+1)->pv);
1001
1002               for (Move* m = (ss+1)->pv; *m != MOVE_NONE; ++m)
1003                   rm.pv.push_back(*m);
1004
1005               // We record how often the best move has been changed in each
1006               // iteration. This information is used for time management: When
1007               // the best move changes frequently, we allocate some more time.
1008               if (moveCount > 1)
1009                   ++BestMoveChanges;
1010           }
1011           else
1012               // All other moves but the PV are set to the lowest value: this is
1013               // not a problem when sorting because the sort is stable and the
1014               // move position in the list is preserved - just the PV is pushed up.
1015               rm.score = -VALUE_INFINITE;
1016       }
1017
1018       if (value > bestValue)
1019       {
1020           bestValue = SpNode ? splitPoint->bestValue = value : value;
1021
1022           if (value > alpha)
1023           {
1024               bestMove = SpNode ? splitPoint->bestMove = move : move;
1025
1026               if (PvNode && !RootNode) // Update pv even in fail-high case
1027                   update_pv(SpNode ? splitPoint->ss->pv : ss->pv, move, (ss+1)->pv);
1028
1029               if (PvNode && value < beta) // Update alpha! Always alpha < beta
1030                   alpha = SpNode ? splitPoint->alpha = value : value;
1031               else
1032               {
1033                   assert(value >= beta); // Fail high
1034
1035                   if (SpNode)
1036                       splitPoint->cutoff = true;
1037
1038                   break;
1039               }
1040           }
1041       }
1042
1043       // Step 19. Check for splitting the search
1044       if (   !SpNode
1045           &&  Threads.size() >= 2
1046           &&  depth >= Threads.minimumSplitDepth
1047           &&  (   !thisThread->activeSplitPoint
1048                || !thisThread->activeSplitPoint->allSlavesSearching)
1049           &&  thisThread->splitPointsSize < MAX_SPLITPOINTS_PER_THREAD)
1050       {
1051           assert(bestValue > -VALUE_INFINITE && bestValue < beta);
1052
1053           thisThread->split(pos, ss, alpha, beta, &bestValue, &bestMove,
1054                             depth, moveCount, &mp, NT, cutNode);
1055
1056           if (Signals.stop || thisThread->cutoff_occurred())
1057               return VALUE_ZERO;
1058
1059           if (bestValue >= beta)
1060               break;
1061       }
1062     }
1063
1064     if (SpNode)
1065         return bestValue;
1066
1067     // Following condition would detect a stop or a cutoff set only after move
1068     // loop has been completed. But in this case bestValue is valid because we
1069     // have fully searched our subtree, and we can anyhow save the result in TT.
1070     /*
1071        if (Signals.stop || thisThread->cutoff_occurred())
1072         return VALUE_DRAW;
1073     */
1074
1075     // Step 20. Check for mate and stalemate
1076     // All legal moves have been searched and if there are no legal moves, it
1077     // must be mate or stalemate. If we are in a singular extension search then
1078     // return a fail low score.
1079     if (!moveCount)
1080         bestValue = excludedMove ? alpha
1081                    :     inCheck ? mated_in(ss->ply) : DrawValue[pos.side_to_move()];
1082
1083     // Quiet best move: update killers, history, countermoves and followupmoves
1084     else if (bestValue >= beta && !pos.capture_or_promotion(bestMove) && !inCheck)
1085         update_stats(pos, ss, bestMove, depth, quietsSearched, quietCount - 1);
1086
1087     TT.store(posKey, value_to_tt(bestValue, ss->ply),
1088              bestValue >= beta  ? BOUND_LOWER :
1089              PvNode && bestMove ? BOUND_EXACT : BOUND_UPPER,
1090              depth, bestMove, ss->staticEval);
1091
1092     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1093
1094     return bestValue;
1095   }
1096
1097
1098   // qsearch() is the quiescence search function, which is called by the main
1099   // search function when the remaining depth is zero (or, to be more precise,
1100   // less than ONE_PLY).
1101
1102   template <NodeType NT, bool InCheck>
1103   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1104
1105     const bool PvNode = NT == PV;
1106
1107     assert(NT == PV || NT == NonPV);
1108     assert(InCheck == !!pos.checkers());
1109     assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1110     assert(PvNode || (alpha == beta - 1));
1111     assert(depth <= DEPTH_ZERO);
1112
1113     Move pv[MAX_PLY+1];
1114     StateInfo st;
1115     const TTEntry* tte;
1116     Key posKey;
1117     Move ttMove, move, bestMove;
1118     Value bestValue, value, ttValue, futilityValue, futilityBase, oldAlpha;
1119     bool givesCheck, evasionPrunable;
1120     Depth ttDepth;
1121
1122     if (PvNode)
1123     {
1124         oldAlpha = alpha; // To flag BOUND_EXACT when eval above alpha and no available moves
1125         (ss+1)->pv = pv;
1126         ss->pv[0] = MOVE_NONE;
1127     }
1128
1129     ss->currentMove = bestMove = MOVE_NONE;
1130     ss->ply = (ss-1)->ply + 1;
1131
1132     // Check for an instant draw or if the maximum ply has been reached
1133     if (pos.is_draw() || ss->ply >= MAX_PLY)
1134         return ss->ply >= MAX_PLY && !InCheck ? evaluate(pos) : DrawValue[pos.side_to_move()];
1135
1136     assert(0 <= ss->ply && ss->ply < MAX_PLY);
1137
1138     // Decide whether or not to include checks: this fixes also the type of
1139     // TT entry depth that we are going to use. Note that in qsearch we use
1140     // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1141     ttDepth = InCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS
1142                                                   : DEPTH_QS_NO_CHECKS;
1143
1144     // Transposition table lookup
1145     posKey = pos.key();
1146     tte = TT.probe(posKey);
1147     ttMove = tte ? tte->move() : MOVE_NONE;
1148     ttValue = tte ? value_from_tt(tte->value(),ss->ply) : VALUE_NONE;
1149
1150     if (  !PvNode
1151         && tte
1152         && tte->depth() >= ttDepth
1153         && ttValue != VALUE_NONE // Only in case of TT access race
1154         && (ttValue >= beta ? (tte->bound() &  BOUND_LOWER)
1155                             : (tte->bound() &  BOUND_UPPER)))
1156     {
1157         ss->currentMove = ttMove; // Can be MOVE_NONE
1158         return ttValue;
1159     }
1160
1161     // Evaluate the position statically
1162     if (InCheck)
1163     {
1164         ss->staticEval = VALUE_NONE;
1165         bestValue = futilityBase = -VALUE_INFINITE;
1166     }
1167     else
1168     {
1169         if (tte)
1170         {
1171             // Never assume anything on values stored in TT
1172             if ((ss->staticEval = bestValue = tte->eval_value()) == VALUE_NONE)
1173                 ss->staticEval = bestValue = evaluate(pos);
1174
1175             // Can ttValue be used as a better position evaluation?
1176             if (ttValue != VALUE_NONE)
1177                 if (tte->bound() & (ttValue > bestValue ? BOUND_LOWER : BOUND_UPPER))
1178                     bestValue = ttValue;
1179         }
1180         else
1181             ss->staticEval = bestValue =
1182             (ss-1)->currentMove != MOVE_NULL ? evaluate(pos) : -(ss-1)->staticEval + 2 * Eval::Tempo;
1183
1184         // Stand pat. Return immediately if static value is at least beta
1185         if (bestValue >= beta)
1186         {
1187             if (!tte)
1188                 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), BOUND_LOWER,
1189                          DEPTH_NONE, MOVE_NONE, ss->staticEval);
1190
1191             return bestValue;
1192         }
1193
1194         if (PvNode && bestValue > alpha)
1195             alpha = bestValue;
1196
1197         futilityBase = bestValue + 128;
1198     }
1199
1200     // Initialize a MovePicker object for the current position, and prepare
1201     // to search the moves. Because the depth is <= 0 here, only captures,
1202     // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1203     // be generated.
1204     MovePicker mp(pos, ttMove, depth, History, to_sq((ss-1)->currentMove));
1205     CheckInfo ci(pos);
1206
1207     // Loop through the moves until no moves remain or a beta cutoff occurs
1208     while ((move = mp.next_move<false>()) != MOVE_NONE)
1209     {
1210       assert(is_ok(move));
1211
1212       givesCheck =  type_of(move) == NORMAL && !ci.dcCandidates
1213                   ? ci.checkSq[type_of(pos.piece_on(from_sq(move)))] & to_sq(move)
1214                   : pos.gives_check(move, ci);
1215
1216       // Futility pruning
1217       if (   !PvNode
1218           && !InCheck
1219           && !givesCheck
1220           &&  futilityBase > -VALUE_KNOWN_WIN
1221           && !pos.advanced_pawn_push(move))
1222       {
1223           assert(type_of(move) != ENPASSANT); // Due to !pos.advanced_pawn_push
1224
1225           futilityValue = futilityBase + PieceValue[EG][pos.piece_on(to_sq(move))];
1226
1227           if (futilityValue < beta)
1228           {
1229               bestValue = std::max(bestValue, futilityValue);
1230               continue;
1231           }
1232
1233           if (futilityBase < beta && pos.see(move) <= VALUE_ZERO)
1234           {
1235               bestValue = std::max(bestValue, futilityBase);
1236               continue;
1237           }
1238       }
1239
1240       // Detect non-capture evasions that are candidates to be pruned
1241       evasionPrunable =    InCheck
1242                        &&  bestValue > VALUE_MATED_IN_MAX_PLY
1243                        && !pos.capture(move)
1244                        && !pos.can_castle(pos.side_to_move());
1245
1246       // Don't search moves with negative SEE values
1247       if (   !PvNode
1248           && (!InCheck || evasionPrunable)
1249           &&  type_of(move) != PROMOTION
1250           &&  pos.see_sign(move) < VALUE_ZERO)
1251           continue;
1252
1253       // Speculative prefetch as early as possible
1254       prefetch((char*)TT.first_entry(pos.key_after(move)));
1255
1256       // Check for legality just before making the move
1257       if (!pos.legal(move, ci.pinned))
1258           continue;
1259
1260       ss->currentMove = move;
1261
1262       // Make and search the move
1263       pos.do_move(move, st, ci, givesCheck);
1264       value = givesCheck ? -qsearch<NT,  true>(pos, ss+1, -beta, -alpha, depth - ONE_PLY)
1265                          : -qsearch<NT, false>(pos, ss+1, -beta, -alpha, depth - ONE_PLY);
1266       pos.undo_move(move);
1267
1268       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1269
1270       // Check for new best move
1271       if (value > bestValue)
1272       {
1273           bestValue = value;
1274
1275           if (value > alpha)
1276           {
1277               if (PvNode) // Update pv even in fail-high case
1278                   update_pv(ss->pv, move, (ss+1)->pv);
1279
1280               if (PvNode && value < beta) // Update alpha here! Always alpha < beta
1281               {
1282                   alpha = value;
1283                   bestMove = move;
1284               }
1285               else // Fail high
1286               {
1287                   TT.store(posKey, value_to_tt(value, ss->ply), BOUND_LOWER,
1288                            ttDepth, move, ss->staticEval);
1289
1290                   return value;
1291               }
1292           }
1293        }
1294     }
1295
1296     // All legal moves have been searched. A special case: If we're in check
1297     // and no legal moves were found, it is checkmate.
1298     if (InCheck && bestValue == -VALUE_INFINITE)
1299         return mated_in(ss->ply); // Plies to mate from the root
1300
1301     TT.store(posKey, value_to_tt(bestValue, ss->ply),
1302              PvNode && bestValue > oldAlpha ? BOUND_EXACT : BOUND_UPPER,
1303              ttDepth, bestMove, ss->staticEval);
1304
1305     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1306
1307     return bestValue;
1308   }
1309
1310
1311   // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1312   // "plies to mate from the current position". Non-mate scores are unchanged.
1313   // The function is called before storing a value in the transposition table.
1314
1315   Value value_to_tt(Value v, int ply) {
1316
1317     assert(v != VALUE_NONE);
1318
1319     return  v >= VALUE_MATE_IN_MAX_PLY  ? v + ply
1320           : v <= VALUE_MATED_IN_MAX_PLY ? v - ply : v;
1321   }
1322
1323
1324   // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
1325   // from the transposition table (which refers to the plies to mate/be mated
1326   // from current position) to "plies to mate/be mated from the root".
1327
1328   Value value_from_tt(Value v, int ply) {
1329
1330     return  v == VALUE_NONE             ? VALUE_NONE
1331           : v >= VALUE_MATE_IN_MAX_PLY  ? v - ply
1332           : v <= VALUE_MATED_IN_MAX_PLY ? v + ply : v;
1333   }
1334
1335
1336   // update_pv() adds current move and appends child pv[]
1337
1338   void update_pv(Move* pv, Move move, Move* childPv) {
1339
1340     for (*pv++ = move; childPv && *childPv != MOVE_NONE; )
1341         *pv++ = *childPv++;
1342     *pv = MOVE_NONE;
1343   }
1344
1345   // update_stats() updates killers, history, countermoves and followupmoves stats after a fail-high
1346   // of a quiet move.
1347
1348   void update_stats(const Position& pos, Stack* ss, Move move, Depth depth, Move* quiets, int quietsCnt) {
1349
1350     if (ss->killers[0] != move)
1351     {
1352         ss->killers[1] = ss->killers[0];
1353         ss->killers[0] = move;
1354     }
1355
1356     // Increase history value of the cut-off move and decrease all the other
1357     // played quiet moves.
1358     Value bonus = Value((depth / ONE_PLY) * (depth / ONE_PLY));
1359     History.update(pos.moved_piece(move), to_sq(move), bonus);
1360     for (int i = 0; i < quietsCnt; ++i)
1361     {
1362         Move m = quiets[i];
1363         History.update(pos.moved_piece(m), to_sq(m), -bonus);
1364     }
1365
1366     if (is_ok((ss-1)->currentMove))
1367     {
1368         Square prevMoveSq = to_sq((ss-1)->currentMove);
1369         Countermoves.update(pos.piece_on(prevMoveSq), prevMoveSq, move);
1370     }
1371
1372     if (is_ok((ss-2)->currentMove) && (ss-1)->currentMove == (ss-1)->ttMove)
1373     {
1374         Square prevOwnMoveSq = to_sq((ss-2)->currentMove);
1375         Followupmoves.update(pos.piece_on(prevOwnMoveSq), prevOwnMoveSq, move);
1376     }
1377   }
1378
1379
1380   // When playing with a strength handicap, choose best move among the first 'candidates'
1381   // RootMoves using a statistical rule dependent on 'level'. Idea by Heinz van Saanen.
1382
1383   Move Skill::pick_move() {
1384
1385     static RKISS rk;
1386
1387     // PRNG sequence should be not deterministic
1388     for (int i = Time::now() % 50; i > 0; --i)
1389         rk.rand<unsigned>();
1390
1391     // RootMoves are already sorted by score in descending order
1392     int variance = std::min(RootMoves[0].score - RootMoves[candidates - 1].score, PawnValueMg);
1393     int weakness = 120 - 2 * level;
1394     int max_s = -VALUE_INFINITE;
1395     best = MOVE_NONE;
1396
1397     // Choose best move. For each move score we add two terms both dependent on
1398     // weakness. One deterministic and bigger for weaker moves, and one random,
1399     // then we choose the move with the resulting highest score.
1400     for (size_t i = 0; i < candidates; ++i)
1401     {
1402         int s = RootMoves[i].score;
1403
1404         // Don't allow crazy blunders even at very low skills
1405         if (i > 0 && RootMoves[i - 1].score > s + 2 * PawnValueMg)
1406             break;
1407
1408         // This is our magic formula
1409         s += (  weakness * int(RootMoves[0].score - s)
1410               + variance * (rk.rand<unsigned>() % weakness)) / 128;
1411
1412         if (s > max_s)
1413         {
1414             max_s = s;
1415             best = RootMoves[i].pv[0];
1416         }
1417     }
1418     return best;
1419   }
1420
1421
1422   // uci_pv() formats PV information according to the UCI protocol. UCI
1423   // requires that all (if any) unsearched PV lines are sent using a previous
1424   // search score.
1425
1426   string uci_pv(const Position& pos, Depth depth, Value alpha, Value beta) {
1427
1428     std::stringstream ss;
1429     Time::point elapsed = Time::now() - SearchTime + 1;
1430     size_t uciPVSize = std::min((size_t)Options["MultiPV"], RootMoves.size());
1431     int selDepth = 0;
1432
1433     for (size_t i = 0; i < Threads.size(); ++i)
1434         if (Threads[i]->maxPly > selDepth)
1435             selDepth = Threads[i]->maxPly;
1436
1437     for (size_t i = 0; i < uciPVSize; ++i)
1438     {
1439         bool updated = (i <= PVIdx);
1440
1441         if (depth == ONE_PLY && !updated)
1442             continue;
1443
1444         Depth d = updated ? depth : depth - ONE_PLY;
1445         Value v = updated ? RootMoves[i].score : RootMoves[i].prevScore;
1446
1447         bool tb = RootInTB;
1448         if (tb)
1449         {
1450             if (abs(v) >= VALUE_MATE - MAX_PLY)
1451                 tb = false;
1452             else
1453                 v = TBScore;
1454         }
1455
1456         if (ss.rdbuf()->in_avail()) // Not at first line
1457             ss << "\n";
1458
1459         ss << "info depth " << d / ONE_PLY
1460            << " seldepth "  << selDepth
1461            << " multipv "   << i + 1
1462            << " score "     << ((!tb && i == PVIdx) ? UCI::format_value(v, alpha, beta) : UCI::format_value(v))
1463            << " nodes "     << pos.nodes_searched()
1464            << " nps "       << pos.nodes_searched() * 1000 / elapsed
1465            << " tbhits "    << TBHits
1466            << " time "      << elapsed
1467            << " pv";
1468
1469         for (size_t j = 0; j < RootMoves[i].pv.size(); ++j)
1470             ss << " " << UCI::format_move(RootMoves[i].pv[j], pos.is_chess960());
1471     }
1472
1473     return ss.str();
1474   }
1475
1476 } // namespace
1477
1478
1479 /// RootMove::insert_pv_in_tt() is called at the end of a search iteration, and
1480 /// inserts the PV back into the TT. This makes sure the old PV moves are searched
1481 /// first, even if the old TT entries have been overwritten.
1482
1483 void RootMove::insert_pv_in_tt(Position& pos) {
1484
1485   StateInfo state[MAX_PLY], *st = state;
1486   const TTEntry* tte;
1487   size_t idx = 0;
1488
1489   for ( ; idx < pv.size(); ++idx)
1490   {
1491       tte = TT.probe(pos.key());
1492
1493       if (!tte || tte->move() != pv[idx]) // Don't overwrite correct entries
1494           TT.store(pos.key(), VALUE_NONE, BOUND_NONE, DEPTH_NONE, pv[idx], VALUE_NONE);
1495
1496       assert(MoveList<LEGAL>(pos).contains(pv[idx]));
1497
1498       pos.do_move(pv[idx], *st++);
1499   }
1500
1501   while (idx) pos.undo_move(pv[--idx]);
1502 }
1503
1504
1505 /// Thread::idle_loop() is where the thread is parked when it has no work to do
1506
1507 void Thread::idle_loop() {
1508
1509   // Pointer 'this_sp' is not null only if we are called from split(), and not
1510   // at the thread creation. This means we are the split point's master.
1511   SplitPoint* this_sp = splitPointsSize ? activeSplitPoint : NULL;
1512
1513   assert(!this_sp || (this_sp->masterThread == this && searching));
1514
1515   while (!exit)
1516   {
1517       // If this thread has been assigned work, launch a search
1518       while (searching)
1519       {
1520           Threads.mutex.lock();
1521
1522           assert(activeSplitPoint);
1523           SplitPoint* sp = activeSplitPoint;
1524
1525           Threads.mutex.unlock();
1526
1527           Stack stack[MAX_PLY+4], *ss = stack+2; // To allow referencing (ss-2) and (ss+2)
1528           Position pos(*sp->pos, this);
1529
1530           std::memcpy(ss-2, sp->ss-2, 5 * sizeof(Stack));
1531           ss->splitPoint = sp;
1532
1533           sp->mutex.lock();
1534
1535           assert(activePosition == NULL);
1536
1537           activePosition = &pos;
1538
1539           if (sp->nodeType == NonPV)
1540               search<NonPV, true>(pos, ss, sp->alpha, sp->beta, sp->depth, sp->cutNode);
1541
1542           else if (sp->nodeType == PV)
1543               search<PV, true>(pos, ss, sp->alpha, sp->beta, sp->depth, sp->cutNode);
1544
1545           else if (sp->nodeType == Root)
1546               search<Root, true>(pos, ss, sp->alpha, sp->beta, sp->depth, sp->cutNode);
1547
1548           else
1549               assert(false);
1550
1551           assert(searching);
1552
1553           searching = false;
1554           activePosition = NULL;
1555           sp->slavesMask.reset(idx);
1556           sp->allSlavesSearching = false;
1557           sp->nodes += pos.nodes_searched();
1558
1559           // Wake up the master thread so to allow it to return from the idle
1560           // loop in case we are the last slave of the split point.
1561           if (    this != sp->masterThread
1562               &&  sp->slavesMask.none())
1563           {
1564               assert(!sp->masterThread->searching);
1565               sp->masterThread->notify_one();
1566           }
1567
1568           // After releasing the lock we can't access any SplitPoint related data
1569           // in a safe way because it could have been released under our feet by
1570           // the sp master.
1571           sp->mutex.unlock();
1572
1573           // Try to late join to another split point if none of its slaves has
1574           // already finished.
1575           if (Threads.size() > 2)
1576               for (size_t i = 0; i < Threads.size(); ++i)
1577               {
1578                   const int size = Threads[i]->splitPointsSize; // Local copy
1579                   sp = size ? &Threads[i]->splitPoints[size - 1] : NULL;
1580
1581                   if (   sp
1582                       && sp->allSlavesSearching
1583                       && available_to(Threads[i]))
1584                   {
1585                       // Recheck the conditions under lock protection
1586                       Threads.mutex.lock();
1587                       sp->mutex.lock();
1588
1589                       if (   sp->allSlavesSearching
1590                           && available_to(Threads[i]))
1591                       {
1592                            sp->slavesMask.set(idx);
1593                            activeSplitPoint = sp;
1594                            searching = true;
1595                       }
1596
1597                       sp->mutex.unlock();
1598                       Threads.mutex.unlock();
1599
1600                       break; // Just a single attempt
1601                   }
1602               }
1603       }
1604
1605       // Grab the lock to avoid races with Thread::notify_one()
1606       mutex.lock();
1607
1608       // If we are master and all slaves have finished then exit idle_loop
1609       if (this_sp && this_sp->slavesMask.none())
1610       {
1611           assert(!searching);
1612           mutex.unlock();
1613           break;
1614       }
1615
1616       // If we are not searching, wait for a condition to be signaled instead of
1617       // wasting CPU time polling for work.
1618       if (!searching && !exit)
1619           sleepCondition.wait(mutex);
1620
1621       mutex.unlock();
1622   }
1623 }
1624
1625
1626 /// check_time() is called by the timer thread when the timer triggers. It is
1627 /// used to print debug info and, more importantly, to detect when we are out of
1628 /// available time and thus stop the search.
1629
1630 void check_time() {
1631
1632   static Time::point lastInfoTime = Time::now();
1633   Time::point elapsed = Time::now() - SearchTime;
1634
1635   if (Time::now() - lastInfoTime >= 1000)
1636   {
1637       lastInfoTime = Time::now();
1638       dbg_print();
1639   }
1640
1641   // An engine may not stop pondering until told so by the GUI
1642   if (Limits.ponder)
1643       return;
1644
1645   if (Limits.use_time_management())
1646   {
1647       bool stillAtFirstMove =    Signals.firstRootMove
1648                              && !Signals.failedLowAtRoot
1649                              &&  elapsed > TimeMgr.available_time() * 75 / 100;
1650
1651       if (   stillAtFirstMove
1652           || elapsed > TimeMgr.maximum_time() - 2 * TimerThread::Resolution)
1653           Signals.stop = true;
1654   }
1655   else if (Limits.movetime && elapsed >= Limits.movetime)
1656       Signals.stop = true;
1657
1658   else if (Limits.nodes)
1659   {
1660       Threads.mutex.lock();
1661
1662       int64_t nodes = RootPos.nodes_searched();
1663
1664       // Loop across all split points and sum accumulated SplitPoint nodes plus
1665       // all the currently active positions nodes.
1666       for (size_t i = 0; i < Threads.size(); ++i)
1667           for (int j = 0; j < Threads[i]->splitPointsSize; ++j)
1668           {
1669               SplitPoint& sp = Threads[i]->splitPoints[j];
1670
1671               sp.mutex.lock();
1672
1673               nodes += sp.nodes;
1674
1675               for (size_t idx = 0; idx < Threads.size(); ++idx)
1676                   if (sp.slavesMask.test(idx) && Threads[idx]->activePosition)
1677                       nodes += Threads[idx]->activePosition->nodes_searched();
1678
1679               sp.mutex.unlock();
1680           }
1681
1682       Threads.mutex.unlock();
1683
1684       if (nodes >= Limits.nodes)
1685           Signals.stop = true;
1686   }
1687 }