-inline int PawnInfo::get_king_shelter(const Position& pos, Color c, Square ksq) {
- return (kingSquares[c] == ksq ? kingShelters[c] : updateShelter(pos, c, ksq));
+/// PawnInfo::updateShelter() calculates and caches king shelter. It is called
+/// only when king square changes, about 20% of total king_shelter() calls.
+template<Color Us>
+Score PawnInfo::updateShelter(const Position& pos, Square ksq) {
+
+ const int Shift = (Us == WHITE ? 8 : -8);
+
+ Bitboard pawns;
+ int r, shelter = 0;
+
+ if (relative_rank(Us, ksq) <= RANK_4)
+ {
+ pawns = pos.pieces(PAWN, Us) & this_and_neighboring_files_bb(ksq);
+ r = square_rank(ksq) * 8;
+ for (int i = 1; i < 4; i++)
+ {
+ r += Shift;
+ shelter += BitCount8Bit[(pawns >> r) & 0xFF] * (128 >> i);
+ }
+ }
+ kingSquares[Us] = ksq;
+ kingShelters[Us] = make_score(shelter, 0);
+ return kingShelters[Us];
+}
+
+template<Color Us>
+inline Score PawnInfo::king_shelter(const Position& pos, Square ksq) {
+ return kingSquares[Us] == ksq ? kingShelters[Us] : updateShelter<Us>(pos, ksq);