]> git.sesse.net Git - stockfish/blob - src/search.cpp
a3d8781889a690e15e0b91c4044c0243245f90d1
[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 connected_threat(const Position& pos, Move m, Move threat);
108   Value refine_eval(const TTEntry* tte, Value ttValue, Value defaultEval);
109   Move do_skill_level();
110   string uci_pv(const Position& pos, int depth, Value alpha, Value beta);
111
112 } // namespace
113
114
115 /// Search::init() is called during startup to initialize various lookup tables
116
117 void Search::init() {
118
119   int d;  // depth (ONE_PLY == 2)
120   int hd; // half depth (ONE_PLY == 1)
121   int mc; // moveCount
122
123   // Init reductions array
124   for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
125   {
126       double    pvRed = log(double(hd)) * log(double(mc)) / 3.0;
127       double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
128       Reductions[1][hd][mc] = (int8_t) (   pvRed >= 1.0 ? floor(   pvRed * int(ONE_PLY)) : 0);
129       Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
130   }
131
132   // Init futility margins array
133   for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
134       FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
135
136   // Init futility move count array
137   for (d = 0; d < 32; d++)
138       FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
139 }
140
141
142 /// Search::perft() is our utility to verify move generation. All the leaf nodes
143 /// up to the given depth are generated and counted and the sum returned.
144
145 size_t Search::perft(Position& pos, Depth depth) {
146
147   // At the last ply just return the number of legal moves (leaf nodes)
148   if (depth == ONE_PLY)
149       return MoveList<LEGAL>(pos).size();
150
151   StateInfo st;
152   size_t cnt = 0;
153   CheckInfo ci(pos);
154
155   for (MoveList<LEGAL> ml(pos); !ml.end(); ++ml)
156   {
157       pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
158       cnt += perft(pos, depth - ONE_PLY);
159       pos.undo_move(ml.move());
160   }
161
162   return cnt;
163 }
164
165
166 /// Search::think() is the external interface to Stockfish's search, and is
167 /// called by the main thread when the program receives the UCI 'go' command. It
168 /// searches from RootPosition and at the end prints the "bestmove" to output.
169
170 void Search::think() {
171
172   static PolyglotBook book; // Defined static to initialize the PRNG only once
173
174   Position& pos = RootPosition;
175   Chess960 = pos.is_chess960();
176   Eval::RootColor = pos.side_to_move();
177   int scaledCF = Eval::ContemptFactor * MaterialTable::game_phase(pos) / PHASE_MIDGAME;
178   Eval::ValueDraw[ Eval::RootColor] = VALUE_DRAW - Value(scaledCF);
179   Eval::ValueDraw[~Eval::RootColor] = VALUE_DRAW + Value(scaledCF);
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
547         && tte && tte->depth() >= depth
548         && (           PvNode ?  tte->type() == BOUND_EXACT
549             : ttValue >= beta ? (tte->type() & BOUND_LOWER)
550                               : (tte->type() & BOUND_UPPER)))
551     {
552         TT.refresh(tte);
553         ss->currentMove = ttMove; // Can be MOVE_NONE
554
555         if (    ttValue >= beta
556             &&  ttMove
557             && !pos.is_capture_or_promotion(ttMove)
558             &&  ttMove != ss->killers[0])
559         {
560             ss->killers[1] = ss->killers[0];
561             ss->killers[0] = ttMove;
562         }
563         return ttValue;
564     }
565
566     // Step 5. Evaluate the position statically and update parent's gain statistics
567     if (inCheck)
568         ss->eval = ss->evalMargin = refinedValue = VALUE_NONE;
569     else if (tte)
570     {
571         assert(tte->static_value() != VALUE_NONE);
572
573         ss->eval = tte->static_value();
574         ss->evalMargin = tte->static_value_margin();
575         refinedValue = refine_eval(tte, ttValue, ss->eval);
576     }
577     else
578     {
579         refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
580         TT.store(posKey, VALUE_NONE, BOUND_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
581     }
582
583     // Update gain for the parent non-capture move given the static position
584     // evaluation before and after the move.
585     if (    (move = (ss-1)->currentMove) != MOVE_NULL
586         &&  (ss-1)->eval != VALUE_NONE
587         &&  ss->eval != VALUE_NONE
588         && !pos.captured_piece_type()
589         &&  type_of(move) == NORMAL)
590     {
591         Square to = to_sq(move);
592         H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
593     }
594
595     // Step 6. Razoring (is omitted in PV nodes)
596     if (   !PvNode
597         &&  depth < 4 * ONE_PLY
598         && !inCheck
599         &&  refinedValue + razor_margin(depth) < beta
600         &&  ttMove == MOVE_NONE
601         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
602         && !pos.pawn_on_7th(pos.side_to_move()))
603     {
604         Value rbeta = beta - razor_margin(depth);
605         Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
606         if (v < rbeta)
607             // Logically we should return (v + razor_margin(depth)), but
608             // surprisingly this did slightly weaker in tests.
609             return v;
610     }
611
612     // Step 7. Static null move pruning (is omitted in PV nodes)
613     // We're betting that the opponent doesn't have a move that will reduce
614     // the score by more than futility_margin(depth) if we do a null move.
615     if (   !PvNode
616         && !ss->skipNullMove
617         &&  depth < 4 * ONE_PLY
618         && !inCheck
619         &&  refinedValue - FutilityMargins[depth][0] >= beta
620         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
621         &&  pos.non_pawn_material(pos.side_to_move()))
622         return refinedValue - FutilityMargins[depth][0];
623
624     // Step 8. Null move search with verification search (is omitted in PV nodes)
625     if (   !PvNode
626         && !ss->skipNullMove
627         &&  depth > ONE_PLY
628         && !inCheck
629         &&  refinedValue >= beta
630         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
631         &&  pos.non_pawn_material(pos.side_to_move()))
632     {
633         ss->currentMove = MOVE_NULL;
634
635         // Null move dynamic reduction based on depth
636         Depth R = 3 * ONE_PLY + depth / 4;
637
638         // Null move dynamic reduction based on value
639         if (refinedValue - PawnValueMg > beta)
640             R += ONE_PLY;
641
642         pos.do_null_move<true>(st);
643         (ss+1)->skipNullMove = true;
644         nullValue = depth-R < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
645                                       : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R);
646         (ss+1)->skipNullMove = false;
647         pos.do_null_move<false>(st);
648
649         if (nullValue >= beta)
650         {
651             // Do not return unproven mate scores
652             if (nullValue >= VALUE_MATE_IN_MAX_PLY)
653                 nullValue = beta;
654
655             if (depth < 6 * ONE_PLY)
656                 return nullValue;
657
658             // Do verification search at high depths
659             ss->skipNullMove = true;
660             Value v = search<NonPV>(pos, ss, alpha, beta, depth-R);
661             ss->skipNullMove = false;
662
663             if (v >= beta)
664                 return nullValue;
665         }
666         else
667         {
668             // The null move failed low, which means that we may be faced with
669             // some kind of threat. If the previous move was reduced, check if
670             // the move that refuted the null move was somehow connected to the
671             // move which was reduced. If a connection is found, return a fail
672             // low score (which will cause the reduced move to fail high in the
673             // parent node, which will trigger a re-search with full depth).
674             threatMove = (ss+1)->currentMove;
675
676             if (   depth < 5 * ONE_PLY
677                 && (ss-1)->reduction
678                 && threatMove != MOVE_NONE
679                 && connected_moves(pos, (ss-1)->currentMove, threatMove))
680                 return beta - 1;
681         }
682     }
683
684     // Step 9. ProbCut (is omitted in PV nodes)
685     // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
686     // and a reduced search returns a value much above beta, we can (almost) safely
687     // prune the previous move.
688     if (   !PvNode
689         &&  depth >= 5 * ONE_PLY
690         && !inCheck
691         && !ss->skipNullMove
692         &&  excludedMove == MOVE_NONE
693         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY)
694     {
695         Value rbeta = beta + 200;
696         Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
697
698         assert(rdepth >= ONE_PLY);
699         assert((ss-1)->currentMove != MOVE_NONE);
700         assert((ss-1)->currentMove != MOVE_NULL);
701
702         MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
703         CheckInfo ci(pos);
704
705         while ((move = mp.next_move<false>()) != MOVE_NONE)
706             if (pos.pl_move_is_legal(move, ci.pinned))
707             {
708                 ss->currentMove = move;
709                 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
710                 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
711                 pos.undo_move(move);
712                 if (value >= rbeta)
713                     return value;
714             }
715     }
716
717     // Step 10. Internal iterative deepening
718     if (   depth >= (PvNode ? 5 * ONE_PLY : 8 * ONE_PLY)
719         && ttMove == MOVE_NONE
720         && (PvNode || (!inCheck && ss->eval + Value(256) >= beta)))
721     {
722         Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
723
724         ss->skipNullMove = true;
725         search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
726         ss->skipNullMove = false;
727
728         tte = TT.probe(posKey);
729         ttMove = tte ? tte->move() : MOVE_NONE;
730     }
731
732 split_point_start: // At split points actual search starts from here
733
734     MovePicker mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
735     CheckInfo ci(pos);
736     value = bestValue; // Workaround a bogus 'uninitialized' warning under gcc
737     singularExtensionNode =   !RootNode
738                            && !SpNode
739                            &&  depth >= (PvNode ? 6 * ONE_PLY : 8 * ONE_PLY)
740                            &&  ttMove != MOVE_NONE
741                            && !excludedMove // Recursive singular search is not allowed
742                            && (tte->type() & BOUND_LOWER)
743                            &&  tte->depth() >= depth - 3 * ONE_PLY;
744
745     // Step 11. Loop through moves
746     // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
747     while ((move = mp.next_move<SpNode>()) != MOVE_NONE)
748     {
749       assert(is_ok(move));
750
751       if (move == excludedMove)
752           continue;
753
754       // At root obey the "searchmoves" option and skip moves not listed in Root
755       // Move List, as a consequence any illegal move is also skipped. In MultiPV
756       // mode we also skip PV moves which have been already searched.
757       if (RootNode && !std::count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
758           continue;
759
760       if (SpNode)
761       {
762           // Shared counter cannot be decremented later if move turns out to be illegal
763           if (!pos.pl_move_is_legal(move, ci.pinned))
764               continue;
765
766           moveCount = ++sp->moveCount;
767           sp->mutex.unlock();
768       }
769       else
770           moveCount++;
771
772       if (RootNode)
773       {
774           Signals.firstRootMove = (moveCount == 1);
775
776           if (thisThread == Threads.main_thread() && Time::now() - SearchTime > 2000)
777               sync_cout << "info depth " << depth / ONE_PLY
778                         << " currmove " << move_to_uci(move, Chess960)
779                         << " currmovenumber " << moveCount + PVIdx << sync_endl;
780       }
781
782       ext = DEPTH_ZERO;
783       captureOrPromotion = pos.is_capture_or_promotion(move);
784       givesCheck = pos.move_gives_check(move, ci);
785       dangerous =   givesCheck
786                  || pos.is_passed_pawn_push(move)
787                  || type_of(move) == CASTLE
788                  || (   captureOrPromotion // Entering a pawn endgame?
789                      && type_of(pos.piece_on(to_sq(move))) != PAWN
790                      && type_of(move) == NORMAL
791                      && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
792                          - PieceValue[Mg][pos.piece_on(to_sq(move))] == VALUE_ZERO));
793
794       // Step 12. Extend checks and, in PV nodes, also dangerous moves
795       if (PvNode && dangerous)
796           ext = ONE_PLY;
797
798       else if (givesCheck && pos.see_sign(move) >= 0)
799           ext = ONE_PLY / 2;
800
801       // Singular extension search. If all moves but one fail low on a search of
802       // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
803       // is singular and should be extended. To verify this we do a reduced search
804       // on all the other moves but the ttMove, if result is lower than ttValue minus
805       // a margin then we extend ttMove.
806       if (    singularExtensionNode
807           && !ext
808           &&  move == ttMove
809           &&  pos.pl_move_is_legal(move, ci.pinned)
810           &&  abs(ttValue) < VALUE_KNOWN_WIN)
811       {
812           Value rBeta = ttValue - int(depth);
813           ss->excludedMove = move;
814           ss->skipNullMove = true;
815           value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
816           ss->skipNullMove = false;
817           ss->excludedMove = MOVE_NONE;
818
819           if (value < rBeta)
820               ext = rBeta >= beta ? ONE_PLY + ONE_PLY / 2 : ONE_PLY;
821       }
822
823       // Update current move (this must be done after singular extension search)
824       newDepth = depth - ONE_PLY + ext;
825
826       // Step 13. Futility pruning (is omitted in PV nodes)
827       if (   !PvNode
828           && !captureOrPromotion
829           && !inCheck
830           && !dangerous
831           &&  move != ttMove
832           && (bestValue > VALUE_MATED_IN_MAX_PLY || (   bestValue == -VALUE_INFINITE
833                                                      && alpha > VALUE_MATED_IN_MAX_PLY)))
834       {
835           // Move count based pruning
836           if (   depth < 16 * ONE_PLY
837               && moveCount >= FutilityMoveCounts[depth]
838               && (!threatMove || !connected_threat(pos, move, threatMove)))
839           {
840               if (SpNode)
841                   sp->mutex.lock();
842
843               continue;
844           }
845
846           // Value based pruning
847           // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
848           // but fixing this made program slightly weaker.
849           Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
850           futilityValue =  ss->eval + ss->evalMargin + futility_margin(predictedDepth, moveCount)
851                          + H.gain(pos.piece_moved(move), to_sq(move));
852
853           if (futilityValue < beta)
854           {
855               if (SpNode)
856                   sp->mutex.lock();
857
858               continue;
859           }
860
861           // Prune moves with negative SEE at low depths
862           if (   predictedDepth < 2 * ONE_PLY
863               && pos.see_sign(move) < 0)
864           {
865               if (SpNode)
866                   sp->mutex.lock();
867
868               continue;
869           }
870       }
871
872       // Check for legality only before to do the move
873       if (!pos.pl_move_is_legal(move, ci.pinned))
874       {
875           moveCount--;
876           continue;
877       }
878
879       pvMove = PvNode ? moveCount == 1 : false;
880       ss->currentMove = move;
881       if (!SpNode && !captureOrPromotion && playedMoveCount < 64)
882           movesSearched[playedMoveCount++] = move;
883
884       // Step 14. Make the move
885       pos.do_move(move, st, ci, givesCheck);
886
887       // Step 15. Reduced depth search (LMR). If the move fails high will be
888       // re-searched at full depth.
889       if (    depth > 3 * ONE_PLY
890           && !pvMove
891           && !captureOrPromotion
892           && !dangerous
893           &&  ss->killers[0] != move
894           &&  ss->killers[1] != move)
895       {
896           ss->reduction = reduction<PvNode>(depth, moveCount);
897           Depth d = std::max(newDepth - ss->reduction, ONE_PLY);
898           alpha = SpNode ? sp->alpha : alpha;
899
900           value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
901
902           doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
903           ss->reduction = DEPTH_ZERO;
904       }
905       else
906           doFullDepthSearch = !pvMove;
907
908       // Step 16. Full depth search, when LMR is skipped or fails high
909       if (doFullDepthSearch)
910       {
911           alpha = SpNode ? sp->alpha : alpha;
912           value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
913                                      : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
914       }
915
916       // Only for PV nodes do a full PV search on the first move or after a fail
917       // high, in the latter case search only if value < beta, otherwise let the
918       // parent node to fail low with value <= alpha and to try another move.
919       if (PvNode && (pvMove || (value > alpha && (RootNode || value < beta))))
920           value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
921                                      : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
922
923       // Step 17. Undo move
924       pos.undo_move(move);
925
926       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
927
928       // Step 18. Check for new best move
929       if (SpNode)
930       {
931           sp->mutex.lock();
932           bestValue = sp->bestValue;
933           alpha = sp->alpha;
934       }
935
936       // Finished searching the move. If Signals.stop is true, the search
937       // was aborted because the user interrupted the search or because we
938       // ran out of time. In this case, the return value of the search cannot
939       // be trusted, and we don't update the best move and/or PV.
940       if (Signals.stop || thisThread->cutoff_occurred())
941           return bestValue;
942
943       if (RootNode)
944       {
945           RootMove& rm = *std::find(RootMoves.begin(), RootMoves.end(), move);
946
947           // PV move or new best move ?
948           if (pvMove || value > alpha)
949           {
950               rm.score = value;
951               rm.extract_pv_from_tt(pos);
952
953               // We record how often the best move has been changed in each
954               // iteration. This information is used for time management: When
955               // the best move changes frequently, we allocate some more time.
956               if (!pvMove && MultiPV == 1)
957                   BestMoveChanges++;
958           }
959           else
960               // All other moves but the PV are set to the lowest value, this
961               // is not a problem when sorting becuase sort is stable and move
962               // position in the list is preserved, just the PV is pushed up.
963               rm.score = -VALUE_INFINITE;
964       }
965
966       if (value > bestValue)
967       {
968           bestValue = value;
969           if (SpNode) sp->bestValue = value;
970
971           if (value > alpha)
972           {
973               bestMove = move;
974               if (SpNode) sp->bestMove = move;
975
976               if (PvNode && value < beta)
977               {
978                   alpha = value; // Update alpha here! Always alpha < beta
979                   if (SpNode) sp->alpha = value;
980               }
981               else // Fail high
982               {
983                   if (SpNode) sp->cutoff = true;
984                   break;
985               }
986           }
987       }
988
989       // Step 19. Check for splitting the search
990       if (   !SpNode
991           &&  depth >= Threads.min_split_depth()
992           &&  bestValue < beta
993           &&  Threads.available_slave_exists(thisThread))
994       {
995           bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, &bestMove,
996                                                depth, threatMove, moveCount, mp, NT);
997           break;
998       }
999     }
1000
1001     if (SpNode)
1002         return bestValue;
1003
1004     // Step 20. Check for mate and stalemate
1005     // All legal moves have been searched and if there are no legal moves, it
1006     // must be mate or stalemate. Note that we can have a false positive in
1007     // case of Signals.stop or thread.cutoff_occurred() are set, but this is
1008     // harmless because return value is discarded anyhow in the parent nodes.
1009     // If we are in a singular extension search then return a fail low score.
1010     // A split node has at least one move, the one tried before to be splitted.
1011     if (!moveCount)
1012         return excludedMove ? alpha : inCheck ? mated_in(ss->ply) : VALUE_DRAW;
1013
1014     // If we have pruned all the moves without searching return a fail-low score
1015     if (bestValue == -VALUE_INFINITE)
1016     {
1017         assert(!playedMoveCount);
1018
1019         bestValue = alpha;
1020     }
1021
1022     if (bestValue >= beta) // Failed high
1023     {
1024         TT.store(posKey, value_to_tt(bestValue, ss->ply), BOUND_LOWER, depth,
1025                  bestMove, ss->eval, ss->evalMargin);
1026
1027         if (!pos.is_capture_or_promotion(bestMove) && !inCheck)
1028         {
1029             if (bestMove != ss->killers[0])
1030             {
1031                 ss->killers[1] = ss->killers[0];
1032                 ss->killers[0] = bestMove;
1033             }
1034
1035             // Increase history value of the cut-off move
1036             Value bonus = Value(int(depth) * int(depth));
1037             H.add(pos.piece_moved(bestMove), to_sq(bestMove), bonus);
1038
1039             // Decrease history of all the other played non-capture moves
1040             for (int i = 0; i < playedMoveCount - 1; i++)
1041             {
1042                 Move m = movesSearched[i];
1043                 H.add(pos.piece_moved(m), to_sq(m), -bonus);
1044             }
1045         }
1046     }
1047     else // Failed low or PV search
1048         TT.store(posKey, value_to_tt(bestValue, ss->ply),
1049                  PvNode && bestMove != MOVE_NONE ? BOUND_EXACT : BOUND_UPPER,
1050                  depth, bestMove, ss->eval, ss->evalMargin);
1051
1052     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1053
1054     return bestValue;
1055   }
1056
1057
1058   // qsearch() is the quiescence search function, which is called by the main
1059   // search function when the remaining depth is zero (or, to be more precise,
1060   // less than ONE_PLY).
1061
1062   template <NodeType NT>
1063   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1064
1065     const bool PvNode = (NT == PV);
1066
1067     assert(NT == PV || NT == NonPV);
1068     assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1069     assert(PvNode || (alpha == beta - 1));
1070     assert(depth <= DEPTH_ZERO);
1071
1072     StateInfo st;
1073     const TTEntry* tte;
1074     Key posKey;
1075     Move ttMove, move, bestMove;
1076     Value bestValue, value, ttValue, futilityValue, futilityBase;
1077     bool inCheck, givesCheck, enoughMaterial, evasionPrunable;
1078     Depth ttDepth;
1079
1080     inCheck = pos.in_check();
1081     ss->currentMove = bestMove = MOVE_NONE;
1082     ss->ply = (ss-1)->ply + 1;
1083
1084     // Check for an instant draw or maximum ply reached
1085     if (pos.is_draw<true>() || ss->ply > MAX_PLY)
1086         return Eval::ValueDraw[pos.side_to_move()];
1087
1088     // Transposition table lookup. At PV nodes, we don't use the TT for
1089     // pruning, but only for move ordering.
1090     posKey = pos.key();
1091     tte = TT.probe(posKey);
1092     ttMove = tte ? tte->move() : MOVE_NONE;
1093     ttValue = tte ? value_from_tt(tte->value(),ss->ply) : VALUE_NONE;
1094
1095     // Decide whether or not to include checks, this fixes also the type of
1096     // TT entry depth that we are going to use. Note that in qsearch we use
1097     // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1098     ttDepth = inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS;
1099
1100     if (   tte && tte->depth() >= ttDepth
1101         && (           PvNode ?  tte->type() == BOUND_EXACT
1102             : ttValue >= beta ? (tte->type() & BOUND_LOWER)
1103                               : (tte->type() & BOUND_UPPER)))
1104     {
1105         ss->currentMove = ttMove; // Can be MOVE_NONE
1106         return ttValue;
1107     }
1108
1109     // Evaluate the position statically
1110     if (inCheck)
1111     {
1112         ss->eval = ss->evalMargin = VALUE_NONE;
1113         bestValue = futilityBase = -VALUE_INFINITE;
1114         enoughMaterial = false;
1115     }
1116     else
1117     {
1118         if (tte)
1119         {
1120             assert(tte->static_value() != VALUE_NONE);
1121
1122             ss->eval = bestValue = tte->static_value();
1123             ss->evalMargin = tte->static_value_margin();
1124         }
1125         else
1126             ss->eval = bestValue = evaluate(pos, ss->evalMargin);
1127
1128         // Stand pat. Return immediately if static value is at least beta
1129         if (bestValue >= beta)
1130         {
1131             if (!tte)
1132                 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), BOUND_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
1133
1134             return bestValue;
1135         }
1136
1137         if (PvNode && bestValue > alpha)
1138             alpha = bestValue;
1139
1140         futilityBase = ss->eval + ss->evalMargin + Value(128);
1141         enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMg;
1142     }
1143
1144     // Initialize a MovePicker object for the current position, and prepare
1145     // to search the moves. Because the depth is <= 0 here, only captures,
1146     // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1147     // be generated.
1148     MovePicker mp(pos, ttMove, depth, H, to_sq((ss-1)->currentMove));
1149     CheckInfo ci(pos);
1150
1151     // Loop through the moves until no moves remain or a beta cutoff occurs
1152     while ((move = mp.next_move<false>()) != MOVE_NONE)
1153     {
1154       assert(is_ok(move));
1155
1156       givesCheck = pos.move_gives_check(move, ci);
1157
1158       // Futility pruning
1159       if (   !PvNode
1160           && !inCheck
1161           && !givesCheck
1162           &&  move != ttMove
1163           &&  enoughMaterial
1164           &&  type_of(move) != PROMOTION
1165           && !pos.is_passed_pawn_push(move))
1166       {
1167           futilityValue =  futilityBase
1168                          + PieceValue[Eg][pos.piece_on(to_sq(move))]
1169                          + (type_of(move) == ENPASSANT ? PawnValueEg : VALUE_ZERO);
1170
1171           if (futilityValue < beta)
1172           {
1173               if (futilityValue > bestValue)
1174                   bestValue = futilityValue;
1175
1176               continue;
1177           }
1178
1179           // Prune moves with negative or equal SEE
1180           if (   futilityBase < beta
1181               && depth < DEPTH_ZERO
1182               && pos.see(move) <= 0)
1183               continue;
1184       }
1185
1186       // Detect non-capture evasions that are candidate to be pruned
1187       evasionPrunable =   !PvNode
1188                        &&  inCheck
1189                        &&  bestValue > VALUE_MATED_IN_MAX_PLY
1190                        && !pos.is_capture(move)
1191                        && !pos.can_castle(pos.side_to_move());
1192
1193       // Don't search moves with negative SEE values
1194       if (   !PvNode
1195           && (!inCheck || evasionPrunable)
1196           &&  move != ttMove
1197           &&  type_of(move) != PROMOTION
1198           &&  pos.see_sign(move) < 0)
1199           continue;
1200
1201       // Don't search useless checks
1202       if (   !PvNode
1203           && !inCheck
1204           &&  givesCheck
1205           &&  move != ttMove
1206           && !pos.is_capture_or_promotion(move)
1207           &&  ss->eval + PawnValueMg / 4 < beta
1208           && !check_is_dangerous(pos, move, futilityBase, beta))
1209           continue;
1210
1211       // Check for legality only before to do the move
1212       if (!pos.pl_move_is_legal(move, ci.pinned))
1213           continue;
1214
1215       ss->currentMove = move;
1216
1217       // Make and search the move
1218       pos.do_move(move, st, ci, givesCheck);
1219       value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth - ONE_PLY);
1220       pos.undo_move(move);
1221
1222       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1223
1224       // Check for new best move
1225       if (value > bestValue)
1226       {
1227           bestValue = value;
1228
1229           if (value > alpha)
1230           {
1231               if (PvNode && value < beta) // Update alpha here! Always alpha < beta
1232               {
1233                   alpha = value;
1234                   bestMove = move;
1235               }
1236               else // Fail high
1237               {
1238                   TT.store(posKey, value_to_tt(value, ss->ply), BOUND_LOWER,
1239                            ttDepth, move, ss->eval, ss->evalMargin);
1240
1241                   return value;
1242               }
1243           }
1244        }
1245     }
1246
1247     // All legal moves have been searched. A special case: If we're in check
1248     // and no legal moves were found, it is checkmate.
1249     if (inCheck && bestValue == -VALUE_INFINITE)
1250         return mated_in(ss->ply); // Plies to mate from the root
1251
1252     TT.store(posKey, value_to_tt(bestValue, ss->ply),
1253              PvNode && bestMove != MOVE_NONE ? BOUND_EXACT : BOUND_UPPER,
1254              ttDepth, bestMove, ss->eval, ss->evalMargin);
1255
1256     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1257
1258     return bestValue;
1259   }
1260
1261
1262   // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1263   // bestValue is updated only when returning false because in that case move
1264   // will be pruned.
1265
1266   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta)
1267   {
1268     Bitboard b, occ, oldAtt, newAtt, kingAtt;
1269     Square from, to, ksq;
1270     Piece pc;
1271     Color them;
1272
1273     from = from_sq(move);
1274     to = to_sq(move);
1275     them = ~pos.side_to_move();
1276     ksq = pos.king_square(them);
1277     kingAtt = pos.attacks_from<KING>(ksq);
1278     pc = pos.piece_moved(move);
1279
1280     occ = pos.pieces() ^ from ^ ksq;
1281     oldAtt = pos.attacks_from(pc, from, occ);
1282     newAtt = pos.attacks_from(pc,   to, occ);
1283
1284     // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1285     b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1286
1287     if (!more_than_one(b))
1288         return true;
1289
1290     // Rule 2. Queen contact check is very dangerous
1291     if (type_of(pc) == QUEEN && (kingAtt & to))
1292         return true;
1293
1294     // Rule 3. Creating new double threats with checks
1295     b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1296     while (b)
1297     {
1298         // Note that here we generate illegal "double move"!
1299         if (futilityBase + PieceValue[Eg][pos.piece_on(pop_lsb(&b))] >= beta)
1300             return true;
1301     }
1302
1303     return false;
1304   }
1305
1306
1307   // connected_moves() tests whether two moves are 'connected' in the sense
1308   // that the first move somehow made the second move possible (for instance
1309   // if the moving piece is the same in both moves). The first move is assumed
1310   // to be the move that was made to reach the current position, while the
1311   // second move is assumed to be a move from the current position.
1312
1313   bool connected_moves(const Position& pos, Move m1, Move m2) {
1314
1315     Square f1, t1, f2, t2;
1316     Piece p1, p2;
1317     Square ksq;
1318
1319     assert(is_ok(m1));
1320     assert(is_ok(m2));
1321
1322     // Case 1: The moving piece is the same in both moves
1323     f2 = from_sq(m2);
1324     t1 = to_sq(m1);
1325     if (f2 == t1)
1326         return true;
1327
1328     // Case 2: The destination square for m2 was vacated by m1
1329     t2 = to_sq(m2);
1330     f1 = from_sq(m1);
1331     if (t2 == f1)
1332         return true;
1333
1334     // Case 3: Moving through the vacated square
1335     p2 = pos.piece_on(f2);
1336     if (piece_is_slider(p2) && (between_bb(f2, t2) & f1))
1337       return true;
1338
1339     // Case 4: The destination square for m2 is defended by the moving piece in m1
1340     p1 = pos.piece_on(t1);
1341     if (pos.attacks_from(p1, t1) & t2)
1342         return true;
1343
1344     // Case 5: Discovered check, checking piece is the piece moved in m1
1345     ksq = pos.king_square(pos.side_to_move());
1346     if (    piece_is_slider(p1)
1347         && (between_bb(t1, ksq) & f2)
1348         && (pos.attacks_from(p1, t1, pos.pieces() ^ f2) & ksq))
1349         return true;
1350
1351     return false;
1352   }
1353
1354
1355   // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1356   // "plies to mate from the current position". Non-mate scores are unchanged.
1357   // The function is called before storing a value to the transposition table.
1358
1359   Value value_to_tt(Value v, int ply) {
1360
1361     if (v >= VALUE_MATE_IN_MAX_PLY)
1362       return v + ply;
1363
1364     if (v <= VALUE_MATED_IN_MAX_PLY)
1365       return v - ply;
1366
1367     return v;
1368   }
1369
1370
1371   // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
1372   // from the transposition table (where refers to the plies to mate/be mated
1373   // from current position) to "plies to mate/be mated from the root".
1374
1375   Value value_from_tt(Value v, int ply) {
1376
1377     if (v >= VALUE_MATE_IN_MAX_PLY)
1378       return v - ply;
1379
1380     if (v <= VALUE_MATED_IN_MAX_PLY)
1381       return v + ply;
1382
1383     return v;
1384   }
1385
1386
1387   // connected_threat() tests whether it is safe to forward prune a move or if
1388   // is somehow connected to the threat move returned by null search.
1389
1390   bool connected_threat(const Position& pos, Move m, Move threat) {
1391
1392     assert(is_ok(m));
1393     assert(is_ok(threat));
1394     assert(!pos.is_capture_or_promotion(m));
1395     assert(!pos.is_passed_pawn_push(m));
1396
1397     Square mfrom, mto, tfrom, tto;
1398
1399     mfrom = from_sq(m);
1400     mto = to_sq(m);
1401     tfrom = from_sq(threat);
1402     tto = to_sq(threat);
1403
1404     // Case 1: Don't prune moves which move the threatened piece
1405     if (mfrom == tto)
1406         return true;
1407
1408     // Case 2: If the threatened piece has value less than or equal to the
1409     // value of the threatening piece, don't prune moves which defend it.
1410     if (   pos.is_capture(threat)
1411         && (   PieceValue[Mg][pos.piece_on(tfrom)] >= PieceValue[Mg][pos.piece_on(tto)]
1412             || type_of(pos.piece_on(tfrom)) == KING)
1413         && pos.move_attacks_square(m, tto))
1414         return true;
1415
1416     // Case 3: If the moving piece in the threatened move is a slider, don't
1417     // prune safe moves which block its ray.
1418     if (    piece_is_slider(pos.piece_on(tfrom))
1419         && (between_bb(tfrom, tto) & mto)
1420         &&  pos.see_sign(m) >= 0)
1421         return true;
1422
1423     return false;
1424   }
1425
1426
1427   // refine_eval() returns the transposition table score if possible, otherwise
1428   // falls back on static position evaluation.
1429
1430   Value refine_eval(const TTEntry* tte, Value v, Value defaultEval) {
1431
1432       assert(tte);
1433
1434       if (   ((tte->type() & BOUND_LOWER) && v >= defaultEval)
1435           || ((tte->type() & BOUND_UPPER) && v < defaultEval))
1436           return v;
1437
1438       return defaultEval;
1439   }
1440
1441
1442   // When playing with strength handicap choose best move among the MultiPV set
1443   // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1444
1445   Move do_skill_level() {
1446
1447     assert(MultiPV > 1);
1448
1449     static RKISS rk;
1450
1451     // PRNG sequence should be not deterministic
1452     for (int i = Time::now() % 50; i > 0; i--)
1453         rk.rand<unsigned>();
1454
1455     // RootMoves are already sorted by score in descending order
1456     size_t size = std::min(MultiPV, RootMoves.size());
1457     int variance = std::min(RootMoves[0].score - RootMoves[size - 1].score, PawnValueMg);
1458     int weakness = 120 - 2 * SkillLevel;
1459     int max_s = -VALUE_INFINITE;
1460     Move best = MOVE_NONE;
1461
1462     // Choose best move. For each move score we add two terms both dependent on
1463     // weakness, one deterministic and bigger for weaker moves, and one random,
1464     // then we choose the move with the resulting highest score.
1465     for (size_t i = 0; i < size; i++)
1466     {
1467         int s = RootMoves[i].score;
1468
1469         // Don't allow crazy blunders even at very low skills
1470         if (i > 0 && RootMoves[i-1].score > s + 2 * PawnValueMg)
1471             break;
1472
1473         // This is our magic formula
1474         s += (  weakness * int(RootMoves[0].score - s)
1475               + variance * (rk.rand<unsigned>() % weakness)) / 128;
1476
1477         if (s > max_s)
1478         {
1479             max_s = s;
1480             best = RootMoves[i].pv[0];
1481         }
1482     }
1483     return best;
1484   }
1485
1486
1487   // uci_pv() formats PV information according to UCI protocol. UCI requires
1488   // to send all the PV lines also if are still to be searched and so refer to
1489   // the previous search score.
1490
1491   string uci_pv(const Position& pos, int depth, Value alpha, Value beta) {
1492
1493     std::stringstream s;
1494     Time::point elaspsed = Time::now() - SearchTime + 1;
1495     int selDepth = 0;
1496
1497     for (size_t i = 0; i < Threads.size(); i++)
1498         if (Threads[i].maxPly > selDepth)
1499             selDepth = Threads[i].maxPly;
1500
1501     for (size_t i = 0; i < std::min(UCIMultiPV, RootMoves.size()); i++)
1502     {
1503         bool updated = (i <= PVIdx);
1504
1505         if (depth == 1 && !updated)
1506             continue;
1507
1508         int d = (updated ? depth : depth - 1);
1509         Value v = (updated ? RootMoves[i].score : RootMoves[i].prevScore);
1510
1511         if (s.rdbuf()->in_avail())
1512             s << "\n";
1513
1514         s << "info depth " << d
1515           << " seldepth "  << selDepth
1516           << " score "     << (i == PVIdx ? score_to_uci(v, alpha, beta) : score_to_uci(v))
1517           << " nodes "     << pos.nodes_searched()
1518           << " nps "       << pos.nodes_searched() * 1000 / elaspsed
1519           << " time "      << elaspsed
1520           << " multipv "   << i + 1
1521           << " pv";
1522
1523         for (size_t j = 0; RootMoves[i].pv[j] != MOVE_NONE; j++)
1524             s <<  " " << move_to_uci(RootMoves[i].pv[j], Chess960);
1525     }
1526
1527     return s.str();
1528   }
1529
1530 } // namespace
1531
1532
1533 /// RootMove::extract_pv_from_tt() builds a PV by adding moves from the TT table.
1534 /// We consider also failing high nodes and not only BOUND_EXACT nodes so to
1535 /// allow to always have a ponder move even when we fail high at root, and a
1536 /// long PV to print that is important for position analysis.
1537
1538 void RootMove::extract_pv_from_tt(Position& pos) {
1539
1540   StateInfo state[MAX_PLY_PLUS_2], *st = state;
1541   TTEntry* tte;
1542   int ply = 1;
1543   Move m = pv[0];
1544
1545   assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1546
1547   pv.clear();
1548   pv.push_back(m);
1549   pos.do_move(m, *st++);
1550
1551   while (   (tte = TT.probe(pos.key())) != NULL
1552          && (m = tte->move()) != MOVE_NONE // Local copy, TT entry could change
1553          && pos.is_pseudo_legal(m)
1554          && pos.pl_move_is_legal(m, pos.pinned_pieces())
1555          && ply < MAX_PLY
1556          && (!pos.is_draw<false>() || ply < 2))
1557   {
1558       pv.push_back(m);
1559       pos.do_move(m, *st++);
1560       ply++;
1561   }
1562   pv.push_back(MOVE_NONE);
1563
1564   do pos.undo_move(pv[--ply]); while (ply);
1565 }
1566
1567
1568 /// RootMove::insert_pv_in_tt() is called at the end of a search iteration, and
1569 /// inserts the PV back into the TT. This makes sure the old PV moves are searched
1570 /// first, even if the old TT entries have been overwritten.
1571
1572 void RootMove::insert_pv_in_tt(Position& pos) {
1573
1574   StateInfo state[MAX_PLY_PLUS_2], *st = state;
1575   TTEntry* tte;
1576   Key k;
1577   Value v, m = VALUE_NONE;
1578   int ply = 0;
1579
1580   assert(pv[ply] != MOVE_NONE && pos.is_pseudo_legal(pv[ply]));
1581
1582   do {
1583       k = pos.key();
1584       tte = TT.probe(k);
1585
1586       // Don't overwrite existing correct entries
1587       if (!tte || tte->move() != pv[ply])
1588       {
1589           v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1590           TT.store(k, VALUE_NONE, BOUND_NONE, DEPTH_NONE, pv[ply], v, m);
1591       }
1592       pos.do_move(pv[ply], *st++);
1593
1594   } while (pv[++ply] != MOVE_NONE);
1595
1596   do pos.undo_move(pv[--ply]); while (ply);
1597 }
1598
1599
1600 /// Thread::idle_loop() is where the thread is parked when it has no work to do
1601
1602 void Thread::idle_loop() {
1603
1604   // Pointer 'sp_master', if non-NULL, points to the active SplitPoint
1605   // object for which the thread is the master.
1606   const SplitPoint* sp_master = splitPointsCnt ? curSplitPoint : NULL;
1607
1608   assert(!sp_master || (sp_master->master == this && is_searching));
1609
1610   // If this thread is the master of a split point and all slaves have
1611   // finished their work at this split point, return from the idle loop.
1612   while (!sp_master || sp_master->slavesMask)
1613   {
1614       // If we are not searching, wait for a condition to be signaled
1615       // instead of wasting CPU time polling for work.
1616       while (   do_sleep
1617              || do_exit
1618              || (!is_searching && Threads.use_sleeping_threads()))
1619       {
1620           if (do_exit)
1621           {
1622               assert(!sp_master);
1623               return;
1624           }
1625
1626           // Grab the lock to avoid races with Thread::wake_up()
1627           mutex.lock();
1628
1629           // If we are master and all slaves have finished don't go to sleep
1630           if (sp_master && !sp_master->slavesMask)
1631           {
1632               mutex.unlock();
1633               break;
1634           }
1635
1636           // Do sleep after retesting sleep conditions under lock protection, in
1637           // particular we need to avoid a deadlock in case a master thread has,
1638           // in the meanwhile, allocated us and sent the wake_up() call before we
1639           // had the chance to grab the lock.
1640           if (do_sleep || !is_searching)
1641               sleepCondition.wait(mutex);
1642
1643           mutex.unlock();
1644       }
1645
1646       // If this thread has been assigned work, launch a search
1647       if (is_searching)
1648       {
1649           assert(!do_sleep && !do_exit);
1650
1651           Threads.mutex.lock();
1652
1653           assert(is_searching);
1654           SplitPoint* sp = curSplitPoint;
1655
1656           Threads.mutex.unlock();
1657
1658           Stack ss[MAX_PLY_PLUS_2];
1659           Position pos(*sp->pos, this);
1660
1661           memcpy(ss, sp->ss - 1, 4 * sizeof(Stack));
1662           (ss+1)->sp = sp;
1663
1664           sp->mutex.lock();
1665
1666           assert(sp->activePositions[idx] == NULL);
1667
1668           sp->activePositions[idx] = &pos;
1669
1670           if (sp->nodeType == Root)
1671               search<SplitPointRoot>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1672           else if (sp->nodeType == PV)
1673               search<SplitPointPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1674           else if (sp->nodeType == NonPV)
1675               search<SplitPointNonPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1676           else
1677               assert(false);
1678
1679           assert(is_searching);
1680
1681           is_searching = false;
1682           sp->activePositions[idx] = NULL;
1683           sp->slavesMask &= ~(1ULL << idx);
1684           sp->nodes += pos.nodes_searched();
1685
1686           // Wake up master thread so to allow it to return from the idle loop in
1687           // case we are the last slave of the split point.
1688           if (    Threads.use_sleeping_threads()
1689               &&  this != sp->master
1690               && !sp->slavesMask)
1691           {
1692               assert(!sp->master->is_searching);
1693               sp->master->wake_up();
1694           }
1695
1696           // After releasing the lock we cannot access anymore any SplitPoint
1697           // related data in a safe way becuase it could have been released under
1698           // our feet by the sp master. Also accessing other Thread objects is
1699           // unsafe because if we are exiting there is a chance are already freed.
1700           sp->mutex.unlock();
1701       }
1702   }
1703 }
1704
1705
1706 /// check_time() is called by the timer thread when the timer triggers. It is
1707 /// used to print debug info and, more important, to detect when we are out of
1708 /// available time and so stop the search.
1709
1710 void check_time() {
1711
1712   static Time::point lastInfoTime = Time::now();
1713   int64_t nodes = 0; // Workaround silly 'uninitialized' gcc warning
1714
1715   if (Time::now() - lastInfoTime >= 1000)
1716   {
1717       lastInfoTime = Time::now();
1718       dbg_print();
1719   }
1720
1721   if (Limits.ponder)
1722       return;
1723
1724   if (Limits.nodes)
1725   {
1726       Threads.mutex.lock();
1727
1728       nodes = RootPosition.nodes_searched();
1729
1730       // Loop across all split points and sum accumulated SplitPoint nodes plus
1731       // all the currently active slaves positions.
1732       for (size_t i = 0; i < Threads.size(); i++)
1733           for (int j = 0; j < Threads[i].splitPointsCnt; j++)
1734           {
1735               SplitPoint& sp = Threads[i].splitPoints[j];
1736
1737               sp.mutex.lock();
1738
1739               nodes += sp.nodes;
1740               Bitboard sm = sp.slavesMask;
1741               while (sm)
1742               {
1743                   Position* pos = sp.activePositions[pop_lsb(&sm)];
1744                   nodes += pos ? pos->nodes_searched() : 0;
1745               }
1746
1747               sp.mutex.unlock();
1748           }
1749
1750       Threads.mutex.unlock();
1751   }
1752
1753   Time::point elapsed = Time::now() - SearchTime;
1754   bool stillAtFirstMove =    Signals.firstRootMove
1755                          && !Signals.failedLowAtRoot
1756                          &&  elapsed > TimeMgr.available_time();
1757
1758   bool noMoreTime =   elapsed > TimeMgr.maximum_time() - 2 * TimerResolution
1759                    || stillAtFirstMove;
1760
1761   if (   (Limits.use_time_management() && noMoreTime)
1762       || (Limits.movetime && elapsed >= Limits.movetime)
1763       || (Limits.nodes && nodes >= Limits.nodes))
1764       Signals.stop = true;
1765 }