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