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