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