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