]> git.sesse.net Git - stockfish/blob - src/search.cpp
857aaff87ea9fd1d0812fcd2519f560ab1adf4fd
[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-2009 Marco Costalba
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
21 ////
22 //// Includes
23 ////
24
25 #include <cassert>
26 #include <cmath>
27 #include <cstring>
28 #include <fstream>
29 #include <iostream>
30 #include <sstream>
31
32 #include "book.h"
33 #include "evaluate.h"
34 #include "history.h"
35 #include "misc.h"
36 #include "movegen.h"
37 #include "movepick.h"
38 #include "lock.h"
39 #include "san.h"
40 #include "search.h"
41 #include "thread.h"
42 #include "tt.h"
43 #include "ucioption.h"
44
45 using std::cout;
46 using std::endl;
47
48 ////
49 //// Local definitions
50 ////
51
52 namespace {
53
54   /// Types
55
56
57   // ThreadsManager class is used to handle all the threads related stuff in search,
58   // init, starting, parking and, the most important, launching a slave thread at a
59   // split point are what this class does. All the access to shared thread data is
60   // done through this class, so that we avoid using global variables instead.
61
62   class ThreadsManager {
63     /* As long as the single ThreadsManager object is defined as a global we don't
64        need to explicitly initialize to zero its data members because variables with
65        static storage duration are automatically set to zero before enter main()
66     */
67   public:
68     void init_threads();
69     void exit_threads();
70
71     int active_threads() const { return ActiveThreads; }
72     void set_active_threads(int newActiveThreads) { ActiveThreads = newActiveThreads; }
73     void set_stop_request(int threadID) { threads[threadID].stop = true; }
74     void incrementNodeCounter(int threadID) { threads[threadID].nodes++; }
75     void incrementBetaCounter(Color us, Depth d, int threadID) { threads[threadID].betaCutOffs[us] += unsigned(d); }
76     void print_current_line(SearchStack ss[], int ply, int threadID);
77
78     void resetNodeCounters();
79     void resetBetaCounters();
80     int64_t nodes_searched() const;
81     void get_beta_counters(Color us, int64_t& our, int64_t& their) const;
82     bool idle_thread_exists(int master) const;
83     bool thread_is_available(int slave, int master) const;
84     bool thread_should_stop(int threadID);
85     void wake_sleeping_threads();
86     void put_threads_to_sleep();
87     void idle_loop(int threadID, SplitPoint* waitSp);
88     bool split(const Position& pos, SearchStack* ss, int ply, Value* alpha, Value* beta, Value* bestValue,
89                const Value futilityValue, Depth depth, int* moves, MovePicker* mp, int master, bool pvNode);
90
91   private:
92     friend void poll();
93
94     int ActiveThreads;
95     bool AllThreadsShouldExit, AllThreadsShouldSleep;
96     Thread threads[THREAD_MAX];
97     SplitPoint SplitPointStack[THREAD_MAX][ACTIVE_SPLIT_POINTS_MAX];
98
99     Lock MPLock, IOLock;
100
101 #if !defined(_MSC_VER)
102     pthread_cond_t WaitCond;
103     pthread_mutex_t WaitLock;
104 #else
105     HANDLE SitIdleEvent[THREAD_MAX];
106 #endif
107
108   };
109
110
111   // RootMove struct is used for moves at the root at the tree. For each
112   // root move, we store a score, a node count, and a PV (really a refutation
113   // in the case of moves which fail low).
114
115   struct RootMove {
116
117     RootMove() { nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL; }
118
119     // RootMove::operator<() is the comparison function used when
120     // sorting the moves. A move m1 is considered to be better
121     // than a move m2 if it has a higher score, or if the moves
122     // have equal score but m1 has the higher node count.
123     bool operator<(const RootMove& m) const {
124
125         return score != m.score ? score < m.score : theirBeta <= m.theirBeta;
126     }
127
128     Move move;
129     Value score;
130     int64_t nodes, cumulativeNodes, ourBeta, theirBeta;
131     Move pv[PLY_MAX_PLUS_2];
132   };
133
134
135   // The RootMoveList class is essentially an array of RootMove objects, with
136   // a handful of methods for accessing the data in the individual moves.
137
138   class RootMoveList {
139
140   public:
141     RootMoveList(Position& pos, Move searchMoves[]);
142
143     int move_count() const { return count; }
144     Move get_move(int moveNum) const { return moves[moveNum].move; }
145     Value get_move_score(int moveNum) const { return moves[moveNum].score; }
146     void set_move_score(int moveNum, Value score) { moves[moveNum].score = score; }
147     Move get_move_pv(int moveNum, int i) const { return moves[moveNum].pv[i]; }
148     int64_t get_move_cumulative_nodes(int moveNum) const { return moves[moveNum].cumulativeNodes; }
149
150     void set_move_nodes(int moveNum, int64_t nodes);
151     void set_beta_counters(int moveNum, int64_t our, int64_t their);
152     void set_move_pv(int moveNum, const Move pv[]);
153     void sort();
154     void sort_multipv(int n);
155
156   private:
157     static const int MaxRootMoves = 500;
158     RootMove moves[MaxRootMoves];
159     int count;
160   };
161
162
163   /// Constants
164
165   // Search depth at iteration 1
166   const Depth InitialDepth = OnePly;
167
168   // Use internal iterative deepening?
169   const bool UseIIDAtPVNodes = true;
170   const bool UseIIDAtNonPVNodes = true;
171
172   // Internal iterative deepening margin. At Non-PV moves, when
173   // UseIIDAtNonPVNodes is true, we do an internal iterative deepening
174   // search when the static evaluation is at most IIDMargin below beta.
175   const Value IIDMargin = Value(0x100);
176
177   // Easy move margin. An easy move candidate must be at least this much
178   // better than the second best move.
179   const Value EasyMoveMargin = Value(0x200);
180
181   // Null move margin. A null move search will not be done if the static
182   // evaluation of the position is more than NullMoveMargin below beta.
183   const Value NullMoveMargin = Value(0x200);
184
185   // If the TT move is at least SingleReplyMargin better then the
186   // remaining ones we will extend it.
187   const Value SingleReplyMargin = Value(0x20);
188
189   // Depth limit for razoring
190   const Depth RazorDepth = 4 * OnePly;
191
192   /// Lookup tables initialized at startup
193
194   // Reduction lookup tables and their getter functions
195   int8_t    PVReductionMatrix[64][64]; // [depth][moveNumber]
196   int8_t NonPVReductionMatrix[64][64]; // [depth][moveNumber]
197
198   inline Depth    pv_reduction(Depth d, int mn) { return (Depth)    PVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
199   inline Depth nonpv_reduction(Depth d, int mn) { return (Depth) NonPVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
200
201   // Futility lookup tables and their getter functions
202   const Value FutilityMarginQS = Value(0x80);
203   int32_t FutilityMarginsMatrix[14][64]; // [depth][moveNumber]
204   int FutilityMoveCountArray[32]; // [depth]
205
206   inline Value futility_margin(Depth d, int mn) { return Value(d < 7*OnePly ? FutilityMarginsMatrix[Max(d, 0)][Min(mn, 63)] : 2 * VALUE_INFINITE); }
207   inline int futility_move_count(Depth d) { return d < 16*OnePly ? FutilityMoveCountArray[d] : 512; }
208
209   /// Variables initialized by UCI options
210
211   // Depth limit for use of dynamic threat detection
212   Depth ThreatDepth;
213
214   // Last seconds noise filtering (LSN)
215   const bool UseLSNFiltering = true;
216   const int LSNTime = 4000; // In milliseconds
217   const Value LSNValue = value_from_centipawns(200);
218   bool loseOnTime = false;
219
220   // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
221   Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
222   Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
223
224   // Iteration counters
225   int Iteration;
226
227   // Scores and number of times the best move changed for each iteration
228   Value ValueByIteration[PLY_MAX_PLUS_2];
229   int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
230
231   // Search window management
232   int AspirationDelta;
233
234   // MultiPV mode
235   int MultiPV;
236
237   // Time managment variables
238   int RootMoveNumber;
239   int SearchStartTime;
240   int MaxNodes, MaxDepth;
241   int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
242   bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
243   bool AbortSearch, Quit;
244   bool AspirationFailLow;
245
246   // Show current line?
247   bool ShowCurrentLine;
248
249   // Log file
250   bool UseLogFile;
251   std::ofstream LogFile;
252
253   // MP related variables
254   Depth MinimumSplitDepth;
255   int MaxThreadsPerSplitPoint;
256   ThreadsManager TM;
257
258   // Node counters, used only by thread[0] but try to keep in different
259   // cache lines (64 bytes each) from the heavy SMP read accessed variables.
260   int NodesSincePoll;
261   int NodesBetweenPolls = 30000;
262
263   // History table
264   History H;
265
266   /// Functions
267
268   Value id_loop(const Position& pos, Move searchMoves[]);
269   Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta);
270   Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
271   Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
272   Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
273   void sp_search(SplitPoint* sp, int threadID);
274   void sp_search_pv(SplitPoint* sp, int threadID);
275   void init_node(SearchStack ss[], int ply, int threadID);
276   void update_pv(SearchStack ss[], int ply);
277   void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
278   bool connected_moves(const Position& pos, Move m1, Move m2);
279   bool value_is_mate(Value value);
280   bool move_is_killer(Move m, const SearchStack& ss);
281   Depth extension(const Position&, Move, bool, bool, bool, bool, bool, bool*);
282   bool ok_to_do_nullmove(const Position& pos);
283   bool ok_to_prune(const Position& pos, Move m, Move threat);
284   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
285   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
286   void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
287   void update_killers(Move m, SearchStack& ss);
288   void update_gains(const Position& pos, Move move, Value before, Value after);
289
290   int current_search_time();
291   int nps();
292   void poll();
293   void ponderhit();
294   void wait_for_stop_or_ponderhit();
295   void init_ss_array(SearchStack ss[]);
296
297 #if !defined(_MSC_VER)
298   void *init_thread(void *threadID);
299 #else
300   DWORD WINAPI init_thread(LPVOID threadID);
301 #endif
302
303 }
304
305
306 ////
307 //// Functions
308 ////
309
310 /// init_threads(), exit_threads() and nodes_searched() are helpers to
311 /// give accessibility to some TM methods from outside of current file.
312
313 void init_threads() { TM.init_threads(); }
314 void exit_threads() { TM.exit_threads(); }
315 int64_t nodes_searched() { return TM.nodes_searched(); }
316
317
318 /// perft() is our utility to verify move generation is bug free. All the legal
319 /// moves up to given depth are generated and counted and the sum returned.
320
321 int perft(Position& pos, Depth depth)
322 {
323     Move move;
324     int sum = 0;
325     MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
326
327     // If we are at the last ply we don't need to do and undo
328     // the moves, just to count them.
329     if (depth <= OnePly) // Replace with '<' to test also qsearch
330     {
331         while (mp.get_next_move()) sum++;
332         return sum;
333     }
334
335     // Loop through all legal moves
336     CheckInfo ci(pos);
337     while ((move = mp.get_next_move()) != MOVE_NONE)
338     {
339         StateInfo st;
340         pos.do_move(move, st, ci, pos.move_is_check(move, ci));
341         sum += perft(pos, depth - OnePly);
342         pos.undo_move(move);
343     }
344     return sum;
345 }
346
347
348 /// think() is the external interface to Stockfish's search, and is called when
349 /// the program receives the UCI 'go' command. It initializes various
350 /// search-related global variables, and calls root_search(). It returns false
351 /// when a quit command is received during the search.
352
353 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
354            int time[], int increment[], int movesToGo, int maxDepth,
355            int maxNodes, int maxTime, Move searchMoves[]) {
356
357   // Initialize global search variables
358   StopOnPonderhit = AbortSearch = Quit = false;
359   AspirationFailLow = false;
360   NodesSincePoll = 0;
361   SearchStartTime = get_system_time();
362   ExactMaxTime = maxTime;
363   MaxDepth = maxDepth;
364   MaxNodes = maxNodes;
365   InfiniteSearch = infinite;
366   PonderSearch = ponder;
367   UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
368
369   // Look for a book move, only during games, not tests
370   if (UseTimeManagement && get_option_value_bool("OwnBook"))
371   {
372       Move bookMove;
373       if (get_option_value_string("Book File") != OpeningBook.file_name())
374           OpeningBook.open(get_option_value_string("Book File"));
375
376       bookMove = OpeningBook.get_move(pos);
377       if (bookMove != MOVE_NONE)
378       {
379           if (PonderSearch)
380               wait_for_stop_or_ponderhit();
381
382           cout << "bestmove " << bookMove << endl;
383           return true;
384       }
385   }
386
387   TM.resetNodeCounters();
388
389   if (button_was_pressed("New Game"))
390       loseOnTime = false; // Reset at the beginning of a new game
391
392   // Read UCI option values
393   TT.set_size(get_option_value_int("Hash"));
394   if (button_was_pressed("Clear Hash"))
395       TT.clear();
396
397   bool PonderingEnabled = get_option_value_bool("Ponder");
398   MultiPV = get_option_value_int("MultiPV");
399
400   CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
401   CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
402
403   SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
404   SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
405
406   PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
407   PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
408
409   PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
410   PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
411
412   PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
413   PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
414
415   MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
416   MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
417
418   ThreatDepth   = get_option_value_int("Threat Depth") * OnePly;
419
420   Chess960 = get_option_value_bool("UCI_Chess960");
421   ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
422   UseLogFile = get_option_value_bool("Use Search Log");
423   if (UseLogFile)
424       LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
425
426   MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
427   MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
428
429   read_weights(pos.side_to_move());
430
431   // Set the number of active threads
432   int newActiveThreads = get_option_value_int("Threads");
433   if (newActiveThreads != TM.active_threads())
434   {
435       TM.set_active_threads(newActiveThreads);
436       init_eval(TM.active_threads());
437       // HACK: init_eval() destroys the static castleRightsMask[] array in the
438       // Position class. The below line repairs the damage.
439       Position p(pos.to_fen());
440       assert(pos.is_ok());
441   }
442
443   // Wake up sleeping threads
444   TM.wake_sleeping_threads();
445
446   for (int i = 1; i < TM.active_threads(); i++)
447       assert(TM.thread_is_available(i, 0));
448
449   // Set thinking time
450   int myTime = time[side_to_move];
451   int myIncrement = increment[side_to_move];
452   if (UseTimeManagement)
453   {
454       if (!movesToGo) // Sudden death time control
455       {
456           if (myIncrement)
457           {
458               MaxSearchTime = myTime / 30 + myIncrement;
459               AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
460           }
461           else // Blitz game without increment
462           {
463               MaxSearchTime = myTime / 30;
464               AbsoluteMaxSearchTime = myTime / 8;
465           }
466       }
467       else // (x moves) / (y minutes)
468       {
469           if (movesToGo == 1)
470           {
471               MaxSearchTime = myTime / 2;
472               AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
473           }
474           else
475           {
476               MaxSearchTime = myTime / Min(movesToGo, 20);
477               AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
478           }
479       }
480
481       if (PonderingEnabled)
482       {
483           MaxSearchTime += MaxSearchTime / 4;
484           MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
485       }
486   }
487
488   // Set best NodesBetweenPolls interval
489   if (MaxNodes)
490       NodesBetweenPolls = Min(MaxNodes, 30000);
491   else if (myTime && myTime < 1000)
492       NodesBetweenPolls = 1000;
493   else if (myTime && myTime < 5000)
494       NodesBetweenPolls = 5000;
495   else
496       NodesBetweenPolls = 30000;
497
498   // Write information to search log file
499   if (UseLogFile)
500       LogFile << "Searching: " << pos.to_fen() << endl
501               << "infinite: "  << infinite
502               << " ponder: "   << ponder
503               << " time: "     << myTime
504               << " increment: " << myIncrement
505               << " moves to go: " << movesToGo << endl;
506
507   // LSN filtering. Used only for developing purpose. Disabled by default.
508   if (   UseLSNFiltering
509       && loseOnTime)
510   {
511       // Step 2. If after last move we decided to lose on time, do it now!
512        while (SearchStartTime + myTime + 1000 > get_system_time())
513            /* wait here */;
514   }
515
516   // We're ready to start thinking. Call the iterative deepening loop function
517   Value v = id_loop(pos, searchMoves);
518
519   if (UseLSNFiltering)
520   {
521       // Step 1. If this is sudden death game and our position is hopeless,
522       // decide to lose on time.
523       if (   !loseOnTime // If we already lost on time, go to step 3.
524           && myTime < LSNTime
525           && myIncrement == 0
526           && movesToGo == 0
527           && v < -LSNValue)
528       {
529           loseOnTime = true;
530       }
531       else if (loseOnTime)
532       {
533           // Step 3. Now after stepping over the time limit, reset flag for next match.
534           loseOnTime = false;
535       }
536   }
537
538   if (UseLogFile)
539       LogFile.close();
540
541   TM.put_threads_to_sleep();
542
543   return !Quit;
544 }
545
546
547 /// init_search() is called during startup. It initializes various lookup tables
548
549 void init_search() {
550
551   // Init our reduction lookup tables
552   for (int i = 1; i < 64; i++) // i == depth (OnePly = 1)
553       for (int j = 1; j < 64; j++) // j == moveNumber
554       {
555           double    pvRed = 0.5 + log(double(i)) * log(double(j)) / 6.0;
556           double nonPVRed = 0.5 + log(double(i)) * log(double(j)) / 3.0;
557           PVReductionMatrix[i][j]    = (int8_t) (   pvRed >= 1.0 ? floor(   pvRed * int(OnePly)) : 0);
558           NonPVReductionMatrix[i][j] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(OnePly)) : 0);
559       }
560
561   // Init futility margins array
562   for (int i = 0; i < 14; i++) // i == depth (OnePly = 2)
563       for (int j = 0; j < 64; j++) // j == moveNumber
564       {
565           FutilityMarginsMatrix[i][j] = (i < 2 ? 0 : 112 * bitScanReverse32(i * i / 2)) - 8 * j; // FIXME: test using log instead of BSR
566       }
567
568   // Init futility move count array
569   for (int i = 0; i < 32; i++) // i == depth (OnePly = 2)
570       FutilityMoveCountArray[i] = 3 + (1 << (3 * i / 8));
571 }
572
573
574 // SearchStack::init() initializes a search stack. Used at the beginning of a
575 // new search from the root.
576 void SearchStack::init(int ply) {
577
578   pv[ply] = pv[ply + 1] = MOVE_NONE;
579   currentMove = threatMove = MOVE_NONE;
580   reduction = Depth(0);
581   eval = VALUE_NONE;
582 }
583
584 void SearchStack::initKillers() {
585
586   mateKiller = MOVE_NONE;
587   for (int i = 0; i < KILLER_MAX; i++)
588       killers[i] = MOVE_NONE;
589 }
590
591 namespace {
592
593   // id_loop() is the main iterative deepening loop. It calls root_search
594   // repeatedly with increasing depth until the allocated thinking time has
595   // been consumed, the user stops the search, or the maximum search depth is
596   // reached.
597
598   Value id_loop(const Position& pos, Move searchMoves[]) {
599
600     Position p(pos);
601     SearchStack ss[PLY_MAX_PLUS_2];
602
603     // searchMoves are verified, copied, scored and sorted
604     RootMoveList rml(p, searchMoves);
605
606     // Handle special case of searching on a mate/stale position
607     if (rml.move_count() == 0)
608     {
609         if (PonderSearch)
610             wait_for_stop_or_ponderhit();
611
612         return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
613     }
614
615     // Print RootMoveList c'tor startup scoring to the standard output,
616     // so that we print information also for iteration 1.
617     cout << "info depth " << 1 << "\ninfo depth " << 1
618          << " score " << value_to_string(rml.get_move_score(0))
619          << " time " << current_search_time()
620          << " nodes " << TM.nodes_searched()
621          << " nps " << nps()
622          << " pv " << rml.get_move(0) << "\n";
623
624     // Initialize
625     TT.new_search();
626     H.clear();
627     init_ss_array(ss);
628     ValueByIteration[1] = rml.get_move_score(0);
629     Iteration = 1;
630
631     // Is one move significantly better than others after initial scoring ?
632     Move EasyMove = MOVE_NONE;
633     if (   rml.move_count() == 1
634         || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
635         EasyMove = rml.get_move(0);
636
637     // Iterative deepening loop
638     while (Iteration < PLY_MAX)
639     {
640         // Initialize iteration
641         rml.sort();
642         Iteration++;
643         BestMoveChangesByIteration[Iteration] = 0;
644         if (Iteration <= 5)
645             ExtraSearchTime = 0;
646
647         cout << "info depth " << Iteration << endl;
648
649         // Calculate dynamic search window based on previous iterations
650         Value alpha, beta;
651
652         if (MultiPV == 1 && Iteration >= 6 && abs(ValueByIteration[Iteration - 1]) < VALUE_KNOWN_WIN)
653         {
654             int prevDelta1 = ValueByIteration[Iteration - 1] - ValueByIteration[Iteration - 2];
655             int prevDelta2 = ValueByIteration[Iteration - 2] - ValueByIteration[Iteration - 3];
656
657             AspirationDelta = Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16);
658             AspirationDelta = (AspirationDelta + 7) / 8 * 8; // Round to match grainSize
659
660             alpha = Max(ValueByIteration[Iteration - 1] - AspirationDelta, -VALUE_INFINITE);
661             beta  = Min(ValueByIteration[Iteration - 1] + AspirationDelta,  VALUE_INFINITE);
662         }
663         else
664         {
665             alpha = - VALUE_INFINITE;
666             beta  =   VALUE_INFINITE;
667         }
668
669         // Search to the current depth
670         Value value = root_search(p, ss, rml, alpha, beta);
671
672         // Write PV to transposition table, in case the relevant entries have
673         // been overwritten during the search.
674         TT.insert_pv(p, ss[0].pv);
675
676         if (AbortSearch)
677             break; // Value cannot be trusted. Break out immediately!
678
679         //Save info about search result
680         ValueByIteration[Iteration] = value;
681
682         // Drop the easy move if it differs from the new best move
683         if (ss[0].pv[0] != EasyMove)
684             EasyMove = MOVE_NONE;
685
686         if (UseTimeManagement)
687         {
688             // Time to stop?
689             bool stopSearch = false;
690
691             // Stop search early if there is only a single legal move,
692             // we search up to Iteration 6 anyway to get a proper score.
693             if (Iteration >= 6 && rml.move_count() == 1)
694                 stopSearch = true;
695
696             // Stop search early when the last two iterations returned a mate score
697             if (  Iteration >= 6
698                 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
699                 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
700                 stopSearch = true;
701
702             // Stop search early if one move seems to be much better than the rest
703             int64_t nodes = TM.nodes_searched();
704             if (   Iteration >= 8
705                 && EasyMove == ss[0].pv[0]
706                 && (  (   rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
707                        && current_search_time() > MaxSearchTime / 16)
708                     ||(   rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
709                        && current_search_time() > MaxSearchTime / 32)))
710                 stopSearch = true;
711
712             // Add some extra time if the best move has changed during the last two iterations
713             if (Iteration > 5 && Iteration <= 50)
714                 ExtraSearchTime = BestMoveChangesByIteration[Iteration]   * (MaxSearchTime / 2)
715                                 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
716
717             // Stop search if most of MaxSearchTime is consumed at the end of the
718             // iteration. We probably don't have enough time to search the first
719             // move at the next iteration anyway.
720             if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
721                 stopSearch = true;
722
723             if (stopSearch)
724             {
725                 if (!PonderSearch)
726                     break;
727                 else
728                     StopOnPonderhit = true;
729             }
730         }
731
732         if (MaxDepth && Iteration >= MaxDepth)
733             break;
734     }
735
736     rml.sort();
737
738     // If we are pondering or in infinite search, we shouldn't print the
739     // best move before we are told to do so.
740     if (!AbortSearch && (PonderSearch || InfiniteSearch))
741         wait_for_stop_or_ponderhit();
742     else
743         // Print final search statistics
744         cout << "info nodes " << TM.nodes_searched()
745              << " nps " << nps()
746              << " time " << current_search_time()
747              << " hashfull " << TT.full() << endl;
748
749     // Print the best move and the ponder move to the standard output
750     if (ss[0].pv[0] == MOVE_NONE)
751     {
752         ss[0].pv[0] = rml.get_move(0);
753         ss[0].pv[1] = MOVE_NONE;
754     }
755     cout << "bestmove " << ss[0].pv[0];
756     if (ss[0].pv[1] != MOVE_NONE)
757         cout << " ponder " << ss[0].pv[1];
758
759     cout << endl;
760
761     if (UseLogFile)
762     {
763         if (dbg_show_mean)
764             dbg_print_mean(LogFile);
765
766         if (dbg_show_hit_rate)
767             dbg_print_hit_rate(LogFile);
768
769         LogFile << "\nNodes: " << TM.nodes_searched()
770                 << "\nNodes/second: " << nps()
771                 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
772
773         StateInfo st;
774         p.do_move(ss[0].pv[0], st);
775         LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
776     }
777     return rml.get_move_score(0);
778   }
779
780
781   // root_search() is the function which searches the root node. It is
782   // similar to search_pv except that it uses a different move ordering
783   // scheme and prints some information to the standard output.
784
785   Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta) {
786
787     int64_t nodes;
788     Move move;
789     StateInfo st;
790     Depth depth, ext, newDepth;
791     Value value;
792     CheckInfo ci(pos);
793     int researchCount = 0;
794     bool moveIsCheck, captureOrPromotion, dangerous;
795     Value alpha = oldAlpha;
796     bool isCheck = pos.is_check();
797
798     // Evaluate the position statically
799     EvalInfo ei;
800     ss[0].eval = !isCheck ? evaluate(pos, ei, 0) : VALUE_NONE;
801
802     while (1) // Fail low loop
803     {
804
805         // Loop through all the moves in the root move list
806         for (int i = 0; i <  rml.move_count() && !AbortSearch; i++)
807         {
808             if (alpha >= beta)
809             {
810                 // We failed high, invalidate and skip next moves, leave node-counters
811                 // and beta-counters as they are and quickly return, we will try to do
812                 // a research at the next iteration with a bigger aspiration window.
813                 rml.set_move_score(i, -VALUE_INFINITE);
814                 continue;
815             }
816
817             RootMoveNumber = i + 1;
818
819             // Save the current node count before the move is searched
820             nodes = TM.nodes_searched();
821
822             // Reset beta cut-off counters
823             TM.resetBetaCounters();
824
825             // Pick the next root move, and print the move and the move number to
826             // the standard output.
827             move = ss[0].currentMove = rml.get_move(i);
828
829             if (current_search_time() >= 1000)
830                 cout << "info currmove " << move
831                      << " currmovenumber " << RootMoveNumber << endl;
832
833             // Decide search depth for this move
834             moveIsCheck = pos.move_is_check(move);
835             captureOrPromotion = pos.move_is_capture_or_promotion(move);
836             depth = (Iteration - 2) * OnePly + InitialDepth;
837             ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
838             newDepth = depth + ext;
839
840             value = - VALUE_INFINITE;
841
842             while (1) // Fail high loop
843             {
844
845                 // Make the move, and search it
846                 pos.do_move(move, st, ci, moveIsCheck);
847
848                 if (i < MultiPV || value > alpha)
849                 {
850                     // Aspiration window is disabled in multi-pv case
851                     if (MultiPV > 1)
852                         alpha = -VALUE_INFINITE;
853
854                     value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
855                 }
856                 else
857                 {
858                     // Try to reduce non-pv search depth by one ply if move seems not problematic,
859                     // if the move fails high will be re-searched at full depth.
860                     bool doFullDepthSearch = true;
861
862                     if (   depth >= 3*OnePly // FIXME was newDepth
863                         && !dangerous
864                         && !captureOrPromotion
865                         && !move_is_castle(move))
866                     {
867                         ss[0].reduction = pv_reduction(depth, RootMoveNumber - MultiPV + 1);
868                         if (ss[0].reduction)
869                         {
870                             value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
871                             doFullDepthSearch = (value > alpha);
872                         }
873                     }
874
875                     if (doFullDepthSearch)
876                     {
877                         ss[0].reduction = Depth(0);
878                         value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
879
880                         if (value > alpha)
881                             value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
882                     }
883                 }
884
885                 pos.undo_move(move);
886
887                 // Can we exit fail high loop ?
888                 if (AbortSearch || value < beta)
889                     break;
890
891                 // We are failing high and going to do a research. It's important to update score
892                 // before research in case we run out of time while researching.
893                 rml.set_move_score(i, value);
894                 update_pv(ss, 0);
895                 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
896                 rml.set_move_pv(i, ss[0].pv);
897
898                 // Print search information to the standard output
899                 cout << "info depth " << Iteration
900                      << " score " << value_to_string(value)
901                      << ((value >= beta) ? " lowerbound" :
902                         ((value <= alpha)? " upperbound" : ""))
903                      << " time "  << current_search_time()
904                      << " nodes " << TM.nodes_searched()
905                      << " nps "   << nps()
906                      << " pv ";
907
908                 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
909                     cout << ss[0].pv[j] << " ";
910
911                 cout << endl;
912
913                 if (UseLogFile)
914                 {
915                     ValueType type =  (value >= beta  ? VALUE_TYPE_LOWER
916                                     : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
917
918                     LogFile << pretty_pv(pos, current_search_time(), Iteration,
919                                          TM.nodes_searched(), value, type, ss[0].pv) << endl;
920                 }
921
922                 // Prepare for a research after a fail high, each time with a wider window
923                 researchCount++;
924                 beta = Min(beta + AspirationDelta * (1 << researchCount), VALUE_INFINITE);
925
926             } // End of fail high loop
927
928             // Finished searching the move. If AbortSearch is true, the search
929             // was aborted because the user interrupted the search or because we
930             // ran out of time. In this case, the return value of the search cannot
931             // be trusted, and we break out of the loop without updating the best
932             // move and/or PV.
933             if (AbortSearch)
934                 break;
935
936             // Remember beta-cutoff and searched nodes counts for this move. The
937             // info is used to sort the root moves at the next iteration.
938             int64_t our, their;
939             TM.get_beta_counters(pos.side_to_move(), our, their);
940             rml.set_beta_counters(i, our, their);
941             rml.set_move_nodes(i, TM.nodes_searched() - nodes);
942
943             assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
944
945             if (value <= alpha && i >= MultiPV)
946                 rml.set_move_score(i, -VALUE_INFINITE);
947             else
948             {
949                 // PV move or new best move!
950
951                 // Update PV
952                 rml.set_move_score(i, value);
953                 update_pv(ss, 0);
954                 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
955                 rml.set_move_pv(i, ss[0].pv);
956
957                 if (MultiPV == 1)
958                 {
959                     // We record how often the best move has been changed in each
960                     // iteration. This information is used for time managment: When
961                     // the best move changes frequently, we allocate some more time.
962                     if (i > 0)
963                         BestMoveChangesByIteration[Iteration]++;
964
965                     // Print search information to the standard output
966                     cout << "info depth " << Iteration
967                          << " score " << value_to_string(value)
968                          << ((value >= beta) ? " lowerbound" :
969                             ((value <= alpha)? " upperbound" : ""))
970                          << " time "  << current_search_time()
971                          << " nodes " << TM.nodes_searched()
972                          << " nps "   << nps()
973                          << " pv ";
974
975                     for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
976                         cout << ss[0].pv[j] << " ";
977
978                     cout << endl;
979
980                     if (UseLogFile)
981                     {
982                         ValueType type =  (value >= beta  ? VALUE_TYPE_LOWER
983                                         : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
984
985                         LogFile << pretty_pv(pos, current_search_time(), Iteration,
986                                              TM.nodes_searched(), value, type, ss[0].pv) << endl;
987                     }
988                     if (value > alpha)
989                         alpha = value;
990                 }
991                 else // MultiPV > 1
992                 {
993                     rml.sort_multipv(i);
994                     for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
995                     {
996                         cout << "info multipv " << j + 1
997                              << " score " << value_to_string(rml.get_move_score(j))
998                              << " depth " << ((j <= i)? Iteration : Iteration - 1)
999                              << " time " << current_search_time()
1000                              << " nodes " << TM.nodes_searched()
1001                              << " nps " << nps()
1002                              << " pv ";
1003
1004                         for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1005                             cout << rml.get_move_pv(j, k) << " ";
1006
1007                         cout << endl;
1008                     }
1009                     alpha = rml.get_move_score(Min(i, MultiPV-1));
1010                 }
1011             } // PV move or new best move
1012
1013             assert(alpha >= oldAlpha);
1014
1015             AspirationFailLow = (alpha == oldAlpha);
1016
1017             if (AspirationFailLow && StopOnPonderhit)
1018                 StopOnPonderhit = false;
1019         }
1020
1021         // Can we exit fail low loop ?
1022         if (AbortSearch || alpha > oldAlpha)
1023             break;
1024
1025         // Prepare for a research after a fail low, each time with a wider window
1026         researchCount++;
1027         alpha = Max(alpha - AspirationDelta * (1 << researchCount), -VALUE_INFINITE);
1028         oldAlpha = alpha;
1029
1030     } // Fail low loop
1031
1032     return alpha;
1033   }
1034
1035
1036   // search_pv() is the main search function for PV nodes.
1037
1038   Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1039                   Depth depth, int ply, int threadID) {
1040
1041     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1042     assert(beta > alpha && beta <= VALUE_INFINITE);
1043     assert(ply >= 0 && ply < PLY_MAX);
1044     assert(threadID >= 0 && threadID < TM.active_threads());
1045
1046     Move movesSearched[256];
1047     StateInfo st;
1048     const TTEntry* tte;
1049     Move ttMove, move;
1050     Depth ext, newDepth;
1051     Value oldAlpha, value;
1052     bool isCheck, mateThreat, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1053     int moveCount = 0;
1054     Value bestValue = value = -VALUE_INFINITE;
1055
1056     if (depth < OnePly)
1057         return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1058
1059     // Initialize, and make an early exit in case of an aborted search,
1060     // an instant draw, maximum ply reached, etc.
1061     init_node(ss, ply, threadID);
1062
1063     // After init_node() that calls poll()
1064     if (AbortSearch || TM.thread_should_stop(threadID))
1065         return Value(0);
1066
1067     if (pos.is_draw() || ply >= PLY_MAX - 1)
1068         return VALUE_DRAW;
1069
1070     // Mate distance pruning
1071     oldAlpha = alpha;
1072     alpha = Max(value_mated_in(ply), alpha);
1073     beta = Min(value_mate_in(ply+1), beta);
1074     if (alpha >= beta)
1075         return alpha;
1076
1077     // Transposition table lookup. At PV nodes, we don't use the TT for
1078     // pruning, but only for move ordering. This is to avoid problems in
1079     // the following areas:
1080     //
1081     // * Repetition draw detection
1082     // * Fifty move rule detection
1083     // * Searching for a mate
1084     // * Printing of full PV line
1085     //
1086     tte = TT.retrieve(pos.get_key());
1087     ttMove = (tte ? tte->move() : MOVE_NONE);
1088
1089     // Go with internal iterative deepening if we don't have a TT move
1090     if (   UseIIDAtPVNodes
1091         && depth >= 5*OnePly
1092         && ttMove == MOVE_NONE)
1093     {
1094         search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1095         ttMove = ss[ply].pv[ply];
1096         tte = TT.retrieve(pos.get_key());
1097     }
1098
1099     isCheck = pos.is_check();
1100     if (!isCheck)
1101     {
1102         // Update gain statistics of the previous move that lead
1103         // us in this position.
1104         EvalInfo ei;
1105         ss[ply].eval = evaluate(pos, ei, threadID);
1106         update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1107     }
1108
1109     // Initialize a MovePicker object for the current position, and prepare
1110     // to search all moves
1111     mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1112     CheckInfo ci(pos);
1113     MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1114
1115     // Loop through all legal moves until no moves remain or a beta cutoff
1116     // occurs.
1117     while (   alpha < beta
1118            && (move = mp.get_next_move()) != MOVE_NONE
1119            && !TM.thread_should_stop(threadID))
1120     {
1121       assert(move_is_ok(move));
1122
1123       singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1124       moveIsCheck = pos.move_is_check(move, ci);
1125       captureOrPromotion = pos.move_is_capture_or_promotion(move);
1126
1127       // Decide the new search depth
1128       ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1129
1130       // Singular extension search. We extend the TT move if its value is much better than
1131       // its siblings. To verify this we do a reduced search on all the other moves but the
1132       // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1133       if (   depth >= 6 * OnePly
1134           && tte
1135           && move == tte->move()
1136           && ext < OnePly
1137           && is_lower_bound(tte->type())
1138           && tte->depth() >= depth - 3 * OnePly)
1139       {
1140           Value ttValue = value_from_tt(tte->value(), ply);
1141
1142           if (abs(ttValue) < VALUE_KNOWN_WIN)
1143           {
1144               Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1145
1146               if (excValue < ttValue - SingleReplyMargin)
1147                   ext = OnePly;
1148           }
1149       }
1150
1151       newDepth = depth - OnePly + ext;
1152
1153       // Update current move
1154       movesSearched[moveCount++] = ss[ply].currentMove = move;
1155
1156       // Make and search the move
1157       pos.do_move(move, st, ci, moveIsCheck);
1158
1159       if (moveCount == 1) // The first move in list is the PV
1160           value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1161       else
1162       {
1163         // Try to reduce non-pv search depth by one ply if move seems not problematic,
1164         // if the move fails high will be re-searched at full depth.
1165         bool doFullDepthSearch = true;
1166
1167         if (    depth >= 3*OnePly
1168             && !dangerous
1169             && !captureOrPromotion
1170             && !move_is_castle(move)
1171             && !move_is_killer(move, ss[ply]))
1172         {
1173             ss[ply].reduction = pv_reduction(depth, moveCount);
1174             if (ss[ply].reduction)
1175             {
1176                 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1177                 doFullDepthSearch = (value > alpha);
1178             }
1179         }
1180
1181         if (doFullDepthSearch) // Go with full depth non-pv search
1182         {
1183             ss[ply].reduction = Depth(0);
1184             value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1185             if (value > alpha && value < beta)
1186                 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1187         }
1188       }
1189       pos.undo_move(move);
1190
1191       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1192
1193       // New best move?
1194       if (value > bestValue)
1195       {
1196           bestValue = value;
1197           if (value > alpha)
1198           {
1199               alpha = value;
1200               update_pv(ss, ply);
1201               if (value == value_mate_in(ply + 1))
1202                   ss[ply].mateKiller = move;
1203           }
1204       }
1205
1206       // Split?
1207       if (   TM.active_threads() > 1
1208           && bestValue < beta
1209           && depth >= MinimumSplitDepth
1210           && Iteration <= 99
1211           && TM.idle_thread_exists(threadID)
1212           && !AbortSearch
1213           && !TM.thread_should_stop(threadID)
1214           && TM.split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE,
1215                       depth, &moveCount, &mp, threadID, true))
1216           break;
1217     }
1218
1219     // All legal moves have been searched.  A special case: If there were
1220     // no legal moves, it must be mate or stalemate.
1221     if (moveCount == 0)
1222         return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1223
1224     // If the search is not aborted, update the transposition table,
1225     // history counters, and killer moves.
1226     if (AbortSearch || TM.thread_should_stop(threadID))
1227         return bestValue;
1228
1229     if (bestValue <= oldAlpha)
1230         TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1231
1232     else if (bestValue >= beta)
1233     {
1234         TM.incrementBetaCounter(pos.side_to_move(), depth, threadID);
1235         move = ss[ply].pv[ply];
1236         if (!pos.move_is_capture_or_promotion(move))
1237         {
1238             update_history(pos, move, depth, movesSearched, moveCount);
1239             update_killers(move, ss[ply]);
1240         }
1241         TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1242     }
1243     else
1244         TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1245
1246     return bestValue;
1247   }
1248
1249
1250   // search() is the search function for zero-width nodes.
1251
1252   Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1253                int ply, bool allowNullmove, int threadID, Move excludedMove) {
1254
1255     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1256     assert(ply >= 0 && ply < PLY_MAX);
1257     assert(threadID >= 0 && threadID < TM.active_threads());
1258
1259     Move movesSearched[256];
1260     EvalInfo ei;
1261     StateInfo st;
1262     const TTEntry* tte;
1263     Move ttMove, move;
1264     Depth ext, newDepth;
1265     Value bestValue, staticValue, nullValue, value, futilityValue, futilityValueScaled;
1266     bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1267     bool mateThreat = false;
1268     int moveCount = 0;
1269     futilityValue = staticValue = bestValue = value = -VALUE_INFINITE;
1270
1271     if (depth < OnePly)
1272         return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1273
1274     // Initialize, and make an early exit in case of an aborted search,
1275     // an instant draw, maximum ply reached, etc.
1276     init_node(ss, ply, threadID);
1277
1278     // After init_node() that calls poll()
1279     if (AbortSearch || TM.thread_should_stop(threadID))
1280         return Value(0);
1281
1282     if (pos.is_draw() || ply >= PLY_MAX - 1)
1283         return VALUE_DRAW;
1284
1285     // Mate distance pruning
1286     if (value_mated_in(ply) >= beta)
1287         return beta;
1288
1289     if (value_mate_in(ply + 1) < beta)
1290         return beta - 1;
1291
1292     // We don't want the score of a partial search to overwrite a previous full search
1293     // TT value, so we use a different position key in case of an excluded move exsists.
1294     Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1295
1296     // Transposition table lookup
1297     tte = TT.retrieve(posKey);
1298     ttMove = (tte ? tte->move() : MOVE_NONE);
1299
1300     if (tte && ok_to_use_TT(tte, depth, beta, ply))
1301     {
1302         ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1303         return value_from_tt(tte->value(), ply);
1304     }
1305
1306     isCheck = pos.is_check();
1307
1308     // Evaluate the position statically
1309     if (!isCheck)
1310     {
1311         if (tte && (tte->type() & VALUE_TYPE_EVAL))
1312             staticValue = value_from_tt(tte->value(), ply);
1313         else
1314             staticValue = evaluate(pos, ei, threadID);
1315
1316         ss[ply].eval = staticValue;
1317         futilityValue = staticValue + futility_margin(depth, 0); //FIXME: Remove me, only for split
1318         staticValue = refine_eval(tte, staticValue, ply); // Enhance accuracy with TT value if possible
1319         update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1320     }
1321
1322     // Static null move pruning. We're betting that the opponent doesn't have
1323     // a move that will reduce the score by more than FutilityMargins[int(depth)]
1324     // if we do a null move.
1325     if (  !isCheck
1326         && allowNullmove
1327         && depth < RazorDepth
1328         && staticValue - futility_margin(depth, 0) >= beta)
1329         return staticValue - futility_margin(depth, 0);
1330
1331     // Null move search
1332     if (    allowNullmove
1333         &&  depth > OnePly
1334         && !isCheck
1335         && !value_is_mate(beta)
1336         &&  ok_to_do_nullmove(pos)
1337         &&  staticValue >= beta - NullMoveMargin)
1338     {
1339         ss[ply].currentMove = MOVE_NULL;
1340
1341         pos.do_null_move(st);
1342
1343         // Null move dynamic reduction based on depth
1344         int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1345
1346         // Null move dynamic reduction based on value
1347         if (staticValue - beta > PawnValueMidgame)
1348             R++;
1349
1350         nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1351
1352         pos.undo_null_move();
1353
1354         if (nullValue >= beta)
1355         {
1356             if (depth < 6 * OnePly)
1357                 return beta;
1358
1359             // Do zugzwang verification search
1360             Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1361             if (v >= beta)
1362                 return beta;
1363         } else {
1364             // The null move failed low, which means that we may be faced with
1365             // some kind of threat. If the previous move was reduced, check if
1366             // the move that refuted the null move was somehow connected to the
1367             // move which was reduced. If a connection is found, return a fail
1368             // low score (which will cause the reduced move to fail high in the
1369             // parent node, which will trigger a re-search with full depth).
1370             if (nullValue == value_mated_in(ply + 2))
1371                 mateThreat = true;
1372
1373             ss[ply].threatMove = ss[ply + 1].currentMove;
1374             if (   depth < ThreatDepth
1375                 && ss[ply - 1].reduction
1376                 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1377                 return beta - 1;
1378         }
1379     }
1380     // Null move search not allowed, try razoring
1381     else if (   !value_is_mate(beta)
1382              && !isCheck
1383              && depth < RazorDepth
1384              && staticValue < beta - (NullMoveMargin + 16 * depth)
1385              && ss[ply - 1].currentMove != MOVE_NULL
1386              && ttMove == MOVE_NONE
1387              && !pos.has_pawn_on_7th(pos.side_to_move()))
1388     {
1389         Value rbeta = beta - (NullMoveMargin + 16 * depth);
1390         Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1391         if (v < rbeta)
1392           return v;
1393     }
1394
1395     // Go with internal iterative deepening if we don't have a TT move
1396     if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1397         !isCheck && ss[ply].eval >= beta - IIDMargin)
1398     {
1399         search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1400         ttMove = ss[ply].pv[ply];
1401         tte = TT.retrieve(posKey);
1402     }
1403
1404     // Initialize a MovePicker object for the current position, and prepare
1405     // to search all moves.
1406     MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1407     CheckInfo ci(pos);
1408
1409     // Loop through all legal moves until no moves remain or a beta cutoff occurs
1410     while (   bestValue < beta
1411            && (move = mp.get_next_move()) != MOVE_NONE
1412            && !TM.thread_should_stop(threadID))
1413     {
1414       assert(move_is_ok(move));
1415
1416       if (move == excludedMove)
1417           continue;
1418
1419       moveIsCheck = pos.move_is_check(move, ci);
1420       singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1421       captureOrPromotion = pos.move_is_capture_or_promotion(move);
1422
1423       // Decide the new search depth
1424       ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1425
1426       // Singular extension search. We extend the TT move if its value is much better than
1427       // its siblings. To verify this we do a reduced search on all the other moves but the
1428       // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1429       if (   depth >= 8 * OnePly
1430           && tte
1431           && move == tte->move()
1432           && !excludedMove // Do not allow recursive single-reply search
1433           && ext < OnePly
1434           && is_lower_bound(tte->type())
1435           && tte->depth() >= depth - 3 * OnePly)
1436       {
1437           Value ttValue = value_from_tt(tte->value(), ply);
1438
1439           if (abs(ttValue) < VALUE_KNOWN_WIN)
1440           {
1441               Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1442
1443               if (excValue < ttValue - SingleReplyMargin)
1444                   ext = OnePly;
1445           }
1446       }
1447
1448       newDepth = depth - OnePly + ext;
1449
1450       // Update current move
1451       movesSearched[moveCount++] = ss[ply].currentMove = move;
1452
1453       // Futility pruning
1454       if (   !isCheck
1455           && !dangerous
1456           && !captureOrPromotion
1457           && !move_is_castle(move)
1458           &&  move != ttMove)
1459       {
1460           // Move count based pruning
1461           if (   moveCount >= futility_move_count(depth)
1462               && ok_to_prune(pos, move, ss[ply].threatMove)
1463               && bestValue > value_mated_in(PLY_MAX))
1464               continue;
1465
1466           // Value based pruning
1467           Depth predictedDepth = newDepth - nonpv_reduction(depth, moveCount); //FIXME: We are ignoring condition: depth >= 3*OnePly, BUG??
1468           futilityValueScaled =  ss[ply].eval + futility_margin(predictedDepth, moveCount)
1469                                + H.gain(pos.piece_on(move_from(move)), move_to(move)) + 45;
1470
1471           if (futilityValueScaled < beta)
1472           {
1473               if (futilityValueScaled > bestValue)
1474                   bestValue = futilityValueScaled;
1475               continue;
1476           }
1477       }
1478
1479       // Make and search the move
1480       pos.do_move(move, st, ci, moveIsCheck);
1481
1482       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1483       // if the move fails high will be re-searched at full depth.
1484       bool doFullDepthSearch = true;
1485
1486       if (    depth >= 3*OnePly
1487           && !dangerous
1488           && !captureOrPromotion
1489           && !move_is_castle(move)
1490           && !move_is_killer(move, ss[ply]))
1491       {
1492           ss[ply].reduction = nonpv_reduction(depth, moveCount);
1493           if (ss[ply].reduction)
1494           {
1495               value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1496               doFullDepthSearch = (value >= beta);
1497           }
1498       }
1499
1500       if (doFullDepthSearch) // Go with full depth non-pv search
1501       {
1502           ss[ply].reduction = Depth(0);
1503           value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1504       }
1505       pos.undo_move(move);
1506
1507       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1508
1509       // New best move?
1510       if (value > bestValue)
1511       {
1512           bestValue = value;
1513           if (value >= beta)
1514               update_pv(ss, ply);
1515
1516           if (value == value_mate_in(ply + 1))
1517               ss[ply].mateKiller = move;
1518       }
1519
1520       // Split?
1521       if (   TM.active_threads() > 1
1522           && bestValue < beta
1523           && depth >= MinimumSplitDepth
1524           && Iteration <= 99
1525           && TM.idle_thread_exists(threadID)
1526           && !AbortSearch
1527           && !TM.thread_should_stop(threadID)
1528           && TM.split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue, //FIXME: SMP & futilityValue
1529                       depth, &moveCount, &mp, threadID, false))
1530           break;
1531     }
1532
1533     // All legal moves have been searched. A special case: If there were
1534     // no legal moves, it must be mate or stalemate.
1535     if (!moveCount)
1536         return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1537
1538     // If the search is not aborted, update the transposition table,
1539     // history counters, and killer moves.
1540     if (AbortSearch || TM.thread_should_stop(threadID))
1541         return bestValue;
1542
1543     if (bestValue < beta)
1544         TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1545     else
1546     {
1547         TM.incrementBetaCounter(pos.side_to_move(), depth, threadID);
1548         move = ss[ply].pv[ply];
1549         TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1550         if (!pos.move_is_capture_or_promotion(move))
1551         {
1552             update_history(pos, move, depth, movesSearched, moveCount);
1553             update_killers(move, ss[ply]);
1554         }
1555
1556     }
1557
1558     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1559
1560     return bestValue;
1561   }
1562
1563
1564   // qsearch() is the quiescence search function, which is called by the main
1565   // search function when the remaining depth is zero (or, to be more precise,
1566   // less than OnePly).
1567
1568   Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1569                 Depth depth, int ply, int threadID) {
1570
1571     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1572     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1573     assert(depth <= 0);
1574     assert(ply >= 0 && ply < PLY_MAX);
1575     assert(threadID >= 0 && threadID < TM.active_threads());
1576
1577     EvalInfo ei;
1578     StateInfo st;
1579     Move ttMove, move;
1580     Value staticValue, bestValue, value, futilityBase, futilityValue;
1581     bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1582     const TTEntry* tte = NULL;
1583     int moveCount = 0;
1584     bool pvNode = (beta - alpha != 1);
1585     Value oldAlpha = alpha;
1586
1587     // Initialize, and make an early exit in case of an aborted search,
1588     // an instant draw, maximum ply reached, etc.
1589     init_node(ss, ply, threadID);
1590
1591     // After init_node() that calls poll()
1592     if (AbortSearch || TM.thread_should_stop(threadID))
1593         return Value(0);
1594
1595     if (pos.is_draw() || ply >= PLY_MAX - 1)
1596         return VALUE_DRAW;
1597
1598     // Transposition table lookup. At PV nodes, we don't use the TT for
1599     // pruning, but only for move ordering.
1600     tte = TT.retrieve(pos.get_key());
1601     ttMove = (tte ? tte->move() : MOVE_NONE);
1602
1603     if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1604     {
1605         assert(tte->type() != VALUE_TYPE_EVAL);
1606
1607         ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1608         return value_from_tt(tte->value(), ply);
1609     }
1610
1611     isCheck = pos.is_check();
1612
1613     // Evaluate the position statically
1614     if (isCheck)
1615         staticValue = -VALUE_INFINITE;
1616     else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1617         staticValue = value_from_tt(tte->value(), ply);
1618     else
1619         staticValue = evaluate(pos, ei, threadID);
1620
1621     if (!isCheck)
1622     {
1623         ss[ply].eval = staticValue;
1624         update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1625     }
1626
1627     // Initialize "stand pat score", and return it immediately if it is
1628     // at least beta.
1629     bestValue = staticValue;
1630
1631     if (bestValue >= beta)
1632     {
1633         // Store the score to avoid a future costly evaluation() call
1634         if (!isCheck && !tte && ei.futilityMargin[pos.side_to_move()] == 0)
1635             TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1636
1637         return bestValue;
1638     }
1639
1640     if (bestValue > alpha)
1641         alpha = bestValue;
1642
1643     // If we are near beta then try to get a cutoff pushing checks a bit further
1644     bool deepChecks = depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8;
1645
1646     // Initialize a MovePicker object for the current position, and prepare
1647     // to search the moves. Because the depth is <= 0 here, only captures,
1648     // queen promotions and checks (only if depth == 0 or depth == -OnePly
1649     // and we are near beta) will be generated.
1650     MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1651     CheckInfo ci(pos);
1652     enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1653     futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin[pos.side_to_move()];
1654
1655     // Loop through the moves until no moves remain or a beta cutoff
1656     // occurs.
1657     while (   alpha < beta
1658            && (move = mp.get_next_move()) != MOVE_NONE)
1659     {
1660       assert(move_is_ok(move));
1661
1662       moveIsCheck = pos.move_is_check(move, ci);
1663
1664       // Update current move
1665       moveCount++;
1666       ss[ply].currentMove = move;
1667
1668       // Futility pruning
1669       if (   enoughMaterial
1670           && !isCheck
1671           && !pvNode
1672           && !moveIsCheck
1673           &&  move != ttMove
1674           && !move_is_promotion(move)
1675           && !pos.move_is_passed_pawn_push(move))
1676       {
1677           futilityValue =  futilityBase
1678                          + pos.endgame_value_of_piece_on(move_to(move))
1679                          + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1680
1681           if (futilityValue < alpha)
1682           {
1683               if (futilityValue > bestValue)
1684                   bestValue = futilityValue;
1685               continue;
1686           }
1687       }
1688
1689       // Detect blocking evasions that are candidate to be pruned
1690       evasionPrunable =   isCheck
1691                        && bestValue != -VALUE_INFINITE
1692                        && !pos.move_is_capture(move)
1693                        && pos.type_of_piece_on(move_from(move)) != KING
1694                        && !pos.can_castle(pos.side_to_move());
1695
1696       // Don't search moves with negative SEE values
1697       if (   (!isCheck || evasionPrunable)
1698           &&  move != ttMove
1699           && !move_is_promotion(move)
1700           &&  pos.see_sign(move) < 0)
1701           continue;
1702
1703       // Make and search the move
1704       pos.do_move(move, st, ci, moveIsCheck);
1705       value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1706       pos.undo_move(move);
1707
1708       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1709
1710       // New best move?
1711       if (value > bestValue)
1712       {
1713           bestValue = value;
1714           if (value > alpha)
1715           {
1716               alpha = value;
1717               update_pv(ss, ply);
1718           }
1719        }
1720     }
1721
1722     // All legal moves have been searched. A special case: If we're in check
1723     // and no legal moves were found, it is checkmate.
1724     if (!moveCount && pos.is_check()) // Mate!
1725         return value_mated_in(ply);
1726
1727     // Update transposition table
1728     Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1729     if (bestValue <= oldAlpha)
1730     {
1731         // If bestValue isn't changed it means it is still the static evaluation
1732         // of the node, so keep this info to avoid a future evaluation() call.
1733         ValueType type = (bestValue == staticValue && !ei.futilityMargin[pos.side_to_move()] ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1734         TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1735     }
1736     else if (bestValue >= beta)
1737     {
1738         move = ss[ply].pv[ply];
1739         TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1740
1741         // Update killers only for good checking moves
1742         if (!pos.move_is_capture_or_promotion(move))
1743             update_killers(move, ss[ply]);
1744     }
1745     else
1746         TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, d, ss[ply].pv[ply]);
1747
1748     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1749
1750     return bestValue;
1751   }
1752
1753
1754   // sp_search() is used to search from a split point.  This function is called
1755   // by each thread working at the split point.  It is similar to the normal
1756   // search() function, but simpler.  Because we have already probed the hash
1757   // table, done a null move search, and searched the first move before
1758   // splitting, we don't have to repeat all this work in sp_search().  We
1759   // also don't need to store anything to the hash table here:  This is taken
1760   // care of after we return from the split point.
1761
1762   void sp_search(SplitPoint* sp, int threadID) {
1763
1764     assert(threadID >= 0 && threadID < TM.active_threads());
1765     assert(TM.active_threads() > 1);
1766
1767     Position pos(*sp->pos);
1768     CheckInfo ci(pos);
1769     SearchStack* ss = sp->sstack[threadID];
1770     Value value = -VALUE_INFINITE;
1771     Move move;
1772     int moveCount;
1773     bool isCheck = pos.is_check();
1774     bool useFutilityPruning =     sp->depth < 7 * OnePly //FIXME: sync with search
1775                               && !isCheck;
1776
1777     while (    lock_grab_bool(&(sp->lock))
1778            &&  sp->bestValue < sp->beta
1779            && !TM.thread_should_stop(threadID)
1780            && (move = sp->mp->get_next_move()) != MOVE_NONE)
1781     {
1782       moveCount = ++sp->moves;
1783       lock_release(&(sp->lock));
1784
1785       assert(move_is_ok(move));
1786
1787       bool moveIsCheck = pos.move_is_check(move, ci);
1788       bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1789
1790       ss[sp->ply].currentMove = move;
1791
1792       // Decide the new search depth
1793       bool dangerous;
1794       Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1795       Depth newDepth = sp->depth - OnePly + ext;
1796
1797       // Prune?
1798       if (    useFutilityPruning
1799           && !dangerous
1800           && !captureOrPromotion)
1801       {
1802           // Move count based pruning
1803           if (   moveCount >= futility_move_count(sp->depth)
1804               && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1805               && sp->bestValue > value_mated_in(PLY_MAX))
1806               continue;
1807
1808           // Value based pruning
1809           Value futilityValueScaled = sp->futilityValue - moveCount * 8; //FIXME: sync with search
1810
1811           if (futilityValueScaled < sp->beta)
1812           {
1813               if (futilityValueScaled > sp->bestValue) // Less then 1% of cases
1814               {
1815                   lock_grab(&(sp->lock));
1816                   if (futilityValueScaled > sp->bestValue)
1817                       sp->bestValue = futilityValueScaled;
1818                   lock_release(&(sp->lock));
1819               }
1820               continue;
1821           }
1822       }
1823
1824       // Make and search the move.
1825       StateInfo st;
1826       pos.do_move(move, st, ci, moveIsCheck);
1827
1828       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1829       // if the move fails high will be re-searched at full depth.
1830       bool doFullDepthSearch = true;
1831
1832       if (   !dangerous
1833           && !captureOrPromotion
1834           && !move_is_castle(move)
1835           && !move_is_killer(move, ss[sp->ply]))
1836       {
1837           ss[sp->ply].reduction = nonpv_reduction(sp->depth, moveCount);
1838           if (ss[sp->ply].reduction)
1839           {
1840               value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1841               doFullDepthSearch = (value >= sp->beta);
1842           }
1843       }
1844
1845       if (doFullDepthSearch) // Go with full depth non-pv search
1846       {
1847           ss[sp->ply].reduction = Depth(0);
1848           value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1849       }
1850       pos.undo_move(move);
1851
1852       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1853
1854       if (TM.thread_should_stop(threadID))
1855       {
1856           lock_grab(&(sp->lock));
1857           break;
1858       }
1859
1860       // New best move?
1861       if (value > sp->bestValue) // Less then 2% of cases
1862       {
1863           lock_grab(&(sp->lock));
1864           if (value > sp->bestValue && !TM.thread_should_stop(threadID))
1865           {
1866               sp->bestValue = value;
1867               if (sp->bestValue >= sp->beta)
1868               {
1869                   sp_update_pv(sp->parentSstack, ss, sp->ply);
1870                   for (int i = 0; i < TM.active_threads(); i++)
1871                       if (i != threadID && (i == sp->master || sp->slaves[i]))
1872                           TM.set_stop_request(i);
1873
1874                   sp->finished = true;
1875               }
1876           }
1877           lock_release(&(sp->lock));
1878       }
1879     }
1880
1881     /* Here we have the lock still grabbed */
1882
1883     // If this is the master thread and we have been asked to stop because of
1884     // a beta cutoff higher up in the tree, stop all slave threads.
1885     if (sp->master == threadID && TM.thread_should_stop(threadID))
1886         for (int i = 0; i < TM.active_threads(); i++)
1887             if (sp->slaves[i])
1888                 TM.set_stop_request(i);
1889
1890     sp->cpus--;
1891     sp->slaves[threadID] = 0;
1892
1893     lock_release(&(sp->lock));
1894   }
1895
1896
1897   // sp_search_pv() is used to search from a PV split point.  This function
1898   // is called by each thread working at the split point.  It is similar to
1899   // the normal search_pv() function, but simpler.  Because we have already
1900   // probed the hash table and searched the first move before splitting, we
1901   // don't have to repeat all this work in sp_search_pv().  We also don't
1902   // need to store anything to the hash table here: This is taken care of
1903   // after we return from the split point.
1904
1905   void sp_search_pv(SplitPoint* sp, int threadID) {
1906
1907     assert(threadID >= 0 && threadID < TM.active_threads());
1908     assert(TM.active_threads() > 1);
1909
1910     Position pos(*sp->pos);
1911     CheckInfo ci(pos);
1912     SearchStack* ss = sp->sstack[threadID];
1913     Value value = -VALUE_INFINITE;
1914     int moveCount;
1915     Move move;
1916
1917     while (    lock_grab_bool(&(sp->lock))
1918            &&  sp->alpha < sp->beta
1919            && !TM.thread_should_stop(threadID)
1920            && (move = sp->mp->get_next_move()) != MOVE_NONE)
1921     {
1922       moveCount = ++sp->moves;
1923       lock_release(&(sp->lock));
1924
1925       assert(move_is_ok(move));
1926
1927       bool moveIsCheck = pos.move_is_check(move, ci);
1928       bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1929
1930       ss[sp->ply].currentMove = move;
1931
1932       // Decide the new search depth
1933       bool dangerous;
1934       Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1935       Depth newDepth = sp->depth - OnePly + ext;
1936
1937       // Make and search the move.
1938       StateInfo st;
1939       pos.do_move(move, st, ci, moveIsCheck);
1940
1941       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1942       // if the move fails high will be re-searched at full depth.
1943       bool doFullDepthSearch = true;
1944
1945       if (   !dangerous
1946           && !captureOrPromotion
1947           && !move_is_castle(move)
1948           && !move_is_killer(move, ss[sp->ply]))
1949       {
1950           ss[sp->ply].reduction = pv_reduction(sp->depth, moveCount);
1951           if (ss[sp->ply].reduction)
1952           {
1953               Value localAlpha = sp->alpha;
1954               value = -search(pos, ss, -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1955               doFullDepthSearch = (value > localAlpha);
1956           }
1957       }
1958
1959       if (doFullDepthSearch) // Go with full depth non-pv search
1960       {
1961           Value localAlpha = sp->alpha;
1962           ss[sp->ply].reduction = Depth(0);
1963           value = -search(pos, ss, -localAlpha, newDepth, sp->ply+1, true, threadID);
1964
1965           if (value > localAlpha && value < sp->beta)
1966           {
1967               // If another thread has failed high then sp->alpha has been increased
1968               // to be higher or equal then beta, if so, avoid to start a PV search.
1969               localAlpha = sp->alpha;
1970               if (localAlpha < sp->beta)
1971                   value = -search_pv(pos, ss, -sp->beta, -localAlpha, newDepth, sp->ply+1, threadID);
1972               else
1973                   assert(TM.thread_should_stop(threadID));
1974         }
1975       }
1976       pos.undo_move(move);
1977
1978       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1979
1980       if (TM.thread_should_stop(threadID))
1981       {
1982           lock_grab(&(sp->lock));
1983           break;
1984       }
1985
1986       // New best move?
1987       if (value > sp->bestValue) // Less then 2% of cases
1988       {
1989           lock_grab(&(sp->lock));
1990           if (value > sp->bestValue && !TM.thread_should_stop(threadID))
1991           {
1992               sp->bestValue = value;
1993               if (value > sp->alpha)
1994               {
1995                   // Ask threads to stop before to modify sp->alpha
1996                   if (value >= sp->beta)
1997                   {
1998                       for (int i = 0; i < TM.active_threads(); i++)
1999                           if (i != threadID && (i == sp->master || sp->slaves[i]))
2000                               TM.set_stop_request(i);
2001
2002                       sp->finished = true;
2003                   }
2004
2005                   sp->alpha = value;
2006
2007                   sp_update_pv(sp->parentSstack, ss, sp->ply);
2008                   if (value == value_mate_in(sp->ply + 1))
2009                       ss[sp->ply].mateKiller = move;
2010               }
2011           }
2012           lock_release(&(sp->lock));
2013       }
2014     }
2015
2016     /* Here we have the lock still grabbed */
2017
2018     // If this is the master thread and we have been asked to stop because of
2019     // a beta cutoff higher up in the tree, stop all slave threads.
2020     if (sp->master == threadID && TM.thread_should_stop(threadID))
2021         for (int i = 0; i < TM.active_threads(); i++)
2022             if (sp->slaves[i])
2023                 TM.set_stop_request(i);
2024
2025     sp->cpus--;
2026     sp->slaves[threadID] = 0;
2027
2028     lock_release(&(sp->lock));
2029   }
2030
2031
2032   // init_node() is called at the beginning of all the search functions
2033   // (search(), search_pv(), qsearch(), and so on) and initializes the
2034   // search stack object corresponding to the current node. Once every
2035   // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2036   // for user input and checks whether it is time to stop the search.
2037
2038   void init_node(SearchStack ss[], int ply, int threadID) {
2039
2040     assert(ply >= 0 && ply < PLY_MAX);
2041     assert(threadID >= 0 && threadID < TM.active_threads());
2042
2043     TM.incrementNodeCounter(threadID);
2044
2045     if (threadID == 0)
2046     {
2047         NodesSincePoll++;
2048         if (NodesSincePoll >= NodesBetweenPolls)
2049         {
2050             poll();
2051             NodesSincePoll = 0;
2052         }
2053     }
2054     ss[ply].init(ply);
2055     ss[ply + 2].initKillers();
2056     TM.print_current_line(ss, ply, threadID);
2057   }
2058
2059
2060   // update_pv() is called whenever a search returns a value > alpha.
2061   // It updates the PV in the SearchStack object corresponding to the
2062   // current node.
2063
2064   void update_pv(SearchStack ss[], int ply) {
2065
2066     assert(ply >= 0 && ply < PLY_MAX);
2067
2068     int p;
2069
2070     ss[ply].pv[ply] = ss[ply].currentMove;
2071
2072     for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2073         ss[ply].pv[p] = ss[ply + 1].pv[p];
2074
2075     ss[ply].pv[p] = MOVE_NONE;
2076   }
2077
2078
2079   // sp_update_pv() is a variant of update_pv for use at split points. The
2080   // difference between the two functions is that sp_update_pv also updates
2081   // the PV at the parent node.
2082
2083   void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2084
2085     assert(ply >= 0 && ply < PLY_MAX);
2086
2087     int p;
2088
2089     ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2090
2091     for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2092         ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2093
2094     ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2095   }
2096
2097
2098   // connected_moves() tests whether two moves are 'connected' in the sense
2099   // that the first move somehow made the second move possible (for instance
2100   // if the moving piece is the same in both moves). The first move is assumed
2101   // to be the move that was made to reach the current position, while the
2102   // second move is assumed to be a move from the current position.
2103
2104   bool connected_moves(const Position& pos, Move m1, Move m2) {
2105
2106     Square f1, t1, f2, t2;
2107     Piece p;
2108
2109     assert(move_is_ok(m1));
2110     assert(move_is_ok(m2));
2111
2112     if (m2 == MOVE_NONE)
2113         return false;
2114
2115     // Case 1: The moving piece is the same in both moves
2116     f2 = move_from(m2);
2117     t1 = move_to(m1);
2118     if (f2 == t1)
2119         return true;
2120
2121     // Case 2: The destination square for m2 was vacated by m1
2122     t2 = move_to(m2);
2123     f1 = move_from(m1);
2124     if (t2 == f1)
2125         return true;
2126
2127     // Case 3: Moving through the vacated square
2128     if (   piece_is_slider(pos.piece_on(f2))
2129         && bit_is_set(squares_between(f2, t2), f1))
2130       return true;
2131
2132     // Case 4: The destination square for m2 is defended by the moving piece in m1
2133     p = pos.piece_on(t1);
2134     if (bit_is_set(pos.attacks_from(p, t1), t2))
2135         return true;
2136
2137     // Case 5: Discovered check, checking piece is the piece moved in m1
2138     if (    piece_is_slider(p)
2139         &&  bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2140         && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2141     {
2142         // discovered_check_candidates() works also if the Position's side to
2143         // move is the opposite of the checking piece.
2144         Color them = opposite_color(pos.side_to_move());
2145         Bitboard dcCandidates = pos.discovered_check_candidates(them);
2146
2147         if (bit_is_set(dcCandidates, f2))
2148             return true;
2149     }
2150     return false;
2151   }
2152
2153
2154   // value_is_mate() checks if the given value is a mate one
2155   // eventually compensated for the ply.
2156
2157   bool value_is_mate(Value value) {
2158
2159     assert(abs(value) <= VALUE_INFINITE);
2160
2161     return   value <= value_mated_in(PLY_MAX)
2162           || value >= value_mate_in(PLY_MAX);
2163   }
2164
2165
2166   // move_is_killer() checks if the given move is among the
2167   // killer moves of that ply.
2168
2169   bool move_is_killer(Move m, const SearchStack& ss) {
2170
2171       const Move* k = ss.killers;
2172       for (int i = 0; i < KILLER_MAX; i++, k++)
2173           if (*k == m)
2174               return true;
2175
2176       return false;
2177   }
2178
2179
2180   // extension() decides whether a move should be searched with normal depth,
2181   // or with extended depth. Certain classes of moves (checking moves, in
2182   // particular) are searched with bigger depth than ordinary moves and in
2183   // any case are marked as 'dangerous'. Note that also if a move is not
2184   // extended, as example because the corresponding UCI option is set to zero,
2185   // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2186
2187   Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2188                   bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2189
2190     assert(m != MOVE_NONE);
2191
2192     Depth result = Depth(0);
2193     *dangerous = moveIsCheck | singleEvasion | mateThreat;
2194
2195     if (*dangerous)
2196     {
2197         if (moveIsCheck)
2198             result += CheckExtension[pvNode];
2199
2200         if (singleEvasion)
2201             result += SingleEvasionExtension[pvNode];
2202
2203         if (mateThreat)
2204             result += MateThreatExtension[pvNode];
2205     }
2206
2207     if (pos.type_of_piece_on(move_from(m)) == PAWN)
2208     {
2209         Color c = pos.side_to_move();
2210         if (relative_rank(c, move_to(m)) == RANK_7)
2211         {
2212             result += PawnPushTo7thExtension[pvNode];
2213             *dangerous = true;
2214         }
2215         if (pos.pawn_is_passed(c, move_to(m)))
2216         {
2217             result += PassedPawnExtension[pvNode];
2218             *dangerous = true;
2219         }
2220     }
2221
2222     if (   captureOrPromotion
2223         && pos.type_of_piece_on(move_to(m)) != PAWN
2224         && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2225             - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2226         && !move_is_promotion(m)
2227         && !move_is_ep(m))
2228     {
2229         result += PawnEndgameExtension[pvNode];
2230         *dangerous = true;
2231     }
2232
2233     if (   pvNode
2234         && captureOrPromotion
2235         && pos.type_of_piece_on(move_to(m)) != PAWN
2236         && pos.see_sign(m) >= 0)
2237     {
2238         result += OnePly/2;
2239         *dangerous = true;
2240     }
2241
2242     return Min(result, OnePly);
2243   }
2244
2245
2246   // ok_to_do_nullmove() looks at the current position and decides whether
2247   // doing a 'null move' should be allowed. In order to avoid zugzwang
2248   // problems, null moves are not allowed when the side to move has very
2249   // little material left. Currently, the test is a bit too simple: Null
2250   // moves are avoided only when the side to move has only pawns left.
2251   // It's probably a good idea to avoid null moves in at least some more
2252   // complicated endgames, e.g. KQ vs KR.  FIXME
2253
2254   bool ok_to_do_nullmove(const Position& pos) {
2255
2256     return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2257   }
2258
2259
2260   // ok_to_prune() tests whether it is safe to forward prune a move. Only
2261   // non-tactical moves late in the move list close to the leaves are
2262   // candidates for pruning.
2263
2264   bool ok_to_prune(const Position& pos, Move m, Move threat) {
2265
2266     assert(move_is_ok(m));
2267     assert(threat == MOVE_NONE || move_is_ok(threat));
2268     assert(!pos.move_is_check(m));
2269     assert(!pos.move_is_capture_or_promotion(m));
2270     assert(!pos.move_is_passed_pawn_push(m));
2271
2272     Square mfrom, mto, tfrom, tto;
2273
2274     // Prune if there isn't any threat move
2275     if (threat == MOVE_NONE)
2276         return true;
2277
2278     mfrom = move_from(m);
2279     mto = move_to(m);
2280     tfrom = move_from(threat);
2281     tto = move_to(threat);
2282
2283     // Case 1: Don't prune moves which move the threatened piece
2284     if (mfrom == tto)
2285         return false;
2286
2287     // Case 2: If the threatened piece has value less than or equal to the
2288     // value of the threatening piece, don't prune move which defend it.
2289     if (   pos.move_is_capture(threat)
2290         && (   pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2291             || pos.type_of_piece_on(tfrom) == KING)
2292         && pos.move_attacks_square(m, tto))
2293         return false;
2294
2295     // Case 3: If the moving piece in the threatened move is a slider, don't
2296     // prune safe moves which block its ray.
2297     if (   piece_is_slider(pos.piece_on(tfrom))
2298         && bit_is_set(squares_between(tfrom, tto), mto)
2299         && pos.see_sign(m) >= 0)
2300         return false;
2301
2302     return true;
2303   }
2304
2305
2306   // ok_to_use_TT() returns true if a transposition table score
2307   // can be used at a given point in search.
2308
2309   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2310
2311     Value v = value_from_tt(tte->value(), ply);
2312
2313     return   (   tte->depth() >= depth
2314               || v >= Max(value_mate_in(PLY_MAX), beta)
2315               || v < Min(value_mated_in(PLY_MAX), beta))
2316
2317           && (   (is_lower_bound(tte->type()) && v >= beta)
2318               || (is_upper_bound(tte->type()) && v < beta));
2319   }
2320
2321
2322   // refine_eval() returns the transposition table score if
2323   // possible otherwise falls back on static position evaluation.
2324
2325   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2326
2327       if (!tte)
2328           return defaultEval;
2329
2330       Value v = value_from_tt(tte->value(), ply);
2331
2332       if (   (is_lower_bound(tte->type()) && v >= defaultEval)
2333           || (is_upper_bound(tte->type()) && v < defaultEval))
2334           return v;
2335
2336       return defaultEval;
2337   }
2338
2339
2340   // update_history() registers a good move that produced a beta-cutoff
2341   // in history and marks as failures all the other moves of that ply.
2342
2343   void update_history(const Position& pos, Move move, Depth depth,
2344                       Move movesSearched[], int moveCount) {
2345
2346     Move m;
2347
2348     H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2349
2350     for (int i = 0; i < moveCount - 1; i++)
2351     {
2352         m = movesSearched[i];
2353
2354         assert(m != move);
2355
2356         if (!pos.move_is_capture_or_promotion(m))
2357             H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2358     }
2359   }
2360
2361
2362   // update_killers() add a good move that produced a beta-cutoff
2363   // among the killer moves of that ply.
2364
2365   void update_killers(Move m, SearchStack& ss) {
2366
2367     if (m == ss.killers[0])
2368         return;
2369
2370     for (int i = KILLER_MAX - 1; i > 0; i--)
2371         ss.killers[i] = ss.killers[i - 1];
2372
2373     ss.killers[0] = m;
2374   }
2375
2376
2377   // update_gains() updates the gains table of a non-capture move given
2378   // the static position evaluation before and after the move.
2379
2380   void update_gains(const Position& pos, Move m, Value before, Value after) {
2381
2382     if (   m != MOVE_NULL
2383         && before != VALUE_NONE
2384         && after != VALUE_NONE
2385         && pos.captured_piece() == NO_PIECE_TYPE
2386         && !move_is_castle(m)
2387         && !move_is_promotion(m))
2388         H.set_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
2389   }
2390
2391
2392   // current_search_time() returns the number of milliseconds which have passed
2393   // since the beginning of the current search.
2394
2395   int current_search_time() {
2396
2397     return get_system_time() - SearchStartTime;
2398   }
2399
2400
2401   // nps() computes the current nodes/second count.
2402
2403   int nps() {
2404
2405     int t = current_search_time();
2406     return (t > 0 ? int((TM.nodes_searched() * 1000) / t) : 0);
2407   }
2408
2409
2410   // poll() performs two different functions: It polls for user input, and it
2411   // looks at the time consumed so far and decides if it's time to abort the
2412   // search.
2413
2414   void poll() {
2415
2416     static int lastInfoTime;
2417     int t = current_search_time();
2418
2419     //  Poll for input
2420     if (Bioskey())
2421     {
2422         // We are line oriented, don't read single chars
2423         std::string command;
2424
2425         if (!std::getline(std::cin, command))
2426             command = "quit";
2427
2428         if (command == "quit")
2429         {
2430             AbortSearch = true;
2431             PonderSearch = false;
2432             Quit = true;
2433             return;
2434         }
2435         else if (command == "stop")
2436         {
2437             AbortSearch = true;
2438             PonderSearch = false;
2439         }
2440         else if (command == "ponderhit")
2441             ponderhit();
2442     }
2443
2444     // Print search information
2445     if (t < 1000)
2446         lastInfoTime = 0;
2447
2448     else if (lastInfoTime > t)
2449         // HACK: Must be a new search where we searched less than
2450         // NodesBetweenPolls nodes during the first second of search.
2451         lastInfoTime = 0;
2452
2453     else if (t - lastInfoTime >= 1000)
2454     {
2455         lastInfoTime = t;
2456         lock_grab(&TM.IOLock);
2457
2458         if (dbg_show_mean)
2459             dbg_print_mean();
2460
2461         if (dbg_show_hit_rate)
2462             dbg_print_hit_rate();
2463
2464         cout << "info nodes " << TM.nodes_searched() << " nps " << nps()
2465              << " time " << t << " hashfull " << TT.full() << endl;
2466
2467         lock_release(&TM.IOLock);
2468
2469         if (ShowCurrentLine)
2470             TM.threads[0].printCurrentLineRequest = true;
2471     }
2472
2473     // Should we stop the search?
2474     if (PonderSearch)
2475         return;
2476
2477     bool stillAtFirstMove =    RootMoveNumber == 1
2478                            && !AspirationFailLow
2479                            &&  t > MaxSearchTime + ExtraSearchTime;
2480
2481     bool noMoreTime =   t > AbsoluteMaxSearchTime
2482                      || stillAtFirstMove;
2483
2484     if (   (Iteration >= 3 && UseTimeManagement && noMoreTime)
2485         || (ExactMaxTime && t >= ExactMaxTime)
2486         || (Iteration >= 3 && MaxNodes && TM.nodes_searched() >= MaxNodes))
2487         AbortSearch = true;
2488   }
2489
2490
2491   // ponderhit() is called when the program is pondering (i.e. thinking while
2492   // it's the opponent's turn to move) in order to let the engine know that
2493   // it correctly predicted the opponent's move.
2494
2495   void ponderhit() {
2496
2497     int t = current_search_time();
2498     PonderSearch = false;
2499
2500     bool stillAtFirstMove =    RootMoveNumber == 1
2501                            && !AspirationFailLow
2502                            &&  t > MaxSearchTime + ExtraSearchTime;
2503
2504     bool noMoreTime =   t > AbsoluteMaxSearchTime
2505                      || stillAtFirstMove;
2506
2507     if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2508         AbortSearch = true;
2509   }
2510
2511
2512   // init_ss_array() does a fast reset of the first entries of a SearchStack array
2513
2514   void init_ss_array(SearchStack ss[]) {
2515
2516     for (int i = 0; i < 3; i++)
2517     {
2518         ss[i].init(i);
2519         ss[i].initKillers();
2520     }
2521   }
2522
2523
2524   // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2525   // while the program is pondering. The point is to work around a wrinkle in
2526   // the UCI protocol: When pondering, the engine is not allowed to give a
2527   // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2528   // We simply wait here until one of these commands is sent, and return,
2529   // after which the bestmove and pondermove will be printed (in id_loop()).
2530
2531   void wait_for_stop_or_ponderhit() {
2532
2533     std::string command;
2534
2535     while (true)
2536     {
2537         if (!std::getline(std::cin, command))
2538             command = "quit";
2539
2540         if (command == "quit")
2541         {
2542             Quit = true;
2543             break;
2544         }
2545         else if (command == "ponderhit" || command == "stop")
2546             break;
2547     }
2548   }
2549
2550
2551   // init_thread() is the function which is called when a new thread is
2552   // launched. It simply calls the idle_loop() function with the supplied
2553   // threadID. There are two versions of this function; one for POSIX
2554   // threads and one for Windows threads.
2555
2556 #if !defined(_MSC_VER)
2557
2558   void* init_thread(void *threadID) {
2559
2560     TM.idle_loop(*(int*)threadID, NULL);
2561     return NULL;
2562   }
2563
2564 #else
2565
2566   DWORD WINAPI init_thread(LPVOID threadID) {
2567
2568     TM.idle_loop(*(int*)threadID, NULL);
2569     return NULL;
2570   }
2571
2572 #endif
2573
2574
2575   /// The ThreadsManager class
2576
2577   // resetNodeCounters(), resetBetaCounters(), searched_nodes() and
2578   // get_beta_counters() are getters/setters for the per thread
2579   // counters used to sort the moves at root.
2580
2581   void ThreadsManager::resetNodeCounters() {
2582
2583     for (int i = 0; i < THREAD_MAX; i++)
2584         threads[i].nodes = 0ULL;
2585   }
2586
2587   void ThreadsManager::resetBetaCounters() {
2588
2589     for (int i = 0; i < THREAD_MAX; i++)
2590         threads[i].betaCutOffs[WHITE] = threads[i].betaCutOffs[BLACK] = 0ULL;
2591   }
2592
2593   int64_t ThreadsManager::nodes_searched() const {
2594
2595     int64_t result = 0ULL;
2596     for (int i = 0; i < ActiveThreads; i++)
2597         result += threads[i].nodes;
2598
2599     return result;
2600   }
2601
2602   void ThreadsManager::get_beta_counters(Color us, int64_t& our, int64_t& their) const {
2603
2604     our = their = 0UL;
2605     for (int i = 0; i < THREAD_MAX; i++)
2606     {
2607         our += threads[i].betaCutOffs[us];
2608         their += threads[i].betaCutOffs[opposite_color(us)];
2609     }
2610   }
2611
2612
2613   // idle_loop() is where the threads are parked when they have no work to do.
2614   // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2615   // object for which the current thread is the master.
2616
2617   void ThreadsManager::idle_loop(int threadID, SplitPoint* waitSp) {
2618
2619     assert(threadID >= 0 && threadID < THREAD_MAX);
2620
2621     threads[threadID].running = true;
2622
2623     while (!AllThreadsShouldExit || threadID == 0)
2624     {
2625         // If we are not thinking, wait for a condition to be signaled
2626         // instead of wasting CPU time polling for work.
2627         while (    threadID != 0
2628                && !AllThreadsShouldExit
2629                && (AllThreadsShouldSleep || threadID >= ActiveThreads))
2630         {
2631
2632             threads[threadID].sleeping = true;
2633
2634 #if !defined(_MSC_VER)
2635             pthread_mutex_lock(&WaitLock);
2636             if (AllThreadsShouldSleep || threadID >= ActiveThreads)
2637                 pthread_cond_wait(&WaitCond, &WaitLock);
2638
2639             pthread_mutex_unlock(&WaitLock);
2640 #else
2641             WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2642 #endif
2643         }
2644
2645         // Out of the while loop to avoid races in case thread is woken up but
2646         // while condition still holds true so that is put to sleep again.
2647         threads[threadID].sleeping = false;
2648
2649         // If this thread has been assigned work, launch a search
2650         if (threads[threadID].workIsWaiting)
2651         {
2652             assert(!threads[threadID].idle);
2653
2654             threads[threadID].workIsWaiting = false;
2655             if (threads[threadID].splitPoint->pvNode)
2656                 sp_search_pv(threads[threadID].splitPoint, threadID);
2657             else
2658                 sp_search(threads[threadID].splitPoint, threadID);
2659
2660             threads[threadID].idle = true;
2661         }
2662
2663         // If this thread is the master of a split point and all threads have
2664         // finished their work at this split point, return from the idle loop.
2665         if (waitSp != NULL && waitSp->cpus == 0)
2666             return;
2667     }
2668
2669     threads[threadID].running = false;
2670   }
2671
2672
2673   // init_threads() is called during startup. It launches all helper threads,
2674   // and initializes the split point stack and the global locks and condition
2675   // objects.
2676
2677   void ThreadsManager::init_threads() {
2678
2679     volatile int i;
2680     bool ok;
2681
2682 #if !defined(_MSC_VER)
2683     pthread_t pthread[1];
2684 #endif
2685
2686     // Initialize global locks
2687     lock_init(&MPLock, NULL);
2688     lock_init(&IOLock, NULL);
2689
2690     // Initialize SplitPointStack locks
2691     for (int i = 0; i < THREAD_MAX; i++)
2692         for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2693         {
2694             SplitPointStack[i][j].parent = NULL;
2695             lock_init(&(SplitPointStack[i][j].lock), NULL);
2696         }
2697
2698 #if !defined(_MSC_VER)
2699     pthread_mutex_init(&WaitLock, NULL);
2700     pthread_cond_init(&WaitCond, NULL);
2701 #else
2702     for (i = 0; i < THREAD_MAX; i++)
2703         SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
2704 #endif
2705
2706     // Will be set just before program exits to properly end the threads
2707     AllThreadsShouldExit = false;
2708
2709     // Threads will be put to sleep as soon as created
2710     AllThreadsShouldSleep = true;
2711
2712     // All threads except the main thread should be initialized to idle state
2713     ActiveThreads = 1;
2714     for (i = 1; i < THREAD_MAX; i++)
2715         threads[i].idle = true;
2716
2717     // Launch the helper threads
2718     for (i = 1; i < THREAD_MAX; i++)
2719     {
2720
2721 #if !defined(_MSC_VER)
2722         ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
2723 #else
2724         DWORD iID[1];
2725         ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID) != NULL);
2726 #endif
2727
2728         if (!ok)
2729         {
2730             cout << "Failed to create thread number " << i << endl;
2731             Application::exit_with_failure();
2732         }
2733
2734         // Wait until the thread has finished launching and is gone to sleep
2735         while (!threads[i].running || !threads[i].sleeping);
2736     }
2737   }
2738
2739
2740   // exit_threads() is called when the program exits. It makes all the
2741   // helper threads exit cleanly.
2742
2743   void ThreadsManager::exit_threads() {
2744
2745     ActiveThreads = THREAD_MAX;  // HACK
2746     AllThreadsShouldSleep = true;  // HACK
2747     wake_sleeping_threads();
2748     AllThreadsShouldExit = true;
2749     for (int i = 1; i < THREAD_MAX; i++)
2750     {
2751         threads[i].stop = true;
2752         while (threads[i].running);
2753     }
2754
2755     // Now we can safely destroy the locks
2756     for (int i = 0; i < THREAD_MAX; i++)
2757         for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2758             lock_destroy(&(SplitPointStack[i][j].lock));
2759   }
2760
2761
2762   // thread_should_stop() checks whether the thread with a given threadID has
2763   // been asked to stop, directly or indirectly. This can happen if a beta
2764   // cutoff has occurred in the thread's currently active split point, or in
2765   // some ancestor of the current split point.
2766
2767   bool ThreadsManager::thread_should_stop(int threadID) {
2768
2769     assert(threadID >= 0 && threadID < ActiveThreads);
2770
2771     SplitPoint* sp;
2772
2773     if (threads[threadID].stop)
2774         return true;
2775
2776     if (ActiveThreads <= 2)
2777         return false;
2778
2779     for (sp = threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2780         if (sp->finished)
2781         {
2782             threads[threadID].stop = true;
2783             return true;
2784         }
2785
2786     return false;
2787   }
2788
2789
2790   // thread_is_available() checks whether the thread with threadID "slave" is
2791   // available to help the thread with threadID "master" at a split point. An
2792   // obvious requirement is that "slave" must be idle. With more than two
2793   // threads, this is not by itself sufficient:  If "slave" is the master of
2794   // some active split point, it is only available as a slave to the other
2795   // threads which are busy searching the split point at the top of "slave"'s
2796   // split point stack (the "helpful master concept" in YBWC terminology).
2797
2798   bool ThreadsManager::thread_is_available(int slave, int master) const {
2799
2800     assert(slave >= 0 && slave < ActiveThreads);
2801     assert(master >= 0 && master < ActiveThreads);
2802     assert(ActiveThreads > 1);
2803
2804     if (!threads[slave].idle || slave == master)
2805         return false;
2806
2807     // Make a local copy to be sure doesn't change under our feet
2808     int localActiveSplitPoints = threads[slave].activeSplitPoints;
2809
2810     if (localActiveSplitPoints == 0)
2811         // No active split points means that the thread is available as
2812         // a slave for any other thread.
2813         return true;
2814
2815     if (ActiveThreads == 2)
2816         return true;
2817
2818     // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2819     // that is known to be > 0, instead of threads[slave].activeSplitPoints that
2820     // could have been set to 0 by another thread leading to an out of bound access.
2821     if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
2822         return true;
2823
2824     return false;
2825   }
2826
2827
2828   // idle_thread_exists() tries to find an idle thread which is available as
2829   // a slave for the thread with threadID "master".
2830
2831   bool ThreadsManager::idle_thread_exists(int master) const {
2832
2833     assert(master >= 0 && master < ActiveThreads);
2834     assert(ActiveThreads > 1);
2835
2836     for (int i = 0; i < ActiveThreads; i++)
2837         if (thread_is_available(i, master))
2838             return true;
2839
2840     return false;
2841   }
2842
2843
2844   // split() does the actual work of distributing the work at a node between
2845   // several threads at PV nodes. If it does not succeed in splitting the
2846   // node (because no idle threads are available, or because we have no unused
2847   // split point objects), the function immediately returns false. If
2848   // splitting is possible, a SplitPoint object is initialized with all the
2849   // data that must be copied to the helper threads (the current position and
2850   // search stack, alpha, beta, the search depth, etc.), and we tell our
2851   // helper threads that they have been assigned work. This will cause them
2852   // to instantly leave their idle loops and call sp_search_pv(). When all
2853   // threads have returned from sp_search_pv (or, equivalently, when
2854   // splitPoint->cpus becomes 0), split() returns true.
2855
2856   bool ThreadsManager::split(const Position& p, SearchStack* sstck, int ply,
2857              Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
2858              Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
2859
2860     assert(p.is_ok());
2861     assert(sstck != NULL);
2862     assert(ply >= 0 && ply < PLY_MAX);
2863     assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2864     assert(!pvNode || *alpha < *beta);
2865     assert(*beta <= VALUE_INFINITE);
2866     assert(depth > Depth(0));
2867     assert(master >= 0 && master < ActiveThreads);
2868     assert(ActiveThreads > 1);
2869
2870     SplitPoint* splitPoint;
2871
2872     lock_grab(&MPLock);
2873
2874     // If no other thread is available to help us, or if we have too many
2875     // active split points, don't split.
2876     if (   !idle_thread_exists(master)
2877         || threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
2878     {
2879         lock_release(&MPLock);
2880         return false;
2881     }
2882
2883     // Pick the next available split point object from the split point stack
2884     splitPoint = SplitPointStack[master] + threads[master].activeSplitPoints;
2885     threads[master].activeSplitPoints++;
2886
2887     // Initialize the split point object
2888     splitPoint->parent = threads[master].splitPoint;
2889     splitPoint->finished = false;
2890     splitPoint->ply = ply;
2891     splitPoint->depth = depth;
2892     splitPoint->alpha = pvNode ? *alpha : (*beta - 1);
2893     splitPoint->beta = *beta;
2894     splitPoint->pvNode = pvNode;
2895     splitPoint->bestValue = *bestValue;
2896     splitPoint->futilityValue = futilityValue;
2897     splitPoint->master = master;
2898     splitPoint->mp = mp;
2899     splitPoint->moves = *moves;
2900     splitPoint->cpus = 1;
2901     splitPoint->pos = &p;
2902     splitPoint->parentSstack = sstck;
2903     for (int i = 0; i < ActiveThreads; i++)
2904         splitPoint->slaves[i] = 0;
2905
2906     threads[master].idle = false;
2907     threads[master].stop = false;
2908     threads[master].splitPoint = splitPoint;
2909
2910     // Allocate available threads setting idle flag to false
2911     for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
2912         if (thread_is_available(i, master))
2913         {
2914             threads[i].idle = false;
2915             threads[i].stop = false;
2916             threads[i].splitPoint = splitPoint;
2917             splitPoint->slaves[i] = 1;
2918             splitPoint->cpus++;
2919         }
2920
2921     assert(splitPoint->cpus > 1);
2922
2923     // We can release the lock because master and slave threads are already booked
2924     lock_release(&MPLock);
2925
2926     // Tell the threads that they have work to do. This will make them leave
2927     // their idle loop. But before copy search stack tail for each thread.
2928     for (int i = 0; i < ActiveThreads; i++)
2929         if (i == master || splitPoint->slaves[i])
2930         {
2931             memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 4 * sizeof(SearchStack));
2932             threads[i].workIsWaiting = true; // This makes the slave to exit from idle_loop()
2933         }
2934
2935     // Everything is set up. The master thread enters the idle loop, from
2936     // which it will instantly launch a search, because its workIsWaiting
2937     // slot is 'true'.  We send the split point as a second parameter to the
2938     // idle loop, which means that the main thread will return from the idle
2939     // loop when all threads have finished their work at this split point
2940     // (i.e. when splitPoint->cpus == 0).
2941     idle_loop(master, splitPoint);
2942
2943     // We have returned from the idle loop, which means that all threads are
2944     // finished. Update alpha, beta and bestValue, and return.
2945     lock_grab(&MPLock);
2946
2947     if (pvNode)
2948         *alpha = splitPoint->alpha;
2949
2950     *beta = splitPoint->beta;
2951     *bestValue = splitPoint->bestValue;
2952     threads[master].stop = false;
2953     threads[master].idle = false;
2954     threads[master].activeSplitPoints--;
2955     threads[master].splitPoint = splitPoint->parent;
2956
2957     lock_release(&MPLock);
2958     return true;
2959   }
2960
2961
2962   // wake_sleeping_threads() wakes up all sleeping threads when it is time
2963   // to start a new search from the root.
2964
2965   void ThreadsManager::wake_sleeping_threads() {
2966
2967     assert(AllThreadsShouldSleep);
2968     assert(ActiveThreads > 0);
2969
2970     AllThreadsShouldSleep = false;
2971
2972     if (ActiveThreads == 1)
2973         return;
2974
2975     for (int i = 1; i < ActiveThreads; i++)
2976     {
2977         assert(threads[i].sleeping == true);
2978
2979         threads[i].idle = true;
2980         threads[i].workIsWaiting = false;
2981     }
2982
2983 #if !defined(_MSC_VER)
2984     pthread_mutex_lock(&WaitLock);
2985     pthread_cond_broadcast(&WaitCond);
2986     pthread_mutex_unlock(&WaitLock);
2987 #else
2988     for (int i = 1; i < THREAD_MAX; i++)
2989         SetEvent(SitIdleEvent[i]);
2990 #endif
2991
2992     // Wait for the threads to be all woken up
2993     for (int i = 1; i < ActiveThreads; i++)
2994         while (threads[i].sleeping);
2995   }
2996
2997
2998   // put_threads_to_sleep() makes all the threads go to sleep just before
2999   // to leave think(), at the end of the search. threads should have already
3000   // finished the job and should be idle.
3001
3002   void ThreadsManager::put_threads_to_sleep() {
3003
3004     assert(!AllThreadsShouldSleep);
3005
3006     AllThreadsShouldSleep = true;
3007
3008     // Wait for the threads to be all sleeping
3009     for (int i = 1; i < ActiveThreads; i++)
3010         while (!threads[i].sleeping);
3011   }
3012
3013
3014   // print_current_line() prints _once_ the current line of search for a
3015   // given thread and then setup the print request for the next thread.
3016   // Called when the UCI option UCI_ShowCurrLine is 'true'.
3017
3018   void ThreadsManager::print_current_line(SearchStack ss[], int ply, int threadID) {
3019
3020     assert(ply >= 0 && ply < PLY_MAX);
3021     assert(threadID >= 0 && threadID < ActiveThreads);
3022
3023     if (!threads[threadID].printCurrentLineRequest)
3024         return;
3025
3026     // One shot only
3027     threads[threadID].printCurrentLineRequest = false;
3028
3029     if (!threads[threadID].idle)
3030     {
3031         lock_grab(&IOLock);
3032         cout << "info currline " << (threadID + 1);
3033         for (int p = 0; p < ply; p++)
3034             cout << " " << ss[p].currentMove;
3035
3036         cout << endl;
3037         lock_release(&IOLock);
3038     }
3039
3040     // Setup print request for the next thread ID
3041     if (threadID + 1 < ActiveThreads)
3042         threads[threadID + 1].printCurrentLineRequest = true;
3043   }
3044
3045
3046   /// The RootMoveList class
3047
3048   // RootMoveList c'tor
3049
3050   RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
3051
3052     SearchStack ss[PLY_MAX_PLUS_2];
3053     MoveStack mlist[MaxRootMoves];
3054     StateInfo st;
3055     bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
3056
3057     // Generate all legal moves
3058     MoveStack* last = generate_moves(pos, mlist);
3059
3060     // Add each move to the moves[] array
3061     for (MoveStack* cur = mlist; cur != last; cur++)
3062     {
3063         bool includeMove = includeAllMoves;
3064
3065         for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
3066             includeMove = (searchMoves[k] == cur->move);
3067
3068         if (!includeMove)
3069             continue;
3070
3071         // Find a quick score for the move
3072         init_ss_array(ss);
3073         pos.do_move(cur->move, st);
3074         moves[count].move = cur->move;
3075         moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
3076         moves[count].pv[0] = cur->move;
3077         moves[count].pv[1] = MOVE_NONE;
3078         pos.undo_move(cur->move);
3079         count++;
3080     }
3081     sort();
3082   }
3083
3084
3085   // RootMoveList simple methods definitions
3086
3087   void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
3088
3089     moves[moveNum].nodes = nodes;
3090     moves[moveNum].cumulativeNodes += nodes;
3091   }
3092
3093   void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
3094
3095     moves[moveNum].ourBeta = our;
3096     moves[moveNum].theirBeta = their;
3097   }
3098
3099   void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
3100
3101     int j;
3102
3103     for (j = 0; pv[j] != MOVE_NONE; j++)
3104         moves[moveNum].pv[j] = pv[j];
3105
3106     moves[moveNum].pv[j] = MOVE_NONE;
3107   }
3108
3109
3110   // RootMoveList::sort() sorts the root move list at the beginning of a new
3111   // iteration.
3112
3113   void RootMoveList::sort() {
3114
3115     sort_multipv(count - 1); // Sort all items
3116   }
3117
3118
3119   // RootMoveList::sort_multipv() sorts the first few moves in the root move
3120   // list by their scores and depths. It is used to order the different PVs
3121   // correctly in MultiPV mode.
3122
3123   void RootMoveList::sort_multipv(int n) {
3124
3125     int i,j;
3126
3127     for (i = 1; i <= n; i++)
3128     {
3129         RootMove rm = moves[i];
3130         for (j = i; j > 0 && moves[j - 1] < rm; j--)
3131             moves[j] = moves[j - 1];
3132
3133         moves[j] = rm;
3134     }
3135   }
3136
3137 } // namspace