]> git.sesse.net Git - stockfish/blob - src/search.cpp
814a96d98cb66abed49d617566001b350d349798
[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   MovesStats Countermoves;
138
139   template <NodeType NT, bool SpNode>
140   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth, bool cutNode);
141
142   template <NodeType NT, bool InCheck>
143   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
144
145   void id_loop(Position& pos);
146   Value value_to_tt(Value v, int ply);
147   Value value_from_tt(Value v, int ply);
148   void update_pv(Move* pv, Move move, Move* childPv);
149   void update_stats(const Position& pos, Stack* ss, Move move, Depth depth, Move* quiets, int quietsCnt);
150
151 } // namespace
152
153
154 /// Search::init() is called during startup to initialize various lookup tables
155
156 void Search::init() {
157
158   const double K[][2] = {{ 0.83, 2.25 }, { 0.50, 3.00 }};
159
160   for (int pv = 0; pv <= 1; ++pv)
161       for (int imp = 0; imp <= 1; ++imp)
162           for (int d = 1; d < 64; ++d)
163               for (int mc = 1; mc < 64; ++mc)
164               {
165                   double r = K[pv][0] + log(d) * log(mc) / K[pv][1];
166
167                   if (r >= 1.5)
168                       Reductions[pv][imp][d][mc] = int(r) * ONE_PLY;
169
170                   // Increase reduction when eval is not improving
171                   if (!pv && !imp && Reductions[pv][imp][d][mc] >= 2 * ONE_PLY)
172                       Reductions[pv][imp][d][mc] += ONE_PLY;
173               }
174
175   for (int d = 0; d < 16; ++d)
176   {
177       FutilityMoveCounts[0][d] = int(2.4 + 0.773 * pow(d + 0.00, 1.8));
178       FutilityMoveCounts[1][d] = int(2.9 + 1.045 * pow(d + 0.49, 1.8));
179   }
180 }
181
182
183 /// Search::reset() clears all search memory, to obtain reproducible search results
184
185 void Search::reset () {
186
187   TT.clear();
188   History.clear();
189   CounterMovesHistory.clear();
190   Countermoves.clear();
191 }
192
193
194 /// Search::perft() is our utility to verify move generation. All the leaf nodes
195 /// up to the given depth are generated and counted and the sum returned.
196 template<bool Root>
197 uint64_t Search::perft(Position& pos, Depth depth) {
198
199   StateInfo st;
200   uint64_t cnt, nodes = 0;
201   CheckInfo ci(pos);
202   const bool leaf = (depth == 2 * ONE_PLY);
203
204   for (const auto& m : MoveList<LEGAL>(pos))
205   {
206       if (Root && depth <= ONE_PLY)
207           cnt = 1, nodes++;
208       else
209       {
210           pos.do_move(m, st, pos.gives_check(m, ci));
211           cnt = leaf ? MoveList<LEGAL>(pos).size() : perft<false>(pos, depth - ONE_PLY);
212           nodes += cnt;
213           pos.undo_move(m);
214       }
215       if (Root)
216           sync_cout << UCI::move(m, pos.is_chess960()) << ": " << cnt << sync_endl;
217   }
218   return nodes;
219 }
220
221 template uint64_t Search::perft<true>(Position& pos, Depth depth);
222
223
224 /// Search::think() is the external interface to Stockfish's search, and is
225 /// called by the main thread when the program receives the UCI 'go' command. It
226 /// searches from RootPos and at the end prints the "bestmove" to output.
227
228 void Search::think() {
229
230   Color us = RootPos.side_to_move();
231   Time.init(Limits, us, RootPos.game_ply(), now());
232
233   int contempt = Options["Contempt"] * PawnValueEg / 100; // From centipawns
234   DrawValue[ us] = VALUE_DRAW - Value(contempt);
235   DrawValue[~us] = VALUE_DRAW + Value(contempt);
236
237   TB::Hits = 0;
238   TB::RootInTB = false;
239   TB::UseRule50 = Options["Syzygy50MoveRule"];
240   TB::ProbeDepth = Options["SyzygyProbeDepth"] * ONE_PLY;
241   TB::Cardinality = Options["SyzygyProbeLimit"];
242
243   // Skip TB probing when no TB found: !TBLargest -> !TB::Cardinality
244   if (TB::Cardinality > TB::MaxCardinality)
245   {
246       TB::Cardinality = TB::MaxCardinality;
247       TB::ProbeDepth = DEPTH_ZERO;
248   }
249
250   if (RootMoves.empty())
251   {
252       RootMoves.push_back(RootMove(MOVE_NONE));
253       sync_cout << "info depth 0 score "
254                 << UCI::value(RootPos.checkers() ? -VALUE_MATE : VALUE_DRAW)
255                 << sync_endl;
256   }
257   else
258   {
259       if (TB::Cardinality >=  RootPos.count<ALL_PIECES>(WHITE)
260                             + RootPos.count<ALL_PIECES>(BLACK))
261       {
262           // If the current root position is in the tablebases then RootMoves
263           // contains only moves that preserve the draw or win.
264           TB::RootInTB = Tablebases::root_probe(RootPos, RootMoves, TB::Score);
265
266           if (TB::RootInTB)
267               TB::Cardinality = 0; // Do not probe tablebases during the search
268
269           else // If DTZ tables are missing, use WDL tables as a fallback
270           {
271               // Filter out moves that do not preserve a draw or win
272               TB::RootInTB = Tablebases::root_probe_wdl(RootPos, RootMoves, TB::Score);
273
274               // Only probe during search if winning
275               if (TB::Score <= VALUE_DRAW)
276                   TB::Cardinality = 0;
277           }
278
279           if (TB::RootInTB)
280           {
281               TB::Hits = RootMoves.size();
282
283               if (!TB::UseRule50)
284                   TB::Score =  TB::Score > VALUE_DRAW ?  VALUE_MATE - MAX_PLY - 1
285                              : TB::Score < VALUE_DRAW ? -VALUE_MATE + MAX_PLY + 1
286                                                       :  VALUE_DRAW;
287           }
288       }
289
290       for (Thread* th : Threads)
291       {
292           th->maxPly = 0;
293           th->notify_one(); // Wake up all the threads
294       }
295
296       Threads.timer->run = true;
297       Threads.timer->notify_one(); // Start the recurring timer
298
299       id_loop(RootPos); // Let's start searching !
300
301       Threads.timer->run = false;
302   }
303
304   // When playing in 'nodes as time' mode, subtract the searched nodes from
305   // the available ones before to exit.
306   if (Limits.npmsec)
307       Time.availableNodes += Limits.inc[us] - RootPos.nodes_searched();
308
309   // When we reach the maximum depth, we can arrive here without a raise of
310   // Signals.stop. However, if we are pondering or in an infinite search,
311   // the UCI protocol states that we shouldn't print the best move before the
312   // GUI sends a "stop" or "ponderhit" command. We therefore simply wait here
313   // until the GUI sends one of those commands (which also raises Signals.stop).
314   if (!Signals.stop && (Limits.ponder || Limits.infinite))
315   {
316       Signals.stopOnPonderhit = true;
317       RootPos.this_thread()->wait_for(Signals.stop);
318   }
319
320   sync_cout << "bestmove " << UCI::move(RootMoves[0].pv[0], RootPos.is_chess960());
321
322   if (RootMoves[0].pv.size() > 1 || RootMoves[0].extract_ponder_from_tt(RootPos))
323       std::cout << " ponder " << UCI::move(RootMoves[0].pv[1], RootPos.is_chess960());
324
325   std::cout << sync_endl;
326 }
327
328
329 namespace {
330
331   // id_loop() is the main iterative deepening loop. It calls search() repeatedly
332   // with increasing depth until the allocated thinking time has been consumed,
333   // user stops the search, or the maximum search depth is reached.
334
335   void id_loop(Position& pos) {
336
337     Stack stack[MAX_PLY+4], *ss = stack+2; // To allow referencing (ss-2) and (ss+2)
338     Depth depth;
339     Value bestValue, alpha, beta, delta;
340
341     Move easyMove = EasyMove.get(pos.key());
342     EasyMove.clear();
343
344     std::memset(ss-2, 0, 5 * sizeof(Stack));
345
346     depth = DEPTH_ZERO;
347     BestMoveChanges = 0;
348     bestValue = delta = alpha = -VALUE_INFINITE;
349     beta = VALUE_INFINITE;
350
351     TT.new_search();
352
353     size_t multiPV = Options["MultiPV"];
354     Skill skill(Options["Skill Level"]);
355
356     // When playing with strength handicap enable MultiPV search that we will
357     // use behind the scenes to retrieve a set of possible moves.
358     if (skill.enabled())
359         multiPV = std::max(multiPV, (size_t)4);
360
361     multiPV = std::min(multiPV, RootMoves.size());
362
363     // Iterative deepening loop until requested to stop or target depth reached
364     while (++depth < DEPTH_MAX && !Signals.stop && (!Limits.depth || depth <= Limits.depth))
365     {
366         // Age out PV variability metric
367         BestMoveChanges *= 0.5;
368
369         // Save the last iteration's scores before first PV line is searched and
370         // all the move scores except the (new) PV are set to -VALUE_INFINITE.
371         for (RootMove& rm : RootMoves)
372             rm.previousScore = rm.score;
373
374         // MultiPV loop. We perform a full root search for each PV line
375         for (PVIdx = 0; PVIdx < multiPV && !Signals.stop; ++PVIdx)
376         {
377             // Reset aspiration window starting size
378             if (depth >= 5 * ONE_PLY)
379             {
380                 delta = Value(16);
381                 alpha = std::max(RootMoves[PVIdx].previousScore - delta,-VALUE_INFINITE);
382                 beta  = std::min(RootMoves[PVIdx].previousScore + delta, VALUE_INFINITE);
383             }
384
385             // Start with a small aspiration window and, in the case of a fail
386             // high/low, re-search with a bigger window until we're not failing
387             // high/low anymore.
388             while (true)
389             {
390                 bestValue = search<Root, false>(pos, ss, alpha, beta, depth, false);
391
392                 // Bring the best move to the front. It is critical that sorting
393                 // is done with a stable algorithm because all the values but the
394                 // first and eventually the new best one are set to -VALUE_INFINITE
395                 // and we want to keep the same order for all the moves except the
396                 // new PV that goes to the front. Note that in case of MultiPV
397                 // search the already searched PV lines are preserved.
398                 std::stable_sort(RootMoves.begin() + PVIdx, RootMoves.end());
399
400                 // Write PV back to transposition table in case the relevant
401                 // entries have been overwritten during the search.
402                 for (size_t i = 0; i <= PVIdx; ++i)
403                     RootMoves[i].insert_pv_in_tt(pos);
404
405                 // If search has been stopped break immediately. Sorting and
406                 // writing PV back to TT is safe because RootMoves is still
407                 // valid, although it refers to previous iteration.
408                 if (Signals.stop)
409                     break;
410
411                 // When failing high/low give some update (without cluttering
412                 // the UI) before a re-search.
413                 if (   multiPV == 1
414                     && (bestValue <= alpha || bestValue >= beta)
415                     && Time.elapsed() > 3000)
416                     sync_cout << UCI::pv(pos, depth, alpha, beta) << sync_endl;
417
418                 // In case of failing low/high increase aspiration window and
419                 // re-search, otherwise exit the loop.
420                 if (bestValue <= alpha)
421                 {
422                     beta = (alpha + beta) / 2;
423                     alpha = std::max(bestValue - delta, -VALUE_INFINITE);
424
425                     Signals.failedLowAtRoot = true;
426                     Signals.stopOnPonderhit = false;
427                 }
428                 else if (bestValue >= beta)
429                 {
430                     alpha = (alpha + beta) / 2;
431                     beta = std::min(bestValue + delta, VALUE_INFINITE);
432                 }
433                 else
434                     break;
435
436                 delta += delta / 2;
437
438                 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
439             }
440
441             // Sort the PV lines searched so far and update the GUI
442             std::stable_sort(RootMoves.begin(), RootMoves.begin() + PVIdx + 1);
443
444             if (Signals.stop)
445                 sync_cout << "info nodes " << RootPos.nodes_searched()
446                           << " time " << Time.elapsed() << sync_endl;
447
448             else if (PVIdx + 1 == multiPV || Time.elapsed() > 3000)
449                 sync_cout << UCI::pv(pos, depth, alpha, beta) << sync_endl;
450         }
451
452         // If skill level is enabled and time is up, pick a sub-optimal best move
453         if (skill.enabled() && skill.time_to_pick(depth))
454             skill.pick_best(multiPV);
455
456         // Have we found a "mate in x"?
457         if (   Limits.mate
458             && bestValue >= VALUE_MATE_IN_MAX_PLY
459             && VALUE_MATE - bestValue <= 2 * Limits.mate)
460             Signals.stop = true;
461
462         // Do we have time for the next iteration? Can we stop searching now?
463         if (Limits.use_time_management())
464         {
465             if (!Signals.stop && !Signals.stopOnPonderhit)
466             {
467                 // Take some extra time if the best move has changed
468                 if (depth > 4 * ONE_PLY && multiPV == 1)
469                     Time.pv_instability(BestMoveChanges);
470
471                 // Stop the search if only one legal move is available or all
472                 // of the available time has been used or we matched an easyMove
473                 // from the previous search and just did a fast verification.
474                 if (   RootMoves.size() == 1
475                     || Time.elapsed() > Time.available()
476                     || (   RootMoves[0].pv[0] == easyMove
477                         && BestMoveChanges < 0.03
478                         && Time.elapsed() > Time.available() / 10))
479                 {
480                     // If we are allowed to ponder do not stop the search now but
481                     // keep pondering until the GUI sends "ponderhit" or "stop".
482                     if (Limits.ponder)
483                         Signals.stopOnPonderhit = true;
484                     else
485                         Signals.stop = true;
486                 }
487             }
488
489             if (RootMoves[0].pv.size() >= 3)
490                 EasyMove.update(pos, RootMoves[0].pv);
491             else
492                 EasyMove.clear();
493         }
494     }
495
496     // Clear any candidate easy move that wasn't stable for the last search
497     // iterations; the second condition prevents consecutive fast moves.
498     if (EasyMove.stableCnt < 6 || Time.elapsed() < Time.available())
499         EasyMove.clear();
500
501     // If skill level is enabled, swap best PV line with the sub-optimal one
502     if (skill.enabled())
503         std::swap(RootMoves[0], *std::find(RootMoves.begin(),
504                   RootMoves.end(), skill.best_move(multiPV)));
505   }
506
507
508   // search<>() is the main search function for both PV and non-PV nodes and for
509   // normal and SplitPoint nodes. When called just after a split point the search
510   // is simpler because we have already probed the hash table, done a null move
511   // search, and searched the first move before splitting, so we don't have to
512   // repeat all this work again. We also don't need to store anything to the hash
513   // table here: This is taken care of after we return from the split point.
514
515   template <NodeType NT, bool SpNode>
516   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth, bool cutNode) {
517
518     const bool RootNode = NT == Root;
519     const bool PvNode   = NT == PV || NT == Root;
520
521     assert(-VALUE_INFINITE <= alpha && alpha < beta && beta <= VALUE_INFINITE);
522     assert(PvNode || (alpha == beta - 1));
523     assert(depth > DEPTH_ZERO);
524
525     Move pv[MAX_PLY+1], quietsSearched[64];
526     StateInfo st;
527     TTEntry* tte;
528     SplitPoint* splitPoint;
529     Key posKey;
530     Move ttMove, move, excludedMove, bestMove;
531     Depth extension, newDepth, predictedDepth;
532     Value bestValue, value, ttValue, eval, nullValue, futilityValue;
533     bool ttHit, inCheck, givesCheck, singularExtensionNode, improving;
534     bool captureOrPromotion, dangerous, doFullDepthSearch;
535     int moveCount, quietCount;
536
537     // Step 1. Initialize node
538     Thread* thisThread = pos.this_thread();
539     inCheck = pos.checkers();
540
541     if (SpNode)
542     {
543         splitPoint = ss->splitPoint;
544         bestMove   = splitPoint->bestMove;
545         bestValue  = splitPoint->bestValue;
546         tte = nullptr;
547         ttHit = false;
548         ttMove = excludedMove = MOVE_NONE;
549         ttValue = VALUE_NONE;
550
551         assert(splitPoint->bestValue > -VALUE_INFINITE && splitPoint->moveCount > 0);
552
553         goto moves_loop;
554     }
555
556     moveCount = quietCount = 0;
557     bestValue = -VALUE_INFINITE;
558     ss->ply = (ss-1)->ply + 1;
559
560     // Used to send selDepth info to GUI
561     if (PvNode && thisThread->maxPly < ss->ply)
562         thisThread->maxPly = ss->ply;
563
564     if (!RootNode)
565     {
566         // Step 2. Check for aborted search and immediate draw
567         if (Signals.stop || pos.is_draw() || ss->ply >= MAX_PLY)
568             return ss->ply >= MAX_PLY && !inCheck ? evaluate(pos) : DrawValue[pos.side_to_move()];
569
570         // Step 3. Mate distance pruning. Even if we mate at the next move our score
571         // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
572         // a shorter mate was found upward in the tree then there is no need to search
573         // because we will never beat the current alpha. Same logic but with reversed
574         // signs applies also in the opposite condition of being mated instead of giving
575         // mate. In this case return a fail-high score.
576         alpha = std::max(mated_in(ss->ply), alpha);
577         beta = std::min(mate_in(ss->ply+1), beta);
578         if (alpha >= beta)
579             return alpha;
580     }
581
582     assert(0 <= ss->ply && ss->ply < MAX_PLY);
583
584     ss->currentMove = ss->ttMove = (ss+1)->excludedMove = bestMove = MOVE_NONE;
585     (ss+1)->skipEarlyPruning = false; (ss+1)->reduction = DEPTH_ZERO;
586     (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
587
588     // Step 4. Transposition table lookup
589     // We don't want the score of a partial search to overwrite a previous full search
590     // TT value, so we use a different position key in case of an excluded move.
591     excludedMove = ss->excludedMove;
592     posKey = excludedMove ? pos.exclusion_key() : pos.key();
593     tte = TT.probe(posKey, ttHit);
594     ss->ttMove = ttMove = RootNode ? RootMoves[PVIdx].pv[0] : ttHit ? tte->move() : MOVE_NONE;
595     ttValue = ttHit ? value_from_tt(tte->value(), ss->ply) : VALUE_NONE;
596
597     // At non-PV nodes we check for a fail high/low. We don't prune at PV nodes
598     if (  !PvNode
599         && ttHit
600         && tte->depth() >= depth
601         && ttValue != VALUE_NONE // Only in case of TT access race
602         && (ttValue >= beta ? (tte->bound() & BOUND_LOWER)
603                             : (tte->bound() & BOUND_UPPER)))
604     {
605         ss->currentMove = ttMove; // Can be MOVE_NONE
606
607         // If ttMove is quiet, update killers, history, counter move on TT hit
608         if (ttValue >= beta && ttMove && !pos.capture_or_promotion(ttMove))
609             update_stats(pos, ss, ttMove, depth, nullptr, 0);
610
611         return ttValue;
612     }
613
614     // Step 4a. Tablebase probe
615     if (!RootNode && TB::Cardinality)
616     {
617         int piecesCnt = pos.count<ALL_PIECES>(WHITE) + pos.count<ALL_PIECES>(BLACK);
618
619         if (    piecesCnt <= TB::Cardinality
620             && (piecesCnt <  TB::Cardinality || depth >= TB::ProbeDepth)
621             &&  pos.rule50_count() == 0)
622         {
623             int found, v = Tablebases::probe_wdl(pos, &found);
624
625             if (found)
626             {
627                 TB::Hits++;
628
629                 int drawScore = TB::UseRule50 ? 1 : 0;
630
631                 value =  v < -drawScore ? -VALUE_MATE + MAX_PLY + ss->ply
632                        : v >  drawScore ?  VALUE_MATE - MAX_PLY - ss->ply
633                                         :  VALUE_DRAW + 2 * v * drawScore;
634
635                 tte->save(posKey, value_to_tt(value, ss->ply), BOUND_EXACT,
636                           std::min(DEPTH_MAX - ONE_PLY, depth + 6 * ONE_PLY),
637                           MOVE_NONE, VALUE_NONE, TT.generation());
638
639                 return value;
640             }
641         }
642     }
643
644     // Step 5. Evaluate the position statically
645     if (inCheck)
646     {
647         ss->staticEval = eval = VALUE_NONE;
648         goto moves_loop;
649     }
650
651     else if (ttHit)
652     {
653         // Never assume anything on values stored in TT
654         if ((ss->staticEval = eval = tte->eval()) == VALUE_NONE)
655             eval = ss->staticEval = evaluate(pos);
656
657         // Can ttValue be used as a better position evaluation?
658         if (ttValue != VALUE_NONE)
659             if (tte->bound() & (ttValue > eval ? BOUND_LOWER : BOUND_UPPER))
660                 eval = ttValue;
661     }
662     else
663     {
664         eval = ss->staticEval =
665         (ss-1)->currentMove != MOVE_NULL ? evaluate(pos) : -(ss-1)->staticEval + 2 * Eval::Tempo;
666
667         tte->save(posKey, VALUE_NONE, BOUND_NONE, DEPTH_NONE, MOVE_NONE, ss->staticEval, TT.generation());
668     }
669
670     if (ss->skipEarlyPruning)
671         goto moves_loop;
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.checkSquares[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) + 256;
906
907               if (futilityValue <= alpha)
908               {
909                   bestValue = std::max(bestValue, futilityValue);
910
911                   if (SpNode)
912                   {
913                       splitPoint->spinlock.acquire();
914                       if (bestValue > splitPoint->bestValue)
915                           splitPoint->bestValue = bestValue;
916                   }
917                   continue;
918               }
919           }
920
921           // Prune moves with negative SEE at low depths
922           if (predictedDepth < 4 * ONE_PLY && pos.see_sign(move) < VALUE_ZERO)
923           {
924               if (SpNode)
925                   splitPoint->spinlock.acquire();
926
927               continue;
928           }
929       }
930
931       // Speculative prefetch as early as possible
932       prefetch(TT.first_entry(pos.key_after(move)));
933
934       // Check for legality just before making the move
935       if (!RootNode && !SpNode && !pos.legal(move, ci.pinned))
936       {
937           moveCount--;
938           continue;
939       }
940
941       ss->currentMove = move;
942
943       // Step 14. Make the move
944       pos.do_move(move, st, givesCheck);
945
946       // Step 15. Reduced depth search (LMR). If the move fails high it will be
947       // re-searched at full depth.
948       if (    depth >= 3 * ONE_PLY
949           &&  moveCount > 1
950           && !captureOrPromotion
951           &&  move != ss->killers[0]
952           &&  move != ss->killers[1])
953       {
954           ss->reduction = reduction<PvNode>(improving, depth, moveCount);
955
956           if (   (!PvNode && cutNode)
957               || (   History[pos.piece_on(to_sq(move))][to_sq(move)] < VALUE_ZERO
958                   && CounterMovesHistory[pos.piece_on(prevMoveSq)][prevMoveSq]
959                                         [pos.piece_on(to_sq(move))][to_sq(move)] <= VALUE_ZERO))
960               ss->reduction += ONE_PLY;
961
962           if (move == countermove)
963               ss->reduction = std::max(DEPTH_ZERO, ss->reduction - ONE_PLY);
964
965           // Decrease reduction for moves that escape a capture
966           if (   ss->reduction
967               && type_of(move) == NORMAL
968               && type_of(pos.piece_on(to_sq(move))) != PAWN
969               && pos.see(make_move(to_sq(move), from_sq(move))) < VALUE_ZERO)
970               ss->reduction = std::max(DEPTH_ZERO, ss->reduction - ONE_PLY);
971
972           Depth d = std::max(newDepth - ss->reduction, ONE_PLY);
973           if (SpNode)
974               alpha = splitPoint->alpha;
975
976           value = -search<NonPV, false>(pos, ss+1, -(alpha+1), -alpha, d, true);
977
978           // Re-search at intermediate depth if reduction is very high
979           if (value > alpha && ss->reduction >= 4 * ONE_PLY)
980           {
981               Depth d2 = std::max(newDepth - 2 * ONE_PLY, ONE_PLY);
982               value = -search<NonPV, false>(pos, ss+1, -(alpha+1), -alpha, d2, true);
983           }
984
985           doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
986           ss->reduction = DEPTH_ZERO;
987       }
988       else
989           doFullDepthSearch = !PvNode || moveCount > 1;
990
991       // Step 16. Full depth search, when LMR is skipped or fails high
992       if (doFullDepthSearch)
993       {
994           if (SpNode)
995               alpha = splitPoint->alpha;
996
997           value = newDepth <   ONE_PLY ?
998                             givesCheck ? -qsearch<NonPV,  true>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
999                                        : -qsearch<NonPV, false>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
1000                                        : - search<NonPV, false>(pos, ss+1, -(alpha+1), -alpha, newDepth, !cutNode);
1001       }
1002
1003       // For PV nodes only, do a full PV search on the first move or after a fail
1004       // high (in the latter case search only if value < beta), otherwise let the
1005       // parent node fail low with value <= alpha and to try another move.
1006       if (PvNode && (moveCount == 1 || (value > alpha && (RootNode || value < beta))))
1007       {
1008           (ss+1)->pv = pv;
1009           (ss+1)->pv[0] = MOVE_NONE;
1010
1011           value = newDepth <   ONE_PLY ?
1012                             givesCheck ? -qsearch<PV,  true>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
1013                                        : -qsearch<PV, false>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
1014                                        : - search<PV, false>(pos, ss+1, -beta, -alpha, newDepth, false);
1015       }
1016
1017       // Step 17. Undo move
1018       pos.undo_move(move);
1019
1020       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1021
1022       // Step 18. Check for new best move
1023       if (SpNode)
1024       {
1025           splitPoint->spinlock.acquire();
1026           bestValue = splitPoint->bestValue;
1027           alpha = splitPoint->alpha;
1028       }
1029
1030       // Finished searching the move. If a stop or a cutoff occurred, the return
1031       // value of the search cannot be trusted, and we return immediately without
1032       // updating best move, PV and TT.
1033       if (Signals.stop || thisThread->cutoff_occurred())
1034           return VALUE_ZERO;
1035
1036       if (RootNode)
1037       {
1038           RootMove& rm = *std::find(RootMoves.begin(), RootMoves.end(), move);
1039
1040           // PV move or new best move ?
1041           if (moveCount == 1 || value > alpha)
1042           {
1043               rm.score = value;
1044               rm.pv.resize(1);
1045
1046               assert((ss+1)->pv);
1047
1048               for (Move* m = (ss+1)->pv; *m != MOVE_NONE; ++m)
1049                   rm.pv.push_back(*m);
1050
1051               // We record how often the best move has been changed in each
1052               // iteration. This information is used for time management: When
1053               // the best move changes frequently, we allocate some more time.
1054               if (moveCount > 1)
1055                   ++BestMoveChanges;
1056           }
1057           else
1058               // All other moves but the PV are set to the lowest value: this is
1059               // not a problem when sorting because the sort is stable and the
1060               // move position in the list is preserved - just the PV is pushed up.
1061               rm.score = -VALUE_INFINITE;
1062       }
1063
1064       if (value > bestValue)
1065       {
1066           bestValue = SpNode ? splitPoint->bestValue = value : value;
1067
1068           if (value > alpha)
1069           {
1070               // If there is an easy move for this position, clear it if unstable
1071               if (    PvNode
1072                   &&  EasyMove.get(pos.key())
1073                   && (move != EasyMove.get(pos.key()) || moveCount > 1))
1074                   EasyMove.clear();
1075
1076               bestMove = SpNode ? splitPoint->bestMove = move : move;
1077
1078               if (PvNode && !RootNode) // Update pv even in fail-high case
1079                   update_pv(SpNode ? splitPoint->ss->pv : ss->pv, move, (ss+1)->pv);
1080
1081               if (PvNode && value < beta) // Update alpha! Always alpha < beta
1082                   alpha = SpNode ? splitPoint->alpha = value : value;
1083               else
1084               {
1085                   assert(value >= beta); // Fail high
1086
1087                   if (SpNode)
1088                       splitPoint->cutoff = true;
1089
1090                   break;
1091               }
1092           }
1093       }
1094
1095       if (!SpNode && !captureOrPromotion && move != bestMove && quietCount < 64)
1096           quietsSearched[quietCount++] = move;
1097
1098       // Step 19. Check for splitting the search
1099       if (   !SpNode
1100           &&  Threads.size() >= 2
1101           &&  depth >= Threads.minimumSplitDepth
1102           &&  (   !thisThread->activeSplitPoint
1103                || !thisThread->activeSplitPoint->allSlavesSearching
1104                || (   Threads.size() > MAX_SLAVES_PER_SPLITPOINT
1105                    && thisThread->activeSplitPoint->slavesMask.count() == MAX_SLAVES_PER_SPLITPOINT))
1106           &&  thisThread->splitPointsSize < MAX_SPLITPOINTS_PER_THREAD)
1107       {
1108           assert(bestValue > -VALUE_INFINITE && bestValue < beta);
1109
1110           thisThread->split(pos, ss, alpha, beta, &bestValue, &bestMove,
1111                             depth, moveCount, &mp, NT, cutNode);
1112
1113           if (Signals.stop || thisThread->cutoff_occurred())
1114               return VALUE_ZERO;
1115
1116           if (bestValue >= beta)
1117               break;
1118       }
1119     }
1120
1121     if (SpNode)
1122         return bestValue;
1123
1124     // Following condition would detect a stop or a cutoff set only after move
1125     // loop has been completed. But in this case bestValue is valid because we
1126     // have fully searched our subtree, and we can anyhow save the result in TT.
1127     /*
1128        if (Signals.stop || thisThread->cutoff_occurred())
1129         return VALUE_DRAW;
1130     */
1131
1132     // Step 20. Check for mate and stalemate
1133     // All legal moves have been searched and if there are no legal moves, it
1134     // must be mate or stalemate. If we are in a singular extension search then
1135     // return a fail low score.
1136     if (!moveCount)
1137         bestValue = excludedMove ? alpha
1138                    :     inCheck ? mated_in(ss->ply) : DrawValue[pos.side_to_move()];
1139
1140     // Quiet best move: update killers, history and countermoves
1141     else if (bestMove && !pos.capture_or_promotion(bestMove))
1142         update_stats(pos, ss, bestMove, depth, quietsSearched, quietCount);
1143
1144     tte->save(posKey, value_to_tt(bestValue, ss->ply),
1145               bestValue >= beta ? BOUND_LOWER :
1146               PvNode && bestMove ? BOUND_EXACT : BOUND_UPPER,
1147               depth, bestMove, ss->staticEval, TT.generation());
1148
1149     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1150
1151     return bestValue;
1152   }
1153
1154
1155   // qsearch() is the quiescence search function, which is called by the main
1156   // search function when the remaining depth is zero (or, to be more precise,
1157   // less than ONE_PLY).
1158
1159   template <NodeType NT, bool InCheck>
1160   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1161
1162     const bool PvNode = NT == PV;
1163
1164     assert(NT == PV || NT == NonPV);
1165     assert(InCheck == !!pos.checkers());
1166     assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1167     assert(PvNode || (alpha == beta - 1));
1168     assert(depth <= DEPTH_ZERO);
1169
1170     Move pv[MAX_PLY+1];
1171     StateInfo st;
1172     TTEntry* tte;
1173     Key posKey;
1174     Move ttMove, move, bestMove;
1175     Value bestValue, value, ttValue, futilityValue, futilityBase, oldAlpha;
1176     bool ttHit, givesCheck, evasionPrunable;
1177     Depth ttDepth;
1178
1179     if (PvNode)
1180     {
1181         oldAlpha = alpha; // To flag BOUND_EXACT when eval above alpha and no available moves
1182         (ss+1)->pv = pv;
1183         ss->pv[0] = MOVE_NONE;
1184     }
1185
1186     ss->currentMove = bestMove = MOVE_NONE;
1187     ss->ply = (ss-1)->ply + 1;
1188
1189     // Check for an instant draw or if the maximum ply has been reached
1190     if (pos.is_draw() || ss->ply >= MAX_PLY)
1191         return ss->ply >= MAX_PLY && !InCheck ? evaluate(pos) : DrawValue[pos.side_to_move()];
1192
1193     assert(0 <= ss->ply && ss->ply < MAX_PLY);
1194
1195     // Decide whether or not to include checks: this fixes also the type of
1196     // TT entry depth that we are going to use. Note that in qsearch we use
1197     // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1198     ttDepth = InCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS
1199                                                   : DEPTH_QS_NO_CHECKS;
1200
1201     // Transposition table lookup
1202     posKey = pos.key();
1203     tte = TT.probe(posKey, ttHit);
1204     ttMove = ttHit ? tte->move() : MOVE_NONE;
1205     ttValue = ttHit ? value_from_tt(tte->value(), ss->ply) : VALUE_NONE;
1206
1207     if (  !PvNode
1208         && ttHit
1209         && tte->depth() >= ttDepth
1210         && ttValue != VALUE_NONE // Only in case of TT access race
1211         && (ttValue >= beta ? (tte->bound() &  BOUND_LOWER)
1212                             : (tte->bound() &  BOUND_UPPER)))
1213     {
1214         ss->currentMove = ttMove; // Can be MOVE_NONE
1215         return ttValue;
1216     }
1217
1218     // Evaluate the position statically
1219     if (InCheck)
1220     {
1221         ss->staticEval = VALUE_NONE;
1222         bestValue = futilityBase = -VALUE_INFINITE;
1223     }
1224     else
1225     {
1226         if (ttHit)
1227         {
1228             // Never assume anything on values stored in TT
1229             if ((ss->staticEval = bestValue = tte->eval()) == VALUE_NONE)
1230                 ss->staticEval = bestValue = evaluate(pos);
1231
1232             // Can ttValue be used as a better position evaluation?
1233             if (ttValue != VALUE_NONE)
1234                 if (tte->bound() & (ttValue > bestValue ? BOUND_LOWER : BOUND_UPPER))
1235                     bestValue = ttValue;
1236         }
1237         else
1238             ss->staticEval = bestValue =
1239             (ss-1)->currentMove != MOVE_NULL ? evaluate(pos) : -(ss-1)->staticEval + 2 * Eval::Tempo;
1240
1241         // Stand pat. Return immediately if static value is at least beta
1242         if (bestValue >= beta)
1243         {
1244             if (!ttHit)
1245                 tte->save(pos.key(), value_to_tt(bestValue, ss->ply), BOUND_LOWER,
1246                           DEPTH_NONE, MOVE_NONE, ss->staticEval, TT.generation());
1247
1248             return bestValue;
1249         }
1250
1251         if (PvNode && bestValue > alpha)
1252             alpha = bestValue;
1253
1254         futilityBase = bestValue + 128;
1255     }
1256
1257     // Initialize a MovePicker object for the current position, and prepare
1258     // to search the moves. Because the depth is <= 0 here, only captures,
1259     // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1260     // be generated.
1261     MovePicker mp(pos, ttMove, depth, History, CounterMovesHistory, to_sq((ss-1)->currentMove));
1262     CheckInfo ci(pos);
1263
1264     // Loop through the moves until no moves remain or a beta cutoff occurs
1265     while ((move = mp.next_move<false>()) != MOVE_NONE)
1266     {
1267       assert(is_ok(move));
1268
1269       givesCheck =  type_of(move) == NORMAL && !ci.dcCandidates
1270                   ? ci.checkSquares[type_of(pos.piece_on(from_sq(move)))] & to_sq(move)
1271                   : pos.gives_check(move, ci);
1272
1273       // Futility pruning
1274       if (   !InCheck
1275           && !givesCheck
1276           &&  futilityBase > -VALUE_KNOWN_WIN
1277           && !pos.advanced_pawn_push(move))
1278       {
1279           assert(type_of(move) != ENPASSANT); // Due to !pos.advanced_pawn_push
1280
1281           futilityValue = futilityBase + PieceValue[EG][pos.piece_on(to_sq(move))];
1282
1283           if (futilityValue <= alpha)
1284           {
1285               bestValue = std::max(bestValue, futilityValue);
1286               continue;
1287           }
1288
1289           if (futilityBase <= alpha && pos.see(move) <= VALUE_ZERO)
1290           {
1291               bestValue = std::max(bestValue, futilityBase);
1292               continue;
1293           }
1294       }
1295
1296       // Detect non-capture evasions that are candidates to be pruned
1297       evasionPrunable =    InCheck
1298                        &&  bestValue > VALUE_MATED_IN_MAX_PLY
1299                        && !pos.capture(move);
1300
1301       // Don't search moves with negative SEE values
1302       if (  (!InCheck || evasionPrunable)
1303           &&  type_of(move) != PROMOTION
1304           &&  pos.see_sign(move) < VALUE_ZERO)
1305           continue;
1306
1307       // Speculative prefetch as early as possible
1308       prefetch(TT.first_entry(pos.key_after(move)));
1309
1310       // Check for legality just before making the move
1311       if (!pos.legal(move, ci.pinned))
1312           continue;
1313
1314       ss->currentMove = move;
1315
1316       // Make and search the move
1317       pos.do_move(move, st, givesCheck);
1318       value = givesCheck ? -qsearch<NT,  true>(pos, ss+1, -beta, -alpha, depth - ONE_PLY)
1319                          : -qsearch<NT, false>(pos, ss+1, -beta, -alpha, depth - ONE_PLY);
1320       pos.undo_move(move);
1321
1322       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1323
1324       // Check for new best move
1325       if (value > bestValue)
1326       {
1327           bestValue = value;
1328
1329           if (value > alpha)
1330           {
1331               if (PvNode) // Update pv even in fail-high case
1332                   update_pv(ss->pv, move, (ss+1)->pv);
1333
1334               if (PvNode && value < beta) // Update alpha here! Always alpha < beta
1335               {
1336                   alpha = value;
1337                   bestMove = move;
1338               }
1339               else // Fail high
1340               {
1341                   tte->save(posKey, value_to_tt(value, ss->ply), BOUND_LOWER,
1342                             ttDepth, move, ss->staticEval, TT.generation());
1343
1344                   return value;
1345               }
1346           }
1347        }
1348     }
1349
1350     // All legal moves have been searched. A special case: If we're in check
1351     // and no legal moves were found, it is checkmate.
1352     if (InCheck && bestValue == -VALUE_INFINITE)
1353         return mated_in(ss->ply); // Plies to mate from the root
1354
1355     tte->save(posKey, value_to_tt(bestValue, ss->ply),
1356               PvNode && bestValue > oldAlpha ? BOUND_EXACT : BOUND_UPPER,
1357               ttDepth, bestMove, ss->staticEval, TT.generation());
1358
1359     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1360
1361     return bestValue;
1362   }
1363
1364
1365   // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1366   // "plies to mate from the current position". Non-mate scores are unchanged.
1367   // The function is called before storing a value in the transposition table.
1368
1369   Value value_to_tt(Value v, int ply) {
1370
1371     assert(v != VALUE_NONE);
1372
1373     return  v >= VALUE_MATE_IN_MAX_PLY  ? v + ply
1374           : v <= VALUE_MATED_IN_MAX_PLY ? v - ply : v;
1375   }
1376
1377
1378   // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
1379   // from the transposition table (which refers to the plies to mate/be mated
1380   // from current position) to "plies to mate/be mated from the root".
1381
1382   Value value_from_tt(Value v, int ply) {
1383
1384     return  v == VALUE_NONE             ? VALUE_NONE
1385           : v >= VALUE_MATE_IN_MAX_PLY  ? v - ply
1386           : v <= VALUE_MATED_IN_MAX_PLY ? v + ply : v;
1387   }
1388
1389
1390   // update_pv() adds current move and appends child pv[]
1391
1392   void update_pv(Move* pv, Move move, Move* childPv) {
1393
1394     for (*pv++ = move; childPv && *childPv != MOVE_NONE; )
1395         *pv++ = *childPv++;
1396     *pv = MOVE_NONE;
1397   }
1398
1399
1400   // update_stats() updates killers, history, countermove history and
1401   // countermoves stats for a quiet best move.
1402
1403   void update_stats(const Position& pos, Stack* ss, Move move,
1404                     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 }