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