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