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