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