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