]> git.sesse.net Git - stockfish/blob - src/tt.cpp
Introduce "Zugzwang detection" temporary hack for 1.7.1
[stockfish] / src / tt.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
21 ////
22 //// Includes
23 ////
24
25 #include <cassert>
26 #include <cmath>
27 #include <cstring>
28 #if !(defined(__hpux) || defined(__ppc__) || defined(__ppc64__) || defined(__arm__))
29 #  include <xmmintrin.h>
30 #endif
31
32 #include "movegen.h"
33 #include "tt.h"
34
35 // The main transposition table
36 TranspositionTable TT;
37
38 ////
39 //// Functions
40 ////
41
42 TranspositionTable::TranspositionTable() {
43
44   size = writes = 0;
45   entries = 0;
46   generation = 0;
47 }
48
49 TranspositionTable::~TranspositionTable() {
50
51   delete [] entries;
52 }
53
54
55 /// TranspositionTable::set_size sets the size of the transposition table,
56 /// measured in megabytes.
57
58 void TranspositionTable::set_size(size_t mbSize) {
59
60   size_t newSize = 1024;
61
62   // We store a cluster of ClusterSize number of TTEntry for each position
63   // and newSize is the maximum number of storable positions.
64   while ((2 * newSize) * sizeof(TTCluster) <= (mbSize << 20))
65       newSize *= 2;
66
67   if (newSize != size)
68   {
69       size = newSize;
70       delete [] entries;
71       entries = new TTCluster[size];
72       if (!entries)
73       {
74           std::cerr << "Failed to allocate " << mbSize
75                     << " MB for transposition table." << std::endl;
76           Application::exit_with_failure();
77       }
78       clear();
79   }
80 }
81
82
83 /// TranspositionTable::clear overwrites the entire transposition table
84 /// with zeroes. It is called whenever the table is resized, or when the
85 /// user asks the program to clear the table (from the UCI interface).
86 /// Perhaps we should also clear it when the "ucinewgame" command is recieved?
87
88 void TranspositionTable::clear() {
89
90   memset(entries, 0, size * sizeof(TTCluster));
91 }
92
93
94 /// TranspositionTable::first_entry returns a pointer to the first
95 /// entry of a cluster given a position. The low 32 bits of the key
96 /// are used to get the index in the table.
97
98 inline TTEntry* TranspositionTable::first_entry(const Key posKey) const {
99
100   return entries[uint32_t(posKey) & (size - 1)].data;
101 }
102
103
104 /// TranspositionTable::store writes a new entry containing a position,
105 /// a value, a value type, a search depth, and a best move to the
106 /// transposition table. Transposition table is organized in clusters of
107 /// four TTEntry objects, and when a new entry is written, it replaces
108 /// the least valuable of the four entries in a cluster. A TTEntry t1 is
109 /// considered to be more valuable than a TTEntry t2 if t1 is from the
110 /// current search and t2 is from a previous search, or if the depth of t1
111 /// is bigger than the depth of t2. A TTEntry of type VALUE_TYPE_EVAL
112 /// never replaces another entry for the same position.
113
114 void TranspositionTable::store(const Key posKey, Value v, ValueType t, Depth d, Move m) {
115
116   TTEntry *tte, *replace;
117   uint32_t posKey32 = posKey >> 32; // Use the high 32 bits as key
118
119   tte = replace = first_entry(posKey);
120   for (int i = 0; i < ClusterSize; i++, tte++)
121   {
122       if (!tte->key() || tte->key() == posKey32) // empty or overwrite old
123       {
124           // Do not overwrite when new type is VALUE_TYPE_EV_LO
125           if (tte->key() && t == VALUE_TYPE_EV_LO)
126               return;
127
128           // Preserve any exsisting ttMove
129           if (m == MOVE_NONE)
130               m = tte->move();
131
132           *tte = TTEntry(posKey32, v, t, d, m, generation);
133           return;
134       }
135       else if (i == 0)  // replace would be a no-op in this common case
136           continue;
137
138       int c1 = (replace->generation() == generation ?  2 : 0);
139       int c2 = (tte->generation() == generation ? -2 : 0);
140       int c3 = (tte->depth() < replace->depth() ?  1 : 0);
141
142       if (c1 + c2 + c3 > 0)
143           replace = tte;
144   }
145   *replace = TTEntry(posKey32, v, t, d, m, generation);
146   writes++;
147 }
148
149
150 /// TranspositionTable::retrieve looks up the current position in the
151 /// transposition table. Returns a pointer to the TTEntry or NULL
152 /// if position is not found.
153
154 TTEntry* TranspositionTable::retrieve(const Key posKey) const {
155
156   uint32_t posKey32 = posKey >> 32;
157   TTEntry* tte = first_entry(posKey);
158
159   for (int i = 0; i < ClusterSize; i++, tte++)
160       if (tte->key() == posKey32)
161           return tte;
162
163   return NULL;
164 }
165
166
167 /// TranspositionTable::prefetch looks up the current position in the
168 /// transposition table and load it in L1/L2 cache. This is a non
169 /// blocking function and do not stalls the CPU waiting for data
170 /// to be loaded from RAM, that can be very slow. When we will
171 /// subsequently call retrieve() the TT data will be already
172 /// quickly accessible in L1/L2 CPU cache.
173 #if defined(__hpux) || defined(__ppc__) || defined(__ppc64__) || defined(__arm__)
174 void TranspositionTable::prefetch(const Key) const {} // Not supported on HP UX
175 #else
176
177 void TranspositionTable::prefetch(const Key posKey) const {
178
179 #if defined(__INTEL_COMPILER) || defined(__ICL)
180    // This hack prevents prefetches to be optimized away by
181    // Intel compiler. Both MSVC and gcc seems not affected.
182    __asm__ ("");
183 #endif
184
185    char const* addr = (char*)first_entry(posKey);
186   _mm_prefetch(addr, _MM_HINT_T2);
187   _mm_prefetch(addr+64, _MM_HINT_T2); // 64 bytes ahead
188 }
189
190 #endif
191
192 /// TranspositionTable::new_search() is called at the beginning of every new
193 /// search. It increments the "generation" variable, which is used to
194 /// distinguish transposition table entries from previous searches from
195 /// entries from the current search.
196
197 void TranspositionTable::new_search() {
198
199   generation++;
200   writes = 0;
201 }
202
203
204 /// TranspositionTable::insert_pv() is called at the end of a search
205 /// iteration, and inserts the PV back into the PV. This makes sure
206 /// the old PV moves are searched first, even if the old TT entries
207 /// have been overwritten.
208
209 void TranspositionTable::insert_pv(const Position& pos, Move pv[]) {
210
211   StateInfo st;
212   Position p(pos);
213
214   for (int i = 0; pv[i] != MOVE_NONE; i++)
215   {
216       TTEntry *tte = retrieve(p.get_key());
217       if (!tte || tte->move() != pv[i])
218           store(p.get_key(), VALUE_NONE, VALUE_TYPE_NONE, Depth(-127*OnePly), pv[i]);
219       p.do_move(pv[i], st);
220   }
221 }
222
223
224 /// TranspositionTable::extract_pv() extends a PV by adding moves from the
225 /// transposition table at the end. This should ensure that the PV is almost
226 /// always at least two plies long, which is important, because otherwise we
227 /// will often get single-move PVs when the search stops while failing high,
228 /// and a single-move PV means that we don't have a ponder move.
229
230 void TranspositionTable::extract_pv(const Position& pos, Move pv[], const int PLY_MAX) {
231
232   const TTEntry* tte;
233   StateInfo st;
234   Position p(pos);
235   int ply = 0;
236
237   // Update position to the end of current PV
238   while (pv[ply] != MOVE_NONE)
239       p.do_move(pv[ply++], st);
240
241   // Try to add moves from TT while possible
242   while (   (tte = retrieve(p.get_key())) != NULL
243          && tte->move() != MOVE_NONE
244          && move_is_legal(p, tte->move())
245          && (!p.is_draw() || ply < 2)
246          && ply < PLY_MAX)
247   {
248       pv[ply] = tte->move();
249       p.do_move(pv[ply++], st);
250   }
251   pv[ply] = MOVE_NONE;
252 }
253
254
255 /// TranspositionTable::full() returns the permill of all transposition table
256 /// entries which have received at least one write during the current search.
257 /// It is used to display the "info hashfull ..." information in UCI.
258
259 int TranspositionTable::full() const {
260
261   double N = double(size) * ClusterSize;
262   return int(1000 * (1 - exp(writes * log(1.0 - 1.0/N))));
263 }