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