]> git.sesse.net Git - stockfish/blob - src/search.cpp
3617853e5f23d2f3589b7af48da9decbf48e4593
[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)
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         // Update transposition table before to leave
1480         TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1481         return bestValue;
1482     }
1483     else if (!isCheck && !tte && ei.futilityMargin == 0)
1484     {
1485         // Store the score to avoid a future costly evaluation() call
1486         TT.store(pos, value_to_tt(bestValue, ply), Depth(-127*OnePly), MOVE_NONE, VALUE_TYPE_EVAL);
1487     }
1488
1489     if (bestValue > alpha)
1490         alpha = bestValue;
1491
1492     // Initialize a MovePicker object for the current position, and prepare
1493     // to search the moves.  Because the depth is <= 0 here, only captures,
1494     // queen promotions and checks (only if depth == 0) will be generated.
1495     MovePicker mp = MovePicker(pos, pvNode, MOVE_NONE, EmptySearchStack, depth);
1496     Move move;
1497     int moveCount = 0;
1498     Bitboard dcCandidates = mp.discovered_check_candidates();
1499     Color us = pos.side_to_move();
1500     bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1501
1502     // Loop through the moves until no moves remain or a beta cutoff
1503     // occurs.
1504     while (   alpha < beta
1505            && (move = mp.get_next_move()) != MOVE_NONE)
1506     {
1507       assert(move_is_ok(move));
1508
1509       moveCount++;
1510       ss[ply].currentMove = move;
1511
1512       // Futility pruning
1513       if (    UseQSearchFutilityPruning
1514           &&  enoughMaterial
1515           && !isCheck
1516           && !pvNode
1517           && !move_promotion(move)
1518           && !pos.move_is_check(move, dcCandidates)
1519           && !pos.move_is_passed_pawn_push(move))
1520       {
1521           Value futilityValue = staticValue
1522                               + Max(pos.midgame_value_of_piece_on(move_to(move)),
1523                                     pos.endgame_value_of_piece_on(move_to(move)))
1524                               + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1525                               + FutilityMarginQS
1526                               + ei.futilityMargin;
1527
1528           if (futilityValue < alpha)
1529           {
1530               if (futilityValue > bestValue)
1531                   bestValue = futilityValue;
1532               continue;
1533           }
1534       }
1535
1536       // Don't search captures and checks with negative SEE values
1537       if (   !isCheck
1538           && !move_promotion(move)
1539           && (pos.midgame_value_of_piece_on(move_from(move)) >
1540               pos.midgame_value_of_piece_on(move_to(move)))
1541           &&  pos.see(move) < 0)
1542           continue;
1543
1544       // Make and search the move.
1545       StateInfo st;
1546       pos.do_move(move, st, dcCandidates);
1547       Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1548       pos.undo_move(move);
1549
1550       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1551
1552       // New best move?
1553       if (value > bestValue)
1554       {
1555           bestValue = value;
1556           if (value > alpha)
1557           {
1558               alpha = value;
1559               update_pv(ss, ply);
1560           }
1561        }
1562     }
1563
1564     // All legal moves have been searched.  A special case: If we're in check
1565     // and no legal moves were found, it is checkmate:
1566     if (pos.is_check() && moveCount == 0) // Mate!
1567         return value_mated_in(ply);
1568
1569     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1570
1571     // Update killers only for good check moves
1572     Move m = ss[ply].currentMove;
1573     if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1574     {
1575         // Wrong to update history when depth is <= 0
1576         update_killers(m, ss[ply]);
1577     }
1578     return bestValue;
1579   }
1580
1581
1582   // sp_search() is used to search from a split point.  This function is called
1583   // by each thread working at the split point.  It is similar to the normal
1584   // search() function, but simpler.  Because we have already probed the hash
1585   // table, done a null move search, and searched the first move before
1586   // splitting, we don't have to repeat all this work in sp_search().  We
1587   // also don't need to store anything to the hash table here:  This is taken
1588   // care of after we return from the split point.
1589
1590   void sp_search(SplitPoint *sp, int threadID) {
1591
1592     assert(threadID >= 0 && threadID < ActiveThreads);
1593     assert(ActiveThreads > 1);
1594
1595     Position pos = Position(sp->pos);
1596     SearchStack *ss = sp->sstack[threadID];
1597     Value value;
1598     Move move;
1599     bool isCheck = pos.is_check();
1600     bool useFutilityPruning =    UseFutilityPruning
1601                               && sp->depth < SelectiveDepth
1602                               && !isCheck;
1603
1604     while (    sp->bestValue < sp->beta
1605            && !thread_should_stop(threadID)
1606            && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1607     {
1608       assert(move_is_ok(move));
1609
1610       bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1611       bool moveIsCapture = pos.move_is_capture(move);
1612
1613       lock_grab(&(sp->lock));
1614       int moveCount = ++sp->moves;
1615       lock_release(&(sp->lock));
1616
1617       ss[sp->ply].currentMove = move;
1618
1619       // Decide the new search depth.
1620       bool dangerous;
1621       Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1622       Depth newDepth = sp->depth - OnePly + ext;
1623
1624       // Prune?
1625       if (    useFutilityPruning
1626           && !dangerous
1627           && !moveIsCapture
1628           && !move_promotion(move)
1629           &&  moveCount >= 2 + int(sp->depth)
1630           &&  ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1631         continue;
1632
1633       // Make and search the move.
1634       StateInfo st;
1635       pos.do_move(move, st, sp->dcCandidates);
1636
1637       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1638       // if the move fails high will be re-searched at full depth.
1639       if (   !dangerous
1640           &&  moveCount >= LMRNonPVMoves
1641           && !moveIsCapture
1642           && !move_promotion(move)
1643           && !move_is_castle(move)
1644           && !move_is_killer(move, ss[sp->ply]))
1645       {
1646           ss[sp->ply].reduction = OnePly;
1647           value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1648       }
1649       else
1650           value = sp->beta; // Just to trigger next condition
1651
1652       if (value >= sp->beta) // Go with full depth non-pv search
1653       {
1654           ss[sp->ply].reduction = Depth(0);
1655           value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1656       }
1657       pos.undo_move(move);
1658
1659       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1660
1661       if (thread_should_stop(threadID))
1662           break;
1663
1664       // New best move?
1665       lock_grab(&(sp->lock));
1666       if (value > sp->bestValue && !thread_should_stop(threadID))
1667       {
1668           sp->bestValue = value;
1669           if (sp->bestValue >= sp->beta)
1670           {
1671               sp_update_pv(sp->parentSstack, ss, sp->ply);
1672               for (int i = 0; i < ActiveThreads; i++)
1673                   if (i != threadID && (i == sp->master || sp->slaves[i]))
1674                       Threads[i].stop = true;
1675
1676               sp->finished = true;
1677         }
1678       }
1679       lock_release(&(sp->lock));
1680     }
1681
1682     lock_grab(&(sp->lock));
1683
1684     // If this is the master thread and we have been asked to stop because of
1685     // a beta cutoff higher up in the tree, stop all slave threads:
1686     if (sp->master == threadID && thread_should_stop(threadID))
1687         for (int i = 0; i < ActiveThreads; i++)
1688             if (sp->slaves[i])
1689                 Threads[i].stop = true;
1690
1691     sp->cpus--;
1692     sp->slaves[threadID] = 0;
1693
1694     lock_release(&(sp->lock));
1695   }
1696
1697
1698   // sp_search_pv() is used to search from a PV split point.  This function
1699   // is called by each thread working at the split point.  It is similar to
1700   // the normal search_pv() function, but simpler.  Because we have already
1701   // probed the hash table and searched the first move before splitting, we
1702   // don't have to repeat all this work in sp_search_pv().  We also don't
1703   // need to store anything to the hash table here:  This is taken care of
1704   // after we return from the split point.
1705
1706   void sp_search_pv(SplitPoint *sp, int threadID) {
1707
1708     assert(threadID >= 0 && threadID < ActiveThreads);
1709     assert(ActiveThreads > 1);
1710
1711     Position pos = Position(sp->pos);
1712     SearchStack *ss = sp->sstack[threadID];
1713     Value value;
1714     Move move;
1715
1716     while (    sp->alpha < sp->beta
1717            && !thread_should_stop(threadID)
1718            && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1719     {
1720       bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1721       bool moveIsCapture = pos.move_is_capture(move);
1722
1723       assert(move_is_ok(move));
1724
1725       if (moveIsCapture)
1726           ss[sp->ply].currentMoveCaptureValue =
1727           move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1728       else
1729           ss[sp->ply].currentMoveCaptureValue = Value(0);
1730
1731       lock_grab(&(sp->lock));
1732       int moveCount = ++sp->moves;
1733       lock_release(&(sp->lock));
1734
1735       ss[sp->ply].currentMove = move;
1736
1737       // Decide the new search depth.
1738       bool dangerous;
1739       Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1740       Depth newDepth = sp->depth - OnePly + ext;
1741
1742       // Make and search the move.
1743       StateInfo st;
1744       pos.do_move(move, st, sp->dcCandidates);
1745
1746       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1747       // if the move fails high will be re-searched at full depth.
1748       if (   !dangerous
1749           &&  moveCount >= LMRPVMoves
1750           && !moveIsCapture
1751           && !move_promotion(move)
1752           && !move_is_castle(move)
1753           && !move_is_killer(move, ss[sp->ply]))
1754       {
1755           ss[sp->ply].reduction = OnePly;
1756           value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1757       }
1758       else
1759           value = sp->alpha + 1; // Just to trigger next condition
1760
1761       if (value > sp->alpha) // Go with full depth non-pv search
1762       {
1763           ss[sp->ply].reduction = Depth(0);
1764           value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1765
1766           if (value > sp->alpha && value < sp->beta)
1767           {
1768               // When the search fails high at ply 1 while searching the first
1769               // move at the root, set the flag failHighPly1.  This is used for
1770               // time managment:  We don't want to stop the search early in
1771               // such cases, because resolving the fail high at ply 1 could
1772               // result in a big drop in score at the root.
1773               if (sp->ply == 1 && RootMoveNumber == 1)
1774                   Threads[threadID].failHighPly1 = true;
1775
1776               value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1777               Threads[threadID].failHighPly1 = false;
1778         }
1779       }
1780       pos.undo_move(move);
1781
1782       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1783
1784       if (thread_should_stop(threadID))
1785           break;
1786
1787       // New best move?
1788       lock_grab(&(sp->lock));
1789       if (value > sp->bestValue && !thread_should_stop(threadID))
1790       {
1791           sp->bestValue = value;
1792           if (value > sp->alpha)
1793           {
1794               sp->alpha = value;
1795               sp_update_pv(sp->parentSstack, ss, sp->ply);
1796               if (value == value_mate_in(sp->ply + 1))
1797                   ss[sp->ply].mateKiller = move;
1798
1799               if(value >= sp->beta)
1800               {
1801                   for(int i = 0; i < ActiveThreads; i++)
1802                       if(i != threadID && (i == sp->master || sp->slaves[i]))
1803                           Threads[i].stop = true;
1804
1805                   sp->finished = true;
1806               }
1807         }
1808         // If we are at ply 1, and we are searching the first root move at
1809         // ply 0, set the 'Problem' variable if the score has dropped a lot
1810         // (from the computer's point of view) since the previous iteration.
1811         if (   sp->ply == 1
1812             && Iteration >= 2
1813             && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1814             Problem = true;
1815       }
1816       lock_release(&(sp->lock));
1817     }
1818
1819     lock_grab(&(sp->lock));
1820
1821     // If this is the master thread and we have been asked to stop because of
1822     // a beta cutoff higher up in the tree, stop all slave threads.
1823     if (sp->master == threadID && thread_should_stop(threadID))
1824         for (int i = 0; i < ActiveThreads; i++)
1825             if (sp->slaves[i])
1826                 Threads[i].stop = true;
1827
1828     sp->cpus--;
1829     sp->slaves[threadID] = 0;
1830
1831     lock_release(&(sp->lock));
1832   }
1833
1834   /// The BetaCounterType class
1835
1836   BetaCounterType::BetaCounterType() { clear(); }
1837
1838   void BetaCounterType::clear() {
1839
1840     for (int i = 0; i < THREAD_MAX; i++)
1841         hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1842   }
1843
1844   void BetaCounterType::add(Color us, Depth d, int threadID) {
1845
1846     // Weighted count based on depth
1847     hits[threadID][us] += int(d);
1848   }
1849
1850   void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1851
1852     our = their = 0UL;
1853     for (int i = 0; i < THREAD_MAX; i++)
1854     {
1855         our += hits[i][us];
1856         their += hits[i][opposite_color(us)];
1857     }
1858   }
1859
1860
1861   /// The RootMove class
1862
1863   // Constructor
1864
1865   RootMove::RootMove() {
1866     nodes = cumulativeNodes = 0ULL;
1867   }
1868
1869   // RootMove::operator<() is the comparison function used when
1870   // sorting the moves.  A move m1 is considered to be better
1871   // than a move m2 if it has a higher score, or if the moves
1872   // have equal score but m1 has the higher node count.
1873
1874   bool RootMove::operator<(const RootMove& m) {
1875
1876     if (score != m.score)
1877         return (score < m.score);
1878
1879     return theirBeta <= m.theirBeta;
1880   }
1881
1882   /// The RootMoveList class
1883
1884   // Constructor
1885
1886   RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1887
1888     MoveStack mlist[MaxRootMoves];
1889     bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1890
1891     // Generate all legal moves
1892     int lm_count = generate_legal_moves(pos, mlist);
1893
1894     // Add each move to the moves[] array
1895     for (int i = 0; i < lm_count; i++)
1896     {
1897         bool includeMove = includeAllMoves;
1898
1899         for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1900             includeMove = (searchMoves[k] == mlist[i].move);
1901
1902         if (includeMove)
1903         {
1904             // Find a quick score for the move
1905             StateInfo st;
1906             SearchStack ss[PLY_MAX_PLUS_2];
1907
1908             moves[count].move = mlist[i].move;
1909             moves[count].nodes = 0ULL;
1910             pos.do_move(moves[count].move, st);
1911             moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1912                                           Depth(0), 1, 0);
1913             pos.undo_move(moves[count].move);
1914             moves[count].pv[0] = moves[i].move;
1915             moves[count].pv[1] = MOVE_NONE; // FIXME
1916             count++;
1917         }
1918     }
1919     sort();
1920   }
1921
1922
1923   // Simple accessor methods for the RootMoveList class
1924
1925   inline Move RootMoveList::get_move(int moveNum) const {
1926     return moves[moveNum].move;
1927   }
1928
1929   inline Value RootMoveList::get_move_score(int moveNum) const {
1930     return moves[moveNum].score;
1931   }
1932
1933   inline void RootMoveList::set_move_score(int moveNum, Value score) {
1934     moves[moveNum].score = score;
1935   }
1936
1937   inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1938     moves[moveNum].nodes = nodes;
1939     moves[moveNum].cumulativeNodes += nodes;
1940   }
1941
1942   inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1943     moves[moveNum].ourBeta = our;
1944     moves[moveNum].theirBeta = their;
1945   }
1946
1947   void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1948     int j;
1949     for(j = 0; pv[j] != MOVE_NONE; j++)
1950       moves[moveNum].pv[j] = pv[j];
1951     moves[moveNum].pv[j] = MOVE_NONE;
1952   }
1953
1954   inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1955     return moves[moveNum].pv[i];
1956   }
1957
1958   inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1959     return moves[moveNum].cumulativeNodes;
1960   }
1961
1962   inline int RootMoveList::move_count() const {
1963     return count;
1964   }
1965
1966
1967   // RootMoveList::scan_for_easy_move() is called at the end of the first
1968   // iteration, and is used to detect an "easy move", i.e. a move which appears
1969   // to be much bester than all the rest.  If an easy move is found, the move
1970   // is returned, otherwise the function returns MOVE_NONE.  It is very
1971   // important that this function is called at the right moment:  The code
1972   // assumes that the first iteration has been completed and the moves have
1973   // been sorted. This is done in RootMoveList c'tor.
1974
1975   Move RootMoveList::scan_for_easy_move() const {
1976
1977     assert(count);
1978
1979     if (count == 1)
1980         return get_move(0);
1981
1982     // moves are sorted so just consider the best and the second one
1983     if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1984         return get_move(0);
1985
1986     return MOVE_NONE;
1987   }
1988
1989   // RootMoveList::sort() sorts the root move list at the beginning of a new
1990   // iteration.
1991
1992   inline void RootMoveList::sort() {
1993
1994     sort_multipv(count - 1); // all items
1995   }
1996
1997
1998   // RootMoveList::sort_multipv() sorts the first few moves in the root move
1999   // list by their scores and depths. It is used to order the different PVs
2000   // correctly in MultiPV mode.
2001
2002   void RootMoveList::sort_multipv(int n) {
2003
2004     for (int i = 1; i <= n; i++)
2005     {
2006       RootMove rm = moves[i];
2007       int j;
2008       for (j = i; j > 0 && moves[j-1] < rm; j--)
2009           moves[j] = moves[j-1];
2010       moves[j] = rm;
2011     }
2012   }
2013
2014
2015   // init_node() is called at the beginning of all the search functions
2016   // (search(), search_pv(), qsearch(), and so on) and initializes the search
2017   // stack object corresponding to the current node.  Once every
2018   // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2019   // for user input and checks whether it is time to stop the search.
2020
2021   void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
2022     assert(ply >= 0 && ply < PLY_MAX);
2023     assert(threadID >= 0 && threadID < ActiveThreads);
2024
2025     Threads[threadID].nodes++;
2026
2027     if(threadID == 0) {
2028       NodesSincePoll++;
2029       if(NodesSincePoll >= NodesBetweenPolls) {
2030         poll();
2031         NodesSincePoll = 0;
2032       }
2033     }
2034
2035     ss[ply].init(ply);
2036     ss[ply+2].initKillers();
2037
2038     if(Threads[threadID].printCurrentLine)
2039       print_current_line(ss, ply, threadID);
2040   }
2041
2042
2043   // update_pv() is called whenever a search returns a value > alpha.  It
2044   // updates the PV in the SearchStack object corresponding to the current
2045   // node.
2046
2047   void update_pv(SearchStack ss[], int ply) {
2048     assert(ply >= 0 && ply < PLY_MAX);
2049
2050     ss[ply].pv[ply] = ss[ply].currentMove;
2051     int p;
2052     for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2053       ss[ply].pv[p] = ss[ply+1].pv[p];
2054     ss[ply].pv[p] = MOVE_NONE;
2055   }
2056
2057
2058   // sp_update_pv() is a variant of update_pv for use at split points.  The
2059   // difference between the two functions is that sp_update_pv also updates
2060   // the PV at the parent node.
2061
2062   void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2063     assert(ply >= 0 && ply < PLY_MAX);
2064
2065     ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2066     int p;
2067     for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2068       ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2069     ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2070   }
2071
2072
2073   // connected_moves() tests whether two moves are 'connected' in the sense
2074   // that the first move somehow made the second move possible (for instance
2075   // if the moving piece is the same in both moves).  The first move is
2076   // assumed to be the move that was made to reach the current position, while
2077   // the second move is assumed to be a move from the current position.
2078
2079   bool connected_moves(const Position &pos, Move m1, Move m2) {
2080     Square f1, t1, f2, t2;
2081
2082     assert(move_is_ok(m1));
2083     assert(move_is_ok(m2));
2084
2085     if(m2 == MOVE_NONE)
2086       return false;
2087
2088     // Case 1: The moving piece is the same in both moves.
2089     f2 = move_from(m2);
2090     t1 = move_to(m1);
2091     if(f2 == t1)
2092       return true;
2093
2094     // Case 2: The destination square for m2 was vacated by m1.
2095     t2 = move_to(m2);
2096     f1 = move_from(m1);
2097     if(t2 == f1)
2098       return true;
2099
2100     // Case 3: Moving through the vacated square:
2101     if(piece_is_slider(pos.piece_on(f2)) &&
2102        bit_is_set(squares_between(f2, t2), f1))
2103       return true;
2104
2105     // Case 4: The destination square for m2 is attacked by the moving piece
2106     // in m1:
2107     if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2108       return true;
2109
2110     // Case 5: Discovered check, checking piece is the piece moved in m1:
2111     if(piece_is_slider(pos.piece_on(t1)) &&
2112        bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2113                   f2) &&
2114        !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2115                    t2)) {
2116       Bitboard occ = pos.occupied_squares();
2117       Color us = pos.side_to_move();
2118       Square ksq = pos.king_square(us);
2119       clear_bit(&occ, f2);
2120       if(pos.type_of_piece_on(t1) == BISHOP) {
2121         if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2122           return true;
2123       }
2124       else if(pos.type_of_piece_on(t1) == ROOK) {
2125         if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2126           return true;
2127       }
2128       else {
2129         assert(pos.type_of_piece_on(t1) == QUEEN);
2130         if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2131           return true;
2132       }
2133     }
2134
2135     return false;
2136   }
2137
2138
2139   // value_is_mate() checks if the given value is a mate one
2140   // eventually compensated for the ply.
2141
2142   bool value_is_mate(Value value) {
2143
2144     assert(abs(value) <= VALUE_INFINITE);
2145
2146     return   value <= value_mated_in(PLY_MAX)
2147           || value >= value_mate_in(PLY_MAX);
2148   }
2149
2150
2151   // move_is_killer() checks if the given move is among the
2152   // killer moves of that ply.
2153
2154   bool move_is_killer(Move m, const SearchStack& ss) {
2155
2156       const Move* k = ss.killers;
2157       for (int i = 0; i < KILLER_MAX; i++, k++)
2158           if (*k == m)
2159               return true;
2160
2161       return false;
2162   }
2163
2164
2165   // extension() decides whether a move should be searched with normal depth,
2166   // or with extended depth.  Certain classes of moves (checking moves, in
2167   // particular) are searched with bigger depth than ordinary moves and in
2168   // any case are marked as 'dangerous'. Note that also if a move is not
2169   // extended, as example because the corresponding UCI option is set to zero,
2170   // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2171
2172   Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2173                   bool singleReply, bool mateThreat, bool* dangerous) {
2174
2175     assert(m != MOVE_NONE);
2176
2177     Depth result = Depth(0);
2178     *dangerous = check || singleReply || mateThreat;
2179
2180     if (check)
2181         result += CheckExtension[pvNode];
2182
2183     if (singleReply)
2184         result += SingleReplyExtension[pvNode];
2185
2186     if (mateThreat)
2187         result += MateThreatExtension[pvNode];
2188
2189     if (pos.type_of_piece_on(move_from(m)) == PAWN)
2190     {
2191         if (pos.move_is_pawn_push_to_7th(m))
2192         {
2193             result += PawnPushTo7thExtension[pvNode];
2194             *dangerous = true;
2195         }
2196         if (pos.move_is_passed_pawn_push(m))
2197         {
2198             result += PassedPawnExtension[pvNode];
2199             *dangerous = true;
2200         }
2201     }
2202
2203     if (   capture
2204         && pos.type_of_piece_on(move_to(m)) != PAWN
2205         && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2206             - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2207         && !move_promotion(m)
2208         && !move_is_ep(m))
2209     {
2210         result += PawnEndgameExtension[pvNode];
2211         *dangerous = true;
2212     }
2213
2214     if (   pvNode
2215         && capture
2216         && pos.type_of_piece_on(move_to(m)) != PAWN
2217         && pos.see(m) >= 0)
2218     {
2219         result += OnePly/2;
2220         *dangerous = true;
2221     }
2222
2223     return Min(result, OnePly);
2224   }
2225
2226
2227   // ok_to_do_nullmove() looks at the current position and decides whether
2228   // doing a 'null move' should be allowed.  In order to avoid zugzwang
2229   // problems, null moves are not allowed when the side to move has very
2230   // little material left.  Currently, the test is a bit too simple:  Null
2231   // moves are avoided only when the side to move has only pawns left.  It's
2232   // probably a good idea to avoid null moves in at least some more
2233   // complicated endgames, e.g. KQ vs KR.  FIXME
2234
2235   bool ok_to_do_nullmove(const Position &pos) {
2236     if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2237       return false;
2238     return true;
2239   }
2240
2241
2242   // ok_to_prune() tests whether it is safe to forward prune a move.  Only
2243   // non-tactical moves late in the move list close to the leaves are
2244   // candidates for pruning.
2245
2246   bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2247     Square mfrom, mto, tfrom, tto;
2248
2249     assert(move_is_ok(m));
2250     assert(threat == MOVE_NONE || move_is_ok(threat));
2251     assert(!move_promotion(m));
2252     assert(!pos.move_is_check(m));
2253     assert(!pos.move_is_capture(m));
2254     assert(!pos.move_is_passed_pawn_push(m));
2255     assert(d >= OnePly);
2256
2257     mfrom = move_from(m);
2258     mto = move_to(m);
2259     tfrom = move_from(threat);
2260     tto = move_to(threat);
2261
2262     // Case 1: Castling moves are never pruned.
2263     if (move_is_castle(m))
2264         return false;
2265
2266     // Case 2: Don't prune moves which move the threatened piece
2267     if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2268         return false;
2269
2270     // Case 3: If the threatened piece has value less than or equal to the
2271     // value of the threatening piece, don't prune move which defend it.
2272     if (   !PruneDefendingMoves
2273         && threat != MOVE_NONE
2274         && pos.move_is_capture(threat)
2275         && (   pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2276             || pos.type_of_piece_on(tfrom) == KING)
2277         && pos.move_attacks_square(m, tto))
2278       return false;
2279
2280     // Case 4: Don't prune moves with good history.
2281     if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2282         return false;
2283
2284     // Case 5: If the moving piece in the threatened move is a slider, don't
2285     // prune safe moves which block its ray.
2286     if (  !PruneBlockingMoves
2287         && threat != MOVE_NONE
2288         && piece_is_slider(pos.piece_on(tfrom))
2289         && bit_is_set(squares_between(tfrom, tto), mto)
2290         && pos.see(m) >= 0)
2291             return false;
2292
2293     return true;
2294   }
2295
2296
2297   // ok_to_use_TT() returns true if a transposition table score
2298   // can be used at a given point in search.
2299
2300   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2301
2302     Value v = value_from_tt(tte->value(), ply);
2303
2304     return   (   tte->depth() >= depth
2305               || v >= Max(value_mate_in(100), beta)
2306               || v < Min(value_mated_in(100), beta))
2307
2308           && (   (is_lower_bound(tte->type()) && v >= beta)
2309               || (is_upper_bound(tte->type()) && v < beta));
2310   }
2311
2312
2313   // ok_to_history() returns true if a move m can be stored
2314   // in history. Should be a non capturing move nor a promotion.
2315
2316   bool ok_to_history(const Position& pos, Move m) {
2317
2318     return !pos.move_is_capture(m) && !move_promotion(m);
2319   }
2320
2321
2322   // update_history() registers a good move that produced a beta-cutoff
2323   // in history and marks as failures all the other moves of that ply.
2324
2325   void update_history(const Position& pos, Move m, Depth depth,
2326                       Move movesSearched[], int moveCount) {
2327
2328     H.success(pos.piece_on(move_from(m)), m, depth);
2329
2330     for (int i = 0; i < moveCount - 1; i++)
2331     {
2332         assert(m != movesSearched[i]);
2333         if (ok_to_history(pos, movesSearched[i]))
2334             H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2335     }
2336   }
2337
2338
2339   // update_killers() add a good move that produced a beta-cutoff
2340   // among the killer moves of that ply.
2341
2342   void update_killers(Move m, SearchStack& ss) {
2343
2344     if (m == ss.killers[0])
2345         return;
2346
2347     for (int i = KILLER_MAX - 1; i > 0; i--)
2348         ss.killers[i] = ss.killers[i - 1];
2349
2350     ss.killers[0] = m;
2351   }
2352
2353   // fail_high_ply_1() checks if some thread is currently resolving a fail
2354   // high at ply 1 at the node below the first root node.  This information
2355   // is used for time managment.
2356
2357   bool fail_high_ply_1() {
2358     for(int i = 0; i < ActiveThreads; i++)
2359       if(Threads[i].failHighPly1)
2360         return true;
2361     return false;
2362   }
2363
2364
2365   // current_search_time() returns the number of milliseconds which have passed
2366   // since the beginning of the current search.
2367
2368   int current_search_time() {
2369     return get_system_time() - SearchStartTime;
2370   }
2371
2372
2373   // nps() computes the current nodes/second count.
2374
2375   int nps() {
2376     int t = current_search_time();
2377     return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2378   }
2379
2380
2381   // poll() performs two different functions:  It polls for user input, and it
2382   // looks at the time consumed so far and decides if it's time to abort the
2383   // search.
2384
2385   void poll() {
2386
2387     static int lastInfoTime;
2388     int t = current_search_time();
2389
2390     //  Poll for input
2391     if (Bioskey())
2392     {
2393         // We are line oriented, don't read single chars
2394         std::string command;
2395         if (!std::getline(std::cin, command))
2396             command = "quit";
2397
2398         if (command == "quit")
2399         {
2400             AbortSearch = true;
2401             PonderSearch = false;
2402             Quit = true;
2403         }
2404         else if(command == "stop")
2405         {
2406             AbortSearch = true;
2407             PonderSearch = false;
2408         }
2409         else if(command == "ponderhit")
2410             ponderhit();
2411     }
2412     // Print search information
2413     if (t < 1000)
2414         lastInfoTime = 0;
2415
2416     else if (lastInfoTime > t)
2417         // HACK: Must be a new search where we searched less than
2418         // NodesBetweenPolls nodes during the first second of search.
2419         lastInfoTime = 0;
2420
2421     else if (t - lastInfoTime >= 1000)
2422     {
2423         lastInfoTime = t;
2424         lock_grab(&IOLock);
2425         if (dbg_show_mean)
2426             dbg_print_mean();
2427
2428         if (dbg_show_hit_rate)
2429             dbg_print_hit_rate();
2430
2431         std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2432                   << " time " << t << " hashfull " << TT.full() << std::endl;
2433         lock_release(&IOLock);
2434         if (ShowCurrentLine)
2435             Threads[0].printCurrentLine = true;
2436     }
2437     // Should we stop the search?
2438     if (PonderSearch)
2439         return;
2440
2441     bool overTime =     t > AbsoluteMaxSearchTime
2442                      || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2443                      || (  !FailHigh && !fail_high_ply_1() && !Problem
2444                          && t > 6*(MaxSearchTime + ExtraSearchTime));
2445
2446     if (   (Iteration >= 3 && (!InfiniteSearch && overTime))
2447         || (ExactMaxTime && t >= ExactMaxTime)
2448         || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2449         AbortSearch = true;
2450   }
2451
2452
2453   // ponderhit() is called when the program is pondering (i.e. thinking while
2454   // it's the opponent's turn to move) in order to let the engine know that
2455   // it correctly predicted the opponent's move.
2456
2457   void ponderhit() {
2458     int t = current_search_time();
2459     PonderSearch = false;
2460     if(Iteration >= 3 &&
2461        (!InfiniteSearch && (StopOnPonderhit ||
2462                             t > AbsoluteMaxSearchTime ||
2463                             (RootMoveNumber == 1 &&
2464                              t > MaxSearchTime + ExtraSearchTime) ||
2465                             (!FailHigh && !fail_high_ply_1() && !Problem &&
2466                              t > 6*(MaxSearchTime + ExtraSearchTime)))))
2467       AbortSearch = true;
2468   }
2469
2470
2471   // print_current_line() prints the current line of search for a given
2472   // thread.  Called when the UCI option UCI_ShowCurrLine is 'true'.
2473
2474   void print_current_line(SearchStack ss[], int ply, int threadID) {
2475     assert(ply >= 0 && ply < PLY_MAX);
2476     assert(threadID >= 0 && threadID < ActiveThreads);
2477
2478     if(!Threads[threadID].idle) {
2479       lock_grab(&IOLock);
2480       std::cout << "info currline " << (threadID + 1);
2481       for(int p = 0; p < ply; p++)
2482         std::cout << " " << ss[p].currentMove;
2483       std::cout << std::endl;
2484       lock_release(&IOLock);
2485     }
2486     Threads[threadID].printCurrentLine = false;
2487     if(threadID + 1 < ActiveThreads)
2488       Threads[threadID + 1].printCurrentLine = true;
2489   }
2490
2491
2492   // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2493   // while the program is pondering.  The point is to work around a wrinkle in
2494   // the UCI protocol:  When pondering, the engine is not allowed to give a
2495   // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2496   // We simply wait here until one of these commands is sent, and return,
2497   // after which the bestmove and pondermove will be printed (in id_loop()).
2498
2499   void wait_for_stop_or_ponderhit() {
2500     std::string command;
2501
2502     while(true) {
2503       if(!std::getline(std::cin, command))
2504         command = "quit";
2505
2506       if(command == "quit") {
2507         OpeningBook.close();
2508         stop_threads();
2509         quit_eval();
2510         exit(0);
2511       }
2512       else if(command == "ponderhit" || command == "stop")
2513         break;
2514     }
2515   }
2516
2517
2518   // idle_loop() is where the threads are parked when they have no work to do.
2519   // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2520   // object for which the current thread is the master.
2521
2522   void idle_loop(int threadID, SplitPoint *waitSp) {
2523     assert(threadID >= 0 && threadID < THREAD_MAX);
2524
2525     Threads[threadID].running = true;
2526
2527     while(true) {
2528       if(AllThreadsShouldExit && threadID != 0)
2529         break;
2530
2531       // If we are not thinking, wait for a condition to be signaled instead
2532       // of wasting CPU time polling for work:
2533       while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2534 #if !defined(_MSC_VER)
2535         pthread_mutex_lock(&WaitLock);
2536         if(Idle || threadID >= ActiveThreads)
2537           pthread_cond_wait(&WaitCond, &WaitLock);
2538         pthread_mutex_unlock(&WaitLock);
2539 #else
2540         WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2541 #endif
2542       }
2543
2544       // If this thread has been assigned work, launch a search:
2545       if(Threads[threadID].workIsWaiting) {
2546         Threads[threadID].workIsWaiting = false;
2547         if(Threads[threadID].splitPoint->pvNode)
2548           sp_search_pv(Threads[threadID].splitPoint, threadID);
2549         else
2550           sp_search(Threads[threadID].splitPoint, threadID);
2551         Threads[threadID].idle = true;
2552       }
2553
2554       // If this thread is the master of a split point and all threads have
2555       // finished their work at this split point, return from the idle loop:
2556       if(waitSp != NULL && waitSp->cpus == 0)
2557         return;
2558     }
2559
2560     Threads[threadID].running = false;
2561   }
2562
2563
2564   // init_split_point_stack() is called during program initialization, and
2565   // initializes all split point objects.
2566
2567   void init_split_point_stack() {
2568     for(int i = 0; i < THREAD_MAX; i++)
2569       for(int j = 0; j < MaxActiveSplitPoints; j++) {
2570         SplitPointStack[i][j].parent = NULL;
2571         lock_init(&(SplitPointStack[i][j].lock), NULL);
2572       }
2573   }
2574
2575
2576   // destroy_split_point_stack() is called when the program exits, and
2577   // destroys all locks in the precomputed split point objects.
2578
2579   void destroy_split_point_stack() {
2580     for(int i = 0; i < THREAD_MAX; i++)
2581       for(int j = 0; j < MaxActiveSplitPoints; j++)
2582         lock_destroy(&(SplitPointStack[i][j].lock));
2583   }
2584
2585
2586   // thread_should_stop() checks whether the thread with a given threadID has
2587   // been asked to stop, directly or indirectly.  This can happen if a beta
2588   // cutoff has occured in thre thread's currently active split point, or in
2589   // some ancestor of the current split point.
2590
2591   bool thread_should_stop(int threadID) {
2592     assert(threadID >= 0 && threadID < ActiveThreads);
2593
2594     SplitPoint *sp;
2595
2596     if(Threads[threadID].stop)
2597       return true;
2598     if(ActiveThreads <= 2)
2599       return false;
2600     for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2601       if(sp->finished) {
2602         Threads[threadID].stop = true;
2603         return true;
2604       }
2605     return false;
2606   }
2607
2608
2609   // thread_is_available() checks whether the thread with threadID "slave" is
2610   // available to help the thread with threadID "master" at a split point.  An
2611   // obvious requirement is that "slave" must be idle.  With more than two
2612   // threads, this is not by itself sufficient:  If "slave" is the master of
2613   // some active split point, it is only available as a slave to the other
2614   // threads which are busy searching the split point at the top of "slave"'s
2615   // split point stack (the "helpful master concept" in YBWC terminology).
2616
2617   bool thread_is_available(int slave, int master) {
2618     assert(slave >= 0 && slave < ActiveThreads);
2619     assert(master >= 0 && master < ActiveThreads);
2620     assert(ActiveThreads > 1);
2621
2622     if(!Threads[slave].idle || slave == master)
2623       return false;
2624
2625     if(Threads[slave].activeSplitPoints == 0)
2626       // No active split points means that the thread is available as a slave
2627       // for any other thread.
2628       return true;
2629
2630     if(ActiveThreads == 2)
2631       return true;
2632
2633     // Apply the "helpful master" concept if possible.
2634     if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2635       return true;
2636
2637     return false;
2638   }
2639
2640
2641   // idle_thread_exists() tries to find an idle thread which is available as
2642   // a slave for the thread with threadID "master".
2643
2644   bool idle_thread_exists(int master) {
2645     assert(master >= 0 && master < ActiveThreads);
2646     assert(ActiveThreads > 1);
2647
2648     for(int i = 0; i < ActiveThreads; i++)
2649       if(thread_is_available(i, master))
2650         return true;
2651     return false;
2652   }
2653
2654
2655   // split() does the actual work of distributing the work at a node between
2656   // several threads at PV nodes.  If it does not succeed in splitting the
2657   // node (because no idle threads are available, or because we have no unused
2658   // split point objects), the function immediately returns false.  If
2659   // splitting is possible, a SplitPoint object is initialized with all the
2660   // data that must be copied to the helper threads (the current position and
2661   // search stack, alpha, beta, the search depth, etc.), and we tell our
2662   // helper threads that they have been assigned work.  This will cause them
2663   // to instantly leave their idle loops and call sp_search_pv().  When all
2664   // threads have returned from sp_search_pv (or, equivalently, when
2665   // splitPoint->cpus becomes 0), split() returns true.
2666
2667   bool split(const Position &p, SearchStack *sstck, int ply,
2668              Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2669              MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2670
2671     assert(p.is_ok());
2672     assert(sstck != NULL);
2673     assert(ply >= 0 && ply < PLY_MAX);
2674     assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2675     assert(!pvNode || *alpha < *beta);
2676     assert(*beta <= VALUE_INFINITE);
2677     assert(depth > Depth(0));
2678     assert(master >= 0 && master < ActiveThreads);
2679     assert(ActiveThreads > 1);
2680
2681     SplitPoint *splitPoint;
2682     int i;
2683
2684     lock_grab(&MPLock);
2685
2686     // If no other thread is available to help us, or if we have too many
2687     // active split points, don't split:
2688     if(!idle_thread_exists(master) ||
2689        Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2690       lock_release(&MPLock);
2691       return false;
2692     }
2693
2694     // Pick the next available split point object from the split point stack:
2695     splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2696     Threads[master].activeSplitPoints++;
2697
2698     // Initialize the split point object:
2699     splitPoint->parent = Threads[master].splitPoint;
2700     splitPoint->finished = false;
2701     splitPoint->ply = ply;
2702     splitPoint->depth = depth;
2703     splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2704     splitPoint->beta = *beta;
2705     splitPoint->pvNode = pvNode;
2706     splitPoint->dcCandidates = dcCandidates;
2707     splitPoint->bestValue = *bestValue;
2708     splitPoint->master = master;
2709     splitPoint->mp = mp;
2710     splitPoint->moves = *moves;
2711     splitPoint->cpus = 1;
2712     splitPoint->pos.copy(p);
2713     splitPoint->parentSstack = sstck;
2714     for(i = 0; i < ActiveThreads; i++)
2715       splitPoint->slaves[i] = 0;
2716
2717     // Copy the current position and the search stack to the master thread:
2718     memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2719     Threads[master].splitPoint = splitPoint;
2720
2721     // Make copies of the current position and search stack for each thread:
2722     for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2723         i++)
2724       if(thread_is_available(i, master)) {
2725         memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2726         Threads[i].splitPoint = splitPoint;
2727         splitPoint->slaves[i] = 1;
2728         splitPoint->cpus++;
2729       }
2730
2731     // Tell the threads that they have work to do.  This will make them leave
2732     // their idle loop.
2733     for(i = 0; i < ActiveThreads; i++)
2734       if(i == master || splitPoint->slaves[i]) {
2735         Threads[i].workIsWaiting = true;
2736         Threads[i].idle = false;
2737         Threads[i].stop = false;
2738       }
2739
2740     lock_release(&MPLock);
2741
2742     // Everything is set up.  The master thread enters the idle loop, from
2743     // which it will instantly launch a search, because its workIsWaiting
2744     // slot is 'true'.  We send the split point as a second parameter to the
2745     // idle loop, which means that the main thread will return from the idle
2746     // loop when all threads have finished their work at this split point
2747     // (i.e. when // splitPoint->cpus == 0).
2748     idle_loop(master, splitPoint);
2749
2750     // We have returned from the idle loop, which means that all threads are
2751     // finished.  Update alpha, beta and bestvalue, and return:
2752     lock_grab(&MPLock);
2753     if(pvNode) *alpha = splitPoint->alpha;
2754     *beta = splitPoint->beta;
2755     *bestValue = splitPoint->bestValue;
2756     Threads[master].stop = false;
2757     Threads[master].idle = false;
2758     Threads[master].activeSplitPoints--;
2759     Threads[master].splitPoint = splitPoint->parent;
2760     lock_release(&MPLock);
2761
2762     return true;
2763   }
2764
2765
2766   // wake_sleeping_threads() wakes up all sleeping threads when it is time
2767   // to start a new search from the root.
2768
2769   void wake_sleeping_threads() {
2770     if(ActiveThreads > 1) {
2771       for(int i = 1; i < ActiveThreads; i++) {
2772         Threads[i].idle = true;
2773         Threads[i].workIsWaiting = false;
2774       }
2775 #if !defined(_MSC_VER)
2776       pthread_mutex_lock(&WaitLock);
2777       pthread_cond_broadcast(&WaitCond);
2778       pthread_mutex_unlock(&WaitLock);
2779 #else
2780       for(int i = 1; i < THREAD_MAX; i++)
2781         SetEvent(SitIdleEvent[i]);
2782 #endif
2783     }
2784   }
2785
2786
2787   // init_thread() is the function which is called when a new thread is
2788   // launched.  It simply calls the idle_loop() function with the supplied
2789   // threadID.  There are two versions of this function; one for POSIX threads
2790   // and one for Windows threads.
2791
2792 #if !defined(_MSC_VER)
2793
2794   void *init_thread(void *threadID) {
2795     idle_loop(*(int *)threadID, NULL);
2796     return NULL;
2797   }
2798
2799 #else
2800
2801   DWORD WINAPI init_thread(LPVOID threadID) {
2802     idle_loop(*(int *)threadID, NULL);
2803     return NULL;
2804   }
2805
2806 #endif
2807
2808 }