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