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