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