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