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