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