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