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