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