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