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