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