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