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