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