]> git.sesse.net Git - stockfish/blob - src/search.cpp
80b907aa7d8450c8fa75899545c898ddf4ce88f4
[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_int("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     assert(threadID >= 0 && threadID < ActiveThreads);
1540     assert(ActiveThreads > 1);
1541
1542     Position pos = Position(sp->pos);
1543     SearchStack *ss = sp->sstack[threadID];
1544     Value value;
1545     Move move;
1546     int moveCount = sp->moves;
1547
1548     while(sp->alpha < sp->beta && !thread_should_stop(threadID)
1549           && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE) {
1550       UndoInfo u;
1551       Depth ext, newDepth;
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       sp->moves++;
1563       moveCount = sp->moves;
1564       lock_release(&(sp->lock));
1565
1566       ss[sp->ply].currentMove = move;
1567
1568       // Decide the new search depth.
1569       ext = extension(pos, move, true, moveIsCheck, false, false);
1570       newDepth = sp->depth - OnePly + ext;
1571
1572       // Make and search the move.
1573       pos.do_move(move, u, sp->dcCandidates);
1574       if(ext == Depth(0) && moveCount >= LMRPVMoves && !moveIsCapture
1575          && !move_promotion(move) && !moveIsPassedPawnPush
1576          && !move_is_castle(move)
1577          && move != ss[sp->ply].killer1 && move != ss[sp->ply].killer2) {
1578         ss[sp->ply].reduction = OnePly;
1579         value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1,
1580                         true, threadID);
1581       }
1582       else
1583         value = sp->alpha + 1;
1584       if(value > sp->alpha) {
1585         ss[sp->ply].reduction = Depth(0);
1586         value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true,
1587                         threadID);
1588         if(value > sp->alpha && value < sp->beta) {
1589           if(sp->ply == 1 && RootMoveNumber == 1)
1590             // When the search fails high at ply 1 while searching the first
1591             // move at the root, set the flag failHighPly1.  This is used for
1592             // time managment:  We don't want to stop the search early in
1593             // such cases, because resolving the fail high at ply 1 could
1594             // result in a big drop in score at the root.
1595             Threads[threadID].failHighPly1 = true;
1596           value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth,
1597                              sp->ply+1, threadID);
1598           Threads[threadID].failHighPly1 = false;
1599         }
1600       }
1601       pos.undo_move(move, u);
1602
1603       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1604
1605       if(thread_should_stop(threadID))
1606         break;
1607
1608       // New best move?
1609       lock_grab(&(sp->lock));
1610       if(value > sp->bestValue && !thread_should_stop(threadID)) {
1611         sp->bestValue = value;
1612         if(value > sp->alpha) {
1613           sp->alpha = value;
1614           sp_update_pv(sp->parentSstack, ss, sp->ply);
1615           if(value == value_mate_in(sp->ply + 1))
1616             ss[sp->ply].mateKiller = move;
1617           if(value >= sp->beta) {
1618             for(int i = 0; i < ActiveThreads; i++)
1619               if(i != threadID && (i == sp->master || sp->slaves[i]))
1620                 Threads[i].stop = true;
1621             sp->finished = true;
1622           }
1623         }
1624         // If we are at ply 1, and we are searching the first root move at
1625         // ply 0, set the 'Problem' variable if the score has dropped a lot
1626         // (from the computer's point of view) since the previous iteration:
1627         if(Iteration >= 2 &&
1628            -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1629           Problem = true;
1630       }
1631       lock_release(&(sp->lock));
1632     }
1633
1634     lock_grab(&(sp->lock));
1635
1636     // If this is the master thread and we have been asked to stop because of
1637     // a beta cutoff higher up in the tree, stop all slave threads:
1638     if(sp->master == threadID && thread_should_stop(threadID))
1639       for(int i = 0; i < ActiveThreads; i++)
1640         if(sp->slaves[i])
1641           Threads[i].stop = true;
1642
1643     sp->cpus--;
1644     sp->slaves[threadID] = 0;
1645
1646     lock_release(&(sp->lock));
1647   }
1648
1649
1650   /// The RootMove class
1651
1652   // Constructor
1653
1654   RootMove::RootMove() {
1655     nodes = cumulativeNodes = 0ULL;
1656   }
1657
1658   // RootMove::operator<() is the comparison function used when
1659   // sorting the moves.  A move m1 is considered to be better
1660   // than a move m2 if it has a higher score, or if the moves
1661   // have equal score but m1 has the higher node count.
1662
1663   bool RootMove::operator<(const RootMove& m) {
1664
1665     if (score != m.score)
1666         return (score < m.score);
1667
1668     return nodes <= m.nodes;
1669   }
1670
1671   /// The RootMoveList class
1672
1673   // Constructor
1674
1675   RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1676
1677     MoveStack mlist[MaxRootMoves];
1678     bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1679
1680     // Generate all legal moves
1681     int lm_count = generate_legal_moves(pos, mlist);
1682
1683     // Add each move to the moves[] array
1684     for (int i = 0; i < lm_count; i++)
1685     {
1686         bool includeMove = includeAllMoves;
1687
1688         for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1689             includeMove = (searchMoves[k] == mlist[i].move);
1690
1691         if (includeMove)
1692         {
1693             // Find a quick score for the move
1694             UndoInfo u;
1695             SearchStack ss[PLY_MAX_PLUS_2];
1696
1697             moves[count].move = mlist[i].move;
1698             moves[count].nodes = 0ULL;
1699             pos.do_move(moves[count].move, u);
1700             moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1701                                           Depth(0), 1, 0);
1702             pos.undo_move(moves[count].move, u);
1703             moves[count].pv[0] = moves[i].move;
1704             moves[count].pv[1] = MOVE_NONE; // FIXME
1705             count++;
1706         }
1707     }
1708     sort();
1709   }
1710
1711
1712   // Simple accessor methods for the RootMoveList class
1713
1714   inline Move RootMoveList::get_move(int moveNum) const {
1715     return moves[moveNum].move;
1716   }
1717
1718   inline Value RootMoveList::get_move_score(int moveNum) const {
1719     return moves[moveNum].score;
1720   }
1721
1722   inline void RootMoveList::set_move_score(int moveNum, Value score) {
1723     moves[moveNum].score = score;
1724   }
1725
1726   inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1727     moves[moveNum].nodes = nodes;
1728     moves[moveNum].cumulativeNodes += nodes;
1729   }
1730
1731   void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1732     int j;
1733     for(j = 0; pv[j] != MOVE_NONE; j++)
1734       moves[moveNum].pv[j] = pv[j];
1735     moves[moveNum].pv[j] = MOVE_NONE;
1736   }
1737
1738   inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1739     return moves[moveNum].pv[i];
1740   }
1741
1742   inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1743     return moves[moveNum].cumulativeNodes;
1744   }
1745
1746   inline int RootMoveList::move_count() const {
1747     return count;
1748   }
1749
1750
1751   // RootMoveList::scan_for_easy_move() is called at the end of the first
1752   // iteration, and is used to detect an "easy move", i.e. a move which appears
1753   // to be much bester than all the rest.  If an easy move is found, the move
1754   // is returned, otherwise the function returns MOVE_NONE.  It is very
1755   // important that this function is called at the right moment:  The code
1756   // assumes that the first iteration has been completed and the moves have
1757   // been sorted. This is done in RootMoveList c'tor.
1758
1759   Move RootMoveList::scan_for_easy_move() const {
1760
1761     assert(count);
1762
1763     if (count == 1)
1764         return get_move(0);
1765
1766     // moves are sorted so just consider the best and the second one
1767     if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1768         return get_move(0);
1769
1770     return MOVE_NONE;
1771   }
1772
1773   // RootMoveList::sort() sorts the root move list at the beginning of a new
1774   // iteration.
1775
1776   inline void RootMoveList::sort() {
1777
1778     sort_multipv(count - 1); // all items
1779   }
1780
1781
1782   // RootMoveList::sort_multipv() sorts the first few moves in the root move
1783   // list by their scores and depths. It is used to order the different PVs
1784   // correctly in MultiPV mode.
1785
1786   void RootMoveList::sort_multipv(int n) {
1787
1788     for (int i = 1; i <= n; i++)
1789     {
1790       RootMove rm = moves[i];
1791       int j;
1792       for (j = i; j > 0 && moves[j-1] < rm; j--)
1793           moves[j] = moves[j-1];
1794       moves[j] = rm;
1795     }
1796   }
1797
1798
1799   // init_search_stack() initializes a search stack at the beginning of a
1800   // new search from the root.
1801
1802   void init_search_stack(SearchStack ss[]) {
1803     for(int i = 0; i < 3; i++) {
1804       ss[i].pv[i] = MOVE_NONE;
1805       ss[i].pv[i+1] = MOVE_NONE;
1806       ss[i].currentMove = MOVE_NONE;
1807       ss[i].mateKiller = MOVE_NONE;
1808       ss[i].killer1 = MOVE_NONE;
1809       ss[i].killer2 = MOVE_NONE;
1810       ss[i].threatMove = MOVE_NONE;
1811       ss[i].reduction = Depth(0);
1812     }
1813   }
1814
1815
1816   // init_node() is called at the beginning of all the search functions
1817   // (search(), search_pv(), qsearch(), and so on) and initializes the search
1818   // stack object corresponding to the current node.  Once every
1819   // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1820   // for user input and checks whether it is time to stop the search.
1821
1822   void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1823     assert(ply >= 0 && ply < PLY_MAX);
1824     assert(threadID >= 0 && threadID < ActiveThreads);
1825
1826     Threads[threadID].nodes++;
1827
1828     if(threadID == 0) {
1829       NodesSincePoll++;
1830       if(NodesSincePoll >= NodesBetweenPolls) {
1831         poll();
1832         NodesSincePoll = 0;
1833       }
1834     }
1835
1836     ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
1837     ss[ply+2].mateKiller = MOVE_NONE;
1838     ss[ply+2].killer1 = ss[ply+2].killer2 = MOVE_NONE;
1839     ss[ply].threatMove = MOVE_NONE;
1840     ss[ply].reduction = Depth(0);
1841     ss[ply].currentMoveCaptureValue = Value(0);
1842
1843     if(Threads[threadID].printCurrentLine)
1844       print_current_line(ss, ply, threadID);
1845   }
1846
1847
1848   // update_pv() is called whenever a search returns a value > alpha.  It
1849   // updates the PV in the SearchStack object corresponding to the current
1850   // node.
1851
1852   void update_pv(SearchStack ss[], int ply) {
1853     assert(ply >= 0 && ply < PLY_MAX);
1854
1855     ss[ply].pv[ply] = ss[ply].currentMove;
1856     int p;
1857     for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1858       ss[ply].pv[p] = ss[ply+1].pv[p];
1859     ss[ply].pv[p] = MOVE_NONE;
1860   }
1861
1862
1863   // sp_update_pv() is a variant of update_pv for use at split points.  The
1864   // difference between the two functions is that sp_update_pv also updates
1865   // the PV at the parent node.
1866
1867   void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
1868     assert(ply >= 0 && ply < PLY_MAX);
1869
1870     ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1871     int p;
1872     for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1873       ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
1874     ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1875   }
1876
1877
1878   // connected_moves() tests whether two moves are 'connected' in the sense
1879   // that the first move somehow made the second move possible (for instance
1880   // if the moving piece is the same in both moves).  The first move is
1881   // assumed to be the move that was made to reach the current position, while
1882   // the second move is assumed to be a move from the current position.
1883
1884   bool connected_moves(const Position &pos, Move m1, Move m2) {
1885     Square f1, t1, f2, t2;
1886
1887     assert(move_is_ok(m1));
1888     assert(move_is_ok(m2));
1889
1890     if(m2 == MOVE_NONE)
1891       return false;
1892
1893     // Case 1: The moving piece is the same in both moves.
1894     f2 = move_from(m2);
1895     t1 = move_to(m1);
1896     if(f2 == t1)
1897       return true;
1898
1899     // Case 2: The destination square for m2 was vacated by m1.
1900     t2 = move_to(m2);
1901     f1 = move_from(m1);
1902     if(t2 == f1)
1903       return true;
1904
1905     // Case 3: Moving through the vacated square:
1906     if(piece_is_slider(pos.piece_on(f2)) &&
1907        bit_is_set(squares_between(f2, t2), f1))
1908       return true;
1909
1910     // Case 4: The destination square for m2 is attacked by the moving piece
1911     // in m1:
1912     if(pos.piece_attacks_square(t1, t2))
1913       return true;
1914
1915     // Case 5: Discovered check, checking piece is the piece moved in m1:
1916     if(piece_is_slider(pos.piece_on(t1)) &&
1917        bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
1918                   f2) &&
1919        !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
1920                    t2)) {
1921       Bitboard occ = pos.occupied_squares();
1922       Color us = pos.side_to_move();
1923       Square ksq = pos.king_square(us);
1924       clear_bit(&occ, f2);
1925       if(pos.type_of_piece_on(t1) == BISHOP) {
1926         if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
1927           return true;
1928       }
1929       else if(pos.type_of_piece_on(t1) == ROOK) {
1930         if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
1931           return true;
1932       }
1933       else {
1934         assert(pos.type_of_piece_on(t1) == QUEEN);
1935         if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
1936           return true;
1937       }
1938     }
1939
1940     return false;
1941   }
1942
1943
1944   // extension() decides whether a move should be searched with normal depth,
1945   // or with extended depth.  Certain classes of moves (checking moves, in
1946   // particular) are searched with bigger depth than ordinary moves.
1947
1948   Depth extension(const Position &pos, Move m, bool pvNode,
1949                   bool check, bool singleReply, bool mateThreat) {
1950     Depth result = Depth(0);
1951
1952     if(check)
1953       result += CheckExtension[pvNode];
1954     if(singleReply)
1955       result += SingleReplyExtension[pvNode];
1956     if(pos.move_is_pawn_push_to_7th(m))
1957       result += PawnPushTo7thExtension[pvNode];
1958     if(pos.move_is_passed_pawn_push(m))
1959       result += PassedPawnExtension[pvNode];
1960     if(mateThreat)
1961       result += MateThreatExtension[pvNode];
1962     if(pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame
1963        && (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
1964            - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
1965        && !move_promotion(m))
1966       result += PawnEndgameExtension[pvNode];
1967     if(pvNode && pos.move_is_capture(m)
1968        && pos.type_of_piece_on(move_to(m)) != PAWN && pos.see(m) >= 0)
1969       result += OnePly/2;
1970
1971     return Min(result, OnePly);
1972   }
1973
1974
1975   // ok_to_do_nullmove() looks at the current position and decides whether
1976   // doing a 'null move' should be allowed.  In order to avoid zugzwang
1977   // problems, null moves are not allowed when the side to move has very
1978   // little material left.  Currently, the test is a bit too simple:  Null
1979   // moves are avoided only when the side to move has only pawns left.  It's
1980   // probably a good idea to avoid null moves in at least some more
1981   // complicated endgames, e.g. KQ vs KR.  FIXME
1982
1983   bool ok_to_do_nullmove(const Position &pos) {
1984     if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
1985       return false;
1986     return true;
1987   }
1988
1989
1990   // ok_to_prune() tests whether it is safe to forward prune a move.  Only
1991   // non-tactical moves late in the move list close to the leaves are
1992   // candidates for pruning.
1993
1994   bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
1995     Square mfrom, mto, tfrom, tto;
1996
1997     assert(move_is_ok(m));
1998     assert(threat == MOVE_NONE || move_is_ok(threat));
1999     assert(!move_promotion(m));
2000     assert(!pos.move_is_check(m));
2001     assert(!pos.move_is_capture(m));
2002     assert(!pos.move_is_passed_pawn_push(m));
2003     assert(d >= OnePly);
2004
2005     mfrom = move_from(m);
2006     mto = move_to(m);
2007     tfrom = move_from(threat);
2008     tto = move_to(threat);
2009
2010     // Case 1: Castling moves are never pruned.
2011     if(move_is_castle(m))
2012       return false;
2013
2014     // Case 2: Don't prune moves which move the threatened piece
2015     if(!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2016       return false;
2017
2018     // Case 3: If the threatened piece has value less than or equal to the
2019     // value of the threatening piece, don't prune move which defend it.
2020     if(!PruneDefendingMoves && threat != MOVE_NONE
2021        && (piece_value_midgame(pos.piece_on(tfrom))
2022            >= piece_value_midgame(pos.piece_on(tto)))
2023        && pos.move_attacks_square(m, tto))
2024       return false;
2025
2026     // Case 4: Don't prune moves with good history.
2027     if(!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2028       return false;
2029
2030     // Case 5: If the moving piece in the threatened move is a slider, don't
2031     // prune safe moves which block its ray.
2032     if(!PruneBlockingMoves && threat != MOVE_NONE
2033        && piece_is_slider(pos.piece_on(tfrom))
2034        && bit_is_set(squares_between(tfrom, tto), mto) && pos.see(m) >= 0)
2035       return false;
2036
2037     return true;
2038   }
2039
2040
2041   // ok_to_use_TT() returns true if a transposition table score
2042   // can be used at a given point in search.
2043
2044   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2045
2046     Value v = value_from_tt(tte->value(), ply);
2047
2048     return   (   tte->depth() >= depth
2049               || v >= Max(value_mate_in(100), beta)
2050               || v < Min(value_mated_in(100), beta))
2051
2052           && (   (is_lower_bound(tte->type()) && v >= beta)
2053               || (is_upper_bound(tte->type()) && v < beta));
2054   }
2055
2056
2057   // ok_to_history() returns true if a move m can be stored
2058   // in history. Should be a non capturing move.
2059
2060   bool ok_to_history(const Position& pos, Move m) {
2061
2062     return    pos.square_is_empty(move_to(m))
2063           && !move_promotion(m)
2064           && !move_is_ep(m);
2065   }
2066
2067
2068   // update_history() registers a good move that produced a beta-cutoff
2069   // in history and marks as failures all the other moves of that ply.
2070
2071   void update_history(const Position& pos, Move m, Depth depth,
2072                       Move movesSearched[], int moveCount) {
2073
2074     H.success(pos.piece_on(move_from(m)), m, depth);
2075
2076     for (int i = 0; i < moveCount - 1; i++)
2077         if (ok_to_history(pos, movesSearched[i]) && m != movesSearched[i])
2078             H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2079   }
2080
2081   // fail_high_ply_1() checks if some thread is currently resolving a fail
2082   // high at ply 1 at the node below the first root node.  This information
2083   // is used for time managment.
2084
2085   bool fail_high_ply_1() {
2086     for(int i = 0; i < ActiveThreads; i++)
2087       if(Threads[i].failHighPly1)
2088         return true;
2089     return false;
2090   }
2091
2092
2093   // current_search_time() returns the number of milliseconds which have passed
2094   // since the beginning of the current search.
2095
2096   int current_search_time() {
2097     return get_system_time() - SearchStartTime;
2098   }
2099
2100
2101   // nps() computes the current nodes/second count.
2102
2103   int nps() {
2104     int t = current_search_time();
2105     return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2106   }
2107
2108
2109   // poll() performs two different functions:  It polls for user input, and it
2110   // looks at the time consumed so far and decides if it's time to abort the
2111   // search.
2112
2113   void poll() {
2114     int t, data;
2115     static int lastInfoTime;
2116
2117     t = current_search_time();
2118
2119     //  Poll for input
2120     data = Bioskey();
2121     if(data) {
2122       char input[256];
2123       if(fgets(input, 255, stdin) == NULL)
2124         strcpy(input, "quit\n");
2125       if(strncmp(input, "quit", 4) == 0) {
2126         AbortSearch = true;
2127         PonderSearch = false;
2128         Quit = true;
2129       }
2130       else if(strncmp(input, "stop", 4) == 0) {
2131         AbortSearch = true;
2132         PonderSearch = false;
2133       }
2134       else if(strncmp(input, "ponderhit", 9) == 0)
2135         ponderhit();
2136     }
2137
2138     // Print search information
2139     if(t < 1000)
2140       lastInfoTime = 0;
2141     else if(lastInfoTime > t)
2142       // HACK: Must be a new search where we searched less than
2143       // NodesBetweenPolls nodes during the first second of search.
2144       lastInfoTime = 0;
2145     else if(t - lastInfoTime >= 1000) {
2146       lastInfoTime = t;
2147       lock_grab(&IOLock);
2148       std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2149                 << " time " << t << " hashfull " << TT.full() << std::endl;
2150       lock_release(&IOLock);
2151       if(ShowCurrentLine)
2152         Threads[0].printCurrentLine = true;
2153     }
2154
2155     // Should we stop the search?
2156     if(!PonderSearch && Iteration >= 2 &&
2157        (!InfiniteSearch && (t > AbsoluteMaxSearchTime ||
2158                             (RootMoveNumber == 1 &&
2159                              t > MaxSearchTime + ExtraSearchTime) ||
2160                             (!FailHigh && !fail_high_ply_1() && !Problem &&
2161                              t > 6*(MaxSearchTime + ExtraSearchTime)))))
2162       AbortSearch = true;
2163
2164     if(!PonderSearch && ExactMaxTime && t >= ExactMaxTime)
2165       AbortSearch = true;
2166
2167     if(!PonderSearch && Iteration >= 3 && MaxNodes
2168        && nodes_searched() >= MaxNodes)
2169       AbortSearch = true;
2170   }
2171
2172
2173   // ponderhit() is called when the program is pondering (i.e. thinking while
2174   // it's the opponent's turn to move) in order to let the engine know that
2175   // it correctly predicted the opponent's move.
2176
2177   void ponderhit() {
2178     int t = current_search_time();
2179     PonderSearch = false;
2180     if(Iteration >= 2 &&
2181        (!InfiniteSearch && (StopOnPonderhit ||
2182                             t > AbsoluteMaxSearchTime ||
2183                             (RootMoveNumber == 1 &&
2184                              t > MaxSearchTime + ExtraSearchTime) ||
2185                             (!FailHigh && !fail_high_ply_1() && !Problem &&
2186                              t > 6*(MaxSearchTime + ExtraSearchTime)))))
2187       AbortSearch = true;
2188   }
2189
2190
2191   // print_current_line() prints the current line of search for a given
2192   // thread.  Called when the UCI option UCI_ShowCurrLine is 'true'.
2193
2194   void print_current_line(SearchStack ss[], int ply, int threadID) {
2195     assert(ply >= 0 && ply < PLY_MAX);
2196     assert(threadID >= 0 && threadID < ActiveThreads);
2197
2198     if(!Threads[threadID].idle) {
2199       lock_grab(&IOLock);
2200       std::cout << "info currline " << (threadID + 1);
2201       for(int p = 0; p < ply; p++)
2202         std::cout << " " << ss[p].currentMove;
2203       std::cout << std::endl;
2204       lock_release(&IOLock);
2205     }
2206     Threads[threadID].printCurrentLine = false;
2207     if(threadID + 1 < ActiveThreads)
2208       Threads[threadID + 1].printCurrentLine = true;
2209   }
2210
2211
2212   // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2213   // while the program is pondering.  The point is to work around a wrinkle in
2214   // the UCI protocol:  When pondering, the engine is not allowed to give a
2215   // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2216   // We simply wait here until one of these commands is sent, and return,
2217   // after which the bestmove and pondermove will be printed (in id_loop()).
2218
2219   void wait_for_stop_or_ponderhit() {
2220     std::string command;
2221
2222     while(true) {
2223       if(!std::getline(std::cin, command))
2224         command = "quit";
2225
2226       if(command == "quit") {
2227         OpeningBook.close();
2228         stop_threads();
2229         quit_eval();
2230         exit(0);
2231       }
2232       else if(command == "ponderhit" || command == "stop")
2233         break;
2234     }
2235   }
2236
2237
2238   // idle_loop() is where the threads are parked when they have no work to do.
2239   // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2240   // object for which the current thread is the master.
2241
2242   void idle_loop(int threadID, SplitPoint *waitSp) {
2243     assert(threadID >= 0 && threadID < THREAD_MAX);
2244
2245     Threads[threadID].running = true;
2246
2247     while(true) {
2248       if(AllThreadsShouldExit && threadID != 0)
2249         break;
2250
2251       // If we are not thinking, wait for a condition to be signaled instead
2252       // of wasting CPU time polling for work:
2253       while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2254 #if !defined(_MSC_VER)
2255         pthread_mutex_lock(&WaitLock);
2256         if(Idle || threadID >= ActiveThreads)
2257           pthread_cond_wait(&WaitCond, &WaitLock);
2258         pthread_mutex_unlock(&WaitLock);
2259 #else
2260         WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2261 #endif
2262       }
2263
2264       // If this thread has been assigned work, launch a search:
2265       if(Threads[threadID].workIsWaiting) {
2266         Threads[threadID].workIsWaiting = false;
2267         if(Threads[threadID].splitPoint->pvNode)
2268           sp_search_pv(Threads[threadID].splitPoint, threadID);
2269         else
2270           sp_search(Threads[threadID].splitPoint, threadID);
2271         Threads[threadID].idle = true;
2272       }
2273
2274       // If this thread is the master of a split point and all threads have
2275       // finished their work at this split point, return from the idle loop:
2276       if(waitSp != NULL && waitSp->cpus == 0)
2277         return;
2278     }
2279
2280     Threads[threadID].running = false;
2281   }
2282
2283
2284   // init_split_point_stack() is called during program initialization, and
2285   // initializes all split point objects.
2286
2287   void init_split_point_stack() {
2288     for(int i = 0; i < THREAD_MAX; i++)
2289       for(int j = 0; j < MaxActiveSplitPoints; j++) {
2290         SplitPointStack[i][j].parent = NULL;
2291         lock_init(&(SplitPointStack[i][j].lock), NULL);
2292       }
2293   }
2294
2295
2296   // destroy_split_point_stack() is called when the program exits, and
2297   // destroys all locks in the precomputed split point objects.
2298
2299   void destroy_split_point_stack() {
2300     for(int i = 0; i < THREAD_MAX; i++)
2301       for(int j = 0; j < MaxActiveSplitPoints; j++)
2302         lock_destroy(&(SplitPointStack[i][j].lock));
2303   }
2304
2305
2306   // thread_should_stop() checks whether the thread with a given threadID has
2307   // been asked to stop, directly or indirectly.  This can happen if a beta
2308   // cutoff has occured in thre thread's currently active split point, or in
2309   // some ancestor of the current split point.
2310
2311   bool thread_should_stop(int threadID) {
2312     assert(threadID >= 0 && threadID < ActiveThreads);
2313
2314     SplitPoint *sp;
2315
2316     if(Threads[threadID].stop)
2317       return true;
2318     if(ActiveThreads <= 2)
2319       return false;
2320     for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2321       if(sp->finished) {
2322         Threads[threadID].stop = true;
2323         return true;
2324       }
2325     return false;
2326   }
2327
2328
2329   // thread_is_available() checks whether the thread with threadID "slave" is
2330   // available to help the thread with threadID "master" at a split point.  An
2331   // obvious requirement is that "slave" must be idle.  With more than two
2332   // threads, this is not by itself sufficient:  If "slave" is the master of
2333   // some active split point, it is only available as a slave to the other
2334   // threads which are busy searching the split point at the top of "slave"'s
2335   // split point stack (the "helpful master concept" in YBWC terminology).
2336
2337   bool thread_is_available(int slave, int master) {
2338     assert(slave >= 0 && slave < ActiveThreads);
2339     assert(master >= 0 && master < ActiveThreads);
2340     assert(ActiveThreads > 1);
2341
2342     if(!Threads[slave].idle || slave == master)
2343       return false;
2344
2345     if(Threads[slave].activeSplitPoints == 0)
2346       // No active split points means that the thread is available as a slave
2347       // for any other thread.
2348       return true;
2349
2350     if(ActiveThreads == 2)
2351       return true;
2352
2353     // Apply the "helpful master" concept if possible.
2354     if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2355       return true;
2356
2357     return false;
2358   }
2359
2360
2361   // idle_thread_exists() tries to find an idle thread which is available as
2362   // a slave for the thread with threadID "master".
2363
2364   bool idle_thread_exists(int master) {
2365     assert(master >= 0 && master < ActiveThreads);
2366     assert(ActiveThreads > 1);
2367
2368     for(int i = 0; i < ActiveThreads; i++)
2369       if(thread_is_available(i, master))
2370         return true;
2371     return false;
2372   }
2373
2374
2375   // split() does the actual work of distributing the work at a node between
2376   // several threads at PV nodes.  If it does not succeed in splitting the
2377   // node (because no idle threads are available, or because we have no unused
2378   // split point objects), the function immediately returns false.  If
2379   // splitting is possible, a SplitPoint object is initialized with all the
2380   // data that must be copied to the helper threads (the current position and
2381   // search stack, alpha, beta, the search depth, etc.), and we tell our
2382   // helper threads that they have been assigned work.  This will cause them
2383   // to instantly leave their idle loops and call sp_search_pv().  When all
2384   // threads have returned from sp_search_pv (or, equivalently, when
2385   // splitPoint->cpus becomes 0), split() returns true.
2386
2387   bool split(const Position &p, SearchStack *sstck, int ply,
2388              Value *alpha, Value *beta, Value *bestValue,
2389              Depth depth, int *moves,
2390              MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2391     assert(p.is_ok());
2392     assert(sstck != NULL);
2393     assert(ply >= 0 && ply < PLY_MAX);
2394     assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2395     assert(!pvNode || *alpha < *beta);
2396     assert(*beta <= VALUE_INFINITE);
2397     assert(depth > Depth(0));
2398     assert(master >= 0 && master < ActiveThreads);
2399     assert(ActiveThreads > 1);
2400
2401     SplitPoint *splitPoint;
2402     int i;
2403
2404     lock_grab(&MPLock);
2405
2406     // If no other thread is available to help us, or if we have too many
2407     // active split points, don't split:
2408     if(!idle_thread_exists(master) ||
2409        Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2410       lock_release(&MPLock);
2411       return false;
2412     }
2413
2414     // Pick the next available split point object from the split point stack:
2415     splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2416     Threads[master].activeSplitPoints++;
2417
2418     // Initialize the split point object:
2419     splitPoint->parent = Threads[master].splitPoint;
2420     splitPoint->finished = false;
2421     splitPoint->ply = ply;
2422     splitPoint->depth = depth;
2423     splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2424     splitPoint->beta = *beta;
2425     splitPoint->pvNode = pvNode;
2426     splitPoint->dcCandidates = dcCandidates;
2427     splitPoint->bestValue = *bestValue;
2428     splitPoint->master = master;
2429     splitPoint->mp = mp;
2430     splitPoint->moves = *moves;
2431     splitPoint->cpus = 1;
2432     splitPoint->pos.copy(p);
2433     splitPoint->parentSstack = sstck;
2434     for(i = 0; i < ActiveThreads; i++)
2435       splitPoint->slaves[i] = 0;
2436
2437     // Copy the current position and the search stack to the master thread:
2438     memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2439     Threads[master].splitPoint = splitPoint;
2440
2441     // Make copies of the current position and search stack for each thread:
2442     for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2443         i++)
2444       if(thread_is_available(i, master)) {
2445         memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2446         Threads[i].splitPoint = splitPoint;
2447         splitPoint->slaves[i] = 1;
2448         splitPoint->cpus++;
2449       }
2450
2451     // Tell the threads that they have work to do.  This will make them leave
2452     // their idle loop.
2453     for(i = 0; i < ActiveThreads; i++)
2454       if(i == master || splitPoint->slaves[i]) {
2455         Threads[i].workIsWaiting = true;
2456         Threads[i].idle = false;
2457         Threads[i].stop = false;
2458       }
2459
2460     lock_release(&MPLock);
2461
2462     // Everything is set up.  The master thread enters the idle loop, from
2463     // which it will instantly launch a search, because its workIsWaiting
2464     // slot is 'true'.  We send the split point as a second parameter to the
2465     // idle loop, which means that the main thread will return from the idle
2466     // loop when all threads have finished their work at this split point
2467     // (i.e. when // splitPoint->cpus == 0).
2468     idle_loop(master, splitPoint);
2469
2470     // We have returned from the idle loop, which means that all threads are
2471     // finished.  Update alpha, beta and bestvalue, and return:
2472     lock_grab(&MPLock);
2473     if(pvNode) *alpha = splitPoint->alpha;
2474     *beta = splitPoint->beta;
2475     *bestValue = splitPoint->bestValue;
2476     Threads[master].stop = false;
2477     Threads[master].idle = false;
2478     Threads[master].activeSplitPoints--;
2479     Threads[master].splitPoint = splitPoint->parent;
2480     lock_release(&MPLock);
2481
2482     return true;
2483   }
2484
2485
2486   // wake_sleeping_threads() wakes up all sleeping threads when it is time
2487   // to start a new search from the root.
2488
2489   void wake_sleeping_threads() {
2490     if(ActiveThreads > 1) {
2491       for(int i = 1; i < ActiveThreads; i++) {
2492         Threads[i].idle = true;
2493         Threads[i].workIsWaiting = false;
2494       }
2495 #if !defined(_MSC_VER)
2496       pthread_mutex_lock(&WaitLock);
2497       pthread_cond_broadcast(&WaitCond);
2498       pthread_mutex_unlock(&WaitLock);
2499 #else
2500       for(int i = 1; i < THREAD_MAX; i++)
2501         SetEvent(SitIdleEvent[i]);
2502 #endif
2503     }
2504   }
2505
2506
2507   // init_thread() is the function which is called when a new thread is
2508   // launched.  It simply calls the idle_loop() function with the supplied
2509   // threadID.  There are two versions of this function; one for POSIX threads
2510   // and one for Windows threads.
2511
2512 #if !defined(_MSC_VER)
2513
2514   void *init_thread(void *threadID) {
2515     idle_loop(*(int *)threadID, NULL);
2516     return NULL;
2517   }
2518
2519 #else
2520
2521   DWORD WINAPI init_thread(LPVOID threadID) {
2522     idle_loop(*(int *)threadID, NULL);
2523     return NULL;
2524   }
2525
2526 #endif
2527
2528 }