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