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