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