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