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