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