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