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