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