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