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