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