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