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