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