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