]> git.sesse.net Git - stockfish/blob - src/movegen.cpp
Simplify and micro-optimize hidden_checkers()
[stockfish] / src / movegen.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-2010 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   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 #include <cassert>
21
22 #include "bitcount.h"
23 #include "movegen.h"
24
25 // Simple macro to wrap a very common while loop, no facny, no flexibility,
26 // hardcoded list name 'mlist' and from square 'from'.
27 #define SERIALIZE_MOVES(b) while (b) (*mlist++).move = make_move(from, pop_1st_bit(&b))
28
29 // Version used for pawns, where the 'from' square is given as a delta from the 'to' square
30 #define SERIALIZE_MOVES_D(b, d) while (b) { to = pop_1st_bit(&b); (*mlist++).move = make_move(to + (d), to); }
31
32 namespace {
33
34   enum CastlingSide {
35     KING_SIDE,
36     QUEEN_SIDE
37   };
38
39   template<CastlingSide>
40   MoveStack* generate_castle_moves(const Position&, MoveStack*, Color us);
41
42   template<Color, MoveType>
43   MoveStack* generate_pawn_moves(const Position&, MoveStack*, Bitboard, Square);
44
45   template<PieceType Pt>
46   inline MoveStack* generate_discovered_checks(const Position& pos, MoveStack* mlist, Square from) {
47
48     assert(Pt != QUEEN);
49     assert(Pt != PAWN);
50
51     Bitboard b = pos.attacks_from<Pt>(from) & pos.empty_squares();
52
53     if (Pt == KING)
54         b &= ~QueenPseudoAttacks[pos.king_square(opposite_color(pos.side_to_move()))];
55
56     SERIALIZE_MOVES(b);
57     return mlist;
58   }
59
60   template<PieceType Pt>
61   inline MoveStack* generate_direct_checks(const Position& pos, MoveStack* mlist, Color us,
62                                            Bitboard dc, Square ksq) {
63     assert(Pt != KING);
64     assert(Pt != PAWN);
65
66     Bitboard checkSqs, b;
67     Square from;
68     const Square* pl = pos.piece_list(us, Pt);
69
70     if ((from = *pl++) == SQ_NONE)
71         return mlist;
72
73     checkSqs = pos.attacks_from<Pt>(ksq) & pos.empty_squares();
74
75     do
76     {
77         if (   (Pt == QUEEN  && !(QueenPseudoAttacks[from]  & checkSqs))
78             || (Pt == ROOK   && !(RookPseudoAttacks[from]   & checkSqs))
79             || (Pt == BISHOP && !(BishopPseudoAttacks[from] & checkSqs)))
80             continue;
81
82         if (dc && bit_is_set(dc, from))
83             continue;
84
85         b = pos.attacks_from<Pt>(from) & checkSqs;
86         SERIALIZE_MOVES(b);
87
88     } while ((from = *pl++) != SQ_NONE);
89
90     return mlist;
91   }
92
93   template<>
94   FORCE_INLINE MoveStack* generate_direct_checks<PAWN>(const Position& p, MoveStack* m, Color us, Bitboard dc, Square ksq) {
95
96     return (us == WHITE ? generate_pawn_moves<WHITE, MV_CHECK>(p, m, dc, ksq)
97                         : generate_pawn_moves<BLACK, MV_CHECK>(p, m, dc, ksq));
98   }
99
100   template<PieceType Pt, MoveType Type>
101   FORCE_INLINE MoveStack* generate_piece_moves(const Position& p, MoveStack* m, Color us, Bitboard t) {
102
103     assert(Pt == PAWN);
104     assert(Type == MV_CAPTURE || Type == MV_NON_CAPTURE || Type == MV_EVASION);
105
106     return (us == WHITE ? generate_pawn_moves<WHITE, Type>(p, m, t, SQ_NONE)
107                         : generate_pawn_moves<BLACK, Type>(p, m, t, SQ_NONE));
108   }
109
110   template<PieceType Pt>
111   FORCE_INLINE MoveStack* generate_piece_moves(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
112
113     Bitboard b;
114     Square from;
115     const Square* pl = pos.piece_list(us, Pt);
116
117     if (*pl != SQ_NONE)
118     {
119         do {
120             from = *pl;
121             b = pos.attacks_from<Pt>(from) & target;
122             SERIALIZE_MOVES(b);
123         } while (*++pl != SQ_NONE);
124     }
125     return mlist;
126   }
127
128   template<>
129   FORCE_INLINE MoveStack* generate_piece_moves<KING>(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
130
131     Bitboard b;
132     Square from = pos.king_square(us);
133
134     b = pos.attacks_from<KING>(from) & target;
135     SERIALIZE_MOVES(b);
136     return mlist;
137   }
138
139 }
140
141
142 /// generate<MV_CAPTURE> generates all pseudo-legal captures and queen
143 /// promotions. Returns a pointer to the end of the move list.
144 ///
145 /// generate<MV_NON_CAPTURE> generates all pseudo-legal non-captures and
146 /// underpromotions. Returns a pointer to the end of the move list.
147 ///
148 /// generate<MV_NON_EVASION> generates all pseudo-legal captures and
149 /// non-captures. Returns a pointer to the end of the move list.
150
151 template<MoveType Type>
152 MoveStack* generate(const Position& pos, MoveStack* mlist) {
153
154   assert(pos.is_ok());
155   assert(!pos.in_check());
156
157   Color us = pos.side_to_move();
158   Bitboard target;
159
160   if (Type == MV_CAPTURE || Type == MV_NON_EVASION)
161       target = pos.pieces(opposite_color(us));
162   else if (Type == MV_NON_CAPTURE)
163       target = pos.empty_squares();
164   else
165       assert(false);
166
167   if (Type == MV_NON_EVASION)
168   {
169       mlist = generate_piece_moves<PAWN, MV_CAPTURE>(pos, mlist, us, target);
170       mlist = generate_piece_moves<PAWN, MV_NON_CAPTURE>(pos, mlist, us, pos.empty_squares());
171       target |= pos.empty_squares();
172   }
173   else
174       mlist = generate_piece_moves<PAWN, Type>(pos, mlist, us, target);
175
176   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
177   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
178   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
179   mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
180   mlist = generate_piece_moves<KING>(pos, mlist, us, target);
181
182   if (Type != MV_CAPTURE && pos.can_castle(us))
183   {
184       if (pos.can_castle(us == WHITE ? WHITE_OO : BLACK_OO))
185           mlist = generate_castle_moves<KING_SIDE>(pos, mlist, us);
186
187       if (pos.can_castle(us == WHITE ? WHITE_OOO : BLACK_OOO))
188           mlist = generate_castle_moves<QUEEN_SIDE>(pos, mlist, us);
189   }
190
191   return mlist;
192 }
193
194 // Explicit template instantiations
195 template MoveStack* generate<MV_CAPTURE>(const Position& pos, MoveStack* mlist);
196 template MoveStack* generate<MV_NON_CAPTURE>(const Position& pos, MoveStack* mlist);
197 template MoveStack* generate<MV_NON_EVASION>(const Position& pos, MoveStack* mlist);
198
199
200 /// generate_non_capture_checks() generates all pseudo-legal non-captures and knight
201 /// underpromotions that give check. Returns a pointer to the end of the move list.
202 template<>
203 MoveStack* generate<MV_NON_CAPTURE_CHECK>(const Position& pos, MoveStack* mlist) {
204
205   assert(pos.is_ok());
206   assert(!pos.in_check());
207
208   Bitboard b, dc;
209   Square from;
210   Color us = pos.side_to_move();
211   Square ksq = pos.king_square(opposite_color(us));
212
213   assert(pos.piece_on(ksq) == make_piece(opposite_color(us), KING));
214
215   // Discovered non-capture checks
216   b = dc = pos.discovered_check_candidates(us);
217
218   while (b)
219   {
220      from = pop_1st_bit(&b);
221      switch (piece_type(pos.piece_on(from)))
222      {
223       case PAWN:   /* Will be generated togheter with pawns direct checks */     break;
224       case KNIGHT: mlist = generate_discovered_checks<KNIGHT>(pos, mlist, from); break;
225       case BISHOP: mlist = generate_discovered_checks<BISHOP>(pos, mlist, from); break;
226       case ROOK:   mlist = generate_discovered_checks<ROOK>(pos, mlist, from);   break;
227       case KING:   mlist = generate_discovered_checks<KING>(pos, mlist, from);   break;
228       default: assert(false); break;
229      }
230   }
231
232   // Direct non-capture checks
233   mlist = generate_direct_checks<PAWN>(pos, mlist, us, dc, ksq);
234   mlist = generate_direct_checks<KNIGHT>(pos, mlist, us, dc, ksq);
235   mlist = generate_direct_checks<BISHOP>(pos, mlist, us, dc, ksq);
236   mlist = generate_direct_checks<ROOK>(pos, mlist, us, dc, ksq);
237   return  generate_direct_checks<QUEEN>(pos, mlist, us, dc, ksq);
238 }
239
240
241 /// generate_evasions() generates all pseudo-legal check evasions when
242 /// the side to move is in check. Returns a pointer to the end of the move list.
243 template<>
244 MoveStack* generate<MV_EVASION>(const Position& pos, MoveStack* mlist) {
245
246   assert(pos.is_ok());
247   assert(pos.in_check());
248
249   Bitboard b, target;
250   Square from, checksq;
251   int checkersCnt = 0;
252   Color us = pos.side_to_move();
253   Square ksq = pos.king_square(us);
254   Bitboard checkers = pos.checkers();
255   Bitboard sliderAttacks = EmptyBoardBB;
256
257   assert(pos.piece_on(ksq) == make_piece(us, KING));
258   assert(checkers);
259
260   // Find squares attacked by slider checkers, we will remove
261   // them from the king evasions set so to early skip known
262   // illegal moves and avoid an useless legality check later.
263   b = checkers;
264   do
265   {
266       checkersCnt++;
267       checksq = pop_1st_bit(&b);
268
269       assert(piece_color(pos.piece_on(checksq)) == opposite_color(us));
270
271       switch (piece_type(pos.piece_on(checksq)))
272       {
273       case BISHOP: sliderAttacks |= BishopPseudoAttacks[checksq]; break;
274       case ROOK:   sliderAttacks |= RookPseudoAttacks[checksq];   break;
275       case QUEEN:
276           // If queen and king are far we can safely remove all the squares attacked
277           // in the other direction becuase are not reachable by the king anyway.
278           if (squares_between(ksq, checksq) || (RookPseudoAttacks[checksq] & (1ULL << ksq)))
279               sliderAttacks |= QueenPseudoAttacks[checksq];
280
281           // Otherwise, if king and queen are adjacent and on a diagonal line, we need to
282           // use real rook attacks to check if king is safe to move in the other direction.
283           // For example: king in B2, queen in A1 a knight in B1, and we can safely move to C1.
284           else
285               sliderAttacks |= BishopPseudoAttacks[checksq] | pos.attacks_from<ROOK>(checksq);
286
287       default:
288           break;
289       }
290   } while (b);
291
292   // Generate evasions for king, capture and non capture moves
293   b = pos.attacks_from<KING>(ksq) & ~pos.pieces(us) & ~sliderAttacks;
294   from = ksq;
295   SERIALIZE_MOVES(b);
296
297   // Generate evasions for other pieces only if not double check
298   if (checkersCnt > 1)
299       return mlist;
300
301   // Find squares where a blocking evasion or a capture of the
302   // checker piece is possible.
303   target = squares_between(checksq, ksq) | checkers;
304
305   mlist = generate_piece_moves<PAWN, MV_EVASION>(pos, mlist, us, target);
306   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
307   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
308   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
309   return  generate_piece_moves<QUEEN>(pos, mlist, us, target);
310 }
311
312
313 /// generate<MV_LEGAL> computes a complete list of legal moves in the current position
314
315 template<>
316 MoveStack* generate<MV_LEGAL>(const Position& pos, MoveStack* mlist) {
317
318   assert(pos.is_ok());
319
320   MoveStack *last, *cur = mlist;
321   Bitboard pinned = pos.pinned_pieces(pos.side_to_move());
322
323   last = pos.in_check() ? generate<MV_EVASION>(pos, mlist)
324                         : generate<MV_NON_EVASION>(pos, mlist);
325
326   // Remove illegal moves from the list
327   while (cur != last)
328       if (!pos.pl_move_is_legal(cur->move, pinned))
329           cur->move = (--last)->move;
330       else
331           cur++;
332
333   return last;
334 }
335
336
337 namespace {
338
339   template<Square Delta>
340   inline Bitboard move_pawns(Bitboard p) {
341
342     return Delta == DELTA_N  ? p << 8 : Delta == DELTA_S  ? p >> 8 :
343            Delta == DELTA_NE ? p << 9 : Delta == DELTA_SE ? p >> 7 :
344            Delta == DELTA_NW ? p << 7 : Delta == DELTA_SW ? p >> 9 : p;
345   }
346
347   template<MoveType Type, Square Delta>
348   inline MoveStack* generate_pawn_captures(MoveStack* mlist, Bitboard pawns, Bitboard target) {
349
350     const Bitboard TFileABB = (Delta == DELTA_NE || Delta == DELTA_SE ? FileABB : FileHBB);
351
352     Bitboard b;
353     Square to;
354
355     // Captures in the a1-h8 (a8-h1 for black) diagonal or in the h1-a8 (h8-a1 for black)
356     b = move_pawns<Delta>(pawns) & target & ~TFileABB;
357     SERIALIZE_MOVES_D(b, -Delta);
358     return mlist;
359   }
360
361   template<MoveType Type, Square Delta>
362   inline MoveStack* generate_promotions(const Position& pos, MoveStack* mlist, Bitboard pawnsOn7, Bitboard target) {
363
364     const Bitboard TFileABB = (Delta == DELTA_NE || Delta == DELTA_SE ? FileABB : FileHBB);
365
366     Bitboard b;
367     Square to;
368
369     // Promotions and under-promotions, both captures and non-captures
370     b = move_pawns<Delta>(pawnsOn7) & target;
371
372     if (Delta != DELTA_N && Delta != DELTA_S)
373         b &= ~TFileABB;
374
375     while (b)
376     {
377         to = pop_1st_bit(&b);
378
379         if (Type == MV_CAPTURE || Type == MV_EVASION)
380             (*mlist++).move = make_promotion_move(to - Delta, to, QUEEN);
381
382         if (Type == MV_NON_CAPTURE || Type == MV_EVASION)
383         {
384             (*mlist++).move = make_promotion_move(to - Delta, to, ROOK);
385             (*mlist++).move = make_promotion_move(to - Delta, to, BISHOP);
386             (*mlist++).move = make_promotion_move(to - Delta, to, KNIGHT);
387         }
388
389         // This is the only possible under promotion that can give a check
390         // not already included in the queen-promotion.
391         if (   Type == MV_CHECK
392             && bit_is_set(pos.attacks_from<KNIGHT>(to), pos.king_square(Delta > 0 ? BLACK : WHITE)))
393             (*mlist++).move = make_promotion_move(to - Delta, to, KNIGHT);
394         else (void)pos; // Silence a warning under MSVC
395     }
396     return mlist;
397   }
398
399   template<Color Us, MoveType Type>
400   MoveStack* generate_pawn_moves(const Position& pos, MoveStack* mlist, Bitboard target, Square ksq) {
401
402     // Calculate our parametrized parameters at compile time, named
403     // according to the point of view of white side.
404     const Color    Them      = (Us == WHITE ? BLACK    : WHITE);
405     const Bitboard TRank7BB  = (Us == WHITE ? Rank7BB  : Rank2BB);
406     const Bitboard TRank3BB  = (Us == WHITE ? Rank3BB  : Rank6BB);
407     const Square   UP        = (Us == WHITE ? DELTA_N  : DELTA_S);
408     const Square   RIGHT_UP  = (Us == WHITE ? DELTA_NE : DELTA_SW);
409     const Square   LEFT_UP   = (Us == WHITE ? DELTA_NW : DELTA_SE);
410
411     Square to;
412     Bitboard b1, b2, dc1, dc2, pawnPushes, emptySquares;
413     Bitboard pawns = pos.pieces(PAWN, Us);
414     Bitboard pawnsOn7 = pawns & TRank7BB;
415     Bitboard enemyPieces = (Type == MV_CAPTURE ? target : pos.pieces(Them));
416
417     // Pre-calculate pawn pushes before changing emptySquares definition
418     if (Type != MV_CAPTURE)
419     {
420         emptySquares = (Type == MV_NON_CAPTURE ? target : pos.empty_squares());
421         pawnPushes = move_pawns<UP>(pawns & ~TRank7BB) & emptySquares;
422     }
423
424     if (Type == MV_EVASION)
425     {
426         emptySquares &= target; // Only blocking squares
427         enemyPieces  &= target; // Capture only the checker piece
428     }
429
430     // Promotions and underpromotions
431     if (pawnsOn7)
432     {
433         if (Type == MV_CAPTURE)
434             emptySquares = pos.empty_squares();
435
436         pawns &= ~TRank7BB;
437         mlist = generate_promotions<Type, RIGHT_UP>(pos, mlist, pawnsOn7, enemyPieces);
438         mlist = generate_promotions<Type, LEFT_UP>(pos, mlist, pawnsOn7, enemyPieces);
439         mlist = generate_promotions<Type, UP>(pos, mlist, pawnsOn7, emptySquares);
440     }
441
442     // Standard captures
443     if (Type == MV_CAPTURE || Type == MV_EVASION)
444     {
445         mlist = generate_pawn_captures<Type, RIGHT_UP>(mlist, pawns, enemyPieces);
446         mlist = generate_pawn_captures<Type, LEFT_UP>(mlist, pawns, enemyPieces);
447     }
448
449     // Single and double pawn pushes
450     if (Type != MV_CAPTURE)
451     {
452         b1 = (Type != MV_EVASION ? pawnPushes : pawnPushes & emptySquares);
453         b2 = move_pawns<UP>(pawnPushes & TRank3BB) & emptySquares;
454
455         if (Type == MV_CHECK)
456         {
457             // Consider only pawn moves which give direct checks
458             b1 &= pos.attacks_from<PAWN>(ksq, Them);
459             b2 &= pos.attacks_from<PAWN>(ksq, Them);
460
461             // Add pawn moves which gives discovered check. This is possible only
462             // if the pawn is not on the same file as the enemy king, because we
463             // don't generate captures.
464             if (pawns & target) // For CHECK type target is dc bitboard
465             {
466                 dc1 = move_pawns<UP>(pawns & target & ~file_bb(ksq)) & emptySquares;
467                 dc2 = move_pawns<UP>(dc1 & TRank3BB) & emptySquares;
468
469                 b1 |= dc1;
470                 b2 |= dc2;
471             }
472         }
473         SERIALIZE_MOVES_D(b1, -UP);
474         SERIALIZE_MOVES_D(b2, -UP -UP);
475     }
476
477     // En passant captures
478     if ((Type == MV_CAPTURE || Type == MV_EVASION) && pos.ep_square() != SQ_NONE)
479     {
480         assert(Us != WHITE || square_rank(pos.ep_square()) == RANK_6);
481         assert(Us != BLACK || square_rank(pos.ep_square()) == RANK_3);
482
483         // An en passant capture can be an evasion only if the checking piece
484         // is the double pushed pawn and so is in the target. Otherwise this
485         // is a discovery check and we are forced to do otherwise.
486         if (Type == MV_EVASION && !bit_is_set(target, pos.ep_square() - UP))
487             return mlist;
488
489         b1 = pawns & pos.attacks_from<PAWN>(pos.ep_square(), Them);
490
491         assert(b1 != EmptyBoardBB);
492
493         while (b1)
494         {
495             to = pop_1st_bit(&b1);
496             (*mlist++).move = make_ep_move(to, pos.ep_square());
497         }
498     }
499     return mlist;
500   }
501
502   template<CastlingSide Side>
503   MoveStack* generate_castle_moves(const Position& pos, MoveStack* mlist, Color us) {
504
505     CastleRight f = CastleRight((Side == KING_SIDE ? WHITE_OO : WHITE_OOO) << us);
506     Color them = opposite_color(us);
507
508     // After castling, the rook and king's final positions are exactly the same
509     // in Chess960 as they would be in standard chess.
510     Square kfrom = pos.king_square(us);
511     Square rfrom = pos.castle_rook_square(f);
512     Square kto = relative_square(us, Side == KING_SIDE ? SQ_G1 : SQ_C1);
513     Square rto = relative_square(us, Side == KING_SIDE ? SQ_F1 : SQ_D1);
514
515     assert(!pos.in_check());
516     assert(pos.piece_on(kfrom) == make_piece(us, KING));
517     assert(pos.piece_on(rfrom) == make_piece(us, ROOK));
518
519     // Unimpeded rule: All the squares between the king's initial and final squares
520     // (including the final square), and all the squares between the rook's initial
521     // and final squares (including the final square), must be vacant except for
522     // the king and castling rook.
523     for (Square s = Min(kfrom, kto); s <= Max(kfrom, kto); s++)
524         if (  (s != kfrom && s != rfrom && !pos.square_is_empty(s))
525             ||(pos.attackers_to(s) & pos.pieces(them)))
526             return mlist;
527
528     for (Square s = Min(rfrom, rto); s <= Max(rfrom, rto); s++)
529         if (s != kfrom && s != rfrom && !pos.square_is_empty(s))
530             return mlist;
531
532     // Because we generate only legal castling moves we need to verify that
533     // when moving the castling rook we do not discover some hidden checker.
534     // For instance an enemy queen in SQ_A1 when castling rook is in SQ_B1.
535     if (pos.is_chess960())
536     {
537         Bitboard occ = pos.occupied_squares();
538         clear_bit(&occ, rfrom);
539         if (pos.attackers_to(kto, occ) & pos.pieces(them))
540             return mlist;
541     }
542
543     (*mlist++).move = make_castle_move(kfrom, rfrom);
544
545     return mlist;
546   }
547
548 } // namespace