]> git.sesse.net Git - stockfish/blob - src/search.cpp
Revert "Implement a fallback system when aspiration search fails low and we are out...
[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     //FIXME: Implement bestValue
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) {
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 <= alpha && 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 > alpha)
1022                   alpha = value;
1023
1024                 // Reset the global variable Problem to false if the value isn't too
1025                 // far below the final value from the last iteration.
1026                 if (value > IterationInfo[Iteration - 1].value() - NoProblemMargin)
1027                     Problem = false;
1028             }
1029             else // MultiPV > 1
1030             {
1031                 rml.sort_multipv(i);
1032                 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1033                 {
1034                     int k;
1035                     std::cout << "info multipv " << j + 1
1036                               << " score " << value_to_string(rml.get_move_score(j))
1037                               << " depth " << ((j <= i)? Iteration : Iteration - 1)
1038                               << " time " << current_search_time()
1039                               << " nodes " << nodes_searched()
1040                               << " nps " << nps()
1041                               << " pv ";
1042
1043                     for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1044                         std::cout << rml.get_move_pv(j, k) << " ";
1045
1046                     std::cout << std::endl;
1047                 }
1048                 alpha = rml.get_move_score(Min(i, MultiPV-1));
1049             }
1050         }
1051
1052         if (alpha <= oldAlpha)
1053           FailLow = true;
1054         else
1055           FailLow = false;
1056
1057     }
1058     return alpha;
1059   }
1060
1061
1062   // search_pv() is the main search function for PV nodes.
1063
1064   Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
1065                   Depth depth, int ply, int threadID) {
1066
1067     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1068     assert(beta > alpha && beta <= VALUE_INFINITE);
1069     assert(ply >= 0 && ply < PLY_MAX);
1070     assert(threadID >= 0 && threadID < ActiveThreads);
1071
1072     if (depth < OnePly)
1073         return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1074
1075     // Initialize, and make an early exit in case of an aborted search,
1076     // an instant draw, maximum ply reached, etc.
1077     init_node(ss, ply, threadID);
1078
1079     // After init_node() that calls poll()
1080     if (AbortSearch || thread_should_stop(threadID))
1081         return Value(0);
1082
1083     if (pos.is_draw())
1084         return VALUE_DRAW;
1085
1086     EvalInfo ei;
1087
1088     if (ply >= PLY_MAX - 1)
1089         return evaluate(pos, ei, threadID);
1090
1091     // Mate distance pruning
1092     Value oldAlpha = alpha;
1093     alpha = Max(value_mated_in(ply), alpha);
1094     beta = Min(value_mate_in(ply+1), beta);
1095     if (alpha >= beta)
1096         return alpha;
1097
1098     // Transposition table lookup. At PV nodes, we don't use the TT for
1099     // pruning, but only for move ordering.
1100     const TTEntry* tte = TT.retrieve(pos);
1101     Move ttMove = (tte ? tte->move() : MOVE_NONE);
1102
1103     // Go with internal iterative deepening if we don't have a TT move
1104     if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1105     {
1106         search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1107         ttMove = ss[ply].pv[ply];
1108     }
1109
1110     // Initialize a MovePicker object for the current position, and prepare
1111     // to search all moves
1112     MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
1113
1114     Move move, movesSearched[256];
1115     int moveCount = 0;
1116     Value value, bestValue = -VALUE_INFINITE;
1117     Bitboard dcCandidates = mp.discovered_check_candidates();
1118     Color us = pos.side_to_move();
1119     bool isCheck = pos.is_check();
1120     bool mateThreat = pos.has_mate_threat(opposite_color(us));
1121
1122     // Loop through all legal moves until no moves remain or a beta cutoff
1123     // occurs.
1124     while (   alpha < beta
1125            && (move = mp.get_next_move()) != MOVE_NONE
1126            && !thread_should_stop(threadID))
1127     {
1128       assert(move_is_ok(move));
1129
1130       bool singleReply = (isCheck && mp.number_of_moves() == 1);
1131       bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1132       bool moveIsCapture = pos.move_is_capture(move);
1133
1134       movesSearched[moveCount++] = ss[ply].currentMove = move;
1135
1136       // Decide the new search depth
1137       bool dangerous;
1138       Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1139       Depth newDepth = depth - OnePly + ext;
1140
1141       // Make and search the move
1142       StateInfo st;
1143       pos.do_move(move, st, dcCandidates);
1144
1145       if (moveCount == 1) // The first move in list is the PV
1146           value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1147       else
1148       {
1149         // Try to reduce non-pv search depth by one ply if move seems not problematic,
1150         // if the move fails high will be re-searched at full depth.
1151         if (    depth >= 2*OnePly
1152             &&  moveCount >= LMRPVMoves
1153             && !dangerous
1154             && !moveIsCapture
1155             && !move_promotion(move)
1156             && !move_is_castle(move)
1157             && !move_is_killer(move, ss[ply]))
1158         {
1159             ss[ply].reduction = OnePly;
1160             value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1161         }
1162         else
1163             value = alpha + 1; // Just to trigger next condition
1164
1165         if (value > alpha) // Go with full depth non-pv search
1166         {
1167             ss[ply].reduction = Depth(0);
1168             value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1169             if (value > alpha && value < beta)
1170             {
1171                 // When the search fails high at ply 1 while searching the first
1172                 // move at the root, set the flag failHighPly1. This is used for
1173                 // time managment:  We don't want to stop the search early in
1174                 // such cases, because resolving the fail high at ply 1 could
1175                 // result in a big drop in score at the root.
1176                 if (ply == 1 && RootMoveNumber == 1)
1177                     Threads[threadID].failHighPly1 = true;
1178
1179                 // A fail high occurred. Re-search at full window (pv search)
1180                 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1181                 Threads[threadID].failHighPly1 = false;
1182           }
1183         }
1184       }
1185       pos.undo_move(move);
1186
1187       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1188
1189       // New best move?
1190       if (value > bestValue)
1191       {
1192           bestValue = value;
1193           if (value > alpha)
1194           {
1195               alpha = value;
1196               update_pv(ss, ply);
1197               if (value == value_mate_in(ply + 1))
1198                   ss[ply].mateKiller = move;
1199           }
1200           // If we are at ply 1, and we are searching the first root move at
1201           // ply 0, set the 'Problem' variable if the score has dropped a lot
1202           // (from the computer's point of view) since the previous iteration:
1203           if (   ply == 1
1204               && Iteration >= 2
1205               && -value <= IterationInfo[Iteration-1].value() - ProblemMargin)
1206               Problem = true;
1207       }
1208
1209       // Split?
1210       if (   ActiveThreads > 1
1211           && bestValue < beta
1212           && depth >= MinimumSplitDepth
1213           && Iteration <= 99
1214           && idle_thread_exists(threadID)
1215           && !AbortSearch
1216           && !thread_should_stop(threadID)
1217           && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1218                    &moveCount, &mp, dcCandidates, threadID, true))
1219           break;
1220     }
1221
1222     // All legal moves have been searched.  A special case: If there were
1223     // no legal moves, it must be mate or stalemate:
1224     if (moveCount == 0)
1225         return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1226
1227     // If the search is not aborted, update the transposition table,
1228     // history counters, and killer moves.
1229     if (AbortSearch || thread_should_stop(threadID))
1230         return bestValue;
1231
1232     if (bestValue <= oldAlpha)
1233         TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1234
1235     else if (bestValue >= beta)
1236     {
1237         BetaCounter.add(pos.side_to_move(), depth, threadID);
1238         Move m = ss[ply].pv[ply];
1239         if (ok_to_history(pos, m)) // Only non capture moves are considered
1240         {
1241             update_history(pos, m, depth, movesSearched, moveCount);
1242             update_killers(m, ss[ply]);
1243         }
1244         TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1245     }
1246     else
1247         TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1248
1249     return bestValue;
1250   }
1251
1252
1253   // search() is the search function for zero-width nodes.
1254
1255   Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1256                int ply, bool allowNullmove, int threadID) {
1257
1258     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1259     assert(ply >= 0 && ply < PLY_MAX);
1260     assert(threadID >= 0 && threadID < ActiveThreads);
1261
1262     if (depth < OnePly)
1263         return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1264
1265     // Initialize, and make an early exit in case of an aborted search,
1266     // an instant draw, maximum ply reached, etc.
1267     init_node(ss, ply, threadID);
1268
1269     // After init_node() that calls poll()
1270     if (AbortSearch || thread_should_stop(threadID))
1271         return Value(0);
1272
1273     if (pos.is_draw())
1274         return VALUE_DRAW;
1275
1276     EvalInfo ei;
1277
1278     if (ply >= PLY_MAX - 1)
1279         return evaluate(pos, ei, threadID);
1280
1281     // Mate distance pruning
1282     if (value_mated_in(ply) >= beta)
1283         return beta;
1284
1285     if (value_mate_in(ply + 1) < beta)
1286         return beta - 1;
1287
1288     // Transposition table lookup
1289     const TTEntry* tte = TT.retrieve(pos);
1290     Move ttMove = (tte ? tte->move() : MOVE_NONE);
1291
1292     if (tte && ok_to_use_TT(tte, depth, beta, ply))
1293     {
1294         ss[ply].currentMove = ttMove; // can be MOVE_NONE
1295         return value_from_tt(tte->value(), ply);
1296     }
1297
1298     Value approximateEval = quick_evaluate(pos);
1299     bool mateThreat = false;
1300     bool isCheck = pos.is_check();
1301
1302     // Null move search
1303     if (    allowNullmove
1304         &&  depth > OnePly
1305         && !isCheck
1306         && !value_is_mate(beta)
1307         &&  ok_to_do_nullmove(pos)
1308         &&  approximateEval >= beta - NullMoveMargin)
1309     {
1310         ss[ply].currentMove = MOVE_NULL;
1311
1312         StateInfo st;
1313         pos.do_null_move(st);
1314         int R = (depth >= 5 * OnePly ? 4 : 3); // Null move dynamic reduction
1315
1316         Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1317
1318         pos.undo_null_move();
1319
1320         if (value_is_mate(nullValue))
1321         {
1322             /* Do not return unproven mates */
1323         }
1324         else if (nullValue >= beta)
1325         {
1326             if (depth < 6 * OnePly)
1327                 return beta;
1328
1329             // Do zugzwang verification search
1330             Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1331             if (v >= beta)
1332                 return beta;
1333         } else {
1334             // The null move failed low, which means that we may be faced with
1335             // some kind of threat. If the previous move was reduced, check if
1336             // the move that refuted the null move was somehow connected to the
1337             // move which was reduced. If a connection is found, return a fail
1338             // low score (which will cause the reduced move to fail high in the
1339             // parent node, which will trigger a re-search with full depth).
1340             if (nullValue == value_mated_in(ply + 2))
1341                 mateThreat = true;
1342
1343             ss[ply].threatMove = ss[ply + 1].currentMove;
1344             if (   depth < ThreatDepth
1345                 && ss[ply - 1].reduction
1346                 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1347                 return beta - 1;
1348         }
1349     }
1350     // Null move search not allowed, try razoring
1351     else if (   !value_is_mate(beta)
1352              && approximateEval < beta - RazorMargin
1353              && depth < RazorDepth
1354              && (RazorAtDepthOne || depth > OnePly)
1355              && ttMove == MOVE_NONE
1356              && !pos.has_pawn_on_7th(pos.side_to_move()))
1357     {
1358         Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1359         if (   (v < beta - RazorMargin - RazorMargin / 4)
1360             || (depth <= 2*OnePly && v < beta - RazorMargin)
1361             || (depth <=   OnePly && v < beta - RazorMargin / 2))
1362             return v;
1363     }
1364
1365     // Go with internal iterative deepening if we don't have a TT move
1366     if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1367         evaluate(pos, ei, threadID) >= beta - IIDMargin)
1368     {
1369         search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1370         ttMove = ss[ply].pv[ply];
1371     }
1372
1373     // Initialize a MovePicker object for the current position, and prepare
1374     // to search all moves:
1375     MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1376
1377     Move move, movesSearched[256];
1378     int moveCount = 0;
1379     Value value, bestValue = -VALUE_INFINITE;
1380     Bitboard dcCandidates = mp.discovered_check_candidates();
1381     Value futilityValue = VALUE_NONE;
1382     bool useFutilityPruning =   UseFutilityPruning
1383                              && depth < SelectiveDepth
1384                              && !isCheck;
1385
1386     // Loop through all legal moves until no moves remain or a beta cutoff
1387     // occurs.
1388     while (   bestValue < beta
1389            && (move = mp.get_next_move()) != MOVE_NONE
1390            && !thread_should_stop(threadID))
1391     {
1392       assert(move_is_ok(move));
1393
1394       bool singleReply = (isCheck && mp.number_of_moves() == 1);
1395       bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1396       bool moveIsCapture = pos.move_is_capture(move);
1397
1398       movesSearched[moveCount++] = ss[ply].currentMove = move;
1399
1400       // Decide the new search depth
1401       bool dangerous;
1402       Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1403       Depth newDepth = depth - OnePly + ext;
1404
1405       // Futility pruning
1406       if (    useFutilityPruning
1407           && !dangerous
1408           && !moveIsCapture
1409           && !move_promotion(move))
1410       {
1411           // History pruning. See ok_to_prune() definition
1412           if (   moveCount >= 2 + int(depth)
1413               && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1414               continue;
1415
1416           // Value based pruning
1417           if (depth < 7 * OnePly && approximateEval < beta)
1418           {
1419               if (futilityValue == VALUE_NONE)
1420                   futilityValue =  evaluate(pos, ei, threadID)
1421                                  + FutilityMargins[int(depth)/2 - 1]
1422                                  + 32 * (depth & 1);
1423
1424               if (futilityValue < beta)
1425               {
1426                   if (futilityValue > bestValue)
1427                       bestValue = futilityValue;
1428                   continue;
1429               }
1430           }
1431       }
1432
1433       // Make and search the move
1434       StateInfo st;
1435       pos.do_move(move, st, dcCandidates);
1436
1437       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1438       // if the move fails high will be re-searched at full depth.
1439       if (    depth >= 2*OnePly
1440           &&  moveCount >= LMRNonPVMoves
1441           && !dangerous
1442           && !moveIsCapture
1443           && !move_promotion(move)
1444           && !move_is_castle(move)
1445           && !move_is_killer(move, ss[ply]))
1446       {
1447           ss[ply].reduction = OnePly;
1448           value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1449       }
1450       else
1451         value = beta; // Just to trigger next condition
1452
1453       if (value >= beta) // Go with full depth non-pv search
1454       {
1455           ss[ply].reduction = Depth(0);
1456           value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1457       }
1458       pos.undo_move(move);
1459
1460       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1461
1462       // New best move?
1463       if (value > bestValue)
1464       {
1465         bestValue = value;
1466         if (value >= beta)
1467             update_pv(ss, ply);
1468
1469         if (value == value_mate_in(ply + 1))
1470             ss[ply].mateKiller = move;
1471       }
1472
1473       // Split?
1474       if (   ActiveThreads > 1
1475           && bestValue < beta
1476           && depth >= MinimumSplitDepth
1477           && Iteration <= 99
1478           && idle_thread_exists(threadID)
1479           && !AbortSearch
1480           && !thread_should_stop(threadID)
1481           && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1482                    &mp, dcCandidates, threadID, false))
1483         break;
1484     }
1485
1486     // All legal moves have been searched.  A special case: If there were
1487     // no legal moves, it must be mate or stalemate.
1488     if (moveCount == 0)
1489         return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1490
1491     // If the search is not aborted, update the transposition table,
1492     // history counters, and killer moves.
1493     if (AbortSearch || thread_should_stop(threadID))
1494         return bestValue;
1495
1496     if (bestValue < beta)
1497         TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1498     else
1499     {
1500         BetaCounter.add(pos.side_to_move(), depth, threadID);
1501         Move m = ss[ply].pv[ply];
1502         if (ok_to_history(pos, m)) // Only non capture moves are considered
1503         {
1504             update_history(pos, m, depth, movesSearched, moveCount);
1505             update_killers(m, ss[ply]);
1506         }
1507         TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1508     }
1509
1510     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1511
1512     return bestValue;
1513   }
1514
1515
1516   // qsearch() is the quiescence search function, which is called by the main
1517   // search function when the remaining depth is zero (or, to be more precise,
1518   // less than OnePly).
1519
1520   Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1521                 Depth depth, int ply, int threadID) {
1522
1523     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1524     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1525     assert(depth <= 0);
1526     assert(ply >= 0 && ply < PLY_MAX);
1527     assert(threadID >= 0 && threadID < ActiveThreads);
1528
1529     // Initialize, and make an early exit in case of an aborted search,
1530     // an instant draw, maximum ply reached, etc.
1531     init_node(ss, ply, threadID);
1532
1533     // After init_node() that calls poll()
1534     if (AbortSearch || thread_should_stop(threadID))
1535         return Value(0);
1536
1537     if (pos.is_draw())
1538         return VALUE_DRAW;
1539
1540     // Transposition table lookup, only when not in PV
1541     TTEntry* tte = NULL;
1542     bool pvNode = (beta - alpha != 1);
1543     if (!pvNode)
1544     {
1545         tte = TT.retrieve(pos);
1546         if (tte && ok_to_use_TT(tte, depth, beta, ply))
1547         {
1548             assert(tte->type() != VALUE_TYPE_EVAL);
1549
1550             return value_from_tt(tte->value(), ply);
1551         }
1552     }
1553
1554     // Evaluate the position statically
1555     EvalInfo ei;
1556     Value staticValue;
1557     bool isCheck = pos.is_check();
1558     ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1559
1560     if (isCheck)
1561         staticValue = -VALUE_INFINITE;
1562
1563     else if (tte && tte->type() == VALUE_TYPE_EVAL)
1564     {
1565         // Use the cached evaluation score if possible
1566         assert(tte->value() == evaluate(pos, ei, threadID));
1567         assert(ei.futilityMargin == Value(0));
1568
1569         staticValue = tte->value();
1570     }
1571     else
1572         staticValue = evaluate(pos, ei, threadID);
1573
1574     if (ply == PLY_MAX - 1)
1575         return evaluate(pos, ei, threadID);
1576
1577     // Initialize "stand pat score", and return it immediately if it is
1578     // at least beta.
1579     Value bestValue = staticValue;
1580
1581     if (bestValue >= beta)
1582     {
1583         // Store the score to avoid a future costly evaluation() call
1584         if (!isCheck && !tte && ei.futilityMargin == 0)
1585             TT.store(pos, value_to_tt(bestValue, ply), Depth(-127*OnePly), MOVE_NONE, VALUE_TYPE_EVAL);
1586
1587         return bestValue;
1588     }
1589
1590     if (bestValue > alpha)
1591         alpha = bestValue;
1592
1593     // Initialize a MovePicker object for the current position, and prepare
1594     // to search the moves.  Because the depth is <= 0 here, only captures,
1595     // queen promotions and checks (only if depth == 0) will be generated.
1596     MovePicker mp = MovePicker(pos, pvNode, MOVE_NONE, EmptySearchStack, depth);
1597     Move move;
1598     int moveCount = 0;
1599     Bitboard dcCandidates = mp.discovered_check_candidates();
1600     Color us = pos.side_to_move();
1601     bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1602
1603     // Loop through the moves until no moves remain or a beta cutoff
1604     // occurs.
1605     while (   alpha < beta
1606            && (move = mp.get_next_move()) != MOVE_NONE)
1607     {
1608       assert(move_is_ok(move));
1609
1610       moveCount++;
1611       ss[ply].currentMove = move;
1612
1613       // Futility pruning
1614       if (    UseQSearchFutilityPruning
1615           &&  enoughMaterial
1616           && !isCheck
1617           && !pvNode
1618           && !move_promotion(move)
1619           && !pos.move_is_check(move, dcCandidates)
1620           && !pos.move_is_passed_pawn_push(move))
1621       {
1622           Value futilityValue = staticValue
1623                               + Max(pos.midgame_value_of_piece_on(move_to(move)),
1624                                     pos.endgame_value_of_piece_on(move_to(move)))
1625                               + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1626                               + FutilityMarginQS
1627                               + ei.futilityMargin;
1628
1629           if (futilityValue < alpha)
1630           {
1631               if (futilityValue > bestValue)
1632                   bestValue = futilityValue;
1633               continue;
1634           }
1635       }
1636
1637       // Don't search captures and checks with negative SEE values
1638       if (   !isCheck
1639           && !move_promotion(move)
1640           && (pos.midgame_value_of_piece_on(move_from(move)) >
1641               pos.midgame_value_of_piece_on(move_to(move)))
1642           &&  pos.see(move) < 0)
1643           continue;
1644
1645       // Make and search the move.
1646       StateInfo st;
1647       pos.do_move(move, st, dcCandidates);
1648       Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1649       pos.undo_move(move);
1650
1651       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1652
1653       // New best move?
1654       if (value > bestValue)
1655       {
1656           bestValue = value;
1657           if (value > alpha)
1658           {
1659               alpha = value;
1660               update_pv(ss, ply);
1661           }
1662        }
1663     }
1664
1665     // All legal moves have been searched.  A special case: If we're in check
1666     // and no legal moves were found, it is checkmate:
1667     if (pos.is_check() && moveCount == 0) // Mate!
1668         return value_mated_in(ply);
1669
1670     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1671
1672     // Update transposition table
1673     if (!pvNode)
1674     {
1675         Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1676         if (bestValue < beta)
1677             TT.store(pos, value_to_tt(bestValue, ply), d, MOVE_NONE, VALUE_TYPE_UPPER);
1678         else
1679             TT.store(pos, value_to_tt(bestValue, ply), d, MOVE_NONE, VALUE_TYPE_LOWER);
1680     }
1681
1682     // Update killers only for good check moves
1683     Move m = ss[ply].currentMove;
1684     if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1685     {
1686         // Wrong to update history when depth is <= 0
1687         update_killers(m, ss[ply]);
1688     }
1689     return bestValue;
1690   }
1691
1692
1693   // sp_search() is used to search from a split point.  This function is called
1694   // by each thread working at the split point.  It is similar to the normal
1695   // search() function, but simpler.  Because we have already probed the hash
1696   // table, done a null move search, and searched the first move before
1697   // splitting, we don't have to repeat all this work in sp_search().  We
1698   // also don't need to store anything to the hash table here:  This is taken
1699   // care of after we return from the split point.
1700
1701   void sp_search(SplitPoint *sp, int threadID) {
1702
1703     assert(threadID >= 0 && threadID < ActiveThreads);
1704     assert(ActiveThreads > 1);
1705
1706     Position pos = Position(sp->pos);
1707     SearchStack *ss = sp->sstack[threadID];
1708     Value value;
1709     Move move;
1710     bool isCheck = pos.is_check();
1711     bool useFutilityPruning =    UseFutilityPruning
1712                               && sp->depth < SelectiveDepth
1713                               && !isCheck;
1714
1715     while (    sp->bestValue < sp->beta
1716            && !thread_should_stop(threadID)
1717            && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1718     {
1719       assert(move_is_ok(move));
1720
1721       bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1722       bool moveIsCapture = pos.move_is_capture(move);
1723
1724       lock_grab(&(sp->lock));
1725       int moveCount = ++sp->moves;
1726       lock_release(&(sp->lock));
1727
1728       ss[sp->ply].currentMove = move;
1729
1730       // Decide the new search depth.
1731       bool dangerous;
1732       Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1733       Depth newDepth = sp->depth - OnePly + ext;
1734
1735       // Prune?
1736       if (    useFutilityPruning
1737           && !dangerous
1738           && !moveIsCapture
1739           && !move_promotion(move)
1740           &&  moveCount >= 2 + int(sp->depth)
1741           &&  ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1742         continue;
1743
1744       // Make and search the move.
1745       StateInfo st;
1746       pos.do_move(move, st, sp->dcCandidates);
1747
1748       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1749       // if the move fails high will be re-searched at full depth.
1750       if (   !dangerous
1751           &&  moveCount >= LMRNonPVMoves
1752           && !moveIsCapture
1753           && !move_promotion(move)
1754           && !move_is_castle(move)
1755           && !move_is_killer(move, ss[sp->ply]))
1756       {
1757           ss[sp->ply].reduction = OnePly;
1758           value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1759       }
1760       else
1761           value = sp->beta; // Just to trigger next condition
1762
1763       if (value >= sp->beta) // Go with full depth non-pv search
1764       {
1765           ss[sp->ply].reduction = Depth(0);
1766           value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1767       }
1768       pos.undo_move(move);
1769
1770       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1771
1772       if (thread_should_stop(threadID))
1773           break;
1774
1775       // New best move?
1776       lock_grab(&(sp->lock));
1777       if (value > sp->bestValue && !thread_should_stop(threadID))
1778       {
1779           sp->bestValue = value;
1780           if (sp->bestValue >= sp->beta)
1781           {
1782               sp_update_pv(sp->parentSstack, ss, sp->ply);
1783               for (int i = 0; i < ActiveThreads; i++)
1784                   if (i != threadID && (i == sp->master || sp->slaves[i]))
1785                       Threads[i].stop = true;
1786
1787               sp->finished = true;
1788         }
1789       }
1790       lock_release(&(sp->lock));
1791     }
1792
1793     lock_grab(&(sp->lock));
1794
1795     // If this is the master thread and we have been asked to stop because of
1796     // a beta cutoff higher up in the tree, stop all slave threads:
1797     if (sp->master == threadID && thread_should_stop(threadID))
1798         for (int i = 0; i < ActiveThreads; i++)
1799             if (sp->slaves[i])
1800                 Threads[i].stop = true;
1801
1802     sp->cpus--;
1803     sp->slaves[threadID] = 0;
1804
1805     lock_release(&(sp->lock));
1806   }
1807
1808
1809   // sp_search_pv() is used to search from a PV split point.  This function
1810   // is called by each thread working at the split point.  It is similar to
1811   // the normal search_pv() function, but simpler.  Because we have already
1812   // probed the hash table and searched the first move before splitting, we
1813   // don't have to repeat all this work in sp_search_pv().  We also don't
1814   // need to store anything to the hash table here:  This is taken care of
1815   // after we return from the split point.
1816
1817   void sp_search_pv(SplitPoint *sp, int threadID) {
1818
1819     assert(threadID >= 0 && threadID < ActiveThreads);
1820     assert(ActiveThreads > 1);
1821
1822     Position pos = Position(sp->pos);
1823     SearchStack *ss = sp->sstack[threadID];
1824     Value value;
1825     Move move;
1826
1827     while (    sp->alpha < sp->beta
1828            && !thread_should_stop(threadID)
1829            && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1830     {
1831       bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1832       bool moveIsCapture = pos.move_is_capture(move);
1833
1834       assert(move_is_ok(move));
1835
1836       lock_grab(&(sp->lock));
1837       int moveCount = ++sp->moves;
1838       lock_release(&(sp->lock));
1839
1840       ss[sp->ply].currentMove = move;
1841
1842       // Decide the new search depth.
1843       bool dangerous;
1844       Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1845       Depth newDepth = sp->depth - OnePly + ext;
1846
1847       // Make and search the move.
1848       StateInfo st;
1849       pos.do_move(move, st, sp->dcCandidates);
1850
1851       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1852       // if the move fails high will be re-searched at full depth.
1853       if (   !dangerous
1854           &&  moveCount >= LMRPVMoves
1855           && !moveIsCapture
1856           && !move_promotion(move)
1857           && !move_is_castle(move)
1858           && !move_is_killer(move, ss[sp->ply]))
1859       {
1860           ss[sp->ply].reduction = OnePly;
1861           value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1862       }
1863       else
1864           value = sp->alpha + 1; // Just to trigger next condition
1865
1866       if (value > sp->alpha) // Go with full depth non-pv search
1867       {
1868           ss[sp->ply].reduction = Depth(0);
1869           value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1870
1871           if (value > sp->alpha && value < sp->beta)
1872           {
1873               // When the search fails high at ply 1 while searching the first
1874               // move at the root, set the flag failHighPly1.  This is used for
1875               // time managment:  We don't want to stop the search early in
1876               // such cases, because resolving the fail high at ply 1 could
1877               // result in a big drop in score at the root.
1878               if (sp->ply == 1 && RootMoveNumber == 1)
1879                   Threads[threadID].failHighPly1 = true;
1880
1881               value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1882               Threads[threadID].failHighPly1 = false;
1883         }
1884       }
1885       pos.undo_move(move);
1886
1887       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1888
1889       if (thread_should_stop(threadID))
1890           break;
1891
1892       // New best move?
1893       lock_grab(&(sp->lock));
1894       if (value > sp->bestValue && !thread_should_stop(threadID))
1895       {
1896           sp->bestValue = value;
1897           if (value > sp->alpha)
1898           {
1899               sp->alpha = value;
1900               sp_update_pv(sp->parentSstack, ss, sp->ply);
1901               if (value == value_mate_in(sp->ply + 1))
1902                   ss[sp->ply].mateKiller = move;
1903
1904               if(value >= sp->beta)
1905               {
1906                   for(int i = 0; i < ActiveThreads; i++)
1907                       if(i != threadID && (i == sp->master || sp->slaves[i]))
1908                           Threads[i].stop = true;
1909
1910                   sp->finished = true;
1911               }
1912         }
1913         // If we are at ply 1, and we are searching the first root move at
1914         // ply 0, set the 'Problem' variable if the score has dropped a lot
1915         // (from the computer's point of view) since the previous iteration.
1916         if (   sp->ply == 1
1917             && Iteration >= 2
1918             && -value <= IterationInfo[Iteration-1].value() - ProblemMargin)
1919             Problem = true;
1920       }
1921       lock_release(&(sp->lock));
1922     }
1923
1924     lock_grab(&(sp->lock));
1925
1926     // If this is the master thread and we have been asked to stop because of
1927     // a beta cutoff higher up in the tree, stop all slave threads.
1928     if (sp->master == threadID && thread_should_stop(threadID))
1929         for (int i = 0; i < ActiveThreads; i++)
1930             if (sp->slaves[i])
1931                 Threads[i].stop = true;
1932
1933     sp->cpus--;
1934     sp->slaves[threadID] = 0;
1935
1936     lock_release(&(sp->lock));
1937   }
1938
1939   /// The BetaCounterType class
1940
1941   BetaCounterType::BetaCounterType() { clear(); }
1942
1943   void BetaCounterType::clear() {
1944
1945     for (int i = 0; i < THREAD_MAX; i++)
1946         hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1947   }
1948
1949   void BetaCounterType::add(Color us, Depth d, int threadID) {
1950
1951     // Weighted count based on depth
1952     hits[threadID][us] += int(d);
1953   }
1954
1955   void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1956
1957     our = their = 0UL;
1958     for (int i = 0; i < THREAD_MAX; i++)
1959     {
1960         our += hits[i][us];
1961         their += hits[i][opposite_color(us)];
1962     }
1963   }
1964
1965
1966   /// The RootMove class
1967
1968   // Constructor
1969
1970   RootMove::RootMove() {
1971     nodes = cumulativeNodes = 0ULL;
1972   }
1973
1974   // RootMove::operator<() is the comparison function used when
1975   // sorting the moves.  A move m1 is considered to be better
1976   // than a move m2 if it has a higher score, or if the moves
1977   // have equal score but m1 has the higher node count.
1978
1979   bool RootMove::operator<(const RootMove& m) {
1980
1981     if (score != m.score)
1982         return (score < m.score);
1983
1984     return theirBeta <= m.theirBeta;
1985   }
1986
1987   /// The RootMoveList class
1988
1989   // Constructor
1990
1991   RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1992
1993     MoveStack mlist[MaxRootMoves];
1994     bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1995
1996     // Generate all legal moves
1997     int lm_count = generate_legal_moves(pos, mlist);
1998
1999     // Add each move to the moves[] array
2000     for (int i = 0; i < lm_count; i++)
2001     {
2002         bool includeMove = includeAllMoves;
2003
2004         for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2005             includeMove = (searchMoves[k] == mlist[i].move);
2006
2007         if (includeMove)
2008         {
2009             // Find a quick score for the move
2010             StateInfo st;
2011             SearchStack ss[PLY_MAX_PLUS_2];
2012
2013             moves[count].move = mlist[i].move;
2014             moves[count].nodes = 0ULL;
2015             pos.do_move(moves[count].move, st);
2016             moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
2017                                           Depth(0), 1, 0);
2018             pos.undo_move(moves[count].move);
2019             moves[count].pv[0] = moves[i].move;
2020             moves[count].pv[1] = MOVE_NONE; // FIXME
2021             count++;
2022         }
2023     }
2024     sort();
2025   }
2026
2027
2028   // Simple accessor methods for the RootMoveList class
2029
2030   inline Move RootMoveList::get_move(int moveNum) const {
2031     return moves[moveNum].move;
2032   }
2033
2034   inline Value RootMoveList::get_move_score(int moveNum) const {
2035     return moves[moveNum].score;
2036   }
2037
2038   inline void RootMoveList::set_move_score(int moveNum, Value score) {
2039     moves[moveNum].score = score;
2040   }
2041
2042   inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2043     moves[moveNum].nodes = nodes;
2044     moves[moveNum].cumulativeNodes += nodes;
2045   }
2046
2047   inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2048     moves[moveNum].ourBeta = our;
2049     moves[moveNum].theirBeta = their;
2050   }
2051
2052   void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2053     int j;
2054     for(j = 0; pv[j] != MOVE_NONE; j++)
2055       moves[moveNum].pv[j] = pv[j];
2056     moves[moveNum].pv[j] = MOVE_NONE;
2057   }
2058
2059   inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
2060     return moves[moveNum].pv[i];
2061   }
2062
2063   inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
2064     return moves[moveNum].cumulativeNodes;
2065   }
2066
2067   inline int RootMoveList::move_count() const {
2068     return count;
2069   }
2070
2071
2072   // RootMoveList::scan_for_easy_move() is called at the end of the first
2073   // iteration, and is used to detect an "easy move", i.e. a move which appears
2074   // to be much bester than all the rest.  If an easy move is found, the move
2075   // is returned, otherwise the function returns MOVE_NONE.  It is very
2076   // important that this function is called at the right moment:  The code
2077   // assumes that the first iteration has been completed and the moves have
2078   // been sorted. This is done in RootMoveList c'tor.
2079
2080   Move RootMoveList::scan_for_easy_move() const {
2081
2082     assert(count);
2083
2084     if (count == 1)
2085         return get_move(0);
2086
2087     // moves are sorted so just consider the best and the second one
2088     if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2089         return get_move(0);
2090
2091     return MOVE_NONE;
2092   }
2093
2094   // RootMoveList::sort() sorts the root move list at the beginning of a new
2095   // iteration.
2096
2097   inline void RootMoveList::sort() {
2098
2099     sort_multipv(count - 1); // all items
2100   }
2101
2102
2103   // RootMoveList::sort_multipv() sorts the first few moves in the root move
2104   // list by their scores and depths. It is used to order the different PVs
2105   // correctly in MultiPV mode.
2106
2107   void RootMoveList::sort_multipv(int n) {
2108
2109     for (int i = 1; i <= n; i++)
2110     {
2111       RootMove rm = moves[i];
2112       int j;
2113       for (j = i; j > 0 && moves[j-1] < rm; j--)
2114           moves[j] = moves[j-1];
2115       moves[j] = rm;
2116     }
2117   }
2118
2119
2120   // init_node() is called at the beginning of all the search functions
2121   // (search(), search_pv(), qsearch(), and so on) and initializes the search
2122   // stack object corresponding to the current node.  Once every
2123   // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2124   // for user input and checks whether it is time to stop the search.
2125
2126   void init_node(SearchStack ss[], int ply, int threadID) {
2127     assert(ply >= 0 && ply < PLY_MAX);
2128     assert(threadID >= 0 && threadID < ActiveThreads);
2129
2130     Threads[threadID].nodes++;
2131
2132     if(threadID == 0) {
2133       NodesSincePoll++;
2134       if(NodesSincePoll >= NodesBetweenPolls) {
2135         poll();
2136         NodesSincePoll = 0;
2137       }
2138     }
2139
2140     ss[ply].init(ply);
2141     ss[ply+2].initKillers();
2142
2143     if(Threads[threadID].printCurrentLine)
2144       print_current_line(ss, ply, threadID);
2145   }
2146
2147
2148   // update_pv() is called whenever a search returns a value > alpha.  It
2149   // updates the PV in the SearchStack object corresponding to the current
2150   // node.
2151
2152   void update_pv(SearchStack ss[], int ply) {
2153     assert(ply >= 0 && ply < PLY_MAX);
2154
2155     ss[ply].pv[ply] = ss[ply].currentMove;
2156     int p;
2157     for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2158       ss[ply].pv[p] = ss[ply+1].pv[p];
2159     ss[ply].pv[p] = MOVE_NONE;
2160   }
2161
2162
2163   // sp_update_pv() is a variant of update_pv for use at split points.  The
2164   // difference between the two functions is that sp_update_pv also updates
2165   // the PV at the parent node.
2166
2167   void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2168     assert(ply >= 0 && ply < PLY_MAX);
2169
2170     ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2171     int p;
2172     for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2173       ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2174     ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2175   }
2176
2177
2178   // connected_moves() tests whether two moves are 'connected' in the sense
2179   // that the first move somehow made the second move possible (for instance
2180   // if the moving piece is the same in both moves).  The first move is
2181   // assumed to be the move that was made to reach the current position, while
2182   // the second move is assumed to be a move from the current position.
2183
2184   bool connected_moves(const Position &pos, Move m1, Move m2) {
2185     Square f1, t1, f2, t2;
2186
2187     assert(move_is_ok(m1));
2188     assert(move_is_ok(m2));
2189
2190     if(m2 == MOVE_NONE)
2191       return false;
2192
2193     // Case 1: The moving piece is the same in both moves.
2194     f2 = move_from(m2);
2195     t1 = move_to(m1);
2196     if(f2 == t1)
2197       return true;
2198
2199     // Case 2: The destination square for m2 was vacated by m1.
2200     t2 = move_to(m2);
2201     f1 = move_from(m1);
2202     if(t2 == f1)
2203       return true;
2204
2205     // Case 3: Moving through the vacated square:
2206     if(piece_is_slider(pos.piece_on(f2)) &&
2207        bit_is_set(squares_between(f2, t2), f1))
2208       return true;
2209
2210     // Case 4: The destination square for m2 is attacked by the moving piece
2211     // in m1:
2212     if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2213       return true;
2214
2215     // Case 5: Discovered check, checking piece is the piece moved in m1:
2216     if(piece_is_slider(pos.piece_on(t1)) &&
2217        bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2218                   f2) &&
2219        !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2220                    t2)) {
2221       Bitboard occ = pos.occupied_squares();
2222       Color us = pos.side_to_move();
2223       Square ksq = pos.king_square(us);
2224       clear_bit(&occ, f2);
2225       if(pos.type_of_piece_on(t1) == BISHOP) {
2226         if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2227           return true;
2228       }
2229       else if(pos.type_of_piece_on(t1) == ROOK) {
2230         if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2231           return true;
2232       }
2233       else {
2234         assert(pos.type_of_piece_on(t1) == QUEEN);
2235         if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2236           return true;
2237       }
2238     }
2239
2240     return false;
2241   }
2242
2243
2244   // value_is_mate() checks if the given value is a mate one
2245   // eventually compensated for the ply.
2246
2247   bool value_is_mate(Value value) {
2248
2249     assert(abs(value) <= VALUE_INFINITE);
2250
2251     return   value <= value_mated_in(PLY_MAX)
2252           || value >= value_mate_in(PLY_MAX);
2253   }
2254
2255
2256   // move_is_killer() checks if the given move is among the
2257   // killer moves of that ply.
2258
2259   bool move_is_killer(Move m, const SearchStack& ss) {
2260
2261       const Move* k = ss.killers;
2262       for (int i = 0; i < KILLER_MAX; i++, k++)
2263           if (*k == m)
2264               return true;
2265
2266       return false;
2267   }
2268
2269
2270   // extension() decides whether a move should be searched with normal depth,
2271   // or with extended depth.  Certain classes of moves (checking moves, in
2272   // particular) are searched with bigger depth than ordinary moves and in
2273   // any case are marked as 'dangerous'. Note that also if a move is not
2274   // extended, as example because the corresponding UCI option is set to zero,
2275   // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2276
2277   Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2278                   bool singleReply, bool mateThreat, bool* dangerous) {
2279
2280     assert(m != MOVE_NONE);
2281
2282     Depth result = Depth(0);
2283     *dangerous = check || singleReply || mateThreat;
2284
2285     if (check)
2286         result += CheckExtension[pvNode];
2287
2288     if (singleReply)
2289         result += SingleReplyExtension[pvNode];
2290
2291     if (mateThreat)
2292         result += MateThreatExtension[pvNode];
2293
2294     if (pos.type_of_piece_on(move_from(m)) == PAWN)
2295     {
2296         if (pos.move_is_pawn_push_to_7th(m))
2297         {
2298             result += PawnPushTo7thExtension[pvNode];
2299             *dangerous = true;
2300         }
2301         if (pos.move_is_passed_pawn_push(m))
2302         {
2303             result += PassedPawnExtension[pvNode];
2304             *dangerous = true;
2305         }
2306     }
2307
2308     if (   capture
2309         && pos.type_of_piece_on(move_to(m)) != PAWN
2310         && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2311             - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2312         && !move_promotion(m)
2313         && !move_is_ep(m))
2314     {
2315         result += PawnEndgameExtension[pvNode];
2316         *dangerous = true;
2317     }
2318
2319     if (   pvNode
2320         && capture
2321         && pos.type_of_piece_on(move_to(m)) != PAWN
2322         && pos.see(m) >= 0)
2323     {
2324         result += OnePly/2;
2325         *dangerous = true;
2326     }
2327
2328     return Min(result, OnePly);
2329   }
2330
2331
2332   // ok_to_do_nullmove() looks at the current position and decides whether
2333   // doing a 'null move' should be allowed.  In order to avoid zugzwang
2334   // problems, null moves are not allowed when the side to move has very
2335   // little material left.  Currently, the test is a bit too simple:  Null
2336   // moves are avoided only when the side to move has only pawns left.  It's
2337   // probably a good idea to avoid null moves in at least some more
2338   // complicated endgames, e.g. KQ vs KR.  FIXME
2339
2340   bool ok_to_do_nullmove(const Position &pos) {
2341     if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2342       return false;
2343     return true;
2344   }
2345
2346
2347   // ok_to_prune() tests whether it is safe to forward prune a move.  Only
2348   // non-tactical moves late in the move list close to the leaves are
2349   // candidates for pruning.
2350
2351   bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2352     Square mfrom, mto, tfrom, tto;
2353
2354     assert(move_is_ok(m));
2355     assert(threat == MOVE_NONE || move_is_ok(threat));
2356     assert(!move_promotion(m));
2357     assert(!pos.move_is_check(m));
2358     assert(!pos.move_is_capture(m));
2359     assert(!pos.move_is_passed_pawn_push(m));
2360     assert(d >= OnePly);
2361
2362     mfrom = move_from(m);
2363     mto = move_to(m);
2364     tfrom = move_from(threat);
2365     tto = move_to(threat);
2366
2367     // Case 1: Castling moves are never pruned.
2368     if (move_is_castle(m))
2369         return false;
2370
2371     // Case 2: Don't prune moves which move the threatened piece
2372     if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2373         return false;
2374
2375     // Case 3: If the threatened piece has value less than or equal to the
2376     // value of the threatening piece, don't prune move which defend it.
2377     if (   !PruneDefendingMoves
2378         && threat != MOVE_NONE
2379         && pos.move_is_capture(threat)
2380         && (   pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2381             || pos.type_of_piece_on(tfrom) == KING)
2382         && pos.move_attacks_square(m, tto))
2383       return false;
2384
2385     // Case 4: Don't prune moves with good history.
2386     if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2387         return false;
2388
2389     // Case 5: If the moving piece in the threatened move is a slider, don't
2390     // prune safe moves which block its ray.
2391     if (  !PruneBlockingMoves
2392         && threat != MOVE_NONE
2393         && piece_is_slider(pos.piece_on(tfrom))
2394         && bit_is_set(squares_between(tfrom, tto), mto)
2395         && pos.see(m) >= 0)
2396             return false;
2397
2398     return true;
2399   }
2400
2401
2402   // ok_to_use_TT() returns true if a transposition table score
2403   // can be used at a given point in search.
2404
2405   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2406
2407     Value v = value_from_tt(tte->value(), ply);
2408
2409     return   (   tte->depth() >= depth
2410               || v >= Max(value_mate_in(100), beta)
2411               || v < Min(value_mated_in(100), beta))
2412
2413           && (   (is_lower_bound(tte->type()) && v >= beta)
2414               || (is_upper_bound(tte->type()) && v < beta));
2415   }
2416
2417
2418   // ok_to_history() returns true if a move m can be stored
2419   // in history. Should be a non capturing move nor a promotion.
2420
2421   bool ok_to_history(const Position& pos, Move m) {
2422
2423     return !pos.move_is_capture(m) && !move_promotion(m);
2424   }
2425
2426
2427   // update_history() registers a good move that produced a beta-cutoff
2428   // in history and marks as failures all the other moves of that ply.
2429
2430   void update_history(const Position& pos, Move m, Depth depth,
2431                       Move movesSearched[], int moveCount) {
2432
2433     H.success(pos.piece_on(move_from(m)), m, depth);
2434
2435     for (int i = 0; i < moveCount - 1; i++)
2436     {
2437         assert(m != movesSearched[i]);
2438         if (ok_to_history(pos, movesSearched[i]))
2439             H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2440     }
2441   }
2442
2443
2444   // update_killers() add a good move that produced a beta-cutoff
2445   // among the killer moves of that ply.
2446
2447   void update_killers(Move m, SearchStack& ss) {
2448
2449     if (m == ss.killers[0])
2450         return;
2451
2452     for (int i = KILLER_MAX - 1; i > 0; i--)
2453         ss.killers[i] = ss.killers[i - 1];
2454
2455     ss.killers[0] = m;
2456   }
2457
2458   // fail_high_ply_1() checks if some thread is currently resolving a fail
2459   // high at ply 1 at the node below the first root node.  This information
2460   // is used for time managment.
2461
2462   bool fail_high_ply_1() {
2463     for(int i = 0; i < ActiveThreads; i++)
2464       if(Threads[i].failHighPly1)
2465         return true;
2466     return false;
2467   }
2468
2469
2470   // current_search_time() returns the number of milliseconds which have passed
2471   // since the beginning of the current search.
2472
2473   int current_search_time() {
2474     return get_system_time() - SearchStartTime;
2475   }
2476
2477
2478   // nps() computes the current nodes/second count.
2479
2480   int nps() {
2481     int t = current_search_time();
2482     return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2483   }
2484
2485
2486   // poll() performs two different functions:  It polls for user input, and it
2487   // looks at the time consumed so far and decides if it's time to abort the
2488   // search.
2489
2490   void poll() {
2491
2492     static int lastInfoTime;
2493     int t = current_search_time();
2494
2495     //  Poll for input
2496     if (Bioskey())
2497     {
2498         // We are line oriented, don't read single chars
2499         std::string command;
2500         if (!std::getline(std::cin, command))
2501             command = "quit";
2502
2503         if (command == "quit")
2504         {
2505             AbortSearch = true;
2506             PonderSearch = false;
2507             Quit = true;
2508         }
2509         else if(command == "stop")
2510         {
2511             AbortSearch = true;
2512             PonderSearch = false;
2513         }
2514         else if(command == "ponderhit")
2515             ponderhit();
2516     }
2517     // Print search information
2518     if (t < 1000)
2519         lastInfoTime = 0;
2520
2521     else if (lastInfoTime > t)
2522         // HACK: Must be a new search where we searched less than
2523         // NodesBetweenPolls nodes during the first second of search.
2524         lastInfoTime = 0;
2525
2526     else if (t - lastInfoTime >= 1000)
2527     {
2528         lastInfoTime = t;
2529         lock_grab(&IOLock);
2530         if (dbg_show_mean)
2531             dbg_print_mean();
2532
2533         if (dbg_show_hit_rate)
2534             dbg_print_hit_rate();
2535
2536         std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2537                   << " time " << t << " hashfull " << TT.full() << std::endl;
2538         lock_release(&IOLock);
2539         if (ShowCurrentLine)
2540             Threads[0].printCurrentLine = true;
2541     }
2542     // Should we stop the search?
2543     if (PonderSearch)
2544         return;
2545
2546     bool overTime =     t > AbsoluteMaxSearchTime
2547                      || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: BUG??
2548                      || (  !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2549                          && t > 6*(MaxSearchTime + ExtraSearchTime));
2550
2551     if (   (Iteration >= 3 && (!InfiniteSearch && overTime))
2552         || (ExactMaxTime && t >= ExactMaxTime)
2553         || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2554         AbortSearch = true;
2555   }
2556
2557
2558   // ponderhit() is called when the program is pondering (i.e. thinking while
2559   // it's the opponent's turn to move) in order to let the engine know that
2560   // it correctly predicted the opponent's move.
2561
2562   void ponderhit() {
2563     int t = current_search_time();
2564     PonderSearch = false;
2565     if(Iteration >= 3 &&
2566        (!InfiniteSearch && (StopOnPonderhit ||
2567                             t > AbsoluteMaxSearchTime ||
2568                             (RootMoveNumber == 1 &&
2569                              t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2570                             (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2571                              t > 6*(MaxSearchTime + ExtraSearchTime)))))
2572       AbortSearch = true;
2573   }
2574
2575
2576   // print_current_line() prints the current line of search for a given
2577   // thread.  Called when the UCI option UCI_ShowCurrLine is 'true'.
2578
2579   void print_current_line(SearchStack ss[], int ply, int threadID) {
2580     assert(ply >= 0 && ply < PLY_MAX);
2581     assert(threadID >= 0 && threadID < ActiveThreads);
2582
2583     if(!Threads[threadID].idle) {
2584       lock_grab(&IOLock);
2585       std::cout << "info currline " << (threadID + 1);
2586       for(int p = 0; p < ply; p++)
2587         std::cout << " " << ss[p].currentMove;
2588       std::cout << std::endl;
2589       lock_release(&IOLock);
2590     }
2591     Threads[threadID].printCurrentLine = false;
2592     if(threadID + 1 < ActiveThreads)
2593       Threads[threadID + 1].printCurrentLine = true;
2594   }
2595
2596
2597   // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2598   // while the program is pondering.  The point is to work around a wrinkle in
2599   // the UCI protocol:  When pondering, the engine is not allowed to give a
2600   // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2601   // We simply wait here until one of these commands is sent, and return,
2602   // after which the bestmove and pondermove will be printed (in id_loop()).
2603
2604   void wait_for_stop_or_ponderhit() {
2605     std::string command;
2606
2607     while(true) {
2608       if(!std::getline(std::cin, command))
2609         command = "quit";
2610
2611       if(command == "quit") {
2612         OpeningBook.close();
2613         stop_threads();
2614         quit_eval();
2615         exit(0);
2616       }
2617       else if(command == "ponderhit" || command == "stop")
2618         break;
2619     }
2620   }
2621
2622
2623   // idle_loop() is where the threads are parked when they have no work to do.
2624   // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2625   // object for which the current thread is the master.
2626
2627   void idle_loop(int threadID, SplitPoint *waitSp) {
2628     assert(threadID >= 0 && threadID < THREAD_MAX);
2629
2630     Threads[threadID].running = true;
2631
2632     while(true) {
2633       if(AllThreadsShouldExit && threadID != 0)
2634         break;
2635
2636       // If we are not thinking, wait for a condition to be signaled instead
2637       // of wasting CPU time polling for work:
2638       while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2639 #if !defined(_MSC_VER)
2640         pthread_mutex_lock(&WaitLock);
2641         if(Idle || threadID >= ActiveThreads)
2642           pthread_cond_wait(&WaitCond, &WaitLock);
2643         pthread_mutex_unlock(&WaitLock);
2644 #else
2645         WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2646 #endif
2647       }
2648
2649       // If this thread has been assigned work, launch a search:
2650       if(Threads[threadID].workIsWaiting) {
2651         Threads[threadID].workIsWaiting = false;
2652         if(Threads[threadID].splitPoint->pvNode)
2653           sp_search_pv(Threads[threadID].splitPoint, threadID);
2654         else
2655           sp_search(Threads[threadID].splitPoint, threadID);
2656         Threads[threadID].idle = true;
2657       }
2658
2659       // If this thread is the master of a split point and all threads have
2660       // finished their work at this split point, return from the idle loop:
2661       if(waitSp != NULL && waitSp->cpus == 0)
2662         return;
2663     }
2664
2665     Threads[threadID].running = false;
2666   }
2667
2668
2669   // init_split_point_stack() is called during program initialization, and
2670   // initializes all split point objects.
2671
2672   void init_split_point_stack() {
2673     for(int i = 0; i < THREAD_MAX; i++)
2674       for(int j = 0; j < MaxActiveSplitPoints; j++) {
2675         SplitPointStack[i][j].parent = NULL;
2676         lock_init(&(SplitPointStack[i][j].lock), NULL);
2677       }
2678   }
2679
2680
2681   // destroy_split_point_stack() is called when the program exits, and
2682   // destroys all locks in the precomputed split point objects.
2683
2684   void destroy_split_point_stack() {
2685     for(int i = 0; i < THREAD_MAX; i++)
2686       for(int j = 0; j < MaxActiveSplitPoints; j++)
2687         lock_destroy(&(SplitPointStack[i][j].lock));
2688   }
2689
2690
2691   // thread_should_stop() checks whether the thread with a given threadID has
2692   // been asked to stop, directly or indirectly.  This can happen if a beta
2693   // cutoff has occured in thre thread's currently active split point, or in
2694   // some ancestor of the current split point.
2695
2696   bool thread_should_stop(int threadID) {
2697     assert(threadID >= 0 && threadID < ActiveThreads);
2698
2699     SplitPoint *sp;
2700
2701     if(Threads[threadID].stop)
2702       return true;
2703     if(ActiveThreads <= 2)
2704       return false;
2705     for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2706       if(sp->finished) {
2707         Threads[threadID].stop = true;
2708         return true;
2709       }
2710     return false;
2711   }
2712
2713
2714   // thread_is_available() checks whether the thread with threadID "slave" is
2715   // available to help the thread with threadID "master" at a split point.  An
2716   // obvious requirement is that "slave" must be idle.  With more than two
2717   // threads, this is not by itself sufficient:  If "slave" is the master of
2718   // some active split point, it is only available as a slave to the other
2719   // threads which are busy searching the split point at the top of "slave"'s
2720   // split point stack (the "helpful master concept" in YBWC terminology).
2721
2722   bool thread_is_available(int slave, int master) {
2723     assert(slave >= 0 && slave < ActiveThreads);
2724     assert(master >= 0 && master < ActiveThreads);
2725     assert(ActiveThreads > 1);
2726
2727     if(!Threads[slave].idle || slave == master)
2728       return false;
2729
2730     if(Threads[slave].activeSplitPoints == 0)
2731       // No active split points means that the thread is available as a slave
2732       // for any other thread.
2733       return true;
2734
2735     if(ActiveThreads == 2)
2736       return true;
2737
2738     // Apply the "helpful master" concept if possible.
2739     if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2740       return true;
2741
2742     return false;
2743   }
2744
2745
2746   // idle_thread_exists() tries to find an idle thread which is available as
2747   // a slave for the thread with threadID "master".
2748
2749   bool idle_thread_exists(int master) {
2750     assert(master >= 0 && master < ActiveThreads);
2751     assert(ActiveThreads > 1);
2752
2753     for(int i = 0; i < ActiveThreads; i++)
2754       if(thread_is_available(i, master))
2755         return true;
2756     return false;
2757   }
2758
2759
2760   // split() does the actual work of distributing the work at a node between
2761   // several threads at PV nodes.  If it does not succeed in splitting the
2762   // node (because no idle threads are available, or because we have no unused
2763   // split point objects), the function immediately returns false.  If
2764   // splitting is possible, a SplitPoint object is initialized with all the
2765   // data that must be copied to the helper threads (the current position and
2766   // search stack, alpha, beta, the search depth, etc.), and we tell our
2767   // helper threads that they have been assigned work.  This will cause them
2768   // to instantly leave their idle loops and call sp_search_pv().  When all
2769   // threads have returned from sp_search_pv (or, equivalently, when
2770   // splitPoint->cpus becomes 0), split() returns true.
2771
2772   bool split(const Position &p, SearchStack *sstck, int ply,
2773              Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2774              MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2775
2776     assert(p.is_ok());
2777     assert(sstck != NULL);
2778     assert(ply >= 0 && ply < PLY_MAX);
2779     assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2780     assert(!pvNode || *alpha < *beta);
2781     assert(*beta <= VALUE_INFINITE);
2782     assert(depth > Depth(0));
2783     assert(master >= 0 && master < ActiveThreads);
2784     assert(ActiveThreads > 1);
2785
2786     SplitPoint *splitPoint;
2787     int i;
2788
2789     lock_grab(&MPLock);
2790
2791     // If no other thread is available to help us, or if we have too many
2792     // active split points, don't split:
2793     if(!idle_thread_exists(master) ||
2794        Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2795       lock_release(&MPLock);
2796       return false;
2797     }
2798
2799     // Pick the next available split point object from the split point stack:
2800     splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2801     Threads[master].activeSplitPoints++;
2802
2803     // Initialize the split point object:
2804     splitPoint->parent = Threads[master].splitPoint;
2805     splitPoint->finished = false;
2806     splitPoint->ply = ply;
2807     splitPoint->depth = depth;
2808     splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2809     splitPoint->beta = *beta;
2810     splitPoint->pvNode = pvNode;
2811     splitPoint->dcCandidates = dcCandidates;
2812     splitPoint->bestValue = *bestValue;
2813     splitPoint->master = master;
2814     splitPoint->mp = mp;
2815     splitPoint->moves = *moves;
2816     splitPoint->cpus = 1;
2817     splitPoint->pos.copy(p);
2818     splitPoint->parentSstack = sstck;
2819     for(i = 0; i < ActiveThreads; i++)
2820       splitPoint->slaves[i] = 0;
2821
2822     // Copy the current position and the search stack to the master thread:
2823     memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2824     Threads[master].splitPoint = splitPoint;
2825
2826     // Make copies of the current position and search stack for each thread:
2827     for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2828         i++)
2829       if(thread_is_available(i, master)) {
2830         memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2831         Threads[i].splitPoint = splitPoint;
2832         splitPoint->slaves[i] = 1;
2833         splitPoint->cpus++;
2834       }
2835
2836     // Tell the threads that they have work to do.  This will make them leave
2837     // their idle loop.
2838     for(i = 0; i < ActiveThreads; i++)
2839       if(i == master || splitPoint->slaves[i]) {
2840         Threads[i].workIsWaiting = true;
2841         Threads[i].idle = false;
2842         Threads[i].stop = false;
2843       }
2844
2845     lock_release(&MPLock);
2846
2847     // Everything is set up.  The master thread enters the idle loop, from
2848     // which it will instantly launch a search, because its workIsWaiting
2849     // slot is 'true'.  We send the split point as a second parameter to the
2850     // idle loop, which means that the main thread will return from the idle
2851     // loop when all threads have finished their work at this split point
2852     // (i.e. when // splitPoint->cpus == 0).
2853     idle_loop(master, splitPoint);
2854
2855     // We have returned from the idle loop, which means that all threads are
2856     // finished.  Update alpha, beta and bestvalue, and return:
2857     lock_grab(&MPLock);
2858     if(pvNode) *alpha = splitPoint->alpha;
2859     *beta = splitPoint->beta;
2860     *bestValue = splitPoint->bestValue;
2861     Threads[master].stop = false;
2862     Threads[master].idle = false;
2863     Threads[master].activeSplitPoints--;
2864     Threads[master].splitPoint = splitPoint->parent;
2865     lock_release(&MPLock);
2866
2867     return true;
2868   }
2869
2870
2871   // wake_sleeping_threads() wakes up all sleeping threads when it is time
2872   // to start a new search from the root.
2873
2874   void wake_sleeping_threads() {
2875     if(ActiveThreads > 1) {
2876       for(int i = 1; i < ActiveThreads; i++) {
2877         Threads[i].idle = true;
2878         Threads[i].workIsWaiting = false;
2879       }
2880 #if !defined(_MSC_VER)
2881       pthread_mutex_lock(&WaitLock);
2882       pthread_cond_broadcast(&WaitCond);
2883       pthread_mutex_unlock(&WaitLock);
2884 #else
2885       for(int i = 1; i < THREAD_MAX; i++)
2886         SetEvent(SitIdleEvent[i]);
2887 #endif
2888     }
2889   }
2890
2891
2892   // init_thread() is the function which is called when a new thread is
2893   // launched.  It simply calls the idle_loop() function with the supplied
2894   // threadID.  There are two versions of this function; one for POSIX threads
2895   // and one for Windows threads.
2896
2897 #if !defined(_MSC_VER)
2898
2899   void *init_thread(void *threadID) {
2900     idle_loop(*(int *)threadID, NULL);
2901     return NULL;
2902   }
2903
2904 #else
2905
2906   DWORD WINAPI init_thread(LPVOID threadID) {
2907     idle_loop(*(int *)threadID, NULL);
2908     return NULL;
2909   }
2910
2911 #endif
2912
2913 }