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