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