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