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