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