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