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