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