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