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