]> git.sesse.net Git - stockfish/blob - src/search.cpp
cf98ca35af3878dbfd5043da2446970236c1157f
[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-2012 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>
24 #include <iostream>
25 #include <sstream>
26
27 #include "book.h"
28 #include "evaluate.h"
29 #include "history.h"
30 #include "movegen.h"
31 #include "movepick.h"
32 #include "notation.h"
33 #include "search.h"
34 #include "timeman.h"
35 #include "thread.h"
36 #include "tt.h"
37 #include "ucioption.h"
38
39 namespace Search {
40
41   volatile SignalsType Signals;
42   LimitsType Limits;
43   std::vector<RootMove> RootMoves;
44   Position RootPosition;
45   Time::point SearchTime;
46   StateStackPtr SetupStates;
47 }
48
49 using std::string;
50 using Eval::evaluate;
51 using namespace Search;
52
53 namespace {
54
55   // Set to true to force running with one thread. Used for debugging
56   const bool FakeSplit = false;
57
58   // This is the minimum interval in msec between two check_time() calls
59   const int TimerResolution = 5;
60
61   // Different node types, used as template parameter
62   enum NodeType { Root, PV, NonPV, SplitPointRoot, SplitPointPV, SplitPointNonPV };
63
64   // Lookup table to check if a Piece is a slider and its access function
65   const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
66   inline bool piece_is_slider(Piece p) { return Slidings[p]; }
67
68   // Dynamic razoring margin based on depth
69   inline Value razor_margin(Depth d) { return Value(512 + 16 * int(d)); }
70
71   // Futility lookup tables (initialized at startup) and their access functions
72   Value FutilityMargins[16][64]; // [depth][moveNumber]
73   int FutilityMoveCounts[32];    // [depth]
74
75   inline Value futility_margin(Depth d, int mn) {
76
77     return d < 7 * ONE_PLY ? FutilityMargins[std::max(int(d), 1)][std::min(mn, 63)]
78                            : 2 * VALUE_INFINITE;
79   }
80
81   // Reduction lookup tables (initialized at startup) and their access function
82   int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
83
84   template <bool PvNode> inline Depth reduction(Depth d, int mn) {
85
86     return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
87   }
88
89   size_t MultiPV, UCIMultiPV, PVIdx;
90   TimeManager TimeMgr;
91   int BestMoveChanges;
92   int SkillLevel;
93   bool SkillLevelEnabled, Chess960;
94   History H;
95
96   template <NodeType NT>
97   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
98
99   template <NodeType NT>
100   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
101
102   void id_loop(Position& pos);
103   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta);
104   bool connected_moves(const Position& pos, Move m1, Move m2);
105   Value value_to_tt(Value v, int ply);
106   Value value_from_tt(Value v, int ply);
107   bool can_return_tt(const TTEntry* tte, Depth depth, Value ttValue, Value beta);
108   bool connected_threat(const Position& pos, Move m, Move threat);
109   Value refine_eval(const TTEntry* tte, Value ttValue, Value defaultEval);
110   Move do_skill_level();
111   string uci_pv(const Position& pos, int depth, Value alpha, Value beta);
112
113 } // namespace
114
115
116 /// Search::init() is called during startup to initialize various lookup tables
117
118 void Search::init() {
119
120   int d;  // depth (ONE_PLY == 2)
121   int hd; // half depth (ONE_PLY == 1)
122   int mc; // moveCount
123
124   // Init reductions array
125   for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
126   {
127       double    pvRed = log(double(hd)) * log(double(mc)) / 3.0;
128       double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
129       Reductions[1][hd][mc] = (int8_t) (   pvRed >= 1.0 ? floor(   pvRed * int(ONE_PLY)) : 0);
130       Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
131   }
132
133   // Init futility margins array
134   for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
135       FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
136
137   // Init futility move count array
138   for (d = 0; d < 32; d++)
139       FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
140 }
141
142
143 /// Search::perft() is our utility to verify move generation. All the leaf nodes
144 /// up to the given depth are generated and counted and the sum returned.
145
146 size_t Search::perft(Position& pos, Depth depth) {
147
148   // At the last ply just return the number of legal moves (leaf nodes)
149   if (depth == ONE_PLY)
150       return MoveList<LEGAL>(pos).size();
151
152   StateInfo st;
153   size_t cnt = 0;
154   CheckInfo ci(pos);
155
156   for (MoveList<LEGAL> ml(pos); !ml.end(); ++ml)
157   {
158       pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
159       cnt += perft(pos, depth - ONE_PLY);
160       pos.undo_move(ml.move());
161   }
162
163   return cnt;
164 }
165
166
167 /// Search::think() is the external interface to Stockfish's search, and is
168 /// called by the main thread when the program receives the UCI 'go' command. It
169 /// searches from RootPosition and at the end prints the "bestmove" to output.
170
171 void Search::think() {
172
173   static PolyglotBook book; // Defined static to initialize the PRNG only once
174
175   Position& pos = RootPosition;
176   Chess960 = pos.is_chess960();
177   Eval::RootColor = pos.side_to_move();
178   Eval::ValueDraw[ Eval::RootColor] = VALUE_DRAW - Eval::ContemptFactor;
179   Eval::ValueDraw[~Eval::RootColor] = VALUE_DRAW + Eval::ContemptFactor;
180   TimeMgr.init(Limits, pos.startpos_ply_counter(), pos.side_to_move());
181   TT.new_search();
182   H.clear();
183
184   if (RootMoves.empty())
185   {
186       sync_cout << "info depth 0 score "
187                 << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW) << sync_endl;
188
189       RootMoves.push_back(MOVE_NONE);
190       goto finalize;
191   }
192
193   if (Options["OwnBook"] && !Limits.infinite)
194   {
195       Move bookMove = book.probe(pos, Options["Book File"], Options["Best Book Move"]);
196
197       if (bookMove && std::count(RootMoves.begin(), RootMoves.end(), bookMove))
198       {
199           std::swap(RootMoves[0], *std::find(RootMoves.begin(), RootMoves.end(), bookMove));
200           goto finalize;
201       }
202   }
203
204   UCIMultiPV = Options["MultiPV"];
205   SkillLevel = Options["Skill Level"];
206
207   // Do we have to play with skill handicap? In this case enable MultiPV that
208   // we will use behind the scenes to retrieve a set of possible moves.
209   SkillLevelEnabled = (SkillLevel < 20);
210   MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, (size_t)4) : UCIMultiPV);
211
212   if (Options["Use Search Log"])
213   {
214       Log log(Options["Search Log Filename"]);
215       log << "\nSearching: "  << pos.to_fen()
216           << "\ninfinite: "   << Limits.infinite
217           << " ponder: "      << Limits.ponder
218           << " time: "        << Limits.time[pos.side_to_move()]
219           << " increment: "   << Limits.inc[pos.side_to_move()]
220           << " moves to go: " << Limits.movestogo
221           << std::endl;
222   }
223
224   Threads.wake_up();
225
226   // Set best timer interval to avoid lagging under time pressure. Timer is
227   // used to check for remaining available thinking time.
228   if (Limits.use_time_management())
229       Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 16, TimerResolution)));
230   else if (Limits.nodes)
231       Threads.set_timer(2 * TimerResolution);
232   else
233       Threads.set_timer(100);
234
235   // We're ready to start searching. Call the iterative deepening loop function
236   id_loop(pos);
237
238   Threads.set_timer(0); // Stop timer
239   Threads.sleep();
240
241   if (Options["Use Search Log"])
242   {
243       Time::point elapsed = Time::now() - SearchTime + 1;
244
245       Log log(Options["Search Log Filename"]);
246       log << "Nodes: "          << pos.nodes_searched()
247           << "\nNodes/second: " << pos.nodes_searched() * 1000 / elapsed
248           << "\nBest move: "    << move_to_san(pos, RootMoves[0].pv[0]);
249
250       StateInfo st;
251       pos.do_move(RootMoves[0].pv[0], st);
252       log << "\nPonder move: " << move_to_san(pos, RootMoves[0].pv[1]) << std::endl;
253       pos.undo_move(RootMoves[0].pv[0]);
254   }
255
256 finalize:
257
258   // When we reach max depth we arrive here even without Signals.stop is raised,
259   // but if we are pondering or in infinite search, we shouldn't print the best
260   // move before we are told to do so.
261   if (!Signals.stop && (Limits.ponder || Limits.infinite))
262       pos.this_thread()->wait_for_stop_or_ponderhit();
263
264   // Best move could be MOVE_NONE when searching on a stalemate position
265   sync_cout << "bestmove " << move_to_uci(RootMoves[0].pv[0], Chess960)
266             << " ponder "  << move_to_uci(RootMoves[0].pv[1], Chess960) << sync_endl;
267 }
268
269
270 namespace {
271
272   // id_loop() is the main iterative deepening loop. It calls search() repeatedly
273   // with increasing depth until the allocated thinking time has been consumed,
274   // user stops the search, or the maximum search depth is reached.
275
276   void id_loop(Position& pos) {
277
278     Stack ss[MAX_PLY_PLUS_2];
279     int depth, prevBestMoveChanges;
280     Value bestValue, alpha, beta, delta;
281     bool bestMoveNeverChanged = true;
282     Move skillBest = MOVE_NONE;
283
284     memset(ss, 0, 4 * sizeof(Stack));
285     depth = BestMoveChanges = 0;
286     bestValue = delta = -VALUE_INFINITE;
287     ss->currentMove = MOVE_NULL; // Hack to skip update gains
288
289     // Iterative deepening loop until requested to stop or target depth reached
290     while (!Signals.stop && ++depth <= MAX_PLY && (!Limits.depth || depth <= Limits.depth))
291     {
292         // Save last iteration's scores before first PV line is searched and all
293         // the move scores but the (new) PV are set to -VALUE_INFINITE.
294         for (size_t i = 0; i < RootMoves.size(); i++)
295             RootMoves[i].prevScore = RootMoves[i].score;
296
297         prevBestMoveChanges = BestMoveChanges;
298         BestMoveChanges = 0;
299
300         // MultiPV loop. We perform a full root search for each PV line
301         for (PVIdx = 0; PVIdx < std::min(MultiPV, RootMoves.size()); PVIdx++)
302         {
303             // Set aspiration window default width
304             if (depth >= 5 && abs(RootMoves[PVIdx].prevScore) < VALUE_KNOWN_WIN)
305             {
306                 delta = Value(16);
307                 alpha = RootMoves[PVIdx].prevScore - delta;
308                 beta  = RootMoves[PVIdx].prevScore + delta;
309             }
310             else
311             {
312                 alpha = -VALUE_INFINITE;
313                 beta  =  VALUE_INFINITE;
314             }
315
316             // Start with a small aspiration window and, in case of fail high/low,
317             // research with bigger window until not failing high/low anymore.
318             while (true)
319             {
320                 // Search starts from ss+1 to allow referencing (ss-1). This is
321                 // needed by update gains and ss copy when splitting at Root.
322                 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
323
324                 // Bring to front the best move. It is critical that sorting is
325                 // done with a stable algorithm because all the values but the first
326                 // and eventually the new best one are set to -VALUE_INFINITE and
327                 // we want to keep the same order for all the moves but the new
328                 // PV that goes to the front. Note that in case of MultiPV search
329                 // the already searched PV lines are preserved.
330                 sort<RootMove>(RootMoves.begin() + PVIdx, RootMoves.end());
331
332                 // In case we have found an exact score and we are going to leave
333                 // the fail high/low loop then reorder the PV moves, otherwise
334                 // leave the last PV move in its position so to be searched again.
335                 // Of course this is needed only in MultiPV search.
336                 if (PVIdx && bestValue > alpha && bestValue < beta)
337                     sort<RootMove>(RootMoves.begin(), RootMoves.begin() + PVIdx);
338
339                 // Write PV back to transposition table in case the relevant
340                 // entries have been overwritten during the search.
341                 for (size_t i = 0; i <= PVIdx; i++)
342                     RootMoves[i].insert_pv_in_tt(pos);
343
344                 // If search has been stopped exit the aspiration window loop.
345                 // Sorting and writing PV back to TT is safe becuase RootMoves
346                 // is still valid, although refers to previous iteration.
347                 if (Signals.stop)
348                     break;
349
350                 // Send full PV info to GUI if we are going to leave the loop or
351                 // if we have a fail high/low and we are deep in the search.
352                 if ((bestValue > alpha && bestValue < beta) || Time::now() - SearchTime > 2000)
353                     sync_cout << uci_pv(pos, depth, alpha, beta) << sync_endl;
354
355                 // In case of failing high/low increase aspiration window and
356                 // research, otherwise exit the fail high/low loop.
357                 if (bestValue >= beta)
358                 {
359                     beta += delta;
360                     delta += delta / 2;
361                 }
362                 else if (bestValue <= alpha)
363                 {
364                     Signals.failedLowAtRoot = true;
365                     Signals.stopOnPonderhit = false;
366
367                     alpha -= delta;
368                     delta += delta / 2;
369                 }
370                 else
371                     break;
372
373                 // Search with full window in case we have a win/mate score
374                 if (abs(bestValue) >= VALUE_KNOWN_WIN)
375                 {
376                     alpha = -VALUE_INFINITE;
377                     beta  =  VALUE_INFINITE;
378                 }
379
380                 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
381             }
382         }
383
384         // Skills: Do we need to pick now the best move ?
385         if (SkillLevelEnabled && depth == 1 + SkillLevel)
386             skillBest = do_skill_level();
387
388         if (!Signals.stop && Options["Use Search Log"])
389         {
390             Log log(Options["Search Log Filename"]);
391             log << pretty_pv(pos, depth, bestValue, Time::now() - SearchTime, &RootMoves[0].pv[0])
392                 << std::endl;
393         }
394
395         // Filter out startup noise when monitoring best move stability
396         if (depth > 2 && BestMoveChanges)
397             bestMoveNeverChanged = false;
398
399         // Do we have time for the next iteration? Can we stop searching now?
400         if (!Signals.stop && !Signals.stopOnPonderhit && Limits.use_time_management())
401         {
402             bool stop = false; // Local variable, not the volatile Signals.stop
403
404             // Take in account some extra time if the best move has changed
405             if (depth > 4 && depth < 50)
406                 TimeMgr.pv_instability(BestMoveChanges, prevBestMoveChanges);
407
408             // Stop search if most of available time is already consumed. We
409             // probably don't have enough time to search the first move at the
410             // next iteration anyway.
411             if (Time::now() - SearchTime > (TimeMgr.available_time() * 62) / 100)
412                 stop = true;
413
414             // Stop search early if one move seems to be much better than others
415             if (    depth >= 12
416                 && !stop
417                 && (   (bestMoveNeverChanged &&  pos.captured_piece_type())
418                     || Time::now() - SearchTime > (TimeMgr.available_time() * 40) / 100))
419             {
420                 Value rBeta = bestValue - 2 * PawnValueMg;
421                 (ss+1)->excludedMove = RootMoves[0].pv[0];
422                 (ss+1)->skipNullMove = true;
423                 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth - 3) * ONE_PLY);
424                 (ss+1)->skipNullMove = false;
425                 (ss+1)->excludedMove = MOVE_NONE;
426
427                 if (v < rBeta)
428                     stop = true;
429             }
430
431             if (stop)
432             {
433                 // If we are allowed to ponder do not stop the search now but
434                 // keep pondering until GUI sends "ponderhit" or "stop".
435                 if (Limits.ponder)
436                     Signals.stopOnPonderhit = true;
437                 else
438                     Signals.stop = true;
439             }
440         }
441     }
442
443     // When using skills swap best PV line with the sub-optimal one
444     if (SkillLevelEnabled)
445     {
446         if (skillBest == MOVE_NONE) // Still unassigned ?
447             skillBest = do_skill_level();
448
449         std::swap(RootMoves[0], *std::find(RootMoves.begin(), RootMoves.end(), skillBest));
450     }
451   }
452
453
454   // search<>() is the main search function for both PV and non-PV nodes and for
455   // normal and SplitPoint nodes. When called just after a split point the search
456   // is simpler because we have already probed the hash table, done a null move
457   // search, and searched the first move before splitting, we don't have to repeat
458   // all this work again. We also don't need to store anything to the hash table
459   // here: This is taken care of after we return from the split point.
460
461   template <NodeType NT>
462   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
463
464     const bool PvNode   = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
465     const bool SpNode   = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
466     const bool RootNode = (NT == Root || NT == SplitPointRoot);
467
468     assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
469     assert(PvNode || (alpha == beta - 1));
470     assert(depth > DEPTH_ZERO);
471
472     Move movesSearched[64];
473     StateInfo st;
474     const TTEntry *tte;
475     SplitPoint* sp;
476     Key posKey;
477     Move ttMove, move, excludedMove, bestMove, threatMove;
478     Depth ext, newDepth;
479     Value bestValue, value, ttValue;
480     Value refinedValue, nullValue, futilityValue;
481     bool inCheck, givesCheck, pvMove, singularExtensionNode;
482     bool captureOrPromotion, dangerous, doFullDepthSearch;
483     int moveCount, playedMoveCount;
484
485     // Step 1. Initialize node
486     Thread* thisThread = pos.this_thread();
487     moveCount = playedMoveCount = 0;
488     inCheck = pos.in_check();
489
490     if (SpNode)
491     {
492         sp = ss->sp;
493         bestMove   = sp->bestMove;
494         threatMove = sp->threatMove;
495         bestValue  = sp->bestValue;
496         tte = NULL;
497         ttMove = excludedMove = MOVE_NONE;
498         ttValue = VALUE_NONE;
499
500         assert(sp->bestValue > -VALUE_INFINITE && sp->moveCount > 0);
501
502         goto split_point_start;
503     }
504
505     bestValue = -VALUE_INFINITE;
506     ss->currentMove = threatMove = (ss+1)->excludedMove = bestMove = MOVE_NONE;
507     ss->ply = (ss-1)->ply + 1;
508     (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
509     (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
510
511     // Used to send selDepth info to GUI
512     if (PvNode && thisThread->maxPly < ss->ply)
513         thisThread->maxPly = ss->ply;
514
515     if (!RootNode)
516     {
517         // Step 2. Check for aborted search and immediate draw
518         if (Signals.stop || pos.is_draw<false>() || ss->ply > MAX_PLY)
519             return Eval::ValueDraw[pos.side_to_move()];
520
521         // Step 3. Mate distance pruning. Even if we mate at the next move our score
522         // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
523         // a shorter mate was found upward in the tree then there is no need to search
524         // further, we will never beat current alpha. Same logic but with reversed signs
525         // applies also in the opposite condition of being mated instead of giving mate,
526         // in this case return a fail-high score.
527         alpha = std::max(mated_in(ss->ply), alpha);
528         beta = std::min(mate_in(ss->ply+1), beta);
529         if (alpha >= beta)
530             return alpha;
531     }
532
533     // Step 4. Transposition table lookup
534     // We don't want the score of a partial search to overwrite a previous full search
535     // TT value, so we use a different position key in case of an excluded move.
536     excludedMove = ss->excludedMove;
537     posKey = excludedMove ? pos.exclusion_key() : pos.key();
538     tte = TT.probe(posKey);
539     ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
540     ttValue = tte ? value_from_tt(tte->value(), ss->ply) : VALUE_NONE;
541
542     // At PV nodes we check for exact scores, while at non-PV nodes we check for
543     // a fail high/low. Biggest advantage at probing at PV nodes is to have a
544     // smooth experience in analysis mode. We don't probe at Root nodes otherwise
545     // we should also update RootMoveList to avoid bogus output.
546     if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == BOUND_EXACT
547                                     : can_return_tt(tte, depth, ttValue, beta)))
548     {
549         TT.refresh(tte);
550         ss->currentMove = ttMove; // Can be MOVE_NONE
551
552         if (    ttValue >= beta
553             &&  ttMove
554             && !pos.is_capture_or_promotion(ttMove)
555             &&  ttMove != ss->killers[0])
556         {
557             ss->killers[1] = ss->killers[0];
558             ss->killers[0] = ttMove;
559         }
560         return ttValue;
561     }
562
563     // Step 5. Evaluate the position statically and update parent's gain statistics
564     if (inCheck)
565         ss->eval = ss->evalMargin = refinedValue = VALUE_NONE;
566     else if (tte)
567     {
568         assert(tte->static_value() != VALUE_NONE);
569
570         ss->eval = tte->static_value();
571         ss->evalMargin = tte->static_value_margin();
572         refinedValue = refine_eval(tte, ttValue, ss->eval);
573     }
574     else
575     {
576         refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
577         TT.store(posKey, VALUE_NONE, BOUND_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
578     }
579
580     // Update gain for the parent non-capture move given the static position
581     // evaluation before and after the move.
582     if (    (move = (ss-1)->currentMove) != MOVE_NULL
583         &&  (ss-1)->eval != VALUE_NONE
584         &&  ss->eval != VALUE_NONE
585         && !pos.captured_piece_type()
586         &&  type_of(move) == NORMAL)
587     {
588         Square to = to_sq(move);
589         H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
590     }
591
592     // Step 6. Razoring (is omitted in PV nodes)
593     if (   !PvNode
594         &&  depth < 4 * ONE_PLY
595         && !inCheck
596         &&  refinedValue + razor_margin(depth) < beta
597         &&  ttMove == MOVE_NONE
598         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
599         && !pos.pawn_on_7th(pos.side_to_move()))
600     {
601         Value rbeta = beta - razor_margin(depth);
602         Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
603         if (v < rbeta)
604             // Logically we should return (v + razor_margin(depth)), but
605             // surprisingly this did slightly weaker in tests.
606             return v;
607     }
608
609     // Step 7. Static null move pruning (is omitted in PV nodes)
610     // We're betting that the opponent doesn't have a move that will reduce
611     // the score by more than futility_margin(depth) if we do a null move.
612     if (   !PvNode
613         && !ss->skipNullMove
614         &&  depth < 4 * ONE_PLY
615         && !inCheck
616         &&  refinedValue - FutilityMargins[depth][0] >= beta
617         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
618         &&  pos.non_pawn_material(pos.side_to_move()))
619         return refinedValue - FutilityMargins[depth][0];
620
621     // Step 8. Null move search with verification search (is omitted in PV nodes)
622     if (   !PvNode
623         && !ss->skipNullMove
624         &&  depth > ONE_PLY
625         && !inCheck
626         &&  refinedValue >= beta
627         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
628         &&  pos.non_pawn_material(pos.side_to_move()))
629     {
630         ss->currentMove = MOVE_NULL;
631
632         // Null move dynamic reduction based on depth
633         Depth R = 3 * ONE_PLY + depth / 4;
634
635         // Null move dynamic reduction based on value
636         if (refinedValue - PawnValueMg > beta)
637             R += ONE_PLY;
638
639         pos.do_null_move<true>(st);
640         (ss+1)->skipNullMove = true;
641         nullValue = depth-R < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
642                                       : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R);
643         (ss+1)->skipNullMove = false;
644         pos.do_null_move<false>(st);
645
646         if (nullValue >= beta)
647         {
648             // Do not return unproven mate scores
649             if (nullValue >= VALUE_MATE_IN_MAX_PLY)
650                 nullValue = beta;
651
652             if (depth < 6 * ONE_PLY)
653                 return nullValue;
654
655             // Do verification search at high depths
656             ss->skipNullMove = true;
657             Value v = search<NonPV>(pos, ss, alpha, beta, depth-R);
658             ss->skipNullMove = false;
659
660             if (v >= beta)
661                 return nullValue;
662         }
663         else
664         {
665             // The null move failed low, which means that we may be faced with
666             // some kind of threat. If the previous move was reduced, check if
667             // the move that refuted the null move was somehow connected to the
668             // move which was reduced. If a connection is found, return a fail
669             // low score (which will cause the reduced move to fail high in the
670             // parent node, which will trigger a re-search with full depth).
671             threatMove = (ss+1)->currentMove;
672
673             if (   depth < 5 * ONE_PLY
674                 && (ss-1)->reduction
675                 && threatMove != MOVE_NONE
676                 && connected_moves(pos, (ss-1)->currentMove, threatMove))
677                 return beta - 1;
678         }
679     }
680
681     // Step 9. ProbCut (is omitted in PV nodes)
682     // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
683     // and a reduced search returns a value much above beta, we can (almost) safely
684     // prune the previous move.
685     if (   !PvNode
686         &&  depth >= 5 * ONE_PLY
687         && !inCheck
688         && !ss->skipNullMove
689         &&  excludedMove == MOVE_NONE
690         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY)
691     {
692         Value rbeta = beta + 200;
693         Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
694
695         assert(rdepth >= ONE_PLY);
696         assert((ss-1)->currentMove != MOVE_NONE);
697         assert((ss-1)->currentMove != MOVE_NULL);
698
699         MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
700         CheckInfo ci(pos);
701
702         while ((move = mp.next_move<false>()) != MOVE_NONE)
703             if (pos.pl_move_is_legal(move, ci.pinned))
704             {
705                 ss->currentMove = move;
706                 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
707                 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
708                 pos.undo_move(move);
709                 if (value >= rbeta)
710                     return value;
711             }
712     }
713
714     // Step 10. Internal iterative deepening
715     if (   depth >= (PvNode ? 5 * ONE_PLY : 8 * ONE_PLY)
716         && ttMove == MOVE_NONE
717         && (PvNode || (!inCheck && ss->eval + Value(256) >= beta)))
718     {
719         Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
720
721         ss->skipNullMove = true;
722         search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
723         ss->skipNullMove = false;
724
725         tte = TT.probe(posKey);
726         ttMove = tte ? tte->move() : MOVE_NONE;
727     }
728
729 split_point_start: // At split points actual search starts from here
730
731     MovePicker mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
732     CheckInfo ci(pos);
733     value = bestValue; // Workaround a bogus 'uninitialized' warning under gcc
734     singularExtensionNode =   !RootNode
735                            && !SpNode
736                            &&  depth >= (PvNode ? 6 * ONE_PLY : 8 * ONE_PLY)
737                            &&  ttMove != MOVE_NONE
738                            && !excludedMove // Recursive singular search is not allowed
739                            && (tte->type() & BOUND_LOWER)
740                            &&  tte->depth() >= depth - 3 * ONE_PLY;
741
742     // Step 11. Loop through moves
743     // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
744     while ((move = mp.next_move<SpNode>()) != MOVE_NONE)
745     {
746       assert(is_ok(move));
747
748       if (move == excludedMove)
749           continue;
750
751       // At root obey the "searchmoves" option and skip moves not listed in Root
752       // Move List, as a consequence any illegal move is also skipped. In MultiPV
753       // mode we also skip PV moves which have been already searched.
754       if (RootNode && !std::count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
755           continue;
756
757       if (SpNode)
758       {
759           // Shared counter cannot be decremented later if move turns out to be illegal
760           if (!pos.pl_move_is_legal(move, ci.pinned))
761               continue;
762
763           moveCount = ++sp->moveCount;
764           sp->mutex.unlock();
765       }
766       else
767           moveCount++;
768
769       if (RootNode)
770       {
771           Signals.firstRootMove = (moveCount == 1);
772
773           if (thisThread == Threads.main_thread() && Time::now() - SearchTime > 2000)
774               sync_cout << "info depth " << depth / ONE_PLY
775                         << " currmove " << move_to_uci(move, Chess960)
776                         << " currmovenumber " << moveCount + PVIdx << sync_endl;
777       }
778
779       ext = DEPTH_ZERO;
780       captureOrPromotion = pos.is_capture_or_promotion(move);
781       givesCheck = pos.move_gives_check(move, ci);
782       dangerous =   givesCheck
783                  || pos.is_passed_pawn_push(move)
784                  || type_of(move) == CASTLE
785                  || (   captureOrPromotion // Entering a pawn endgame?
786                      && type_of(pos.piece_on(to_sq(move))) != PAWN
787                      && type_of(move) == NORMAL
788                      && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
789                          - PieceValue[Mg][pos.piece_on(to_sq(move))] == VALUE_ZERO));
790
791       // Step 12. Extend checks and, in PV nodes, also dangerous moves
792       if (PvNode && dangerous)
793           ext = ONE_PLY;
794
795       else if (givesCheck && pos.see_sign(move) >= 0)
796           ext = ONE_PLY / 2;
797
798       // Singular extension search. If all moves but one fail low on a search of
799       // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
800       // is singular and should be extended. To verify this we do a reduced search
801       // on all the other moves but the ttMove, if result is lower than ttValue minus
802       // a margin then we extend ttMove.
803       if (    singularExtensionNode
804           && !ext
805           &&  move == ttMove
806           &&  pos.pl_move_is_legal(move, ci.pinned)
807           &&  abs(ttValue) < VALUE_KNOWN_WIN)
808       {
809           Value rBeta = ttValue - int(depth);
810           ss->excludedMove = move;
811           ss->skipNullMove = true;
812           value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
813           ss->skipNullMove = false;
814           ss->excludedMove = MOVE_NONE;
815
816           if (value < rBeta)
817               ext = rBeta >= beta ? ONE_PLY + ONE_PLY / 2 : ONE_PLY;
818       }
819
820       // Update current move (this must be done after singular extension search)
821       newDepth = depth - ONE_PLY + ext;
822
823       // Step 13. Futility pruning (is omitted in PV nodes)
824       if (   !PvNode
825           && !captureOrPromotion
826           && !inCheck
827           && !dangerous
828           &&  move != ttMove
829           && (bestValue > VALUE_MATED_IN_MAX_PLY || (   bestValue == -VALUE_INFINITE
830                                                      && alpha > VALUE_MATED_IN_MAX_PLY)))
831       {
832           // Move count based pruning
833           if (   depth < 16 * ONE_PLY
834               && moveCount >= FutilityMoveCounts[depth]
835               && (!threatMove || !connected_threat(pos, move, threatMove)))
836           {
837               if (SpNode)
838                   sp->mutex.lock();
839
840               continue;
841           }
842
843           // Value based pruning
844           // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
845           // but fixing this made program slightly weaker.
846           Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
847           futilityValue =  ss->eval + ss->evalMargin + futility_margin(predictedDepth, moveCount)
848                          + H.gain(pos.piece_moved(move), to_sq(move));
849
850           if (futilityValue < beta)
851           {
852               if (SpNode)
853                   sp->mutex.lock();
854
855               continue;
856           }
857
858           // Prune moves with negative SEE at low depths
859           if (   predictedDepth < 2 * ONE_PLY
860               && pos.see_sign(move) < 0)
861           {
862               if (SpNode)
863                   sp->mutex.lock();
864
865               continue;
866           }
867       }
868
869       // Check for legality only before to do the move
870       if (!pos.pl_move_is_legal(move, ci.pinned))
871       {
872           moveCount--;
873           continue;
874       }
875
876       pvMove = PvNode ? moveCount == 1 : false;
877       ss->currentMove = move;
878       if (!SpNode && !captureOrPromotion && playedMoveCount < 64)
879           movesSearched[playedMoveCount++] = move;
880
881       // Step 14. Make the move
882       pos.do_move(move, st, ci, givesCheck);
883
884       // Step 15. Reduced depth search (LMR). If the move fails high will be
885       // re-searched at full depth.
886       if (    depth > 3 * ONE_PLY
887           && !pvMove
888           && !captureOrPromotion
889           && !dangerous
890           &&  ss->killers[0] != move
891           &&  ss->killers[1] != move)
892       {
893           ss->reduction = reduction<PvNode>(depth, moveCount);
894           Depth d = std::max(newDepth - ss->reduction, ONE_PLY);
895           alpha = SpNode ? sp->alpha : alpha;
896
897           value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
898
899           doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
900           ss->reduction = DEPTH_ZERO;
901       }
902       else
903           doFullDepthSearch = !pvMove;
904
905       // Step 16. Full depth search, when LMR is skipped or fails high
906       if (doFullDepthSearch)
907       {
908           alpha = SpNode ? sp->alpha : alpha;
909           value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
910                                      : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
911       }
912
913       // Only for PV nodes do a full PV search on the first move or after a fail
914       // high, in the latter case search only if value < beta, otherwise let the
915       // parent node to fail low with value <= alpha and to try another move.
916       if (PvNode && (pvMove || (value > alpha && (RootNode || value < beta))))
917           value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
918                                      : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
919
920       // Step 17. Undo move
921       pos.undo_move(move);
922
923       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
924
925       // Step 18. Check for new best move
926       if (SpNode)
927       {
928           sp->mutex.lock();
929           bestValue = sp->bestValue;
930           alpha = sp->alpha;
931       }
932
933       // Finished searching the move. If Signals.stop is true, the search
934       // was aborted because the user interrupted the search or because we
935       // ran out of time. In this case, the return value of the search cannot
936       // be trusted, and we don't update the best move and/or PV.
937       if (Signals.stop || thisThread->cutoff_occurred())
938           return bestValue;
939
940       if (RootNode)
941       {
942           RootMove& rm = *std::find(RootMoves.begin(), RootMoves.end(), move);
943
944           // PV move or new best move ?
945           if (pvMove || value > alpha)
946           {
947               rm.score = value;
948               rm.extract_pv_from_tt(pos);
949
950               // We record how often the best move has been changed in each
951               // iteration. This information is used for time management: When
952               // the best move changes frequently, we allocate some more time.
953               if (!pvMove && MultiPV == 1)
954                   BestMoveChanges++;
955           }
956           else
957               // All other moves but the PV are set to the lowest value, this
958               // is not a problem when sorting becuase sort is stable and move
959               // position in the list is preserved, just the PV is pushed up.
960               rm.score = -VALUE_INFINITE;
961       }
962
963       if (value > bestValue)
964       {
965           bestValue = value;
966           if (SpNode) sp->bestValue = value;
967
968           if (value > alpha)
969           {
970               bestMove = move;
971               if (SpNode) sp->bestMove = move;
972
973               if (PvNode && value < beta)
974               {
975                   alpha = value; // Update alpha here! Always alpha < beta
976                   if (SpNode) sp->alpha = value;
977               }
978               else // Fail high
979               {
980                   if (SpNode) sp->cutoff = true;
981                   break;
982               }
983           }
984       }
985
986       // Step 19. Check for splitting the search
987       if (   !SpNode
988           &&  depth >= Threads.min_split_depth()
989           &&  bestValue < beta
990           &&  Threads.available_slave_exists(thisThread))
991       {
992           bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, &bestMove,
993                                                depth, threatMove, moveCount, mp, NT);
994           break;
995       }
996     }
997
998     if (SpNode)
999         return bestValue;
1000
1001     // Step 20. Check for mate and stalemate
1002     // All legal moves have been searched and if there are no legal moves, it
1003     // must be mate or stalemate. Note that we can have a false positive in
1004     // case of Signals.stop or thread.cutoff_occurred() are set, but this is
1005     // harmless because return value is discarded anyhow in the parent nodes.
1006     // If we are in a singular extension search then return a fail low score.
1007     // A split node has at least one move, the one tried before to be splitted.
1008     if (!moveCount)
1009         return excludedMove ? alpha : inCheck ? mated_in(ss->ply) : VALUE_DRAW;
1010
1011     // If we have pruned all the moves without searching return a fail-low score
1012     if (bestValue == -VALUE_INFINITE)
1013     {
1014         assert(!playedMoveCount);
1015
1016         bestValue = alpha;
1017     }
1018
1019     if (bestValue >= beta) // Failed high
1020     {
1021         TT.store(posKey, value_to_tt(bestValue, ss->ply), BOUND_LOWER, depth,
1022                  bestMove, ss->eval, ss->evalMargin);
1023
1024         if (!pos.is_capture_or_promotion(bestMove) && !inCheck)
1025         {
1026             if (bestMove != ss->killers[0])
1027             {
1028                 ss->killers[1] = ss->killers[0];
1029                 ss->killers[0] = bestMove;
1030             }
1031
1032             // Increase history value of the cut-off move
1033             Value bonus = Value(int(depth) * int(depth));
1034             H.add(pos.piece_moved(bestMove), to_sq(bestMove), bonus);
1035
1036             // Decrease history of all the other played non-capture moves
1037             for (int i = 0; i < playedMoveCount - 1; i++)
1038             {
1039                 Move m = movesSearched[i];
1040                 H.add(pos.piece_moved(m), to_sq(m), -bonus);
1041             }
1042         }
1043     }
1044     else // Failed low or PV search
1045         TT.store(posKey, value_to_tt(bestValue, ss->ply),
1046                  PvNode && bestMove != MOVE_NONE ? BOUND_EXACT : BOUND_UPPER,
1047                  depth, bestMove, ss->eval, ss->evalMargin);
1048
1049     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1050
1051     return bestValue;
1052   }
1053
1054
1055   // qsearch() is the quiescence search function, which is called by the main
1056   // search function when the remaining depth is zero (or, to be more precise,
1057   // less than ONE_PLY).
1058
1059   template <NodeType NT>
1060   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1061
1062     const bool PvNode = (NT == PV);
1063
1064     assert(NT == PV || NT == NonPV);
1065     assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1066     assert(PvNode || (alpha == beta - 1));
1067     assert(depth <= DEPTH_ZERO);
1068
1069     StateInfo st;
1070     const TTEntry* tte;
1071     Key posKey;
1072     Move ttMove, move, bestMove;
1073     Value bestValue, value, ttValue, futilityValue, futilityBase;
1074     bool inCheck, givesCheck, enoughMaterial, evasionPrunable;
1075     Depth ttDepth;
1076
1077     inCheck = pos.in_check();
1078     ss->currentMove = bestMove = MOVE_NONE;
1079     ss->ply = (ss-1)->ply + 1;
1080
1081     // Check for an instant draw or maximum ply reached
1082     if (pos.is_draw<true>() || ss->ply > MAX_PLY)
1083         return Eval::ValueDraw[pos.side_to_move()];
1084
1085     // Transposition table lookup. At PV nodes, we don't use the TT for
1086     // pruning, but only for move ordering.
1087     posKey = pos.key();
1088     tte = TT.probe(posKey);
1089     ttMove = tte ? tte->move() : MOVE_NONE;
1090     ttValue = tte ? value_from_tt(tte->value(),ss->ply) : VALUE_NONE;
1091
1092     // Decide whether or not to include checks, this fixes also the type of
1093     // TT entry depth that we are going to use. Note that in qsearch we use
1094     // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1095     ttDepth = inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS;
1096
1097     if (!PvNode && tte && can_return_tt(tte, ttDepth, ttValue, beta))
1098     {
1099         ss->currentMove = ttMove; // Can be MOVE_NONE
1100         return ttValue;
1101     }
1102
1103     // Evaluate the position statically
1104     if (inCheck)
1105     {
1106         ss->eval = ss->evalMargin = VALUE_NONE;
1107         bestValue = futilityBase = -VALUE_INFINITE;
1108         enoughMaterial = false;
1109     }
1110     else
1111     {
1112         if (tte)
1113         {
1114             assert(tte->static_value() != VALUE_NONE);
1115
1116             ss->eval = bestValue = tte->static_value();
1117             ss->evalMargin = tte->static_value_margin();
1118         }
1119         else
1120             ss->eval = bestValue = evaluate(pos, ss->evalMargin);
1121
1122         // Stand pat. Return immediately if static value is at least beta
1123         if (bestValue >= beta)
1124         {
1125             if (!tte)
1126                 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), BOUND_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
1127
1128             return bestValue;
1129         }
1130
1131         if (PvNode && bestValue > alpha)
1132             alpha = bestValue;
1133
1134         futilityBase = ss->eval + ss->evalMargin + Value(128);
1135         enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMg;
1136     }
1137
1138     // Initialize a MovePicker object for the current position, and prepare
1139     // to search the moves. Because the depth is <= 0 here, only captures,
1140     // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1141     // be generated.
1142     MovePicker mp(pos, ttMove, depth, H, to_sq((ss-1)->currentMove));
1143     CheckInfo ci(pos);
1144
1145     // Loop through the moves until no moves remain or a beta cutoff occurs
1146     while ((move = mp.next_move<false>()) != MOVE_NONE)
1147     {
1148       assert(is_ok(move));
1149
1150       givesCheck = pos.move_gives_check(move, ci);
1151
1152       // Futility pruning
1153       if (   !PvNode
1154           && !inCheck
1155           && !givesCheck
1156           &&  move != ttMove
1157           &&  enoughMaterial
1158           &&  type_of(move) != PROMOTION
1159           && !pos.is_passed_pawn_push(move))
1160       {
1161           futilityValue =  futilityBase
1162                          + PieceValue[Eg][pos.piece_on(to_sq(move))]
1163                          + (type_of(move) == ENPASSANT ? PawnValueEg : VALUE_ZERO);
1164
1165           if (futilityValue < beta)
1166           {
1167               if (futilityValue > bestValue)
1168                   bestValue = futilityValue;
1169
1170               continue;
1171           }
1172
1173           // Prune moves with negative or equal SEE
1174           if (   futilityBase < beta
1175               && depth < DEPTH_ZERO
1176               && pos.see(move) <= 0)
1177               continue;
1178       }
1179
1180       // Detect non-capture evasions that are candidate to be pruned
1181       evasionPrunable =   !PvNode
1182                        &&  inCheck
1183                        &&  bestValue > VALUE_MATED_IN_MAX_PLY
1184                        && !pos.is_capture(move)
1185                        && !pos.can_castle(pos.side_to_move());
1186
1187       // Don't search moves with negative SEE values
1188       if (   !PvNode
1189           && (!inCheck || evasionPrunable)
1190           &&  move != ttMove
1191           &&  type_of(move) != PROMOTION
1192           &&  pos.see_sign(move) < 0)
1193           continue;
1194
1195       // Don't search useless checks
1196       if (   !PvNode
1197           && !inCheck
1198           &&  givesCheck
1199           &&  move != ttMove
1200           && !pos.is_capture_or_promotion(move)
1201           &&  ss->eval + PawnValueMg / 4 < beta
1202           && !check_is_dangerous(pos, move, futilityBase, beta))
1203           continue;
1204
1205       // Check for legality only before to do the move
1206       if (!pos.pl_move_is_legal(move, ci.pinned))
1207           continue;
1208
1209       ss->currentMove = move;
1210
1211       // Make and search the move
1212       pos.do_move(move, st, ci, givesCheck);
1213       value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth - ONE_PLY);
1214       pos.undo_move(move);
1215
1216       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1217
1218       // Check for new best move
1219       if (value > bestValue)
1220       {
1221           bestValue = value;
1222
1223           if (value > alpha)
1224           {
1225               if (PvNode && value < beta) // Update alpha here! Always alpha < beta
1226               {
1227                   alpha = value;
1228                   bestMove = move;
1229               }
1230               else // Fail high
1231               {
1232                   TT.store(posKey, value_to_tt(value, ss->ply), BOUND_LOWER,
1233                            ttDepth, move, ss->eval, ss->evalMargin);
1234
1235                   return value;
1236               }
1237           }
1238        }
1239     }
1240
1241     // All legal moves have been searched. A special case: If we're in check
1242     // and no legal moves were found, it is checkmate.
1243     if (inCheck && bestValue == -VALUE_INFINITE)
1244         return mated_in(ss->ply); // Plies to mate from the root
1245
1246     TT.store(posKey, value_to_tt(bestValue, ss->ply),
1247              PvNode && bestMove != MOVE_NONE ? BOUND_EXACT : BOUND_UPPER,
1248              ttDepth, bestMove, ss->eval, ss->evalMargin);
1249
1250     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1251
1252     return bestValue;
1253   }
1254
1255
1256   // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1257   // bestValue is updated only when returning false because in that case move
1258   // will be pruned.
1259
1260   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta)
1261   {
1262     Bitboard b, occ, oldAtt, newAtt, kingAtt;
1263     Square from, to, ksq;
1264     Piece pc;
1265     Color them;
1266
1267     from = from_sq(move);
1268     to = to_sq(move);
1269     them = ~pos.side_to_move();
1270     ksq = pos.king_square(them);
1271     kingAtt = pos.attacks_from<KING>(ksq);
1272     pc = pos.piece_moved(move);
1273
1274     occ = pos.pieces() ^ from ^ ksq;
1275     oldAtt = pos.attacks_from(pc, from, occ);
1276     newAtt = pos.attacks_from(pc,   to, occ);
1277
1278     // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1279     b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1280
1281     if (!more_than_one(b))
1282         return true;
1283
1284     // Rule 2. Queen contact check is very dangerous
1285     if (type_of(pc) == QUEEN && (kingAtt & to))
1286         return true;
1287
1288     // Rule 3. Creating new double threats with checks
1289     b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1290     while (b)
1291     {
1292         // Note that here we generate illegal "double move"!
1293         if (futilityBase + PieceValue[Eg][pos.piece_on(pop_lsb(&b))] >= beta)
1294             return true;
1295     }
1296
1297     return false;
1298   }
1299
1300
1301   // connected_moves() tests whether two moves are 'connected' in the sense
1302   // that the first move somehow made the second move possible (for instance
1303   // if the moving piece is the same in both moves). The first move is assumed
1304   // to be the move that was made to reach the current position, while the
1305   // second move is assumed to be a move from the current position.
1306
1307   bool connected_moves(const Position& pos, Move m1, Move m2) {
1308
1309     Square f1, t1, f2, t2;
1310     Piece p1, p2;
1311     Square ksq;
1312
1313     assert(is_ok(m1));
1314     assert(is_ok(m2));
1315
1316     // Case 1: The moving piece is the same in both moves
1317     f2 = from_sq(m2);
1318     t1 = to_sq(m1);
1319     if (f2 == t1)
1320         return true;
1321
1322     // Case 2: The destination square for m2 was vacated by m1
1323     t2 = to_sq(m2);
1324     f1 = from_sq(m1);
1325     if (t2 == f1)
1326         return true;
1327
1328     // Case 3: Moving through the vacated square
1329     p2 = pos.piece_on(f2);
1330     if (piece_is_slider(p2) && (between_bb(f2, t2) & f1))
1331       return true;
1332
1333     // Case 4: The destination square for m2 is defended by the moving piece in m1
1334     p1 = pos.piece_on(t1);
1335     if (pos.attacks_from(p1, t1) & t2)
1336         return true;
1337
1338     // Case 5: Discovered check, checking piece is the piece moved in m1
1339     ksq = pos.king_square(pos.side_to_move());
1340     if (    piece_is_slider(p1)
1341         && (between_bb(t1, ksq) & f2)
1342         && (pos.attacks_from(p1, t1, pos.pieces() ^ f2) & ksq))
1343         return true;
1344
1345     return false;
1346   }
1347
1348
1349   // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1350   // "plies to mate from the current position". Non-mate scores are unchanged.
1351   // The function is called before storing a value to the transposition table.
1352
1353   Value value_to_tt(Value v, int ply) {
1354
1355     if (v >= VALUE_MATE_IN_MAX_PLY)
1356       return v + ply;
1357
1358     if (v <= VALUE_MATED_IN_MAX_PLY)
1359       return v - ply;
1360
1361     return v;
1362   }
1363
1364
1365   // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
1366   // from the transposition table (where refers to the plies to mate/be mated
1367   // from current position) to "plies to mate/be mated from the root".
1368
1369   Value value_from_tt(Value v, int ply) {
1370
1371     if (v >= VALUE_MATE_IN_MAX_PLY)
1372       return v - ply;
1373
1374     if (v <= VALUE_MATED_IN_MAX_PLY)
1375       return v + ply;
1376
1377     return v;
1378   }
1379
1380
1381   // connected_threat() tests whether it is safe to forward prune a move or if
1382   // is somehow connected to the threat move returned by null search.
1383
1384   bool connected_threat(const Position& pos, Move m, Move threat) {
1385
1386     assert(is_ok(m));
1387     assert(is_ok(threat));
1388     assert(!pos.is_capture_or_promotion(m));
1389     assert(!pos.is_passed_pawn_push(m));
1390
1391     Square mfrom, mto, tfrom, tto;
1392
1393     mfrom = from_sq(m);
1394     mto = to_sq(m);
1395     tfrom = from_sq(threat);
1396     tto = to_sq(threat);
1397
1398     // Case 1: Don't prune moves which move the threatened piece
1399     if (mfrom == tto)
1400         return true;
1401
1402     // Case 2: If the threatened piece has value less than or equal to the
1403     // value of the threatening piece, don't prune moves which defend it.
1404     if (   pos.is_capture(threat)
1405         && (   PieceValue[Mg][pos.piece_on(tfrom)] >= PieceValue[Mg][pos.piece_on(tto)]
1406             || type_of(pos.piece_on(tfrom)) == KING)
1407         && pos.move_attacks_square(m, tto))
1408         return true;
1409
1410     // Case 3: If the moving piece in the threatened move is a slider, don't
1411     // prune safe moves which block its ray.
1412     if (    piece_is_slider(pos.piece_on(tfrom))
1413         && (between_bb(tfrom, tto) & mto)
1414         &&  pos.see_sign(m) >= 0)
1415         return true;
1416
1417     return false;
1418   }
1419
1420
1421   // can_return_tt() returns true if a transposition table score can be used to
1422   // cut-off at a given point in search.
1423
1424   bool can_return_tt(const TTEntry* tte, Depth depth, Value v, Value beta) {
1425
1426     return   (   tte->depth() >= depth
1427               || v >= std::max(VALUE_MATE_IN_MAX_PLY, beta)
1428               || v < std::min(VALUE_MATED_IN_MAX_PLY, beta))
1429
1430           && (   ((tte->type() & BOUND_LOWER) && v >= beta)
1431               || ((tte->type() & BOUND_UPPER) && v < beta));
1432   }
1433
1434
1435   // refine_eval() returns the transposition table score if possible, otherwise
1436   // falls back on static position evaluation.
1437
1438   Value refine_eval(const TTEntry* tte, Value v, Value defaultEval) {
1439
1440       assert(tte);
1441
1442       if (   ((tte->type() & BOUND_LOWER) && v >= defaultEval)
1443           || ((tte->type() & BOUND_UPPER) && v < defaultEval))
1444           return v;
1445
1446       return defaultEval;
1447   }
1448
1449
1450   // When playing with strength handicap choose best move among the MultiPV set
1451   // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1452
1453   Move do_skill_level() {
1454
1455     assert(MultiPV > 1);
1456
1457     static RKISS rk;
1458
1459     // PRNG sequence should be not deterministic
1460     for (int i = Time::now() % 50; i > 0; i--)
1461         rk.rand<unsigned>();
1462
1463     // RootMoves are already sorted by score in descending order
1464     size_t size = std::min(MultiPV, RootMoves.size());
1465     int variance = std::min(RootMoves[0].score - RootMoves[size - 1].score, PawnValueMg);
1466     int weakness = 120 - 2 * SkillLevel;
1467     int max_s = -VALUE_INFINITE;
1468     Move best = MOVE_NONE;
1469
1470     // Choose best move. For each move score we add two terms both dependent on
1471     // weakness, one deterministic and bigger for weaker moves, and one random,
1472     // then we choose the move with the resulting highest score.
1473     for (size_t i = 0; i < size; i++)
1474     {
1475         int s = RootMoves[i].score;
1476
1477         // Don't allow crazy blunders even at very low skills
1478         if (i > 0 && RootMoves[i-1].score > s + 2 * PawnValueMg)
1479             break;
1480
1481         // This is our magic formula
1482         s += (  weakness * int(RootMoves[0].score - s)
1483               + variance * (rk.rand<unsigned>() % weakness)) / 128;
1484
1485         if (s > max_s)
1486         {
1487             max_s = s;
1488             best = RootMoves[i].pv[0];
1489         }
1490     }
1491     return best;
1492   }
1493
1494
1495   // uci_pv() formats PV information according to UCI protocol. UCI requires
1496   // to send all the PV lines also if are still to be searched and so refer to
1497   // the previous search score.
1498
1499   string uci_pv(const Position& pos, int depth, Value alpha, Value beta) {
1500
1501     std::stringstream s;
1502     Time::point elaspsed = Time::now() - SearchTime + 1;
1503     int selDepth = 0;
1504
1505     for (size_t i = 0; i < Threads.size(); i++)
1506         if (Threads[i].maxPly > selDepth)
1507             selDepth = Threads[i].maxPly;
1508
1509     for (size_t i = 0; i < std::min(UCIMultiPV, RootMoves.size()); i++)
1510     {
1511         bool updated = (i <= PVIdx);
1512
1513         if (depth == 1 && !updated)
1514             continue;
1515
1516         int d = (updated ? depth : depth - 1);
1517         Value v = (updated ? RootMoves[i].score : RootMoves[i].prevScore);
1518
1519         if (s.rdbuf()->in_avail())
1520             s << "\n";
1521
1522         s << "info depth " << d
1523           << " seldepth "  << selDepth
1524           << " score "     << (i == PVIdx ? score_to_uci(v, alpha, beta) : score_to_uci(v))
1525           << " nodes "     << pos.nodes_searched()
1526           << " nps "       << pos.nodes_searched() * 1000 / elaspsed
1527           << " time "      << elaspsed
1528           << " multipv "   << i + 1
1529           << " pv";
1530
1531         for (size_t j = 0; RootMoves[i].pv[j] != MOVE_NONE; j++)
1532             s <<  " " << move_to_uci(RootMoves[i].pv[j], Chess960);
1533     }
1534
1535     return s.str();
1536   }
1537
1538 } // namespace
1539
1540
1541 /// RootMove::extract_pv_from_tt() builds a PV by adding moves from the TT table.
1542 /// We consider also failing high nodes and not only BOUND_EXACT nodes so to
1543 /// allow to always have a ponder move even when we fail high at root, and a
1544 /// long PV to print that is important for position analysis.
1545
1546 void RootMove::extract_pv_from_tt(Position& pos) {
1547
1548   StateInfo state[MAX_PLY_PLUS_2], *st = state;
1549   TTEntry* tte;
1550   int ply = 1;
1551   Move m = pv[0];
1552
1553   assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1554
1555   pv.clear();
1556   pv.push_back(m);
1557   pos.do_move(m, *st++);
1558
1559   while (   (tte = TT.probe(pos.key())) != NULL
1560          && (m = tte->move()) != MOVE_NONE // Local copy, TT entry could change
1561          && pos.is_pseudo_legal(m)
1562          && pos.pl_move_is_legal(m, pos.pinned_pieces())
1563          && ply < MAX_PLY
1564          && (!pos.is_draw<false>() || ply < 2))
1565   {
1566       pv.push_back(m);
1567       pos.do_move(m, *st++);
1568       ply++;
1569   }
1570   pv.push_back(MOVE_NONE);
1571
1572   do pos.undo_move(pv[--ply]); while (ply);
1573 }
1574
1575
1576 /// RootMove::insert_pv_in_tt() is called at the end of a search iteration, and
1577 /// inserts the PV back into the TT. This makes sure the old PV moves are searched
1578 /// first, even if the old TT entries have been overwritten.
1579
1580 void RootMove::insert_pv_in_tt(Position& pos) {
1581
1582   StateInfo state[MAX_PLY_PLUS_2], *st = state;
1583   TTEntry* tte;
1584   Key k;
1585   Value v, m = VALUE_NONE;
1586   int ply = 0;
1587
1588   assert(pv[ply] != MOVE_NONE && pos.is_pseudo_legal(pv[ply]));
1589
1590   do {
1591       k = pos.key();
1592       tte = TT.probe(k);
1593
1594       // Don't overwrite existing correct entries
1595       if (!tte || tte->move() != pv[ply])
1596       {
1597           v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1598           TT.store(k, VALUE_NONE, BOUND_NONE, DEPTH_NONE, pv[ply], v, m);
1599       }
1600       pos.do_move(pv[ply], *st++);
1601
1602   } while (pv[++ply] != MOVE_NONE);
1603
1604   do pos.undo_move(pv[--ply]); while (ply);
1605 }
1606
1607
1608 /// Thread::idle_loop() is where the thread is parked when it has no work to do
1609
1610 void Thread::idle_loop() {
1611
1612   // Pointer 'sp_master', if non-NULL, points to the active SplitPoint
1613   // object for which the thread is the master.
1614   const SplitPoint* sp_master = splitPointsCnt ? curSplitPoint : NULL;
1615
1616   assert(!sp_master || (sp_master->master == this && is_searching));
1617
1618   // If this thread is the master of a split point and all slaves have
1619   // finished their work at this split point, return from the idle loop.
1620   while (!sp_master || sp_master->slavesMask)
1621   {
1622       // If we are not searching, wait for a condition to be signaled
1623       // instead of wasting CPU time polling for work.
1624       while (   do_sleep
1625              || do_exit
1626              || (!is_searching && Threads.use_sleeping_threads()))
1627       {
1628           if (do_exit)
1629           {
1630               assert(!sp_master);
1631               return;
1632           }
1633
1634           // Grab the lock to avoid races with Thread::wake_up()
1635           mutex.lock();
1636
1637           // If we are master and all slaves have finished don't go to sleep
1638           if (sp_master && !sp_master->slavesMask)
1639           {
1640               mutex.unlock();
1641               break;
1642           }
1643
1644           // Do sleep after retesting sleep conditions under lock protection, in
1645           // particular we need to avoid a deadlock in case a master thread has,
1646           // in the meanwhile, allocated us and sent the wake_up() call before we
1647           // had the chance to grab the lock.
1648           if (do_sleep || !is_searching)
1649               sleepCondition.wait(mutex);
1650
1651           mutex.unlock();
1652       }
1653
1654       // If this thread has been assigned work, launch a search
1655       if (is_searching)
1656       {
1657           assert(!do_sleep && !do_exit);
1658
1659           Threads.mutex.lock();
1660
1661           assert(is_searching);
1662           SplitPoint* sp = curSplitPoint;
1663
1664           Threads.mutex.unlock();
1665
1666           Stack ss[MAX_PLY_PLUS_2];
1667           Position pos(*sp->pos, this);
1668
1669           memcpy(ss, sp->ss - 1, 4 * sizeof(Stack));
1670           (ss+1)->sp = sp;
1671
1672           sp->mutex.lock();
1673
1674           assert(sp->activePositions[idx] == NULL);
1675
1676           sp->activePositions[idx] = &pos;
1677
1678           if (sp->nodeType == Root)
1679               search<SplitPointRoot>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1680           else if (sp->nodeType == PV)
1681               search<SplitPointPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1682           else if (sp->nodeType == NonPV)
1683               search<SplitPointNonPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1684           else
1685               assert(false);
1686
1687           assert(is_searching);
1688
1689           is_searching = false;
1690           sp->activePositions[idx] = NULL;
1691           sp->slavesMask &= ~(1ULL << idx);
1692           sp->nodes += pos.nodes_searched();
1693
1694           // Wake up master thread so to allow it to return from the idle loop in
1695           // case we are the last slave of the split point.
1696           if (    Threads.use_sleeping_threads()
1697               &&  this != sp->master
1698               && !sp->slavesMask)
1699           {
1700               assert(!sp->master->is_searching);
1701               sp->master->wake_up();
1702           }
1703
1704           // After releasing the lock we cannot access anymore any SplitPoint
1705           // related data in a safe way becuase it could have been released under
1706           // our feet by the sp master. Also accessing other Thread objects is
1707           // unsafe because if we are exiting there is a chance are already freed.
1708           sp->mutex.unlock();
1709       }
1710   }
1711 }
1712
1713
1714 /// check_time() is called by the timer thread when the timer triggers. It is
1715 /// used to print debug info and, more important, to detect when we are out of
1716 /// available time and so stop the search.
1717
1718 void check_time() {
1719
1720   static Time::point lastInfoTime = Time::now();
1721   int64_t nodes = 0; // Workaround silly 'uninitialized' gcc warning
1722
1723   if (Time::now() - lastInfoTime >= 1000)
1724   {
1725       lastInfoTime = Time::now();
1726       dbg_print();
1727   }
1728
1729   if (Limits.ponder)
1730       return;
1731
1732   if (Limits.nodes)
1733   {
1734       Threads.mutex.lock();
1735
1736       nodes = RootPosition.nodes_searched();
1737
1738       // Loop across all split points and sum accumulated SplitPoint nodes plus
1739       // all the currently active slaves positions.
1740       for (size_t i = 0; i < Threads.size(); i++)
1741           for (int j = 0; j < Threads[i].splitPointsCnt; j++)
1742           {
1743               SplitPoint& sp = Threads[i].splitPoints[j];
1744
1745               sp.mutex.lock();
1746
1747               nodes += sp.nodes;
1748               Bitboard sm = sp.slavesMask;
1749               while (sm)
1750               {
1751                   Position* pos = sp.activePositions[pop_lsb(&sm)];
1752                   nodes += pos ? pos->nodes_searched() : 0;
1753               }
1754
1755               sp.mutex.unlock();
1756           }
1757
1758       Threads.mutex.unlock();
1759   }
1760
1761   Time::point elapsed = Time::now() - SearchTime;
1762   bool stillAtFirstMove =    Signals.firstRootMove
1763                          && !Signals.failedLowAtRoot
1764                          &&  elapsed > TimeMgr.available_time();
1765
1766   bool noMoreTime =   elapsed > TimeMgr.maximum_time() - 2 * TimerResolution
1767                    || stillAtFirstMove;
1768
1769   if (   (Limits.use_time_management() && noMoreTime)
1770       || (Limits.movetime && elapsed >= Limits.movetime)
1771       || (Limits.nodes && nodes >= Limits.nodes))
1772       Signals.stop = true;
1773 }