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