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