]> git.sesse.net Git - stockfish/blob - src/search.cpp
Restore LSN filtering
[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)*80) / 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     // Initialize, and make an early exit in case of an aborted search,
898     // an instant draw, maximum ply reached, etc.
899     if (AbortSearch || thread_should_stop(threadID))
900         return Value(0);
901
902     if (depth < OnePly)
903         return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
904
905     init_node(pos, ss, ply, threadID);
906
907     if (pos.is_draw())
908         return VALUE_DRAW;
909
910     EvalInfo ei;
911
912     if (ply >= PLY_MAX - 1)
913         return evaluate(pos, ei, threadID);
914
915     // Mate distance pruning
916     Value oldAlpha = alpha;
917     alpha = Max(value_mated_in(ply), alpha);
918     beta = Min(value_mate_in(ply+1), beta);
919     if (alpha >= beta)
920         return alpha;
921
922     // Transposition table lookup. At PV nodes, we don't use the TT for
923     // pruning, but only for move ordering.
924     const TTEntry* tte = TT.retrieve(pos);
925     Move ttMove = (tte ? tte->move() : MOVE_NONE);
926
927     // Go with internal iterative deepening if we don't have a TT move
928     if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
929     {
930         search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
931         ttMove = ss[ply].pv[ply];
932     }
933
934     // Initialize a MovePicker object for the current position, and prepare
935     // to search all moves
936     MovePicker mp = MovePicker(pos, true, ttMove, ss[ply].mateKiller,
937                                ss[ply].killer1, ss[ply].killer2, depth);
938
939     Move move, movesSearched[256];
940     int moveCount = 0;
941     Value value, bestValue = -VALUE_INFINITE;
942     Bitboard dcCandidates = mp.discovered_check_candidates();
943     bool isCheck = pos.is_check();
944     bool mateThreat =   MateThreatExtension[1] > Depth(0)
945                      && pos.has_mate_threat(opposite_color(pos.side_to_move()));
946
947     // Loop through all legal moves until no moves remain or a beta cutoff
948     // occurs.
949     while (   alpha < beta
950            && (move = mp.get_next_move()) != MOVE_NONE
951            && !thread_should_stop(threadID))
952     {
953       assert(move_is_ok(move));
954
955       bool singleReply = (isCheck && mp.number_of_moves() == 1);
956       bool moveIsCheck = pos.move_is_check(move, dcCandidates);
957       bool moveIsCapture = pos.move_is_capture(move);
958       bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
959
960       movesSearched[moveCount++] = ss[ply].currentMove = move;
961
962       if (moveIsCapture)
963           ss[ply].currentMoveCaptureValue = pos.midgame_value_of_piece_on(move_to(move));
964       else if (move_is_ep(move))
965           ss[ply].currentMoveCaptureValue = PawnValueMidgame;
966       else
967           ss[ply].currentMoveCaptureValue = Value(0);
968
969       // Decide the new search depth
970       Depth ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat);
971       Depth newDepth = depth - OnePly + ext;
972
973       // Make and search the move
974       UndoInfo u;
975       pos.do_move(move, u, dcCandidates);
976
977       if (moveCount == 1) // The first move in list is the PV
978           value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
979       else
980       {
981         // Try to reduce non-pv search depth by one ply if move seems not problematic,
982         // if the move fails high will be re-searched at full depth.
983         if (    depth >= 2*OnePly
984             &&  ext == Depth(0)
985             &&  moveCount >= LMRPVMoves
986             && !moveIsCapture
987             && !move_promotion(move)
988             && !moveIsPassedPawnPush
989             && !move_is_castle(move)
990             &&  move != ss[ply].killer1
991             &&  move != ss[ply].killer2)
992         {
993             ss[ply].reduction = OnePly;
994             value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
995         }
996         else
997             value = alpha + 1; // Just to trigger next condition
998
999         if (value > alpha) // Go with full depth pv search
1000         {
1001             ss[ply].reduction = Depth(0);
1002             value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1003             if (value > alpha && value < beta)
1004             {
1005                 // When the search fails high at ply 1 while searching the first
1006                 // move at the root, set the flag failHighPly1. This is used for
1007                 // time managment:  We don't want to stop the search early in
1008                 // such cases, because resolving the fail high at ply 1 could
1009                 // result in a big drop in score at the root.
1010                 if (ply == 1 && RootMoveNumber == 1)
1011                     Threads[threadID].failHighPly1 = true;
1012
1013                 // A fail high occurred. Re-search at full window (pv search)
1014                 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1015                 Threads[threadID].failHighPly1 = false;
1016           }
1017         }
1018       }
1019       pos.undo_move(move, u);
1020
1021       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1022
1023       // New best move?
1024       if (value > bestValue)
1025       {
1026           bestValue = value;
1027           if (value > alpha)
1028           {
1029               alpha = value;
1030               update_pv(ss, ply);
1031               if (value == value_mate_in(ply + 1))
1032                   ss[ply].mateKiller = move;
1033           }
1034           // If we are at ply 1, and we are searching the first root move at
1035           // ply 0, set the 'Problem' variable if the score has dropped a lot
1036           // (from the computer's point of view) since the previous iteration:
1037           if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1038               Problem = true;
1039       }
1040
1041       // Split?
1042       if (   ActiveThreads > 1
1043           && bestValue < beta
1044           && depth >= MinimumSplitDepth
1045           && Iteration <= 99
1046           && idle_thread_exists(threadID)
1047           && !AbortSearch
1048           && !thread_should_stop(threadID)
1049           && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1050                    &moveCount, &mp, dcCandidates, threadID, true))
1051           break;
1052     }
1053
1054     // All legal moves have been searched.  A special case: If there were
1055     // no legal moves, it must be mate or stalemate:
1056     if (moveCount == 0)
1057         return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1058
1059     // If the search is not aborted, update the transposition table,
1060     // history counters, and killer moves.
1061     if (AbortSearch || thread_should_stop(threadID))
1062         return bestValue;
1063
1064     if (bestValue <= oldAlpha)
1065         TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1066
1067     else if (bestValue >= beta)
1068     {
1069         Move m = ss[ply].pv[ply];
1070         if (ok_to_history(pos, m)) // Only non capture moves are considered
1071         {
1072             update_history(pos, m, depth, movesSearched, moveCount);
1073             if (m != ss[ply].killer1)
1074             {
1075                 ss[ply].killer2 = ss[ply].killer1;
1076                 ss[ply].killer1 = m;
1077             }
1078         }
1079         TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1080     }
1081     else
1082         TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1083
1084     return bestValue;
1085   }
1086
1087
1088   // search() is the search function for zero-width nodes.
1089
1090   Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1091                int ply, bool allowNullmove, int threadID) {
1092
1093     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1094     assert(ply >= 0 && ply < PLY_MAX);
1095     assert(threadID >= 0 && threadID < ActiveThreads);
1096
1097     EvalInfo ei;
1098
1099     // Initialize, and make an early exit in case of an aborted search,
1100     // an instant draw, maximum ply reached, etc.
1101     if (AbortSearch || thread_should_stop(threadID))
1102         return Value(0);
1103
1104     if (depth < OnePly)
1105         return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1106
1107     init_node(pos, ss, ply, threadID);
1108
1109     if (pos.is_draw())
1110         return VALUE_DRAW;
1111
1112     if (ply >= PLY_MAX - 1)
1113         return evaluate(pos, ei, threadID);
1114
1115     // Mate distance pruning
1116     if (value_mated_in(ply) >= beta)
1117         return beta;
1118
1119     if (value_mate_in(ply + 1) < beta)
1120         return beta - 1;
1121
1122     // Transposition table lookup
1123     const TTEntry* tte = TT.retrieve(pos);
1124     Move ttMove = (tte ? tte->move() : MOVE_NONE);
1125
1126     if (tte && ok_to_use_TT(tte, depth, beta, ply))
1127     {
1128         ss[ply].currentMove = ttMove; // can be MOVE_NONE ?
1129         return value_from_tt(tte->value(), ply);
1130     }
1131
1132     Value approximateEval = quick_evaluate(pos);
1133     bool mateThreat = false;
1134     bool isCheck = pos.is_check();
1135
1136     // Null move search
1137     if (    allowNullmove
1138         && !isCheck
1139         &&  ok_to_do_nullmove(pos)
1140         &&  approximateEval >= beta - NullMoveMargin)
1141     {
1142         ss[ply].currentMove = MOVE_NULL;
1143
1144         UndoInfo u;
1145         pos.do_null_move(u);
1146         Value nullValue = -search(pos, ss, -(beta-1), depth-4*OnePly, ply+1, false, threadID);
1147         pos.undo_null_move(u);
1148
1149         if (nullValue >= beta)
1150         {
1151             if (depth < 6 * OnePly)
1152                 return beta;
1153
1154             // Do zugzwang verification search
1155             Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1156             if (v >= beta)
1157                 return beta;
1158         } else {
1159             // The null move failed low, which means that we may be faced with
1160             // some kind of threat.  If the previous move was reduced, check if
1161             // the move that refuted the null move was somehow connected to the
1162             // move which was reduced.  If a connection is found, return a fail
1163             // low score (which will cause the reduced move to fail high in the
1164             // parent node, which will trigger a re-search with full depth).
1165             if (nullValue == value_mated_in(ply + 2))
1166                 mateThreat = true;
1167
1168             ss[ply].threatMove = ss[ply + 1].currentMove;
1169             if (   depth < ThreatDepth
1170                 && ss[ply - 1].reduction
1171                 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1172                 return beta - 1;
1173         }
1174     }
1175     // Null move search not allowed, try razoring
1176     else if (  (approximateEval < beta - RazorMargin && depth < RazorDepth)
1177              ||(approximateEval < beta - PawnValueMidgame && depth <= OnePly))
1178     {
1179         Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1180         if (v < beta)
1181             return v;
1182     }
1183
1184     // Go with internal iterative deepening if we don't have a TT move
1185     if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1186         evaluate(pos, ei, threadID) >= beta - IIDMargin)
1187     {
1188         search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1189         ttMove = ss[ply].pv[ply];
1190     }
1191
1192     // Initialize a MovePicker object for the current position, and prepare
1193     // to search all moves:
1194     MovePicker mp = MovePicker(pos, false, ttMove, ss[ply].mateKiller,
1195                                ss[ply].killer1, ss[ply].killer2, depth);
1196
1197     Move move, movesSearched[256];
1198     int moveCount = 0;
1199     Value value, bestValue = -VALUE_INFINITE;
1200     Bitboard dcCandidates = mp.discovered_check_candidates();
1201     Value futilityValue = VALUE_NONE;
1202     bool useFutilityPruning =   UseFutilityPruning
1203                              && depth < SelectiveDepth
1204                              && !isCheck;
1205
1206     // Loop through all legal moves until no moves remain or a beta cutoff
1207     // occurs.
1208     while (   bestValue < beta
1209            && (move = mp.get_next_move()) != MOVE_NONE
1210            && !thread_should_stop(threadID))
1211     {
1212       assert(move_is_ok(move));
1213
1214       bool singleReply = (isCheck && mp.number_of_moves() == 1);
1215       bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1216       bool moveIsCapture = pos.move_is_capture(move);
1217       bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1218
1219       movesSearched[moveCount++] = ss[ply].currentMove = move;
1220
1221       // Decide the new search depth
1222       Depth ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat);
1223       Depth newDepth = depth - OnePly + ext;
1224
1225       // Futility pruning
1226       if (    useFutilityPruning
1227           &&  ext == Depth(0)
1228           && !moveIsCapture
1229           && !moveIsPassedPawnPush
1230           && !move_promotion(move))
1231       {
1232           if (   moveCount >= 2 + int(depth)
1233               && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1234               continue;
1235
1236           if (depth < 3 * OnePly && approximateEval < beta)
1237           {
1238               if (futilityValue == VALUE_NONE)
1239                   futilityValue =  evaluate(pos, ei, threadID)
1240                                 + (depth < 2 * OnePly ? FutilityMargin1 : FutilityMargin2);
1241
1242               if (futilityValue < beta)
1243               {
1244                   if (futilityValue > bestValue)
1245                       bestValue = futilityValue;
1246                   continue;
1247               }
1248           }
1249       }
1250
1251       // Make and search the move
1252       UndoInfo u;
1253       pos.do_move(move, u, dcCandidates);
1254
1255       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1256       // if the move fails high will be re-searched at full depth.
1257       if (   depth >= 2*OnePly
1258           && ext == Depth(0)
1259           && moveCount >= LMRNonPVMoves
1260           && !moveIsCapture
1261           && !move_promotion(move)
1262           && !moveIsPassedPawnPush
1263           && !move_is_castle(move)
1264           &&  move != ss[ply].killer1
1265           &&  move != ss[ply].killer2)
1266       {
1267           ss[ply].reduction = OnePly;
1268           value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1269       }
1270       else
1271         value = beta; // Just to trigger next condition
1272
1273       if (value >= beta) // Go with full depth non-pv search
1274       {
1275           ss[ply].reduction = Depth(0);
1276           value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1277       }
1278       pos.undo_move(move, u);
1279
1280       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1281
1282       // New best move?
1283       if (value > bestValue)
1284       {
1285         bestValue = value;
1286         if (value >= beta)
1287             update_pv(ss, ply);
1288
1289         if (value == value_mate_in(ply + 1))
1290             ss[ply].mateKiller = move;
1291       }
1292
1293       // Split?
1294       if (   ActiveThreads > 1
1295           && bestValue < beta
1296           && depth >= MinimumSplitDepth
1297           && Iteration <= 99
1298           && idle_thread_exists(threadID)
1299           && !AbortSearch
1300           && !thread_should_stop(threadID)
1301           && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1302                    &mp, dcCandidates, threadID, false))
1303         break;
1304     }
1305
1306     // All legal moves have been searched.  A special case: If there were
1307     // no legal moves, it must be mate or stalemate.
1308     if (moveCount == 0)
1309         return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1310
1311     // If the search is not aborted, update the transposition table,
1312     // history counters, and killer moves.
1313     if (AbortSearch || thread_should_stop(threadID))
1314         return bestValue;
1315
1316     if (bestValue < beta)
1317         TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1318     else
1319     {
1320         Move m = ss[ply].pv[ply];
1321         if (ok_to_history(pos, m)) // Only non capture moves are considered
1322         {
1323             update_history(pos, m, depth, movesSearched, moveCount);
1324             if (m != ss[ply].killer1)
1325             {
1326                 ss[ply].killer2 = ss[ply].killer1;
1327                 ss[ply].killer1 = m;
1328             }
1329         }
1330         TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1331     }
1332     return bestValue;
1333   }
1334
1335
1336   // qsearch() is the quiescence search function, which is called by the main
1337   // search function when the remaining depth is zero (or, to be more precise,
1338   // less than OnePly).
1339
1340   Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1341                 Depth depth, int ply, int threadID) {
1342
1343     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1344     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1345     assert(depth <= 0);
1346     assert(ply >= 0 && ply < PLY_MAX);
1347     assert(threadID >= 0 && threadID < ActiveThreads);
1348
1349     EvalInfo ei;
1350
1351     // Initialize, and make an early exit in case of an aborted search,
1352     // an instant draw, maximum ply reached, etc.
1353     if (AbortSearch || thread_should_stop(threadID))
1354         return Value(0);
1355
1356     init_node(pos, ss, ply, threadID);
1357
1358     if (pos.is_draw())
1359         return VALUE_DRAW;
1360
1361     // Transposition table lookup
1362     const TTEntry* tte = TT.retrieve(pos);
1363     if (tte && ok_to_use_TT(tte, depth, beta, ply))
1364         return value_from_tt(tte->value(), ply);
1365
1366     // Evaluate the position statically
1367     Value staticValue = evaluate(pos, ei, threadID);
1368
1369     if (ply == PLY_MAX - 1)
1370         return staticValue;
1371
1372     // Initialize "stand pat score", and return it immediately if it is
1373     // at least beta.
1374     Value bestValue = (pos.is_check() ? -VALUE_INFINITE : staticValue);
1375
1376     if (bestValue >= beta)
1377         return bestValue;
1378
1379     if (bestValue > alpha)
1380         alpha = bestValue;
1381
1382     // Initialize a MovePicker object for the current position, and prepare
1383     // to search the moves.  Because the depth is <= 0 here, only captures,
1384     // queen promotions and checks (only if depth == 0) will be generated.
1385     MovePicker mp = MovePicker(pos, false, MOVE_NONE, MOVE_NONE, MOVE_NONE,
1386                                MOVE_NONE, depth);
1387     Move move;
1388     int moveCount = 0;
1389     Bitboard dcCandidates = mp.discovered_check_candidates();
1390     bool isCheck = pos.is_check();
1391
1392     // Loop through the moves until no moves remain or a beta cutoff
1393     // occurs.
1394     while (   alpha < beta
1395            && (move = mp.get_next_move()) != MOVE_NONE)
1396     {
1397       assert(move_is_ok(move));
1398
1399       bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1400       bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1401
1402       moveCount++;
1403       ss[ply].currentMove = move;
1404
1405       // Futility pruning
1406       if (    UseQSearchFutilityPruning
1407           && !isCheck
1408           && !moveIsCheck
1409           && !move_promotion(move)
1410           && !moveIsPassedPawnPush
1411           &&  beta - alpha == 1
1412           &&  pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame)
1413       {
1414           Value futilityValue = staticValue
1415                               + Max(pos.midgame_value_of_piece_on(move_to(move)),
1416                                     pos.endgame_value_of_piece_on(move_to(move)))
1417                               + FutilityMargin0
1418                               + ei.futilityMargin;
1419
1420           if (futilityValue < alpha)
1421           {
1422               if (futilityValue > bestValue)
1423                   bestValue = futilityValue;
1424               continue;
1425           }
1426       }
1427
1428       // Don't search captures and checks with negative SEE values.
1429       if (   !isCheck
1430           && !move_promotion(move)
1431           && (pos.midgame_value_of_piece_on(move_from(move)) >
1432               pos.midgame_value_of_piece_on(move_to(move)))
1433           &&  pos.see(move) < 0)
1434           continue;
1435
1436       // Make and search the move.
1437       UndoInfo u;
1438       pos.do_move(move, u, dcCandidates);
1439       Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1440       pos.undo_move(move, u);
1441
1442       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1443
1444       // New best move?
1445       if (value > bestValue)
1446       {
1447           bestValue = value;
1448           if (value > alpha)
1449           {
1450               alpha = value;
1451               update_pv(ss, ply);
1452           }
1453        }
1454     }
1455
1456     // All legal moves have been searched.  A special case: If we're in check
1457     // and no legal moves were found, it is checkmate:
1458     if (pos.is_check() && moveCount == 0) // Mate!
1459         return value_mated_in(ply);
1460
1461     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1462
1463     // Update transposition table
1464     TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1465
1466     return bestValue;
1467   }
1468
1469
1470   // sp_search() is used to search from a split point.  This function is called
1471   // by each thread working at the split point.  It is similar to the normal
1472   // search() function, but simpler.  Because we have already probed the hash
1473   // table, done a null move search, and searched the first move before
1474   // splitting, we don't have to repeat all this work in sp_search().  We
1475   // also don't need to store anything to the hash table here:  This is taken
1476   // care of after we return from the split point.
1477
1478   void sp_search(SplitPoint *sp, int threadID) {
1479
1480     assert(threadID >= 0 && threadID < ActiveThreads);
1481     assert(ActiveThreads > 1);
1482
1483     Position pos = Position(sp->pos);
1484     SearchStack *ss = sp->sstack[threadID];
1485     Value value;
1486     Move move;
1487     bool isCheck = pos.is_check();
1488     bool useFutilityPruning =    UseFutilityPruning
1489                               && sp->depth < SelectiveDepth
1490                               && !isCheck;
1491
1492     while (    sp->bestValue < sp->beta
1493            && !thread_should_stop(threadID)
1494            && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1495     {
1496       assert(move_is_ok(move));
1497
1498       bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1499       bool moveIsCapture = pos.move_is_capture(move);
1500       bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1501
1502       lock_grab(&(sp->lock));
1503       int moveCount = ++sp->moves;
1504       lock_release(&(sp->lock));
1505
1506       ss[sp->ply].currentMove = move;
1507
1508       // Decide the new search depth.
1509       Depth ext = extension(pos, move, false, moveIsCheck, false, false);
1510       Depth newDepth = sp->depth - OnePly + ext;
1511
1512       // Prune?
1513       if (    useFutilityPruning
1514           &&  ext == Depth(0)
1515           && !moveIsCapture
1516           && !moveIsPassedPawnPush
1517           && !move_promotion(move)
1518           &&  moveCount >= 2 + int(sp->depth)
1519           &&  ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1520         continue;
1521
1522       // Make and search the move.
1523       UndoInfo u;
1524       pos.do_move(move, u, sp->dcCandidates);
1525
1526       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1527       // if the move fails high will be re-searched at full depth.
1528       if (    ext == Depth(0)
1529           &&  moveCount >= LMRNonPVMoves
1530           && !moveIsCapture
1531           && !moveIsPassedPawnPush
1532           && !move_promotion(move)
1533           && !move_is_castle(move)
1534           &&  move != ss[sp->ply].killer1
1535           &&  move != ss[sp->ply].killer2)
1536       {
1537           ss[sp->ply].reduction = OnePly;
1538           value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1539       }
1540       else
1541           value = sp->beta; // Just to trigger next condition
1542
1543       if (value >= sp->beta) // Go with full depth non-pv search
1544       {
1545           ss[sp->ply].reduction = Depth(0);
1546           value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1547       }
1548       pos.undo_move(move, u);
1549
1550       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1551
1552       if (thread_should_stop(threadID))
1553           break;
1554
1555       // New best move?
1556       lock_grab(&(sp->lock));
1557       if (value > sp->bestValue && !thread_should_stop(threadID))
1558       {
1559           sp->bestValue = value;
1560           if (sp->bestValue >= sp->beta)
1561           {
1562               sp_update_pv(sp->parentSstack, ss, sp->ply);
1563               for (int i = 0; i < ActiveThreads; i++)
1564                   if (i != threadID && (i == sp->master || sp->slaves[i]))
1565                       Threads[i].stop = true;
1566
1567               sp->finished = true;
1568         }
1569       }
1570       lock_release(&(sp->lock));
1571     }
1572
1573     lock_grab(&(sp->lock));
1574
1575     // If this is the master thread and we have been asked to stop because of
1576     // a beta cutoff higher up in the tree, stop all slave threads:
1577     if (sp->master == threadID && thread_should_stop(threadID))
1578         for (int i = 0; i < ActiveThreads; i++)
1579             if (sp->slaves[i])
1580                 Threads[i].stop = true;
1581
1582     sp->cpus--;
1583     sp->slaves[threadID] = 0;
1584
1585     lock_release(&(sp->lock));
1586   }
1587
1588
1589   // sp_search_pv() is used to search from a PV split point.  This function
1590   // is called by each thread working at the split point.  It is similar to
1591   // the normal search_pv() function, but simpler.  Because we have already
1592   // probed the hash table and searched the first move before splitting, we
1593   // don't have to repeat all this work in sp_search_pv().  We also don't
1594   // need to store anything to the hash table here:  This is taken care of
1595   // after we return from the split point.
1596
1597   void sp_search_pv(SplitPoint *sp, int threadID) {
1598
1599     assert(threadID >= 0 && threadID < ActiveThreads);
1600     assert(ActiveThreads > 1);
1601
1602     Position pos = Position(sp->pos);
1603     SearchStack *ss = sp->sstack[threadID];
1604     Value value;
1605     Move move;
1606
1607     while (    sp->alpha < sp->beta
1608            && !thread_should_stop(threadID)
1609            && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1610     {
1611       bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1612       bool moveIsCapture = pos.move_is_capture(move);
1613       bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1614
1615       assert(move_is_ok(move));
1616
1617       ss[sp->ply].currentMoveCaptureValue = move_is_ep(move)?
1618         PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1619
1620       lock_grab(&(sp->lock));
1621       int moveCount = ++sp->moves;
1622       lock_release(&(sp->lock));
1623
1624       ss[sp->ply].currentMove = move;
1625
1626       // Decide the new search depth.
1627       Depth ext = extension(pos, move, true, moveIsCheck, false, false);
1628       Depth newDepth = sp->depth - OnePly + ext;
1629
1630       // Make and search the move.
1631       UndoInfo u;
1632       pos.do_move(move, u, sp->dcCandidates);
1633
1634       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1635       // if the move fails high will be re-searched at full depth.
1636       if (    ext == Depth(0)
1637           &&  moveCount >= LMRPVMoves
1638           && !moveIsCapture
1639           && !moveIsPassedPawnPush
1640           && !move_promotion(move)
1641           && !move_is_castle(move)
1642           &&  move != ss[sp->ply].killer1
1643           &&  move != ss[sp->ply].killer2)
1644       {
1645           ss[sp->ply].reduction = OnePly;
1646           value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1647       }
1648       else
1649           value = sp->alpha + 1; // Just to trigger next condition
1650
1651       if (value > sp->alpha) // Go with full depth non-pv search
1652       {
1653           ss[sp->ply].reduction = Depth(0);
1654           value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1655
1656           if (value > sp->alpha && value < sp->beta)
1657           {
1658               // When the search fails high at ply 1 while searching the first
1659               // move at the root, set the flag failHighPly1.  This is used for
1660               // time managment:  We don't want to stop the search early in
1661               // such cases, because resolving the fail high at ply 1 could
1662               // result in a big drop in score at the root.
1663               if (sp->ply == 1 && RootMoveNumber == 1)
1664                   Threads[threadID].failHighPly1 = true;
1665
1666               value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1667               Threads[threadID].failHighPly1 = false;
1668         }
1669       }
1670       pos.undo_move(move, u);
1671
1672       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1673
1674       if (thread_should_stop(threadID))
1675           break;
1676
1677       // New best move?
1678       lock_grab(&(sp->lock));
1679       if (value > sp->bestValue && !thread_should_stop(threadID))
1680       {
1681           sp->bestValue = value;
1682           if (value > sp->alpha)
1683           {
1684               sp->alpha = value;
1685               sp_update_pv(sp->parentSstack, ss, sp->ply);
1686               if (value == value_mate_in(sp->ply + 1))
1687                   ss[sp->ply].mateKiller = move;
1688
1689               if(value >= sp->beta)
1690               {
1691                   for(int i = 0; i < ActiveThreads; i++)
1692                       if(i != threadID && (i == sp->master || sp->slaves[i]))
1693                           Threads[i].stop = true;
1694
1695                   sp->finished = true;
1696               }
1697         }
1698         // If we are at ply 1, and we are searching the first root move at
1699         // ply 0, set the 'Problem' variable if the score has dropped a lot
1700         // (from the computer's point of view) since the previous iteration:
1701         if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1702             Problem = true;
1703       }
1704       lock_release(&(sp->lock));
1705     }
1706
1707     lock_grab(&(sp->lock));
1708
1709     // If this is the master thread and we have been asked to stop because of
1710     // a beta cutoff higher up in the tree, stop all slave threads:
1711     if (sp->master == threadID && thread_should_stop(threadID))
1712         for (int i = 0; i < ActiveThreads; i++)
1713             if (sp->slaves[i])
1714                 Threads[i].stop = true;
1715
1716     sp->cpus--;
1717     sp->slaves[threadID] = 0;
1718
1719     lock_release(&(sp->lock));
1720   }
1721
1722
1723   /// The RootMove class
1724
1725   // Constructor
1726
1727   RootMove::RootMove() {
1728     nodes = cumulativeNodes = 0ULL;
1729   }
1730
1731   // RootMove::operator<() is the comparison function used when
1732   // sorting the moves.  A move m1 is considered to be better
1733   // than a move m2 if it has a higher score, or if the moves
1734   // have equal score but m1 has the higher node count.
1735
1736   bool RootMove::operator<(const RootMove& m) {
1737
1738     if (score != m.score)
1739         return (score < m.score);
1740
1741     return nodes <= m.nodes;
1742   }
1743
1744   /// The RootMoveList class
1745
1746   // Constructor
1747
1748   RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1749
1750     MoveStack mlist[MaxRootMoves];
1751     bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1752
1753     // Generate all legal moves
1754     int lm_count = generate_legal_moves(pos, mlist);
1755
1756     // Add each move to the moves[] array
1757     for (int i = 0; i < lm_count; i++)
1758     {
1759         bool includeMove = includeAllMoves;
1760
1761         for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1762             includeMove = (searchMoves[k] == mlist[i].move);
1763
1764         if (includeMove)
1765         {
1766             // Find a quick score for the move
1767             UndoInfo u;
1768             SearchStack ss[PLY_MAX_PLUS_2];
1769
1770             moves[count].move = mlist[i].move;
1771             moves[count].nodes = 0ULL;
1772             pos.do_move(moves[count].move, u);
1773             moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1774                                           Depth(0), 1, 0);
1775             pos.undo_move(moves[count].move, u);
1776             moves[count].pv[0] = moves[i].move;
1777             moves[count].pv[1] = MOVE_NONE; // FIXME
1778             count++;
1779         }
1780     }
1781     sort();
1782   }
1783
1784
1785   // Simple accessor methods for the RootMoveList class
1786
1787   inline Move RootMoveList::get_move(int moveNum) const {
1788     return moves[moveNum].move;
1789   }
1790
1791   inline Value RootMoveList::get_move_score(int moveNum) const {
1792     return moves[moveNum].score;
1793   }
1794
1795   inline void RootMoveList::set_move_score(int moveNum, Value score) {
1796     moves[moveNum].score = score;
1797   }
1798
1799   inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1800     moves[moveNum].nodes = nodes;
1801     moves[moveNum].cumulativeNodes += nodes;
1802   }
1803
1804   void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1805     int j;
1806     for(j = 0; pv[j] != MOVE_NONE; j++)
1807       moves[moveNum].pv[j] = pv[j];
1808     moves[moveNum].pv[j] = MOVE_NONE;
1809   }
1810
1811   inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1812     return moves[moveNum].pv[i];
1813   }
1814
1815   inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1816     return moves[moveNum].cumulativeNodes;
1817   }
1818
1819   inline int RootMoveList::move_count() const {
1820     return count;
1821   }
1822
1823
1824   // RootMoveList::scan_for_easy_move() is called at the end of the first
1825   // iteration, and is used to detect an "easy move", i.e. a move which appears
1826   // to be much bester than all the rest.  If an easy move is found, the move
1827   // is returned, otherwise the function returns MOVE_NONE.  It is very
1828   // important that this function is called at the right moment:  The code
1829   // assumes that the first iteration has been completed and the moves have
1830   // been sorted. This is done in RootMoveList c'tor.
1831
1832   Move RootMoveList::scan_for_easy_move() const {
1833
1834     assert(count);
1835
1836     if (count == 1)
1837         return get_move(0);
1838
1839     // moves are sorted so just consider the best and the second one
1840     if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1841         return get_move(0);
1842
1843     return MOVE_NONE;
1844   }
1845
1846   // RootMoveList::sort() sorts the root move list at the beginning of a new
1847   // iteration.
1848
1849   inline void RootMoveList::sort() {
1850
1851     sort_multipv(count - 1); // all items
1852   }
1853
1854
1855   // RootMoveList::sort_multipv() sorts the first few moves in the root move
1856   // list by their scores and depths. It is used to order the different PVs
1857   // correctly in MultiPV mode.
1858
1859   void RootMoveList::sort_multipv(int n) {
1860
1861     for (int i = 1; i <= n; i++)
1862     {
1863       RootMove rm = moves[i];
1864       int j;
1865       for (j = i; j > 0 && moves[j-1] < rm; j--)
1866           moves[j] = moves[j-1];
1867       moves[j] = rm;
1868     }
1869   }
1870
1871
1872   // init_search_stack() initializes a search stack at the beginning of a
1873   // new search from the root.
1874
1875   void init_search_stack(SearchStack ss[]) {
1876     for(int i = 0; i < 3; i++) {
1877       ss[i].pv[i] = MOVE_NONE;
1878       ss[i].pv[i+1] = MOVE_NONE;
1879       ss[i].currentMove = MOVE_NONE;
1880       ss[i].mateKiller = MOVE_NONE;
1881       ss[i].killer1 = MOVE_NONE;
1882       ss[i].killer2 = MOVE_NONE;
1883       ss[i].threatMove = MOVE_NONE;
1884       ss[i].reduction = Depth(0);
1885     }
1886   }
1887
1888
1889   // init_node() is called at the beginning of all the search functions
1890   // (search(), search_pv(), qsearch(), and so on) and initializes the search
1891   // stack object corresponding to the current node.  Once every
1892   // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1893   // for user input and checks whether it is time to stop the search.
1894
1895   void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1896     assert(ply >= 0 && ply < PLY_MAX);
1897     assert(threadID >= 0 && threadID < ActiveThreads);
1898
1899     Threads[threadID].nodes++;
1900
1901     if(threadID == 0) {
1902       NodesSincePoll++;
1903       if(NodesSincePoll >= NodesBetweenPolls) {
1904         poll();
1905         NodesSincePoll = 0;
1906       }
1907     }
1908
1909     ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
1910     ss[ply+2].mateKiller = MOVE_NONE;
1911     ss[ply+2].killer1 = ss[ply+2].killer2 = MOVE_NONE;
1912     ss[ply].threatMove = MOVE_NONE;
1913     ss[ply].reduction = Depth(0);
1914     ss[ply].currentMoveCaptureValue = Value(0);
1915
1916     if(Threads[threadID].printCurrentLine)
1917       print_current_line(ss, ply, threadID);
1918   }
1919
1920
1921   // update_pv() is called whenever a search returns a value > alpha.  It
1922   // updates the PV in the SearchStack object corresponding to the current
1923   // node.
1924
1925   void update_pv(SearchStack ss[], int ply) {
1926     assert(ply >= 0 && ply < PLY_MAX);
1927
1928     ss[ply].pv[ply] = ss[ply].currentMove;
1929     int p;
1930     for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1931       ss[ply].pv[p] = ss[ply+1].pv[p];
1932     ss[ply].pv[p] = MOVE_NONE;
1933   }
1934
1935
1936   // sp_update_pv() is a variant of update_pv for use at split points.  The
1937   // difference between the two functions is that sp_update_pv also updates
1938   // the PV at the parent node.
1939
1940   void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
1941     assert(ply >= 0 && ply < PLY_MAX);
1942
1943     ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1944     int p;
1945     for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1946       ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
1947     ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1948   }
1949
1950
1951   // connected_moves() tests whether two moves are 'connected' in the sense
1952   // that the first move somehow made the second move possible (for instance
1953   // if the moving piece is the same in both moves).  The first move is
1954   // assumed to be the move that was made to reach the current position, while
1955   // the second move is assumed to be a move from the current position.
1956
1957   bool connected_moves(const Position &pos, Move m1, Move m2) {
1958     Square f1, t1, f2, t2;
1959
1960     assert(move_is_ok(m1));
1961     assert(move_is_ok(m2));
1962
1963     if(m2 == MOVE_NONE)
1964       return false;
1965
1966     // Case 1: The moving piece is the same in both moves.
1967     f2 = move_from(m2);
1968     t1 = move_to(m1);
1969     if(f2 == t1)
1970       return true;
1971
1972     // Case 2: The destination square for m2 was vacated by m1.
1973     t2 = move_to(m2);
1974     f1 = move_from(m1);
1975     if(t2 == f1)
1976       return true;
1977
1978     // Case 3: Moving through the vacated square:
1979     if(piece_is_slider(pos.piece_on(f2)) &&
1980        bit_is_set(squares_between(f2, t2), f1))
1981       return true;
1982
1983     // Case 4: The destination square for m2 is attacked by the moving piece
1984     // in m1:
1985     if(pos.piece_attacks_square(t1, t2))
1986       return true;
1987
1988     // Case 5: Discovered check, checking piece is the piece moved in m1:
1989     if(piece_is_slider(pos.piece_on(t1)) &&
1990        bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
1991                   f2) &&
1992        !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
1993                    t2)) {
1994       Bitboard occ = pos.occupied_squares();
1995       Color us = pos.side_to_move();
1996       Square ksq = pos.king_square(us);
1997       clear_bit(&occ, f2);
1998       if(pos.type_of_piece_on(t1) == BISHOP) {
1999         if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2000           return true;
2001       }
2002       else if(pos.type_of_piece_on(t1) == ROOK) {
2003         if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2004           return true;
2005       }
2006       else {
2007         assert(pos.type_of_piece_on(t1) == QUEEN);
2008         if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2009           return true;
2010       }
2011     }
2012
2013     return false;
2014   }
2015
2016
2017   // extension() decides whether a move should be searched with normal depth,
2018   // or with extended depth.  Certain classes of moves (checking moves, in
2019   // particular) are searched with bigger depth than ordinary moves.
2020
2021   Depth extension(const Position &pos, Move m, bool pvNode,
2022                   bool check, bool singleReply, bool mateThreat) {
2023
2024     Depth result = Depth(0);
2025
2026     if (check)
2027         result += CheckExtension[pvNode];
2028
2029     if (singleReply)
2030         result += SingleReplyExtension[pvNode];
2031
2032     if (pos.move_is_pawn_push_to_7th(m))
2033         result += PawnPushTo7thExtension[pvNode];
2034
2035     if (pos.move_is_passed_pawn_push(m))
2036         result += PassedPawnExtension[pvNode];
2037
2038     if (mateThreat)
2039         result += MateThreatExtension[pvNode];
2040
2041     if (   pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame\r
2042         && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)\r
2043             - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))\r
2044         && !move_promotion(m))
2045         result += PawnEndgameExtension[pvNode];
2046     
2047     if (   pvNode
2048         && pos.move_is_capture(m)
2049         && pos.type_of_piece_on(move_to(m)) != PAWN
2050         && pos.see(m) >= 0)
2051         result += OnePly/2;
2052
2053     return Min(result, OnePly);
2054   }
2055
2056
2057   // ok_to_do_nullmove() looks at the current position and decides whether
2058   // doing a 'null move' should be allowed.  In order to avoid zugzwang
2059   // problems, null moves are not allowed when the side to move has very
2060   // little material left.  Currently, the test is a bit too simple:  Null
2061   // moves are avoided only when the side to move has only pawns left.  It's
2062   // probably a good idea to avoid null moves in at least some more
2063   // complicated endgames, e.g. KQ vs KR.  FIXME
2064
2065   bool ok_to_do_nullmove(const Position &pos) {
2066     if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2067       return false;
2068     return true;
2069   }
2070
2071
2072   // ok_to_prune() tests whether it is safe to forward prune a move.  Only
2073   // non-tactical moves late in the move list close to the leaves are
2074   // candidates for pruning.
2075
2076   bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2077     Square mfrom, mto, tfrom, tto;
2078
2079     assert(move_is_ok(m));
2080     assert(threat == MOVE_NONE || move_is_ok(threat));
2081     assert(!move_promotion(m));
2082     assert(!pos.move_is_check(m));
2083     assert(!pos.move_is_capture(m));
2084     assert(!pos.move_is_passed_pawn_push(m));
2085     assert(d >= OnePly);
2086
2087     mfrom = move_from(m);
2088     mto = move_to(m);
2089     tfrom = move_from(threat);
2090     tto = move_to(threat);
2091
2092     // Case 1: Castling moves are never pruned.
2093     if(move_is_castle(m))
2094       return false;
2095
2096     // Case 2: Don't prune moves which move the threatened piece
2097     if(!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2098       return false;
2099
2100     // Case 3: If the threatened piece has value less than or equal to the
2101     // value of the threatening piece, don't prune move which defend it.
2102     if(!PruneDefendingMoves && threat != MOVE_NONE
2103        && (piece_value_midgame(pos.piece_on(tfrom))
2104            >= piece_value_midgame(pos.piece_on(tto)))
2105        && pos.move_attacks_square(m, tto))
2106       return false;
2107
2108     // Case 4: Don't prune moves with good history.
2109     if(!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2110       return false;
2111
2112     // Case 5: If the moving piece in the threatened move is a slider, don't
2113     // prune safe moves which block its ray.
2114     if(!PruneBlockingMoves && threat != MOVE_NONE
2115        && piece_is_slider(pos.piece_on(tfrom))
2116        && bit_is_set(squares_between(tfrom, tto), mto) && pos.see(m) >= 0)
2117       return false;
2118
2119     return true;
2120   }
2121
2122
2123   // ok_to_use_TT() returns true if a transposition table score
2124   // can be used at a given point in search.
2125
2126   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2127
2128     Value v = value_from_tt(tte->value(), ply);
2129
2130     return   (   tte->depth() >= depth
2131               || v >= Max(value_mate_in(100), beta)
2132               || v < Min(value_mated_in(100), beta))
2133
2134           && (   (is_lower_bound(tte->type()) && v >= beta)
2135               || (is_upper_bound(tte->type()) && v < beta));
2136   }
2137
2138
2139   // ok_to_history() returns true if a move m can be stored
2140   // in history. Should be a non capturing move.
2141
2142   bool ok_to_history(const Position& pos, Move m) {
2143
2144     return    pos.square_is_empty(move_to(m))
2145           && !move_promotion(m)
2146           && !move_is_ep(m);
2147   }
2148
2149
2150   // update_history() registers a good move that produced a beta-cutoff
2151   // in history and marks as failures all the other moves of that ply.
2152
2153   void update_history(const Position& pos, Move m, Depth depth,
2154                       Move movesSearched[], int moveCount) {
2155
2156     H.success(pos.piece_on(move_from(m)), m, depth);
2157
2158     for (int i = 0; i < moveCount - 1; i++)
2159         if (ok_to_history(pos, movesSearched[i]) && m != movesSearched[i])
2160             H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2161   }
2162
2163   // fail_high_ply_1() checks if some thread is currently resolving a fail
2164   // high at ply 1 at the node below the first root node.  This information
2165   // is used for time managment.
2166
2167   bool fail_high_ply_1() {
2168     for(int i = 0; i < ActiveThreads; i++)
2169       if(Threads[i].failHighPly1)
2170         return true;
2171     return false;
2172   }
2173
2174
2175   // current_search_time() returns the number of milliseconds which have passed
2176   // since the beginning of the current search.
2177
2178   int current_search_time() {
2179     return get_system_time() - SearchStartTime;
2180   }
2181
2182
2183   // nps() computes the current nodes/second count.
2184
2185   int nps() {
2186     int t = current_search_time();
2187     return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2188   }
2189
2190
2191   // poll() performs two different functions:  It polls for user input, and it
2192   // looks at the time consumed so far and decides if it's time to abort the
2193   // search.
2194
2195   void poll() {
2196
2197     static int lastInfoTime;
2198     int t = current_search_time();
2199
2200     //  Poll for input
2201     if (Bioskey())
2202     {
2203         // We are line oriented, don't read single chars
2204         std::string command;
2205         if (!std::getline(std::cin, command))
2206             command = "quit";
2207
2208         if (command == "quit")
2209         {
2210             AbortSearch = true;
2211             PonderSearch = false;
2212             Quit = true;
2213         }
2214         else if(command == "stop")
2215         {
2216             AbortSearch = true;
2217             PonderSearch = false;
2218         }
2219         else if(command == "ponderhit")
2220             ponderhit();
2221     }
2222     // Print search information
2223     if (t < 1000)
2224         lastInfoTime = 0;
2225
2226     else if (lastInfoTime > t)
2227         // HACK: Must be a new search where we searched less than
2228         // NodesBetweenPolls nodes during the first second of search.
2229         lastInfoTime = 0;
2230
2231     else if (t - lastInfoTime >= 1000)
2232     {
2233         lastInfoTime = t;
2234         lock_grab(&IOLock);
2235         if (dbg_show_mean)
2236             dbg_print_mean();
2237
2238         if (dbg_show_hit_rate)
2239             dbg_print_hit_rate();
2240
2241         std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2242                   << " time " << t << " hashfull " << TT.full() << std::endl;
2243         lock_release(&IOLock);
2244         if (ShowCurrentLine)
2245             Threads[0].printCurrentLine = true;
2246     }
2247     // Should we stop the search?
2248     if (PonderSearch)
2249         return;
2250
2251     bool overTime =     t > AbsoluteMaxSearchTime
2252                      || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2253                      || (  !FailHigh && !fail_high_ply_1() && !Problem
2254                          && t > 6*(MaxSearchTime + ExtraSearchTime));
2255
2256     if (   (Iteration >= 2 && (!InfiniteSearch && overTime))
2257         || (ExactMaxTime && t >= ExactMaxTime)
2258         || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2259         AbortSearch = true;
2260   }
2261
2262
2263   // ponderhit() is called when the program is pondering (i.e. thinking while
2264   // it's the opponent's turn to move) in order to let the engine know that
2265   // it correctly predicted the opponent's move.
2266
2267   void ponderhit() {
2268     int t = current_search_time();
2269     PonderSearch = false;
2270     if(Iteration >= 2 &&
2271        (!InfiniteSearch && (StopOnPonderhit ||
2272                             t > AbsoluteMaxSearchTime ||
2273                             (RootMoveNumber == 1 &&
2274                              t > MaxSearchTime + ExtraSearchTime) ||
2275                             (!FailHigh && !fail_high_ply_1() && !Problem &&
2276                              t > 6*(MaxSearchTime + ExtraSearchTime)))))
2277       AbortSearch = true;
2278   }
2279
2280
2281   // print_current_line() prints the current line of search for a given
2282   // thread.  Called when the UCI option UCI_ShowCurrLine is 'true'.
2283
2284   void print_current_line(SearchStack ss[], int ply, int threadID) {
2285     assert(ply >= 0 && ply < PLY_MAX);
2286     assert(threadID >= 0 && threadID < ActiveThreads);
2287
2288     if(!Threads[threadID].idle) {
2289       lock_grab(&IOLock);
2290       std::cout << "info currline " << (threadID + 1);
2291       for(int p = 0; p < ply; p++)
2292         std::cout << " " << ss[p].currentMove;
2293       std::cout << std::endl;
2294       lock_release(&IOLock);
2295     }
2296     Threads[threadID].printCurrentLine = false;
2297     if(threadID + 1 < ActiveThreads)
2298       Threads[threadID + 1].printCurrentLine = true;
2299   }
2300
2301
2302   // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2303   // while the program is pondering.  The point is to work around a wrinkle in
2304   // the UCI protocol:  When pondering, the engine is not allowed to give a
2305   // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2306   // We simply wait here until one of these commands is sent, and return,
2307   // after which the bestmove and pondermove will be printed (in id_loop()).
2308
2309   void wait_for_stop_or_ponderhit() {
2310     std::string command;
2311
2312     while(true) {
2313       if(!std::getline(std::cin, command))
2314         command = "quit";
2315
2316       if(command == "quit") {
2317         OpeningBook.close();
2318         stop_threads();
2319         quit_eval();
2320         exit(0);
2321       }
2322       else if(command == "ponderhit" || command == "stop")
2323         break;
2324     }
2325   }
2326
2327
2328   // idle_loop() is where the threads are parked when they have no work to do.
2329   // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2330   // object for which the current thread is the master.
2331
2332   void idle_loop(int threadID, SplitPoint *waitSp) {
2333     assert(threadID >= 0 && threadID < THREAD_MAX);
2334
2335     Threads[threadID].running = true;
2336
2337     while(true) {
2338       if(AllThreadsShouldExit && threadID != 0)
2339         break;
2340
2341       // If we are not thinking, wait for a condition to be signaled instead
2342       // of wasting CPU time polling for work:
2343       while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2344 #if !defined(_MSC_VER)
2345         pthread_mutex_lock(&WaitLock);
2346         if(Idle || threadID >= ActiveThreads)
2347           pthread_cond_wait(&WaitCond, &WaitLock);
2348         pthread_mutex_unlock(&WaitLock);
2349 #else
2350         WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2351 #endif
2352       }
2353
2354       // If this thread has been assigned work, launch a search:
2355       if(Threads[threadID].workIsWaiting) {
2356         Threads[threadID].workIsWaiting = false;
2357         if(Threads[threadID].splitPoint->pvNode)
2358           sp_search_pv(Threads[threadID].splitPoint, threadID);
2359         else
2360           sp_search(Threads[threadID].splitPoint, threadID);
2361         Threads[threadID].idle = true;
2362       }
2363
2364       // If this thread is the master of a split point and all threads have
2365       // finished their work at this split point, return from the idle loop:
2366       if(waitSp != NULL && waitSp->cpus == 0)
2367         return;
2368     }
2369
2370     Threads[threadID].running = false;
2371   }
2372
2373
2374   // init_split_point_stack() is called during program initialization, and
2375   // initializes all split point objects.
2376
2377   void init_split_point_stack() {
2378     for(int i = 0; i < THREAD_MAX; i++)
2379       for(int j = 0; j < MaxActiveSplitPoints; j++) {
2380         SplitPointStack[i][j].parent = NULL;
2381         lock_init(&(SplitPointStack[i][j].lock), NULL);
2382       }
2383   }
2384
2385
2386   // destroy_split_point_stack() is called when the program exits, and
2387   // destroys all locks in the precomputed split point objects.
2388
2389   void destroy_split_point_stack() {
2390     for(int i = 0; i < THREAD_MAX; i++)
2391       for(int j = 0; j < MaxActiveSplitPoints; j++)
2392         lock_destroy(&(SplitPointStack[i][j].lock));
2393   }
2394
2395
2396   // thread_should_stop() checks whether the thread with a given threadID has
2397   // been asked to stop, directly or indirectly.  This can happen if a beta
2398   // cutoff has occured in thre thread's currently active split point, or in
2399   // some ancestor of the current split point.
2400
2401   bool thread_should_stop(int threadID) {
2402     assert(threadID >= 0 && threadID < ActiveThreads);
2403
2404     SplitPoint *sp;
2405
2406     if(Threads[threadID].stop)
2407       return true;
2408     if(ActiveThreads <= 2)
2409       return false;
2410     for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2411       if(sp->finished) {
2412         Threads[threadID].stop = true;
2413         return true;
2414       }
2415     return false;
2416   }
2417
2418
2419   // thread_is_available() checks whether the thread with threadID "slave" is
2420   // available to help the thread with threadID "master" at a split point.  An
2421   // obvious requirement is that "slave" must be idle.  With more than two
2422   // threads, this is not by itself sufficient:  If "slave" is the master of
2423   // some active split point, it is only available as a slave to the other
2424   // threads which are busy searching the split point at the top of "slave"'s
2425   // split point stack (the "helpful master concept" in YBWC terminology).
2426
2427   bool thread_is_available(int slave, int master) {
2428     assert(slave >= 0 && slave < ActiveThreads);
2429     assert(master >= 0 && master < ActiveThreads);
2430     assert(ActiveThreads > 1);
2431
2432     if(!Threads[slave].idle || slave == master)
2433       return false;
2434
2435     if(Threads[slave].activeSplitPoints == 0)
2436       // No active split points means that the thread is available as a slave
2437       // for any other thread.
2438       return true;
2439
2440     if(ActiveThreads == 2)
2441       return true;
2442
2443     // Apply the "helpful master" concept if possible.
2444     if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2445       return true;
2446
2447     return false;
2448   }
2449
2450
2451   // idle_thread_exists() tries to find an idle thread which is available as
2452   // a slave for the thread with threadID "master".
2453
2454   bool idle_thread_exists(int master) {
2455     assert(master >= 0 && master < ActiveThreads);
2456     assert(ActiveThreads > 1);
2457
2458     for(int i = 0; i < ActiveThreads; i++)
2459       if(thread_is_available(i, master))
2460         return true;
2461     return false;
2462   }
2463
2464
2465   // split() does the actual work of distributing the work at a node between
2466   // several threads at PV nodes.  If it does not succeed in splitting the
2467   // node (because no idle threads are available, or because we have no unused
2468   // split point objects), the function immediately returns false.  If
2469   // splitting is possible, a SplitPoint object is initialized with all the
2470   // data that must be copied to the helper threads (the current position and
2471   // search stack, alpha, beta, the search depth, etc.), and we tell our
2472   // helper threads that they have been assigned work.  This will cause them
2473   // to instantly leave their idle loops and call sp_search_pv().  When all
2474   // threads have returned from sp_search_pv (or, equivalently, when
2475   // splitPoint->cpus becomes 0), split() returns true.
2476
2477   bool split(const Position &p, SearchStack *sstck, int ply,
2478              Value *alpha, Value *beta, Value *bestValue,
2479              Depth depth, int *moves,
2480              MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2481     assert(p.is_ok());
2482     assert(sstck != NULL);
2483     assert(ply >= 0 && ply < PLY_MAX);
2484     assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2485     assert(!pvNode || *alpha < *beta);
2486     assert(*beta <= VALUE_INFINITE);
2487     assert(depth > Depth(0));
2488     assert(master >= 0 && master < ActiveThreads);
2489     assert(ActiveThreads > 1);
2490
2491     SplitPoint *splitPoint;
2492     int i;
2493
2494     lock_grab(&MPLock);
2495
2496     // If no other thread is available to help us, or if we have too many
2497     // active split points, don't split:
2498     if(!idle_thread_exists(master) ||
2499        Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2500       lock_release(&MPLock);
2501       return false;
2502     }
2503
2504     // Pick the next available split point object from the split point stack:
2505     splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2506     Threads[master].activeSplitPoints++;
2507
2508     // Initialize the split point object:
2509     splitPoint->parent = Threads[master].splitPoint;
2510     splitPoint->finished = false;
2511     splitPoint->ply = ply;
2512     splitPoint->depth = depth;
2513     splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2514     splitPoint->beta = *beta;
2515     splitPoint->pvNode = pvNode;
2516     splitPoint->dcCandidates = dcCandidates;
2517     splitPoint->bestValue = *bestValue;
2518     splitPoint->master = master;
2519     splitPoint->mp = mp;
2520     splitPoint->moves = *moves;
2521     splitPoint->cpus = 1;
2522     splitPoint->pos.copy(p);
2523     splitPoint->parentSstack = sstck;
2524     for(i = 0; i < ActiveThreads; i++)
2525       splitPoint->slaves[i] = 0;
2526
2527     // Copy the current position and the search stack to the master thread:
2528     memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2529     Threads[master].splitPoint = splitPoint;
2530
2531     // Make copies of the current position and search stack for each thread:
2532     for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2533         i++)
2534       if(thread_is_available(i, master)) {
2535         memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2536         Threads[i].splitPoint = splitPoint;
2537         splitPoint->slaves[i] = 1;
2538         splitPoint->cpus++;
2539       }
2540
2541     // Tell the threads that they have work to do.  This will make them leave
2542     // their idle loop.
2543     for(i = 0; i < ActiveThreads; i++)
2544       if(i == master || splitPoint->slaves[i]) {
2545         Threads[i].workIsWaiting = true;
2546         Threads[i].idle = false;
2547         Threads[i].stop = false;
2548       }
2549
2550     lock_release(&MPLock);
2551
2552     // Everything is set up.  The master thread enters the idle loop, from
2553     // which it will instantly launch a search, because its workIsWaiting
2554     // slot is 'true'.  We send the split point as a second parameter to the
2555     // idle loop, which means that the main thread will return from the idle
2556     // loop when all threads have finished their work at this split point
2557     // (i.e. when // splitPoint->cpus == 0).
2558     idle_loop(master, splitPoint);
2559
2560     // We have returned from the idle loop, which means that all threads are
2561     // finished.  Update alpha, beta and bestvalue, and return:
2562     lock_grab(&MPLock);
2563     if(pvNode) *alpha = splitPoint->alpha;
2564     *beta = splitPoint->beta;
2565     *bestValue = splitPoint->bestValue;
2566     Threads[master].stop = false;
2567     Threads[master].idle = false;
2568     Threads[master].activeSplitPoints--;
2569     Threads[master].splitPoint = splitPoint->parent;
2570     lock_release(&MPLock);
2571
2572     return true;
2573   }
2574
2575
2576   // wake_sleeping_threads() wakes up all sleeping threads when it is time
2577   // to start a new search from the root.
2578
2579   void wake_sleeping_threads() {
2580     if(ActiveThreads > 1) {
2581       for(int i = 1; i < ActiveThreads; i++) {
2582         Threads[i].idle = true;
2583         Threads[i].workIsWaiting = false;
2584       }
2585 #if !defined(_MSC_VER)
2586       pthread_mutex_lock(&WaitLock);
2587       pthread_cond_broadcast(&WaitCond);
2588       pthread_mutex_unlock(&WaitLock);
2589 #else
2590       for(int i = 1; i < THREAD_MAX; i++)
2591         SetEvent(SitIdleEvent[i]);
2592 #endif
2593     }
2594   }
2595
2596
2597   // init_thread() is the function which is called when a new thread is
2598   // launched.  It simply calls the idle_loop() function with the supplied
2599   // threadID.  There are two versions of this function; one for POSIX threads
2600   // and one for Windows threads.
2601
2602 #if !defined(_MSC_VER)
2603
2604   void *init_thread(void *threadID) {
2605     idle_loop(*(int *)threadID, NULL);
2606     return NULL;
2607   }
2608
2609 #else
2610
2611   DWORD WINAPI init_thread(LPVOID threadID) {
2612     idle_loop(*(int *)threadID, NULL);
2613     return NULL;
2614   }
2615
2616 #endif
2617
2618 }