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