]> git.sesse.net Git - stockfish/blob - src/movegen.cpp
Cleanup pinned and friends in movegen.cpp
[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) Copyright (C) 2008 Marco Costalba
4
5   Stockfish is free software: you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation, either version 3 of the License, or
8   (at your option) any later version.
9
10   Stockfish is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19
20 ////
21 //// Includes
22 ////
23
24 #include <cassert>
25
26 #include "movegen.h"
27
28 // Simple macro to wrap a very common while loop, no facny, no flexibility,
29 // hardcoded list name 'mlist' and from square 'from'.
30 #define SERIALIZE_MOVES(b) while (b) (*mlist++).move = make_move(from, pop_1st_bit(&b))
31
32 ////
33 //// Local definitions
34 ////
35
36 namespace {
37
38   enum CastlingSide {
39     KING_SIDE,
40     QUEEN_SIDE
41   };
42
43   enum MoveType {
44     CAPTURE,
45     NON_CAPTURE
46   };
47
48   // Functions
49   bool castling_is_check(const Position&, CastlingSide);
50
51   // Helper templates
52   template<CastlingSide Side>
53   MoveStack* generate_castle_moves(const Position& pos, MoveStack* mlist);
54
55   template<Color Us, Rank, Bitboard, SquareDelta>
56   MoveStack* generate_pawn_blocking_evasions(const Position&, Bitboard, Bitboard, MoveStack*);
57
58   template<Color, Color, Bitboard, SquareDelta, SquareDelta, SquareDelta>
59   MoveStack* generate_pawn_captures(const Position& pos, MoveStack* mlist);
60
61   template<Color, Color, Bitboard, Bitboard, SquareDelta, SquareDelta, SquareDelta>
62   MoveStack* generate_pawn_noncaptures(const Position& pos, MoveStack* mlist);
63
64   template<Color, Color, Bitboard, Bitboard, SquareDelta>
65   MoveStack* generate_pawn_checks(const Position&, Bitboard, Square, MoveStack*);
66
67   // Template generate_piece_checks() with specializations
68   template<PieceType>
69   MoveStack* generate_piece_checks(const Position&, MoveStack*, Color, Bitboard, Square);
70
71   template<>
72   inline MoveStack* generate_piece_checks<PAWN>(const Position& p, MoveStack* m, Color us, Bitboard dc, Square ksq) {
73
74     if (us == WHITE)
75         return generate_pawn_checks<WHITE, BLACK, Rank8BB, Rank3BB, DELTA_N>(p, dc, ksq, m);
76     else
77         return generate_pawn_checks<BLACK, WHITE, Rank1BB, Rank6BB, DELTA_S>(p, dc, ksq, m);
78
79   }
80
81   // Template generate_piece_moves() with specializations and overloads
82   template<PieceType>
83   MoveStack* generate_piece_moves(const Position&, MoveStack*, Color us, Bitboard);
84
85   template<>
86   MoveStack* generate_piece_moves<KING>(const Position&, MoveStack*, Color, Bitboard);
87
88   template<PieceType Piece, MoveType Type>
89   inline MoveStack* generate_piece_moves(const Position& p, MoveStack* m, Color us) {
90
91       assert(Piece == PAWN);
92
93       if (Type == CAPTURE)
94           return (us == WHITE ? generate_pawn_captures<WHITE, BLACK, Rank8BB, DELTA_NE, DELTA_NW, DELTA_N>(p, m)
95                               : generate_pawn_captures<BLACK, WHITE, Rank1BB, DELTA_SE, DELTA_SW, DELTA_S>(p, m));
96       else
97           return (us == WHITE ? generate_pawn_noncaptures<WHITE, BLACK, Rank8BB, Rank3BB, DELTA_NE, DELTA_NW, DELTA_N>(p, m)
98                               : generate_pawn_noncaptures<BLACK, WHITE, Rank1BB, Rank6BB, DELTA_SE, DELTA_SW, DELTA_S>(p, m));
99   }
100
101   template<PieceType>
102   MoveStack* generate_piece_moves(const Position&, MoveStack*, Color us, Bitboard, Bitboard);
103
104   template<>
105   inline MoveStack* generate_piece_moves<PAWN>(const Position& p, MoveStack* m,
106                                                Color us, Bitboard t, Bitboard pnd) {
107     if (us == WHITE)
108         return generate_pawn_blocking_evasions<WHITE, RANK_8, Rank3BB, DELTA_N>(p, pnd, t, m);
109     else
110         return generate_pawn_blocking_evasions<BLACK, RANK_1, Rank6BB, DELTA_S>(p, pnd, t, m);
111   }
112 }
113
114
115 ////
116 //// Functions
117 ////
118
119
120 /// generate_captures generates() all pseudo-legal captures and queen
121 /// promotions.  The return value is the number of moves generated.
122
123 int generate_captures(const Position& pos, MoveStack* mlist) {
124
125   assert(pos.is_ok());
126   assert(!pos.is_check());
127
128   Color us = pos.side_to_move();
129   Bitboard target = pos.pieces_of_color(opposite_color(us));
130   MoveStack* mlist_start = mlist;
131
132   mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
133   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
134   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
135   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
136   mlist = generate_piece_moves<PAWN, CAPTURE>(pos, mlist, us);
137   mlist = generate_piece_moves<KING>(pos, mlist, us, target);
138   return int(mlist - mlist_start);
139 }
140
141
142 /// generate_noncaptures() generates all pseudo-legal non-captures and
143 /// underpromotions. The return value is the number of moves generated.
144
145 int generate_noncaptures(const Position& pos, MoveStack* mlist) {
146
147   assert(pos.is_ok());
148   assert(!pos.is_check());
149
150   Color us = pos.side_to_move();
151   Bitboard target = pos.empty_squares();
152   MoveStack* mlist_start = mlist;
153
154   mlist = generate_piece_moves<PAWN, NON_CAPTURE>(pos, mlist, us);
155   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
156   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
157   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
158   mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
159   mlist = generate_piece_moves<KING>(pos, mlist, us, target);
160   mlist = generate_castle_moves<KING_SIDE>(pos, mlist);
161   mlist = generate_castle_moves<QUEEN_SIDE>(pos, mlist);
162   return int(mlist - mlist_start);
163 }
164
165
166 /// generate_checks() generates all pseudo-legal non-capturing, non-promoting
167 /// checks. It returns the number of generated moves.
168
169 int generate_checks(const Position& pos, MoveStack* mlist) {
170
171   assert(pos.is_ok());
172   assert(!pos.is_check());
173
174   Color us = pos.side_to_move();
175   Square ksq = pos.king_square(opposite_color(us));
176   Bitboard dc = pos.discovered_check_candidates(us);
177   MoveStack* mlist_start = mlist;
178
179   assert(pos.piece_on(ksq) == piece_of_color_and_type(opposite_color(us), KING));
180
181   // Pieces moves
182   mlist = generate_piece_checks<PAWN>(pos, mlist, us, dc, ksq);
183   mlist = generate_piece_checks<KNIGHT>(pos, mlist, us, dc, ksq);
184   mlist = generate_piece_checks<BISHOP>(pos, mlist, us, dc, ksq);
185   mlist = generate_piece_checks<ROOK>(pos, mlist, us, dc, ksq);
186   mlist = generate_piece_checks<QUEEN>(pos, mlist, us, dc, ksq);
187   mlist = generate_piece_checks<KING>(pos, mlist, us, dc, ksq);
188
189   // Castling moves that give check. Very rare but nice to have!
190   if (   pos.can_castle_queenside(us)
191       && (square_rank(ksq) == square_rank(pos.king_square(us)) || square_file(ksq) == FILE_D)
192       && castling_is_check(pos, QUEEN_SIDE))
193       mlist = generate_castle_moves<QUEEN_SIDE>(pos, mlist);
194
195   if (   pos.can_castle_kingside(us)
196       && (square_rank(ksq) == square_rank(pos.king_square(us)) || square_file(ksq) == FILE_F)
197       && castling_is_check(pos, KING_SIDE))
198       mlist = generate_castle_moves<KING_SIDE>(pos, mlist);
199
200   return int(mlist - mlist_start);
201 }
202
203
204 /// generate_evasions() generates all check evasions when the side to move is
205 /// in check. Unlike the other move generation functions, this one generates
206 /// only legal moves. It returns the number of generated moves.
207
208 int generate_evasions(const Position& pos, MoveStack* mlist) {
209
210   assert(pos.is_ok());
211   assert(pos.is_check());
212
213   Square from, to;
214   Color us = pos.side_to_move();
215   Color them = opposite_color(us);
216   Square ksq = pos.king_square(us);
217   MoveStack* mlist_start = mlist;
218
219   assert(pos.piece_on(ksq) == piece_of_color_and_type(us, KING));
220
221   // The bitboard of occupied pieces without our king
222   Bitboard b_noKing = pos.occupied_squares();
223   clear_bit(&b_noKing, ksq);
224
225   // Find squares attacked by slider checkers, we will
226   // remove them from king evasions set so to avoid a couple
227   // of cycles in the slow king evasions legality check loop
228   // and to be able to use square_is_attacked().
229   Bitboard checkers = pos.checkers();
230   Bitboard checkersAttacks = EmptyBoardBB;
231   Bitboard b = checkers & (pos.queens() | pos.bishops());
232   while (b)
233   {
234       from = pop_1st_bit(&b);
235       checkersAttacks |= bishop_attacks_bb(from, b_noKing);
236   }
237
238   b = checkers & (pos.queens() | pos.rooks());
239   while (b)
240   {
241       from = pop_1st_bit(&b);
242       checkersAttacks |= rook_attacks_bb(from, b_noKing);
243   }
244
245   // Generate evasions for king
246   Bitboard b1 = pos.piece_attacks<KING>(ksq) & ~pos.pieces_of_color(us) & ~checkersAttacks;
247   while (b1)
248   {
249       to = pop_1st_bit(&b1);
250       // Note that we can use square_is_attacked() only because we
251       // have already removed slider checkers.
252       if (!pos.square_is_attacked(to, them))
253           (*mlist++).move = make_move(ksq, to);
254   }
255
256   // Generate evasions for other pieces only if not double check. We use a
257   // simple bit twiddling hack here rather than calling count_1s in order to
258   // save some time (we know that pos.checkers() has at most two nonzero bits).
259   if (!(checkers & (checkers - 1))) // Only one bit set?
260   {
261       Square checksq = first_1(checkers);
262       Bitboard pinned = pos.pinned_pieces(us);
263
264       assert(pos.color_of_piece_on(checksq) == them);
265
266       // Generate captures of the checking piece
267
268       // Pawn captures
269       b1 = pos.pawn_attacks(them, checksq) & pos.pawns(us) & ~pinned;
270       while (b1)
271       {
272           from = pop_1st_bit(&b1);
273           if (relative_rank(us, checksq) == RANK_8)
274           {
275               (*mlist++).move = make_promotion_move(from, checksq, QUEEN);
276               (*mlist++).move = make_promotion_move(from, checksq, ROOK);
277               (*mlist++).move = make_promotion_move(from, checksq, BISHOP);
278               (*mlist++).move = make_promotion_move(from, checksq, KNIGHT);
279           } else
280               (*mlist++).move = make_move(from, checksq);
281       }
282
283       // Pieces captures
284       b1 = (  (pos.piece_attacks<KNIGHT>(checksq) & pos.knights(us))
285             | (pos.piece_attacks<BISHOP>(checksq) & pos.bishops_and_queens(us))
286             | (pos.piece_attacks<ROOK>(checksq)   & pos.rooks_and_queens(us)) ) & ~pinned;
287
288       while (b1)
289       {
290           from = pop_1st_bit(&b1);
291           (*mlist++).move = make_move(from, checksq);
292       }
293
294       // Blocking check evasions are possible only if the checking piece is
295       // a slider.
296       if (checkers & pos.sliders())
297       {
298           Bitboard blockSquares = squares_between(checksq, ksq);
299
300           assert((pos.occupied_squares() & blockSquares) == EmptyBoardBB);
301
302           if (blockSquares != EmptyBoardBB)
303           {
304               mlist = generate_piece_moves<PAWN>(pos, mlist, us, blockSquares, pinned);
305               mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, blockSquares, pinned);
306               mlist = generate_piece_moves<BISHOP>(pos, mlist, us, blockSquares, pinned);
307               mlist = generate_piece_moves<ROOK>(pos, mlist, us, blockSquares, pinned);
308               mlist = generate_piece_moves<QUEEN>(pos, mlist, us, blockSquares, pinned);
309           }
310       }
311
312       // Finally, the special case of en passant captures. An en passant
313       // capture can only be a check evasion if the check is not a discovered
314       // check. If pos.ep_square() is set, the last move made must have been
315       // a double pawn push. If, furthermore, the checking piece is a pawn,
316       // an en passant check evasion may be possible.
317       if (pos.ep_square() != SQ_NONE && (checkers & pos.pawns(them)))
318       {
319           to = pos.ep_square();
320           b1 = pos.pawn_attacks(them, to) & pos.pawns(us);
321
322           // The checking pawn cannot be a discovered (bishop) check candidate
323           // otherwise we were in check also before last double push move.
324           assert(!bit_is_set(pos.discovered_check_candidates(them), checksq));
325           assert(count_1s(b1) == 1 || count_1s(b1) == 2);
326
327           b1 &= ~pinned;
328           while (b1)
329           {
330               from = pop_1st_bit(&b1);
331               // Move is always legal because checking pawn is not a discovered
332               // check candidate and our capturing pawn has been already tested
333               // against pinned pieces.
334               (*mlist++).move = make_ep_move(from, to);
335           }
336       }
337   }
338   return int(mlist - mlist_start);
339 }
340
341
342 /// generate_legal_moves() computes a complete list of legal moves in the
343 /// current position. This function is not very fast, and should be used
344 /// only in situations where performance is unimportant. It wouldn't be
345 /// very hard to write an efficient legal move generator, but for the moment
346 /// we don't need it.
347
348 int generate_legal_moves(const Position& pos, MoveStack* mlist) {
349
350   assert(pos.is_ok());
351
352   Bitboard pinned = pos.pinned_pieces(pos.side_to_move());
353
354   if (pos.is_check())
355       return generate_evasions(pos, mlist);
356
357   // Generate pseudo-legal moves
358   int n = generate_captures(pos, mlist);
359   n += generate_noncaptures(pos, mlist + n);
360
361   // Remove illegal moves from the list
362   for (int i = 0; i < n; i++)
363       if (!pos.pl_move_is_legal(mlist[i].move, pinned))
364           mlist[i--].move = mlist[--n].move;
365
366   return n;
367 }
368
369
370 /// move_is_legal() takes a position and a (not necessarily pseudo-legal)
371 /// move and a pinned pieces bitboard as input, and tests whether
372 /// the move is legal.  If the move is legal, the move itself is
373 /// returned. If not, the function returns false.  This function must
374 /// only be used when the side to move is not in check.
375
376 bool move_is_legal(const Position& pos, const Move m) {
377
378   assert(pos.is_ok());
379   assert(!pos.is_check());
380   assert(move_is_ok(m));
381
382   Color us = pos.side_to_move();
383   Color them = opposite_color(us);
384   Square from = move_from(m);
385   Piece pc = pos.piece_on(from);
386   Bitboard pinned = pos.pinned_pieces(us);
387
388   // If the from square is not occupied by a piece belonging to the side to
389   // move, the move is obviously not legal.
390   if (color_of_piece(pc) != us)
391       return false;
392
393   Square to = move_to(m);
394
395   // En passant moves
396   if (move_is_ep(m))
397   {
398       // The piece must be a pawn and destination square must be the
399       // en passant square.
400       if (   type_of_piece(pc) != PAWN
401           || to != pos.ep_square())
402           return false;
403
404       assert(pos.square_is_empty(to));
405       assert(pos.piece_on(to - pawn_push(us)) == piece_of_color_and_type(them, PAWN));
406
407       // The move is pseudo-legal, check if it is also legal
408       return pos.pl_move_is_legal(m, pinned);
409   }
410
411   // Castling moves
412   if (move_is_short_castle(m))
413   {
414       // The piece must be a king and side to move must still have
415       // the right to castle kingside.
416       if (   type_of_piece(pc) != KING
417           ||!pos.can_castle_kingside(us))
418           return false;
419
420       assert(from == pos.king_square(us));
421       assert(to == pos.initial_kr_square(us));
422       assert(pos.piece_on(to) == piece_of_color_and_type(us, ROOK));
423
424       Square g1 = relative_square(us, SQ_G1);
425       Square f1 = relative_square(us, SQ_F1);
426       Square s;
427       bool illegal = false;
428
429       // Check if any of the squares between king and rook
430       // is occupied or under attack.
431       for (s = Min(from, g1); s <= Max(from, g1); s++)
432           if (  (s != from && s != to && !pos.square_is_empty(s))
433               || pos.square_is_attacked(s, them))
434               illegal = true;
435
436       // Check if any of the squares between king and rook
437       // is occupied.
438       for (s = Min(to, f1); s <= Max(to, f1); s++)
439           if (s != from && s != to && !pos.square_is_empty(s))
440               illegal = true;
441
442       return !illegal;
443   }
444
445   if (move_is_long_castle(m))
446   {
447       // The piece must be a king and side to move must still have
448       // the right to castle kingside.
449       if (   type_of_piece(pc) != KING
450           ||!pos.can_castle_queenside(us))
451           return false;
452
453       assert(from == pos.king_square(us));
454       assert(to == pos.initial_qr_square(us));
455       assert(pos.piece_on(to) == piece_of_color_and_type(us, ROOK));
456
457       Square c1 = relative_square(us, SQ_C1);
458       Square d1 = relative_square(us, SQ_D1);
459       Square s;
460       bool illegal = false;
461
462       for (s = Min(from, c1); s <= Max(from, c1); s++)
463           if(  (s != from && s != to && !pos.square_is_empty(s))
464              || pos.square_is_attacked(s, them))
465               illegal = true;
466
467       for (s = Min(to, d1); s <= Max(to, d1); s++)
468           if(s != from && s != to && !pos.square_is_empty(s))
469               illegal = true;
470
471       if (   square_file(to) == FILE_B
472           && (   pos.piece_on(to + DELTA_W) == piece_of_color_and_type(them, ROOK)
473               || pos.piece_on(to + DELTA_W) == piece_of_color_and_type(them, QUEEN)))
474           illegal = true;
475
476       return !illegal;
477   }
478
479   // Normal moves
480
481   // The destination square cannot be occupied by a friendly piece
482   if (pos.color_of_piece_on(to) == us)
483       return false;
484
485   // Proceed according to the type of the moving piece.
486   if (type_of_piece(pc) == PAWN)
487   {
488       // If the destination square is on the 8/1th rank, the move must
489       // be a promotion.
490       if (   (  (square_rank(to) == RANK_8 && us == WHITE)
491               ||(square_rank(to) == RANK_1 && us != WHITE))
492            && !move_promotion(m))
493           return false;
494
495       // Proceed according to the square delta between the source and
496       // destionation squares.
497       switch (to - from)
498       {
499       case DELTA_NW:
500       case DELTA_NE:
501       case DELTA_SW:
502       case DELTA_SE:
503       // Capture. The destination square must be occupied by an enemy
504       // piece (en passant captures was handled earlier).
505           if (pos.color_of_piece_on(to) != them)
506               return false;
507           break;
508
509       case DELTA_N:
510       case DELTA_S:
511       // Pawn push. The destination square must be empty.
512           if (!pos.square_is_empty(to))
513               return false;
514           break;
515
516       case DELTA_NN:
517       // Double white pawn push. The destination square must be on the fourth
518       // rank, and both the destination square and the square between the
519       // source and destination squares must be empty.
520       if (   square_rank(to) != RANK_4
521           || !pos.square_is_empty(to)
522           || !pos.square_is_empty(from + DELTA_N))
523           return false;
524           break;
525
526       case DELTA_SS:
527       // Double black pawn push. The destination square must be on the fifth
528       // rank, and both the destination square and the square between the
529       // source and destination squares must be empty.
530           if (   square_rank(to) != RANK_5
531               || !pos.square_is_empty(to)
532               || !pos.square_is_empty(from + DELTA_S))
533               return false;
534           break;
535
536       default:
537           return false;
538       }
539       // The move is pseudo-legal, check if it is also legal
540       return pos.pl_move_is_legal(m, pinned);
541   }
542
543   // Luckly we can handle all the other pieces in one go
544   return (   pos.piece_attacks_square(pos.piece_on(from), from, to)
545           && pos.pl_move_is_legal(m, pinned)
546           && !move_promotion(m));
547 }
548
549
550 namespace {
551
552   template<PieceType Piece>
553   MoveStack* generate_piece_moves(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
554
555     Square from;
556     Bitboard b;
557
558     for (int i = 0, e = pos.piece_count(us, Piece); i < e; i++)
559     {
560         from = pos.piece_list(us, Piece, i);
561         b = pos.piece_attacks<Piece>(from) & target;
562         SERIALIZE_MOVES(b);
563     }
564     return mlist;
565   }
566
567   template<PieceType Piece>
568   MoveStack* generate_piece_moves(const Position& pos, MoveStack* mlist,
569                                   Color us, Bitboard target, Bitboard pinned) {
570     Square from;
571     Bitboard b;
572
573     for (int i = 0, e = pos.piece_count(us, Piece); i < e; i++)
574     {
575         from = pos.piece_list(us, Piece, i);
576         if (pinned && bit_is_set(pinned, from))
577             continue;
578
579         b = pos.piece_attacks<Piece>(from) & target;
580         SERIALIZE_MOVES(b);
581     }
582     return mlist;
583   }
584
585   template<>
586   MoveStack* generate_piece_moves<KING>(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
587
588     Bitboard b;
589     Square from = pos.king_square(us);
590
591     b = pos.piece_attacks<KING>(from) & target;
592     SERIALIZE_MOVES(b);
593     return mlist;
594   }
595
596   template<Color Us, Color Them, Bitboard TRank8BB, SquareDelta TDELTA_NE,
597            SquareDelta TDELTA_NW, SquareDelta TDELTA_N
598           >
599   MoveStack* generate_pawn_captures(const Position& pos, MoveStack* mlist) {
600
601     Square to;
602     Bitboard pawns = pos.pawns(Us);
603     Bitboard enemyPieces = pos.pieces_of_color(Them);
604
605     // Captures in the a1-h8 (a8-h1 for black) direction
606     Bitboard b1 = (Us == WHITE ? pawns << 9 : pawns >> 7) & ~FileABB & enemyPieces;
607
608     // Capturing promotions
609     Bitboard b2 = b1 & TRank8BB;
610     while (b2)
611     {
612         to = pop_1st_bit(&b2);
613         (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, QUEEN);
614     }
615
616     // Capturing non-promotions
617     b2 = b1 & ~TRank8BB;
618     while (b2)
619     {
620         to = pop_1st_bit(&b2);
621         (*mlist++).move = make_move(to - TDELTA_NE, to);
622     }
623
624     // Captures in the h1-a8 (h8-a1 for black) direction
625     b1 = (Us == WHITE ? pawns << 7 : pawns >> 9) & ~FileHBB & enemyPieces;
626
627     // Capturing promotions
628     b2 = b1 & TRank8BB;
629     while (b2)
630     {
631         to = pop_1st_bit(&b2);
632         (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, QUEEN);
633     }
634
635     // Capturing non-promotions
636     b2 = b1 & ~TRank8BB;
637     while (b2)
638     {
639         to = pop_1st_bit(&b2);
640         (*mlist++).move = make_move(to - TDELTA_NW, to);
641     }
642
643     // Non-capturing promotions
644     b1 = (Us == WHITE ? pawns << 8 : pawns >> 8) & pos.empty_squares() & TRank8BB;
645     while (b1)
646     {
647         to = pop_1st_bit(&b1);
648         (*mlist++).move = make_promotion_move(to - TDELTA_N, to, QUEEN);
649     }
650
651     // En passant captures
652     if (pos.ep_square() != SQ_NONE)
653     {
654         assert(Us != WHITE || square_rank(pos.ep_square()) == RANK_6);
655         assert(Us != BLACK || square_rank(pos.ep_square()) == RANK_3);
656
657         b1 = pawns & pos.pawn_attacks(Them, pos.ep_square());
658         assert(b1 != EmptyBoardBB);
659
660         while (b1)
661         {
662             to = pop_1st_bit(&b1);
663             (*mlist++).move = make_ep_move(to, pos.ep_square());
664         }
665     }
666     return mlist;
667   }
668
669   template<Color Us, Color Them, Bitboard TRank8BB, Bitboard TRank3BB,
670            SquareDelta TDELTA_NE, SquareDelta TDELTA_NW, SquareDelta TDELTA_N
671           >
672   MoveStack* generate_pawn_noncaptures(const Position& pos, MoveStack* mlist) {
673
674     Bitboard pawns = pos.pawns(Us);
675     Bitboard enemyPieces = pos.pieces_of_color(Them);
676     Bitboard emptySquares = pos.empty_squares();
677     Bitboard b1, b2;
678     Square to;
679
680     // Underpromotion captures in the a1-h8 (a8-h1 for black) direction
681     b1 = (Us == WHITE ? pawns << 9 : pawns >> 7) & ~FileABB & enemyPieces & TRank8BB;
682     while (b1)
683     {
684         to = pop_1st_bit(&b1);
685         (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, ROOK);
686         (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, BISHOP);
687         (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, KNIGHT);
688     }
689
690     // Underpromotion captures in the h1-a8 (h8-a1 for black) direction
691     b1 = (Us == WHITE ? pawns << 7 : pawns >> 9) & ~FileHBB & enemyPieces & TRank8BB;
692     while (b1)
693     {
694         to = pop_1st_bit(&b1);
695         (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, ROOK);
696         (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, BISHOP);
697         (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, KNIGHT);
698     }
699
700     // Single pawn pushes
701     b1 = (Us == WHITE ? pawns << 8 : pawns >> 8) & emptySquares;
702     b2 = b1 & TRank8BB;
703     while (b2)
704     {
705         to = pop_1st_bit(&b2);
706         (*mlist++).move = make_promotion_move(to - TDELTA_N, to, ROOK);
707         (*mlist++).move = make_promotion_move(to - TDELTA_N, to, BISHOP);
708         (*mlist++).move = make_promotion_move(to - TDELTA_N, to, KNIGHT);
709     }
710     b2 = b1 & ~TRank8BB;
711     while (b2)
712     {
713         to = pop_1st_bit(&b2);
714         (*mlist++).move = make_move(to - TDELTA_N, to);
715     }
716
717     // Double pawn pushes
718     b2 = (Us == WHITE ? (b1 & TRank3BB) << 8 : (b1 & TRank3BB) >> 8) & emptySquares;
719     while (b2)
720     {
721         to = pop_1st_bit(&b2);
722         (*mlist++).move = make_move(to - TDELTA_N - TDELTA_N, to);
723     }
724     return mlist;
725   }
726
727
728   template<Color Us, Color Them, Bitboard TRank8BB, Bitboard TRank3BB, SquareDelta TDELTA_N>
729   MoveStack* generate_pawn_checks(const Position& pos, Bitboard dc, Square ksq, MoveStack* mlist)
730   {
731     // Find all friendly pawns not on the enemy king's file
732     Bitboard b1, b2, b3;
733     Bitboard empty = pos.empty_squares();
734
735     if (dc != EmptyBoardBB)
736     {
737         // Pawn moves which gives discovered check. This is possible only if the
738         // pawn is not on the same file as the enemy king, because we don't
739         // generate captures.
740         b1 = pos.pawns(Us) & ~file_bb(ksq);
741
742         // Discovered checks, single pawn pushes, no promotions
743         b2 = b3 = (Us == WHITE ? (b1 & dc) << 8 : (b1 & dc) >> 8) & empty & ~TRank8BB;
744         while (b3)
745         {
746             Square to = pop_1st_bit(&b3);
747             (*mlist++).move = make_move(to - TDELTA_N, to);
748         }
749
750         // Discovered checks, double pawn pushes
751         b3 = (Us == WHITE ? (b2 & TRank3BB) << 8 : (b2 & TRank3BB) >> 8) & empty;
752         while (b3)
753         {
754             Square to = pop_1st_bit(&b3);
755             (*mlist++).move = make_move(to - TDELTA_N - TDELTA_N, to);
756         }
757     }
758
759     // Direct checks. These are possible only for pawns on neighboring files
760     // of the enemy king.
761     b1 = pos.pawns(Us) & neighboring_files_bb(ksq) & ~dc;
762
763     // Direct checks, single pawn pushes
764     b2 = (Us == WHITE ? b1 << 8 : b1 >> 8) & empty;
765     b3 = b2 & pos.pawn_attacks(Them, ksq);
766     while (b3)
767     {
768         Square to = pop_1st_bit(&b3);
769         (*mlist++).move = make_move(to - TDELTA_N, to);
770     }
771
772     // Direct checks, double pawn pushes
773     b3 =  (Us == WHITE ? (b2 & TRank3BB) << 8 : (b2 & TRank3BB) >> 8)
774         & empty
775         & pos.pawn_attacks(Them, ksq);
776     while (b3)
777     {
778         Square to = pop_1st_bit(&b3);
779         (*mlist++).move = make_move(to - TDELTA_N - TDELTA_N, to);
780     }
781     return mlist;
782   }
783
784   template<PieceType Piece>
785   MoveStack* generate_piece_checks(const Position& pos, MoveStack* mlist, Color us,
786                                    Bitboard dc, Square ksq) {
787
788     Bitboard target = pos.pieces_of_color_and_type(us, Piece);
789
790     // Discovered checks
791     Bitboard b = target & dc;
792     while (b)
793     {
794         Square from = pop_1st_bit(&b);
795         Bitboard bb = pos.piece_attacks<Piece>(from) & pos.empty_squares();
796         if (Piece == KING)
797             bb &= ~QueenPseudoAttacks[ksq];
798
799         SERIALIZE_MOVES(bb);
800     }
801
802     // Direct checks
803     b = target & ~dc;
804     if (Piece == KING || !b)
805         return mlist;
806
807     Bitboard checkSqs = pos.piece_attacks<Piece>(ksq) & pos.empty_squares();
808     while (b)
809     {
810         Square from = pop_1st_bit(&b);
811         Bitboard bb = pos.piece_attacks<Piece>(from) & checkSqs;
812         SERIALIZE_MOVES(bb);
813     }
814     return mlist;
815   }
816
817   template<Color Us, Rank TRANK_8, Bitboard TRank3BB, SquareDelta TDELTA_N>
818   MoveStack* generate_pawn_blocking_evasions(const Position& pos, Bitboard pinned,
819                                              Bitboard blockSquares, MoveStack* mlist) {
820     Square to;
821
822     // Find non-pinned pawns
823     Bitboard b1 = pos.pawns(Us) & ~pinned;
824
825     // Single pawn pushes. We don't have to AND with empty squares here,
826     // because the blocking squares will always be empty.
827     Bitboard b2 = (Us == WHITE ? b1 << 8 : b1 >> 8) & blockSquares;
828     while (b2)
829     {
830         to = pop_1st_bit(&b2);
831
832         assert(pos.piece_on(to) == EMPTY);
833
834         if (square_rank(to) == TRANK_8)
835         {
836             (*mlist++).move = make_promotion_move(to - TDELTA_N, to, QUEEN);
837             (*mlist++).move = make_promotion_move(to - TDELTA_N, to, ROOK);
838             (*mlist++).move = make_promotion_move(to - TDELTA_N, to, BISHOP);
839             (*mlist++).move = make_promotion_move(to - TDELTA_N, to, KNIGHT);
840         } else
841             (*mlist++).move = make_move(to - TDELTA_N, to);
842     }
843
844     // Double pawn pushes
845     b2 = (Us == WHITE ? b1 << 8 : b1 >> 8) & pos.empty_squares() & TRank3BB;
846     b2 = (Us == WHITE ? b2 << 8 : b2 >> 8) & blockSquares;
847     while (b2)
848     {
849         to = pop_1st_bit(&b2);
850
851         assert(pos.piece_on(to) == EMPTY);
852         assert(Us != WHITE || square_rank(to) == RANK_4);
853         assert(Us != BLACK || square_rank(to) == RANK_5);
854
855         (*mlist++).move = make_move(to - TDELTA_N - TDELTA_N, to);
856     }
857     return mlist;
858   }
859
860   template<CastlingSide Side>
861   MoveStack* generate_castle_moves(const Position& pos, MoveStack* mlist) {
862
863     Color us = pos.side_to_move();
864
865     if (  (Side == KING_SIDE && pos.can_castle_kingside(us))
866         ||(Side == QUEEN_SIDE && pos.can_castle_queenside(us)))
867     {
868         Color them = opposite_color(us);
869         Square ksq = pos.king_square(us);
870
871         assert(pos.piece_on(ksq) == piece_of_color_and_type(us, KING));
872
873         Square rsq = (Side == KING_SIDE ? pos.initial_kr_square(us) : pos.initial_qr_square(us));
874         Square s1 = relative_square(us, Side == KING_SIDE ? SQ_G1 : SQ_C1);
875         Square s2 = relative_square(us, Side == KING_SIDE ? SQ_F1 : SQ_D1);
876         Square s;
877         bool illegal = false;
878
879         assert(pos.piece_on(rsq) == piece_of_color_and_type(us, ROOK));
880
881         // It is a bit complicated to correctly handle Chess960
882         for (s = Min(ksq, s1); s <= Max(ksq, s1); s++)
883             if (  (s != ksq && s != rsq && pos.square_is_occupied(s))
884                 || pos.square_is_attacked(s, them))
885                 illegal = true;
886
887         for (s = Min(rsq, s2); s <= Max(rsq, s2); s++)
888             if (s != ksq && s != rsq && pos.square_is_occupied(s))
889                 illegal = true;
890
891         if (   Side == QUEEN_SIDE
892             && square_file(rsq) == FILE_B
893             && (   pos.piece_on(relative_square(us, SQ_A1)) == piece_of_color_and_type(them, ROOK)
894                 || pos.piece_on(relative_square(us, SQ_A1)) == piece_of_color_and_type(them, QUEEN)))
895             illegal = true;
896
897         if (!illegal)
898             (*mlist++).move = make_castle_move(ksq, rsq);
899     }
900     return mlist;
901   }
902
903   bool castling_is_check(const Position& pos, CastlingSide side) {
904
905     // After castling opponent king is attacked by the castled rook?
906     File rookFile = (side == QUEEN_SIDE ? FILE_D : FILE_F);
907     Color us = pos.side_to_move();
908     Square ksq = pos.king_square(us);
909     Bitboard occ = pos.occupied_squares();
910
911     clear_bit(&occ, ksq); // Remove our king from the board
912     Square rsq = make_square(rookFile, square_rank(ksq));
913     return bit_is_set(rook_attacks_bb(rsq, occ), pos.king_square(opposite_color(us)));
914   }
915 }