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