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