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