]> git.sesse.net Git - stockfish/blob - src/search.cpp
Fix some comments in early stop detection
[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-2010 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 <cassert>
21 #include <cmath>
22 #include <cstring>
23 #include <fstream>
24 #include <iostream>
25 #include <sstream>
26 #include <vector>
27
28 #include "book.h"
29 #include "evaluate.h"
30 #include "history.h"
31 #include "misc.h"
32 #include "move.h"
33 #include "movegen.h"
34 #include "movepick.h"
35 #include "lock.h"
36 #include "search.h"
37 #include "timeman.h"
38 #include "thread.h"
39 #include "tt.h"
40 #include "ucioption.h"
41
42 using std::cout;
43 using std::endl;
44
45 namespace {
46
47   // Different node types, used as template parameter
48   enum NodeType { NonPV, PV };
49
50   // Set to true to force running with one thread. Used for debugging.
51   const bool FakeSplit = false;
52
53   // Lookup table to check if a Piece is a slider and its access function
54   const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
55   inline bool piece_is_slider(Piece p) { return Slidings[p]; }
56
57   // ThreadsManager class is used to handle all the threads related stuff like init,
58   // starting, parking and, the most important, launching a slave thread at a split
59   // point. All the access to shared thread data is done through this class.
60
61   class ThreadsManager {
62     /* As long as the single ThreadsManager object is defined as a global we don't
63        need to explicitly initialize to zero its data members because variables with
64        static storage duration are automatically set to zero before enter main()
65     */
66   public:
67     Thread& operator[](int threadID) { return threads[threadID]; }
68     void init_threads();
69     void exit_threads();
70
71     int min_split_depth() const { return minimumSplitDepth; }
72     int active_threads() const { return activeThreads; }
73     void set_active_threads(int cnt) { activeThreads = cnt; }
74
75     void read_uci_options();
76     bool available_thread_exists(int master) const;
77     bool thread_is_available(int slave, int master) const;
78     bool cutoff_at_splitpoint(int threadID) const;
79     void idle_loop(int threadID, SplitPoint* sp);
80
81     template <bool Fake>
82     void split(Position& pos, SearchStack* ss, Value* alpha, const Value beta, Value* bestValue,
83                Depth depth, Move threatMove, int moveCount, MovePicker* mp, bool pvNode);
84   private:
85     Lock mpLock;
86     Depth minimumSplitDepth;
87     int maxThreadsPerSplitPoint;
88     bool useSleepingThreads;
89     int activeThreads;
90     volatile bool allThreadsShouldExit;
91     Thread threads[MAX_THREADS];
92   };
93
94
95   // RootMove struct is used for moves at the root of the tree. For each root
96   // move, we store two scores, a node count, and a PV (really a refutation
97   // in the case of moves which fail low). Value pv_score is normally set at
98   // -VALUE_INFINITE for all non-pv moves, while non_pv_score is computed
99   // according to the order in which moves are returned by MovePicker.
100
101   struct RootMove {
102
103     RootMove();
104     RootMove(const RootMove& rm) { *this = rm; }
105     RootMove& operator=(const RootMove& rm);
106
107     // RootMove::operator<() is the comparison function used when
108     // sorting the moves. A move m1 is considered to be better
109     // than a move m2 if it has an higher pv_score, or if it has
110     // equal pv_score but m1 has the higher non_pv_score. In this way
111     // we are guaranteed that PV moves are always sorted as first.
112     bool operator<(const RootMove& m) const {
113       return pv_score != m.pv_score ? pv_score < m.pv_score
114                                     : non_pv_score < m.non_pv_score;
115     }
116
117     void extract_pv_from_tt(Position& pos);
118     void insert_pv_in_tt(Position& pos);
119     std::string pv_info_to_uci(Position& pos, int depth, int selDepth,
120                                Value alpha, Value beta, int pvIdx);
121     int64_t nodes;
122     Value pv_score;
123     Value non_pv_score;
124     Move pv[PLY_MAX_PLUS_2];
125   };
126
127
128   // RootMoveList struct is just a vector of RootMove objects,
129   // with an handful of methods above the standard ones.
130
131   struct RootMoveList : public std::vector<RootMove> {
132
133     typedef std::vector<RootMove> Base;
134
135     void init(Position& pos, Move searchMoves[]);
136     void sort() { insertion_sort<RootMove, Base::iterator>(begin(), end()); }
137     void sort_multipv(int n) { insertion_sort<RootMove, Base::iterator>(begin(), begin() + n); }
138
139     int bestMoveChanges;
140   };
141
142
143   // Overload operator<<() to make it easier to print moves in a coordinate
144   // notation compatible with UCI protocol.
145   std::ostream& operator<<(std::ostream& os, Move m) {
146
147     bool chess960 = (os.iword(0) != 0); // See set960()
148     return os << move_to_uci(m, chess960);
149   }
150
151
152   // When formatting a move for std::cout we must know if we are in Chess960
153   // or not. To keep using the handy operator<<() on the move the trick is to
154   // embed this flag in the stream itself. Function-like named enum set960 is
155   // used as a custom manipulator and the stream internal general-purpose array,
156   // accessed through ios_base::iword(), is used to pass the flag to the move's
157   // operator<<() that will read it to properly format castling moves.
158   enum set960 {};
159
160   std::ostream& operator<< (std::ostream& os, const set960& f) {
161
162     os.iword(0) = int(f);
163     return os;
164   }
165
166
167   /// Adjustments
168
169   // Step 6. Razoring
170
171   // Maximum depth for razoring
172   const Depth RazorDepth = 4 * ONE_PLY;
173
174   // Dynamic razoring margin based on depth
175   inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
176
177   // Maximum depth for use of dynamic threat detection when null move fails low
178   const Depth ThreatDepth = 5 * ONE_PLY;
179
180   // Step 9. Internal iterative deepening
181
182   // Minimum depth for use of internal iterative deepening
183   const Depth IIDDepth[2] = { 8 * ONE_PLY /* non-PV */, 5 * ONE_PLY /* PV */};
184
185   // At Non-PV nodes we do an internal iterative deepening search
186   // when the static evaluation is bigger then beta - IIDMargin.
187   const Value IIDMargin = Value(0x100);
188
189   // Step 11. Decide the new search depth
190
191   // Extensions. Configurable UCI options. Array index 0 is used at
192   // non-PV nodes, index 1 at PV nodes.
193   Depth CheckExtension[2], PawnPushTo7thExtension[2];
194   Depth PassedPawnExtension[2], PawnEndgameExtension[2];
195
196   // Minimum depth for use of singular extension
197   const Depth SingularExtensionDepth[2] = { 8 * ONE_PLY /* non-PV */, 6 * ONE_PLY /* PV */};
198
199   // Step 12. Futility pruning
200
201   // Futility margin for quiescence search
202   const Value FutilityMarginQS = Value(0x80);
203
204   // Futility lookup tables (initialized at startup) and their access functions
205   Value FutilityMarginsMatrix[16][64]; // [depth][moveNumber]
206   int FutilityMoveCountArray[32];      // [depth]
207
208   inline Value futility_margin(Depth d, int mn) { return d < 7 * ONE_PLY ? FutilityMarginsMatrix[Max(d, 1)][Min(mn, 63)] : 2 * VALUE_INFINITE; }
209   inline int futility_move_count(Depth d) { return d < 16 * ONE_PLY ? FutilityMoveCountArray[d] : 512; }
210
211   // Step 14. Reduced search
212
213   // Reduction lookup tables (initialized at startup) and their access function
214   int8_t ReductionMatrix[2][64][64]; // [pv][depth][moveNumber]
215
216   template <NodeType PV>
217   inline Depth reduction(Depth d, int mn) { return (Depth) ReductionMatrix[PV][Min(d / ONE_PLY, 63)][Min(mn, 63)]; }
218
219   // Easy move margin. An easy move candidate must be at least this much
220   // better than the second best move.
221   const Value EasyMoveMargin = Value(0x200);
222
223
224   /// Namespace variables
225
226   // Book
227   Book OpeningBook;
228
229   // Root move list
230   RootMoveList Rml;
231
232   // MultiPV mode
233   int MultiPV, UCIMultiPV;
234
235   // Time management variables
236   bool StopOnPonderhit, FirstRootMove, StopRequest, QuitRequest, AspirationFailLow;
237   TimeManager TimeMgr;
238   SearchLimits Limits;
239
240   // Log file
241   std::ofstream LogFile;
242
243   // Skill level adjustment
244   int SkillLevel;
245   bool SkillLevelEnabled;
246   RKISS RK;
247
248   // Multi-threads manager
249   ThreadsManager ThreadsMgr;
250
251   // Node counters, used only by thread[0] but try to keep in different cache
252   // lines (64 bytes each) from the heavy multi-thread read accessed variables.
253   bool SendSearchedNodes;
254   int NodesSincePoll;
255   int NodesBetweenPolls = 30000;
256
257   // History table
258   History H;
259
260
261   /// Local functions
262
263   Move id_loop(Position& pos, Move searchMoves[], Move* ponderMove);
264
265   template <NodeType PvNode, bool SpNode, bool Root>
266   Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth);
267
268   template <NodeType PvNode>
269   Value qsearch(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth);
270
271   template <NodeType PvNode>
272   inline Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth) {
273
274     return depth < ONE_PLY ? qsearch<PvNode>(pos, ss, alpha, beta, DEPTH_ZERO)
275                            : search<PvNode, false, false>(pos, ss, alpha, beta, depth);
276   }
277
278   template <NodeType PvNode>
279   Depth extension(const Position& pos, Move m, bool captureOrPromotion, bool moveIsCheck, bool* dangerous);
280
281   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bValue);
282   bool connected_moves(const Position& pos, Move m1, Move m2);
283   Value value_to_tt(Value v, int ply);
284   Value value_from_tt(Value v, int ply);
285   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
286   bool connected_threat(const Position& pos, Move m, Move threat);
287   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
288   void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
289   void update_gains(const Position& pos, Move move, Value before, Value after);
290   void do_skill_level(Move* best, Move* ponder);
291
292   int current_search_time(int set = 0);
293   std::string value_to_uci(Value v);
294   std::string speed_to_uci(int64_t nodes);
295   void poll(const Position& pos);
296   void wait_for_stop_or_ponderhit();
297
298 #if !defined(_MSC_VER)
299   void* init_thread(void* threadID);
300 #else
301   DWORD WINAPI init_thread(LPVOID threadID);
302 #endif
303
304
305   // MovePickerExt is an extended MovePicker class used to choose at compile time
306   // the proper move source according to the type of node.
307   template<bool SpNode, bool Root> struct MovePickerExt;
308
309   // In Root nodes use RootMoveList as source. Score and sort the root moves
310   // before to search them.
311   template<> struct MovePickerExt<false, true> : public MovePicker {
312
313     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss, Value b)
314                  : MovePicker(p, ttm, d, h, ss, b), firstCall(true) {
315       Move move;
316       Value score = VALUE_ZERO;
317
318       // Score root moves using standard ordering used in main search, the moves
319       // are scored according to the order in which they are returned by MovePicker.
320       // This is the second order score that is used to compare the moves when
321       // the first orders pv_score of both moves are equal.
322       while ((move = MovePicker::get_next_move()) != MOVE_NONE)
323           for (rm = Rml.begin(); rm != Rml.end(); ++rm)
324               if (rm->pv[0] == move)
325               {
326                   rm->non_pv_score = score--;
327                   break;
328               }
329
330       Rml.sort();
331       rm = Rml.begin();
332     }
333
334     Move get_next_move() {
335
336       if (!firstCall)
337           ++rm;
338       else
339           firstCall = false;
340
341       return rm != Rml.end() ? rm->pv[0] : MOVE_NONE;
342     }
343
344     RootMoveList::iterator rm;
345     bool firstCall;
346   };
347
348   // In SpNodes use split point's shared MovePicker object as move source
349   template<> struct MovePickerExt<true, false> : public MovePicker {
350
351     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss, Value b)
352                   : MovePicker(p, ttm, d, h, ss, b), mp(ss->sp->mp) {}
353
354     Move get_next_move() { return mp->get_next_move(); }
355
356     RootMoveList::iterator rm; // Dummy, needed to compile
357     MovePicker* mp;
358   };
359
360   // Default case, create and use a MovePicker object as source
361   template<> struct MovePickerExt<false, false> : public MovePicker {
362
363     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss, Value b)
364                   : MovePicker(p, ttm, d, h, ss, b) {}
365
366     RootMoveList::iterator rm; // Dummy, needed to compile
367   };
368
369 } // namespace
370
371
372 /// init_threads() is called during startup. It initializes various lookup tables
373 /// and creates and launches search threads.
374
375 void init_threads() {
376
377   int d;  // depth (ONE_PLY == 2)
378   int hd; // half depth (ONE_PLY == 1)
379   int mc; // moveCount
380
381   // Init reductions array
382   for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
383   {
384       double    pvRed = log(double(hd)) * log(double(mc)) / 3.0;
385       double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
386       ReductionMatrix[PV][hd][mc]    = (int8_t) (   pvRed >= 1.0 ? floor(   pvRed * int(ONE_PLY)) : 0);
387       ReductionMatrix[NonPV][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
388   }
389
390   // Init futility margins array
391   for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
392       FutilityMarginsMatrix[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
393
394   // Init futility move count array
395   for (d = 0; d < 32; d++)
396       FutilityMoveCountArray[d] = int(3.001 + 0.25 * pow(d, 2.0));
397
398   // Create and startup threads
399   ThreadsMgr.init_threads();
400 }
401
402
403 /// exit_threads() is a trampoline to access ThreadsMgr from outside of current file
404 void exit_threads() { ThreadsMgr.exit_threads(); }
405
406
407 /// perft() is our utility to verify move generation. All the legal moves up to
408 /// given depth are generated and counted and the sum returned.
409
410 int64_t perft(Position& pos, Depth depth) {
411
412   MoveStack mlist[MOVES_MAX];
413   StateInfo st;
414   Move m;
415   int64_t sum = 0;
416
417   // Generate all legal moves
418   MoveStack* last = generate<MV_LEGAL>(pos, mlist);
419
420   // If we are at the last ply we don't need to do and undo
421   // the moves, just to count them.
422   if (depth <= ONE_PLY)
423       return int(last - mlist);
424
425   // Loop through all legal moves
426   CheckInfo ci(pos);
427   for (MoveStack* cur = mlist; cur != last; cur++)
428   {
429       m = cur->move;
430       pos.do_move(m, st, ci, pos.move_is_check(m, ci));
431       sum += perft(pos, depth - ONE_PLY);
432       pos.undo_move(m);
433   }
434   return sum;
435 }
436
437
438 /// think() is the external interface to Stockfish's search, and is called when
439 /// the program receives the UCI 'go' command. It initializes various global
440 /// variables, and calls id_loop(). It returns false when a "quit" command is
441 /// received during the search.
442
443 bool think(Position& pos, const SearchLimits& limits, Move searchMoves[]) {
444
445   // Initialize global search-related variables
446   StopOnPonderhit = StopRequest = QuitRequest = AspirationFailLow = SendSearchedNodes = false;
447   NodesSincePoll = 0;
448   current_search_time(get_system_time());
449   Limits = limits;
450   TimeMgr.init(Limits, pos.startpos_ply_counter());
451
452   // Set best NodesBetweenPolls interval to avoid lagging under time pressure
453   if (Limits.maxNodes)
454       NodesBetweenPolls = Min(Limits.maxNodes, 30000);
455   else if (Limits.time && Limits.time < 1000)
456       NodesBetweenPolls = 1000;
457   else if (Limits.time && Limits.time < 5000)
458       NodesBetweenPolls = 5000;
459   else
460       NodesBetweenPolls = 30000;
461
462   // Look for a book move, only during games, not tests
463   if (Limits.useTimeManagement() && Options["OwnBook"].value<bool>())
464   {
465       if (Options["Book File"].value<std::string>() != OpeningBook.name())
466           OpeningBook.open(Options["Book File"].value<std::string>());
467
468       Move bookMove = OpeningBook.get_move(pos, Options["Best Book Move"].value<bool>());
469       if (bookMove != MOVE_NONE)
470       {
471           if (Limits.ponder)
472               wait_for_stop_or_ponderhit();
473
474           cout << "bestmove " << bookMove << endl;
475           return !QuitRequest;
476       }
477   }
478
479   // Read UCI options
480   CheckExtension[1]         = Options["Check Extension (PV nodes)"].value<Depth>();
481   CheckExtension[0]         = Options["Check Extension (non-PV nodes)"].value<Depth>();
482   PawnPushTo7thExtension[1] = Options["Pawn Push to 7th Extension (PV nodes)"].value<Depth>();
483   PawnPushTo7thExtension[0] = Options["Pawn Push to 7th Extension (non-PV nodes)"].value<Depth>();
484   PassedPawnExtension[1]    = Options["Passed Pawn Extension (PV nodes)"].value<Depth>();
485   PassedPawnExtension[0]    = Options["Passed Pawn Extension (non-PV nodes)"].value<Depth>();
486   PawnEndgameExtension[1]   = Options["Pawn Endgame Extension (PV nodes)"].value<Depth>();
487   PawnEndgameExtension[0]   = Options["Pawn Endgame Extension (non-PV nodes)"].value<Depth>();
488   UCIMultiPV                = Options["MultiPV"].value<int>();
489   SkillLevel                = Options["Skill level"].value<int>();
490
491   read_evaluation_uci_options(pos.side_to_move());
492
493   if (Options["Clear Hash"].value<bool>())
494   {
495       Options["Clear Hash"].set_value("false");
496       TT.clear();
497   }
498   TT.set_size(Options["Hash"].value<int>());
499
500   // Do we have to play with skill handicap? In this case enable MultiPV that
501   // we will use behind the scenes to retrieve a set of possible moves.
502   SkillLevelEnabled = (SkillLevel < 20);
503   MultiPV = (SkillLevelEnabled ? Max(UCIMultiPV, 4) : UCIMultiPV);
504
505   // Set the number of active threads
506   ThreadsMgr.read_uci_options();
507   init_eval(ThreadsMgr.active_threads());
508
509   // Wake up needed threads and reset maxPly counter
510   for (int i = 0; i < ThreadsMgr.active_threads(); i++)
511   {
512       ThreadsMgr[i].wake_up();
513       ThreadsMgr[i].maxPly = 0;
514   }
515
516   // Write to log file and keep it open to be accessed during the search
517   if (Options["Use Search Log"].value<bool>())
518   {
519       std::string name = Options["Search Log Filename"].value<std::string>();
520       LogFile.open(name.c_str(), std::ios::out | std::ios::app);
521
522       if (LogFile.is_open())
523           LogFile << "\nSearching: "  << pos.to_fen()
524                   << "\ninfinite: "   << Limits.infinite
525                   << " ponder: "      << Limits.ponder
526                   << " time: "        << Limits.time
527                   << " increment: "   << Limits.increment
528                   << " moves to go: " << Limits.movesToGo
529                   << endl;
530   }
531
532   // We're ready to start thinking. Call the iterative deepening loop function
533   Move ponderMove = MOVE_NONE;
534   Move bestMove = id_loop(pos, searchMoves, &ponderMove);
535
536   cout << "info" << speed_to_uci(pos.nodes_searched()) << endl;
537
538   // Write final search statistics and close log file
539   if (LogFile.is_open())
540   {
541       int t = current_search_time();
542
543       LogFile << "Nodes: "          << pos.nodes_searched()
544               << "\nNodes/second: " << (t > 0 ? pos.nodes_searched() * 1000 / t : 0)
545               << "\nBest move: "    << move_to_san(pos, bestMove);
546
547       StateInfo st;
548       pos.do_move(bestMove, st);
549       LogFile << "\nPonder move: " << move_to_san(pos, ponderMove) << endl;
550       pos.undo_move(bestMove); // Return from think() with unchanged position
551       LogFile.close();
552   }
553
554   // This makes all the threads to go to sleep
555   ThreadsMgr.set_active_threads(1);
556
557   // If we are pondering or in infinite search, we shouldn't print the
558   // best move before we are told to do so.
559   if (!StopRequest && (Limits.ponder || Limits.infinite))
560       wait_for_stop_or_ponderhit();
561
562   // Could be MOVE_NONE when searching on a stalemate position
563   cout << "bestmove " << bestMove;
564
565   // UCI protol is not clear on allowing sending an empty ponder move, instead
566   // it is clear that ponder move is optional. So skip it if empty.
567   if (ponderMove != MOVE_NONE)
568       cout << " ponder " << ponderMove;
569
570   cout << endl;
571
572   return !QuitRequest;
573 }
574
575
576 namespace {
577
578   // id_loop() is the main iterative deepening loop. It calls search() repeatedly
579   // with increasing depth until the allocated thinking time has been consumed,
580   // user stops the search, or the maximum search depth is reached.
581
582   Move id_loop(Position& pos, Move searchMoves[], Move* ponderMove) {
583
584     SearchStack ss[PLY_MAX_PLUS_2];
585     Value bestValues[PLY_MAX_PLUS_2];
586     int bestMoveChanges[PLY_MAX_PLUS_2];
587     int depth, selDepth, aspirationDelta;
588     Value value, alpha, beta;
589     Move bestMove, easyMove, skillBest, skillPonder;
590
591     // Initialize stuff before a new search
592     memset(ss, 0, 4 * sizeof(SearchStack));
593     TT.new_search();
594     H.clear();
595     *ponderMove = bestMove = easyMove = skillBest = skillPonder = MOVE_NONE;
596     depth = aspirationDelta = 0;
597     alpha = -VALUE_INFINITE, beta = VALUE_INFINITE;
598     ss->currentMove = MOVE_NULL; // Hack to skip update_gains()
599
600     // Moves to search are verified and copied
601     Rml.init(pos, searchMoves);
602
603     // Handle special case of searching on a mate/stalemate position
604     if (Rml.size() == 0)
605     {
606         cout << "info depth 0 score "
607              << value_to_uci(pos.is_check() ? -VALUE_MATE : VALUE_DRAW)
608              << endl;
609
610         return MOVE_NONE;
611     }
612
613     // Iterative deepening loop until requested to stop or target depth reached
614     while (!StopRequest && ++depth <= PLY_MAX && (!Limits.maxDepth || depth <= Limits.maxDepth))
615     {
616         Rml.bestMoveChanges = 0;
617         cout << set960(pos.is_chess960()) << "info depth " << depth << endl;
618
619         // Calculate dynamic aspiration window based on previous iterations
620         if (MultiPV == 1 && depth >= 5 && abs(bestValues[depth - 1]) < VALUE_KNOWN_WIN)
621         {
622             int prevDelta1 = bestValues[depth - 1] - bestValues[depth - 2];
623             int prevDelta2 = bestValues[depth - 2] - bestValues[depth - 3];
624
625             aspirationDelta = Min(Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16), 24);
626             aspirationDelta = (aspirationDelta + 7) / 8 * 8; // Round to match grainSize
627
628             alpha = Max(bestValues[depth - 1] - aspirationDelta, -VALUE_INFINITE);
629             beta  = Min(bestValues[depth - 1] + aspirationDelta,  VALUE_INFINITE);
630         }
631
632         // Start with a small aspiration window and, in case of fail high/low,
633         // research with bigger window until not failing high/low anymore.
634         do {
635             // Search starting from ss+1 to allow calling update_gains()
636             value = search<PV, false, true>(pos, ss+1, alpha, beta, depth * ONE_PLY);
637
638             // Write PV back to transposition table in case the relevant entries
639             // have been overwritten during the search.
640             for (int i = 0; i < Min(MultiPV, (int)Rml.size()); i++)
641                 Rml[i].insert_pv_in_tt(pos);
642
643             // Value cannot be trusted. Break out immediately!
644             if (StopRequest)
645                 break;
646
647             assert(value >= alpha);
648
649             // In case of failing high/low increase aspiration window and research,
650             // otherwise exit the fail high/low loop.
651             if (value >= beta)
652             {
653                 beta = Min(beta + aspirationDelta, VALUE_INFINITE);
654                 aspirationDelta += aspirationDelta / 2;
655             }
656             else if (value <= alpha)
657             {
658                 AspirationFailLow = true;
659                 StopOnPonderhit = false;
660
661                 alpha = Max(alpha - aspirationDelta, -VALUE_INFINITE);
662                 aspirationDelta += aspirationDelta / 2;
663             }
664             else
665                 break;
666
667         } while (abs(value) < VALUE_KNOWN_WIN);
668
669         // Collect info about search result
670         bestMove = Rml[0].pv[0];
671         *ponderMove = Rml[0].pv[1];
672         bestValues[depth] = value;
673         bestMoveChanges[depth] = Rml.bestMoveChanges;
674
675         // Do we need to pick now the best and the ponder moves ?
676         if (SkillLevelEnabled && depth == 1 + SkillLevel)
677             do_skill_level(&skillBest, &skillPonder);
678
679         // Retrieve max searched depth among threads
680         selDepth = 0;
681         for (int i = 0; i < ThreadsMgr.active_threads(); i++)
682             if (ThreadsMgr[i].maxPly > selDepth)
683                 selDepth = ThreadsMgr[i].maxPly;
684
685         // Send PV line to GUI and to log file
686         for (int i = 0; i < Min(UCIMultiPV, (int)Rml.size()); i++)
687             cout << Rml[i].pv_info_to_uci(pos, depth, selDepth, alpha, beta, i) << endl;
688
689         if (LogFile.is_open())
690             LogFile << pretty_pv(pos, depth, value, current_search_time(), Rml[0].pv) << endl;
691
692         // Init easyMove after first iteration or drop if differs from the best move
693         if (depth == 1 && (Rml.size() == 1 || Rml[0].pv_score > Rml[1].pv_score + EasyMoveMargin))
694             easyMove = bestMove;
695         else if (bestMove != easyMove)
696             easyMove = MOVE_NONE;
697
698         // Check for some early stop condition
699         if (!StopRequest && Limits.useTimeManagement())
700         {
701             // Stop search early when the last two iterations returned a mate score
702             if (   depth >= 5
703                 && abs(bestValues[depth])     >= VALUE_MATE_IN_PLY_MAX
704                 && abs(bestValues[depth - 1]) >= VALUE_MATE_IN_PLY_MAX)
705                 StopRequest = true;
706
707             // Stop search early if one move seems to be much better than the
708             // others or if there is only a single legal move. Also in the latter
709             // case we search up to some depth anyway to get a proper score.
710             if (   depth >= 7
711                 && easyMove == bestMove
712                 && (   Rml.size() == 1
713                     ||(   Rml[0].nodes > (pos.nodes_searched() * 85) / 100
714                        && current_search_time() > TimeMgr.available_time() / 16)
715                     ||(   Rml[0].nodes > (pos.nodes_searched() * 98) / 100
716                        && current_search_time() > TimeMgr.available_time() / 32)))
717                 StopRequest = true;
718
719             // Take in account some extra time if the best move has changed
720             if (depth > 4 && depth < 50)
721                 TimeMgr.pv_instability(bestMoveChanges[depth], bestMoveChanges[depth - 1]);
722
723             // Stop search if most of available time is already consumed. We probably don't
724             // have enough time to search the first move at the next iteration anyway.
725             if (current_search_time() > (TimeMgr.available_time() * 62) / 100)
726                 StopRequest = true;
727
728             // If we are allowed to ponder do not stop the search now but keep pondering
729             if (StopRequest && Limits.ponder)
730             {
731                 StopRequest = false;
732                 StopOnPonderhit = true;
733             }
734         }
735     }
736
737     // When using skills overwrite best and ponder moves with the sub-optimal ones
738     if (SkillLevelEnabled)
739     {
740         if (skillBest == MOVE_NONE) // Still unassigned ?
741             do_skill_level(&skillBest, &skillPonder);
742
743         bestMove = skillBest;
744         *ponderMove = skillPonder;
745     }
746
747     return bestMove;
748   }
749
750
751   // search<>() is the main search function for both PV and non-PV nodes and for
752   // normal and SplitPoint nodes. When called just after a split point the search
753   // is simpler because we have already probed the hash table, done a null move
754   // search, and searched the first move before splitting, we don't have to repeat
755   // all this work again. We also don't need to store anything to the hash table
756   // here: This is taken care of after we return from the split point.
757
758   template <NodeType PvNode, bool SpNode, bool Root>
759   Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth) {
760
761     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
762     assert(beta > alpha && beta <= VALUE_INFINITE);
763     assert(PvNode || alpha == beta - 1);
764     assert(pos.thread() >= 0 && pos.thread() < ThreadsMgr.active_threads());
765
766     Move movesSearched[MOVES_MAX];
767     int64_t nodes;
768     StateInfo st;
769     const TTEntry *tte;
770     Key posKey;
771     Move ttMove, move, excludedMove, threatMove;
772     Depth ext, newDepth;
773     ValueType vt;
774     Value bestValue, value, oldAlpha;
775     Value refinedValue, nullValue, futilityBase, futilityValueScaled; // Non-PV specific
776     bool isPvMove, isCheck, singularExtensionNode, moveIsCheck, captureOrPromotion, dangerous, isBadCap;
777     int moveCount = 0, playedMoveCount = 0;
778     int threadID = pos.thread();
779     SplitPoint* sp = NULL;
780
781     refinedValue = bestValue = value = -VALUE_INFINITE;
782     oldAlpha = alpha;
783     isCheck = pos.is_check();
784     ss->ply = (ss-1)->ply + 1;
785
786     // Used to send selDepth info to GUI
787     if (PvNode && ThreadsMgr[threadID].maxPly < ss->ply)
788         ThreadsMgr[threadID].maxPly = ss->ply;
789
790     if (SpNode)
791     {
792         sp = ss->sp;
793         tte = NULL;
794         ttMove = excludedMove = MOVE_NONE;
795         threatMove = sp->threatMove;
796         goto split_point_start;
797     }
798     else if (Root)
799         bestValue = alpha;
800
801     // Step 1. Initialize node and poll. Polling can abort search
802     ss->currentMove = ss->bestMove = threatMove = (ss+1)->excludedMove = MOVE_NONE;
803     (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
804     (ss+2)->killers[0] = (ss+2)->killers[1] = (ss+2)->mateKiller = MOVE_NONE;
805
806     if (threadID == 0 && ++NodesSincePoll > NodesBetweenPolls)
807     {
808         NodesSincePoll = 0;
809         poll(pos);
810     }
811
812     // Step 2. Check for aborted search and immediate draw
813     if ((   StopRequest
814          || ThreadsMgr.cutoff_at_splitpoint(threadID)
815          || pos.is_draw()
816          || ss->ply > PLY_MAX) && !Root)
817         return VALUE_DRAW;
818
819     // Step 3. Mate distance pruning
820     alpha = Max(value_mated_in(ss->ply), alpha);
821     beta = Min(value_mate_in(ss->ply+1), beta);
822     if (alpha >= beta)
823         return alpha;
824
825     // Step 4. Transposition table lookup
826     // We don't want the score of a partial search to overwrite a previous full search
827     // TT value, so we use a different position key in case of an excluded move.
828     excludedMove = ss->excludedMove;
829     posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
830
831     tte = TT.retrieve(posKey);
832     ttMove = tte ? tte->move() : MOVE_NONE;
833
834     // At PV nodes we check for exact scores, while at non-PV nodes we check for
835     // a fail high/low. Biggest advantage at probing at PV nodes is to have a
836     // smooth experience in analysis mode.
837     if (   !Root
838         && tte
839         && (PvNode ? tte->depth() >= depth && tte->type() == VALUE_TYPE_EXACT
840                    : ok_to_use_TT(tte, depth, beta, ss->ply)))
841     {
842         TT.refresh(tte);
843         ss->bestMove = ttMove; // Can be MOVE_NONE
844         return value_from_tt(tte->value(), ss->ply);
845     }
846
847     // Step 5. Evaluate the position statically and update parent's gain statistics
848     if (isCheck)
849         ss->eval = ss->evalMargin = VALUE_NONE;
850     else if (tte)
851     {
852         assert(tte->static_value() != VALUE_NONE);
853
854         ss->eval = tte->static_value();
855         ss->evalMargin = tte->static_value_margin();
856         refinedValue = refine_eval(tte, ss->eval, ss->ply);
857     }
858     else
859     {
860         refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
861         TT.store(posKey, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
862     }
863
864     // Save gain for the parent non-capture move
865     update_gains(pos, (ss-1)->currentMove, (ss-1)->eval, ss->eval);
866
867     // Step 6. Razoring (is omitted in PV nodes)
868     if (   !PvNode
869         &&  depth < RazorDepth
870         && !isCheck
871         &&  refinedValue + razor_margin(depth) < beta
872         &&  ttMove == MOVE_NONE
873         &&  abs(beta) < VALUE_MATE_IN_PLY_MAX
874         && !pos.has_pawn_on_7th(pos.side_to_move()))
875     {
876         Value rbeta = beta - razor_margin(depth);
877         Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
878         if (v < rbeta)
879             // Logically we should return (v + razor_margin(depth)), but
880             // surprisingly this did slightly weaker in tests.
881             return v;
882     }
883
884     // Step 7. Static null move pruning (is omitted in PV nodes)
885     // We're betting that the opponent doesn't have a move that will reduce
886     // the score by more than futility_margin(depth) if we do a null move.
887     if (   !PvNode
888         && !ss->skipNullMove
889         &&  depth < RazorDepth
890         && !isCheck
891         &&  refinedValue - futility_margin(depth, 0) >= beta
892         &&  abs(beta) < VALUE_MATE_IN_PLY_MAX
893         &&  pos.non_pawn_material(pos.side_to_move()))
894         return refinedValue - futility_margin(depth, 0);
895
896     // Step 8. Null move search with verification search (is omitted in PV nodes)
897     if (   !PvNode
898         && !ss->skipNullMove
899         &&  depth > ONE_PLY
900         && !isCheck
901         &&  refinedValue >= beta
902         &&  abs(beta) < VALUE_MATE_IN_PLY_MAX
903         &&  pos.non_pawn_material(pos.side_to_move()))
904     {
905         ss->currentMove = MOVE_NULL;
906
907         // Null move dynamic reduction based on depth
908         int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);
909
910         // Null move dynamic reduction based on value
911         if (refinedValue - PawnValueMidgame > beta)
912             R++;
913
914         pos.do_null_move(st);
915         (ss+1)->skipNullMove = true;
916         nullValue = -search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY);
917         (ss+1)->skipNullMove = false;
918         pos.undo_null_move();
919
920         if (nullValue >= beta)
921         {
922             // Do not return unproven mate scores
923             if (nullValue >= VALUE_MATE_IN_PLY_MAX)
924                 nullValue = beta;
925
926             if (depth < 6 * ONE_PLY)
927                 return nullValue;
928
929             // Do verification search at high depths
930             ss->skipNullMove = true;
931             Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY);
932             ss->skipNullMove = false;
933
934             if (v >= beta)
935                 return nullValue;
936         }
937         else
938         {
939             // The null move failed low, which means that we may be faced with
940             // some kind of threat. If the previous move was reduced, check if
941             // the move that refuted the null move was somehow connected to the
942             // move which was reduced. If a connection is found, return a fail
943             // low score (which will cause the reduced move to fail high in the
944             // parent node, which will trigger a re-search with full depth).
945             threatMove = (ss+1)->bestMove;
946
947             if (   depth < ThreatDepth
948                 && (ss-1)->reduction
949                 && threatMove != MOVE_NONE
950                 && connected_moves(pos, (ss-1)->currentMove, threatMove))
951                 return beta - 1;
952         }
953     }
954
955     // Step 9. Internal iterative deepening
956     if (   depth >= IIDDepth[PvNode]
957         && ttMove == MOVE_NONE
958         && (PvNode || (!isCheck && ss->eval + IIDMargin >= beta)))
959     {
960         Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
961
962         ss->skipNullMove = true;
963         search<PvNode>(pos, ss, alpha, beta, d);
964         ss->skipNullMove = false;
965
966         ttMove = ss->bestMove;
967         tte = TT.retrieve(posKey);
968     }
969
970 split_point_start: // At split points actual search starts from here
971
972     // Initialize a MovePicker object for the current position
973     MovePickerExt<SpNode, Root> mp(pos, ttMove, depth, H, ss, (PvNode ? -VALUE_INFINITE : beta));
974     CheckInfo ci(pos);
975     ss->bestMove = MOVE_NONE;
976     futilityBase = ss->eval + ss->evalMargin;
977     singularExtensionNode =   !Root
978                            && !SpNode
979                            && depth >= SingularExtensionDepth[PvNode]
980                            && tte
981                            && tte->move()
982                            && !excludedMove // Do not allow recursive singular extension search
983                            && (tte->type() & VALUE_TYPE_LOWER)
984                            && tte->depth() >= depth - 3 * ONE_PLY;
985     if (SpNode)
986     {
987         lock_grab(&(sp->lock));
988         bestValue = sp->bestValue;
989     }
990
991     // Step 10. Loop through moves
992     // Loop through all legal moves until no moves remain or a beta cutoff occurs
993     while (   bestValue < beta
994            && (move = mp.get_next_move()) != MOVE_NONE
995            && !ThreadsMgr.cutoff_at_splitpoint(threadID))
996     {
997       assert(move_is_ok(move));
998
999       if (SpNode)
1000       {
1001           moveCount = ++sp->moveCount;
1002           lock_release(&(sp->lock));
1003       }
1004       else if (move == excludedMove)
1005           continue;
1006       else
1007           moveCount++;
1008
1009       if (Root)
1010       {
1011           // This is used by time management
1012           FirstRootMove = (moveCount == 1);
1013
1014           // Save the current node count before the move is searched
1015           nodes = pos.nodes_searched();
1016
1017           // If it's time to send nodes info, do it here where we have the
1018           // correct accumulated node counts searched by each thread.
1019           if (SendSearchedNodes)
1020           {
1021               SendSearchedNodes = false;
1022               cout << "info" << speed_to_uci(pos.nodes_searched()) << endl;
1023           }
1024
1025           if (current_search_time() > 2000)
1026               cout << "info currmove " << move
1027                    << " currmovenumber " << moveCount << endl;
1028       }
1029
1030       // At Root and at first iteration do a PV search on all the moves to score root moves
1031       isPvMove = (PvNode && moveCount <= (Root ? depth <= ONE_PLY ? 1000 : MultiPV : 1));
1032       moveIsCheck = pos.move_is_check(move, ci);
1033       captureOrPromotion = pos.move_is_capture_or_promotion(move);
1034
1035       // Step 11. Decide the new search depth
1036       ext = extension<PvNode>(pos, move, captureOrPromotion, moveIsCheck, &dangerous);
1037
1038       // Singular extension search. If all moves but one fail low on a search of
1039       // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
1040       // is singular and should be extended. To verify this we do a reduced search
1041       // on all the other moves but the ttMove, if result is lower than ttValue minus
1042       // a margin then we extend ttMove.
1043       if (   singularExtensionNode
1044           && move == tte->move()
1045           && ext < ONE_PLY)
1046       {
1047           Value ttValue = value_from_tt(tte->value(), ss->ply);
1048
1049           if (abs(ttValue) < VALUE_KNOWN_WIN)
1050           {
1051               Value rBeta = ttValue - int(depth);
1052               ss->excludedMove = move;
1053               ss->skipNullMove = true;
1054               Value v = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
1055               ss->skipNullMove = false;
1056               ss->excludedMove = MOVE_NONE;
1057               ss->bestMove = MOVE_NONE;
1058               if (v < rBeta)
1059                   ext = ONE_PLY;
1060           }
1061       }
1062
1063       // Update current move (this must be done after singular extension search)
1064       ss->currentMove = move;
1065       newDepth = depth - ONE_PLY + ext;
1066
1067       // Step 12. Futility pruning (is omitted in PV nodes)
1068       if (   !PvNode
1069           && !captureOrPromotion
1070           && !isCheck
1071           && !dangerous
1072           &&  move != ttMove
1073           && !move_is_castle(move))
1074       {
1075           // Move count based pruning
1076           if (   moveCount >= futility_move_count(depth)
1077               && (!threatMove || !connected_threat(pos, move, threatMove))
1078               && bestValue > VALUE_MATED_IN_PLY_MAX) // FIXME bestValue is racy
1079           {
1080               if (SpNode)
1081                   lock_grab(&(sp->lock));
1082
1083               continue;
1084           }
1085
1086           // Value based pruning
1087           // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
1088           // but fixing this made program slightly weaker.
1089           Depth predictedDepth = newDepth - reduction<NonPV>(depth, moveCount);
1090           futilityValueScaled =  futilityBase + futility_margin(predictedDepth, moveCount)
1091                                + H.gain(pos.piece_on(move_from(move)), move_to(move));
1092
1093           if (futilityValueScaled < beta)
1094           {
1095               if (SpNode)
1096               {
1097                   lock_grab(&(sp->lock));
1098                   if (futilityValueScaled > sp->bestValue)
1099                       sp->bestValue = bestValue = futilityValueScaled;
1100               }
1101               else if (futilityValueScaled > bestValue)
1102                   bestValue = futilityValueScaled;
1103
1104               continue;
1105           }
1106
1107           // Prune moves with negative SEE at low depths
1108           if (   predictedDepth < 2 * ONE_PLY
1109               && bestValue > VALUE_MATED_IN_PLY_MAX
1110               && pos.see_sign(move) < 0)
1111           {
1112               if (SpNode)
1113                   lock_grab(&(sp->lock));
1114
1115               continue;
1116           }
1117       }
1118
1119       // Bad capture detection. Will be used by prob-cut search
1120       isBadCap =   depth >= 3 * ONE_PLY
1121                 && depth < 8 * ONE_PLY
1122                 && captureOrPromotion
1123                 && move != ttMove
1124                 && !dangerous
1125                 && !move_is_promotion(move)
1126                 &&  abs(alpha) < VALUE_MATE_IN_PLY_MAX
1127                 &&  pos.see_sign(move) < 0;
1128
1129       // Step 13. Make the move
1130       pos.do_move(move, st, ci, moveIsCheck);
1131
1132       if (!SpNode && !captureOrPromotion)
1133           movesSearched[playedMoveCount++] = move;
1134
1135       // Step extra. pv search (only in PV nodes)
1136       // The first move in list is the expected PV
1137       if (isPvMove)
1138       {
1139           // Aspiration window is disabled in multi-pv case
1140           if (Root && MultiPV > 1)
1141               alpha = -VALUE_INFINITE;
1142
1143           value = -search<PV>(pos, ss+1, -beta, -alpha, newDepth);
1144       }
1145       else
1146       {
1147           // Step 14. Reduced depth search
1148           // If the move fails high will be re-searched at full depth.
1149           bool doFullDepthSearch = true;
1150           alpha = SpNode ? sp->alpha : alpha;
1151
1152           if (    depth >= 3 * ONE_PLY
1153               && !captureOrPromotion
1154               && !dangerous
1155               && !move_is_castle(move)
1156               &&  ss->killers[0] != move
1157               &&  ss->killers[1] != move)
1158           {
1159               ss->reduction = reduction<PvNode>(depth, moveCount);
1160               if (ss->reduction)
1161               {
1162                   alpha = SpNode ? sp->alpha : alpha;
1163                   Depth d = newDepth - ss->reduction;
1164                   value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
1165
1166                   doFullDepthSearch = (value > alpha);
1167               }
1168               ss->reduction = DEPTH_ZERO; // Restore original reduction
1169           }
1170
1171           // Probcut search for bad captures. If a reduced search returns a value
1172           // very below beta then we can (almost) safely prune the bad capture.
1173           if (isBadCap)
1174           {
1175               ss->reduction = 3 * ONE_PLY;
1176               Value rAlpha = alpha - 300;
1177               Depth d = newDepth - ss->reduction;
1178               value = -search<NonPV>(pos, ss+1, -(rAlpha+1), -rAlpha, d);
1179               doFullDepthSearch = (value > rAlpha);
1180               ss->reduction = DEPTH_ZERO; // Restore original reduction
1181           }
1182
1183           // Step 15. Full depth search
1184           if (doFullDepthSearch)
1185           {
1186               alpha = SpNode ? sp->alpha : alpha;
1187               value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
1188
1189               // Step extra. pv search (only in PV nodes)
1190               // Search only for possible new PV nodes, if instead value >= beta then
1191               // parent node fails low with value <= alpha and tries another move.
1192               if (PvNode && value > alpha && (Root || value < beta))
1193                   value = -search<PV>(pos, ss+1, -beta, -alpha, newDepth);
1194           }
1195       }
1196
1197       // Step 16. Undo move
1198       pos.undo_move(move);
1199
1200       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1201
1202       // Step 17. Check for new best move
1203       if (SpNode)
1204       {
1205           lock_grab(&(sp->lock));
1206           bestValue = sp->bestValue;
1207           alpha = sp->alpha;
1208       }
1209
1210       if (value > bestValue && !(SpNode && ThreadsMgr.cutoff_at_splitpoint(threadID)))
1211       {
1212           bestValue = value;
1213
1214           if (SpNode)
1215               sp->bestValue = value;
1216
1217           if (!Root && value > alpha)
1218           {
1219               if (PvNode && value < beta) // We want always alpha < beta
1220               {
1221                   alpha = value;
1222
1223                   if (SpNode)
1224                       sp->alpha = value;
1225               }
1226               else if (SpNode)
1227                   sp->betaCutoff = true;
1228
1229               if (value == value_mate_in(ss->ply + 1))
1230                   ss->mateKiller = move;
1231
1232               ss->bestMove = move;
1233
1234               if (SpNode)
1235                   sp->ss->bestMove = move;
1236           }
1237       }
1238
1239       if (Root)
1240       {
1241           // Finished searching the move. If StopRequest is true, the search
1242           // was aborted because the user interrupted the search or because we
1243           // ran out of time. In this case, the return value of the search cannot
1244           // be trusted, and we break out of the loop without updating the best
1245           // move and/or PV.
1246           if (StopRequest)
1247               break;
1248
1249           // Remember searched nodes counts for this move
1250           mp.rm->nodes += pos.nodes_searched() - nodes;
1251
1252           // PV move or new best move ?
1253           if (isPvMove || value > alpha)
1254           {
1255               // Update PV
1256               ss->bestMove = move;
1257               mp.rm->pv_score = value;
1258               mp.rm->extract_pv_from_tt(pos);
1259
1260               // We record how often the best move has been changed in each
1261               // iteration. This information is used for time management: When
1262               // the best move changes frequently, we allocate some more time.
1263               if (!isPvMove && MultiPV == 1)
1264                   Rml.bestMoveChanges++;
1265
1266               Rml.sort_multipv(moveCount);
1267
1268               // Update alpha. In multi-pv we don't use aspiration window, so
1269               // set alpha equal to minimum score among the PV lines.
1270               if (MultiPV > 1)
1271                   alpha = Rml[Min(moveCount, MultiPV) - 1].pv_score; // FIXME why moveCount?
1272               else if (value > alpha)
1273                   alpha = value;
1274           }
1275           else
1276               mp.rm->pv_score = -VALUE_INFINITE;
1277
1278       } // Root
1279
1280       // Step 18. Check for split
1281       if (   !Root
1282           && !SpNode
1283           && depth >= ThreadsMgr.min_split_depth()
1284           && ThreadsMgr.active_threads() > 1
1285           && bestValue < beta
1286           && ThreadsMgr.available_thread_exists(threadID)
1287           && !StopRequest
1288           && !ThreadsMgr.cutoff_at_splitpoint(threadID))
1289           ThreadsMgr.split<FakeSplit>(pos, ss, &alpha, beta, &bestValue, depth,
1290                                       threatMove, moveCount, &mp, PvNode);
1291     }
1292
1293     // Step 19. Check for mate and stalemate
1294     // All legal moves have been searched and if there are
1295     // no legal moves, it must be mate or stalemate.
1296     // If one move was excluded return fail low score.
1297     if (!SpNode && !moveCount)
1298         return excludedMove ? oldAlpha : isCheck ? value_mated_in(ss->ply) : VALUE_DRAW;
1299
1300     // Step 20. Update tables
1301     // If the search is not aborted, update the transposition table,
1302     // history counters, and killer moves.
1303     if (!SpNode && !StopRequest && !ThreadsMgr.cutoff_at_splitpoint(threadID))
1304     {
1305         move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1306         vt   = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1307              : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1308
1309         TT.store(posKey, value_to_tt(bestValue, ss->ply), vt, depth, move, ss->eval, ss->evalMargin);
1310
1311         // Update killers and history only for non capture moves that fails high
1312         if (    bestValue >= beta
1313             && !pos.move_is_capture_or_promotion(move))
1314         {
1315             if (move != ss->killers[0])
1316             {
1317                 ss->killers[1] = ss->killers[0];
1318                 ss->killers[0] = move;
1319             }
1320             update_history(pos, move, depth, movesSearched, playedMoveCount);
1321         }
1322     }
1323
1324     if (SpNode)
1325     {
1326         // Here we have the lock still grabbed
1327         sp->slaves[threadID] = 0;
1328         sp->nodes += pos.nodes_searched();
1329         lock_release(&(sp->lock));
1330     }
1331
1332     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1333
1334     return bestValue;
1335   }
1336
1337   // qsearch() is the quiescence search function, which is called by the main
1338   // search function when the remaining depth is zero (or, to be more precise,
1339   // less than ONE_PLY).
1340
1341   template <NodeType PvNode>
1342   Value qsearch(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth) {
1343
1344     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1345     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1346     assert(PvNode || alpha == beta - 1);
1347     assert(depth <= 0);
1348     assert(pos.thread() >= 0 && pos.thread() < ThreadsMgr.active_threads());
1349
1350     StateInfo st;
1351     Move ttMove, move;
1352     Value bestValue, value, evalMargin, futilityValue, futilityBase;
1353     bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1354     const TTEntry* tte;
1355     Depth ttDepth;
1356     Value oldAlpha = alpha;
1357
1358     ss->bestMove = ss->currentMove = MOVE_NONE;
1359     ss->ply = (ss-1)->ply + 1;
1360
1361     // Check for an instant draw or maximum ply reached
1362     if (ss->ply > PLY_MAX || pos.is_draw())
1363         return VALUE_DRAW;
1364
1365     // Decide whether or not to include checks, this fixes also the type of
1366     // TT entry depth that we are going to use. Note that in qsearch we use
1367     // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1368     isCheck = pos.is_check();
1369     ttDepth = (isCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1370
1371     // Transposition table lookup. At PV nodes, we don't use the TT for
1372     // pruning, but only for move ordering.
1373     tte = TT.retrieve(pos.get_key());
1374     ttMove = (tte ? tte->move() : MOVE_NONE);
1375
1376     if (!PvNode && tte && ok_to_use_TT(tte, ttDepth, beta, ss->ply))
1377     {
1378         ss->bestMove = ttMove; // Can be MOVE_NONE
1379         return value_from_tt(tte->value(), ss->ply);
1380     }
1381
1382     // Evaluate the position statically
1383     if (isCheck)
1384     {
1385         bestValue = futilityBase = -VALUE_INFINITE;
1386         ss->eval = evalMargin = VALUE_NONE;
1387         enoughMaterial = false;
1388     }
1389     else
1390     {
1391         if (tte)
1392         {
1393             assert(tte->static_value() != VALUE_NONE);
1394
1395             evalMargin = tte->static_value_margin();
1396             ss->eval = bestValue = tte->static_value();
1397         }
1398         else
1399             ss->eval = bestValue = evaluate(pos, evalMargin);
1400
1401         update_gains(pos, (ss-1)->currentMove, (ss-1)->eval, ss->eval);
1402
1403         // Stand pat. Return immediately if static value is at least beta
1404         if (bestValue >= beta)
1405         {
1406             if (!tte)
1407                 TT.store(pos.get_key(), value_to_tt(bestValue, ss->ply), VALUE_TYPE_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1408
1409             return bestValue;
1410         }
1411
1412         if (PvNode && bestValue > alpha)
1413             alpha = bestValue;
1414
1415         // Futility pruning parameters, not needed when in check
1416         futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1417         enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1418     }
1419
1420     // Initialize a MovePicker object for the current position, and prepare
1421     // to search the moves. Because the depth is <= 0 here, only captures,
1422     // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1423     // be generated.
1424     MovePicker mp(pos, ttMove, depth, H);
1425     CheckInfo ci(pos);
1426
1427     // Loop through the moves until no moves remain or a beta cutoff occurs
1428     while (   alpha < beta
1429            && (move = mp.get_next_move()) != MOVE_NONE)
1430     {
1431       assert(move_is_ok(move));
1432
1433       moveIsCheck = pos.move_is_check(move, ci);
1434
1435       // Futility pruning
1436       if (   !PvNode
1437           && !isCheck
1438           && !moveIsCheck
1439           &&  move != ttMove
1440           &&  enoughMaterial
1441           && !move_is_promotion(move)
1442           && !pos.move_is_passed_pawn_push(move))
1443       {
1444           futilityValue =  futilityBase
1445                          + pos.endgame_value_of_piece_on(move_to(move))
1446                          + (move_is_ep(move) ? PawnValueEndgame : VALUE_ZERO);
1447
1448           if (futilityValue < alpha)
1449           {
1450               if (futilityValue > bestValue)
1451                   bestValue = futilityValue;
1452               continue;
1453           }
1454
1455           // Prune moves with negative or equal SEE
1456           if (   futilityBase < beta
1457               && depth < DEPTH_ZERO
1458               && pos.see(move) <= 0)
1459               continue;
1460       }
1461
1462       // Detect non-capture evasions that are candidate to be pruned
1463       evasionPrunable =   isCheck
1464                        && bestValue > VALUE_MATED_IN_PLY_MAX
1465                        && !pos.move_is_capture(move)
1466                        && !pos.can_castle(pos.side_to_move());
1467
1468       // Don't search moves with negative SEE values
1469       if (   !PvNode
1470           && (!isCheck || evasionPrunable)
1471           &&  move != ttMove
1472           && !move_is_promotion(move)
1473           &&  pos.see_sign(move) < 0)
1474           continue;
1475
1476       // Don't search useless checks
1477       if (   !PvNode
1478           && !isCheck
1479           &&  moveIsCheck
1480           &&  move != ttMove
1481           && !pos.move_is_capture_or_promotion(move)
1482           &&  ss->eval + PawnValueMidgame / 4 < beta
1483           && !check_is_dangerous(pos, move, futilityBase, beta, &bestValue))
1484       {
1485           if (ss->eval + PawnValueMidgame / 4 > bestValue)
1486               bestValue = ss->eval + PawnValueMidgame / 4;
1487
1488           continue;
1489       }
1490
1491       // Update current move
1492       ss->currentMove = move;
1493
1494       // Make and search the move
1495       pos.do_move(move, st, ci, moveIsCheck);
1496       value = -qsearch<PvNode>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1497       pos.undo_move(move);
1498
1499       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1500
1501       // New best move?
1502       if (value > bestValue)
1503       {
1504           bestValue = value;
1505           if (value > alpha)
1506           {
1507               alpha = value;
1508               ss->bestMove = move;
1509           }
1510        }
1511     }
1512
1513     // All legal moves have been searched. A special case: If we're in check
1514     // and no legal moves were found, it is checkmate.
1515     if (isCheck && bestValue == -VALUE_INFINITE)
1516         return value_mated_in(ss->ply);
1517
1518     // Update transposition table
1519     ValueType vt = (bestValue <= oldAlpha ? VALUE_TYPE_UPPER : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT);
1520     TT.store(pos.get_key(), value_to_tt(bestValue, ss->ply), vt, ttDepth, ss->bestMove, ss->eval, evalMargin);
1521
1522     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1523
1524     return bestValue;
1525   }
1526
1527
1528   // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1529   // bestValue is updated only when returning false because in that case move
1530   // will be pruned.
1531
1532   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bestValue)
1533   {
1534     Bitboard b, occ, oldAtt, newAtt, kingAtt;
1535     Square from, to, ksq, victimSq;
1536     Piece pc;
1537     Color them;
1538     Value futilityValue, bv = *bestValue;
1539
1540     from = move_from(move);
1541     to = move_to(move);
1542     them = opposite_color(pos.side_to_move());
1543     ksq = pos.king_square(them);
1544     kingAtt = pos.attacks_from<KING>(ksq);
1545     pc = pos.piece_on(from);
1546
1547     occ = pos.occupied_squares() & ~(1ULL << from) & ~(1ULL << ksq);
1548     oldAtt = pos.attacks_from(pc, from, occ);
1549     newAtt = pos.attacks_from(pc,   to, occ);
1550
1551     // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1552     b = kingAtt & ~pos.pieces_of_color(them) & ~newAtt & ~(1ULL << to);
1553
1554     if (!(b && (b & (b - 1))))
1555         return true;
1556
1557     // Rule 2. Queen contact check is very dangerous
1558     if (   type_of_piece(pc) == QUEEN
1559         && bit_is_set(kingAtt, to))
1560         return true;
1561
1562     // Rule 3. Creating new double threats with checks
1563     b = pos.pieces_of_color(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1564
1565     while (b)
1566     {
1567         victimSq = pop_1st_bit(&b);
1568         futilityValue = futilityBase + pos.endgame_value_of_piece_on(victimSq);
1569
1570         // Note that here we generate illegal "double move"!
1571         if (   futilityValue >= beta
1572             && pos.see_sign(make_move(from, victimSq)) >= 0)
1573             return true;
1574
1575         if (futilityValue > bv)
1576             bv = futilityValue;
1577     }
1578
1579     // Update bestValue only if check is not dangerous (because we will prune the move)
1580     *bestValue = bv;
1581     return false;
1582   }
1583
1584
1585   // connected_moves() tests whether two moves are 'connected' in the sense
1586   // that the first move somehow made the second move possible (for instance
1587   // if the moving piece is the same in both moves). The first move is assumed
1588   // to be the move that was made to reach the current position, while the
1589   // second move is assumed to be a move from the current position.
1590
1591   bool connected_moves(const Position& pos, Move m1, Move m2) {
1592
1593     Square f1, t1, f2, t2;
1594     Piece p;
1595
1596     assert(m1 && move_is_ok(m1));
1597     assert(m2 && move_is_ok(m2));
1598
1599     // Case 1: The moving piece is the same in both moves
1600     f2 = move_from(m2);
1601     t1 = move_to(m1);
1602     if (f2 == t1)
1603         return true;
1604
1605     // Case 2: The destination square for m2 was vacated by m1
1606     t2 = move_to(m2);
1607     f1 = move_from(m1);
1608     if (t2 == f1)
1609         return true;
1610
1611     // Case 3: Moving through the vacated square
1612     if (   piece_is_slider(pos.piece_on(f2))
1613         && bit_is_set(squares_between(f2, t2), f1))
1614       return true;
1615
1616     // Case 4: The destination square for m2 is defended by the moving piece in m1
1617     p = pos.piece_on(t1);
1618     if (bit_is_set(pos.attacks_from(p, t1), t2))
1619         return true;
1620
1621     // Case 5: Discovered check, checking piece is the piece moved in m1
1622     if (    piece_is_slider(p)
1623         &&  bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
1624         && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
1625     {
1626         // discovered_check_candidates() works also if the Position's side to
1627         // move is the opposite of the checking piece.
1628         Color them = opposite_color(pos.side_to_move());
1629         Bitboard dcCandidates = pos.discovered_check_candidates(them);
1630
1631         if (bit_is_set(dcCandidates, f2))
1632             return true;
1633     }
1634     return false;
1635   }
1636
1637
1638   // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1639   // "plies to mate from the current ply".  Non-mate scores are unchanged.
1640   // The function is called before storing a value to the transposition table.
1641
1642   Value value_to_tt(Value v, int ply) {
1643
1644     if (v >= VALUE_MATE_IN_PLY_MAX)
1645       return v + ply;
1646
1647     if (v <= VALUE_MATED_IN_PLY_MAX)
1648       return v - ply;
1649
1650     return v;
1651   }
1652
1653
1654   // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score from
1655   // the transposition table to a mate score corrected for the current ply.
1656
1657   Value value_from_tt(Value v, int ply) {
1658
1659     if (v >= VALUE_MATE_IN_PLY_MAX)
1660       return v - ply;
1661
1662     if (v <= VALUE_MATED_IN_PLY_MAX)
1663       return v + ply;
1664
1665     return v;
1666   }
1667
1668
1669   // extension() decides whether a move should be searched with normal depth,
1670   // or with extended depth. Certain classes of moves (checking moves, in
1671   // particular) are searched with bigger depth than ordinary moves and in
1672   // any case are marked as 'dangerous'. Note that also if a move is not
1673   // extended, as example because the corresponding UCI option is set to zero,
1674   // the move is marked as 'dangerous' so, at least, we avoid to prune it.
1675   template <NodeType PvNode>
1676   Depth extension(const Position& pos, Move m, bool captureOrPromotion,
1677                   bool moveIsCheck, bool* dangerous) {
1678
1679     assert(m != MOVE_NONE);
1680
1681     Depth result = DEPTH_ZERO;
1682     *dangerous = moveIsCheck;
1683
1684     if (moveIsCheck && pos.see_sign(m) >= 0)
1685         result += CheckExtension[PvNode];
1686
1687     if (pos.type_of_piece_on(move_from(m)) == PAWN)
1688     {
1689         Color c = pos.side_to_move();
1690         if (relative_rank(c, move_to(m)) == RANK_7)
1691         {
1692             result += PawnPushTo7thExtension[PvNode];
1693             *dangerous = true;
1694         }
1695         if (pos.pawn_is_passed(c, move_to(m)))
1696         {
1697             result += PassedPawnExtension[PvNode];
1698             *dangerous = true;
1699         }
1700     }
1701
1702     if (   captureOrPromotion
1703         && pos.type_of_piece_on(move_to(m)) != PAWN
1704         && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
1705             - pos.midgame_value_of_piece_on(move_to(m)) == VALUE_ZERO)
1706         && !move_is_special(m))
1707     {
1708         result += PawnEndgameExtension[PvNode];
1709         *dangerous = true;
1710     }
1711
1712     return Min(result, ONE_PLY);
1713   }
1714
1715
1716   // connected_threat() tests whether it is safe to forward prune a move or if
1717   // is somehow connected to the threat move returned by null search.
1718
1719   bool connected_threat(const Position& pos, Move m, Move threat) {
1720
1721     assert(move_is_ok(m));
1722     assert(threat && move_is_ok(threat));
1723     assert(!pos.move_is_check(m));
1724     assert(!pos.move_is_capture_or_promotion(m));
1725     assert(!pos.move_is_passed_pawn_push(m));
1726
1727     Square mfrom, mto, tfrom, tto;
1728
1729     mfrom = move_from(m);
1730     mto = move_to(m);
1731     tfrom = move_from(threat);
1732     tto = move_to(threat);
1733
1734     // Case 1: Don't prune moves which move the threatened piece
1735     if (mfrom == tto)
1736         return true;
1737
1738     // Case 2: If the threatened piece has value less than or equal to the
1739     // value of the threatening piece, don't prune moves which defend it.
1740     if (   pos.move_is_capture(threat)
1741         && (   pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
1742             || pos.type_of_piece_on(tfrom) == KING)
1743         && pos.move_attacks_square(m, tto))
1744         return true;
1745
1746     // Case 3: If the moving piece in the threatened move is a slider, don't
1747     // prune safe moves which block its ray.
1748     if (   piece_is_slider(pos.piece_on(tfrom))
1749         && bit_is_set(squares_between(tfrom, tto), mto)
1750         && pos.see_sign(m) >= 0)
1751         return true;
1752
1753     return false;
1754   }
1755
1756
1757   // ok_to_use_TT() returns true if a transposition table score
1758   // can be used at a given point in search.
1759
1760   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
1761
1762     Value v = value_from_tt(tte->value(), ply);
1763
1764     return   (   tte->depth() >= depth
1765               || v >= Max(VALUE_MATE_IN_PLY_MAX, beta)
1766               || v < Min(VALUE_MATED_IN_PLY_MAX, beta))
1767
1768           && (   ((tte->type() & VALUE_TYPE_LOWER) && v >= beta)
1769               || ((tte->type() & VALUE_TYPE_UPPER) && v < beta));
1770   }
1771
1772
1773   // refine_eval() returns the transposition table score if
1774   // possible otherwise falls back on static position evaluation.
1775
1776   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1777
1778       assert(tte);
1779
1780       Value v = value_from_tt(tte->value(), ply);
1781
1782       if (   ((tte->type() & VALUE_TYPE_LOWER) && v >= defaultEval)
1783           || ((tte->type() & VALUE_TYPE_UPPER) && v < defaultEval))
1784           return v;
1785
1786       return defaultEval;
1787   }
1788
1789
1790   // update_history() registers a good move that produced a beta-cutoff
1791   // in history and marks as failures all the other moves of that ply.
1792
1793   void update_history(const Position& pos, Move move, Depth depth,
1794                       Move movesSearched[], int moveCount) {
1795     Move m;
1796     Value bonus = Value(int(depth) * int(depth));
1797
1798     H.update(pos.piece_on(move_from(move)), move_to(move), bonus);
1799
1800     for (int i = 0; i < moveCount - 1; i++)
1801     {
1802         m = movesSearched[i];
1803
1804         assert(m != move);
1805
1806         H.update(pos.piece_on(move_from(m)), move_to(m), -bonus);
1807     }
1808   }
1809
1810
1811   // update_gains() updates the gains table of a non-capture move given
1812   // the static position evaluation before and after the move.
1813
1814   void update_gains(const Position& pos, Move m, Value before, Value after) {
1815
1816     if (   m != MOVE_NULL
1817         && before != VALUE_NONE
1818         && after != VALUE_NONE
1819         && pos.captured_piece_type() == PIECE_TYPE_NONE
1820         && !move_is_special(m))
1821         H.update_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
1822   }
1823
1824
1825   // current_search_time() returns the number of milliseconds which have passed
1826   // since the beginning of the current search.
1827
1828   int current_search_time(int set) {
1829
1830     static int searchStartTime;
1831
1832     if (set)
1833         searchStartTime = set;
1834
1835     return get_system_time() - searchStartTime;
1836   }
1837
1838
1839   // value_to_uci() converts a value to a string suitable for use with the UCI
1840   // protocol specifications:
1841   //
1842   // cp <x>     The score from the engine's point of view in centipawns.
1843   // mate <y>   Mate in y moves, not plies. If the engine is getting mated
1844   //            use negative values for y.
1845
1846   std::string value_to_uci(Value v) {
1847
1848     std::stringstream s;
1849
1850     if (abs(v) < VALUE_MATE - PLY_MAX * ONE_PLY)
1851         s << "cp " << int(v) * 100 / int(PawnValueMidgame); // Scale to centipawns
1852     else
1853         s << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
1854
1855     return s.str();
1856   }
1857
1858
1859   // speed_to_uci() returns a string with time stats of current search suitable
1860   // to be sent to UCI gui.
1861
1862   std::string speed_to_uci(int64_t nodes) {
1863
1864     std::stringstream s;
1865     int t = current_search_time();
1866
1867     s << " nodes " << nodes
1868       << " nps "   << (t > 0 ? int(nodes * 1000 / t) : 0)
1869       << " time "  << t;
1870
1871     return s.str();
1872   }
1873
1874
1875   // poll() performs two different functions: It polls for user input, and it
1876   // looks at the time consumed so far and decides if it's time to abort the
1877   // search.
1878
1879   void poll(const Position& pos) {
1880
1881     static int lastInfoTime;
1882     int t = current_search_time();
1883
1884     //  Poll for input
1885     if (input_available())
1886     {
1887         // We are line oriented, don't read single chars
1888         std::string command;
1889
1890         if (!std::getline(std::cin, command) || command == "quit")
1891         {
1892             // Quit the program as soon as possible
1893             Limits.ponder = false;
1894             QuitRequest = StopRequest = true;
1895             return;
1896         }
1897         else if (command == "stop")
1898         {
1899             // Stop calculating as soon as possible, but still send the "bestmove"
1900             // and possibly the "ponder" token when finishing the search.
1901             Limits.ponder = false;
1902             StopRequest = true;
1903         }
1904         else if (command == "ponderhit")
1905         {
1906             // The opponent has played the expected move. GUI sends "ponderhit" if
1907             // we were told to ponder on the same move the opponent has played. We
1908             // should continue searching but switching from pondering to normal search.
1909             Limits.ponder = false;
1910
1911             if (StopOnPonderhit)
1912                 StopRequest = true;
1913         }
1914     }
1915
1916     // Print search information
1917     if (t < 1000)
1918         lastInfoTime = 0;
1919
1920     else if (lastInfoTime > t)
1921         // HACK: Must be a new search where we searched less than
1922         // NodesBetweenPolls nodes during the first second of search.
1923         lastInfoTime = 0;
1924
1925     else if (t - lastInfoTime >= 1000)
1926     {
1927         lastInfoTime = t;
1928
1929         dbg_print_mean();
1930         dbg_print_hit_rate();
1931
1932         // Send info on searched nodes as soon as we return to root
1933         SendSearchedNodes = true;
1934     }
1935
1936     // Should we stop the search?
1937     if (Limits.ponder)
1938         return;
1939
1940     bool stillAtFirstMove =    FirstRootMove
1941                            && !AspirationFailLow
1942                            &&  t > TimeMgr.available_time();
1943
1944     bool noMoreTime =   t > TimeMgr.maximum_time()
1945                      || stillAtFirstMove;
1946
1947     if (   (Limits.useTimeManagement() && noMoreTime)
1948         || (Limits.maxTime && t >= Limits.maxTime)
1949         || (Limits.maxNodes && pos.nodes_searched() >= Limits.maxNodes)) // FIXME
1950         StopRequest = true;
1951   }
1952
1953
1954   // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
1955   // while the program is pondering. The point is to work around a wrinkle in
1956   // the UCI protocol: When pondering, the engine is not allowed to give a
1957   // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
1958   // We simply wait here until one of these commands is sent, and return,
1959   // after which the bestmove and pondermove will be printed.
1960
1961   void wait_for_stop_or_ponderhit() {
1962
1963     std::string command;
1964
1965     // Wait for a command from stdin
1966     while (   std::getline(std::cin, command)
1967            && command != "ponderhit" && command != "stop" && command != "quit") {};
1968
1969     if (command != "ponderhit" && command != "stop")
1970         QuitRequest = true; // Must be "quit" or getline() returned false
1971   }
1972
1973
1974   // init_thread() is the function which is called when a new thread is
1975   // launched. It simply calls the idle_loop() function with the supplied
1976   // threadID. There are two versions of this function; one for POSIX
1977   // threads and one for Windows threads.
1978
1979 #if !defined(_MSC_VER)
1980
1981   void* init_thread(void* threadID) {
1982
1983     ThreadsMgr.idle_loop(*(int*)threadID, NULL);
1984     return NULL;
1985   }
1986
1987 #else
1988
1989   DWORD WINAPI init_thread(LPVOID threadID) {
1990
1991     ThreadsMgr.idle_loop(*(int*)threadID, NULL);
1992     return 0;
1993   }
1994
1995 #endif
1996
1997
1998   /// The ThreadsManager class
1999
2000
2001   // read_uci_options() updates number of active threads and other internal
2002   // parameters according to the UCI options values. It is called before
2003   // to start a new search.
2004
2005   void ThreadsManager::read_uci_options() {
2006
2007     maxThreadsPerSplitPoint = Options["Maximum Number of Threads per Split Point"].value<int>();
2008     minimumSplitDepth       = Options["Minimum Split Depth"].value<int>() * ONE_PLY;
2009     useSleepingThreads      = Options["Use Sleeping Threads"].value<bool>();
2010     activeThreads           = Options["Threads"].value<int>();
2011   }
2012
2013
2014   // idle_loop() is where the threads are parked when they have no work to do.
2015   // The parameter 'sp', if non-NULL, is a pointer to an active SplitPoint
2016   // object for which the current thread is the master.
2017
2018   void ThreadsManager::idle_loop(int threadID, SplitPoint* sp) {
2019
2020     assert(threadID >= 0 && threadID < MAX_THREADS);
2021
2022     int i;
2023     bool allFinished;
2024
2025     while (true)
2026     {
2027         // Slave threads can exit as soon as AllThreadsShouldExit raises,
2028         // master should exit as last one.
2029         if (allThreadsShouldExit)
2030         {
2031             assert(!sp);
2032             threads[threadID].state = THREAD_TERMINATED;
2033             return;
2034         }
2035
2036         // If we are not thinking, wait for a condition to be signaled
2037         // instead of wasting CPU time polling for work.
2038         while (   threadID >= activeThreads
2039                || threads[threadID].state == THREAD_INITIALIZING
2040                || (useSleepingThreads && threads[threadID].state == THREAD_AVAILABLE))
2041         {
2042             assert(!sp || useSleepingThreads);
2043             assert(threadID != 0 || useSleepingThreads);
2044
2045             if (threads[threadID].state == THREAD_INITIALIZING)
2046                 threads[threadID].state = THREAD_AVAILABLE;
2047
2048             // Grab the lock to avoid races with Thread::wake_up()
2049             lock_grab(&threads[threadID].sleepLock);
2050
2051             // If we are master and all slaves have finished do not go to sleep
2052             for (i = 0; sp && i < activeThreads && !sp->slaves[i]; i++) {}
2053             allFinished = (i == activeThreads);
2054
2055             if (allFinished || allThreadsShouldExit)
2056             {
2057                 lock_release(&threads[threadID].sleepLock);
2058                 break;
2059             }
2060
2061             // Do sleep here after retesting sleep conditions
2062             if (threadID >= activeThreads || threads[threadID].state == THREAD_AVAILABLE)
2063                 cond_wait(&threads[threadID].sleepCond, &threads[threadID].sleepLock);
2064
2065             lock_release(&threads[threadID].sleepLock);
2066         }
2067
2068         // If this thread has been assigned work, launch a search
2069         if (threads[threadID].state == THREAD_WORKISWAITING)
2070         {
2071             assert(!allThreadsShouldExit);
2072
2073             threads[threadID].state = THREAD_SEARCHING;
2074
2075             // Copy split point position and search stack and call search()
2076             // with SplitPoint template parameter set to true.
2077             SearchStack ss[PLY_MAX_PLUS_2];
2078             SplitPoint* tsp = threads[threadID].splitPoint;
2079             Position pos(*tsp->pos, threadID);
2080
2081             memcpy(ss, tsp->ss - 1, 4 * sizeof(SearchStack));
2082             (ss+1)->sp = tsp;
2083
2084             if (tsp->pvNode)
2085                 search<PV, true, false>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2086             else
2087                 search<NonPV, true, false>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2088
2089             assert(threads[threadID].state == THREAD_SEARCHING);
2090
2091             threads[threadID].state = THREAD_AVAILABLE;
2092
2093             // Wake up master thread so to allow it to return from the idle loop in
2094             // case we are the last slave of the split point.
2095             if (   useSleepingThreads
2096                 && threadID != tsp->master
2097                 && threads[tsp->master].state == THREAD_AVAILABLE)
2098                 threads[tsp->master].wake_up();
2099         }
2100
2101         // If this thread is the master of a split point and all slaves have
2102         // finished their work at this split point, return from the idle loop.
2103         for (i = 0; sp && i < activeThreads && !sp->slaves[i]; i++) {}
2104         allFinished = (i == activeThreads);
2105
2106         if (allFinished)
2107         {
2108             // Because sp->slaves[] is reset under lock protection,
2109             // be sure sp->lock has been released before to return.
2110             lock_grab(&(sp->lock));
2111             lock_release(&(sp->lock));
2112
2113             // In helpful master concept a master can help only a sub-tree, and
2114             // because here is all finished is not possible master is booked.
2115             assert(threads[threadID].state == THREAD_AVAILABLE);
2116
2117             threads[threadID].state = THREAD_SEARCHING;
2118             return;
2119         }
2120     }
2121   }
2122
2123
2124   // init_threads() is called during startup. Initializes locks and condition
2125   // variables and launches all threads sending them immediately to sleep.
2126
2127   void ThreadsManager::init_threads() {
2128
2129     int i, arg[MAX_THREADS];
2130     bool ok;
2131
2132     // This flag is needed to properly end the threads when program exits
2133     allThreadsShouldExit = false;
2134
2135     // Threads will sent to sleep as soon as created, only main thread is kept alive
2136     activeThreads = 1;
2137
2138     lock_init(&mpLock);
2139
2140     for (i = 0; i < MAX_THREADS; i++)
2141     {
2142         // Initialize thread and split point locks
2143         lock_init(&threads[i].sleepLock);
2144         cond_init(&threads[i].sleepCond);
2145
2146         for (int j = 0; j < MAX_ACTIVE_SPLIT_POINTS; j++)
2147             lock_init(&(threads[i].splitPoints[j].lock));
2148
2149         // All threads but first should be set to THREAD_INITIALIZING
2150         threads[i].state = (i == 0 ? THREAD_SEARCHING : THREAD_INITIALIZING);
2151     }
2152
2153     // Create and startup the threads
2154     for (i = 1; i < MAX_THREADS; i++)
2155     {
2156         arg[i] = i;
2157
2158 #if !defined(_MSC_VER)
2159         pthread_t pthread[1];
2160         ok = (pthread_create(pthread, NULL, init_thread, (void*)(&arg[i])) == 0);
2161         pthread_detach(pthread[0]);
2162 #else
2163         ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&arg[i]), 0, NULL) != NULL);
2164 #endif
2165         if (!ok)
2166         {
2167             cout << "Failed to create thread number " << i << endl;
2168             exit(EXIT_FAILURE);
2169         }
2170
2171         // Wait until the thread has finished launching and is gone to sleep
2172         while (threads[i].state == THREAD_INITIALIZING) {}
2173     }
2174   }
2175
2176
2177   // exit_threads() is called when the program exits. It makes all the
2178   // helper threads exit cleanly.
2179
2180   void ThreadsManager::exit_threads() {
2181
2182     // Force the woken up threads to exit idle_loop() and hence terminate
2183     allThreadsShouldExit = true;
2184
2185     for (int i = 0; i < MAX_THREADS; i++)
2186     {
2187         // Wake up all the threads and waits for termination
2188         if (i != 0)
2189         {
2190             threads[i].wake_up();
2191             while (threads[i].state != THREAD_TERMINATED) {}
2192         }
2193
2194         // Now we can safely destroy the locks and wait conditions
2195         lock_destroy(&threads[i].sleepLock);
2196         cond_destroy(&threads[i].sleepCond);
2197
2198         for (int j = 0; j < MAX_ACTIVE_SPLIT_POINTS; j++)
2199             lock_destroy(&(threads[i].splitPoints[j].lock));
2200     }
2201
2202     lock_destroy(&mpLock);
2203   }
2204
2205
2206   // cutoff_at_splitpoint() checks whether a beta cutoff has occurred in
2207   // the thread's currently active split point, or in some ancestor of
2208   // the current split point.
2209
2210   bool ThreadsManager::cutoff_at_splitpoint(int threadID) const {
2211
2212     assert(threadID >= 0 && threadID < activeThreads);
2213
2214     SplitPoint* sp = threads[threadID].splitPoint;
2215
2216     for ( ; sp && !sp->betaCutoff; sp = sp->parent) {}
2217     return sp != NULL;
2218   }
2219
2220
2221   // thread_is_available() checks whether the thread with threadID "slave" is
2222   // available to help the thread with threadID "master" at a split point. An
2223   // obvious requirement is that "slave" must be idle. With more than two
2224   // threads, this is not by itself sufficient:  If "slave" is the master of
2225   // some active split point, it is only available as a slave to the other
2226   // threads which are busy searching the split point at the top of "slave"'s
2227   // split point stack (the "helpful master concept" in YBWC terminology).
2228
2229   bool ThreadsManager::thread_is_available(int slave, int master) const {
2230
2231     assert(slave >= 0 && slave < activeThreads);
2232     assert(master >= 0 && master < activeThreads);
2233     assert(activeThreads > 1);
2234
2235     if (threads[slave].state != THREAD_AVAILABLE || slave == master)
2236         return false;
2237
2238     // Make a local copy to be sure doesn't change under our feet
2239     int localActiveSplitPoints = threads[slave].activeSplitPoints;
2240
2241     // No active split points means that the thread is available as
2242     // a slave for any other thread.
2243     if (localActiveSplitPoints == 0 || activeThreads == 2)
2244         return true;
2245
2246     // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2247     // that is known to be > 0, instead of threads[slave].activeSplitPoints that
2248     // could have been set to 0 by another thread leading to an out of bound access.
2249     if (threads[slave].splitPoints[localActiveSplitPoints - 1].slaves[master])
2250         return true;
2251
2252     return false;
2253   }
2254
2255
2256   // available_thread_exists() tries to find an idle thread which is available as
2257   // a slave for the thread with threadID "master".
2258
2259   bool ThreadsManager::available_thread_exists(int master) const {
2260
2261     assert(master >= 0 && master < activeThreads);
2262     assert(activeThreads > 1);
2263
2264     for (int i = 0; i < activeThreads; i++)
2265         if (thread_is_available(i, master))
2266             return true;
2267
2268     return false;
2269   }
2270
2271
2272   // split() does the actual work of distributing the work at a node between
2273   // several available threads. If it does not succeed in splitting the
2274   // node (because no idle threads are available, or because we have no unused
2275   // split point objects), the function immediately returns. If splitting is
2276   // possible, a SplitPoint object is initialized with all the data that must be
2277   // copied to the helper threads and we tell our helper threads that they have
2278   // been assigned work. This will cause them to instantly leave their idle loops and
2279   // call search().When all threads have returned from search() then split() returns.
2280
2281   template <bool Fake>
2282   void ThreadsManager::split(Position& pos, SearchStack* ss, Value* alpha, const Value beta,
2283                              Value* bestValue, Depth depth, Move threatMove,
2284                              int moveCount, MovePicker* mp, bool pvNode) {
2285     assert(pos.is_ok());
2286     assert(*bestValue >= -VALUE_INFINITE);
2287     assert(*bestValue <= *alpha);
2288     assert(*alpha < beta);
2289     assert(beta <= VALUE_INFINITE);
2290     assert(depth > DEPTH_ZERO);
2291     assert(pos.thread() >= 0 && pos.thread() < activeThreads);
2292     assert(activeThreads > 1);
2293
2294     int i, master = pos.thread();
2295     Thread& masterThread = threads[master];
2296
2297     lock_grab(&mpLock);
2298
2299     // If no other thread is available to help us, or if we have too many
2300     // active split points, don't split.
2301     if (   !available_thread_exists(master)
2302         || masterThread.activeSplitPoints >= MAX_ACTIVE_SPLIT_POINTS)
2303     {
2304         lock_release(&mpLock);
2305         return;
2306     }
2307
2308     // Pick the next available split point object from the split point stack
2309     SplitPoint& splitPoint = masterThread.splitPoints[masterThread.activeSplitPoints++];
2310
2311     // Initialize the split point object
2312     splitPoint.parent = masterThread.splitPoint;
2313     splitPoint.master = master;
2314     splitPoint.betaCutoff = false;
2315     splitPoint.depth = depth;
2316     splitPoint.threatMove = threatMove;
2317     splitPoint.alpha = *alpha;
2318     splitPoint.beta = beta;
2319     splitPoint.pvNode = pvNode;
2320     splitPoint.bestValue = *bestValue;
2321     splitPoint.mp = mp;
2322     splitPoint.moveCount = moveCount;
2323     splitPoint.pos = &pos;
2324     splitPoint.nodes = 0;
2325     splitPoint.ss = ss;
2326     for (i = 0; i < activeThreads; i++)
2327         splitPoint.slaves[i] = 0;
2328
2329     masterThread.splitPoint = &splitPoint;
2330
2331     // If we are here it means we are not available
2332     assert(masterThread.state != THREAD_AVAILABLE);
2333
2334     int workersCnt = 1; // At least the master is included
2335
2336     // Allocate available threads setting state to THREAD_BOOKED
2337     for (i = 0; !Fake && i < activeThreads && workersCnt < maxThreadsPerSplitPoint; i++)
2338         if (thread_is_available(i, master))
2339         {
2340             threads[i].state = THREAD_BOOKED;
2341             threads[i].splitPoint = &splitPoint;
2342             splitPoint.slaves[i] = 1;
2343             workersCnt++;
2344         }
2345
2346     assert(Fake || workersCnt > 1);
2347
2348     // We can release the lock because slave threads are already booked and master is not available
2349     lock_release(&mpLock);
2350
2351     // Tell the threads that they have work to do. This will make them leave
2352     // their idle loop.
2353     for (i = 0; i < activeThreads; i++)
2354         if (i == master || splitPoint.slaves[i])
2355         {
2356             assert(i == master || threads[i].state == THREAD_BOOKED);
2357
2358             threads[i].state = THREAD_WORKISWAITING; // This makes the slave to exit from idle_loop()
2359
2360             if (useSleepingThreads && i != master)
2361                 threads[i].wake_up();
2362         }
2363
2364     // Everything is set up. The master thread enters the idle loop, from
2365     // which it will instantly launch a search, because its state is
2366     // THREAD_WORKISWAITING.  We send the split point as a second parameter to the
2367     // idle loop, which means that the main thread will return from the idle
2368     // loop when all threads have finished their work at this split point.
2369     idle_loop(master, &splitPoint);
2370
2371     // We have returned from the idle loop, which means that all threads are
2372     // finished. Update alpha and bestValue, and return.
2373     lock_grab(&mpLock);
2374
2375     *alpha = splitPoint.alpha;
2376     *bestValue = splitPoint.bestValue;
2377     masterThread.activeSplitPoints--;
2378     masterThread.splitPoint = splitPoint.parent;
2379     pos.set_nodes_searched(pos.nodes_searched() + splitPoint.nodes);
2380
2381     lock_release(&mpLock);
2382   }
2383
2384
2385   /// RootMove and RootMoveList method's definitions
2386
2387   RootMove::RootMove() {
2388
2389     nodes = 0;
2390     pv_score = non_pv_score = -VALUE_INFINITE;
2391     pv[0] = MOVE_NONE;
2392   }
2393
2394   RootMove& RootMove::operator=(const RootMove& rm) {
2395
2396     const Move* src = rm.pv;
2397     Move* dst = pv;
2398
2399     // Avoid a costly full rm.pv[] copy
2400     do *dst++ = *src; while (*src++ != MOVE_NONE);
2401
2402     nodes = rm.nodes;
2403     pv_score = rm.pv_score;
2404     non_pv_score = rm.non_pv_score;
2405     return *this;
2406   }
2407
2408   // extract_pv_from_tt() builds a PV by adding moves from the transposition table.
2409   // We consider also failing high nodes and not only VALUE_TYPE_EXACT nodes. This
2410   // allow to always have a ponder move even when we fail high at root and also a
2411   // long PV to print that is important for position analysis.
2412
2413   void RootMove::extract_pv_from_tt(Position& pos) {
2414
2415     StateInfo state[PLY_MAX_PLUS_2], *st = state;
2416     TTEntry* tte;
2417     int ply = 1;
2418
2419     assert(pv[0] != MOVE_NONE && pos.move_is_legal(pv[0]));
2420
2421     pos.do_move(pv[0], *st++);
2422
2423     while (   (tte = TT.retrieve(pos.get_key())) != NULL
2424            && tte->move() != MOVE_NONE
2425            && pos.move_is_legal(tte->move())
2426            && ply < PLY_MAX
2427            && (!pos.is_draw() || ply < 2))
2428     {
2429         pv[ply] = tte->move();
2430         pos.do_move(pv[ply++], *st++);
2431     }
2432     pv[ply] = MOVE_NONE;
2433
2434     do pos.undo_move(pv[--ply]); while (ply);
2435   }
2436
2437   // insert_pv_in_tt() is called at the end of a search iteration, and inserts
2438   // the PV back into the TT. This makes sure the old PV moves are searched
2439   // first, even if the old TT entries have been overwritten.
2440
2441   void RootMove::insert_pv_in_tt(Position& pos) {
2442
2443     StateInfo state[PLY_MAX_PLUS_2], *st = state;
2444     TTEntry* tte;
2445     Key k;
2446     Value v, m = VALUE_NONE;
2447     int ply = 0;
2448
2449     assert(pv[0] != MOVE_NONE && pos.move_is_legal(pv[0]));
2450
2451     do {
2452         k = pos.get_key();
2453         tte = TT.retrieve(k);
2454
2455         // Don't overwrite existing correct entries
2456         if (!tte || tte->move() != pv[ply])
2457         {
2458             v = (pos.is_check() ? VALUE_NONE : evaluate(pos, m));
2459             TT.store(k, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, pv[ply], v, m);
2460         }
2461         pos.do_move(pv[ply], *st++);
2462
2463     } while (pv[++ply] != MOVE_NONE);
2464
2465     do pos.undo_move(pv[--ply]); while (ply);
2466   }
2467
2468   // pv_info_to_uci() returns a string with information on the current PV line
2469   // formatted according to UCI specification.
2470
2471   std::string RootMove::pv_info_to_uci(Position& pos, int depth, int selDepth, Value alpha,
2472                                        Value beta, int pvIdx) {
2473     std::stringstream s;
2474
2475     s << "info depth " << depth
2476       << " seldepth " << selDepth
2477       << " multipv " << pvIdx + 1
2478       << " score " << value_to_uci(pv_score)
2479       << (pv_score >= beta ? " lowerbound" : pv_score <= alpha ? " upperbound" : "")
2480       << speed_to_uci(pos.nodes_searched())
2481       << " pv ";
2482
2483     for (Move* m = pv; *m != MOVE_NONE; m++)
2484         s << *m << " ";
2485
2486     return s.str();
2487   }
2488
2489
2490   void RootMoveList::init(Position& pos, Move searchMoves[]) {
2491
2492     MoveStack mlist[MOVES_MAX];
2493     Move* sm;
2494
2495     clear();
2496     bestMoveChanges = 0;
2497
2498     // Generate all legal moves and add them to RootMoveList
2499     MoveStack* last = generate<MV_LEGAL>(pos, mlist);
2500     for (MoveStack* cur = mlist; cur != last; cur++)
2501     {
2502         // If we have a searchMoves[] list then verify cur->move
2503         // is in the list before to add it.
2504         for (sm = searchMoves; *sm && *sm != cur->move; sm++) {}
2505
2506         if (searchMoves[0] && *sm != cur->move)
2507             continue;
2508
2509         RootMove rm;
2510         rm.pv[0] = cur->move;
2511         rm.pv[1] = MOVE_NONE;
2512         rm.pv_score = -VALUE_INFINITE;
2513         push_back(rm);
2514     }
2515   }
2516
2517
2518   // When playing with strength handicap choose best move among the MultiPV set
2519   // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
2520   void do_skill_level(Move* best, Move* ponder) {
2521
2522     assert(MultiPV > 1);
2523
2524     // Rml list is already sorted by pv_score in descending order
2525     int s;
2526     int max_s = -VALUE_INFINITE;
2527     int size = Min(MultiPV, (int)Rml.size());
2528     int max = Rml[0].pv_score;
2529     int var = Min(max - Rml[size - 1].pv_score, PawnValueMidgame);
2530     int wk = 120 - 2 * SkillLevel;
2531
2532     // PRNG sequence should be non deterministic
2533     for (int i = abs(get_system_time() % 50); i > 0; i--)
2534         RK.rand<unsigned>();
2535
2536     // Choose best move. For each move's score we add two terms both dependent
2537     // on wk, one deterministic and bigger for weaker moves, and one random,
2538     // then we choose the move with the resulting highest score.
2539     for (int i = 0; i < size; i++)
2540     {
2541         s = Rml[i].pv_score;
2542
2543         // Don't allow crazy blunders even at very low skills
2544         if (i > 0 && Rml[i-1].pv_score > s + EasyMoveMargin)
2545             break;
2546
2547         // This is our magical formula
2548         s += ((max - s) * wk + var * (RK.rand<unsigned>() % wk)) / 128;
2549
2550         if (s > max_s)
2551         {
2552             max_s = s;
2553             *best = Rml[i].pv[0];
2554             *ponder = Rml[i].pv[1];
2555         }
2556     }
2557   }
2558
2559 } // namespace