]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Fix an assert in SMP case
[stockfish] / src / movepick.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-2013 Marco Costalba, Joona Kiiski, Tord Romstad
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
12   Stockfish is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <cassert>
22
23 #include "movepick.h"
24 #include "thread.h"
25
26 namespace {
27
28   enum Stages {
29     MAIN_SEARCH, CAPTURES_S1, KILLERS_S1, QUIETS_1_S1, QUIETS_2_S1, BAD_CAPTURES_S1,
30     EVASION,     EVASIONS_S2,
31     QSEARCH_0,   CAPTURES_S3, QUIET_CHECKS_S3,
32     QSEARCH_1,   CAPTURES_S4,
33     PROBCUT,     CAPTURES_S5,
34     RECAPTURE,   CAPTURES_S6,
35     STOP
36   };
37
38   // Our insertion sort, guaranteed to be stable, as is needed
39   void insertion_sort(ExtMove* begin, ExtMove* end)
40   {
41     ExtMove tmp, *p, *q;
42
43     for (p = begin + 1; p < end; ++p)
44     {
45         tmp = *p;
46         for (q = p; q != begin && *(q-1) < tmp; --q)
47             *q = *(q-1);
48         *q = tmp;
49     }
50   }
51
52   // Unary predicate used by std::partition to split positive scores from remaining
53   // ones so to sort separately the two sets, and with the second sort delayed.
54   inline bool has_positive_score(const ExtMove& ms) { return ms.score > 0; }
55
56   // Picks and moves to the front the best move in the range [begin, end),
57   // it is faster than sorting all the moves in advance when moves are few, as
58   // normally are the possible captures.
59   inline ExtMove* pick_best(ExtMove* begin, ExtMove* end)
60   {
61       std::swap(*begin, *std::max_element(begin, end));
62       return begin;
63   }
64 }
65
66
67 /// Constructors of the MovePicker class. As arguments we pass information
68 /// to help it to return the presumably good moves first, to decide which
69 /// moves to return (in the quiescence search, for instance, we only want to
70 /// search captures, promotions and some checks) and about how important good
71 /// move ordering is at the current node.
72
73 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const HistoryStats& h,
74                        Move* cm, Search::Stack* s) : pos(p), history(h), depth(d) {
75
76   assert(d > DEPTH_ZERO);
77
78   cur = end = moves;
79   endBadCaptures = moves + MAX_MOVES - 1;
80   countermoves = cm;
81   ss = s;
82
83   if (p.checkers())
84       stage = EVASION;
85
86   else
87       stage = MAIN_SEARCH;
88
89   ttMove = (ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE);
90   end += (ttMove != MOVE_NONE);
91 }
92
93 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const HistoryStats& h,
94                        Square sq) : pos(p), history(h), cur(moves), end(moves) {
95
96   assert(d <= DEPTH_ZERO);
97
98   if (p.checkers())
99       stage = EVASION;
100
101   else if (d > DEPTH_QS_NO_CHECKS)
102       stage = QSEARCH_0;
103
104   else if (d > DEPTH_QS_RECAPTURES)
105   {
106       stage = QSEARCH_1;
107
108       // Skip TT move if is not a capture or a promotion, this avoids qsearch
109       // tree explosion due to a possible perpetual check or similar rare cases
110       // when TT table is full.
111       if (ttm && !pos.capture_or_promotion(ttm))
112           ttm = MOVE_NONE;
113   }
114   else
115   {
116       stage = RECAPTURE;
117       recaptureSquare = sq;
118       ttm = MOVE_NONE;
119   }
120
121   ttMove = (ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE);
122   end += (ttMove != MOVE_NONE);
123 }
124
125 MovePicker::MovePicker(const Position& p, Move ttm, const HistoryStats& h, PieceType pt)
126                        : pos(p), history(h), cur(moves), end(moves) {
127
128   assert(!pos.checkers());
129
130   stage = PROBCUT;
131
132   // In ProbCut we generate only captures better than parent's captured piece
133   captureThreshold = PieceValue[MG][pt];
134   ttMove = (ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE);
135
136   if (ttMove && (!pos.capture(ttMove) || pos.see(ttMove) <= captureThreshold))
137       ttMove = MOVE_NONE;
138
139   end += (ttMove != MOVE_NONE);
140 }
141
142
143 /// quiet_moves() returns a pointer to the beginning of moves array. It
144 /// is used to access already tried quiet moves when updating history.
145
146 const ExtMove* MovePicker::quiet_moves() const {
147   return  stage == KILLERS_S1 ? killers
148         : stage == QUIETS_1_S1 || stage == QUIETS_2_S1 ? moves : NULL;
149 }
150
151
152 /// score() assign a numerical move ordering score to each move in a move list.
153 /// The moves with highest scores will be picked first.
154 template<>
155 void MovePicker::score<CAPTURES>() {
156   // Winning and equal captures in the main search are ordered by MVV/LVA.
157   // Suprisingly, this appears to perform slightly better than SEE based
158   // move ordering. The reason is probably that in a position with a winning
159   // capture, capturing a more valuable (but sufficiently defended) piece
160   // first usually doesn't hurt. The opponent will have to recapture, and
161   // the hanging piece will still be hanging (except in the unusual cases
162   // where it is possible to recapture with the hanging piece). Exchanging
163   // big pieces before capturing a hanging piece probably helps to reduce
164   // the subtree size.
165   // In main search we want to push captures with negative SEE values to
166   // badCaptures[] array, but instead of doing it now we delay till when
167   // the move has been picked up in pick_move_from_list(), this way we save
168   // some SEE calls in case we get a cutoff (idea from Pablo Vazquez).
169   Move m;
170
171   for (ExtMove* it = moves; it != end; ++it)
172   {
173       m = it->move;
174       it->score =  PieceValue[MG][pos.piece_on(to_sq(m))]
175                  - type_of(pos.moved_piece(m));
176
177       if (type_of(m) == PROMOTION)
178           it->score += PieceValue[MG][promotion_type(m)] - PieceValue[MG][PAWN];
179
180       else if (type_of(m) == ENPASSANT)
181           it->score += PieceValue[MG][PAWN];
182   }
183 }
184
185 template<>
186 void MovePicker::score<QUIETS>() {
187
188   Move m;
189
190   for (ExtMove* it = moves; it != end; ++it)
191   {
192       m = it->move;
193       it->score = history[pos.moved_piece(m)][to_sq(m)];
194   }
195 }
196
197 template<>
198 void MovePicker::score<EVASIONS>() {
199   // Try good captures ordered by MVV/LVA, then non-captures if destination square
200   // is not under attack, ordered by history value, then bad-captures and quiet
201   // moves with a negative SEE. This last group is ordered by the SEE score.
202   Move m;
203   int seeScore;
204
205   for (ExtMove* it = moves; it != end; ++it)
206   {
207       m = it->move;
208       if ((seeScore = pos.see_sign(m)) < 0)
209           it->score = seeScore - HistoryStats::Max; // At the bottom
210
211       else if (pos.capture(m))
212           it->score =  PieceValue[MG][pos.piece_on(to_sq(m))]
213                      - type_of(pos.moved_piece(m)) + HistoryStats::Max;
214       else
215           it->score = history[pos.moved_piece(m)][to_sq(m)];
216   }
217 }
218
219
220 /// generate_next() generates, scores and sorts the next bunch of moves, when
221 /// there are no more moves to try for the current phase.
222
223 void MovePicker::generate_next() {
224
225   cur = moves;
226
227   switch (++stage) {
228
229   case CAPTURES_S1: case CAPTURES_S3: case CAPTURES_S4: case CAPTURES_S5: case CAPTURES_S6:
230       end = generate<CAPTURES>(pos, moves);
231       score<CAPTURES>();
232       return;
233
234   case KILLERS_S1:
235       cur = killers;
236       end = cur + 2;
237
238       killers[0].move = ss->killers[0];
239       killers[1].move = ss->killers[1];
240       killers[2].move = killers[3].move = MOVE_NONE;
241
242       // Be sure countermoves are different from killers
243       for (int i = 0; i < 2; ++i)
244           if (countermoves[i] != cur->move && countermoves[i] != (cur+1)->move)
245               (end++)->move = countermoves[i];
246
247       if (countermoves[1] && countermoves[1] == countermoves[0]) // Due to SMP races
248           killers[3].move = MOVE_NONE;
249
250       return;
251
252   case QUIETS_1_S1:
253       endQuiets = end = generate<QUIETS>(pos, moves);
254       score<QUIETS>();
255       end = std::partition(cur, end, has_positive_score);
256       insertion_sort(cur, end);
257       return;
258
259   case QUIETS_2_S1:
260       cur = end;
261       end = endQuiets;
262       if (depth >= 3 * ONE_PLY)
263           insertion_sort(cur, end);
264       return;
265
266   case BAD_CAPTURES_S1:
267       // Just pick them in reverse order to get MVV/LVA ordering
268       cur = moves + MAX_MOVES - 1;
269       end = endBadCaptures;
270       return;
271
272   case EVASIONS_S2:
273       end = generate<EVASIONS>(pos, moves);
274       if (end > moves + 1)
275           score<EVASIONS>();
276       return;
277
278   case QUIET_CHECKS_S3:
279       end = generate<QUIET_CHECKS>(pos, moves);
280       return;
281
282   case EVASION: case QSEARCH_0: case QSEARCH_1: case PROBCUT: case RECAPTURE:
283       stage = STOP;
284   case STOP:
285       end = cur + 1; // Avoid another next_phase() call
286       return;
287
288   default:
289       assert(false);
290   }
291 }
292
293
294 /// next_move() is the most important method of the MovePicker class. It returns
295 /// a new pseudo legal move every time is called, until there are no more moves
296 /// left. It picks the move with the biggest score from a list of generated moves
297 /// taking care not returning the ttMove if has already been searched previously.
298 template<>
299 Move MovePicker::next_move<false>() {
300
301   Move move;
302
303   while (true)
304   {
305       while (cur == end)
306           generate_next();
307
308       switch (stage) {
309
310       case MAIN_SEARCH: case EVASION: case QSEARCH_0: case QSEARCH_1: case PROBCUT:
311           ++cur;
312           return ttMove;
313
314       case CAPTURES_S1:
315           move = pick_best(cur++, end)->move;
316           if (move != ttMove)
317           {
318               if (pos.see_sign(move) >= 0)
319                   return move;
320
321               // Losing capture, move it to the tail of the array
322               (endBadCaptures--)->move = move;
323           }
324           break;
325
326       case KILLERS_S1:
327           move = (cur++)->move;
328           if (    move != MOVE_NONE
329               &&  pos.pseudo_legal(move)
330               &&  move != ttMove
331               && !pos.capture(move))
332               return move;
333           break;
334
335       case QUIETS_1_S1: case QUIETS_2_S1:
336           move = (cur++)->move;
337           if (   move != ttMove
338               && move != killers[0].move
339               && move != killers[1].move
340               && move != killers[2].move
341               && move != killers[3].move)
342               return move;
343           break;
344
345       case BAD_CAPTURES_S1:
346           return (cur--)->move;
347
348       case EVASIONS_S2: case CAPTURES_S3: case CAPTURES_S4:
349           move = pick_best(cur++, end)->move;
350           if (move != ttMove)
351               return move;
352           break;
353
354       case CAPTURES_S5:
355            move = pick_best(cur++, end)->move;
356            if (move != ttMove && pos.see(move) > captureThreshold)
357                return move;
358            break;
359
360       case CAPTURES_S6:
361           move = pick_best(cur++, end)->move;
362           if (to_sq(move) == recaptureSquare)
363               return move;
364           break;
365
366       case QUIET_CHECKS_S3:
367           move = (cur++)->move;
368           if (move != ttMove)
369               return move;
370           break;
371
372       case STOP:
373           return MOVE_NONE;
374
375       default:
376           assert(false);
377       }
378   }
379 }
380
381
382 /// Version of next_move() to use at split point nodes where the move is grabbed
383 /// from the split point's shared MovePicker object. This function is not thread
384 /// safe so must be lock protected by the caller.
385 template<>
386 Move MovePicker::next_move<true>() { return ss->splitPoint->movePicker->next_move<false>(); }