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