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