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