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