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