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