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