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